The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(adapters/whatsapp_webhook): 6449->4465; whatsapp_cloud/common/plugin send + media unification, webhook route/filter dispatch tables
Tekniumc4f96565d0c4
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex aa44aeb2d7c..f4537cff2bd 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -1,33 +1,20 @@-"""Generic webhook platform adapter.+"""Generic webhook platform adapter: aiohttp server that validates HMAC-signed POSTs+(GitHub, GitLab, Svix, Linear, generic), renders payloads into agent prompts, and+routes responses back (github_comment or any gateway platform).-Runs an aiohttp HTTP server that receives webhook POSTs from external-services (GitHub, GitLab, JIRA, Stripe, etc.), validates HMAC signatures,-transforms payloads into agent prompts, and routes responses back to the-source or to another configured platform.--Configuration lives in config.yaml under platforms.webhook.extra.routes.-Each route defines:+Routes live in config.yaml under platforms.webhook.extra.routes. Each route:- events: which event types to accept (header-based filtering)- - secret: HMAC secret for signature validation (REQUIRED)+ - secret: HMAC secret for signature validation (REQUIRED; "INSECURE_NO_AUTH"+ skips validation, loopback bind only)- prompt: template string formatted with the webhook payload- skills: optional list of skills to load for the agent- deliver: where to send the response (github_comment, telegram, etc.)- deliver_extra: additional delivery config (repo, pr_number, chat_id)- - deliver_only: if true, skip the agent — the rendered prompt IS the- message that gets delivered. Use for external push notifications- (Supabase, monitoring alerts, inter-agent pings) where zero LLM cost- and sub-second delivery matter more than agent reasoning.--Security:- - HMAC secret is required per route (validated at startup)- - Rate limiting per route (fixed-window, configurable)- - Idempotency cache prevents duplicate agent runs on webhook retries- - Body size limits checked before reading payload- - Generic HMAC supports a V2 signature (X-Webhook-Signature-V2) that- binds a timestamp into the signed data for replay protection; the- legacy body-only V1 (X-Webhook-Signature) is deprecated but still- accepted with a warning, since it has no replay protection- - Set secret to "INSECURE_NO_AUTH" to skip validation (testing only)+ - deliver_only: skip the agent — the rendered prompt IS the delivered message++Per-route rate limiting, an idempotency cache for provider retries, and body-size+caps checked before reading. Generic HMAC V2 (X-Webhook-Signature-V2) binds a+timestamp for replay protection; body-only V1 is deprecated but accepted with a warning."""import asyncio@@ -54,16 +41,8 @@ except ImportError:web = None # type: ignore[assignment]from gateway.config import Platform, PlatformConfig-from gateway.platforms.base import (- BasePlatformAdapter,- MessageEvent,- MessageType,- SendResult,-)-from gateway.platforms.webhook_filters import (- DEFAULT_SCRIPT_TIMEOUT_SECONDS,- WebhookRouteProcessor,-)+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResult+from gateway.platforms.webhook_filters import DEFAULT_SCRIPT_TIMEOUT_SECONDS, WebhookRouteProcessorfrom gateway.response_filters import is_autonomous_silence_responselogger = logging.getLogger(__name__)@@ -72,35 +51,16 @@ logger = logging.getLogger(__name__)def _is_webhook_silence_response(content: Any) -> bool:"""Whether an agent response means "deliberately say nothing".- Webhook routes are autonomous background lanes: a subscription prompt tells- the agent to answer with ``[SILENT]`` when a tick produced nothing worth a- human's attention (a duplicate inbound, a stand-down because a sibling lane- already replied, a routine close). Nobody is waiting on the other end, so- there is no reader for whom a "nothing happened" message is useful.-- The reason this is the loose autonomous rule rather than the live gateway's- is what the two lanes optimise for. In an interactive chat, swallowing a- real answer because it happens to open with a marker is much worse than- showing a stray marker, so ``is_intentional_silence_response`` demands the- response be EXACTLY a marker. A webhook run has the opposite payoff: the- cost of a leaked non-story is a pointless notification on every tick, and- models reliably add a sentence explaining why they stayed quiet — which- under the strict rule flips the whole thing back to "deliver". That is not- a hypothetical: it is why a Helper support lane kept messaging its owner to- report that it had nothing to report.-- So use the shared autonomous-lane matcher (also used by cron), which treats- a marker on its own first or last line as silence while still delivering- prose that merely mentions one mid-sentence. Sharing the function keeps- the two autonomous lanes from drifting apart, and keeps the interactive- path untouched.+ Autonomous lanes (no human reader) use the loose matcher shared with cron —+ marker on its own first/last line — because models add a sentence explaining+ why they stayed quiet, which the interactive exact-match rule would deliver."""return is_autonomous_silence_response(content)-# Sentinel returned by _resolve_request_profile when a /p/<profile>/ prefix-# names a profile this gateway does not serve (→ 404). Distinct from None-# (no prefix / multiplexing off → handle as the default profile).+# Sentinel from _resolve_request_profile: a /p/<profile>/ prefix names a profile+# this gateway does not serve (→ 404). Distinct from None (no prefix / default)._PROFILE_REJECTED = object()+_UNPARSEABLE = object()_BUILTIN_DELIVER_PLATFORMS = {"telegram", "discord", "slack", "signal", "sms", "whatsapp",@@ -109,67 +69,44 @@ _BUILTIN_DELIVER_PLATFORMS = {"qqbot", "yuanbao",}-# Default bind host. ``None`` tells aiohttp/asyncio's ``create_server`` to bind-# BOTH address families (IPv4 + IPv6) — the portable dual-stack default.-#-# Why not "0.0.0.0" (the old default) or "::"?-# - "0.0.0.0" binds IPv4 ONLY. On IPv6-only private networks — notably Fly.io-# 6PN, where an agent's ``<app>.internal`` name resolves to an ``fdaa:…``-# IPv6 address — an IPv4-only listener is unreachable. That is exactly why-# hosted-agent webhook routes were publicly unreachable: the edge router-# reverse-proxies to ``<app>.internal:8644`` over 6PN (IPv6) but the adapter-# was listening on 0.0.0.0 (v4 only) → connection refused.-# - "::" is NOT a safe fix: on hosts where the kernel sets IPV6_V6ONLY=1-# (verified on Fly machines), binding "::" yields an IPv6-ONLY socket, which-# then breaks the IPv4 loopback health check (``curl 127.0.0.1:8644/health``)-# and the AF_INET port-conflict probe in connect().-# - ``None`` asks the event loop to create a listening socket per resolved-# family, so both 127.0.0.1 (v4) and the 6PN fdaa (v6) are served regardless-# of the bindv6only sysctl. Users can still pin a specific host via-# ``platforms.webhook.extra.host``.+# ``None`` → aiohttp binds BOTH address families. "0.0.0.0" is IPv4-only and was+# unreachable on IPv6-only networks (Fly.io 6PN); "::" becomes IPv6-only where the+# kernel sets IPV6_V6ONLY=1, breaking the 127.0.0.1 health check. Users can pin a+# host via ``platforms.webhook.extra.host``.DEFAULT_HOST = NoneDEFAULT_PORT = 8644_INSECURE_NO_AUTH = "INSECURE_NO_AUTH"_DYNAMIC_ROUTES_FILENAME = "webhook_subscriptions.json"_RATE_WINDOW_SECONDS = 60.0-# Hostnames/IP literals that only serve connections originating on the same-# machine. Anything else is treated as a public bind for safety-rail purposes.-_LOOPBACK_HOSTS = frozenset({- "127.0.0.1",- "localhost",- "::1",- "ip6-localhost",- "ip6-loopback",-})+# Hosts that only serve same-machine connections; anything else is a public bind.+_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1", "ip6-localhost", "ip6-loopback"})+_V2_REPLAY_WINDOW_SECONDS = 300def _is_loopback_host(host: Optional[str]) -> bool:- """True when `host` binds only to the local machine.-- Covers IPv4 loopback, the standard `localhost` alias, IPv6 loopback in- both bracketed and bare form, and the common Debian-style aliases. Any- falsy value (empty string, None) is conservatively treated as non-loopback- because an unset host usually means the platform-default public bind.- """+ """True when `host` binds only to the local machine (falsy → non-loopback: usually a public default bind)."""if not host:return Falsereturn host.strip().lower() in _LOOPBACK_HOSTSdef _hmac_str_equal(provided: str, expected: str) -> bool:- """Timing-safe equality for two ``str`` values, tolerant of non-ASCII input.-- ``hmac.compare_digest`` raises ``TypeError`` when given a ``str`` that- contains non-ASCII characters. The ``provided`` value here is an- attacker-controlled signature/token header on a public, unauthenticated- webhook endpoint, so a single non-ASCII byte would otherwise raise out of- the request handler and return a 500 instead of rejecting the request.- Comparing as UTF-8 bytes keeps the constant-time guarantee while making a- hostile header fail closed with a clean rejection.+ """Timing-safe str equality tolerant of non-ASCII.++ ``compare_digest`` raises TypeError on non-ASCII str; ``provided`` is an+ attacker-controlled header, so compare as UTF-8 bytes to fail closed."""return hmac.compare_digest(provided.encode(), expected.encode())+def _hex_hmac(secret: str, data: bytes) -> str:+ return hmac.new(secret.encode(), data, hashlib.sha256).hexdigest()+++def _json_error(message: str, status: int) -> "web.Response":+ return web.json_response({"error": message}, status=status)++def check_webhook_requirements() -> bool:"""Check if webhook adapter dependencies are available."""return AIOHTTP_AVAILABLE@@ -178,17 +115,13 @@ def check_webhook_requirements() -> bool:class WebhookAdapter(BasePlatformAdapter):"""Generic webhook receiver that triggers agent runs from HTTP POSTs."""- # No human is present to answer a "session restored — what next?" prompt:- # webhook runs are event-triggered. The startup auto-resume turn must- # instruct the model to FINISH the interrupted work instead of emitting an- # interactive acknowledgement that abandons the task (#57056).+ # Event-triggered, no human present: the startup auto-resume turn must FINISH+ # the interrupted work instead of asking "what next?".interactive_resume: bool = Falsedef __init__(self, config: PlatformConfig):super().__init__(config, Platform.WEBHOOK)- # ``host`` may be None (dual-stack default) or a user-pinned string.- # A config value of empty string / null is normalised to None so it- # also means "bind all families" rather than an invalid "" host.+ # Empty string / null host normalises to None ("bind all families")._cfg_host = config.extra.get("host", DEFAULT_HOST)self._host: Optional[str] = _cfg_host or Noneself._port: int = int(config.extra.get("port", DEFAULT_PORT))@@ -198,28 +131,19 @@ class WebhookAdapter(BasePlatformAdapter):self._dynamic_routes_mtime: float = 0.0self._routes: Dict[str, dict] = dict(self._static_routes)self._runner = None- # Routes already warned about legacy V1 body-only signatures- # (once-per-route so a busy sender doesn't spam the log).+ # Routes already warned about legacy V1 body-only signatures (once per route).self._v1_signature_warned: set[str] = set()- # Delivery info keyed by session chat_id.- #- # Read by every send() invocation for the chat_id (status messages- # AND the final response). Cleaned up via TTL on each POST so the- # dict stays bounded — see _prune_delivery_info(). Do NOT pop on- # send(), or interim status messages (e.g. fallback notifications,- # context-pressure warnings) will consume the entry before the- # final response arrives, causing the response to silently fall- # back to the "log" deliver type.+ # Keyed by session chat_id; read by EVERY send() (interim status messages AND+ # the final response) so never pop on send(). TTL-pruned on each POST.self._delivery_info: Dict[str, dict] = {}self._delivery_info_created: Dict[str, float] = {}self._delivery_info_order: Deque[tuple[float, str]] = deque()- # Reference to gateway runner for cross-platform delivery (set externally)+ # Gateway runner for cross-platform delivery (set externally).self.gateway_runner = None# Idempotency: TTL cache of recently processed delivery IDs.- # Prevents duplicate agent runs when webhook providers retry.self._seen_deliveries: Dict[str, float] = {}self._idempotency_ttl: int = 3600 # 1 hourself._seen_deliveries_next_prune_at: float = 0.0@@ -227,30 +151,20 @@ class WebhookAdapter(BasePlatformAdapter):# Rate limiting: per-route timestamps in a fixed window.self._rate_counts: Dict[str, Deque[float]] = {}self._rate_limit: int = int(config.extra.get("rate_limit", 30)) # per minute-- # Body size limit (auth-before-body pattern)- self._max_body_bytes: int = int(- config.extra.get("max_body_bytes", 1_048_576)- ) # 1MB+ self._max_body_bytes: int = int(config.extra.get("max_body_bytes", 1_048_576)) # 1MBself._script_timeout_seconds: int = int(- config.extra.get(- "script_timeout_seconds",- DEFAULT_SCRIPT_TIMEOUT_SECONDS,- )- )- self._route_processor = WebhookRouteProcessor(- script_timeout_seconds=self._script_timeout_seconds+ config.extra.get("script_timeout_seconds", DEFAULT_SCRIPT_TIMEOUT_SECONDS))+ self._route_processor = WebhookRouteProcessor(script_timeout_seconds=self._script_timeout_seconds)# ------------------------------------------------------------------# Lifecycle# ------------------------------------------------------------------async def connect(self, *, is_reconnect: bool = False) -> bool:- # Load agent-created subscriptions before validatingself._reload_dynamic_routes()- # Validate routes at startup — secret is required per route+ # Validate routes at startup — secret is required per route.for name, route in self._routes.items():secret = route.get("secret", self._global_secret)if not secret:@@ -259,11 +173,8 @@ class WebhookAdapter(BasePlatformAdapter):f"Set 'secret' on the route or globally. "f"For testing without auth, set secret to '{_INSECURE_NO_AUTH}'.")-- # Safety rail: refuse to start if INSECURE_NO_AUTH is combined with a- # non-loopback bind. The escape hatch is for local testing only;- # serving an unauthenticated route on a public interface is a- # deployment-grade footgun we'd rather crash early than ship.+ # Serving an unauthenticated route on a public interface is a footgun+ # we'd rather crash early than ship.if secret == _INSECURE_NO_AUTH and not _is_loopback_host(self._host):raise ValueError(f"[webhook] Route '{name}' uses INSECURE_NO_AUTH secret "@@ -271,10 +182,6 @@ class WebhookAdapter(BasePlatformAdapter):f"INSECURE_NO_AUTH is for local testing only. "f"Refusing to start to prevent accidental exposure.")- # deliver_only routes bypass the agent — the POST body becomes a- # direct push notification via the configured delivery target.- # Validate up-front so misconfiguration surfaces at startup rather- # than on the first webhook POST.if route.get("deliver_only"):deliver = route.get("deliver", "log")if not deliver or deliver == "log":@@ -284,39 +191,22 @@ class WebhookAdapter(BasePlatformAdapter):f"real target (telegram, discord, slack, github_comment, etc.).")- # client_max_size makes aiohttp enforce the cap on every read path,- # including Transfer-Encoding: chunked bodies that carry no- # Content-Length and would otherwise bypass the header check below.+ # client_max_size enforces the cap on every read path, including chunked+ # bodies without Content-Length that bypass the header check.app = web.Application(client_max_size=self._max_body_bytes)app.router.add_get("/health", self._handle_health)app.router.add_post("/webhooks/{route_name}", self._handle_webhook)- # Multi-profile multiplexing: a /p/<profile>/webhooks/<route> prefix- # routes the inbound event to that profile. Same handler; the profile is- # captured from the path and stamped onto the SessionSource so the agent- # turn resolves that profile's config/skills/credentials. Only honored- # when gateway.multiplex_profiles is on (the handler validates).- app.router.add_post(- "/p/{profile}/webhooks/{route_name}", self._handle_webhook- )-+ # /p/<profile>/ prefix routes the event to that profile (only honored when+ # gateway.multiplex_profiles is on; the handler validates).+ app.router.add_post("/p/{profile}/webhooks/{route_name}", self._handle_webhook)self._runner = web.AppRunner(app)await self._runner.setup()- # Do not probe only one address family before binding. With the- # dual-stack default, an IPv6-only listener can already own this port- # while 127.0.0.1 still looks free.- #- # SO_REUSEADDR is platform-dependent:- # - macOS (BSD semantics): two wildcard/specific sockets with- # SO_REUSEADDR can silently split traffic while both servers- # report success — so disable it there.- # - Linux: SO_REUSEADDR only permits rebinding past TIME_WAIT- # (a second live listener needs SO_REUSEPORT, which we never- # set). Disabling it would make a quick gateway restart fail- # to bind for up to ~60s — so keep the default (enabled).+ # SO_REUSEADDR: on macOS (BSD) two wildcard/specific sockets can silently+ # split traffic while both report success → disable. On Linux it only+ # permits rebinding past TIME_WAIT (a quick restart would otherwise fail+ # to bind for ~60s) → keep the default.site = web.TCPSite(- self._runner,- self._host,- self._port,+ self._runner, self._host, self._port,reuse_address=False if sys.platform == "darwin" else None,)try:@@ -328,21 +218,15 @@ class WebhookAdapter(BasePlatformAdapter):"[webhook] Could not bind %s:%d: %s. ""Set a different host or port in config.yaml under ""platforms.webhook.extra.",- self._host or "all IPv4+IPv6 interfaces",- self._port,- exc,+ self._host or "all IPv4+IPv6 interfaces", self._port, exc,)return Falseself._mark_connected()-route_names = ", ".join(self._routes.keys()) or "(none configured)"logger.info("[webhook] Listening on %s:%d — routes: %s",- self._host or "* (all interfaces, IPv4+IPv6)",- self._port,- route_names,+ self._host or "* (all interfaces, IPv4+IPv6)", self._port, route_names,)- # Plugin-registered native handlers (ctx.register_platform_handler).self._wire_plugin_handlers(None)return True@@ -354,39 +238,23 @@ class WebhookAdapter(BasePlatformAdapter):logger.info("[webhook] Disconnected")async def send(- self,- chat_id: str,- content: str,- reply_to: Optional[str] = None,+ self, chat_id: str, content: str, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- """Deliver the agent's response to the configured destination.-- chat_id is ``webhook:{route}:{delivery_id}``. The delivery info- stored during webhook receipt is read with ``.get()`` (not popped)- so that interim status messages emitted before the final response- — fallback-model notifications, context-pressure warnings, etc. —- do not consume the entry and silently downgrade the final response- to the ``log`` deliver type. TTL cleanup happens on POST.- """+ """Deliver the agent's response to the destination stored for ``chat_id``+ (``webhook:{route}:{delivery_id}``) — read with ``.get()``, never popped."""if _is_webhook_silence_response(content):- logger.info(- "[webhook] Response for %s is a silence marker — not delivering", chat_id- )+ logger.info("[webhook] Response for %s is a silence marker — not delivering", chat_id)return SendResult(success=True)-delivery = self._delivery_info.get(chat_id, {})deliver_type = delivery.get("deliver", "log")-if deliver_type == "log":logger.info("[webhook] Response for %s: %s", chat_id, content[:200])return SendResult(success=True)-if deliver_type == "github_comment":return await self._deliver_github_comment(content, delivery)- # Cross-platform delivery — any platform with a gateway adapter.- # Check both built-in names and plugin-registered platforms.+ # Cross-platform delivery: built-in names or plugin-registered platforms._is_known_platform = deliver_type in _BUILTIN_DELIVER_PLATFORMSif not _is_known_platform:try:@@ -395,28 +263,17 @@ class WebhookAdapter(BasePlatformAdapter):except Exception:passif self.gateway_runner and _is_known_platform:- return await self._deliver_cross_platform(- deliver_type, content, delivery- )-+ return await self._deliver_cross_platform(deliver_type, content, delivery)logger.warning("[webhook] Unknown deliver type: %s", deliver_type)- return SendResult(- success=False, error=f"Unknown deliver type: {deliver_type}"- )+ return SendResult(success=False, error=f"Unknown deliver type: {deliver_type}")def _prune_delivery_info(self, now: float) -> None:- """Drop delivery_info entries older than the idempotency TTL.-- Mirrors the cleanup pattern used for ``_seen_deliveries``. Called- on each POST so the dict size is bounded by ``rate_limit * TTL``- even if many webhooks fire and never receive a final response.- """+ """Drop delivery_info entries older than the idempotency TTL (bounds the dict+ by ``rate_limit * TTL`` even when runs never produce a final response)."""if len(self._delivery_info_order) < len(self._delivery_info_created):self._delivery_info_order = deque((created_at, key)- for key, created_at in sorted(- self._delivery_info_created.items(), key=lambda item: item[1]- )+ for key, created_at in sorted(self._delivery_info_created.items(), key=lambda item: item[1]))cutoff = now - self._idempotency_ttlwhile self._delivery_info_order and self._delivery_info_order[0][0] < cutoff:@@ -467,22 +324,9 @@ class WebhookAdapter(BasePlatformAdapter):return {"name": chat_id, "type": "webhook"}def toolsets_for_source(self, source) -> Optional[List[str]]:- """Per-route toolset override.-- Webhook session chat_ids are ``webhook:{route}:{delivery_id}``.- When the matching route config carries a ``toolsets`` list, that list- replaces the platform-level ``platform_toolsets.webhook`` resolution- for this run only. Routes without the key keep the platform default- (the intentionally constrained webhook-safe toolset), so a single- trusted route (e.g. a localhost monitoring push) can be granted- ``terminal`` without widening every other webhook route.-- Set via ``platforms.webhook.extra.routes.<name>.toolsets`` in- config.yaml or a ``toolsets`` key on a subscription in- ``webhook_subscriptions.json`` (manual edit — deliberately NOT- exposed through `hermes webhook subscribe`, so an agent-created- subscription cannot self-grant elevated tools).- """+ """Per-route ``toolsets`` override (config.yaml or a manual key in+ webhook_subscriptions.json — deliberately NOT settable via `hermes webhook+ subscribe`, so an agent-created subscription cannot self-grant tools)."""chat_id = str(getattr(source, "chat_id", "") or "")parts = chat_id.split(":", 2)if len(parts) < 2 or parts[0] != "webhook":@@ -507,8 +351,7 @@ class WebhookAdapter(BasePlatformAdapter):def _reload_dynamic_routes(self) -> None:"""Reload agent-created subscriptions from disk if the file changed."""from hermes_constants import get_hermes_home- hermes_home = get_hermes_home()- subs_path = hermes_home / _DYNAMIC_ROUTES_FILENAME+ subs_path = get_hermes_home() / _DYNAMIC_ROUTES_FILENAMEif not subs_path.exists():if self._dynamic_routes:self._dynamic_routes = {}@@ -522,10 +365,8 @@ class WebhookAdapter(BasePlatformAdapter):data = json.loads(subs_path.read_text(encoding="utf-8"))if not isinstance(data, dict):return- # Merge: static routes take precedence over dynamic ones.- # Reject any dynamic route whose effective secret is empty —- # an empty secret would cause _handle_webhook to skip HMAC- # validation entirely, letting unauthenticated callers in.+ # Static routes take precedence. An empty effective secret would make+ # _handle_webhook skip HMAC validation → reject such dynamic routes.new_dynamic: Dict[str, dict] = {}for k, v in data.items():if k in self._static_routes:@@ -536,19 +377,14 @@ class WebhookAdapter(BasePlatformAdapter):"[webhook] Dynamic route '%s' skipped: 'secret' is ""missing or empty. Set a valid HMAC secret, or use ""'%s' to explicitly disable auth (testing only).",- k,- _INSECURE_NO_AUTH,+ k, _INSECURE_NO_AUTH,)continue- if (- effective_secret == _INSECURE_NO_AUTH- and not _is_loopback_host(self._host)- ):+ if effective_secret == _INSECURE_NO_AUTH and not _is_loopback_host(self._host):logger.warning("[webhook] Dynamic route '%s' skipped: INSECURE_NO_AUTH ""is only allowed on loopback hosts. Current host: '%s'.",- k,- self._host,+ k, self._host,)continuenew_dynamic[k] = v@@ -557,24 +393,17 @@ class WebhookAdapter(BasePlatformAdapter):self._dynamic_routes_mtime = mtimelogger.info("[webhook] Reloaded %d dynamic route(s): %s",- len(self._dynamic_routes),- ", ".join(self._dynamic_routes.keys()) or "(none)",+ len(self._dynamic_routes), ", ".join(self._dynamic_routes.keys()) or "(none)",)except Exception as e:logger.error("[webhook] Failed to reload dynamic routes: %s", e)def _resolve_request_profile(self, request: "web.Request"):- """Resolve + validate the /p/<profile>/ URL prefix on a webhook request.-- Returns:- - ``None`` when no profile prefix is present, or when multiplexing- is off and the prefix names this gateway's own profile (the- request is handled as the serving profile).- - the profile name (str) when present, multiplexing is on, and the- profile is one this gateway serves.- - ``_PROFILE_REJECTED`` when a prefix is present but the profile is- unknown/unconfigured, or names a profile this single-profile- gateway does not serve (handler returns 404).+ """Resolve + validate the /p/<profile>/ URL prefix.++ Returns None (no prefix, or multiplexing off and the prefix names this+ gateway's own profile), the profile name (served under multiplexing), or+ ``_PROFILE_REJECTED`` (unknown / not served → 404)."""profile = (request.match_info.get("profile") or "").strip()if not profile:@@ -582,14 +411,11 @@ class WebhookAdapter(BasePlatformAdapter):runner = self.gateway_runnercfg = getattr(runner, "config", None)if not getattr(cfg, "multiplex_profiles", False):- # Prefix supplied but multiplexing is off. Only a self-referential- # prefix (naming this gateway's own profile) may fall through to- # the bare route; anything else fails closed — silently ignoring- # the prefix served the gateway owner's routes/config under- # another profile's URL (#91583 defect 2).+ # Only a self-referential prefix may fall through to the bare route;+ # anything else fails closed (silently ignoring the prefix served the+ # owner's routes under another profile's URL).try:from hermes_cli.profiles import profile_matches_home-if profile_matches_home(profile):return Noneexcept Exception:@@ -601,9 +427,7 @@ class WebhookAdapter(BasePlatformAdapter):namefor name, _ in profiles_to_serve(multiplex=True,- profile_allowlist=getattr(- cfg, "multiplex_profile_allowlist", None- ),+ profile_allowlist=getattr(cfg, "multiplex_profile_allowlist", None),)}except Exception:@@ -613,15 +437,8 @@ class WebhookAdapter(BasePlatformAdapter):return profile@staticmethod- def _route_allows_profile(- route_config: dict,- request_profile: Optional[str],- ) -> bool:- """Return whether a route is bound to the URL-selected profile.-- Omitting ``profile`` keeps a route on the default profile. An explicit- null, blank, or non-string value is malformed and fails closed.- """+ def _route_allows_profile(route_config: dict, request_profile: Optional[str]) -> bool:+ """Omitting ``profile`` binds a route to default; an explicit null/blank/non-string fails closed."""if "profile" not in route_config:configured_profile = "default"else:@@ -636,135 +453,119 @@ class WebhookAdapter(BasePlatformAdapter):@staticmethoddef _profile_scope(profile: Optional[str]):- """Enter the URL-resolved profile's runtime scope, or a no-op.-- Only a resolved ``/p/<profile>/`` prefix enters a scope (same helper- the runner wraps ``handle_message`` in); bare routes keep serving the- launch profile exactly as before.- """+ """Runtime scope for a resolved ``/p/<profile>/`` prefix; bare routes get a no-op."""if not profile or not isinstance(profile, str):return nullcontext()from gateway.run import _profile_runtime_scopefrom hermes_cli.profiles import get_profile_dir-return _profile_runtime_scope(get_profile_dir(profile))- async def _handle_webhook(self, request: "web.Request") -> "web.Response":- """POST /webhooks/{route_name} — receive and process a webhook event."""- # Hot-reload dynamic subscriptions on each request (mtime-gated, cheap)- self._reload_dynamic_routes()-- route_name = request.match_info.get("route_name", "")- route_config = self._routes.get(route_name)-- # Multi-profile: resolve + validate the /p/<profile>/ prefix if present.- profile = self._resolve_request_profile(request)- if profile is _PROFILE_REJECTED:- return web.json_response(- {"error": "Unknown or unconfigured profile"}, status=404- )-- if not route_config:- return web.json_response(- {"error": f"Unknown route: {route_name}"}, status=404- )-- if not self._route_allows_profile(route_config, profile):- effective_profile = profile or "default"- logger.warning(- "[webhook] Route %s is not authorized for profile %r",- route_name,- effective_profile,- )- # Match the unknown-route response so callers cannot use profile- # mismatches to enumerate route bindings.- return web.json_response(- {"error": f"Unknown route: {route_name}"}, status=404- )-- # Disabled routes are kept in the subscriptions file (so the dashboard- # can re-enable them) but reject incoming events. Default-enabled:- # only an explicit ``enabled: false`` turns a route off, matching the- # mcp_servers ``enabled`` semantics.- if route_config.get("enabled", True) is False:- return web.json_response(- {"error": f"Route disabled: {route_name}"}, status=403- )-- # ── Auth-before-body ─────────────────────────────────────- # Check Content-Length before reading the full payload.+ async def _read_authenticated_body(+ self, request: "web.Request", route_name: str, route_config: dict+ ) -> "tuple[Optional[bytes], Optional[web.Response]]":+ """Auth-before-body: size-cap, read, then HMAC-validate. Returns ``(body, None)`` or ``(None, response)``."""content_length = request.content_length or 0if content_length > self._max_body_bytes:- return web.json_response(- {"error": "Payload too large"}, status=413- )-- # Read body (must be done before any validation)+ return None, _json_error("Payload too large", 413)try:raw_body = await request.read()except web.HTTPRequestEntityTooLarge:- # aiohttp's client_max_size tripped — chunked or lying- # Content-Length. Same 413 as the header check above.- return web.json_response(- {"error": "Payload too large"}, status=413- )+ # aiohttp's client_max_size tripped — chunked or lying Content-Length.+ return None, _json_error("Payload too large", 413)except Exception as e:logger.error("[webhook] Failed to read body: %s", e)- return web.json_response({"error": "Bad request"}, status=400)+ return None, _json_error("Bad request", 400)if len(raw_body) > self._max_body_bytes:- # Defense in depth: enforce the cap on the actual bytes read even- # if the server-level limit was bypassed or misconfigured.- return web.json_response(- {"error": "Payload too large"}, status=413- )+ # Defense in depth if the server-level limit was bypassed or misconfigured.+ return None, _json_error("Payload too large", 413)- # Validate HMAC signature FIRST (skip only for the explicit local-test- # INSECURE_NO_AUTH mode). Missing/empty secrets must fail closed here,- # not only during connect(), so direct handler reuse cannot turn a- # network webhook route into an unauthenticated agent-dispatch surface.+ # Missing/empty secrets fail closed here too (not only in connect()), so+ # direct handler reuse cannot become an unauthenticated dispatch surface.secret = route_config.get("secret", self._global_secret)if not secret:- logger.error(- "[webhook] Route %s has no HMAC secret; refusing request",- route_name,- )- return web.json_response(- {"error": "Webhook route is missing an HMAC secret"},- status=403,- )+ logger.error("[webhook] Route %s has no HMAC secret; refusing request", route_name)+ return None, _json_error("Webhook route is missing an HMAC secret", 403)if secret != _INSECURE_NO_AUTH:if not self._validate_signature(request, raw_body, secret):- logger.warning(- "[webhook] Invalid signature for route %s", route_name- )- return web.json_response(- {"error": "Invalid signature"}, status=401- )-- # ── Rate limiting (after auth) ───────────────────────────- now = time.time()- if not self._record_rate_limit_hit(route_name, now):- return web.json_response(- {"error": "Rate limit exceeded"}, status=429- )+ logger.warning("[webhook] Invalid signature for route %s", route_name)+ return None, _json_error("Invalid signature", 401)+ return raw_body, None- # Parse payload+ @staticmethod+ def _parse_body(raw_body: bytes) -> Any:+ """JSON, falling back to form-encoded; ``_UNPARSEABLE`` when neither parses."""try:- payload = json.loads(raw_body)+ return json.loads(raw_body)except json.JSONDecodeError:- # Try form-encoded as fallbacktry:import urllib.parse-- payload = dict(- urllib.parse.parse_qsl(raw_body.decode("utf-8"))- )+ return dict(urllib.parse.parse_qsl(raw_body.decode("utf-8")))except Exception:- return web.json_response(- {"error": "Cannot parse body"}, status=400- )+ return _UNPARSEABLE++ async def _handle_deliver_only(+ self, prompt: str, payload: Any, route_config: dict, route_name: str, event_type: str, delivery_id: str+ ) -> "web.Response":+ """deliver_only: the rendered prompt IS the message — skip the agent, reuse+ the same auth/rate-limit/idempotency/template pipeline."""+ delivery = {+ "deliver": route_config.get("deliver", "log"),+ "deliver_extra": self._render_delivery_extra(route_config.get("deliver_extra", {}), payload),+ "payload": payload,+ }+ logger.info(+ "[webhook] direct-deliver event=%s route=%s target=%s msg_len=%d delivery=%s",+ event_type, route_name, delivery["deliver"], len(prompt), delivery_id,+ )+ failed = {"status": "error", "error": "Delivery failed", "delivery_id": delivery_id}+ try:+ result = await self._direct_deliver(prompt, delivery)+ except Exception:+ logger.exception("[webhook] direct-deliver failed route=%s delivery=%s", route_name, delivery_id)+ return web.json_response(failed, status=502)+ if result.success:+ return web.json_response(+ {"status": "delivered", "route": route_name, "target": delivery["deliver"], "delivery_id": delivery_id},+ status=200,+ )+ # Target rejected it — 502 with a generic error (don't leak adapter detail).+ logger.warning(+ "[webhook] direct-deliver target rejected route=%s target=%s error=%s",+ route_name, delivery["deliver"], result.error,+ )+ return web.json_response(failed, status=502)++ async def _handle_webhook(self, request: "web.Request") -> "web.Response":+ """POST /webhooks/{route_name} — receive and process a webhook event."""+ # Hot-reload dynamic subscriptions on each request (mtime-gated, cheap)+ self._reload_dynamic_routes()+ route_name = request.match_info.get("route_name", "")+ route_config = self._routes.get(route_name)+ profile = self._resolve_request_profile(request)+ if profile is _PROFILE_REJECTED:+ return _json_error("Unknown or unconfigured profile", 404)+ if not route_config:+ return _json_error(f"Unknown route: {route_name}", 404)+ if not self._route_allows_profile(route_config, profile):+ logger.warning("[webhook] Route %s is not authorized for profile %r", route_name, profile or "default")+ # Same as unknown-route so profile mismatches can't enumerate route bindings.+ return _json_error(f"Unknown route: {route_name}", 404)- # Check event type filter+ # Disabled routes stay in the subscriptions file (dashboard can re-enable)+ # but reject events. Only an explicit ``enabled: false`` turns a route off.+ if route_config.get("enabled", True) is False:+ return _json_error(f"Route disabled: {route_name}", 403)+ raw_body, error_response = await self._read_authenticated_body(request, route_name, route_config)+ if error_response is not None:+ return error_response++ # Rate limiting (after auth)+ now = time.time()+ if not self._record_rate_limit_hit(route_name, now):+ return _json_error("Rate limit exceeded", 429)+ payload = self._parse_body(raw_body)+ if payload is _UNPARSEABLE:+ return _json_error("Cannot parse body", 400)event_type = (request.headers.get("X-GitHub-Event", "")or request.headers.get("X-GitLab-Event", "")@@ -775,195 +576,70 @@ class WebhookAdapter(BasePlatformAdapter):allowed_events = route_config.get("events", [])if allowed_events and event_type not in allowed_events:logger.debug(- "[webhook] Ignoring event %s for route %s (allowed: %s)",- event_type,- route_name,- allowed_events,- )- return web.json_response(- {"status": "ignored", "event": event_type}- )-- if not self._route_processor.route_filters_match(- route_config, payload, event_type, request.headers- ):- logger.info(- "[webhook] filtered event=%s route=%s",- event_type,- route_name,- )- return web.json_response(- {- "status": "ignored",- "reason": "filter",- "route": route_name,- }+ "[webhook] Ignoring event %s for route %s (allowed: %s)", event_type, route_name, allowed_events,)+ return web.json_response({"status": "ignored", "event": event_type})+ if not self._route_processor.route_filters_match(route_config, payload, event_type, request.headers):+ logger.info("[webhook] filtered event=%s route=%s", event_type, route_name)+ return web.json_response({"status": "ignored", "reason": "filter", "route": route_name})- # The route script, prompt render and skill lookup below read the- # profile's home (skills/, config). The runner only enters the routed- # profile's scope later, around handle_message, so without this they- # ran against the launch (default) profile (#67277). Only a resolved- # /p/<profile>/ enters a scope; bare routes are unchanged.+ # Script, prompt render and skill lookup read the profile's home (skills/,+ # config); the runner only enters the routed profile's scope later around+ # handle_message, so enter it here. Bare routes are unchanged.with self._profile_scope(profile):if route_config.get("script"):- # run_route_script shells out (subprocess.run, up to its- # timeout); run it in a worker thread so it can't block the- # gateway event loop. to_thread copies the contextvars, so- # the profile scope follows it.+ # Shells out (up to its timeout) — worker thread so the event loop+ # isn't blocked; to_thread copies contextvars so the scope follows.keep, transformed_payload = await asyncio.to_thread(- self._route_processor.run_route_script,- route_config.get("script"),- payload,+ self._route_processor.run_route_script, route_config.get("script"), payload,)if not keep:- logger.info(- "[webhook] script ignored event=%s route=%s",- event_type,- route_name,- )- return web.json_response(- {- "status": "ignored",- "reason": "script",- "route": route_name,- }- )+ logger.info("[webhook] script ignored event=%s route=%s", event_type, route_name)+ return web.json_response({"status": "ignored", "reason": "script", "route": route_name})payload = transformed_payload or payload+ prompt = self._render_prompt(route_config.get("prompt", ""), payload, event_type, route_name)- # Format prompt from template- prompt_template = route_config.get("prompt", "")- prompt = self._render_prompt(- prompt_template, payload, event_type, route_name- )-- # Inject skill content if configured.- # We call build_skill_invocation_message() directly rather than- # using /skill-name slash commands — the gateway's command parser- # would intercept those and break the flow.+ # Inject skill content via build_skill_invocation_message() directly —+ # /skill-name slash commands would be intercepted by the command parser.skills = route_config.get("skills", [])if skills:try:- from agent.skill_commands import (- build_skill_invocation_message,- get_skill_commands,- )-+ from agent.skill_commands import build_skill_invocation_message, get_skill_commandsskill_cmds = get_skill_commands()for skill_name in skills:cmd_key = f"/{skill_name}"if cmd_key in skill_cmds:- skill_content = build_skill_invocation_message(- cmd_key, user_instruction=prompt- )+ skill_content = build_skill_invocation_message(cmd_key, user_instruction=prompt)if skill_content:prompt = skill_contentbreak # Load the first matching skillelse:- logger.warning(- "[webhook] Skill '%s' not found", skill_name- )+ logger.warning("[webhook] Skill '%s' not found", skill_name)except Exception as e:logger.warning("[webhook] Skill loading failed: %s", e)-- # Build a unique delivery IDdelivery_id = request.headers.get("X-GitHub-Delivery",- request.headers.get(- "svix-id",- request.headers.get("X-Request-ID", str(int(time.time() * 1000))),- ),+ request.headers.get("svix-id", request.headers.get("X-Request-ID", str(int(time.time() * 1000)))),)- # ── Idempotency ─────────────────────────────────────────- # Skip duplicate deliveries (webhook retries).+ # Idempotency: skip duplicate deliveries (webhook retries).now = time.time()if not self._record_delivery_id(delivery_id, now):- logger.info(- "[webhook] Skipping duplicate delivery %s", delivery_id- )- return web.json_response(- {"status": "duplicate", "delivery_id": delivery_id},- status=200,- )-- # ── Direct delivery mode (deliver_only) ─────────────────- # Skip the agent entirely — the rendered prompt IS the message we- # deliver. Use case: external services (Supabase, monitoring,- # cron jobs, other agents) that need to push a plain notification- # to a user's chat with zero LLM cost. Reuses the same HMAC auth,- # rate limiting, idempotency, and template rendering as agent mode.+ logger.info("[webhook] Skipping duplicate delivery %s", delivery_id)+ return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)if route_config.get("deliver_only"):- delivery = {- "deliver": route_config.get("deliver", "log"),- "deliver_extra": self._render_delivery_extra(- route_config.get("deliver_extra", {}), payload- ),- "payload": payload,- }- logger.info(- "[webhook] direct-deliver event=%s route=%s target=%s msg_len=%d delivery=%s",- event_type,- route_name,- delivery["deliver"],- len(prompt),- delivery_id,- )- try:- result = await self._direct_deliver(prompt, delivery)- except Exception:- logger.exception(- "[webhook] direct-deliver failed route=%s delivery=%s",- route_name,- delivery_id,- )- return web.json_response(- {"status": "error", "error": "Delivery failed", "delivery_id": delivery_id},- status=502,- )-- if result.success:- return web.json_response(- {- "status": "delivered",- "route": route_name,- "target": delivery["deliver"],- "delivery_id": delivery_id,- },- status=200,- )- # Delivery attempted but target rejected it — surface as 502- # with a generic error (don't leak adapter-level detail).- logger.warning(- "[webhook] direct-deliver target rejected route=%s target=%s error=%s",- route_name,- delivery["deliver"],- result.error,- )- return web.json_response(- {"status": "error", "error": "Delivery failed", "delivery_id": delivery_id},- status=502,- )+ return await self._handle_deliver_only(prompt, payload, route_config, route_name, event_type, delivery_id)- # Use delivery_id in session key so concurrent webhooks on the- # same route get independent agent runs (not queued/interrupted).+ # delivery_id in the session key → concurrent webhooks on one route get+ # independent agent runs (not queued/interrupted).session_chat_id = f"webhook:{route_name}:{delivery_id}"-- # Store delivery info for send(). Read by every send() invocation- # for this chat_id (interim status messages and the final response),- # so we do NOT pop on send. TTL-based cleanup keeps the dict bounded.- deliver_config = {+ self._delivery_info[session_chat_id] = {"deliver": route_config.get("deliver", "log"),- "deliver_extra": self._render_delivery_extra(- route_config.get("deliver_extra", {}), payload- ),+ "deliver_extra": self._render_delivery_extra(route_config.get("deliver_extra", {}), payload),}- self._delivery_info[session_chat_id] = deliver_configself._delivery_info_created[session_chat_id] = nowself._delivery_info_order.append((now, session_chat_id))self._prune_delivery_info(now)-- # Build source and eventsource = self.build_source(chat_id=session_chat_id,chat_name=f"webhook/{route_name}",@@ -980,69 +656,34 @@ class WebhookAdapter(BasePlatformAdapter):raw_message=payload,message_id=delivery_id,)-logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s",- request.method,- event_type,- route_name,- len(prompt),- delivery_id,+ request.method, event_type, route_name, len(prompt), delivery_id,)- # Non-blocking — return 202 Accepted immediately. The per-delivery- # session is closed by the ``on_processing_complete`` override below- # once the agent run actually finishes (``handle_message`` itself is- # fire-and-forget: it spawns ``_process_message_background`` and- # returns before the run starts, so nothing can be closed here).+ # Return 202 immediately. The per-delivery session is closed by+ # ``on_processing_complete`` once the run finishes (``handle_message`` is+ # fire-and-forget, so nothing can be closed here).task = asyncio.create_task(self.handle_message(event))self._background_tasks.add(task)task.add_done_callback(self._background_tasks.discard)-return web.json_response(- {- "status": "accepted",- "route": route_name,- "event": event_type,- "delivery_id": delivery_id,- },+ {"status": "accepted", "route": route_name, "event": event_type, "delivery_id": delivery_id},status=202,)- async def on_processing_complete(- self, event: "MessageEvent", outcome: Any- ) -> None:- """Close the per-delivery webhook session once its run finishes.-- A webhook delivery is one-shot: the ``delivery_id`` is baked into the- session key, so the session will never receive a second turn. Mirror- the cron completion path (``cron/scheduler.py`` →- ``end_session(..., "cron_complete")``) by marking the session ended- when the run completes. Without this, webhook sessions keep- ``ended_at`` NULL forever; ``SessionDB.prune_sessions`` only reaps- rows with ``ended_at`` set, so unclosed webhook sessions accumulate- unbounded and drive state.db bloat (the ghost-session leak).-- This hook is the one seam that runs at the TRUE end of the run:- ``BasePlatformAdapter._process_message_background`` fires it after the- message handler returns, on the success, failure, and cancellation- paths alike — so error runs are reaped too. (``handle_message`` is- fire-and-forget; wrapping IT closes before the run even starts.)- ``end_session()`` is first-reason-wins and no-ops on an already-ended- row, so this never clobbers a ``compression``/``agent_close`` reason.+ async def on_processing_complete(self, event: "MessageEvent", outcome: Any) -> None:+ """Close the one-shot per-delivery session once its run finishes.++ ``prune_sessions`` only reaps rows with ``ended_at`` set, so unclosed webhook+ sessions leak unbounded. This hook fires at the true end of the run (success,+ failure, cancellation); ``end_session()`` is first-reason-wins."""await self._end_webhook_session(event, event.source.chat_id)- async def _end_webhook_session(- self, event: "MessageEvent", session_chat_id: str- ) -> None:- """Mark the per-delivery webhook session ended in state.db.-- Resolves the persisted ``session_id`` from the gateway session store- using the SAME source the run was keyed on (so profile multiplexing- and key construction match exactly), then closes it via the existing- ``SessionDB.end_session`` API — never a hand-written UPDATE.- """+ async def _end_webhook_session(self, event: "MessageEvent", session_chat_id: str) -> None:+ """Mark the per-delivery session ended via ``SessionDB.end_session`` (never a hand-written UPDATE),+ resolving session_id from the SAME source the run was keyed on."""runner = self.gateway_runnerif runner is None:return@@ -1055,11 +696,8 @@ class WebhookAdapter(BasePlatformAdapter):if key_fn is None:returnsession_key = key_fn(event.source)- # Resolve the persisted session_id via the store's public,- # lock-held accessor (peek_session_id) rather than reaching into- # the private _entries dict without the store lock. Fall back to- # the private path only for older stores / test doubles that- # predate the accessor.+ # Prefer the store's lock-held accessor; fall back to the private path+ # only for older stores / test doubles that predate it.peek = getattr(store, "peek_session_id", None)if callable(peek):session_id = peek(session_key)@@ -1073,37 +711,21 @@ class WebhookAdapter(BasePlatformAdapter):entry = entries.get(session_key)session_id = getattr(entry, "session_id", None) if entry else Noneif not session_id:- logger.debug(- "[webhook] No session_id to close for %s (key=%s)",- session_chat_id,- session_key,- )+ logger.debug("[webhook] No session_id to close for %s (key=%s)", session_chat_id, session_key)return- # AsyncSessionDB forwards end_session via asyncio.to_thread; a- # plain SessionDB exposes it synchronously. Handle both.- _end = session_db.end_session- result = _end(session_id, "webhook_complete")+ # AsyncSessionDB forwards end_session via to_thread; plain SessionDB is sync.+ result = session_db.end_session(session_id, "webhook_complete")if asyncio.iscoroutine(result):await result- logger.debug(- "[webhook] Closed session %s for delivery %s",- session_id,- session_chat_id,- )+ logger.debug("[webhook] Closed session %s for delivery %s", session_id, session_chat_id)except Exception as e:- logger.debug(- "[webhook] Failed to close session for %s: %s",- session_chat_id,- e,- )+ logger.debug("[webhook] Failed to close session for %s: %s", session_chat_id, e)# ------------------------------------------------------------------# Signature validation# ------------------------------------------------------------------- def _validate_signature(- self, request: "web.Request", body: bytes, secret: str- ) -> bool:+ def _validate_signature(self, request: "web.Request", body: bytes, secret: str) -> bool:"""Validate webhook signature (GitHub, GitLab, Svix, Linear, generic HMAC-SHA256)."""def _header(name: str) -> str:return (@@ -1112,65 +734,35 @@ class WebhookAdapter(BasePlatformAdapter):or request.headers.get(name.upper(), ""))- # Svix / AgentMail:- # svix-id: msg_...- # svix-timestamp: unix seconds- # svix-signature: v1,<base64-hmac> [v1,<base64-hmac> ...]- # Signed content is: "{id}.{timestamp}.{raw_body}". Svix secrets- # usually start with "whsec_" and the remainder is base64-encoded.+ # Svix / AgentMail: signed content is "{id}.{timestamp}.{raw_body}".svix_id = _header("svix-id")svix_timestamp = _header("svix-timestamp")svix_signature = _header("svix-signature")if svix_id or svix_timestamp or svix_signature:return self._validate_svix_signature(- body=body,- secret=secret,- msg_id=svix_id,- timestamp=svix_timestamp,- signature_header=svix_signature,+ body=body, secret=secret, msg_id=svix_id, timestamp=svix_timestamp, signature_header=svix_signature,)- # Linear: linear-signature = <hex HMAC-SHA256 of the raw body, keyed- # by the webhook signing key>. Linear's documented scheme signs the- # body only (no timestamp binding), so this mirrors it exactly;- # without this branch every Linear delivery to a secret-configured- # route was rejected as unrecognized (#87348).+ # Linear: linear-signature = hex HMAC-SHA256 of the raw body (no timestamp binding).linear_sig = _header("linear-signature")if linear_sig:- expected_linear = hmac.new(- secret.encode(), body, hashlib.sha256- ).hexdigest()- return _hmac_str_equal(linear_sig, expected_linear)+ return _hmac_str_equal(linear_sig, _hex_hmac(secret, body))# GitHub: X-Hub-Signature-256 = sha256=<hex>gh_sig = request.headers.get("X-Hub-Signature-256", "")if gh_sig:- expected = "sha256=" + hmac.new(- secret.encode(), body, hashlib.sha256- ).hexdigest()- return _hmac_str_equal(gh_sig, expected)+ return _hmac_str_equal(gh_sig, "sha256=" + _hex_hmac(secret, body))# GitLab: X-Gitlab-Token = <plain secret>gl_token = request.headers.get("X-Gitlab-Token", "")if gl_token:return _hmac_str_equal(gl_token, secret)- # Generic V2: X-Webhook-Signature-V2 = <hex HMAC-SHA256 of "<timestamp>.<body>">- # X-Webhook-Timestamp = <unix seconds> (required for V2)- # Checked independently of (and before) legacy V1 below — a sender- # that only ever sends V2 headers must still validate here; nesting- # this inside `if generic_sig:` would silently skip V2-only senders.- #- # The presence of X-Webhook-Signature-V2 alone selects V2 mode and- # commits to it — it must NOT fall through to the V1 branch just- # because the timestamp is missing/malformed/expired. A sender- # migrating to V2 typically sends both V1 and V2 headers together- # for compatibility; if incomplete V2 fell through to V1, an- # attacker who captured one such mixed request could strip the- # X-Webhook-Timestamp header from a replay and have it validate- # against the still-present, still-unprotected V1 signature instead- # — silently downgrading a V2-protected request back to the replay- # hole V2 exists to close.+ # Generic V2: X-Webhook-Signature-V2 = hex HMAC-SHA256 of "<timestamp>.<body>",+ # X-Webhook-Timestamp required. Presence of the V2 header COMMITS to V2 — it+ # must not fall through to V1 on a missing/bad timestamp, or an attacker could+ # strip the timestamp from a captured mixed V1+V2 request and replay it+ # against the still-present body-only V1 signature.v2_sig = request.headers.get("X-Webhook-Signature-V2", "")if v2_sig:v2_timestamp = request.headers.get("X-Webhook-Timestamp", "")@@ -1186,29 +778,17 @@ class WebhookAdapter(BasePlatformAdapter):ts = int(v2_timestamp)except (TypeError, ValueError):return False- if abs(int(time.time()) - ts) > 300:+ if abs(int(time.time()) - ts) > _V2_REPLAY_WINDOW_SECONDS:logger.warning("[webhook] Route '%s' generic HMAC V2 timestamp outside replay window",request.match_info.get("route_name", ""),)return False- signed_content = v2_timestamp.encode() + b"." + body- expected_v2 = hmac.new(- secret.encode(), signed_content, hashlib.sha256- ).hexdigest()- return _hmac_str_equal(v2_sig, expected_v2)-- # Generic V1 (legacy): X-Webhook-Signature = <hex HMAC-SHA256 of body>- # (deprecated — no replay protection, since the signature only- # covers the body: a captured (body, signature) pair replays- # indefinitely with no timestamp binding it to a specific delivery.)- # Only reachable when X-Webhook-Signature-V2 was not sent at all —- # see the guard above.+ return _hmac_str_equal(v2_sig, _hex_hmac(secret, v2_timestamp.encode() + b"." + body))++ # Generic V1 (legacy, deprecated): body-only HMAC → replays indefinitely.generic_sig = request.headers.get("X-Webhook-Signature", "")if generic_sig:- expected = hmac.new(- secret.encode(), body, hashlib.sha256- ).hexdigest()route_name = request.match_info.get("route_name", "")if route_name not in self._v1_signature_warned:self._v1_signature_warned.add(route_name)@@ -1220,27 +800,17 @@ class WebhookAdapter(BasePlatformAdapter):"'<timestamp>.<body>').",route_name,)- return _hmac_str_equal(generic_sig, expected)-- # No recognised signature header but secret is configured → reject- logger.debug(- "[webhook] Secret configured but no signature header found"- )+ return _hmac_str_equal(generic_sig, _hex_hmac(secret, body))+ logger.debug("[webhook] Secret configured but no signature header found")return Falsedef _validate_svix_signature(- self,- body: bytes,- secret: str,- msg_id: str,- timestamp: str,- signature_header: str,+ self, body: bytes, secret: str, msg_id: str, timestamp: str, signature_header: str,tolerance_seconds: int = 300,) -> bool:"""Validate Svix-compatible signatures used by AgentMail webhooks."""if not (msg_id and timestamp and signature_header and secret):return False-try:ts = int(timestamp)except (TypeError, ValueError):@@ -1248,7 +818,6 @@ class WebhookAdapter(BasePlatformAdapter):if abs(int(time.time()) - ts) > tolerance_seconds:logger.warning("[webhook] Svix signature timestamp outside replay window")return False-if secret.startswith("whsec_"):encoded_secret = secret.removeprefix("whsec_")try:@@ -1257,18 +826,13 @@ class WebhookAdapter(BasePlatformAdapter):logger.debug("[webhook] Invalid whsec_ Svix signing secret")return Falseelse:- # Be permissive for providers that document Svix-style headers but- # hand out raw shared secrets rather than whsec_ base64 secrets.+ # Some providers document Svix-style headers but hand out raw shared secrets.logger.debug("[webhook] Validating Svix-style signature with raw secret")key = secret.encode()-signed_content = msg_id.encode() + b"." + timestamp.encode() + b"." + body- expected = base64.b64encode(- hmac.new(key, signed_content, hashlib.sha256).digest()- ).decode()+ expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest()).decode()- # Svix can send multiple signatures separated by spaces during secret- # rotation. Each entry is formatted as "vN,<base64>".+ # Multiple space-separated "vN,<base64>" entries during secret rotation.for part in signature_header.split():try:version, signature = part.split(",", 1)@@ -1282,21 +846,10 @@ class WebhookAdapter(BasePlatformAdapter):# Prompt rendering# ------------------------------------------------------------------- def _render_prompt(- self,- template: str,- payload: dict,- event_type: str,- route_name: str,- ) -> str:- """Render a prompt template with the webhook payload.-- Supports dot-notation access into nested dicts:- ``{pull_request.title}`` → ``payload["pull_request"]["title"]``-- Special token ``{__raw__}`` dumps the entire payload as indented- JSON (truncated to 4000 chars). Useful for monitoring alerts or- any webhook where the agent needs to see the full payload.+ def _render_prompt(self, template: str, payload: dict, event_type: str, route_name: str) -> str:+ """Render a prompt template with dot-notation payload access (``{pull_request.title}``).++ ``{__raw__}`` dumps the whole payload as indented JSON (truncated to 4000 chars)."""if not template:truncated = json.dumps(payload, indent=2)[:4000]@@ -1307,7 +860,6 @@ class WebhookAdapter(BasePlatformAdapter):def _resolve(match: re.Match) -> str:key = match.group(1)- # Special token: dump the entire payload as JSONif key == "__raw__":return json.dumps(payload, indent=2)[:4000]if key == "event_type":@@ -1324,9 +876,7 @@ class WebhookAdapter(BasePlatformAdapter):return re.sub(r"\{([a-zA-Z0-9_.]+)\}", _resolve, template)- def _render_delivery_extra(- self, extra: dict, payload: dict- ) -> dict:+ def _render_delivery_extra(self, extra: dict, payload: dict) -> dict:"""Render delivery_extra template values with payload data."""rendered: Dict[str, Any] = {}for key, value in extra.items():@@ -1340,136 +890,73 @@ class WebhookAdapter(BasePlatformAdapter):# Response delivery# ------------------------------------------------------------------- async def _direct_deliver(- self, content: str, delivery: dict- ) -> SendResult:- """Deliver *content* directly without invoking the agent.-- Used by ``deliver_only`` routes: the rendered template becomes the- literal message body, and we dispatch to the same delivery helpers- that the agent-mode ``send()`` flow uses. All target types that- work in agent mode work here — Telegram, Discord, Slack, GitHub- PR comments, etc.- """+ async def _direct_deliver(self, content: str, delivery: dict) -> SendResult:+ """deliver_only: dispatch *content* to the same delivery helpers agent-mode ``send()`` uses."""deliver_type = delivery.get("deliver", "log")-if deliver_type == "log":- # Shouldn't reach here — startup validation rejects deliver_only- # with deliver=log — but guard defensively.+ # Startup validation rejects deliver_only + log, but guard defensively.logger.info("[webhook] direct-deliver log-only: %s", content[:200])return SendResult(success=True)-if deliver_type == "github_comment":return await self._deliver_github_comment(content, delivery)+ return await self._deliver_cross_platform(deliver_type, content, delivery)- # Fall through to the cross-platform dispatcher, which validates the- # target name and routes via the gateway runner.- return await self._deliver_cross_platform(- deliver_type, content, delivery- )-- async def _deliver_github_comment(- self, content: str, delivery: dict- ) -> SendResult:+ async def _deliver_github_comment(self, content: str, delivery: dict) -> SendResult:"""Post agent response as a GitHub PR/issue comment via ``gh`` CLI."""extra = delivery.get("deliver_extra", {})repo = extra.get("repo", "")pr_number = extra.get("pr_number", "")-if not repo or not pr_number:- logger.error(- "[webhook] github_comment delivery missing repo or pr_number"- )- return SendResult(- success=False, error="Missing repo or pr_number"- )+ logger.error("[webhook] github_comment delivery missing repo or pr_number")+ return SendResult(success=False, error="Missing repo or pr_number")- # --- Input validation (prevent CLI argument injection) ---- # pr_number must be a positive integer.+ # Input validation (prevent CLI argument injection).try:pr_int = int(pr_number)if pr_int <= 0:raise ValueError("non-positive")except (ValueError, TypeError):- logger.error(- "[webhook] invalid pr_number: %r", pr_number- )- return SendResult(- success=False, error="Invalid pr_number"- )-- # repo must match owner/name (alphanumeric, hyphens, underscores, dots).+ logger.error("[webhook] invalid pr_number: %r", pr_number)+ return SendResult(success=False, error="Invalid pr_number")if not re.fullmatch(r"[A-Za-z0-9._-]+/[A-Za-z0-9._-]+", repo):logger.error("[webhook] invalid repo format: %r", repo)- return SendResult(- success=False, error="Invalid repo format"- )-+ return SendResult(success=False, error="Invalid repo format")try:- # Off-loop: `gh` does network I/O and can take its full 30s- # timeout. Running it inline froze every adapter and timer on- # the gateway event loop for the duration (Pattern A, #91912- # class). asyncio.to_thread keeps the loop serving while the- # subprocess runs; the worker thread is bounded by the- # subprocess timeout below.+ # Off-loop: `gh` does network I/O up to its 30s timeout; inline it froze+ # every adapter and timer on the gateway event loop.result = await asyncio.to_thread(subprocess.run,- [- "gh",- "pr",- "comment",- str(pr_int),- "--repo",- repo,- "--body",- content,- ],+ ["gh", "pr", "comment", str(pr_int), "--repo", repo, "--body", content],capture_output=True,text=True, encoding='utf-8', errors='replace',timeout=30,)if result.returncode == 0:- logger.info(- "[webhook] Posted comment on %s#%s", repo, pr_number- )+ logger.info("[webhook] Posted comment on %s#%s", repo, pr_number)return SendResult(success=True)- else:- logger.error(- "[webhook] gh pr comment failed: %s", result.stderr- )- return SendResult(success=False, error=result.stderr)+ logger.error("[webhook] gh pr comment failed: %s", result.stderr)+ return SendResult(success=False, error=result.stderr)except FileNotFoundError:logger.error("[webhook] 'gh' CLI not found — install GitHub CLI for ""github_comment delivery")- return SendResult(- success=False, error="gh CLI not installed"- )+ return SendResult(success=False, error="gh CLI not installed")except Exception as e:logger.error("[webhook] github_comment delivery error: %s", e)return SendResult(success=False, error=str(e))- async def _deliver_cross_platform(- self, platform_name: str, content: str, delivery: dict- ) -> SendResult:+ async def _deliver_cross_platform(self, platform_name: str, content: str, delivery: dict) -> SendResult:"""Route response to another platform (telegram, discord, etc.)."""if not self.gateway_runner:- return SendResult(- success=False,- error="No gateway runner for cross-platform delivery",- )-+ return SendResult(success=False, error="No gateway runner for cross-platform delivery")try:target_platform = Platform(platform_name)except ValueError:- return SendResult(- success=False, error=f"Unknown platform: {platform_name}"- )+ return SendResult(success=False, error=f"Unknown platform: {platform_name}")- # Default adapters first; multiplex may park Slack/etc. only on a- # secondary profile (self._profile_adapters). Fall back so webhook- # deliver:slack still works when default has slack disabled.+ # Default adapters first; multiplex may park a platform only on a secondary+ # profile (_profile_adapters), so fall back to those.adapter = self.gateway_runner.adapters.get(target_platform)if not adapter:for _prof, amap in (getattr(self.gateway_runner, "_profile_adapters", None) or {}).items():@@ -1480,12 +967,7 @@ class WebhookAdapter(BasePlatformAdapter):adapter = candbreakif not adapter:- return SendResult(- success=False,- error=f"Platform {platform_name} not connected",- )-- # Use home channel if no specific chat_id in deliver_extra+ return SendResult(success=False, error=f"Platform {platform_name} not connected")extra = delivery.get("deliver_extra", {})chat_id = extra.get("chat_id", "")if not chat_id:@@ -1493,15 +975,11 @@ class WebhookAdapter(BasePlatformAdapter):if home:chat_id = home.chat_idelse:- return SendResult(- success=False,- error=f"No chat_id or home channel for {platform_name}",- )+ return SendResult(success=False, error=f"No chat_id or home channel for {platform_name}")- # Pass thread_id from deliver_extra so Telegram forum topics work+ # thread_id from deliver_extra so Telegram forum topics work.metadata = Nonethread_id = extra.get("message_thread_id") or extra.get("thread_id")if thread_id:metadata = {"thread_id": thread_id}-return await adapter.send(chat_id, content, metadata=metadata)diff --git a/gateway/platforms/webhook_filters.py b/gateway/platforms/webhook_filters.pyindex 881effdf85a..41c3ef46549 100644--- a/gateway/platforms/webhook_filters.py+++ b/gateway/platforms/webhook_filters.py@@ -34,7 +34,6 @@ def _resolve_profile_path(path_value: Any) -> Optional[Path]:if not raw:return Nonefrom hermes_constants import get_hermes_home-hermes_home = get_hermes_home()if raw == "~/.hermes":return hermes_home@@ -51,7 +50,6 @@ def _resolve_script_path(script_value: Any) -> tuple[Optional[Path], Optional[stif not isinstance(script_value, str) or not script_value.strip():return None, "script path is empty"from hermes_constants import get_hermes_home-scripts_root = (get_hermes_home() / "scripts").resolve()raw_text = os.path.expandvars(script_value.strip())if raw_text == "~/.hermes" or raw_text.startswith("~/.hermes/"):@@ -94,32 +92,21 @@ def _load_filter_file_values(path_value: Any) -> list[Any]:class WebhookRouteProcessor:"""Evaluate declarative filters and optional script transforms."""- def __init__(- self,- *,- script_timeout_seconds: int = DEFAULT_SCRIPT_TIMEOUT_SECONDS,- ) -> None:+ def __init__(self, *, script_timeout_seconds: int = DEFAULT_SCRIPT_TIMEOUT_SECONDS) -> None:self.script_timeout_seconds = max(1, int(script_timeout_seconds))- def resolve_filter_field(- self,- field: Any,- payload: dict,- event_type: str,- headers: Any,- ) -> Any:+ def resolve_filter_field(self, field: Any, payload: dict, event_type: str, headers: Any) -> Any:"""Resolve a dotted filter field against payload/event/headers context."""if not isinstance(field, str) or not field.strip():return _MISSINGparts = [part for part in field.strip().split(".") if part]if not parts:return _MISSING- header_dict = dict(headers or {})context = {"payload": payload.get("payload", payload),"event": event_type,"event_type": event_type,- "headers": header_dict,+ "headers": dict(headers or {}),}if parts[0] in context:value: Any = context[parts[0]]@@ -138,37 +125,24 @@ class WebhookRouteProcessor:return _MISSINGreturn value- def filter_matches(- self,- spec: Any,- payload: dict,- event_type: str,- headers: Any,- ) -> bool:+ def filter_matches(self, spec: Any, payload: dict, event_type: str, headers: Any) -> bool:"""Evaluate one declarative webhook filter spec."""if not isinstance(spec, dict):logger.warning("[webhook] Ignoring invalid filter spec: %r", spec)return False+ def _sub(item) -> bool:+ return self.filter_matches(item, payload, event_type, headers)+if "all" in spec:items = spec.get("all")- return isinstance(items, list) and all(- self.filter_matches(item, payload, event_type, headers)- for item in items- )+ return isinstance(items, list) and all(_sub(item) for item in items)if "any" in spec:items = spec.get("any")- return isinstance(items, list) and any(- self.filter_matches(item, payload, event_type, headers)- for item in items- )+ return isinstance(items, list) and any(_sub(item) for item in items)if "not" in spec:- return not self.filter_matches(spec.get("not"), payload, event_type, headers)-- value = self.resolve_filter_field(- spec.get("field"), payload, event_type, headers- )-+ return not _sub(spec.get("not"))+ value = self.resolve_filter_field(spec.get("field"), payload, event_type, headers)if "exists" in spec:exists = value is not _MISSINGreturn exists is bool(spec.get("exists"))@@ -194,24 +168,14 @@ class WebhookRouteProcessor:if value is _MISSING:return Falsetry:- return (- re.search(str(spec.get("regex")), _stringify_filter_value(value))- is not None- )+ return re.search(str(spec.get("regex")), _stringify_filter_value(value)) is not Noneexcept re.error as exc:logger.warning("[webhook] Invalid webhook filter regex: %s", exc)return False-logger.warning("[webhook] Filter spec has no supported operator: %r", spec)return False- def route_filters_match(- self,- route_config: dict,- payload: dict,- event_type: str,- headers: Any,- ) -> bool:+ def route_filters_match(self, route_config: dict, payload: dict, event_type: str, headers: Any) -> bool:filters = route_config.get("filters") or []if not filters:return True@@ -220,10 +184,7 @@ class WebhookRouteProcessor:if not isinstance(filters, list):logger.warning("[webhook] filters must be a list or object")return False- return all(- self.filter_matches(spec, payload, event_type, headers)- for spec in filters- )+ return all(self.filter_matches(spec, payload, event_type, headers) for spec in filters)def run_route_script(self, script_value: Any, payload: dict) -> tuple[bool, Optional[dict]]:"""Run a route script and return (should_continue, transformed_payload)."""@@ -231,22 +192,17 @@ class WebhookRouteProcessor:if error or path is None:logger.warning("[webhook] script ignored webhook: %s", error)return False, None-suffix = path.suffix.lower()if suffix in {".sh", ".bash"}:- bash = shutil.which("bash") or (- "/bin/bash" if os.path.isfile("/bin/bash") else None- )+ bash = shutil.which("bash") or ("/bin/bash" if os.path.isfile("/bin/bash") else None)if bash is None:logger.warning("[webhook] script ignored webhook: bash not found")return False, Noneargv = [bash, str(path)]else:argv = [sys.executable, str(path)]-try:from tools.environments.local import build_subprocess_env-popen_kwargs = {"creationflags": 0x08000000} if sys.platform == "win32" else {}result = subprocess.run(argv,@@ -264,12 +220,10 @@ class WebhookRouteProcessor:except Exception as exc:logger.warning("[webhook] script execution failed: %s", exc)return False, None-stdout = (result.stdout or "").strip()stderr = (result.stderr or "").strip()try:from agent.redact import redact_sensitive_text-stdout = redact_sensitive_text(stdout)stderr = redact_sensitive_text(stderr)except Exception as exc:@@ -279,14 +233,11 @@ class WebhookRouteProcessor:if result.returncode != 0:logger.info("[webhook] script ignored webhook path=%s code=%s stderr=%s",- path.name,- result.returncode,- stderr[:200],+ path.name, result.returncode, stderr[:200],)return False, Noneif not stdout or stdout == "[SILENT]":return False, None-try:transformed = json.loads(stdout)except json.JSONDecodeError:@@ -294,9 +245,6 @@ class WebhookRouteProcessor:if not isinstance(transformed, dict):logger.warning("[webhook] script stdout must be a JSON object or text")return False, None- if (- transformed.get("[SILENT]") is True- or transformed.get("__hermes_ignore__") is True- ):+ if transformed.get("[SILENT]") is True or transformed.get("__hermes_ignore__") is True:return False, Nonereturn True, transformeddiff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex d8cdd192b45..b056dfe4ca2 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -1,34 +1,15 @@"""WhatsApp Cloud API adapter — official Meta WhatsApp Business Platform.-This adapter is a *complement* to ``whatsapp.py`` (the Baileys bridge), not-a replacement. The two are independent:--- ``whatsapp.py`` — unofficial Baileys bridge, personal accounts, no- public URL needed, account-ban risk.-- ``whatsapp_cloud.py`` (this file) — official Meta Cloud API, Business- account required, public webhook URL required,- token-based auth.--Both share gating / mention / formatting behavior via ``WhatsAppBehaviorMixin``.--Phase scope (this file evolves across phases):-- Phase 2 — outbound text via Graph API + webhook server with verify-token- handshake.-- Phase 3 — X-Hub-Signature-256 HMAC verification (raw body, constant-time)- + wamid replay protection + dispatch via handle_message. Phase 3- adapter is end-to-end usable for text DMs.-- Phase 4 — media upload + send (image/video/audio/document), inbound- media download via the Graph media endpoint, voice-note opus- conversion via ffmpeg with graceful MP3 fallback when ffmpeg- isn't on PATH. Document text injection for readable types.-- Phase 5 — 24-hour conversation window + template fallback.+Complement to the Baileys bridge plugin (``plugins/platforms/whatsapp``): official+Cloud API, Business account + public webhook URL required, token auth. Both share+gating / mention / formatting behavior via ``WhatsAppBehaviorMixin``.Required env vars to enable the adapter:- WHATSAPP_CLOUD_PHONE_NUMBER_ID (the Graph URL path component)- WHATSAPP_CLOUD_ACCESS_TOKEN (System User permanent token)-Optional / Phase-3+:+Optional:- WHATSAPP_CLOUD_APP_ID- WHATSAPP_CLOUD_APP_SECRET (HMAC key for X-Hub-Signature-256)- WHATSAPP_CLOUD_WABA_ID (analytics / future use)@@ -44,6 +25,7 @@ from __future__ import annotationsimport asyncioimport hashlibimport hmac+import jsonimport loggingimport mimetypesimport os@@ -71,12 +53,7 @@ except ImportError:httpx = None # type: ignore[assignment]from gateway.config import Platform, PlatformConfig-from gateway.platforms.base import (- BasePlatformAdapter,- MessageEvent,- MessageType,- SendResult,-)+from gateway.platforms.base import BasePlatformAdapter, MessageEvent, MessageType, SendResultfrom gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin, _get_wsecretfrom gateway.platforms.media_cache import ext_for_mimefrom gateway import rich_sent_store@@ -86,35 +63,28 @@ logger = logging.getLogger(__name__)DEFAULT_API_VERSION = "v20.0"-# ``None`` → aiohttp/asyncio ``create_server`` binds one listening socket per-# address family (IPv4 + IPv6). The old "0.0.0.0" default bound IPv4 ONLY and-# was unreachable over IPv6-only private networks (e.g. Fly.io 6PN) — same-# bug as the LINE adapter (NS-603) and gateway/platforms/webhook.py-# (d542894ad). Pin a host via WHATSAPP_CLOUD_WEBHOOK_HOST or extra.webhook_host.+# ``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).DEFAULT_WEBHOOK_HOST = NoneDEFAULT_WEBHOOK_PORT = 8090DEFAULT_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. We don't need to remember-# every wamid for the full retry window — the practical risk is duplicate-# delivery within minutes, not days. 5000 entries with FIFO eviction is-# plenty for normal traffic and bounds memory.+# 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. Generous for any realistic number of in-flight prompts / chats.+# Cap for the interactive-button state dicts and the per-chat last-wamid cache.INTERACTIVE_STATE_CACHE_SIZE = 1000-# Per-type size caps documented by Meta for the Cloud API /media endpoint.-# These are the hard limits; we refuse uploads above them with a clean-# error instead of round-tripping to Graph just to be rejected.+# 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_MEDIA_SIZE_LIMITS = {- "image": 5 * 1024 * 1024, # 5 MB (JPEG, PNG)- "video": 16 * 1024 * 1024, # 16 MB- "audio": 16 * 1024 * 1024, # 16 MB (MP3, AAC, AMR, OGG opus)- "document": 100 * 1024 * 1024, # 100 MB- "sticker": 100 * 1024, # 100 KB animated, 500 KB static+ "image": 5 * 1024 * 1024,+ "video": 16 * 1024 * 1024,+ "audio": 16 * 1024 * 1024,+ "document": 100 * 1024 * 1024,+ "sticker": 100 * 1024,}# Default mime types when we can't guess from the path's extension.@@ -126,29 +96,42 @@ _DEFAULT_MIME = {"sticker": "image/webp",}-# ffmpeg location at import time. ``shutil.which`` honours PATHEXT on-# Windows so a user's ``ffmpeg.exe`` is picked up. None means MP3 voice-# falls back to "audio file attachment" rendering in WhatsApp.+# ``shutil.which`` honours PATHEXT on Windows. None → MP3 voice falls back to an+# "audio file attachment" rendering in WhatsApp._FFMPEG_PATH = shutil.which("ffmpeg")-# Python's mimetypes module returns RFC-correct but real-world-uncommon-# extensions for some types (audio/ogg → .oga since RFC 5334; audio/mp4-# → .mp4 instead of the de-facto .m4a for voice notes). Our downstream-# STT pipeline whitelists the common-in-the-wild extensions, so override-# the few Meta sends that don't match those defaults.+# 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._WHATSAPP_MIME_EXTENSION_OVERRIDES: Dict[str, str] = {- # WhatsApp voice notes — opus codec inside an Ogg container."audio/ogg": ".ogg","audio/x-opus+ogg": ".ogg","audio/opus": ".ogg",- # iOS voice memos — AAC inside an MP4 container; STT tools expect .m4a."audio/mp4": ".m4a","audio/x-m4a": ".m4a",- # Image — mimetypes occasionally returns .jpe (legacy IANA) instead- # of .jpg, which trips up tools that switch on extension."image/jpeg": ".jpg",}+_INBOUND_MEDIA_KINDS = {"image", "video", "audio", "voice", "document", "sticker"}+_TEXT_INJECT_EXTS = {+ ".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml",+ ".log", ".py", ".js", ".ts", ".html", ".css",+}+_MAX_TEXT_INJECT_BYTES = 100 * 1024 # matches Telegram/Discord/Slack+_MESSAGE_TYPE_BY_KIND = {+ "text": MessageType.TEXT,+ "image": MessageType.PHOTO,+ "video": MessageType.VIDEO,+ "audio": MessageType.VOICE,+ "voice": MessageType.VOICE,+ "document": MessageType.DOCUMENT,+ "sticker": MessageType.PHOTO,+ "button": MessageType.TEXT,+ "interactive": MessageType.TEXT,+ "location": MessageType.TEXT,+ "contacts": MessageType.TEXT,+}+async def _read_limited_request_body(request: Any, max_bytes: int) -> bytes:"""Read at most ``max_bytes`` from an aiohttp request body."""@@ -162,132 +145,63 @@ async def _read_limited_request_body(request: Any, max_bytes: int) -> bytes:def _ext_for_mime(mime: str) -> Optional[str]:- """Resolve a mime type to the file extension we want on disk.-- Thin wrapper over the shared dispatch in- ``gateway.platforms.media_cache``. Consults the WhatsApp override map- first so types like ``audio/ogg`` produce the extension downstream- tools actually accept (``.ogg``, not the technically-correct-but-broken- ``.oga``). Falls back to Python's ``mimetypes.guess_extension`` for- anything we haven't pinned — the shared default table is skipped so- behavior stays byte-identical to the historical implementation.- """+ """Mime → on-disk extension: WhatsApp overrides → mimetypes → None (never the shared default table)."""if not mime:return Nonereturn ext_for_mime(- mime,- # preserves historical whatsapp_cloud mapping: overrides →- # mimetypes → None, never the shared default table.- overrides=_WHATSAPP_MIME_EXTENSION_OVERRIDES,- use_defaults=False,- use_mimetypes=True,- fallback=None,+ mime, overrides=_WHATSAPP_MIME_EXTENSION_OVERRIDES,+ use_defaults=False, use_mimetypes=True, fallback=None,)-# Inbound media cache lives under the user's hermes dir so it survives-# restarts and gateway reloads — same convention the Baileys bridge uses.+# 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"))def check_whatsapp_cloud_requirements() -> bool:- """Return whether transport dependencies are available.-- aiohttp is needed for the webhook server (inbound). httpx is needed- for Graph API calls (outbound). Both ship with hermes-agent's default- dependency set, so this should always be True in normal installs.- """+ """aiohttp (webhook server) + httpx (Graph API) — both default deps."""return AIOHTTP_AVAILABLE and HTTPX_AVAILABLEclass WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):- """WhatsApp Business Cloud API adapter.-- Outbound: HTTPS POST to ``graph.facebook.com/<api_version>/<phone_id>/messages``.- Inbound: aiohttp server accepting Meta's webhook payloads.-- The mixin must come first in the bases list so its ``format_message``- overrides ``BasePlatformAdapter.format_message`` (the base provides a- generic implementation that does not convert markdown to WhatsApp- syntax). The Baileys adapter does the same.- """+ """Outbound: Graph ``/<api_version>/<phone_id>/messages``; inbound: aiohttp webhook+ server. The mixin comes first so its ``format_message`` overrides the base one."""splits_long_messages = True # send() chunks via truncate_message()def __init__(self, config: PlatformConfig):super().__init__(config, Platform.WHATSAPP_CLOUD)extra = config.extra or {}-- # Requiredself._phone_number_id: str = str(extra.get("phone_number_id", "")).strip()self._access_token: str = str(extra.get("access_token", "")).strip()-- # Optional / used in later phasesself._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()- # Webhook server config# Falsy host (None/"") collapses to the dual-stack default._raw_webhook_host = extra.get("webhook_host", DEFAULT_WEBHOOK_HOST) or DEFAULT_WEBHOOK_HOST- self._webhook_host: Optional[str] = (- str(_raw_webhook_host) if _raw_webhook_host else None- )+ self._webhook_host: Optional[str] = str(_raw_webhook_host) if _raw_webhook_host else Noneself._webhook_port: int = int(extra.get("webhook_port", DEFAULT_WEBHOOK_PORT))- self._webhook_path: str = self._normalize_path(- extra.get("webhook_path", DEFAULT_WEBHOOK_PATH)- )- self._health_path: str = self._normalize_path(- extra.get("health_path", "/health")- )-- # Graph API+ self._webhook_path: str = self._normalize_path(extra.get("webhook_path", DEFAULT_WEBHOOK_PATH))+ self._health_path: str = self._normalize_path(extra.get("health_path", "/health"))self._api_version: str = str(extra.get("api_version", DEFAULT_API_VERSION))- # Behavior-mixin contract: these names are read by the mixin's- # gating methods. WHATSAPP_CLOUD_* env vars take precedence so the- # two adapters can run in parallel with independent policies; the- # shared WHATSAPP_* names remain as fallback for single-adapter- # setups.- import os-+ # Behavior-mixin contract attributes. WHATSAPP_CLOUD_* env vars take+ # precedence so both adapters can run in parallel with independent+ # policies; shared WHATSAPP_* names remain the fallback.self._reply_prefix: Optional[str] = extra.get("reply_prefix")- # Allowlist: honor the *documented* WHATSAPP_CLOUD_ALLOWED_USERS (the- # var the setup wizard writes) in addition to WHATSAPP_CLOUD_ALLOW_FROM.- # Precedence matches construction forever: explicit config (by key- # presence, including empty []), then legacy ALLOW_FROM, then- # ALLOWED_USERS. Track the winning source so live DM checks do not let- # a lower-precedence env broaden access.- if "allow_from" in extra:- self._dm_allowlist_source = "config"- allow_raw = extra.get("allow_from")- elif "allowFrom" in extra:- self._dm_allowlist_source = "config"- allow_raw = extra.get("allowFrom")- elif _get_wsecret("WHATSAPP_CLOUD_ALLOW_FROM"):- self._dm_allowlist_source = "WHATSAPP_CLOUD_ALLOW_FROM"- allow_raw = _get_wsecret("WHATSAPP_CLOUD_ALLOW_FROM")- elif _get_wsecret("WHATSAPP_CLOUD_ALLOWED_USERS"):- self._dm_allowlist_source = "WHATSAPP_CLOUD_ALLOWED_USERS"- allow_raw = _get_wsecret("WHATSAPP_CLOUD_ALLOWED_USERS")- else:- self._dm_allowlist_source = None- allow_raw = None- self._allow_from: set[str] = self._normalize_allow_ids(- self._coerce_allow_list(allow_raw)+ # Config first, then legacy ALLOW_FROM, then the documented ALLOWED_USERS.+ allow_raw = self._select_dm_allowlist(+ extra, ("WHATSAPP_CLOUD_ALLOW_FROM", "WHATSAPP_CLOUD_ALLOWED_USERS"), _get_wsecret)- # DM policy: explicit config wins; otherwise choose a safe, working- # default -- "open" if the operator opted into allow-all, else- # "allowlist" when an allowlist is configured (so it is actually- # enforced instead of silently dropping), else "open".+ self._allow_from: set[str] = self._normalize_allow_ids(self._coerce_allow_list(allow_raw))+ # DM policy default: "open" if the operator opted into allow-all, else+ # "allowlist" when one is configured (so it is enforced), else "open"._allow_all_optin = str(_get_wsecret("WHATSAPP_CLOUD_ALLOW_ALL_USERS", default="") or "").strip().lower() in {"true", "1", "yes"}- _default_dm_policy = (- "open" if _allow_all_optin- else ("allowlist" if self._allow_from else "open")- )+ _default_dm_policy = "open" if _allow_all_optin else ("allowlist" if self._allow_from else "open")self._dm_policy: str = str(extra.get("dm_policy")or _get_wsecret("WHATSAPP_CLOUD_DM_POLICY")@@ -309,46 +223,23 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):)self._mention_patterns = self._compile_mention_patterns()- # Webhook dedup state — wamid → True. OrderedDict gives O(1) FIFO- # eviction. In-memory only; Phase 5 may promote to SessionDB if we- # decide we need replay protection across gateway restarts.+ # Webhook dedup state (in-memory, FIFO-evicted).self._seen_wamids: "OrderedDict[str, bool]" = OrderedDict()self._duplicate_count: int = 0self._accepted_count: int = 0self._rejected_signature_count: int = 0-- # One-shot flags for warnings that would otherwise spam the log.self._warned_no_ffmpeg: bool = False- # Per-chat cache of the latest inbound wamid. Meta's typing- # indicator + read-receipt API requires a specific message_id- # to attach to (typically "the latest message in the- # conversation"). We refresh this on every accepted inbound- # message so ``send_typing`` always has a valid target without- # threading an extra kwarg through the gateway's base contract.- # In-memory only; on gateway restart the next inbound message- # repopulates it.+ # Latest inbound wamid per chat: Meta's typing/read-receipt API needs a+ # message_id to attach to, and the base send_typing contract has none.self._last_inbound_wamid_by_chat: "OrderedDict[str, str]" = OrderedDict()- # Interactive-button state. Each maps a short id (embedded in the- # outbound button payload) → the session/correlation key needed- # by the gateway's resolver. See ``_handle_interactive_reply`` for- # the dispatch table. Entries are popped when the user taps a- # button; ignored prompts would otherwise accumulate forever, so- # each dict is FIFO-capped via _bounded_put (oldest pending prompt- # evicted first — an evicted button tap degrades to the plain-text- # fallback path, same as after a gateway restart).- # _clarify_state: clarify_id → session_key (resolves via- # tools.clarify_gateway.resolve_gateway_clarify)- # _exec_approval_state: approval_id → session_key (resolves via- # tools.approval.resolve_gateway_approval)- # _slash_confirm_state: confirm_id → session_key (resolves via- # tools.slash_confirm.resolve)+ # Interactive-button state: short id (in the button payload) → session_key+ # for the gateway resolver. Popped on tap; FIFO-capped via _bounded_put so+ # ignored prompts don't accumulate (an evicted tap degrades to text fallback).self._clarify_state: "OrderedDict[str, str]" = OrderedDict()self._exec_approval_state: "OrderedDict[str, str]" = OrderedDict()self._slash_confirm_state: "OrderedDict[str, str]" = OrderedDict()-- # Runtimeself._runner = Noneself._http_client: Optional["httpx.AsyncClient"] = None@@ -364,6 +255,12 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):path = path[1:]return f"{GRAPH_API_BASE}/{self._api_version}/{self._phone_number_id}/{path}"+ def _auth_headers(self, *, json_body: bool = True) -> Dict[str, str]:+ headers = {"Authorization": f"Bearer {self._access_token}"}+ if json_body:+ headers["Content-Type"] = "application/json"+ return headers+@staticmethoddef _bounded_put(cache: "OrderedDict[str, str]", key: str, value: str) -> None:"""Insert into a FIFO-capped OrderedDict, evicting oldest entries."""@@ -372,25 +269,14 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):cache.popitem(last=False)def _effective_reply_prefix(self) -> str:- """Cloud API has no self-chat concept — never prepend a reply prefix.-- Override the mixin default which keys off WHATSAPP_MODE=self-chat- (a Baileys-only setting).- """+ """Cloud API has no self-chat concept (a Baileys-only setting) — no default prefix."""if self._reply_prefix is not None:return self._reply_prefix.replace("\\n", "\n")return ""@staticmethoddef _normalize_allow_ids(ids: set[str]) -> set[str]:- """Normalize allowlist entries to bare wa_id form.-- The Cloud API identifies users by bare wa_id (digits, no JID- suffix), while Baileys uses ``<digits>@s.whatsapp.net`` JIDs.- Users sharing an allowlist between both adapters (or pasting a- JID/phone number with ``+`` or separators) should still match,- so strip any ``@...`` suffix and non-digit characters.- """+ """Normalize allowlist entries to bare wa_id (digits): strip ``@...`` JID suffixes and non-digits."""normalized: set[str] = set()for entry in ids:bare = entry.split("@", 1)[0]@@ -407,25 +293,14 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return super()._is_dm_allowed(sender_id)def _open_dm_opted_in(self) -> bool:- """Also honor the documented WHATSAPP_CLOUD_ALLOW_ALL_USERS opt-in.-- The shared mixin only checks GATEWAY_ALLOW_ALL_USERS /- WHATSAPP_ALLOW_ALL_USERS; the Cloud adapter's documented open-access- opt-in is WHATSAPP_CLOUD_ALLOW_ALL_USERS, so honor it here too.- """+ """Also honor the documented WHATSAPP_CLOUD_ALLOW_ALL_USERS opt-in."""if str(_get_wsecret("WHATSAPP_CLOUD_ALLOW_ALL_USERS", default="") or "").strip().lower() in {"true", "1", "yes"}:return Truereturn super()._open_dm_opted_in()def _is_interactive_sender_authorized(self, sender_id: str) -> bool:- """Authorize inbound button/list taps before running resolvers.-- Interactive replies bypass the normal ``_build_message_event_from_cloud``- path (which calls ``_should_process_message``), so approval /- slash-confirm / clarify taps must re-check DM policy here. Uses the- strict ``_is_dm_allowed`` gate (not intake/pairing) so a stale prompt- cannot be answered after the sender is removed from the allowlist.- """+ """Interactive taps bypass ``_should_process_message``; re-check the strict DM gate+ so a stale prompt can't be answered after the sender leaves the allowlist."""principal = str(sender_id or "").strip()if not principal:return False@@ -450,36 +325,24 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):)return False- # Outbound HTTP client. Tighter keepalive matches other platform- # adapters so idle CLOSE_WAIT drains promptly (#18451).+ # 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())- self._http_client = httpx.AsyncClient(- timeout=30.0, limits=platform_httpx_limits()- )-- # Inbound webhook server.- # client_max_size backstops the bounded reader in _handle_webhook —- # aiohttp enforces the cap on request.read()/post() paths too- # (#58536/#58902/#59180 pattern).+ # client_max_size backstops the bounded reader in _handle_webhook.app = web.Application(client_max_size=WEBHOOK_MAX_BODY_BYTES)app.router.add_get(self._health_path, self._handle_health)app.router.add_get(self._webhook_path, self._handle_verify)app.router.add_post(self._webhook_path, self._handle_webhook)-self._runner = web.AppRunner(app)await self._runner.setup()site = web.TCPSite(self._runner, self._webhook_host, self._webhook_port)await site.start()-self._mark_connected()logger.info("[whatsapp_cloud] Listening on %s:%d%s (Graph %s, phone_id=%s)",- self._webhook_host,- self._webhook_port,- self._webhook_path,- self._api_version,- self._phone_number_id,+ self._webhook_host, self._webhook_port, self._webhook_path,+ self._api_version, self._phone_number_id,)if not self._verify_token:logger.warning(@@ -492,7 +355,6 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):"incoming webhook POSTs will be refused with 503. Set ""the app secret to enable inbound message delivery.")- # Plugin-registered native handlers (ctx.register_platform_handler).self._wire_plugin_handlers(None)return True@@ -512,32 +374,46 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._mark_disconnected()# ------------------------------------------------------------------ outbound+ @staticmethod+ def _response_error(resp: Any) -> str:+ """Map a non-200 Graph response to an actionable error string."""+ try:+ body = resp.json()+ except Exception:+ body = {"raw": resp.text[:500]}+ return WhatsAppCloudAdapter._format_graph_error(body, resp.status_code)++ async def _post_messages(+ self, payload: Dict[str, Any], *, fail_log: str, reject_log: str, reject_args: tuple = (),+ ) -> tuple[list, Optional[str]]:+ """POST one /messages payload. Returns ``(response messages[], None)`` or ``([], error)``."""+ try:+ resp = await self._http_client.post(+ self._graph_url("messages"), headers=self._auth_headers(), json=payload+ )+ except Exception as exc:+ logger.exception(fail_log)+ return [], str(exc) or type(exc).__name__+ if resp.status_code != 200:+ error_msg = self._response_error(resp)+ logger.warning(reject_log, resp.status_code, *reject_args, error_msg)+ return [], error_msg+ try:+ return resp.json().get("messages") or [], None+ except Exception:+ return [], None+async def send(- self,- chat_id: str,- content: str,- reply_to: Optional[str] = None,+ self, chat_id: str, content: str, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- """Send a text message via Graph API.-- ``chat_id`` is the recipient's WhatsApp ID (``wa_id``) — typically- their phone number with country code, no plus sign.- """+ """Send a text message via Graph API. ``chat_id`` is the recipient's ``wa_id``."""if self._http_client is None:return SendResult(success=False, error="Not connected")if not content or not content.strip():return SendResult(success=True, message_id=None)-formatted = self.format_message(content)chunks = self.truncate_message(formatted, self._outgoing_chunk_limit())-- url = self._graph_url("messages")- headers = {- "Authorization": f"Bearer {self._access_token}",- "Content-Type": "application/json",- }-last_message_id: Optional[str] = Nonefor idx, chunk in enumerate(chunks):payload: Dict[str, Any] = {@@ -550,83 +426,35 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if reply_to and idx == 0:# Quote the user's message on the first chunk only.payload["context"] = {"message_id": reply_to}- try:- resp = await self._http_client.post(url, headers=headers, json=payload)- except Exception as exc:- logger.exception("[whatsapp_cloud] send failed")- return SendResult(success=False, error=str(exc) or type(exc).__name__)-- if resp.status_code != 200:- # Meta returns structured errors in the body — surface them- # to the caller so log lines have actionable context.- try:- body = resp.json()- except Exception:- body = {"raw": resp.text[:500]}- error_msg = self._format_graph_error(body, resp.status_code)- logger.warning(- "[whatsapp_cloud] send rejected (status=%d): %s",- resp.status_code,- error_msg,- )- return SendResult(success=False, error=error_msg)+ ids, err = await self._post_messages(+ payload,+ fail_log="[whatsapp_cloud] send failed",+ reject_log="[whatsapp_cloud] send rejected (status=%d): %s",+ )+ if err is not None:+ return SendResult(success=False, error=err)+ if ids:+ last_message_id = ids[0].get("id")- try:- data = resp.json()- ids = data.get("messages") or []- if ids:- last_message_id = ids[0].get("id")- except Exception:- pass-- # Remember (chat_id, wamid) -> text so that when the user replies to- # one of our messages, _build_message_event_from_cloud can resolve the- # quoted text. Meta's inbound webhook ``context`` object carries only- # the quoted message's id, never its text, so without this index the- # agent would never learn what the user was replying to. Best-effort;- # rich_sent_store swallows all errors.+ # 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:rich_sent_store.record(chat_id, last_message_id, formatted)-return SendResult(success=True, message_id=last_message_id)# ------------------------------------------------------------------ typing indicator + read receipts- #- # Meta couples these into a single API call: a POST to /messages- # with ``status: "read"`` marks the message read (blue double- # checkmarks), and the optional ``typing_indicator`` field- # additionally shows the user a "typing..." pip in their chat UI.- # The indicator auto-dismisses when we respond OR after 25 seconds,- # whichever comes first — so this matches "I see your message and- # I'm working on a reply" UX exactly.- #- # The API requires a specific message_id to attach to. We cache the- # latest inbound wamid per chat in _last_inbound_wamid_by_chat- # (refreshed in _build_message_event_from_cloud) so this method can- # look it up without needing the gateway base contract to plumb- # event.message_id into send_typing's signature.-async def send_typing(self, chat_id: str, metadata=None) -> None:- """Mark the latest inbound message as read AND show a typing- indicator in the user's chat UI.+ """Mark the latest inbound message read AND show a typing indicator.- Best-effort: any error (no inbound wamid yet, network failure,- stale token, message older than 30 days) is swallowed silently- so the agent's main reply path isn't blocked by UX polish.+ Meta couples both into one POST (``status: "read"`` + ``typing_indicator``);+ the indicator auto-dismisses on reply or after 25s. Best-effort: every error+ is swallowed so the main reply path is never blocked."""if self._http_client is None:returnwamid = self._last_inbound_wamid_by_chat.get(chat_id)if not wamid:- # No inbound message yet for this chat (or cache cleared on- # restart) — skip. The next inbound message will repopulate.- return-- url = self._graph_url("messages")- headers = {- "Authorization": f"Bearer {self._access_token}",- "Content-Type": "application/json",- }+ return # no inbound yet for this chat (or cache cleared on restart)payload = {"messaging_product": "whatsapp","status": "read",@@ -634,19 +462,16 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):"typing_indicator": {"type": "text"},}try:- resp = await self._http_client.post(url, headers=headers, json=payload)+ resp = await self._http_client.post(+ self._graph_url("messages"), headers=self._auth_headers(), json=payload+ )except Exception:- # Network / connection error — silent fail. Typing UX must- # never block message dispatch.return- # Best-effort: surface 4xx for ops visibility but don't raise.- # Code 131009 = "Parameter value is not valid" (typically wamid- # > 30 days old) — common after a long-quiet conversation, log- # at info not warning.+ # Code 131009 = "Parameter value is not valid" (typically wamid > 30 days+ # old) — common after a long-quiet conversation, so log at info.if resp.status_code != 200:try:- body = resp.json()- code = ((body or {}).get("error") or {}).get("code")+ code = ((resp.json() or {}).get("error") or {}).get("code")except Exception:code = Noneif code == 131009:@@ -662,42 +487,17 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# ------------------------------------------------------------------ interactive messages#- # WhatsApp Cloud supports two interactive primitives we use here:- # * ``interactive.type=button`` — up to 3 quick-reply buttons. Each- # button has an ``id`` (≤256 chars, returned verbatim on tap) and- # a ``title`` (≤20 chars, the label shown). Used for clarify with- # ≤3 choices, exec_approval, and slash_confirm.- # * ``interactive.type=list`` — a single "Tap to choose" button- # that opens a sheet with up to 10 rows. Used for clarify with- # >3 choices and the model picker.- #- # Unlike utility templates these are FREE-FORM and need no Meta-side- # approval. They only work *inside* the 24-hour conversation window —- # which is fine because all five senders below fire in direct response- # to a user message (clarify mid-conversation, approval mid-tool-call,- # etc.) so we're always inside the window when they're invoked.+ # ``interactive.type=button``: ≤3 quick-reply buttons (id ≤256 chars, title ≤20).+ # ``interactive.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 direct response to a user message.async def _post_interactive(- self,- chat_id: str,- interactive_body: Dict[str, Any],- reply_to: Optional[str] = None,+ self, chat_id: str, interactive_body: Dict[str, Any], reply_to: Optional[str] = None,) -> SendResult:- """Low-level POST for an ``interactive`` message payload.-- ``interactive_body`` is the inner ``interactive: {...}`` dict —- the caller supplies ``type``, ``body``, and ``action``. This- wrapper handles auth, error mapping, and message_id extraction so- each send_* method stays focused on its own button shape.- """+ """POST an ``interactive`` message; caller supplies ``type``/``body``/``action``."""if self._http_client is None:return SendResult(success=False, error="Not connected")-- url = self._graph_url("messages")- headers = {- "Authorization": f"Bearer {self._access_token}",- "Content-Type": "application/json",- }payload: Dict[str, Any] = {"messaging_product": "whatsapp","recipient_type": "individual",@@ -707,45 +507,21 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):}if reply_to:payload["context"] = {"message_id": reply_to}-- try:- resp = await self._http_client.post(url, headers=headers, json=payload)- except Exception as exc:- logger.exception("[whatsapp_cloud] interactive send failed")- return SendResult(success=False, error=str(exc) or type(exc).__name__)-- if resp.status_code != 200:- try:- body = resp.json()- except Exception:- body = {"raw": resp.text[:500]}- error_msg = self._format_graph_error(body, resp.status_code)- logger.warning(- "[whatsapp_cloud] interactive rejected (status=%d): %s",- resp.status_code, error_msg,- )- return SendResult(success=False, error=error_msg)-- last_message_id: Optional[str] = None- try:- data = resp.json()- ids = data.get("messages") or []- if ids:- last_message_id = ids[0].get("id")- except Exception:- pass- return SendResult(success=True, message_id=last_message_id)+ ids, err = await self._post_messages(+ payload,+ fail_log="[whatsapp_cloud] interactive send failed",+ reject_log="[whatsapp_cloud] interactive rejected (status=%d): %s",+ )+ if err is not None:+ return SendResult(success=False, error=err)+ return SendResult(success=True, message_id=ids[0].get("id") if ids else None)@staticmethoddef _truncate_button_label(text: str, limit: int = 20) -> str:- """WhatsApp caps quick-reply button titles at 20 chars and list-row- titles at 24. Truncate with an ellipsis so we surface as much of- the choice as fits."""+ """Button titles cap at 20 chars, list-row titles at 24; the ellipsis counts."""text = str(text or "").strip()if len(text) <= limit:return text- # Reserve 1 char for the ellipsis. WhatsApp counts the ellipsis- # toward the limit.return text[: max(1, limit - 1)] + "…"@staticmethod@@ -756,75 +532,50 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return textreturn text[: limit - 3] + "..."+ @staticmethod+ def _reply_buttons(*buttons: tuple[str, str]) -> list[Dict[str, Any]]:+ return [{"type": "reply", "reply": {"id": bid, "title": title}} for bid, title in 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,+ self, chat_id: str, question: str, choices: Optional[list], clarify_id: str,+ session_key: str, metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- """Render a clarify prompt as native WhatsApp interactive buttons.-- - 1–3 choices → ``interactive.type=button`` (inline pill buttons).- - 4+ choices → ``interactive.type=list`` (tap-to-open sheet with- up to 10 rows). Telegram's "Other (type answer)" escape hatch- is appended as the final row, picking it flips the entry into- text-capture mode handled by the gateway's text intercept.- - 0 choices (open-ended) → plain text question; the next message- in the session is captured by the gateway and resolves clarify.-- The button ``id`` field carries ``cl:<clarify_id>:<idx>`` (or- ``:other``); inbound webhook parsing dispatches on the prefix.+ """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:<clarify_id>:<idx|other>``; inbound dispatches on it."""if self._http_client is None:return SendResult(success=False, error="Not connected")-question = (question or "").strip()reply_to = (metadata or {}).get("reply_to_message_id") if metadata else None-- # Open-ended → just send the question, gateway captures next msg.if not choices:return await self.send(chat_id, f"❓ {question}", reply_to=reply_to)- # Mirror Telegram: render full choice text in body so long- # options aren't truncated to the 20-char button label cap.- # Truncate choices to MAX_CHOICES (4) — the tool layer enforces- # this already, but be defensive.+ # Full choice text goes in the body so long options aren't lost to the+ # 20-char label cap; labels are just the option number.choices_list = [str(c).strip() for c in choices[:10] if str(c).strip()]- option_lines = "\n".join(- f"{i + 1}. {c}" for i, c in enumerate(choices_list)- )+ option_lines = "\n".join(f"{i + 1}. {c}" for i, c in enumerate(choices_list))body_text = self._truncate_body(f"❓ {question}\n\n{option_lines}")-if len(choices_list) <= 3:- buttons = [- {- "type": "reply",- "reply": {- "id": f"cl:{clarify_id}:{idx}",- "title": self._truncate_button_label(str(idx + 1)),- },- }- for idx in range(len(choices_list))- ]interactive: Dict[str, Any] = {"type": "button","body": {"text": body_text},- "action": {"buttons": buttons},+ "action": {"buttons": self._reply_buttons(*(+ (f"cl:{clarify_id}:{idx}", self._truncate_button_label(str(idx + 1)))+ for idx in range(len(choices_list))+ ))},}else:- # List mode: rows must each have id + title (≤24 chars).- # Description (≤72 chars) renders below the title — we put- # the truncated choice text there for skimmability.- rows = []- for idx, choice_text in enumerate(choices_list):- rows.append({+ # List rows: id + title (≤24) + description (≤72) with the choice text.+ rows = [+ {"id": f"cl:{clarify_id}:{idx}","title": self._truncate_button_label(f"{idx + 1}", limit=24),"description": self._truncate_button_label(choice_text, limit=72),- })+ }+ for idx, choice_text in enumerate(choices_list)+ ]rows.append({"id": f"cl:{clarify_id}:other","title": "✏️ Other",@@ -833,41 +584,23 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):interactive = {"type": "list","body": {"text": body_text},- "action": {- "button": "Choose",- "sections": [{"title": "Options", "rows": rows}],- },+ "action": {"button": "Choose", "sections": [{"title": "Options", "rows": rows}]},}-result = await self._post_interactive(chat_id, interactive, reply_to=reply_to)if result.success:self._bounded_put(self._clarify_state, clarify_id, session_key)return resultasync 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,+ 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:- """Render a dangerous-command approval prompt with native buttons.-- Two quick-reply buttons (Approve / Deny). Tapping resolves the- waiting agent via ``tools.approval.resolve_gateway_approval`` —- same mechanism as the text ``/approve`` flow. The agent thread- is blocked until the user taps or types a response.- """+ """Approve / Deny buttons; a tap resolves via ``tools.approval.resolve_gateway_approval``."""if self._http_client is None:return SendResult(success=False, error="Not connected")-del allow_permanent, allow_session # This adapter already offers one-shot Approve / Deny only.- # WhatsApp body caps at 1024 chars; reserve room for the- # framing prose around the command.+ # Body caps at 1024; reserve room for the framing prose.cmd = command or ""cmd_preview = cmd if len(cmd) <= 800 else cmd[:800] + "..."body_text = self._truncate_body(@@ -876,75 +609,39 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):f"Reason: {description}"+ ("\n\nSmart DENY: owner override applies to this one operation only." if smart_denied else ""))-approval_id = uuid.uuid4().hex[:12]reply_to = (metadata or {}).get("reply_to_message_id") if metadata else None-interactive = {"type": "button","body": {"text": body_text},- "action": {- "buttons": [- {- "type": "reply",- "reply": {"id": f"appr:{approval_id}:approve", "title": "✅ Approve"},- },- {- "type": "reply",- "reply": {"id": f"appr:{approval_id}:deny", "title": "❌ Deny"},- },- ],- },+ "action": {"buttons": self._reply_buttons(+ (f"appr:{approval_id}:approve", "✅ Approve"),+ (f"appr:{approval_id}:deny", "❌ Deny"),+ )},}-result = await self._post_interactive(chat_id, interactive, reply_to=reply_to)if result.success:self._bounded_put(self._exec_approval_state, approval_id, session_key)return resultasync def send_slash_confirm(- self,- chat_id: str,- title: str,- message: str,- session_key: str,- confirm_id: str,+ self, chat_id: str, title: str, message: str, session_key: str, confirm_id: str,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- """Render a 3-button slash-command confirmation prompt.-- Mirrors Telegram's send_slash_confirm: Approve Once / Always /- Cancel. The confirm_id is supplied by the caller (slash command- handler) — we just store the session_key mapping for the inbound- resolver to look up.- """+ """Approve Once / Always / Cancel buttons; ``confirm_id`` is caller-supplied."""if self._http_client is None:return SendResult(success=False, error="Not connected")-body_text = self._truncate_body(f"*{title}*\n\n{message}")reply_to = (metadata or {}).get("reply_to_message_id") if metadata else None-interactive = {"type": "button","body": {"text": body_text},- "action": {- "buttons": [- {- "type": "reply",- "reply": {"id": f"sc:once:{confirm_id}", "title": "✅ Approve Once"},- },- {- "type": "reply",- "reply": {"id": f"sc:always:{confirm_id}", "title": "🔒 Always"},- },- {- "type": "reply",- "reply": {"id": f"sc:cancel:{confirm_id}", "title": "❌ Cancel"},- },- ],- },+ "action": {"buttons": self._reply_buttons(+ (f"sc:once:{confirm_id}", "✅ Approve Once"),+ (f"sc:always:{confirm_id}", "🔒 Always"),+ (f"sc:cancel:{confirm_id}", "❌ Cancel"),+ )},}-result = await self._post_interactive(chat_id, interactive, reply_to=reply_to)if result.success:self._bounded_put(self._slash_confirm_state, confirm_id, session_key)@@ -952,9 +649,8 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):@staticmethoddef _format_graph_error(body: Dict[str, Any], status_code: int) -> str:+ # Graph shape: {"error": {"message", "type", "code", "fbtrace_id"}}err = (body or {}).get("error") or {}- # Graph API error shape:- # {"error": {"message": "...", "type": "...", "code": ..., "fbtrace_id": "..."}}message = err.get("message") or body.get("raw") or "unknown error"code = err.get("code")if code is not None:@@ -962,33 +658,18 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return f"HTTP {status_code}: {message}"async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:- # Cloud API doesn't expose a direct "chat info" endpoint the way- # Slack/Discord do — we just echo the wa_id. Profile name (when- # known) flows in via webhook ``contacts[].profile.name`` and is- # cached on the MessageEvent, not here.+ # No chat-info endpoint; profile name arrives via webhook contacts[].return {"name": chat_id, "type": "dm"}# ------------------------------------------------------------------ outbound mediaasync def _upload_media(- self,- file_path: str,- media_kind: str,- mime_type: Optional[str] = None,+ self, file_path: str, media_kind: str, mime_type: Optional[str] = None,) -> tuple[Optional[str], Optional[str]]:- """Upload a local file to the Graph /media endpoint.-- Returns ``(media_id, None)`` on success, ``(None, error_string)``- on failure. Two-step send: this gets the id, then ``_send_media``- references it. Used when we have a local file and no public URL.-- ``media_kind`` is one of "image", "video", "audio", "document",- "sticker" — selects size cap + default mime fallback.- """+ """Upload a local file to Graph /media. Returns ``(media_id, None)`` or ``(None, error)``."""if self._http_client is None: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"])if size > cap:@@ -996,14 +677,10 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):f"File {os.path.basename(file_path)} is {size} bytes; "f"Cloud API {media_kind} cap is {cap} bytes")-if not mime_type:mime_type, _ = mimetypes.guess_type(file_path)if not mime_type:mime_type = _DEFAULT_MIME.get(media_kind, "application/octet-stream")-- url = self._graph_url("media")- headers = {"Authorization": f"Bearer {self._access_token}"}try:with open(file_path, "rb") as fh:files = {@@ -1011,21 +688,16 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):"messaging_product": (None, "whatsapp"),"type": (None, mime_type),}- resp = await self._http_client.post(url, headers=headers, files=files)+ resp = await self._http_client.post(+ self._graph_url("media"), headers=self._auth_headers(json_body=False), files=files+ )except Exception as exc:logger.exception("[whatsapp_cloud] media upload failed")return None, str(exc)-if resp.status_code != 200:- try:- body = resp.json()- except Exception:- body = {"raw": resp.text[:500]}- return None, self._format_graph_error(body, resp.status_code)-+ return None, self._response_error(resp)try:- data = resp.json()- media_id = data.get("id")+ media_id = resp.json().get("id")except Exception:media_id = Noneif not media_id:@@ -1033,37 +705,18 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return media_id, Noneasync def _send_media(- self,- chat_id: str,- media_kind: str,- *,- media_id: Optional[str] = None,- media_link: Optional[str] = None,- caption: Optional[str] = None,- filename: Optional[str] = None,- reply_to: Optional[str] = None,+ self, chat_id: str, media_kind: str, *, media_id: Optional[str] = None,+ media_link: Optional[str] = None, caption: Optional[str] = None,+ filename: Optional[str] = None, reply_to: Optional[str] = None,) -> SendResult:- """POST a media message referencing either an uploaded media_id or- a public ``link``.+ """POST a media message referencing exactly one of an uploaded ``media_id`` or a public ``link``.- Exactly one of ``media_id`` or ``media_link`` must be set. Captions- and filenames are passed through where Meta accepts them (caption- on image/video/document; filename on document only).+ Caption is accepted on image/video/document; filename on document only."""if self._http_client is None:return SendResult(success=False, error="Not connected")if bool(media_id) == bool(media_link):- return SendResult(- success=False,- error="Exactly one of media_id or media_link must be set",- )-- url = self._graph_url("messages")- headers = {- "Authorization": f"Bearer {self._access_token}",- "Content-Type": "application/json",- }-+ return SendResult(success=False, error="Exactly one of media_id or media_link must be set")media_block: Dict[str, Any] = {}if media_id:media_block["id"] = media_id@@ -1073,7 +726,6 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):media_block["caption"] = captionif filename and media_kind == "document":media_block["filename"] = filename-payload: Dict[str, Any] = {"messaging_product": "whatsapp","recipient_type": "individual",@@ -1083,135 +735,60 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):}if reply_to:payload["context"] = {"message_id": reply_to}-- try:- resp = await self._http_client.post(url, headers=headers, json=payload)- except Exception as exc:- logger.exception("[whatsapp_cloud] media send failed")- return SendResult(success=False, error=str(exc) or type(exc).__name__)-- if resp.status_code != 200:- try:- body = resp.json()- except Exception:- body = {"raw": resp.text[:500]}- error_msg = self._format_graph_error(body, resp.status_code)- logger.warning(- "[whatsapp_cloud] media send rejected (status=%d, kind=%s): %s",- resp.status_code, media_kind, error_msg,- )- return SendResult(success=False, error=error_msg)-- try:- data = resp.json()- ids = data.get("messages") or []- wamid = ids[0].get("id") if ids else None- except Exception:- wamid = None- return SendResult(success=True, message_id=wamid)+ ids, err = await self._post_messages(+ payload,+ fail_log="[whatsapp_cloud] media send failed",+ reject_log="[whatsapp_cloud] media send rejected (status=%d, kind=%s): %s",+ reject_args=(media_kind,),+ )+ if err is not None:+ return SendResult(success=False, error=err)+ return SendResult(success=True, message_id=ids[0].get("id") if ids else None)async def _send_media_from_path_or_link(- self,- chat_id: str,- source: str,- media_kind: str,- *,- caption: Optional[str] = None,- filename: Optional[str] = None,- reply_to: Optional[str] = None,+ self, chat_id: str, source: str, media_kind: str, *, caption: Optional[str] = None,+ filename: Optional[str] = None, reply_to: Optional[str] = None,mime_type: Optional[str] = None,) -> SendResult:- """Smart dispatcher: HTTPS URL → ``link`` send; local path → upload + ``id`` send.-- Prefers the ``link`` path when possible (one fewer Graph round- trip). Meta fetches from the URL themselves. Used as the common- backend for ``send_image`` / ``send_video`` / etc. — keeps the- public method bodies thin.- """+ """HTTPS URL → ``link`` send (one fewer round trip); local path → upload + ``id`` send."""if source.startswith(("http://", "https://")):return await self._send_media(- chat_id,- media_kind,- media_link=source,- caption=caption,- filename=filename,- reply_to=reply_to,+ chat_id, media_kind, media_link=source, caption=caption, filename=filename, reply_to=reply_to)media_id, err = await self._upload_media(source, media_kind, mime_type)if err:return SendResult(success=False, error=err)return await self._send_media(- chat_id,- media_kind,- media_id=media_id,- caption=caption,- filename=filename,- reply_to=reply_to,+ chat_id, media_kind, media_id=media_id, caption=caption, filename=filename, reply_to=reply_to)+ # ``**kwargs`` absorbs base-class args (e.g. ``metadata``) the Cloud API has no use for.async def send_image(- self,- chat_id: str,- image_url: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, image_url: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send an image by public URL. Prefers Meta's ``link`` mode.-- ``**kwargs`` absorbs platform-agnostic args the base class passes- (e.g. ``metadata``) that the Cloud API doesn't have a use for.- Mirrors send_image_file / send_video / send_voice / send_document.- """- return await self._send_media_from_path_or_link(- chat_id, image_url, "image", caption=caption, reply_to=reply_to- )+ return await self._send_media_from_path_or_link(chat_id, image_url, "image", caption=caption, reply_to=reply_to)async def send_image_file(- self,- chat_id: str,- image_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, image_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send a local image file via two-step upload + id."""- return await self._send_media_from_path_or_link(- chat_id, image_path, "image", caption=caption, reply_to=reply_to- )+ return await self._send_media_from_path_or_link(chat_id, image_path, "image", caption=caption, reply_to=reply_to)async def send_video(- self,- chat_id: str,- video_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, video_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send a video. Local path → upload; HTTPS URL → link mode."""- return await self._send_media_from_path_or_link(- chat_id, video_path, "video", caption=caption, reply_to=reply_to- )+ return await self._send_media_from_path_or_link(chat_id, video_path, "video", caption=caption, reply_to=reply_to)async def send_voice(- self,- chat_id: str,- audio_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, audio_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send an audio file as a WhatsApp voice message.-- WhatsApp renders ``audio/ogg; codecs=opus`` as the green- voice-note bubble; other audio types (MP3, AAC, etc.) appear as- a generic audio attachment. Hermes TTS produces MP3, so we try- ffmpeg conversion to opus first and fall back to sending the- MP3 as-is when ffmpeg is unavailable.- """+ """Voice message: ``audio/ogg; codecs=opus`` renders as a voice bubble, so a+ local MP3 (Hermes TTS output) is converted via ffmpeg first; other audio is sent as-is."""source = audio_pathmime_type: Optional[str] = None-is_local_mp3 = (not audio_path.startswith(("http://", "https://"))and audio_path.lower().endswith(".mp3")@@ -1227,56 +804,37 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):mime_type="audio/ogg; codecs=opus",)finally:- # The .ogg is a transient conversion artifact next to- # the source MP3 — clean it up after upload so voice- # sends don't leak a file per message.+ # The .ogg is a transient artifact next to the source MP3.try:os.unlink(opus_path)except OSError:passreturn result- # Will deliver as MP3 attachment, not voice bubble.- # Warn-once is logged inside _convert_to_opus.+ # 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, source, "audio",- caption=caption, reply_to=reply_to, mime_type=mime_type,+ chat_id, source, "audio", caption=caption, reply_to=reply_to, mime_type=mime_type,)async def send_document(- self,- chat_id: str,- file_path: str,- caption: Optional[str] = None,- file_name: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, file_path: str, caption: Optional[str] = None,+ file_name: Optional[str] = None, reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send a document attachment with optional filename + caption."""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,+ caption=caption, filename=file_name or os.path.basename(file_path), reply_to=reply_to,)# ------------------------------------------------------------------ opus conversionasync def _convert_to_opus(self, mp3_path: str) -> Optional[str]:- """Convert an MP3 to ``audio/ogg; codecs=opus`` for voice bubbles.-- Returns the path to the converted file, or None if ffmpeg is- missing / conversion fails (caller falls back to sending the- original MP3 as an audio file).+ """MP3 → ``audio/ogg; codecs=opus``; None if ffmpeg is missing or fails.- ``-application voip`` tunes the opus encoder for speech.- ``-b:a 32k -vbr on`` matches the bitrate WhatsApp produces for- native voice notes (small files, good intelligibility).+ ``-application voip`` tunes for speech; ``-b:a 32k -vbr on`` matches+ WhatsApp's native voice-note bitrate."""if not _FFMPEG_PATH:self._warn_once_no_ffmpeg()return None-out_path = mp3_path.rsplit(".", 1)[0] + ".ogg"try:proc = await asyncio.create_subprocess_exec(@@ -1314,44 +872,27 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# ------------------------------------------------------------------ inbound mediaasync def _download_media_to_cache(- self,- media_id: str,- *,- ext_hint: Optional[str] = None,+ self, media_id: str, *, ext_hint: Optional[str] = None,) -> tuple[Optional[str], Optional[str]]:- """Two-step Graph media download: ``GET /<id>`` → temp URL → bytes.-- Returns ``(local_path, mime_type)`` on success. ``mime_type``- falls back to what Graph reports in the metadata response.- Returns ``(None, None)`` on any failure (logged).+ """Two-step Graph download: ``GET /<id>`` → signed temp URL (~5 min) → bytes.- The temporary URL from step 1 is signed and expires in ~5- minutes; we download immediately and never persist the URL.+ Returns ``(local_path, mime_type)`` or ``(None, None)`` on any failure (logged)."""if self._http_client is None:return None, None- # Defense in depth: media_id comes from the (signature-verified)- # webhook payload, but it's interpolated into both a Graph URL and- # a cache filename below — refuse anything that isn't a plain- # Meta-style media id so a hostile payload can't traverse paths.+ # media_id is interpolated into a Graph URL and a cache filename — refuse+ # anything that isn't a plain Meta-style id so a hostile payload can't traverse.media_id = str(media_id).strip()if not re.fullmatch(r"[A-Za-z0-9._-]+", media_id):- logger.warning(- "[whatsapp_cloud] refusing malformed media id %r", media_id[:64]- )+ logger.warning("[whatsapp_cloud] refusing malformed media id %r", media_id[:64])return None, None- headers = {"Authorization": f"Bearer {self._access_token}"}-- # Step 1 — metadata (gives us a temporary signed URL + mime)+ headers = self._auth_headers(json_body=False)try:meta_resp = await self._http_client.get(- f"{GRAPH_API_BASE}/{self._api_version}/{media_id}",- headers=headers,+ f"{GRAPH_API_BASE}/{self._api_version}/{media_id}", headers=headers)except Exception:- logger.exception(- "[whatsapp_cloud] media metadata fetch raised (id=%s)", media_id- )+ logger.exception("[whatsapp_cloud] media metadata fetch raised (id=%s)", media_id)return None, Noneif meta_resp.status_code != 200:logger.warning(@@ -1359,7 +900,6 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):media_id, meta_resp.status_code,)return None, None-try:meta = meta_resp.json()except Exception:@@ -1369,14 +909,11 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if not temp_url:return None, None- # Step 2 — bytes (auth required even though URL is signed; Meta- # documents this explicitly — the URL alone is not enough).+ # Auth is required even though the URL is signed (Meta documents this).try:blob_resp = await self._http_client.get(temp_url, headers=headers)except Exception:- logger.exception(- "[whatsapp_cloud] media bytes fetch raised (id=%s)", media_id- )+ logger.exception("[whatsapp_cloud] media bytes fetch raised (id=%s)", media_id)return None, Noneif blob_resp.status_code != 200:logger.warning(@@ -1384,30 +921,20 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):media_id, blob_resp.status_code,)return None, None-- # Decide the extension. Prefer the override map so audio/ogg- # produces .ogg (not the technically-correct-but-broken .oga- # mimetypes returns by default). Fall back to ext_hint then- # ``.bin`` for unknown types.ext = ext_hintif not ext and mime:ext = _ext_for_mime(mime)if not ext:ext = ".bin"-_INBOUND_MEDIA_CACHE.mkdir(parents=True, exist_ok=True)out_path = _INBOUND_MEDIA_CACHE / f"{media_id}{ext}"try:out_path.write_bytes(blob_resp.content)except OSError:- logger.exception(- "[whatsapp_cloud] failed to write cached media (id=%s)", media_id- )+ logger.exception("[whatsapp_cloud] failed to write cached media (id=%s)", media_id)return None, None-return str(out_path), mime or None-# ------------------------------------------------------------------ inboundasync def _handle_health(self, request: "web.Request") -> "web.Response":return web.json_response(@@ -1426,111 +953,69 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):)async def _handle_verify(self, request: "web.Request") -> "web.Response":- """Meta subscription verification handshake.-- Meta calls GET ``<webhook>?hub.mode=subscribe&hub.verify_token=...- &hub.challenge=...``. We must echo the challenge as plain text iff- ``hub.mode == "subscribe"`` AND ``hub.verify_token`` matches the- shared secret. Constant-time comparison.- """+ """Meta subscription handshake: echo ``hub.challenge`` iff mode is+ ``subscribe`` and ``hub.verify_token`` matches (constant-time)."""if not self._verify_token:- # Misconfigured server — refuse rather than silently accepting- # any verify_token, which would let an attacker subscribe.+ # Refuse rather than accept any token, which would let an attacker subscribe.return web.Response(status=503, text="verify_token not configured")-mode = request.query.get("hub.mode", "")token = request.query.get("hub.verify_token", "")challenge = request.query.get("hub.challenge", "")-if mode != "subscribe":return web.Response(status=400, text="bad mode")-- # Constant-time compare to avoid token-length / token-content leaks- # via timing. Compare as bytes: ``compare_digest`` raises TypeError on- # a str with non-ASCII characters, and the token is a raw query param.- import hmac as _hmac-- if not _hmac.compare_digest(token.encode(), self._verify_token.encode()):+ # Compare as bytes: compare_digest raises TypeError on non-ASCII str.+ if not hmac.compare_digest(token.encode(), self._verify_token.encode()):return web.Response(status=403, text="verify_token mismatch")if not challenge:return web.Response(status=400, text="missing challenge")return web.Response(text=challenge, content_type="text/plain")async def _handle_webhook(self, request: "web.Request") -> "web.Response":- """Inbound webhook POST handler.-- Lifecycle:- 1. Read raw bytes (signature is over the raw body — JSON parsing- must NOT happen first, or the bytes change).- 2. Verify ``X-Hub-Signature-256`` HMAC against ``app_secret``.- 3. Parse JSON.- 4. Walk ``entry[].changes[].value.{messages, statuses, contacts}``.- 5. Per-message: dedup by wamid, build MessageEvent, dispatch via- ``handle_message`` (which runs the mixin's gating).- 6. Always respond 200 once we've ack'd a valid request — Meta- retries on non-200 for up to 7 days, and we don't want to- multiply downstream agent work because of a transient bug- during dispatch.+ """Inbound webhook POST: raw bytes → HMAC verify → JSON → dispatch.++ Signature is over the raw body, so JSON parsing must come after+ verification. Always 200 once a valid request is ack'd — Meta retries+ non-200 for up to 7 days and would multiply downstream agent work."""- # Meta's documented max payload is 3MB. Read one byte past the limit- # so oversized chunked bodies are rejected before buffering the rest.+ # Read one byte past Meta's 3MB max so oversized chunked bodies are+ # rejected before buffering the rest.try:- raw = await _read_limited_request_body(- request,- WEBHOOK_MAX_BODY_BYTES,- )+ raw = await _read_limited_request_body(request, WEBHOOK_MAX_BODY_BYTES)except ValueError:return web.Response(status=413)except Exception:return web.Response(status=400)- # Refuse to accept anything if app_secret isn't configured. Without- # it we can't authenticate the sender, and the handler would be a- # data-injection point. Same defensive posture as the GET verify- # handshake refusing when verify_token is empty.+ # Without app_secret the sender can't be authenticated → refuse (same+ # posture as the GET handshake refusing without verify_token).if not self._app_secret:logger.error("[whatsapp_cloud] webhook POST refused: app_secret unset. ""Set WHATSAPP_CLOUD_APP_SECRET to enable inbound delivery.")return web.Response(status=503, text="app_secret not configured")-signature_header = request.headers.get("X-Hub-Signature-256", "")if not self._verify_signature(raw, signature_header):self._rejected_signature_count += 1logger.warning("[whatsapp_cloud] rejected webhook: invalid X-Hub-Signature-256 ""(header=%r, body_len=%d)",- signature_header,- len(raw),+ signature_header, len(raw),)return web.Response(status=401)-- # Parse only AFTER signature passes — bad JSON from an attacker is- # already filtered out, this just guards against Meta sending- # something malformed.- import json as _json-try:- payload = _json.loads(raw)+ payload = json.loads(raw)except Exception:logger.warning("[whatsapp_cloud] webhook body is not valid JSON")return web.Response(status=400)-if not isinstance(payload, dict):return web.Response(status=400)-await self._dispatch_payload(payload)return web.Response(status=200)# ------------------------------------------------------------------ signaturedef _verify_signature(self, raw_body: bytes, header: str) -> bool:- """Verify the X-Hub-Signature-256 HMAC.-- Meta sends ``sha256=<hex>``; we compute the same HMAC with- ``app_secret`` as the key and ``raw_body`` (UTF-8 bytes, not- re-serialized JSON) as the message. Constant-time compare.- """+ """Verify ``sha256=<hex>`` HMAC of the raw body keyed by ``app_secret`` (constant-time)."""if not self._app_secret or not header:return Falseif not header.startswith("sha256="):@@ -1538,55 +1023,31 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):expected_hex = header[len("sha256="):].strip()if not expected_hex:return False- computed = hmac.new(- self._app_secret.encode("utf-8"),- raw_body,- hashlib.sha256,- ).hexdigest()- # Compare as bytes: compare_digest raises TypeError on a str with- # non-ASCII characters, and the signature is a raw request header.- return hmac.compare_digest(- computed.lower().encode(), expected_hex.lower().encode()- )+ 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.+ return hmac.compare_digest(computed.lower().encode(), expected_hex.lower().encode())# ------------------------------------------------------------------ dispatchdef _dedup_wamid(self, wamid: str) -> bool:- """Return True if this wamid is being seen for the first time.-- Returns False (and increments duplicate counter) if the wamid is- already in the in-memory cache. Cache is FIFO-evicted at- ``WAMID_DEDUP_CACHE_SIZE``.- """+ """True if this wamid is new; False (and count a duplicate) if already seen."""if not wamid:- # No wamid means we can't dedup — let it through. Meta should- # always populate ``id``, but be defensive.- return True+ return True # can't dedup without an id — let it throughif wamid in self._seen_wamids:self._duplicate_count += 1return Falseself._seen_wamids[wamid] = True- # Trim oldest entries to stay under the cap.while len(self._seen_wamids) > WAMID_DEDUP_CACHE_SIZE:self._seen_wamids.popitem(last=False)return Trueasync def _dispatch_payload(self, payload: Dict[str, Any]) -> None:- """Walk a verified Meta webhook payload and dispatch each message.-- Payload shape (truncated):- {object, entry: [{id, changes: [{value: {messages, contacts,- statuses, metadata}, field: "messages"}]}]}+ """Walk ``entry[].changes[].value.{messages, contacts, statuses}`` and dispatch each message.- We surface ``messages`` events as MessageEvents; ``statuses``- events (sent/delivered/read/failed) are logged but not dispatched- — the agent doesn't currently consume delivery receipts and- forwarding them would create noisy synthetic events.+ ``statuses`` (sent/delivered/read/failed) are logged at debug, not+ dispatched — the agent doesn't consume delivery receipts."""if payload.get("object") != "whatsapp_business_account":- logger.debug(- "[whatsapp_cloud] ignoring non-WABA payload (object=%r)",- payload.get("object"),- )+ logger.debug("[whatsapp_cloud] ignoring non-WABA payload (object=%r)", payload.get("object"))returnfor entry in payload.get("entry") or []:if not isinstance(entry, dict):@@ -1595,17 +1056,11 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if not isinstance(change, dict):continueif change.get("field") != "messages":- # Other fields (account_alerts, template_status_update,- # etc.) are subscription-dependent and not message- # ingress. Silent skip.- continue+ continue # account_alerts, template_status_update, … — not message ingressvalue = change.get("value") or {}- contacts = value.get("contacts") or []metadata = value.get("metadata") or {}- # Build a wa_id → profile-name index for the messages we're- # about to surface.contacts_by_waid: Dict[str, str] = {}- for contact in contacts:+ for contact in value.get("contacts") or []:if not isinstance(contact, dict):continuewa_id = str(contact.get("wa_id") or "").strip()@@ -1613,31 +1068,20 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):name = str(profile.get("name") or "").strip()if wa_id:contacts_by_waid[wa_id] = name-for raw_message in value.get("messages") or []:if not isinstance(raw_message, dict):continuewamid = str(raw_message.get("id") or "").strip()if not self._dedup_wamid(wamid):- logger.debug(- "[whatsapp_cloud] duplicate wamid %s, skipping",- wamid,- )+ logger.debug("[whatsapp_cloud] duplicate wamid %s, skipping", wamid)continue+ # Neither build nor dispatch errors may bubble out: the wamid is+ # already dedup-marked, so a 500 would make Meta retry the batch+ # and every message in it would then be dropped as a duplicate.try:- event = await self._build_message_event_from_cloud(- raw_message, contacts_by_waid, metadata- )+ event = await self._build_message_event_from_cloud(raw_message, contacts_by_waid, metadata)except Exception:- # Build errors must not bubble out either: the wamid- # is already dedup-marked above, so a 500 here would- # make Meta retry the batch and every message in it- # (including this one) would be silently dropped as- # a duplicate. Log and move on to the next message.- logger.exception(- "[whatsapp_cloud] failed to build event for wamid %s",- wamid,- )+ logger.exception("[whatsapp_cloud] failed to build event for wamid %s", wamid)continueif event is None:continue@@ -1645,325 +1089,256 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):try:await self.handle_message(event)except Exception:- # Dispatch errors must not bubble out — Meta would- # retry the whole batch, multiplying the bug.- logger.exception(- "[whatsapp_cloud] handle_message raised for wamid %s",- wamid,- )-- # Log status updates at debug level — useful for diagnosing- # "did Meta accept my outbound" without flooding INFO logs.+ logger.exception("[whatsapp_cloud] handle_message raised for wamid %s", wamid)for status in value.get("statuses") or []:if isinstance(status, dict):- logger.debug(- "[whatsapp_cloud] status %s for %s",- status.get("status"),- status.get("id"),- )+ logger.debug("[whatsapp_cloud] status %s for %s", status.get("status"), status.get("id"))async def _dispatch_interactive_reply(- self,- raw_message: Dict[str, Any],- contacts_by_waid: Dict[str, str],+ self, raw_message: Dict[str, Any], contacts_by_waid: Dict[str, str],) -> bool:- """Route an inbound interactive reply to the matching resolver.-- Returns True if the tap was claimed (caller should drop the- webhook entry without dispatching a fresh conversation turn).- Returns False when the id has no recognized prefix, no live- state entry, or the resolver itself reports no waiter — in- those cases the caller falls back to standard text-event- dispatch, which treats the button title as a normal user- message. That graceful fallback covers stale-tap and- cross-process-restart scenarios.-- Dispatch table:- ``cl:<clarify_id>:<idx|other>`` → resolve_gateway_clarify- ``appr:<approval_id>:approve|deny`` → resolve_gateway_approval- ``sc:<once|always|cancel>:<confirm_id>`` → slash_confirm.resolve+ """Route an inbound button tap to its resolver (see ``_INTERACTIVE_HANDLERS``).++ True = claimed. False (unknown prefix, no live state, or no waiter) makes the+ caller fall back to text dispatch with the button title — covers stale taps."""inter = raw_message.get("interactive") or {}- # button_reply (interactive.type=button) and list_reply- # (interactive.type=list) carry id+title in different sub-objects.+ # button_reply (type=button) and list_reply (type=list) carry id+title.inner = inter.get("button_reply") or inter.get("list_reply") or {}button_id = str(inner.get("id") 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 "<unknown>",- button_id,+ sender_id or "<unknown>", button_id,)- # Claim the webhook entry so the tap is not re-dispatched as- # plain text (which could re-enter the agent loop).- return True-- # Clarify: cl:<clarify_id>:<idx|other>- if button_id.startswith("cl:"):- parts = button_id.split(":", 2)- if len(parts) != 3:- return False- _, clarify_id, choice = parts- session_key = self._clarify_state.pop(clarify_id, None)- if not session_key:- logger.info(- "[whatsapp_cloud] clarify tap with no matching state "- "(clarify_id=%s) — likely stale; falling back to text",- clarify_id,- )- 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"- )- return False- if choice == "other":- # User wants to type a free-form answer. Flip the entry- # into text-capture mode so the gateway's text-intercept- # (in _handle_message) picks up their next message and- # resolves the clarify. Without this flip,- # ``get_pending_for_session`` won't return the entry —- # the next text would fall through to the regular agent- # path, which collides with the agent thread still- # blocked in clarify and produces an "Interrupting- # current task" loop.- try:- from tools.clarify_gateway import mark_awaiting_text- flipped = mark_awaiting_text(clarify_id)- except Exception:- logger.exception(- "[whatsapp_cloud] mark_awaiting_text failed for %s",- clarify_id,- )- flipped = False- if not flipped:- # Entry vanished between the user tap and our handler- # (timeout, /new, gateway restart). Drop the stale- # state and fall through to text dispatch so the- # user's tap isn't completely ignored.- logger.info(- "[whatsapp_cloud] clarify 'Other' tap but entry "- "missing (clarify_id=%s); falling back to text",- clarify_id,- )+ return True # claim so the tap isn't re-dispatched as plain text+ parts = button_id.split(":", 2)+ reply_target = str(raw_message.get("from") or "")+ for prefix, handler in self._INTERACTIVE_HANDLERS.items():+ if button_id.startswith(prefix):+ if len(parts) != 3:return False- # Put state back since we popped it earlier — keep the- # clarify_id → session_key mapping live in case future- # taps land on the same prompt.- self._clarify_state[clarify_id] = session_key- try:- await self.send(- str(raw_message.get("from") or ""),- "✏️ Type your answer:",- )- except Exception:- logger.exception("[whatsapp_cloud] clarify other-prompt failed")- return True # claim so we don't also dispatch the tap as text- try:- idx = int(choice)- except ValueError:- logger.warning(- "[whatsapp_cloud] clarify tap had non-int choice: %r",- choice,- )- # Put state back so a follow-up text can still resolve.- self._clarify_state[clarify_id] = session_key- return False- # Use the title text as the resolved response so the agent- # sees the human-readable answer, not the index. Title is- # the numeric label ("1", "2", ...) so we look up the- # full choice from the original prompt — but we didn't- # persist that. Fall back to passing the index; the agent- # has the prompt in context and can interpret it.- response_text = str(inner.get("title") or str(idx + 1))- resolved = resolve_gateway_clarify(clarify_id, response_text)- if not resolved:- # Resolver couldn't find a waiter (e.g. agent already- # timed out). Fall through to text dispatch.- logger.info(- "[whatsapp_cloud] clarify resolver reported no waiter "- "(clarify_id=%s) — falling back to text", clarify_id,- )- return False- return True+ return await handler(self, reply_target, inner, parts)+ # Unknown prefix (maybe a plugin-defined adapter's) — text dispatch is the safe default.+ return False- # Exec approval: appr:<approval_id>:approve|deny- if button_id.startswith("appr:"):- parts = button_id.split(":", 2)- if len(parts) != 3:- return False- _, approval_id, choice = parts- session_key = self._exec_approval_state.pop(approval_id, None)- if not session_key:- logger.info(- "[whatsapp_cloud] approval tap with no matching state "- "(approval_id=%s) — likely stale; falling back to text",- approval_id,- )- return False- 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"- )- return False- count = resolve_gateway_approval(session_key, choice)- if not count:- logger.info(- "[whatsapp_cloud] approval resolver reported no waiter "- "(session_key=%s) — likely already resolved",- session_key,- )- # Send confirmation message — paralleling Telegram's UX. A tap- # that lands after the wait timed out (count == 0) must not claim- # the command was approved: it was already denied fail-closed.+ async def _reply_best_effort(self, to: str, text: str, fail_log: str) -> None:+ try:+ await self.send(to, text)+ except Exception:+ logger.exception(fail_log)++ async def _handle_clarify_tap(self, to: str, inner: Dict[str, Any], parts: list) -> bool:+ _, clarify_id, choice = parts+ session_key = self._clarify_state.pop(clarify_id, None)+ if not session_key:+ logger.info(+ "[whatsapp_cloud] clarify tap with no matching state "+ "(clarify_id=%s) — likely stale; falling back to text",+ clarify_id,+ )+ 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"+ )+ 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).try:- if count:- confirm_text = (- "✅ Approved." if choice == "approve" else "❌ Denied."- )- else:- confirm_text = (- "⌛ Approval expired — command was not run "- "(already timed out or resolved elsewhere)."- )- await self.send(str(raw_message.get("from") or ""), confirm_text)+ from tools.clarify_gateway import mark_awaiting_text+ flipped = mark_awaiting_text(clarify_id)except Exception:- logger.exception("[whatsapp_cloud] approval confirm failed")- return True-- # Slash confirm: sc:<once|always|cancel>:<confirm_id>- if button_id.startswith("sc:"):- parts = button_id.split(":", 2)- if len(parts) != 3:- return False- _, choice, confirm_id = parts- session_key = self._slash_confirm_state.pop(confirm_id, None)- if not session_key:+ logger.exception("[whatsapp_cloud] mark_awaiting_text failed for %s", clarify_id)+ flipped = False+ if not flipped:+ # Entry vanished (timeout, /new, restart) — fall through to text.logger.info(- "[whatsapp_cloud] slash_confirm tap with no matching state "- "(confirm_id=%s) — likely stale", confirm_id,- )- return False- 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"+ "[whatsapp_cloud] clarify 'Other' tap but entry "+ "missing (clarify_id=%s); falling back to text",+ clarify_id,)return False- try:- result_text = await _slash_confirm_mod.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- if result_text:- try:- await self.send(str(raw_message.get("from") or ""), result_text)- except Exception:- logger.exception("[whatsapp_cloud] slash_confirm reply failed")+ # Keep the mapping live for further taps on the same prompt.+ self._clarify_state[clarify_id] = session_key+ await self._reply_best_effort(to, "✏️ Type your answer:", "[whatsapp_cloud] clarify other-prompt failed")return True+ try:+ idx = int(choice)+ except ValueError:+ logger.warning("[whatsapp_cloud] clarify tap had non-int choice: %r", choice)+ 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.+ response_text = str(inner.get("title") or str(idx + 1))+ resolved = resolve_gateway_clarify(clarify_id, response_text)+ if not resolved:+ logger.info(+ "[whatsapp_cloud] clarify resolver reported no waiter "+ "(clarify_id=%s) — falling back to text", clarify_id,+ )+ return False+ return True- # Unknown prefix — let text dispatch handle the title as a- # regular message. Could be a tap from a plugin-defined adapter- # we don't know about; treating it as text is the safe default.- return False+ async def _handle_approval_tap(self, to: str, inner: Dict[str, Any], parts: list) -> bool:+ _, approval_id, choice = parts+ session_key = self._exec_approval_state.pop(approval_id, None)+ if not session_key:+ logger.info(+ "[whatsapp_cloud] approval tap with no matching state "+ "(approval_id=%s) — likely stale; falling back to text",+ approval_id,+ )+ return False+ 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")+ return False+ count = resolve_gateway_approval(session_key, choice)+ if not count:+ logger.info(+ "[whatsapp_cloud] approval resolver reported no waiter "+ "(session_key=%s) — likely already resolved",+ session_key,+ )+ # A tap after the wait timed out (count == 0) must not claim approval:+ # the command was already denied fail-closed.+ if count:+ confirm_text = "✅ Approved." if choice == "approve" else "❌ Denied."+ else:+ confirm_text = (+ "⌛ Approval expired — command was not run "+ "(already timed out or resolved elsewhere)."+ )+ await self._reply_best_effort(to, confirm_text, "[whatsapp_cloud] approval confirm failed")+ return True++ async def _handle_slash_confirm_tap(self, to: str, inner: Dict[str, Any], parts: list) -> bool:+ _, choice, confirm_id = parts+ session_key = self._slash_confirm_state.pop(confirm_id, None)+ if not session_key:+ logger.info(+ "[whatsapp_cloud] slash_confirm tap with no matching state "+ "(confirm_id=%s) — likely stale", confirm_id,+ )+ return False+ 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")+ return False+ try:+ result_text = await _slash_confirm_mod.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+ if result_text:+ 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,+ }++ async def _collect_inbound_media(+ self, msg_type_str: str, raw_message: Dict[str, Any], body: str+ ) -> tuple[list[str], list[str], str]:+ """Download inbound media by ``media_id``; returns ``(media_urls, media_types, body)``."""+ 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()+ if not media_id:+ return media_urls, media_types, body+ ext_hint = _ext_for_mime(inbound_mime) if inbound_mime else None+ local_path, dl_mime = await self._download_media_to_cache(media_id, ext_hint=ext_hint)+ if local_path:+ media_urls.append(local_path)+ media_types.append(dl_mime or inbound_mime or "application/octet-stream")+ logger.info("[whatsapp_cloud] cached inbound %s media: %s", msg_type_str, local_path)+ else:+ logger.warning(+ "[whatsapp_cloud] failed to download inbound %s (id=%s) — "+ "agent will see message metadata but not the binary",+ msg_type_str, media_id,+ )+ if msg_type_str == "document":+ fname = str(inner.get("filename") or "").strip()+ if fname and not body:+ body = f"[Document: {fname}]"+ return media_urls, media_types, body++ @staticmethod+ def _inject_document_text(media_urls: list[str], body: str) -> str:+ """Prepend text-readable document contents (≤100KB) to the body."""+ for doc_path in media_urls:+ if Path(doc_path).suffix.lower() not in _TEXT_INJECT_EXTS:+ continue+ try:+ file_size = Path(doc_path).stat().st_size+ if file_size > _MAX_TEXT_INJECT_BYTES:+ logger.info(+ "[whatsapp_cloud] skipping text injection for %s "+ "(%d bytes > %d)",+ doc_path, file_size, _MAX_TEXT_INJECT_BYTES,+ )+ continue+ content = Path(doc_path).read_text(encoding="utf-8", errors="replace")+ injection = f"[Content of {Path(doc_path).name}]:\n{content}"+ body = f"{injection}\n\n{body}" if body else injection+ except OSError:+ logger.exception("[whatsapp_cloud] failed to read document text: %s", doc_path)+ return bodyasync def _build_message_event_from_cloud(- self,- raw_message: Dict[str, Any],- contacts_by_waid: Dict[str, str],+ self, raw_message: Dict[str, Any], contacts_by_waid: Dict[str, str],metadata: Dict[str, Any],) -> Optional[MessageEvent]:- """Convert a Cloud-API message object into a Hermes MessageEvent.-- Phase 4 expands beyond text to download inbound media (image,- video, audio/voice, document, sticker) by ``media_id`` via the- two-step Graph endpoint. Cached files are populated into- ``media_urls`` / ``media_types`` so the agent's vision and STT- layers see them. Text-readable documents (.txt, .md, .json,- source code, etc.) are read and prepended to the message body- up to 100KB — same heuristic the Baileys adapter uses.-- Returns None if the message is filtered out by the mixin's- gating (broadcast filter, allow-list, mention requirements).- """+ """Convert a Cloud-API message object into a MessageEvent, or None if gated out."""msg_type_str = str(raw_message.get("type") or "text").lower()- # Interactive replies (button taps, list selections) carry an ``id``- # we set when sending the prompt. Route those to the appropriate- # gateway resolver BEFORE falling through to text dispatch — the- # resolver unblocks the waiting agent thread, so we don't want to- # also kick a fresh conversation turn off the same tap.+ # Button taps route to the gateway resolver BEFORE text dispatch — the+ # resolver unblocks the waiting agent, so don't also start a fresh turn.if msg_type_str == "interactive":- handled = await self._dispatch_interactive_reply(- raw_message, contacts_by_waid- )- if handled:+ if await self._dispatch_interactive_reply(raw_message, contacts_by_waid):return None-body = ""if msg_type_str == "text":- text = raw_message.get("text") or {}- body = str(text.get("body") or "")- elif msg_type_str in {"button", "interactive"}:- # Quick-reply buttons. Treat the button payload as text so the- # agent can reason about the user's choice.- if msg_type_str == "button":- body = str((raw_message.get("button") or {}).get("text") or "")- else:- inter = raw_message.get("interactive") or {}- # button_reply / list_reply both expose ``title``- inner = inter.get("button_reply") or inter.get("list_reply") or {}- body = str(inner.get("title") or "")- elif msg_type_str in {"image", "video", "audio", "voice", "document", "sticker"}:- # Captions live on image / video / document. Other media types- # don't carry a caption in Meta's spec, but be defensive.- inner = raw_message.get(msg_type_str) or {}- body = str(inner.get("caption") or "")-- message_type = {- "text": MessageType.TEXT,- "image": MessageType.PHOTO,- "video": MessageType.VIDEO,- "audio": MessageType.VOICE,- "voice": MessageType.VOICE,- "document": MessageType.DOCUMENT,- "sticker": MessageType.PHOTO,- "button": MessageType.TEXT,- "interactive": MessageType.TEXT,- "location": MessageType.TEXT,- "contacts": MessageType.TEXT,- }.get(msg_type_str, MessageType.TEXT)-+ body = str((raw_message.get("text") or {}).get("body") or "")+ elif msg_type_str == "button":+ body = str((raw_message.get("button") or {}).get("text") or "")+ elif msg_type_str == "interactive":+ inter = raw_message.get("interactive") or {}+ inner = inter.get("button_reply") or inter.get("list_reply") or {}+ body = str(inner.get("title") or "")+ elif msg_type_str in _INBOUND_MEDIA_KINDS:+ body = str((raw_message.get(msg_type_str) or {}).get("caption") or "")+ message_type = _MESSAGE_TYPE_BY_KIND.get(msg_type_str, MessageType.TEXT)sender_id = str(raw_message.get("from") or "").strip()sender_name = contacts_by_waid.get(sender_id, "")- # Cloud API doesn't have a separate "chat" entity for DMs — chat_id- # equals the sender's wa_id. Group support is deferred to v2.- #- # Defensive guard: if Meta ever delivers a group-shaped payload- # (group support is capability-tier gated by Meta; some WABAs- # have it enabled), refuse rather than silently treating it as- # a DM. Group messages carry a ``chat`` field on the message- # object identifying the group JID — its absence signals DM.+ # DMs only: chat_id == sender wa_id. A ``chat`` field marks a group-shaped+ # payload (capability-gated by Meta) — refuse rather than treat as a DM.chat_field = raw_message.get("chat")if chat_field:logger.warning(@@ -1973,108 +1348,30 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):chat_field, raw_message.get("id"),)return None-chat_id = sender_id-- # Build the data dict the mixin's _should_process_message expects.- # Cloud API uses different field names from Baileys, so we adapt.- gating_data = {- "chatId": chat_id,- "senderId": sender_id,- "isGroup": False, # Phase 3 = DM only- "body": body,- }+ gating_data = {"chatId": chat_id, "senderId": sender_id, "isGroup": False, "body": body}if not self._should_process_message(gating_data):return None-- # Download media if this is a non-text message type. Inbound media- # arrives as ``{type: "image", image: {id, mime_type, sha256, ...}}``.media_urls: list[str] = []media_types: list[str] = []- if msg_type_str in {"image", "video", "audio", "voice", "document", "sticker"}:- 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()- if media_id:- ext_hint = None- if inbound_mime:- ext_hint = _ext_for_mime(inbound_mime)- local_path, dl_mime = await self._download_media_to_cache(- media_id, ext_hint=ext_hint- )- if local_path:- media_urls.append(local_path)- media_types.append(dl_mime or inbound_mime or "application/octet-stream")- logger.info(- "[whatsapp_cloud] cached inbound %s media: %s",- msg_type_str, local_path,- )- else:- logger.warning(- "[whatsapp_cloud] failed to download inbound %s (id=%s) — "- "agent will see message metadata but not the binary",- msg_type_str, media_id,- )- # Document: original filename for the agent's UX.- if msg_type_str == "document":- fname = str(inner.get("filename") or "").strip()- if fname and not body:- body = f"[Document: {fname}]"-- # For text-readable documents, inject the file content directly into- # the message body so the agent can reason about it without a- # separate read_file call. Same heuristic the Baileys adapter uses.- # 100KB cap matches Telegram/Discord/Slack.- MAX_TEXT_INJECT_BYTES = 100 * 1024+ 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:- for doc_path in media_urls:- ext = Path(doc_path).suffix.lower()- if ext in {- ".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml",- ".log", ".py", ".js", ".ts", ".html", ".css",- }:- try:- file_size = Path(doc_path).stat().st_size- if file_size > MAX_TEXT_INJECT_BYTES:- logger.info(- "[whatsapp_cloud] skipping text injection for %s "- "(%d bytes > %d)",- doc_path, file_size, MAX_TEXT_INJECT_BYTES,- )- continue- content = Path(doc_path).read_text(- encoding="utf-8", errors="replace"- )- display_name = Path(doc_path).name- injection = f"[Content of {display_name}]:\n{content}"- body = f"{injection}\n\n{body}" if body else injection- except OSError:- logger.exception(- "[whatsapp_cloud] failed to read document text: %s",- doc_path,- )-- # context.id is set when the user replied to a prior message. Meta's- # webhook only gives us the quoted message's id (and its author in- # context.from) — never the quoted text. We resolve the text from- # rich_sent_store, which we populate on every inbound message (below)- # and every outbound send. Without this the agent receives a bare- # reply_to_message_id and run.py can't inject the "[Replying to: ...]"- # disambiguation prefix (it gates on reply_to_text being present).+ body = self._inject_document_text(media_urls, body)++ # Meta's ``context`` gives only the quoted message's id (+ author), never its+ # text; resolve from rich_sent_store so run.py can build "[Replying to: ...]".context = raw_message.get("context") or {}reply_to_id = str(context.get("id") or "").strip() or Nonereply_to_text: Optional[str] = Nonereply_to_is_own = Falseif reply_to_id:reply_to_text = rich_sent_store.lookup(chat_id, reply_to_id)- # context.from is the wa_id of the quoted message's author. When it- # matches our business number the user replied to the bot's own- # message; otherwise they replied to one of their own messages.+ # context.from == our business number → user replied to the bot.quoted_from = str(context.get("from") or "").strip()our_number = str(metadata.get("display_phone_number") or "").strip()if quoted_from and our_number:reply_to_is_own = quoted_from == our_number-source = self.build_source(chat_id=chat_id,chat_name=sender_name or chat_id,@@ -2082,23 +1379,12 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):user_id=sender_id,user_name=sender_name or None,)-- # Cloud API timestamps are unix seconds (string). MessageEvent- # doesn't enforce a type but downstream code formats with it.wamid = str(raw_message.get("id") or "") or Noneif wamid and chat_id:- # Refresh the per-chat latest-wamid cache so a subsequent- # send_typing call can attach the indicator + read receipt- # to this message. Done HERE (after _should_process_message- # gating) so filtered messages don't leak typing on- # unwanted inbound traffic.+ # Done AFTER gating so filtered messages don't leak typing/read receipts.self._bounded_put(self._last_inbound_wamid_by_chat, chat_id, wamid)- # Index this message's text by wamid so a later reply to it can- # resolve the quoted text (Meta's webhook context carries only- # the id). Mirrors the outbound record in send(). Best-effort.if body:rich_sent_store.record(chat_id, wamid, body)-return MessageEvent(text=body,message_type=message_type,diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.pyindex 09e7b0b64f8..29e14945ebb 100644--- a/gateway/platforms/whatsapp_common.py+++ b/gateway/platforms/whatsapp_common.py@@ -1,17 +1,7 @@"""-Transport-agnostic WhatsApp behavior shared by the Baileys bridge adapter-and the official WhatsApp Cloud API adapter.--The mixin provides:-- Allow-list / DM / group gating-- Mention detection (explicit @-mentions + configurable regex patterns)-- Quoted-reply-to-bot detection-- Broadcast / Channel / Newsletter filtering-- WhatsApp-flavored markdown conversion-- Outgoing chunk length budgeting--It is the *behavior layer*. Transport-specific concerns (subprocess management,-HTTP webhooks, Graph API calls, media upload protocols) live in each adapter.+Transport-agnostic WhatsApp behavior shared by the Baileys bridge adapter and the+Cloud API adapter: allow-list / DM / group gating, mention detection, quoted-reply-+to-bot detection, broadcast filtering, WhatsApp markdown conversion, chunk budgeting.Mixin contract — the adapter must set these on ``self`` before any of themixin's methods are called (typically in ``__init__``):@@ -37,40 +27,19 @@ import osimport refrom typing import Any, Dict, Optional-from agent.secret_scope import UnscopedSecretError as _UnscopedSecretError-from agent.secret_scope import get_secret as _scoped_get_secret---def _get_wsecret(name, default=None):- """Scope-aware WHATSAPP_* read with the default-profile startup fallback.+from gateway.platforms._shared import get_scoped_secret as _get_wsecret- Secondary profiles run under ``_profile_runtime_scope`` -- the scope is- authoritative and a scoped miss returns ``default`` (no cross-profile- borrow). The DEFAULT profile's adapter constructs and sends *unscoped*- under multiplexing, where a bare ``get_secret`` would raise- ``UnscopedSecretError`` and crash its WhatsApp path; there ``os.environ``- is that profile's own value, so fall back to it. Same pattern as the- Slack ``SLACK_APP_TOKEN`` read (#59739).- """- try:- val = _scoped_get_secret(name, default)- except _UnscopedSecretError:- val = os.getenv(name)- return val if val is not None else defaultlogger = logging.getLogger(__name__)+_TRUTHY = {"true", "1", "yes", "on"}-class WhatsAppBehaviorMixin:- """Shared behavior for all WhatsApp adapters (Baileys + Cloud API).- See module docstring for the attribute contract the host adapter must- satisfy. This mixin owns no state of its own — every value it touches- is either a class attribute or set by the adapter's ``__init__``.- """+class WhatsAppBehaviorMixin:+ """Shared behavior for all WhatsApp adapters (Baileys + Cloud API); owns no state+ of its own — see the module docstring for the host adapter's attribute contract."""- # WhatsApp message limits — practical UX limit, not protocol max.- # WhatsApp allows ~65K but long messages are unreadable on mobile.+ # Practical UX limit, not the ~65K protocol max (long messages are unreadable on mobile).MAX_MESSAGE_LENGTH: int = 4096supports_code_blocks = True # WhatsApp renders fenced code blocks (monospace)@@ -81,14 +50,8 @@ class WhatsAppBehaviorMixin:@classmethoddef _sanitize_outbound_text(cls, content: str) -> str:- """Remove invisible formatting chars that leak badly in WhatsApp.-- Some provider/gateway formatting paths can emit unicode like WORD- JOINER (U+2060) plus NARROW NO-BREAK SPACE (U+202F). WhatsApp may- render those as mojibake-looking prefixes (`` text``) instead of- invisible spacing. Keep normal text and emoji joiners intact, but- strip known zero-width format chars and normalize odd unicode spaces.- """+ """Strip zero-width format chars (WORD JOINER etc.) and normalize odd unicode+ spaces — WhatsApp renders them as mojibake prefixes. Emoji joiners are kept."""if not content:return contentcontent = cls._OUTBOUND_INVISIBLE_CHARS_RE.sub("", content)@@ -99,14 +62,8 @@ class WhatsAppBehaviorMixin:"""WhatsApp gates DM/group access at intake via dm_policy/group_policy."""return True- # ------------------------------------------------------------------ configdef _effective_reply_prefix(self) -> str:- """Return the prefix to add to outgoing replies in self-chat mode.-- Subclasses that don't have a self-chat concept (the Cloud API- adapter) can override this to always return ``""`` or apply a- different policy.- """+ """Prefix for outgoing replies in self-chat mode (Cloud API overrides to ``""``)."""whatsapp_mode = _get_wsecret("WHATSAPP_MODE", default="self-chat") or "self-chat"if whatsapp_mode != "self-chat":return ""@@ -118,61 +75,60 @@ class WhatsAppBehaviorMixin:return self.DEFAULT_REPLY_PREFIXdef _outgoing_chunk_limit(self) -> int:- """Reserve room for the reply prefix so the final message fits."""- prefix_len = len(self._effective_reply_prefix())- # Keep enough space for truncate_message's pagination indicator and- # code-fence repair even if a user configures a very long prefix.- return max(1024, self.MAX_MESSAGE_LENGTH - prefix_len)+ """Reserve room for the reply prefix; floor keeps space for pagination/fence repair."""+ return max(1024, self.MAX_MESSAGE_LENGTH - len(self._effective_reply_prefix()))def _whatsapp_require_mention(self) -> bool:configured = self.config.extra.get("require_mention")if configured is not None:if isinstance(configured, str):- return configured.lower() in {"true", "1", "yes", "on"}+ return configured.lower() in _TRUTHYreturn bool(configured)- return (_get_wsecret("WHATSAPP_REQUIRE_MENTION", default="false") or "false").lower() in {- "true",- "1",- "yes",- "on",- }+ return (_get_wsecret("WHATSAPP_REQUIRE_MENTION", default="false") or "false").lower() in _TRUTHYdef _whatsapp_free_response_chats(self) -> set[str]:raw = self.config.extra.get("free_response_chats")if raw is None:raw = _get_wsecret("WHATSAPP_FREE_RESPONSE_CHATS", default="") or ""- if isinstance(raw, list):- return {str(part).strip() for part in raw if str(part).strip()}- return {part.strip() for part in str(raw).split(",") if part.strip()}+ return self._coerce_allow_list(raw)@staticmethoddef _coerce_allow_list(raw) -> set[str]:- """Parse allow_from / group_allow_from from config or env var."""+ """Parse allow_from / group_allow_from from config (list) or env var (CSV)."""if raw is None:return set()if isinstance(raw, list):return {str(part).strip() for part in raw if str(part).strip()}return {part.strip() for part in str(raw).split(",") if part.strip()}+ def _select_dm_allowlist(self, extra: Dict[str, Any], env_keys, read_env) -> Any:+ """Pick the raw DM allowlist by key *presence*: ``allow_from``/``allowFrom`` in+ config (an explicit empty list stays authoritative), then the first truthy+ env carrier. Records the winning source in ``_dm_allowlist_source`` so live+ DM checks keep the same precedence."""+ for key in ("allow_from", "allowFrom"):+ if key in extra:+ self._dm_allowlist_source = "config"+ return extra.get(key)+ for env in env_keys:+ if read_env(env):+ self._dm_allowlist_source = env+ return read_env(env)+ self._dm_allowlist_source = None+ return None+def _live_dm_allow_from(self) -> set[str]:"""Allowlist currently enforced for DM intake / strict DM auth.- Source precedence matches construction: explicit config wins over any- env carrier. When the adapter was seeded from an env var, re-read that- same key so pairing approve/revoke takes effect without restart- (including an empty value while the key is still present). When the key- is absent — sole-entry revoke calls ``remove_env_value`` — treat the- allowlist as empty instead of falling back to the construction-time- snapshot. Config-seeded adapters keep the in-memory snapshot, which- pairing revoke purges in place — a lower-precedence or stale env value- must not broaden access.+ Env-seeded adapters re-read the same key so pairing approve/revoke takes+ effect without restart; a removed key (sole-entry revoke) means empty, not+ the construction snapshot. Config-seeded adapters keep the in-memory set+ (pairing revoke purges it in place) — a stale env value must not broaden access."""source = getattr(self, "_dm_allowlist_source", None)if isinstance(source, str) and source != "config":if source in os.environ:return self._coerce_allow_list(os.environ.get(source, ""))- # Key removed (e.g. sole-entry pairing revoke) — do not revive the- # stale construction snapshot.return set()return set(self._allow_from or ())@@ -188,23 +144,12 @@ class WhatsAppBehaviorMixin:@staticmethoddef _is_broadcast_chat(chat_id: str) -> bool:- """True for WhatsApp pseudo-chats that aren't real conversations.-- Covers Status updates (Stories) and Channel/Newsletter broadcasts.- These show up as inbound messages on Baileys but the agent should- never reply — answering a Story update spams the contact's status- feed, and Channel posts aren't addressable in the first place.- """+ """Status updates (Stories) and Channel/Newsletter broadcasts — never reply+ (answering a Story spams the status feed; Channel posts aren't addressable)."""if not chat_id:return Falsecid = chat_id.strip().lower()- if cid == "status@broadcast":- return True- # @broadcast suffix covers status@broadcast plus any future- # broadcast-list variants. @newsletter is the Channel JID suffix.- if cid.endswith("@broadcast") or cid.endswith("@newsletter"):- return True- return False+ return cid == "status@broadcast" or cid.endswith("@broadcast") or cid.endswith("@newsletter")# ------------------------------------------------------------------ gatingdef _open_dm_opted_in(self) -> bool:@@ -216,27 +161,18 @@ class WhatsAppBehaviorMixin:def _matches_whatsapp_allowlist(candidate: str, allow_from) -> bool:"""Match a WhatsApp identifier against an allowlist across phone/LID forms.- WhatsApp delivers inbound senders in LID form (``<id>@lid``) while- operators usually configure allowlists with phone numbers, and vice- versa. A raw set-membership check therefore never matches a known- contact. Resolve both the candidate and each allowlist entry through- the bridge's ``lid-mapping-*.json`` files (the shared- ``gateway.whatsapp_identity`` helper that the gateway authz and- session-key paths already use) so either configured form resolves to- the inbound form.+ Inbound senders arrive as ``<id>@lid`` while allowlists hold phone numbers+ (or vice versa), so resolve both sides through the bridge's lid-mapping+ files via ``gateway.whatsapp_identity``."""if not allow_from:return False- # Fast path: exact match against the raw configured value (e.g. a full- # ``@g.us`` group JID or an entry that already matches verbatim).if candidate in allow_from:return True-from gateway.whatsapp_identity import (expand_whatsapp_aliases,normalize_whatsapp_identifier,)-candidate_aliases = expand_whatsapp_aliases(candidate)if not candidate_aliases:return False@@ -245,16 +181,12 @@ class WhatsAppBehaviorMixin:return Trueif normalize_whatsapp_identifier(entry) in candidate_aliases:return True- # Entry may itself be an unmapped form; expand it too so a phone- # allowlist entry resolves when the inbound sender arrived as a LID.if expand_whatsapp_aliases(entry) & candidate_aliases:return Truereturn Falsedef _is_dm_allowed(self, sender_id: str) -> bool:"""Strict DM authorization — pairing does not imply access."""- if self._dm_policy == "disabled":- return Falseif self._dm_policy == "allowlist":return self._matches_whatsapp_allowlist(sender_id, self._live_dm_allow_from())if self._dm_policy == "open":@@ -266,8 +198,6 @@ class WhatsAppBehaviorMixin:principal = str(sender_id or "").strip()if not principal:return False- if self._dm_policy == "disabled":- return Falseif self._dm_policy == "allowlist":return self._matches_whatsapp_allowlist(principal, self._live_dm_allow_from())if self._dm_policy == "pairing":@@ -278,15 +208,9 @@ class WhatsAppBehaviorMixin:def _is_group_allowed(self, chat_id: str) -> bool:"""Check whether a group chat should be processed."""- if self._group_policy == "disabled":- return Falseif self._group_policy == "allowlist":return self._matches_whatsapp_allowlist(chat_id, self._group_allow_from)- if self._group_policy == "pairing":- return False- if self._group_policy == "open":- return True- return False+ return self._group_policy == "open"def _compile_mention_patterns(self):patterns = self.config.extra.get("mention_patterns")@@ -296,13 +220,9 @@ class WhatsAppBehaviorMixin:try:patterns = json.loads(raw)except Exception:- patterns = [- part.strip() for part in raw.splitlines() if part.strip()- ]+ patterns = [part.strip() for part in raw.splitlines() if part.strip()]if not patterns:- patterns = [- part.strip() for part in raw.split(",") if part.strip()- ]+ patterns = [part.strip() for part in raw.split(",") if part.strip()]if patterns is None:return []if isinstance(patterns, str):@@ -310,11 +230,9 @@ class WhatsAppBehaviorMixin:if not isinstance(patterns, list):logger.warning("[%s] whatsapp mention_patterns must be a list or string; got %s",- self.name,- type(patterns).__name__,+ self.name, type(patterns).__name__,)return []-compiled = []for pattern in patterns:if not isinstance(pattern, str) or not pattern.strip():@@ -322,16 +240,9 @@ class WhatsAppBehaviorMixin:try:compiled.append(re.compile(pattern, re.IGNORECASE))except re.error as exc:- logger.warning(- "[%s] Invalid WhatsApp mention pattern %r: %s",- self.name,- pattern,- exc,- )+ logger.warning("[%s] Invalid WhatsApp mention pattern %r: %s", self.name, pattern, exc)if compiled:- logger.info(- "[%s] Loaded %d WhatsApp mention pattern(s)", self.name, len(compiled)- )+ logger.info("[%s] Loaded %d WhatsApp mention pattern(s)", self.name, len(compiled))return compileddef _bot_ids_from_message(self, data: Dict[str, Any]) -> set[str]:@@ -359,9 +270,7 @@ class WhatsAppBehaviorMixin:}if mentioned_ids & bot_ids:return True-- body = str(data.get("body") or "")- lower_body = body.lower()+ lower_body = str(data.get("body") or "").lower()for bot_id in bot_ids:bare_id = bot_id.split("@", 1)[0].lower()if bare_id and (f"@{bare_id}" in lower_body or bare_id in lower_body):@@ -377,37 +286,25 @@ class WhatsAppBehaviorMixin:def _clean_bot_mention_text(self, text: str, data: Dict[str, Any]) -> str:if not text:return text- bot_ids = self._bot_ids_from_message(data)cleaned = text- for bot_id in bot_ids:+ for bot_id in self._bot_ids_from_message(data):bare_id = bot_id.split("@", 1)[0]if bare_id:- cleaned = re.sub(- rf"@{re.escape(bare_id)}\b[,:\-]*\s*", "", cleaned- )+ cleaned = re.sub(rf"@{re.escape(bare_id)}\b[,:\-]*\s*", "", cleaned)return cleaned.strip() or textdef _should_process_message(self, data: Dict[str, Any]) -> bool:- chat_id_raw = str(data.get("chatId") or "")- # WhatsApp uses pseudo-chats for Status updates (Stories) and- # Channel/Newsletter broadcasts. These are not real conversations- # and the agent should never reply to them — even in self-chat mode- # where the bridge may surface them as "fromMe" events.- if self._is_broadcast_chat(chat_id_raw):+ chat_id = str(data.get("chatId") or "")+ # Broadcast pseudo-chats are filtered even in self-chat mode (fromMe events).+ if self._is_broadcast_chat(chat_id):return False- is_group = data.get("isGroup", False)- if is_group:- chat_id = chat_id_raw- if not self._is_group_allowed(chat_id):- return False- else:- sender_id = str(data.get("senderId") or data.get("from") or "")- if not self._is_dm_intake_allowed(sender_id):- return False+ if not data.get("isGroup", False):# DMs that pass the policy gate are always processed- return True+ sender_id = str(data.get("senderId") or data.get("from") or "")+ return self._is_dm_intake_allowed(sender_id)+ if not self._is_group_allowed(chat_id):+ return False# Group messages: check mention / free-response settings- chat_id = str(data.get("chatId") or "")if chat_id in self._whatsapp_free_response_chats():return Trueif not self._whatsapp_require_mention():@@ -423,21 +320,11 @@ class WhatsAppBehaviorMixin:# ------------------------------------------------------------------ formattingdef format_message(self, content: str) -> str:- """Convert standard markdown to WhatsApp-compatible formatting.-- WhatsApp supports: *bold*, _italic_, ~strikethrough~, ```code```,- and monospaced `inline`. Standard markdown uses different syntax- for bold/italic/strikethrough, so we convert here.-- Code blocks (``` fenced) and inline code (`) are protected from- conversion via placeholder substitution.- """+ """Convert markdown to WhatsApp syntax (*bold*, _italic_, ~strike~); fenced and+ inline code are protected via placeholder substitution."""if not content:return content-content = self._sanitize_outbound_text(content)-- # --- 1. Protect fenced code blocks from formatting changes ---_FENCE_PH = "\x00FENCE"fences: list[str] = []@@ -446,8 +333,6 @@ class WhatsAppBehaviorMixin:return f"{_FENCE_PH}{len(fences) - 1}\x00"result = re.sub(r"```[\s\S]*?```", _save_fence, content)-- # --- 2. Protect inline code ---_CODE_PH = "\x00CODE"codes: list[str] = []@@ -457,73 +342,39 @@ class WhatsAppBehaviorMixin:result = re.sub(r"`[^`\n]+`", _save_code, result)- # --- 3. Convert markdown formatting to WhatsApp syntax ---- # Italic: standard Markdown *text* → WhatsApp _text_. Do this before- # bold conversion so **bold** does not become italic by accident. The- # lookarounds avoid list bullets and bold delimiters.- result = re.sub(- r"(?<!\*)\*(?!\s|\*)([^*\n]*?\S[^*\n]*?)\*(?!\*)",- r"_\1_",- result,- )- # Bold: **text** or __text__ → *text*+ # Italic *text* → _text_ BEFORE bold so **bold** doesn't become italic;+ # lookarounds skip list bullets and bold delimiters.+ result = re.sub(r"(?<!\*)\*(?!\s|\*)([^*\n]*?\S[^*\n]*?)\*(?!\*)", r"_\1_", result)result = re.sub(r"\*\*(.+?)\*\*", r"*\1*", result)result = re.sub(r"__(.+?)__", r"*\1*", result)- # Strikethrough: ~~text~~ → ~text~result = re.sub(r"~~(.+?)~~", r"~\1~", result)- # _text_ is already WhatsApp italic — leave as-is- # --- 4. Convert markdown headers to bold text ---- # # Header → *Header*. Strip any *...* wrapping already produced- # by step 3 (e.g. "# **Title**" → "*Title*", not "**Title**",- # which WhatsApp renders with literal asterisks).+ # "# Header" → *Header*, stripping *...* already produced above so+ # "# **Title**" doesn't render with literal asterisks.def _header_to_bold(m: re.Match) -> str:inner = m.group(1).strip()while len(inner) > 1 and inner.startswith("*") and inner.endswith("*"):inner = inner[1:-1].strip()return f"*{inner}*"- result = re.sub(- r"^#{1,6}\s+(.+)$", _header_to_bold, result, flags=re.MULTILINE- )-- # --- 5. Convert markdown links: [text](url) → text (url) ---+ result = re.sub(r"^#{1,6}\s+(.+)$", _header_to_bold, result, flags=re.MULTILINE)+ # [text](url) → text (url)result = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", result)-- # --- 6. Restore protected sections ---for i, fence in enumerate(fences):result = result.replace(f"{_FENCE_PH}{i}\x00", fence)for i, code in enumerate(codes):result = result.replace(f"{_CODE_PH}{i}\x00", code)-return result-# ----------------------------------------------------------------------------# Shared bridge directory resolution for CLI and adapter-# ----------------------------------------------------------------------------def resolve_whatsapp_bridge_dir() -> Path:- """Resolve the WhatsApp bridge directory, mirroring to HERMES_HOME if needed.-- When the install tree is read-only (e.g., Docker /opt/hermes), this function- mirrors the bridge source to a writable HERMES_HOME location and returns that- path. This ensures npm install works in Docker environments.-- Returns the resolved bridge directory path.- """+ """Bridge directory for CLI and adapter. A read-only install tree (e.g. Docker+ /opt/hermes) is mirrored to HERMES_HOME so npm install works."""import shutilfrom pathlib import Path as _Path-- # Default location in install tree (may be read-only)from hermes_constants import get_hermes_homeinstall_bridge = _Path(__file__).resolve().parents[2] / "scripts" / "whatsapp-bridge"-- # Try HERMES_HOME location first- hermes_home = get_hermes_home()- hermes_home_bridge = hermes_home / "scripts" / "whatsapp-bridge"-- # Check if install dir is writable+ hermes_home_bridge = get_hermes_home() / "scripts" / "whatsapp-bridge"try:test_file = install_bridge / ".write_test"test_file.touch()@@ -531,22 +382,13 @@ def resolve_whatsapp_bridge_dir() -> Path:install_writable = Trueexcept (OSError, PermissionError):install_writable = False-if install_writable:return install_bridge-- # Install dir is read-only, mirror to HERMES_HOME if neededif hermes_home_bridge.exists():return hermes_home_bridge-- # Mirror the bridge source to HERMES_HOMEtry:hermes_home_bridge.parent.mkdir(parents=True, exist_ok=True)- shutil.copytree(- install_bridge,- hermes_home_bridge,- dirs_exist_ok=False,- )+ shutil.copytree(install_bridge, hermes_home_bridge, dirs_exist_ok=False)return hermes_home_bridgeexcept Exception:return install_bridgediff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 2749217a1b0..a57cdc131d7 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -1,18 +1,8 @@"""-WhatsApp platform adapter.+WhatsApp platform adapter (Baileys bridge).-WhatsApp integration is more complex than Telegram/Discord because:-- No official bot API for personal accounts-- Business API requires Meta Business verification-- Most solutions use web-based automation--This adapter supports multiple backends:-1. WhatsApp Business API (requires Meta verification)-2. whatsapp-web.js (via Node.js subprocess) - for personal accounts-3. Baileys (via Node.js subprocess) - alternative for personal accounts--For simplicity, we'll implement a generic interface that can work-with different backends via a bridge pattern.+A Node.js bridge process runs the WhatsApp Web client; messages are polled over a+local HTTP API and responses are posted back through the bridge."""import asyncio@@ -22,38 +12,20 @@ import platformimport reimport signalimport subprocess--_IS_WINDOWS = platform.system() == "Windows"from pathlib import Pathfrom typing import Dict, Optional, Any+from gateway.platforms._shared import get_scoped_secretfrom hermes_cli._subprocess_compat import windows_detach_popen_kwargs-from hermes_constants import (- find_node_executable,- get_hermes_dir,- with_hermes_node_path,-)+from hermes_constants import (find_node_executable, get_hermes_dir, with_hermes_node_path)-def _wenv(name: str, default: str = "") -> str:- """Read a WHATSAPP_* env var through the profile secret scope.+_IS_WINDOWS = platform.system() == "Windows"- Under multiplexing, ``os.getenv`` bypasses the per-profile ``.env`` and- returns the process-global value (often unset), causing the bridge to- silently fall back to ``"self-chat"`` and reject all messages.- ``get_secret`` honors the active ``_profile_runtime_scope`` so secondary- profiles see their own credentials.- """- from agent.secret_scope import UnscopedSecretError, get_secret- try:- val = get_secret(name)- except UnscopedSecretError:- # DEFAULT profile's adapter constructs/connects outside any- # _profile_runtime_scope under multiplexing; os.environ is that- # profile's own value there. Same pattern as Slack SLACK_APP_TOKEN- # (#59739) and the Matrix recovery key. A *scoped* miss still- # returns the default (no cross-profile borrow).- val = os.getenv(name)- return val if val is not None else default++def _wenv(name: str, default: str = "") -> str:+ """WHATSAPP_* env read through the profile secret scope (multiplexed profiles see+ their own .env; os.getenv would return the process-global value)."""+ return get_scoped_secret(name, default)logger = logging.getLogger(__name__)@@ -61,23 +33,19 @@ logger = logging.getLogger(__name__)# transcripts stay disambiguated even if downstream plugins fail before silent_ingest._OWNER_REPLY_PREFIX = "[owner reply] "+_RUN_TEXT = dict(capture_output=True, text=True, encoding='utf-8', errors='replace')+def _listener_pids_on_port(port: int) -> list:"""PIDs of processes *listening* on ``port`` (POSIX) — never clients.- This must match only LISTEN sockets. A bare ``lsof -i :PORT`` (or- ``fuser PORT/tcp``) also returns *clients* whose connection merely involves- that port number — e.g. a browser with a tab open on a local dev server- sharing the port. SIGTERMing those closed the user's browser at irregular- intervals. Restricting to LISTEN state frees the port for a new bridge- without ever touching an unrelated client.+ A bare ``lsof -i :PORT`` also returns clients whose connection involves that+ port (e.g. a browser tab on a local dev server); SIGTERMing those closed the+ user's browser. Restricting to LISTEN state never touches an unrelated client."""pids: list = []try:- result = subprocess.run(- ["lsof", "-ti", f"tcp:{port}", "-sTCP:LISTEN"],- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,- )+ result = subprocess.run(["lsof", "-ti", f"tcp:{port}", "-sTCP:LISTEN"], timeout=5, **_RUN_TEXT)for line in result.stdout.strip().splitlines():try:pids.append(int(line))@@ -87,12 +55,8 @@ def _listener_pids_on_port(port: int) -> list:return pidsexcept FileNotFoundError:pass # lsof not installed — fall through to ss- # Fallback: ss (iproute2, present on virtually every modern Linux).try:- result = subprocess.run(- ["ss", "-ltnHp", f"sport = :{port}"],- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,- )+ result = subprocess.run(["ss", "-ltnHp", f"sport = :{port}"], timeout=5, **_RUN_TEXT)for m in re.finditer(r"pid=(\d+)", result.stdout):pids.append(int(m.group(1)))except FileNotFoundError:@@ -103,16 +67,12 @@ def _listener_pids_on_port(port: int) -> list:def _pid_looks_like_node_bridge(pid: int) -> bool:"""Fail-closed check that *pid* is plausibly a stale node bridge.- ``_kill_port_process`` discovers PIDs from a netstat/lsof scan of a TCP- port — a bare number naming a *stranger* process (#89614 class: an- unverified scan-time PID force-killed later can be anything, including a- critical system process). Before any kill, require the live process to- actually look like our Baileys bridge: a ``node`` executable. Any+ A scan-time PID can name a stranger (even a critical system process) by the+ time we kill it; require the live process to be a ``node`` executable. Anyambiguity (process gone, unreadable cmdline) refuses the kill."""try:import psutil-proc = psutil.Process(pid)name = (proc.name() or "").lower()cmdline = " ".join(proc.cmdline() or []).lower()@@ -121,54 +81,42 @@ def _pid_looks_like_node_bridge(pid: int) -> bool:return False+def _warn_not_bridge(pid: int, port: int) -> None:+ logger.warning(+ "[whatsapp] Not killing PID %s on port %d: process is not a node bridge "+ "(or identity unverifiable)", pid, port)++def _kill_port_process(port: int) -> None:- """Kill any process *listening* on the given TCP port (a stale bridge)."""+ """Kill any node bridge *listening* on the given TCP port (never a client)."""try:if _IS_WINDOWS:from hermes_cli._subprocess_compat import windows_hide_flags-- # Use netstat to find the PID bound to this port, then taskkillresult = subprocess.run(- ["netstat", "-ano", "-p", "TCP"],- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,- creationflags=windows_hide_flags(),+ ["netstat", "-ano", "-p", "TCP"], timeout=5, creationflags=windows_hide_flags(), **_RUN_TEXT,)for line in result.stdout.splitlines():parts = line.split()- if len(parts) >= 5 and parts[3] == "LISTENING":- local_addr = parts[1]- if local_addr.endswith(f":{port}"):- try:- pid = int(parts[4])- except ValueError:- continue- # Never taskkill a bare netstat-scanned PID: verify- # the live process is a node bridge first (fail- # closed). taskkill /F on a mistyped or recycled PID- # is unrecoverable.- if pid <= 0 or not _pid_looks_like_node_bridge(pid):- logger.warning(- "[whatsapp] Not killing PID %s on port %d: "- "process is not a node bridge (or identity "- "unverifiable)", pid, port)- continue- try:- subprocess.run(- ["taskkill", "/PID", str(pid), "/F"],- capture_output=True, timeout=5,- creationflags=windows_hide_flags(),- )- except subprocess.SubprocessError:- pass+ if len(parts) >= 5 and parts[3] == "LISTENING" and parts[1].endswith(f":{port}"):+ try:+ pid = int(parts[4])+ except ValueError:+ continue+ # taskkill /F on a mistyped or recycled PID is unrecoverable — verify first.+ if pid <= 0 or not _pid_looks_like_node_bridge(pid):+ _warn_not_bridge(pid, port)+ continue+ try:+ subprocess.run(+ ["taskkill", "/PID", str(pid), "/F"],+ capture_output=True, timeout=5, creationflags=windows_hide_flags(),+ )+ except subprocess.SubprocessError:+ passelse:- # POSIX: only ever signal a process LISTENING on the port. A client- # whose connection happens to involve this port number (a browser- # tab on a local dev server, etc.) must never be killed.for pid in _listener_pids_on_port(port):if not _pid_looks_like_node_bridge(pid):- logger.warning(- "[whatsapp] Not killing PID %s on port %d: process is "- "not a node bridge (or identity unverifiable)", pid, port)+ _warn_not_bridge(pid, port)continuetry:os.kill(pid, signal.SIGTERM)@@ -181,27 +129,17 @@ def _kill_port_process(port: int) -> None:def _bridge_pid_is_ours(pid: int, session_path: Path, expected_start) -> bool:"""True only if ``pid`` is alive AND still our node bridge for this session.- The PID is read from a file written by a previous run. Once that process- exits and is reaped the kernel can recycle the number onto an unrelated- process — observed in the wild landing on a desktop browser's main process,- which a bare-liveness ``os.kill`` then SIGTERMed, closing the whole browser- at irregular intervals (every time the flapping bridge restarted).-- Identity is confirmed two ways: the kernel start time captured when we wrote- the pidfile (definitive), and — for legacy pidfiles with no baseline — the- command line, which must contain ``node`` and this session's unique path.- A recycled PID (different start time / different cmdline) is never ours.+ The kernel can recycle a pidfile's PID onto an unrelated process (seen landing+ on a desktop browser, which a bare-liveness kill then closed). Identity is the+ recorded kernel start time (definitive); legacy pidfiles without one fall back+ to a cmdline containing ``node`` and this session's unique path."""from gateway.status import _pid_existsif not _pid_exists(pid):return Falseif expected_start is not None:from gateway.status import get_process_start_time- # A matching (pid, start time) pair uniquely identifies the process.return get_process_start_time(pid) == expected_start- # Legacy pidfile (no recorded start time): fall back to a command-line- # signature so a recycled PID is still never signalled. If we cannot read- # the cmdline we refuse to kill rather than risk a stranger.from gateway.status import _read_process_cmdlinecmdline = _read_process_cmdline(pid)if not cmdline:@@ -210,15 +148,9 @@ def _bridge_pid_is_ours(pid: int, session_path: Path, expected_start) -> bool:def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:- """Kill a bridge process recorded in a PID file from a previous run.-- The bridge writes ``bridge.pid`` into the session directory when it- starts. If the gateway crashed without a clean shutdown the old bridge- process becomes orphaned — this helper finds and kills it.+ """Kill an orphaned bridge recorded in ``bridge.pid`` from a previous run.- Critically, the recorded PID is re-validated against the live process- (:func:`_bridge_pid_is_ours`) before any signal, so a recycled PID that now- names an unrelated process (e.g. the user's browser) is never killed.+ The PID is re-validated via :func:`_bridge_pid_is_ours` before any signal."""pid_file = session_path / "bridge.pid"if not pid_file.exists():@@ -226,8 +158,7 @@ def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:pid = Nonerecorded_start = Nonetry:- # Format: line 1 = pid, optional line 2 = kernel start time. Legacy- # files written before the guard existed have only the pid.+ # Line 1 = pid, optional line 2 = kernel start time (legacy files: pid only).lines = pid_file.read_text(encoding="utf-8").split("\n")pid = int(lines[0].strip())if len(lines) > 1 and lines[1].strip():@@ -259,12 +190,7 @@ def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:def _write_bridge_pidfile(session_path: Path, pid: int) -> None:- """Write the bridge PID (and its kernel start time) for later cleanup.-- The start time on line 2 lets a future run prove the PID still names this- exact process before signalling it, so a recycled PID can never be killed- as a "stale bridge". Older single-line files remain readable.- """+ """Write the bridge PID plus its kernel start time (line 2) for later identity-checked cleanup."""try:from gateway.status import get_process_start_timestart = get_process_start_time(pid)@@ -281,42 +207,27 @@ def _terminate_bridge_process(proc, *, force: bool = False) -> None:if force:cmd.append("/F")try:- result = subprocess.run(- cmd,- capture_output=True,- text=True, encoding='utf-8', errors='replace',- timeout=10,- )+ result = subprocess.run(cmd, timeout=10, **_RUN_TEXT)except FileNotFoundError:if force:proc.kill()else:proc.terminate()return-if result.returncode != 0:details = (result.stderr or result.stdout or "").strip()raise OSError(details or f"taskkill failed for PID {proc.pid}")return-import psutil+ action = "kill" if force else "terminate"try:parent = psutil.Process(proc.pid)- children = parent.children(recursive=True)- if force:- for child in children:- try:- child.kill()- except psutil.NoSuchProcess:- pass- parent.kill()- else:- for child in children:- try:- child.terminate()- except psutil.NoSuchProcess:- pass- parent.terminate()+ for child in parent.children(recursive=True):+ try:+ getattr(child, action)()+ except psutil.NoSuchProcess:+ pass+ getattr(parent, action)()except psutil.NoSuchProcess:return@@ -339,38 +250,24 @@ from utils import env_intdef _is_allowed_bridge_path(url: str) -> bool:- """Return True only when an absolute path from the bridge resolves inside a- known Hermes media cache directory.-- The Baileys bridge is a local subprocess that downloads inbound media and- hands back absolute file paths. A compromised or buggy bridge could hand- back an arbitrary path (e.g. ``/etc/passwd``) which would otherwise be- attached verbatim and sent to the model. Resolve the path (following any- symlinks) and require it to live under one of the real cache roots — this- covers both the canonical ``cache/<kind>`` layout and the legacy- ``<kind>_cache`` layout that ``get_hermes_dir`` may return.+ """True only when an absolute bridge path resolves inside a Hermes media cache dir.++ A compromised or buggy bridge could hand back ``/etc/passwd``; resolve+ symlinks and require one of the real cache roots (canonical ``cache/<kind>``+ or legacy ``<kind>_cache`` layout)."""try:resolved = Path(url).resolve()except (OSError, ValueError):return False- # Resolve the cache roots per-call via the getters (not the import-time- # constants) so this validator follows the active profile override; under a- # profile override the inbound bridge writes media into that profile's- # cache, which the frozen constants would not match.+ # Per-call getters (not import-time constants) so a profile override's cache matches.from gateway.platforms.base import (get_audio_cache_dir,get_document_cache_dir,get_image_cache_dir,get_video_cache_dir,)-- for root in (- get_image_cache_dir(),- get_audio_cache_dir(),- get_video_cache_dir(),- get_document_cache_dir(),- ):+ for root in (get_image_cache_dir(), get_audio_cache_dir(), get_video_cache_dir(), get_document_cache_dir()):try:if resolved.is_relative_to(Path(root).resolve()):return True@@ -380,13 +277,10 @@ def _is_allowed_bridge_path(url: str) -> bool:def _file_content_hash(path: Path) -> str:- """Return the first 16 hex chars of the SHA-256 of *path*'s contents.+ """First 16 hex chars of SHA-256 of *path* ("" if unreadable).- Used for the bridge staleness handshake: bridge.js reports its own- source hash in ``/health`` (``scriptHash``), and the adapter compares- it against the hash of bridge.js currently on disk. A mismatch means- a long-lived bridge process is serving code from before an update.- Returns ``""`` when the file can't be read.+ bridge.js reports its own hash in ``/health`` (``scriptHash``); a mismatch with+ the on-disk file means a long-lived bridge is serving pre-update code."""import hashlibtry:@@ -396,97 +290,71 @@ def _file_content_hash(path: Path) -> str:def check_whatsapp_requirements() -> bool:- """- Check if WhatsApp dependencies are available.-- WhatsApp requires a Node.js bridge for most implementations.- """- # Prefer Hermes-managed Node/npm so Windows installs are not broken by a- # bad or elevation-triggering system Node on PATH.+ """Node.js (Hermes-managed first, so a bad system Node on PATH can't break Windows) is available."""_node = find_node_executable("node")if not _node:return Falsetry:- result = subprocess.run(- [_node, "--version"],- capture_output=True,- text=True, encoding='utf-8', errors='replace',- timeout=5- )+ result = subprocess.run([_node, "--version"], timeout=5, **_RUN_TEXT)return result.returncode == 0except Exception:return False+# Env vars bridge.js consumes. Under multiplexing the subprocess gets a copy of+# os.environ without the secondary profile's .env, so the resolved values are injected.+_BRIDGE_PASSTHROUGH_ENV = (+ "WHATSAPP_ALLOWED_USERS", "WHATSAPP_ALLOW_FROM",+ "WHATSAPP_DM_POLICY", "WHATSAPP_GROUP_POLICY",+ "WHATSAPP_GROUP_ALLOWED_USERS", "WHATSAPP_GROUP_ALLOW_FROM",+ "WHATSAPP_REQUIRE_MENTION", "WHATSAPP_MENTION_PATTERNS",+ "WHATSAPP_FREE_RESPONSE_CHATS",+ "WHATSAPP_DEBUG", "WHATSAPP_FORWARD_OWNER_MESSAGES",+ "WHATSAPP_REPLY_PREFIX", "WHATSAPP_MAX_MESSAGE_LENGTH",+ "WHATSAPP_CHUNK_DELAY_MS", "WHATSAPP_SEND_TIMEOUT_MS",+)+_TEXT_INJECT_EXTS = {".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml", ".log", ".py", ".js", ".ts", ".html", ".css"}+_MAX_TEXT_INJECT_BYTES = 100 * 1024 # matches Telegram/Discord/Slack+_MEDIA_LABEL = {+ MessageType.PHOTO: "image", MessageType.VOICE: "audio", MessageType.AUDIO: "audio",+ MessageType.DOCUMENT: "document", MessageType.VIDEO: "video",+}+_MEDIA_DEFAULT_MIME = {+ MessageType.PHOTO: "image/jpeg", MessageType.VOICE: "audio/ogg",+ MessageType.AUDIO: "audio/mpeg", MessageType.VIDEO: "video/mp4",+}++class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):- """- WhatsApp adapter.-- This implementation uses a simple HTTP bridge pattern where:- 1. A Node.js process runs the WhatsApp Web client- 2. Messages are forwarded via HTTP/IPC to this Python adapter- 3. Responses are sent back through the bridge-- The actual Node.js bridge implementation can vary:- - whatsapp-web.js based- - Baileys based- - Business API based-- Configuration:- - bridge_script: Path to the Node.js bridge script- - bridge_port: Port for HTTP communication (default: 3000)- - session_path: Path to store WhatsApp session data- - dm_policy: "open" | "allowlist" | "disabled" | "pairing" — how DMs are handled (default: "pairing")- - allow_from: List of sender IDs allowed in DMs (when dm_policy="allowlist")- - group_policy: "open" | "allowlist" | "disabled" | "pairing" — which groups are processed (default: "pairing")- - group_allow_from: List of group JIDs allowed (when group_policy="allowlist")- - send_read_receipts: Mark accepted inbound WhatsApp messages as read+ """WhatsApp adapter over a local Node.js (Baileys) HTTP bridge; behavior comes+ from ``WhatsAppBehaviorMixin``, only transport lives here.- Behavior (gating, mention parsing, markdown conversion, chunking) is- provided by ``WhatsAppBehaviorMixin`` so the Cloud API adapter can- share it. Only transport-specific code lives here.+ Configuration (config.extra):+ - bridge_script / bridge_port (default 3000) / session_path+ - dm_policy, group_policy: "open" | "allowlist" | "disabled" | "pairing" (default "pairing")+ - allow_from / group_allow_from: IDs allowed when the policy is "allowlist"+ - send_read_receipts: Mark accepted inbound WhatsApp messages as read"""- # Default bridge location resolved via shared helper_DEFAULT_BRIDGE_DIR = None # resolved in __init__splits_long_messages = True # send() chunks via truncate_message()def __init__(self, config: PlatformConfig):super().__init__(config, Platform.WHATSAPP)- # Use shared helper for bridge directory resolution (handles read-only install tree)if WhatsAppAdapter._DEFAULT_BRIDGE_DIR is None:from gateway.platforms.whatsapp_common import resolve_whatsapp_bridge_dirWhatsAppAdapter._DEFAULT_BRIDGE_DIR = resolve_whatsapp_bridge_dir()self._bridge_process: Optional[subprocess.Popen] = Noneself._bridge_port: int = config.extra.get("bridge_port", 3000)self._bridge_script: Optional[str] = config.extra.get(- "bridge_script",- str(self._DEFAULT_BRIDGE_DIR / "bridge.js"),+ "bridge_script", str(self._DEFAULT_BRIDGE_DIR / "bridge.js"),)self._session_path: Path = Path(config.extra.get(- "session_path",- get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")+ "session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")))self._reply_prefix: Optional[str] = config.extra.get("reply_prefix")self._dm_policy = str(config.extra.get("dm_policy") or _wenv("WHATSAPP_DM_POLICY", "pairing")).strip().lower()- # Prefer config.extra, then the documented WHATSAPP_ALLOWED_USERS env- # (setup wizard / pairing mirror). Select by key *presence* so an- # explicit empty allow_from: [] stays authoritative and does not fall- # through to a lower-precedence env grant. Track which source won so- # live DM checks preserve that precedence. Env reads go through the- # profile secret scope (_wenv) so multiplexed profiles see their own.- if "allow_from" in config.extra:- self._dm_allowlist_source = "config"- allow_raw = config.extra.get("allow_from")- elif "allowFrom" in config.extra:- self._dm_allowlist_source = "config"- allow_raw = config.extra.get("allowFrom")- elif _wenv("WHATSAPP_ALLOWED_USERS"):- self._dm_allowlist_source = "WHATSAPP_ALLOWED_USERS"- allow_raw = _wenv("WHATSAPP_ALLOWED_USERS")- else:- self._dm_allowlist_source = None- allow_raw = None+ allow_raw = self._select_dm_allowlist(config.extra, ("WHATSAPP_ALLOWED_USERS",), _wenv)self._allow_from = self._coerce_allow_list(allow_raw)self._group_policy = str(config.extra.get("group_policy") or _wenv("WHATSAPP_GROUP_POLICY", "pairing")).strip().lower()self._group_allow_from = self._coerce_allow_list(config.extra.get("group_allow_from") or config.extra.get("groupAllowFrom"))@@ -501,40 +369,21 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._bridge_log: Optional[Path] = Noneself._poll_task: Optional[asyncio.Task] = Noneself._http_session: Optional["aiohttp.ClientSession"] = None- # Set to True by disconnect() before we SIGTERM our child bridge so- # _check_managed_bridge_exit() can distinguish an intentional- # shutdown-time exit (returncode -15 / -2 / 0) from a real crash.- # Without this, every graceful gateway shutdown/restart would log- # "Fatal whatsapp adapter error" plus dispatch a fatal-error- # notification before the normal "✓ whatsapp disconnected" fires.+ # Set by disconnect() before SIGTERMing the child so _check_managed_bridge_exit()+ # can tell an intentional exit (-15 / -2 / 0) from a crash.self._shutting_down: bool = False- # Text debounce batching (mirrors Telegram adapter pattern).- # WhatsApp often delivers multiple messages in rapid succession- # (e.g. forwarded batches, paste-splits) — without debounce each- # message triggers a separate agent invocation, wasting tokens and- # flooding the user with reply fragments. Default 5s delay /- # 10s split delay are conservative for WhatsApp's delivery cadence.- # Tunable via config.yaml under- # ``gateway.platforms.whatsapp.extra.text_batch_delay_seconds`` /- # ``text_batch_split_delay_seconds``.- self._text_batch_delay_seconds = self._coerce_float_extra(- "text_batch_delay_seconds", 5.0- )- self._text_batch_split_delay_seconds = self._coerce_float_extra(- "text_batch_split_delay_seconds", 10.0- )+ # Text debounce batching: WhatsApp delivers rapid bursts (forwards,+ # paste-splits); without debounce each triggers a separate agent turn.+ # Tunable via extra.text_batch_delay_seconds / text_batch_split_delay_seconds.+ self._text_batch_delay_seconds = self._coerce_float_extra("text_batch_delay_seconds", 5.0)+ self._text_batch_split_delay_seconds = self._coerce_float_extra("text_batch_split_delay_seconds", 10.0)self._pending_text_batches: Dict[str, MessageEvent] = {}self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}def _coerce_float_extra(self, key: str, default: float) -> float:- """Read a float from ``config.extra``, guarding against bad/non-finite values.-- The result is fed directly to ``asyncio.sleep()``, so NaN/Inf and- unparseable values fall back to ``default``.- """+ """Read a float from ``config.extra``; NaN/Inf/negative/unparseable → ``default`` (fed to asyncio.sleep)."""import math-value = self.config.extra.get(key) if getattr(self.config, "extra", None) else Noneif value is None:return float(default)@@ -546,12 +395,187 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return float(default)return parsed- async def connect(self, *, is_reconnect: bool = False) -> bool:- """- Start the WhatsApp bridge.-- This launches the Node.js bridge process and waits for it to be ready.+ # ── bridge lifecycle ─────────────────────────────────────────────++ def _bridge_url(self, path: str) -> str:+ return f"http://127.0.0.1:{self._bridge_port}/{path}"++ async def _probe_bridge_health(self) -> tuple[bool, Any]:+ """GET /health with a fresh session. Returns ``(http_200, json)``; a 200 with+ an unparseable body yields ``(True, None)``. Connection errors propagate."""+ import aiohttp+ async with aiohttp.ClientSession() as session:+ async with session.get(self._bridge_url("health"), timeout=aiohttp.ClientTimeout(total=2)) as resp:+ if resp.status != 200:+ return False, None+ try:+ return True, await resp.json()+ except Exception:+ return True, None++ def _ensure_bridge_deps(self, bridge_dir: Path) -> bool:+ """npm install when node_modules is missing OR package.json changed since the+ last install (stamp file holds the package.json hash). False = fatal error set."""+ _pkg_json = bridge_dir / "package.json"+ _dep_stamp = bridge_dir / "node_modules" / ".hermes-pkg-hash"+ _pkg_hash = _file_content_hash(_pkg_json)+ _deps_fresh = False+ if (bridge_dir / "node_modules").exists():+ try:+ _deps_fresh = (_dep_stamp.read_text(encoding="utf-8").strip() == _pkg_hash) and bool(_pkg_hash)+ except OSError:+ _deps_fresh = False+ if _deps_fresh:+ return True+ print(f"[{self.name}] Installing WhatsApp bridge dependencies...")+ # Hermes-managed portable Node's npm.cmd first (Windows), then PATH.+ _npm_bin = find_node_executable("npm") or "npm"+ try:+ # Default 300s accommodates slow systems like an Unraid NAS.+ npm_install_timeout = env_int("WHATSAPP_NPM_INSTALL_TIMEOUT", 300)+ install_result = subprocess.run(+ [_npm_bin, "install", "--silent"],+ cwd=str(bridge_dir), timeout=npm_install_timeout, env=with_hermes_node_path(), **_RUN_TEXT,+ )+ if install_result.returncode != 0:+ print(f"[{self.name}] npm install failed: {install_result.stderr}")+ self._set_fatal_error(+ "whatsapp_npm_install_failed",+ f"WhatsApp bridge npm install failed. Run `cd {bridge_dir} && {_npm_bin} install` manually, then restart `hermes gateway`.",+ retryable=False,+ )+ return False+ print(f"[{self.name}] Dependencies installed")+ if _pkg_hash:+ try:+ _dep_stamp.write_text(_pkg_hash, encoding="utf-8")+ except OSError:+ pass # Stamp is an optimization; install still succeeded+ except Exception as e:+ print(f"[{self.name}] Failed to install dependencies: {e}")+ self._set_fatal_error(+ "whatsapp_npm_install_failed",+ f"WhatsApp bridge npm install failed ({e}). Run `cd {bridge_dir} && {_npm_bin} install` manually, then restart `hermes gateway`.",+ retryable=False,+ )+ return False+ return True++ def _attach_to_bridge(self, managed_process) -> None:+ import aiohttp+ self._bridge_process = managed_process+ self._http_session = aiohttp.ClientSession()+ self._poll_task = asyncio.create_task(self._poll_messages())++ async def _reuse_running_bridge(self, bridge_path: Path) -> bool:+ """Adopt an already-connected bridge if it serves the on-disk bridge.js and+ the same read-receipt config; otherwise report why it will be restarted.++ A long-lived bridge survives gateway restarts AND `hermes update`, so a+ hash mismatch (or no ``scriptHash`` at all) is stale by definition."""+ try:+ ok, data = await self._probe_bridge_health()+ if ok and data is not None:+ bridge_status = data.get("status", "unknown")+ if bridge_status == "connected":+ running_hash = data.get("scriptHash", "")+ disk_hash = _file_content_hash(bridge_path)+ running_read_receipts = bool(data.get("sendReadReceipts", False))+ config_matches = running_read_receipts == self._send_read_receipts+ if running_hash and disk_hash and running_hash == disk_hash and config_matches:+ print(f"[{self.name}] Using existing bridge (status: {bridge_status})")+ self._mark_connected()+ self._attach_to_bridge(None) # Not managed by us+ self._wire_plugin_handlers(None)+ return True+ stale_reason = (+ f"running={running_hash or 'unversioned'}, disk={disk_hash}"+ if running_hash != disk_hash+ else "send_read_receipts config changed"+ )+ print(f"[{self.name}] Running bridge is stale ({stale_reason}), restarting")+ else:+ print(f"[{self.name}] Bridge found but not connected (status: {bridge_status}), restarting")+ except Exception:+ pass # Bridge not running, start a new one+ return False++ def _bridge_env(self) -> dict:+ """Subprocess env: profile-resolved WHATSAPP_* values + profile-aware cache dirs."""+ # with_hermes_node_path() copies os.environ when called with no arg.+ bridge_env = with_hermes_node_path()+ if self._reply_prefix is not None:+ bridge_env["WHATSAPP_REPLY_PREFIX"] = self._reply_prefix+ bridge_env["WHATSAPP_SEND_READ_RECEIPTS"] = "true" if self._send_read_receipts else "false"+ _profile_wa_mode = _wenv("WHATSAPP_MODE", "self-chat")+ if _profile_wa_mode:+ bridge_env["WHATSAPP_MODE"] = _profile_wa_mode+ for _key in _BRIDGE_PASSTHROUGH_ENV:+ _v = _wenv(_key)+ if _v:+ bridge_env[_key] = _v+ # Without these the bridge hardcodes ~/.hermes/{image,audio,document}_cache,+ # which diverges under HERMES_HOME overrides, profiles, and the cache/ layout.+ from gateway.platforms.base import (+ get_audio_cache_dir as _get_audio_dir,+ get_document_cache_dir as _get_doc_dir,+ get_image_cache_dir as _get_img_dir,+ )+ bridge_env["HERMES_IMAGE_CACHE_DIR"] = str(_get_img_dir())+ bridge_env["HERMES_AUDIO_CACHE_DIR"] = str(_get_audio_dir())+ bridge_env["HERMES_DOCUMENT_CACHE_DIR"] = str(_get_doc_dir())+ return bridge_env++ def _bridge_died(self, detail: str) -> bool:+ print(f"[{self.name}] {detail}")+ print(f"[{self.name}] Check log: {self._bridge_log}")+ self._close_bridge_log()+ return False++ async def _poll_bridge_health(self, died_msg: str) -> tuple[Optional[bool], bool, dict]:+ """Poll /health up to 15×1s. Returns ``(connected, http_ready, data)``; ``connected``+ is False when the process died (already reported), None when time ran out."""+ http_ready = False+ data: dict = {}+ for attempt in range(15):+ await asyncio.sleep(1)+ if self._bridge_process.poll() is not None:+ return self._bridge_died(died_msg.format(code=self._bridge_process.returncode)), http_ready, data+ try:+ ok, d = await self._probe_bridge_health()+ if ok:+ http_ready = True+ if d is not None:+ data = d+ if data.get("status") == "connected":+ print(f"[{self.name}] Bridge ready (status: connected)")+ return True, http_ready, data+ except Exception:+ continue+ return None, http_ready, data++ async def _wait_for_bridge(self) -> bool:+ """Phase 1: HTTP server up (≤15s). Phase 2: WhatsApp ``status: connected`` (≤15s more;+ proceeds with a warning if still connecting — the bridge may auto-reconnect later)."""+ connected, http_ready, data = await self._poll_bridge_health("Bridge process died (exit code {code})")+ if connected is False:+ return False+ if not http_ready:+ return self._bridge_died("Bridge HTTP server did not start in 15s")+ if data.get("status") != "connected":+ print(f"[{self.name}] Bridge HTTP ready, waiting for WhatsApp connection...")+ connected, _, _ = await self._poll_bridge_health("Bridge process died during connection")+ if connected is False:+ return False+ if connected is None:+ print(f"[{self.name}] ⚠ WhatsApp not connected after 30s")+ print(f"[{self.name}] Bridge log: {self._bridge_log}")+ print(f"[{self.name}] If session expired, re-pair: hermes whatsapp")+ return True++ async def connect(self, *, is_reconnect: bool = False) -> bool:+ """Start (or adopt) the Node.js bridge and wait for it to be ready."""if not check_whatsapp_requirements():logger.warning("[%s] Node.js not found. WhatsApp requires Node.js.", self.name)self._set_fatal_error(@@ -560,7 +584,6 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):retryable=False,)return False-bridge_path = Path(self._bridge_script)if not bridge_path.exists():logger.warning("[%s] Bridge script not found: %s", self.name, bridge_path)@@ -571,13 +594,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):)return False- # Pre-flight: skip the 30s bridge bootstrap entirely if the user- # never finished pairing. Without creds.json the bridge prints- # QR codes to its log file and never reaches status:connected,- # so every gateway restart paid the 30s timeout + queued WhatsApp- # for indefinite retries. Mark non-retryable so the user gets a- # clear pairing message instead of the watcher- # silently hammering an unconfigured platform.+ # Without creds.json the bridge only prints QR codes and never connects, so+ # every restart would pay the 30s timeout; fail non-retryable with a clear message.creds_path = self._session_path / "creds.json"if not creds_path.exists():logger.warning(@@ -592,10 +610,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):retryable=False,)return False-logger.info("[%s] Bridge found at %s", self.name, bridge_path)-- # Acquire scoped lock to prevent duplicate sessionslock_acquired = Falsetry:if not self._acquire_platform_lock('whatsapp-session', str(self._session_path), 'WhatsApp session'):@@ -603,177 +618,23 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):lock_acquired = Trueexcept Exception as e:logger.warning("[%s] Could not acquire session lock (non-fatal): %s", self.name, e)-try:- # Auto-install npm dependencies when node_modules is missing OR- # package.json changed since the last install (e.g. after- # `hermes update` bumps the Baileys pin). The stamp file records- # the package.json hash of the last successful install.- bridge_dir = bridge_path.parent- _pkg_json = bridge_dir / "package.json"- _dep_stamp = bridge_dir / "node_modules" / ".hermes-pkg-hash"- _pkg_hash = _file_content_hash(_pkg_json)- _deps_fresh = False- if (bridge_dir / "node_modules").exists():- try:- _deps_fresh = (- _dep_stamp.read_text(encoding="utf-8").strip() == _pkg_hash- ) and bool(_pkg_hash)- except OSError:- _deps_fresh = False- if not _deps_fresh:- print(f"[{self.name}] Installing WhatsApp bridge dependencies...")- # Resolve npm path so Windows uses npm.cmd from the- # Hermes-managed portable Node before falling back to PATH.- _npm_bin = find_node_executable("npm") or "npm"- try:- # Read timeout from environment variable, default to 300 seconds (5 minutes)- # to accommodate slower systems like Unraid NAS- npm_install_timeout = env_int("WHATSAPP_NPM_INSTALL_TIMEOUT", 300)- install_result = subprocess.run(- [_npm_bin, "install", "--silent"],- cwd=str(bridge_dir),- capture_output=True,- text=True, encoding='utf-8', errors='replace',- timeout=npm_install_timeout,- env=with_hermes_node_path(),- )- if install_result.returncode != 0:- print(f"[{self.name}] npm install failed: {install_result.stderr}")- self._set_fatal_error(- "whatsapp_npm_install_failed",- f"WhatsApp bridge npm install failed. Run `cd {bridge_dir} && {_npm_bin} install` manually, then restart `hermes gateway`.",- retryable=False,- )- return False- print(f"[{self.name}] Dependencies installed")- if _pkg_hash:- try:- _dep_stamp.write_text(_pkg_hash, encoding="utf-8")- except OSError:- pass # Stamp is an optimization; install still succeeded- except Exception as e:- print(f"[{self.name}] Failed to install dependencies: {e}")- self._set_fatal_error(- "whatsapp_npm_install_failed",- f"WhatsApp bridge npm install failed ({e}). Run `cd {bridge_dir} && {_npm_bin} install` manually, then restart `hermes gateway`.",- retryable=False,- )- return False-- # Ensure session directory exists+ if not self._ensure_bridge_deps(bridge_path.parent):+ return Falseself._session_path.mkdir(parents=True, exist_ok=True)-- # Check if bridge is already running and connected- import aiohttp- try:- async with aiohttp.ClientSession() as session:- async with session.get(- f"http://127.0.0.1:{self._bridge_port}/health",- timeout=aiohttp.ClientTimeout(total=2)- ) as resp:- if resp.status == 200:- data = await resp.json()- bridge_status = data.get("status", "unknown")- if bridge_status == "connected":- # Staleness handshake: only reuse a running- # bridge if it is serving the same bridge.js- # that is on disk right now. A long-lived- # bridge survives gateway restarts AND- # `hermes update`, so without this check it- # keeps serving pre-update code forever- # (e.g. no inbound media download). Old- # bridges that don't report scriptHash are- # treated as stale by definition.- running_hash = data.get("scriptHash", "")- disk_hash = _file_content_hash(bridge_path)- running_read_receipts = bool(data.get("sendReadReceipts", False))- config_matches = running_read_receipts == self._send_read_receipts- if (- running_hash- and disk_hash- and running_hash == disk_hash- and config_matches- ):- print(f"[{self.name}] Using existing bridge (status: {bridge_status})")- self._mark_connected()- self._bridge_process = None # Not managed by us- self._http_session = aiohttp.ClientSession()- self._poll_task = asyncio.create_task(self._poll_messages())- # Plugin-registered native handlers.- self._wire_plugin_handlers(None)- return True- stale_reason = (- f"running={running_hash or 'unversioned'}, disk={disk_hash}"- if running_hash != disk_hash- else "send_read_receipts config changed"- )- print(f"[{self.name}] Running bridge is stale ({stale_reason}), restarting")- else:- print(f"[{self.name}] Bridge found but not connected (status: {bridge_status}), restarting")- except Exception:- pass # Bridge not running, start a new one-- # Kill any orphaned bridge from a previous gateway run+ if await self._reuse_running_bridge(bridge_path):+ return True_kill_stale_bridge_by_pidfile(self._session_path)_kill_port_process(self._bridge_port)await asyncio.sleep(1)-- # Start the bridge process in its own process group.- # Route output to a log file so QR codes, errors, and reconnection++ # Bridge output goes to a log file so QR codes, errors, and reconnection# messages are preserved for troubleshooting.whatsapp_mode = _wenv("WHATSAPP_MODE", "self-chat")self._bridge_log = self._session_path.parent / "bridge.log"bridge_log_fh = open(self._bridge_log, "a", encoding="utf-8")self._bridge_log_fh = bridge_log_fh-- # Build bridge subprocess environment.- # Pass WHATSAPP_REPLY_PREFIX from config.yaml so the Node bridge- # can use it without the user needing to set a separate env var.- # with_hermes_node_path() copies os.environ when called with no arg.- bridge_env = with_hermes_node_path()- if self._reply_prefix is not None:- bridge_env["WHATSAPP_REPLY_PREFIX"] = self._reply_prefix- bridge_env["WHATSAPP_SEND_READ_RECEIPTS"] = (- "true" if self._send_read_receipts else "false"- )- # Under multiplexing, the bridge subprocess runs with a copy of- # os.environ that does NOT contain the secondary profile's .env- # vars. Inject the resolved WHATSAPP_* values so the Node bridge- # (which reads process.env.WHATSAPP_MODE etc.) sees the profile's- # own configuration instead of falling back to self-chat defaults.- _profile_wa_mode = _wenv("WHATSAPP_MODE", "self-chat")- if _profile_wa_mode:- bridge_env["WHATSAPP_MODE"] = _profile_wa_mode- for _key in (- "WHATSAPP_ALLOWED_USERS", "WHATSAPP_ALLOW_FROM",- "WHATSAPP_DM_POLICY", "WHATSAPP_GROUP_POLICY",- "WHATSAPP_GROUP_ALLOWED_USERS", "WHATSAPP_GROUP_ALLOW_FROM",- "WHATSAPP_REQUIRE_MENTION", "WHATSAPP_MENTION_PATTERNS",- "WHATSAPP_FREE_RESPONSE_CHATS",- # Full set bridge.js consumes -- without these a secondary- # profile's bridge silently reverts to defaults for debug,- # forwarding, prefixes, and send pacing.- "WHATSAPP_DEBUG", "WHATSAPP_FORWARD_OWNER_MESSAGES",- "WHATSAPP_REPLY_PREFIX", "WHATSAPP_MAX_MESSAGE_LENGTH",- "WHATSAPP_CHUNK_DELAY_MS", "WHATSAPP_SEND_TIMEOUT_MS",- ):- _v = _wenv(_key)- if _v:- bridge_env[_key] = _v- # Pass the profile-aware cache directories so the bridge writes- # media where the Python side reads it. Without these the bridge- # hardcodes ~/.hermes/{image,audio,document}_cache, which diverges- # under HERMES_HOME overrides, profiles, and the new cache/ layout.- from gateway.platforms.base import (- get_audio_cache_dir as _get_audio_dir,- get_document_cache_dir as _get_doc_dir,- get_image_cache_dir as _get_img_dir,- )- bridge_env["HERMES_IMAGE_CACHE_DIR"] = str(_get_img_dir())- bridge_env["HERMES_AUDIO_CACHE_DIR"] = str(_get_audio_dir())- bridge_env["HERMES_DOCUMENT_CACHE_DIR"] = str(_get_doc_dir())-+ bridge_env = self._bridge_env()self._bridge_process = subprocess.Popen([find_node_executable("node") or "node",@@ -788,84 +649,13 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):**windows_detach_popen_kwargs(),)_write_bridge_pidfile(self._session_path, self._bridge_process.pid)-- # Wait for the bridge to connect to WhatsApp.- # Phase 1: wait for the HTTP server to come up (up to 15s).- # Phase 2: wait for WhatsApp status: connected (up to 15s more).- import aiohttp- http_ready = False- data = {}- for attempt in range(15):- await asyncio.sleep(1)- if self._bridge_process.poll() is not None:- print(f"[{self.name}] Bridge process died (exit code {self._bridge_process.returncode})")- print(f"[{self.name}] Check log: {self._bridge_log}")- self._close_bridge_log()- return False- try:- async with aiohttp.ClientSession() as session:- async with session.get(- f"http://127.0.0.1:{self._bridge_port}/health",- timeout=aiohttp.ClientTimeout(total=2)- ) as resp:- if resp.status == 200:- http_ready = True- data = await resp.json()- if data.get("status") == "connected":- print(f"[{self.name}] Bridge ready (status: connected)")- break- except Exception:- continue-- if not http_ready:- print(f"[{self.name}] Bridge HTTP server did not start in 15s")- print(f"[{self.name}] Check log: {self._bridge_log}")- self._close_bridge_log()+ if not await self._wait_for_bridge():return False-- # Phase 2: HTTP is up but WhatsApp may still be connecting.- # Give it more time to authenticate with saved credentials.- if data.get("status") != "connected":- print(f"[{self.name}] Bridge HTTP ready, waiting for WhatsApp connection...")- for attempt in range(15):- await asyncio.sleep(1)- if self._bridge_process.poll() is not None:- print(f"[{self.name}] Bridge process died during connection")- print(f"[{self.name}] Check log: {self._bridge_log}")- self._close_bridge_log()- return False- try:- async with aiohttp.ClientSession() as session:- async with session.get(- f"http://127.0.0.1:{self._bridge_port}/health",- timeout=aiohttp.ClientTimeout(total=2)- ) as resp:- if resp.status == 200:- data = await resp.json()- if data.get("status") == "connected":- print(f"[{self.name}] Bridge ready (status: connected)")- break- except Exception:- continue- else:- # Still not connected — warn but proceed (bridge may- # auto-reconnect later, e.g. after a code 515 restart).- print(f"[{self.name}] ⚠ WhatsApp not connected after 30s")- print(f"[{self.name}] Bridge log: {self._bridge_log}")- print(f"[{self.name}] If session expired, re-pair: hermes whatsapp")-- # Create a persistent HTTP session for all bridge communication- self._http_session = aiohttp.ClientSession()-- # Start message polling task- self._poll_task = asyncio.create_task(self._poll_messages())-+ self._attach_to_bridge(self._bridge_process)self._mark_connected()print(f"[{self.name}] Bridge started on port {self._bridge_port}")- # Plugin-registered native handlers.self._wire_plugin_handlers(None)return True-except Exception as e:logger.error("[%s] Failed to start bridge: %s", self.name, e, exc_info=True)return False@@ -874,7 +664,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if lock_acquired:self._release_platform_lock()self._close_bridge_log()-+def _close_bridge_log(self) -> None:"""Close the bridge log file handle if open."""if self._bridge_log_fh:@@ -888,26 +678,14 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):"""Return a fatal error message if the managed bridge child exited."""if self._bridge_process is None:return None-returncode = self._bridge_process.poll()if returncode is None:return None- # Planned shutdown: disconnect() sets _shutting_down before it sends- # SIGTERM to the bridge, so a returncode of -15 (SIGTERM), -2 (SIGINT),- # or 0 (clean exit) at that point is expected, not a crash. Treat it- # as informational and skip the fatal-error path.- # getattr-with-default keeps tests that construct the adapter via- # ``WhatsAppAdapter.__new__`` (bypassing __init__) working without- # every _make_adapter() helper having to seed the attribute.+ # getattr-with-default: tests build the adapter via ``__new__`` without __init__.if getattr(self, "_shutting_down", False) and returncode in {0, -2, -15}:- logger.info(- "[%s] Bridge exited during shutdown (code %d).",- self.name,- returncode,- )+ logger.info("[%s] Bridge exited during shutdown (code %d).", self.name, returncode)return None-message = f"WhatsApp bridge process exited unexpectedly (code {returncode})."if not self.has_fatal_error:logger.error("[%s] %s", self.name, message)@@ -918,9 +696,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):async def disconnect(self) -> None:"""Stop the WhatsApp bridge and clean up any orphaned processes."""- # Flip the shutdown flag BEFORE signalling the child so the exit-check- # path (which runs from other tasks like send() and the poll loop)- # doesn't race us and report the intentional termination as fatal.+ # Flip BEFORE signalling so the exit-check path (send(), poll loop) doesn't+ # report the intentional termination as fatal.self._shutting_down = Trueif self._bridge_process:try:@@ -937,16 +714,11 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):except Exception as e:print(f"[{self.name}] Error stopping bridge: {e}")else:- # Bridge was not started by us, don't kill itprint(f"[{self.name}] Disconnecting (external bridge left running)")-- # Clean up PID filetry:(self._session_path / "bridge.pid").unlink(missing_ok=True)except OSError:pass-- # Cancel the poll task explicitlyif self._poll_task and not self._poll_task.done():self._poll_task.cancel()try:@@ -954,19 +726,38 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):except (asyncio.CancelledError, Exception):passself._poll_task = None-- # Close the persistent HTTP sessionif self._http_session and not self._http_session.closed:await self._http_session.close()self._http_session = None-self._release_platform_lock()-self._mark_disconnected()self._bridge_process = Noneself._close_bridge_log()print(f"[{self.name}] Disconnected")-++ # ── outbound ─────────────────────────────────────────────────────++ async def _bridge_unavailable(self) -> Optional[str]:+ """Error string when the bridge can't take a request, else None."""+ if not self._running or not self._http_session:+ return "Not connected"+ return await self._check_managed_bridge_exit() or None++ async def _post_bridge_message(self, path: str, payload: Dict[str, Any], *, timeout: float) -> SendResult:+ """POST to the bridge; 200 → SendResult(messageId, raw_response), else the error text."""+ try:+ import aiohttp+ async with self._http_session.post(+ self._bridge_url(path), json=payload, timeout=aiohttp.ClientTimeout(total=timeout),+ ) as resp:+ if resp.status == 200:+ data = await resp.json()+ return SendResult(success=True, message_id=data.get("messageId"), raw_response=data)+ error = await resp.text()+ return SendResult(success=False, error=error)+ except Exception as e:+ return SendResult(success=False, error=str(e))+async def send(self,chat_id: str,@@ -974,59 +765,32 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None) -> SendResult:- """Send a message via the WhatsApp bridge.-- Formats markdown for WhatsApp, splits long messages into chunks- that preserve code block boundaries, and sends each chunk sequentially.- """- if not self._running or not self._http_session:- return SendResult(success=False, error="Not connected")- bridge_exit = await self._check_managed_bridge_exit()- if bridge_exit:- return SendResult(success=False, error=bridge_exit)-+ """Format markdown for WhatsApp, chunk preserving code blocks, send sequentially."""+ unavailable = await self._bridge_unavailable()+ if unavailable:+ return SendResult(success=False, error=unavailable)if not content or not content.strip():return SendResult(success=True, message_id=None)-chat_id = to_whatsapp_jid(chat_id)-try:- import aiohttp-- # Format and chunk the messageformatted = self.format_message(content)chunks = self.truncate_message(formatted, self._outgoing_chunk_limit())-sent_message_ids: list[str] = []last_message_id = Nonefor idx, chunk in enumerate(chunks):- payload: Dict[str, Any] = {- "chatId": chat_id,- "message": chunk,- }+ payload: Dict[str, Any] = {"chatId": chat_id, "message": chunk}if reply_to and idx == 0:- # Only reply-to on the first text chunk, even if the bridge- # response omits a parseable message id.+ # Reply-to on the first chunk only.payload["replyTo"] = reply_to-- async with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/send",- json=payload,- timeout=aiohttp.ClientTimeout(total=30)- ) as resp:- if resp.status == 200:- data = await resp.json()- last_message_id = data.get("messageId")- if last_message_id:- sent_message_ids.append(str(last_message_id))- else:- error = await resp.text()- return SendResult(success=False, error=error)-+ result = await self._post_bridge_message("send", payload, timeout=30)+ if not result.success:+ return SendResult(success=False, error=result.error)+ last_message_id = result.message_id+ if last_message_id:+ sent_message_ids.append(str(last_message_id))# Small delay between chunks to avoid rate limitingif len(chunks) > 1:await asyncio.sleep(0.3)-return SendResult(success=True,message_id=last_message_id,@@ -1037,234 +801,107 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return SendResult(success=False, error=str(e))async def edit_message(- self,- chat_id: str,- message_id: str,- content: str,- *,- finalize: bool = False,+ self, chat_id: str, message_id: str, content: str, *, finalize: bool = False,) -> SendResult:"""Edit a previously sent message via the WhatsApp bridge."""- if not self._running or not self._http_session:- return SendResult(success=False, error="Not connected")- bridge_exit = await self._check_managed_bridge_exit()- if bridge_exit:- return SendResult(success=False, error=bridge_exit)+ unavailable = await self._bridge_unavailable()+ if unavailable:+ return SendResult(success=False, error=unavailable)try:import aiohttpasync with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/edit",- json={- "chatId": to_whatsapp_jid(chat_id),- "messageId": message_id,- "message": content,- },+ self._bridge_url("edit"),+ json={"chatId": to_whatsapp_jid(chat_id), "messageId": message_id, "message": content},timeout=aiohttp.ClientTimeout(total=15)) as resp:if resp.status == 200:return SendResult(success=True, message_id=message_id)- else:- error = await resp.text()- return SendResult(success=False, error=error)+ error = await resp.text()+ return SendResult(success=False, error=error)except Exception as e:return SendResult(success=False, error=str(e))async def _send_media_to_bridge(- self,- chat_id: str,- file_path: str,- media_type: str,- caption: Optional[str] = None,+ self, chat_id: str, file_path: str, media_type: str, caption: Optional[str] = None,file_name: Optional[str] = None,) -> SendResult:"""Send any media file via bridge /send-media endpoint."""- if not self._running or not self._http_session:- return SendResult(success=False, error="Not connected")- bridge_exit = await self._check_managed_bridge_exit()- if bridge_exit:- return SendResult(success=False, error=bridge_exit)- try:- import aiohttp-- if not os.path.exists(file_path):- return SendResult(success=False, error=f"File not found: {file_path}")-- payload: Dict[str, Any] = {- "chatId": to_whatsapp_jid(chat_id),- "filePath": file_path,- "mediaType": media_type,- }- if caption:- payload["caption"] = caption- if file_name:- payload["fileName"] = file_name-- async with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/send-media",- json=payload,- timeout=aiohttp.ClientTimeout(total=120),- ) as resp:- if resp.status == 200:- data = await resp.json()- return SendResult(- success=True,- message_id=data.get("messageId"),- raw_response=data,- )- else:- error = await resp.text()- return SendResult(success=False, error=error)-- except Exception as e:- return SendResult(success=False, error=str(e))+ unavailable = await self._bridge_unavailable()+ if unavailable:+ return SendResult(success=False, error=unavailable)+ if not os.path.exists(file_path):+ return SendResult(success=False, error=f"File not found: {file_path}")+ payload: Dict[str, Any] = {"chatId": to_whatsapp_jid(chat_id), "filePath": file_path, "mediaType": media_type}+ if caption:+ payload["caption"] = caption+ if file_name:+ payload["fileName"] = file_name+ return await self._post_bridge_message("send-media", payload, timeout=120)async def send_poll(- self,- chat_id: str,- question: str,- options: list[str],- *,- selectable_count: int = 1,+ self, chat_id: str, question: str, options: list[str], *, selectable_count: int = 1,) -> SendResult:- """Send a native WhatsApp poll via the Baileys bridge.-- This is a low-level transport primitive only. Gateway approval UX must- remain gateway-owned and add text fallback plus explicit confirmation- semantics before approval prompts are ever mapped onto polls.- """- if not self._running or not self._http_session:- return SendResult(success=False, error="Not connected")- bridge_exit = await self._check_managed_bridge_exit()- if bridge_exit:- return SendResult(success=False, error=bridge_exit)- try:- import aiohttp-- payload: Dict[str, Any] = {- "chatId": to_whatsapp_jid(chat_id),- "question": question,- "options": list(options or []),- "selectableCount": selectable_count,- }- async with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/send-poll",- json=payload,- timeout=aiohttp.ClientTimeout(total=30),- ) as resp:- if resp.status == 200:- data = await resp.json()- return SendResult(- success=True,- message_id=data.get("messageId"),- raw_response=data,- )- error = await resp.text()- return SendResult(success=False, error=error)- except Exception as e:- return SendResult(success=False, error=str(e))+ """Native WhatsApp poll (low-level transport primitive; approval UX stays gateway-owned)."""+ unavailable = await self._bridge_unavailable()+ if unavailable:+ return SendResult(success=False, error=unavailable)+ payload: Dict[str, Any] = {+ "chatId": to_whatsapp_jid(chat_id),+ "question": question,+ "options": list(options or []),+ "selectableCount": selectable_count,+ }+ return await self._post_bridge_message("send-poll", payload, timeout=30)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,+ self, chat_id: str, question: str, choices: Optional[list], clarify_id: str,+ session_key: str, metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- """Render multiple-choice clarify as a native WhatsApp poll.-- The gateway registers the pending clarify before calling this method.- When Baileys later emits a poll_update with the selected option as- message text, the normal clarify text-intercept resolves the pending- question and the blocked agent continues. Open-ended clarifies use the- text fallback so the user's next typed message is captured.- """+ """Multiple-choice clarify as a native poll; Baileys emits the selected option+ as message text, which the normal clarify text-intercept resolves. Open-ended+ (or failed poll) falls back to the text prompt."""clean_choices = [str(choice).strip() for choice in (choices or []) if str(choice).strip()]if 2 <= len(clean_choices) <= 12:- result = await self.send_poll(- chat_id,- str(question or "").strip(),- clean_choices,- selectable_count=1,- )+ result = await self.send_poll(chat_id, str(question or "").strip(), clean_choices, selectable_count=1)if result.success:return resultlogger.warning("[%s] Native WhatsApp clarify poll failed; falling back to text: %s",- self.name,- result.error,+ self.name, result.error,)return await super().send_clarify(- chat_id=chat_id,- question=question,- choices=choices,- clarify_id=clarify_id,- session_key=session_key,- metadata=metadata,+ chat_id=chat_id, question=question, choices=choices,+ clarify_id=clarify_id, session_key=session_key, metadata=metadata,)async def send_location(- self,- chat_id: str,- latitude: float,- longitude: float,- *,- name: Optional[str] = None,- address: Optional[str] = None,- reply_to: Optional[str] = None,+ self, chat_id: str, latitude: float, longitude: float, *, name: Optional[str] = None,+ address: Optional[str] = None, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,) -> SendResult:"""Send a native WhatsApp location pin via the Baileys bridge."""- if not self._running or not self._http_session:- return SendResult(success=False, error="Not connected")- bridge_exit = await self._check_managed_bridge_exit()- if bridge_exit:- return SendResult(success=False, error=bridge_exit)+ unavailable = await self._bridge_unavailable()+ if unavailable:+ return SendResult(success=False, error=unavailable)try:- import aiohttp-payload: Dict[str, Any] = {"chatId": to_whatsapp_jid(chat_id),"latitude": float(latitude),"longitude": float(longitude),}- if name:- payload["name"] = name- if address:- payload["address"] = address- async with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/send-location",- json=payload,- timeout=aiohttp.ClientTimeout(total=30),- ) as resp:- if resp.status == 200:- data = await resp.json()- return SendResult(- success=True,- message_id=data.get("messageId"),- raw_response=data,- )- error = await resp.text()- return SendResult(success=False, error=error)except Exception as e:return SendResult(success=False, error=str(e))+ if name:+ payload["name"] = name+ if address:+ payload["address"] = address+ return await self._post_bridge_message("send-location", payload, timeout=30)async def send_image(- self,- chat_id: str,- image_url: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None,+ self, chat_id: str, image_url: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,) -> SendResult:- """Download image URL to cache, send natively via bridge.-- ``metadata`` is accepted to honor the base-class contract — the- batch sender ``send_multiple_images`` passes it through to every- send path. The bridge media call doesn't use it, matching the- sibling overrides (send_video / send_voice / send_document).- """+ """Download image URL to cache, send natively via bridge (``metadata`` honors the base contract)."""try:local_path = await cache_image_from_url(image_url)return await self._send_media_to_bridge(chat_id, local_path, "image", caption)@@ -1272,87 +909,59 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return await super().send_image(chat_id, image_url, caption, reply_to, metadata)async def send_image_file(- self,- chat_id: str,- image_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, image_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send a local image file natively via bridge."""return await self._send_media_to_bridge(chat_id, image_path, "image", caption)async def send_video(- self,- chat_id: str,- video_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, video_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send a video natively via bridge — plays inline in WhatsApp."""return await self._send_media_to_bridge(chat_id, video_path, "video", caption)async def send_voice(- self,- chat_id: str,- audio_path: str,- caption: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, audio_path: str, caption: Optional[str] = None,+ reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send an audio file as a WhatsApp voice message via bridge."""return await self._send_media_to_bridge(chat_id, audio_path, "audio", caption)async def send_document(- self,- chat_id: str,- file_path: str,- caption: Optional[str] = None,- file_name: Optional[str] = None,- reply_to: Optional[str] = None,- **kwargs,+ self, chat_id: str, file_path: str, caption: Optional[str] = None,+ file_name: Optional[str] = None, reply_to: Optional[str] = None, **kwargs,) -> SendResult:- """Send a document/file as a downloadable attachment via bridge."""return await self._send_media_to_bridge(- chat_id, file_path, "document", caption,- file_name or os.path.basename(file_path),+ chat_id, file_path, "document", caption, file_name or os.path.basename(file_path),)async def send_typing(self, chat_id: str, metadata=None) -> None:- """Send typing indicator via bridge."""- if not self._running or not self._http_session:- return- if await self._check_managed_bridge_exit():+ """Send typing indicator via bridge (failures ignored)."""+ if await self._bridge_unavailable():return-try:import aiohttp- # Must wrap in `async with` — a bare `await session.post(...)`- # leaves the response object alive until GC, holding its TCP- # socket in CLOSE_WAIT. See #18451.+ # ``async with`` — a bare ``await session.post(...)`` leaves the response+ # alive until GC, holding its socket in CLOSE_WAIT.async with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/typing",+ self._bridge_url("typing"),json={"chatId": to_whatsapp_jid(chat_id)},timeout=aiohttp.ClientTimeout(total=5)):passexcept Exception:- pass # Ignore typing indicator failures-+ pass+async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:"""Get information about a WhatsApp chat."""if not self._running or not self._http_session:return {"name": "Unknown", "type": "dm"}if await self._check_managed_bridge_exit():return {"name": chat_id, "type": "dm"}-try:import aiohttp-async with self._http_session.get(- f"http://127.0.0.1:{self._bridge_port}/chat/{to_whatsapp_jid(chat_id)}",+ self._bridge_url(f"chat/{to_whatsapp_jid(chat_id)}"),timeout=aiohttp.ClientTimeout(total=10)) as resp:if resp.status == 200:@@ -1364,13 +973,13 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):}except Exception as e:logger.debug("Could not get WhatsApp chat info for %s: %s", chat_id, e)-return {"name": chat_id, "type": "dm"}-++ # ── inbound ──────────────────────────────────────────────────────+async def _poll_messages(self) -> None:"""Poll the bridge for incoming messages."""import aiohttp-while self._running:if not self._http_session:break@@ -1380,17 +989,14 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):breaktry:async with self._http_session.get(- f"http://127.0.0.1:{self._bridge_port}/messages",- timeout=aiohttp.ClientTimeout(total=30)+ self._bridge_url("messages"), timeout=aiohttp.ClientTimeout(total=30)) as resp:if resp.status == 200:messages = await resp.json()for msg_data in messages:event = await self._build_message_event(msg_data)if event:- # Fire-and-forget: a slow bridge /read must not- # delay message dispatch (matches BlueBubbles- # asyncio.create_task pattern for mark_read).+ # Fire-and-forget: a slow bridge /read must not delay dispatch.asyncio.create_task(self._send_read_receipt(msg_data))if event.message_type == MessageType.TEXT:self._enqueue_text_event(event)@@ -1405,7 +1011,6 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):breakprint(f"[{self.name}] Poll error: {e}")await asyncio.sleep(5)-await asyncio.sleep(1) # Poll intervalasync def _send_read_receipt(self, data: Dict[str, Any]) -> None:@@ -1417,18 +1022,11 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):returntry:import aiohttp-async with self._http_session.post(- f"http://127.0.0.1:{self._bridge_port}/read",- json={"key": key},- timeout=aiohttp.ClientTimeout(total=5),+ self._bridge_url("read"), json={"key": key}, timeout=aiohttp.ClientTimeout(total=5),) as resp:if resp.status != 200:- logger.warning(- "[%s] WhatsApp read receipt failed with HTTP %s",- self.name,- resp.status,- )+ logger.warning("[%s] WhatsApp read receipt failed with HTTP %s", self.name, resp.status)except Exception as exc:logger.warning("[%s] WhatsApp read receipt failed: %s", self.name, exc)@@ -1436,44 +1034,6 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):_SPLIT_THRESHOLD = 6000 # WhatsApp supports ~65K chars; generous threshold- def _text_batch_key(self, event: MessageEvent) -> str:- """Session-scoped key for text message batching."""- from gateway.session import build_session_key- return build_session_key(- event.source,- group_sessions_per_user=self.config.extra.get("group_sessions_per_user", True),- thread_sessions_per_user=self.config.extra.get("thread_sessions_per_user", False),- profile=self._session_key_profile(event.source),- )-- def _enqueue_text_event(self, event: MessageEvent) -> None:- """Buffer a text event and reset the flush timer.-- When WhatsApp delivers rapid-fire messages (e.g. forwarded- batches), this concatenates them and waits for a short quiet- period before dispatching the combined message.- """- key = self._text_batch_key(event)- existing = self._pending_text_batches.get(key)- chunk_len = len(event.text or "")- if existing is None:- event._last_chunk_len = chunk_len # type: ignore[attr-defined]- self._pending_text_batches[key] = event- else:- if event.text:- existing.text = f"{existing.text}\n{event.text}" if existing.text else event.text- existing._last_chunk_len = chunk_len # type: ignore[attr-defined]- if event.media_urls:- existing.media_urls.extend(event.media_urls)- existing.media_types.extend(event.media_types)-- prior_task = self._pending_text_batch_tasks.get(key)- if prior_task and not prior_task.done():- prior_task.cancel()- self._pending_text_batch_tasks[key] = asyncio.create_task(- self._flush_text_batch(key)- )-async def _flush_text_batch(self, key: str) -> None:"""Wait for quiet period then dispatch aggregated text."""current_task = asyncio.current_task()@@ -1493,111 +1053,107 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if self._pending_text_batch_tasks.get(key) is current_task:self._pending_text_batch_tasks.pop(key, None)+ @staticmethod+ def _classify_bridge_message(data: Dict[str, Any]) -> MessageType:+ media_type = str(data.get("mediaType", "") or "")+ if media_type in {"location", "live_location"}:+ return MessageType.LOCATION+ if media_type == "sticker":+ return MessageType.STICKER+ if data.get("hasMedia"):+ if "image" in media_type:+ return MessageType.PHOTO+ if "video" in media_type:+ return MessageType.VIDEO+ if "ptt" in media_type: # ptt = WhatsApp voice note+ return MessageType.VOICE+ if "audio" in media_type:+ return MessageType.AUDIO+ return MessageType.DOCUMENT+ return MessageType.TEXT++ async def _collect_bridge_media(+ self, data: Dict[str, Any], msg_type: MessageType+ ) -> tuple[list, list]:+ """Resolve bridge ``mediaUrls`` into ``(cached_urls, media_types)``.++ Remote image/audio URLs are downloaded to the local cache; absolute paths the+ bridge already downloaded are accepted only inside a Hermes cache dir.+ """+ cached_urls = []+ media_types = []+ label = _MEDIA_LABEL.get(msg_type)+ for url in data.get("mediaUrls", []):+ bridge_mime = str(data.get("mime") or "").strip()+ is_http = url.startswith(("http://", "https://"))+ if msg_type == MessageType.DOCUMENT:+ mime = bridge_mime or SUPPORTED_DOCUMENT_TYPES.get(Path(url).suffix.lower(), "application/octet-stream")+ else:+ mime = bridge_mime or _MEDIA_DEFAULT_MIME.get(msg_type, "")+ if is_http and msg_type in {MessageType.PHOTO, MessageType.VOICE, MessageType.AUDIO}:+ cacher, ext = (+ (cache_image_from_url, ".jpg") if msg_type == MessageType.PHOTO else (cache_audio_from_url, ".ogg")+ )+ try:+ cached_path = await cacher(url, ext=ext)+ cached_urls.append(cached_path)+ media_types.append(mime)+ print(f"[{self.name}] Cached user {label}: {cached_path}", flush=True)+ except Exception as e:+ print(f"[{self.name}] Failed to cache {label}: {e}", flush=True)+ cached_urls.append(url)+ media_types.append(mime)+ elif label is not None and os.path.isabs(url):+ if _is_allowed_bridge_path(url):+ cached_urls.append(url)+ media_types.append(mime)+ print(f"[{self.name}] Using bridge-cached {label}: {url}", flush=True)+ else:+ print(f"[{self.name}] Rejected bridge {label} path outside cache dir: {url}", flush=True)+ else:+ cached_urls.append(url)+ media_types.append("unknown")+ return cached_urls, media_types++ def _inject_document_text(self, cached_urls: list, body: str) -> str:+ """Prepend text-readable document contents (≤100KB) so the agent reads them inline."""+ for doc_path in cached_urls:+ if Path(doc_path).suffix.lower() not in _TEXT_INJECT_EXTS:+ continue+ try:+ file_size = Path(doc_path).stat().st_size+ if file_size > _MAX_TEXT_INJECT_BYTES:+ print(f"[{self.name}] Skipping text injection for {doc_path} ({file_size} bytes > {_MAX_TEXT_INJECT_BYTES})", flush=True)+ continue+ content = Path(doc_path).read_text(encoding="utf-8", errors="replace")+ fname = Path(doc_path).name+ # Remove the doc_<hex>_ prefix for display+ display_name = fname+ if "_" in fname:+ parts = fname.split("_", 2)+ if len(parts) >= 3:+ display_name = parts[2]+ injection = f"[Content of {display_name}]:\n{content}"+ body = f"{injection}\n\n{body}" if body else injection+ print(f"[{self.name}] Injected text content from: {doc_path}", flush=True)+ except Exception as e:+ print(f"[{self.name}] Failed to read document text: {e}", flush=True)+ return body+async def _build_message_event(self, data: Dict[str, Any]) -> Optional[MessageEvent]:"""Build a MessageEvent from bridge message data, downloading images to cache."""try:if not self._should_process_message(data):return None-- # Determine message type- msg_type = MessageType.TEXT- media_type = str(data.get("mediaType", "") or "")- if media_type in {"location", "live_location"}:- msg_type = MessageType.LOCATION- elif media_type == "sticker":- msg_type = MessageType.STICKER- elif data.get("hasMedia"):- if "image" in media_type:- msg_type = MessageType.PHOTO- elif "video" in media_type:- msg_type = MessageType.VIDEO- elif "ptt" in media_type: # ptt = WhatsApp voice note- msg_type = MessageType.VOICE- elif "audio" in media_type:- msg_type = MessageType.AUDIO- else:- msg_type = MessageType.DOCUMENT-- # Determine chat type- is_group = data.get("isGroup", False)- chat_type = "group" if is_group else "dm"-- # Build source+ msg_type = self._classify_bridge_message(data)source = self.build_source(chat_id=data.get("chatId", ""),chat_name=data.get("chatName"),- chat_type=chat_type,+ chat_type="group" if data.get("isGroup", False) else "dm",user_id=data.get("senderId"),user_name=data.get("senderName"),)-- # Download media URLs to the local cache so agent tools- # can access them reliably regardless of URL expiration.- raw_urls = data.get("mediaUrls", [])- cached_urls = []- media_types = []- for url in raw_urls:- bridge_mime = str(data.get("mime") or "").strip()- if msg_type == MessageType.PHOTO and url.startswith(("http://", "https://")):- try:- cached_path = await cache_image_from_url(url, ext=".jpg")- cached_urls.append(cached_path)- media_types.append(bridge_mime or "image/jpeg")- print(f"[{self.name}] Cached user image: {cached_path}", flush=True)- except Exception as e:- print(f"[{self.name}] Failed to cache image: {e}", flush=True)- cached_urls.append(url)- media_types.append(bridge_mime or "image/jpeg")- elif msg_type == MessageType.PHOTO and os.path.isabs(url):- # Local file path — bridge already downloaded the image- if _is_allowed_bridge_path(url):- cached_urls.append(url)- media_types.append(bridge_mime or "image/jpeg")- print(f"[{self.name}] Using bridge-cached image: {url}", flush=True)- else:- print(f"[{self.name}] Rejected bridge image path outside cache dir: {url}", flush=True)- elif msg_type in {MessageType.VOICE, MessageType.AUDIO} and url.startswith(("http://", "https://")):- try:- cached_path = await cache_audio_from_url(url, ext=".ogg")- cached_urls.append(cached_path)- media_types.append(bridge_mime or ("audio/ogg" if msg_type == MessageType.VOICE else "audio/mpeg"))- print(f"[{self.name}] Cached user audio: {cached_path}", flush=True)- except Exception as e:- print(f"[{self.name}] Failed to cache audio: {e}", flush=True)- cached_urls.append(url)- media_types.append(bridge_mime or ("audio/ogg" if msg_type == MessageType.VOICE else "audio/mpeg"))- elif msg_type in {MessageType.VOICE, MessageType.AUDIO} and os.path.isabs(url):- # Local file path — bridge already downloaded the audio- if _is_allowed_bridge_path(url):- cached_urls.append(url)- media_types.append(bridge_mime or ("audio/ogg" if msg_type == MessageType.VOICE else "audio/mpeg"))- print(f"[{self.name}] Using bridge-cached audio: {url}", flush=True)- else:- print(f"[{self.name}] Rejected bridge audio path outside cache dir: {url}", flush=True)- elif msg_type == MessageType.DOCUMENT and os.path.isabs(url):- # Local file path — bridge already downloaded the document- if _is_allowed_bridge_path(url):- cached_urls.append(url)- ext = Path(url).suffix.lower()- mime = bridge_mime or SUPPORTED_DOCUMENT_TYPES.get(ext, "application/octet-stream")- media_types.append(mime)- print(f"[{self.name}] Using bridge-cached document: {url}", flush=True)- else:- print(f"[{self.name}] Rejected bridge document path outside cache dir: {url}", flush=True)- elif msg_type == MessageType.VIDEO and os.path.isabs(url):- if _is_allowed_bridge_path(url):- cached_urls.append(url)- media_types.append(bridge_mime or "video/mp4")- print(f"[{self.name}] Using bridge-cached video: {url}", flush=True)- else:- print(f"[{self.name}] Rejected bridge video path outside cache dir: {url}", flush=True)- else:- cached_urls.append(url)- media_types.append("unknown")-- # For text-readable documents, inject file content directly into- # the message text so the agent can read it inline.- # Cap at 100KB to match Telegram/Discord/Slack behaviour.+ cached_urls, media_types = await self._collect_bridge_media(data, msg_type)body = data.get("body", "")if data.get("isGroup"):body = self._clean_bot_mention_text(body, data)@@ -1606,15 +1162,11 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):and cached_urlsand str(body).strip().lower() == "[ptt received]"):- # The bridge synthesizes this placeholder for captionless voice- # notes. The cached audio is the real payload; retaining the- # placeholder makes the agent answer it as if it were user text.+ # Bridge placeholder for captionless voice notes; the audio is the payload.body = ""- # If this is a reply, keep the quoted message in structured fields- # only. GatewayRunner._prepare_inbound_message_text owns rendering- # the `[Replying to: ...]` pointer for every platform; pre-rendering- # it here makes WhatsApp replies show the quote twice.+ # Quoted message stays in structured fields only — GatewayRunner renders+ # the "[Replying to: ...]" pointer for every platform.quoted_text = str(data.get("quotedText") or "").strip()reply_to_text = quoted_text or Nonereply_to_message_id = None@@ -1628,33 +1180,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if quoted_participant:reply_to_author_id = quoted_participantreply_to_is_own_message = self._message_is_reply_to_bot(data)- MAX_TEXT_INJECT_BYTES = 100 * 1024if msg_type == MessageType.DOCUMENT and cached_urls:- for doc_path in cached_urls:- ext = Path(doc_path).suffix.lower()- if ext in {".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml", ".log", ".py", ".js", ".ts", ".html", ".css"}:- try:- file_size = Path(doc_path).stat().st_size- if file_size > MAX_TEXT_INJECT_BYTES:- print(f"[{self.name}] Skipping text injection for {doc_path} ({file_size} bytes > {MAX_TEXT_INJECT_BYTES})", flush=True)- continue- content = Path(doc_path).read_text(encoding="utf-8", errors="replace")- fname = Path(doc_path).name- # Remove the doc_<hex>_ prefix for display- display_name = fname- if "_" in fname:- parts = fname.split("_", 2)- if len(parts) >= 3:- display_name = parts[2]- injection = f"[Content of {display_name}]:\n{content}"- if body:- body = f"{injection}\n\n{body}"- else:- body = injection- print(f"[{self.name}] Injected text content from: {doc_path}", flush=True)- except Exception as e:- print(f"[{self.name}] Failed to read document text: {e}", flush=True)-+ body = self._inject_document_text(cached_urls, body)metadata: Dict[str, Any] = {}native_type = str(data.get("nativeType") or "").strip()native_metadata = data.get("nativeMetadata")@@ -1662,21 +1189,13 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):metadata["whatsapp_native_type"] = native_typeif isinstance(native_metadata, dict) and native_metadata:metadata["whatsapp_native"] = native_metadata- # The bridge sets ``fromOwner: true`` on inbound fromMe messages- # that look owner-typed (linked-device send, not echoed from our- # own /send). Surfaced under a platform-prefixed key so plugins- # can detect "owner just replied in this customer chat" without- # having to peek at raw_message. We also prefix ``MessageEvent.text``- # with ``[owner reply] `` here so the marker survives any downstream- # failure (e.g. handover-rule errors that bypass silent_ingest).- # Gated by ``WHATSAPP_FORWARD_OWNER_MESSAGES`` at the bridge layer;- # metadata + text tagging are unconditional when the flag is present- # so a future producer can set it without adapter changes.+ # ``fromOwner`` = owner-typed inbound fromMe (linked device), gated by+ # WHATSAPP_FORWARD_OWNER_MESSAGES at the bridge. Surfaced as metadata AND+ # a text prefix so the marker survives downstream failures before silent_ingest.if data.get("fromOwner"):metadata["whatsapp_from_owner"] = Trueif not body.startswith(_OWNER_REPLY_PREFIX):body = f"{_OWNER_REPLY_PREFIX}{body}"-return MessageEvent(text=body,message_type=msg_type,@@ -1697,17 +1216,9 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# ──────────────────────────────────────────────────────────────────────────-# Plugin migration glue (#41112 / #3823)-#-# Added when the WhatsApp adapter moved from gateway/platforms/whatsapp.py into-# this bundled plugin. Mirrors the Discord (#24356) / Slack migrations: a-# register(ctx) entry point plus hook implementations that replace the-# per-platform core touchpoints (the Platform.WHATSAPP elif in gateway/run.py,-# the whatsapp_cfg YAML→env block + _PLATFORM_CONNECTED_CHECKERS entry in-# gateway/config.py, the _setup_whatsapp wizard + _PLATFORMS["whatsapp"] static-# dict in hermes_cli/gateway.py, and the _send_whatsapp dispatch in-# tools/send_message_tool.py). WhatsApp auth is handled by the Node.js bridge,-# so is_connected is always True (matches the legacy checker).+# Plugin glue: register(ctx) plus the hook implementations that replaced the+# per-platform core touchpoints (gateway/run.py, gateway/config.py,+# hermes_cli/gateway.py, tools/send_message_tool.py).# ──────────────────────────────────────────────────────────────────────────@@ -1717,12 +1228,9 @@ _WA_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"}def _bridge_media_type(file_path: str, is_voice: bool, force_document: bool) -> str:- """Map a local media file to the bridge /send-media ``mediaType``.+ """Map a local file to the bridge ``mediaType`` (image|video|audio|document).- Returns one of ``image`` | ``video`` | ``audio`` | ``document`` so the- Baileys bridge renders the right native WhatsApp message kind. Voice notes- and audio files route to ``audio``; ``force_document`` (the [[as_document]]- directive) forces every file to ``document`` regardless of extension.+ ``force_document`` (the [[as_document]] directive) forces ``document``."""if force_document:return "document"@@ -1737,25 +1245,14 @@ def _bridge_media_type(file_path: str, is_voice: bool, force_document: bool) ->async def _standalone_send(- pconfig,- chat_id,- message,- *,- thread_id=None,- media_files=None,- force_document=False,+ pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False,caption=None,):- """Out-of-process WhatsApp delivery via the local bridge HTTP API.-- Implements the standalone_sender_fn contract so deliver=whatsapp cron jobs- succeed when cron runs separately from the gateway. Replaces the legacy- _send_whatsapp helper.+ """Out-of-process WhatsApp delivery via the bridge HTTP API (standalone_sender_fn+ contract, so deliver=whatsapp cron jobs work when cron runs apart from the gateway).- When ``caption`` is provided (single-file ``MEDIA:<path> caption`` send),- the text rides on the media bubble's native caption via the bridge- ``/send-media`` ``caption`` field instead of being posted as a separate- ``/send`` message beforehand.+ With ``caption`` (single-file ``MEDIA:<path> caption`` send) the text rides on+ the media bubble's native caption instead of a separate ``/send``."""extra = getattr(pconfig, "extra", {}) or {}try:@@ -1767,42 +1264,32 @@ async def _standalone_send(normalized_chat_id = to_whatsapp_jid(chat_id)media = media_files or []text = message or ""- # A caption only applies to a single media file; guard defensively so- # a caption is never silently repeated across a multi-file send.+ # A caption only applies to a single media file — never repeat it across a multi-file send.media_caption = caption if (caption and len(media) == 1) else Nonelast_message_id = Noneasync with aiohttp.ClientSession() as session:- # 1) Text first (skip the /send call when this chunk is media-only- # or when the text is delivered as the media caption instead).+ def _post(path, payload, total):+ return session.post(+ f"http://localhost:{bridge_port}/{path}", json=payload, timeout=aiohttp.ClientTimeout(total=total),+ )++ # 1) Text first (skipped when media-only or when the text rides as the caption).if text.strip() and not media_caption:- async with session.post(- f"http://localhost:{bridge_port}/send",- json={"chatId": normalized_chat_id, "message": text},- timeout=aiohttp.ClientTimeout(total=30),- ) as resp:+ async with _post("send", {"chatId": normalized_chat_id, "message": text}, 30) as resp:if resp.status != 200:body = await resp.text()return {"error": f"WhatsApp bridge error ({resp.status}): {body}"}data = await resp.json()last_message_id = data.get("messageId")- # 2) Each media file as a native attachment via /send-media. The- # bridge maps mediaType -> image/video/audio/document message kinds- # so PNG/JPEG/WebP/GIF arrive as inline images, MP4 as a video- # bubble, and ogg/opus as a voice note — not a file/document.+ # 2) Each media file as a native attachment (mediaType picks the WhatsApp kind).for media_path, is_voice in media:if not os.path.exists(media_path):- # If the text was suppressed to ride as this file's caption- # (caption mode), the words would otherwise be lost when the- # file is missing — deliver the caption as a plain message- # so nothing silently disappears.+ # In caption mode the words would be lost with the missing file —+ # deliver the caption as a plain message so nothing silently disappears.if media_caption:try:- async with session.post(- f"http://localhost:{bridge_port}/send",- json={"chatId": normalized_chat_id, "message": media_caption},- timeout=aiohttp.ClientTimeout(total=30),- ) as resp:+ async with _post("send", {"chatId": normalized_chat_id, "message": media_caption}, 30) as resp:if resp.status == 200:last_message_id = (await resp.json()).get("messageId")except Exception:@@ -1818,17 +1305,12 @@ async def _standalone_send(payload["fileName"] = os.path.basename(media_path)if media_caption:payload["caption"] = media_caption- async with session.post(- f"http://localhost:{bridge_port}/send-media",- json=payload,- timeout=aiohttp.ClientTimeout(total=120),- ) as resp:+ async with _post("send-media", payload, 120) as resp:if resp.status != 200:body = await resp.text()return {"error": f"WhatsApp media error ({resp.status}): {body}"}data = await resp.json()last_message_id = data.get("messageId") or last_message_id-return {"success": True,"platform": "whatsapp",@@ -1840,12 +1322,7 @@ async def _standalone_send(def interactive_setup() -> None:- """Guide the user through WhatsApp setup.-- Replaces the central _setup_whatsapp in hermes_cli/gateway.py and the- static _PLATFORMS["whatsapp"] dict. CLI helpers are lazy-imported so the- plugin's module-load surface stays minimal.- """+ """Guide the user through WhatsApp setup (CLI helpers lazy-imported)."""from hermes_cli.config import get_env_value, remove_env_value, save_env_valuefrom hermes_cli.cli_output import (prompt,@@ -1854,7 +1331,6 @@ def interactive_setup() -> None:print_info,print_success,)-print_header("WhatsApp")print_info("WhatsApp uses a local Node.js bridge (WhatsApp Web client).")print_info("Start the bridge separately; the gateway connects to it over HTTP.")@@ -1863,7 +1339,6 @@ def interactive_setup() -> None:print_info("WhatsApp: already enabled")if not prompt_yes_no("Reconfigure WhatsApp?", False):return-if prompt_yes_no("Enable WhatsApp?", True):save_env_value("WHATSAPP_ENABLED", "true")print_success("WhatsApp enabled")@@ -1871,14 +1346,10 @@ def interactive_setup() -> None:save_env_value("WHATSAPP_ENABLED", "false")print_info("WhatsApp left disabled")return-- allowed_users = prompt(- "Allowed user IDs (comma-separated, leave empty for no allowlist)"- )+ allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for no allowlist)")if allowed_users:save_env_value("WHATSAPP_ALLOWED_USERS", allowed_users.replace(" ", ""))print_success("WhatsApp allowlist configured")-home_channel = prompt("Home chat ID for cron delivery (leave empty to skip)").strip()if home_channel:save_env_value("WHATSAPP_HOME_CHANNEL", home_channel)@@ -1887,59 +1358,50 @@ def interactive_setup() -> None:print_info("Home channel cleared.")+# config.yaml whatsapp: key → env var. Env vars take precedence over YAML.+_YAML_LOWERCASE_KEYS = (+ ("require_mention", "WHATSAPP_REQUIRE_MENTION"),+ ("dm_policy", "WHATSAPP_DM_POLICY"),+ ("group_policy", "WHATSAPP_GROUP_POLICY"),+)+_YAML_LIST_KEYS = (+ ("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS"),+ ("allow_from", "WHATSAPP_ALLOWED_USERS"),+ ("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS"),+)++def _apply_yaml_config(yaml_cfg: dict, whatsapp_cfg: dict) -> dict | None:- """Translate config.yaml whatsapp: keys into WHATSAPP_* env vars.+ """Translate config.yaml whatsapp: keys into WHATSAPP_* env vars (apply_yaml_config_fn contract).- Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy- whatsapp_cfg block from gateway/config.py::load_gateway_config(). Env vars- take precedence over YAML. Returns None — everything flows through env.+ Returns None — everything flows through env."""import json as _json- if "require_mention" in whatsapp_cfg and not os.getenv("WHATSAPP_REQUIRE_MENTION"):- os.environ["WHATSAPP_REQUIRE_MENTION"] = str(whatsapp_cfg["require_mention"]).lower()+ for key, env in _YAML_LOWERCASE_KEYS:+ if key in whatsapp_cfg and not os.getenv(env):+ os.environ[env] = str(whatsapp_cfg[key]).lower()if "mention_patterns" in whatsapp_cfg and not os.getenv("WHATSAPP_MENTION_PATTERNS"):os.environ["WHATSAPP_MENTION_PATTERNS"] = _json.dumps(whatsapp_cfg["mention_patterns"])- frc = whatsapp_cfg.get("free_response_chats")- if frc is not None and not os.getenv("WHATSAPP_FREE_RESPONSE_CHATS"):- if isinstance(frc, list):- frc = ",".join(str(v) for v in frc)- os.environ["WHATSAPP_FREE_RESPONSE_CHATS"] = str(frc)- if "dm_policy" in whatsapp_cfg and not os.getenv("WHATSAPP_DM_POLICY"):- os.environ["WHATSAPP_DM_POLICY"] = str(whatsapp_cfg["dm_policy"]).lower()- af = whatsapp_cfg.get("allow_from")- if af is not None and not os.getenv("WHATSAPP_ALLOWED_USERS"):- if isinstance(af, list):- af = ",".join(str(v) for v in af)- os.environ["WHATSAPP_ALLOWED_USERS"] = str(af)- if "group_policy" in whatsapp_cfg and not os.getenv("WHATSAPP_GROUP_POLICY"):- os.environ["WHATSAPP_GROUP_POLICY"] = str(whatsapp_cfg["group_policy"]).lower()- gaf = whatsapp_cfg.get("group_allow_from")- if gaf is not None and not os.getenv("WHATSAPP_GROUP_ALLOWED_USERS"):- if isinstance(gaf, list):- gaf = ",".join(str(v) for v in gaf)- os.environ["WHATSAPP_GROUP_ALLOWED_USERS"] = str(gaf)+ for key, env in _YAML_LIST_KEYS:+ val = whatsapp_cfg.get(key)+ if val is not None and not os.getenv(env):+ if isinstance(val, list):+ val = ",".join(str(v) for v in val)+ os.environ[env] = str(val)return Nonedef _is_connected(config) -> bool:- """WhatsApp is considered connected when the user has explicitly enabled it- via ``WHATSAPP_ENABLED`` (or the YAML-bridged equivalent on the config).-- Auth itself is handled by the external Node.js bridge — we can't verify the- bridge token here — so the opt-in flag is the connection signal. The legacy- built-in path keyed off ``WHATSAPP_ENABLED`` in both the connected-platforms- check and the setup-status display; returning an unconditional True here- would make WhatsApp always show as "configured" in ``hermes setup`` even- when the user never enabled it. #41112.+ """Connected == explicitly enabled via WHATSAPP_ENABLED (or an enabled PlatformConfig with extras).++ Auth is handled by the Node.js bridge, so the opt-in flag is the signal; an+ unconditional True would show WhatsApp as configured in ``hermes setup`` always."""extra = getattr(config, "extra", {}) or {}if config is not None and getattr(config, "enabled", False) and extra:- # An explicitly-enabled PlatformConfig with seeded extras (e.g. from- # YAML) counts as configured.return True- # Read via hermes_cli.gateway.get_env_value (not os.getenv) so setup-status- # callers that patch get_env_value — and the gateway connected-platforms- # check — observe the same value. Matches the discord/slack plugin pattern.+ # Via hermes_cli.gateway.get_env_value (not os.getenv) so setup-status callers+ # that patch get_env_value observe the same value.import hermes_cli.gateway as gateway_modval = (gateway_mod.get_env_value("WHATSAPP_ENABLED") or "").strip().lower()return val in {"true", "1", "yes"}