The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(whatsapp_cloud): move WhatsApp Cloud adapter into a bundled platform plugin
Tekniumf11062a83774
diff --git a/gateway/platforms/ADDING_A_PLATFORM.md b/gateway/platforms/ADDING_A_PLATFORM.mdindex 917482cf92c..dfb8c71d137 100644--- a/gateway/platforms/ADDING_A_PLATFORM.md+++ b/gateway/platforms/ADDING_A_PLATFORM.md@@ -64,8 +64,8 @@ orphans) and the developer-guide page for the prose walkthrough.two transport modes the user picks between — unofficial vs officialAPIs, polling vs websocket, library A vs library B — the rightstructure is two adapters that share a behavior mixin. WhatsApp does-this: `gateway/platforms/whatsapp.py` (Baileys bridge) and-`gateway/platforms/whatsapp_cloud.py` (Meta Cloud API) both inherit+this: `plugins/platforms/whatsapp/adapter.py` (Baileys bridge) and+`plugins/platforms/whatsapp_cloud/adapter.py` (Meta Cloud API) both inheritfrom `WhatsAppBehaviorMixin` in `gateway/platforms/whatsapp_common.py`.The mixin owns gating, allow-lists, mention parsing, broadcastfilters, and the WhatsApp-flavored markdown conversion — everything@@ -137,7 +137,7 @@ If your platform supports interactive button/menu messages, implement these for| `send_model_picker(...)` | Interactive `/model` picker. Used by Telegram, Discord, and Slack (Socket Mode). || `send_choice_picker(...)` | Flat single-level picker for finite-choice commands (`/reasoning`, `/fast`). Implemented by Telegram (inline keyboard), Discord (select menu), and Matrix (reactions). Platforms without it fall back to the text status card automatically. |-See `gateway/platforms/telegram.py`, `discord.py`, and `whatsapp_cloud.py` for reference implementations. The button-callback id convention (`cl:<id>:<idx>`, `appr:<id>:<choice>`, `sc:<choice>:<id>`) is shared across adapters — match it so the gateway-side resolvers work without modification.+See `gateway/platforms/telegram.py`, `discord.py`, and `plugins/platforms/whatsapp_cloud/adapter.py` for reference implementations. The button-callback id convention (`cl:<id>:<idx>`, `appr:<id>:<choice>`, `sc:<choice>:<id>`) is shared across adapters — match it so the gateway-side resolvers work without modification.### Required functiondiff --git a/hermes_cli/main_platform_setup.py b/hermes_cli/main_platform_setup.pyindex 595f8030ac4..5f274b24e73 100644--- a/hermes_cli/main_platform_setup.py+++ b/hermes_cli/main_platform_setup.py@@ -225,10 +225,10 @@ def cmd_whatsapp(args):def cmd_whatsapp_cloud(args):"""Set up WhatsApp Business Cloud API (official Meta integration) — complementary to the- ``hermes whatsapp`` Baileys bridge wizard. See ``hermes_cli/setup_whatsapp_cloud.py``."""+ ``hermes whatsapp`` Baileys bridge wizard. See ``plugins/platforms/whatsapp_cloud/setup_wizard.py``."""from hermes_cli.main import _require_tty_require_tty("whatsapp-cloud")- from hermes_cli.setup_whatsapp_cloud import run_whatsapp_cloud_setup+ from plugins.platforms.whatsapp_cloud.setup_wizard import run_whatsapp_cloud_setupreturn run_whatsapp_cloud_setup()diff --git a/plugins/platforms/whatsapp_cloud/__init__.py b/plugins/platforms/whatsapp_cloud/__init__.pynew file mode 100644index 00000000000..d4f1d7bf0e3--- /dev/null+++ b/plugins/platforms/whatsapp_cloud/__init__.py@@ -0,0 +1,3 @@+from .adapter import register++__all__ = ["register"]diff --git a/gateway/platforms/whatsapp_cloud.py b/plugins/platforms/whatsapp_cloud/adapter.pysimilarity index 96%rename from gateway/platforms/whatsapp_cloud.pyrename to plugins/platforms/whatsapp_cloud/adapter.pyindex d7e753fb354..b9e31cdc833 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/plugins/platforms/whatsapp_cloud/adapter.py@@ -1062,3 +1062,41 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):reply_to_text=reply_to_text, reply_to_is_own_message=reply_to_is_own,media_urls=media_urls, media_types=media_types, media_text_inlined=media_text_inlined,)+++# ---------------------------------------------------------------------------+# Plugin registration+# ---------------------------------------------------------------------------++def _is_connected(config) -> bool:+ """Phone-number id + access token, from ``PlatformConfig.extra`` (YAML / env seeding) or the+ scope-aware env reader (``hermes_cli.gateway.get_env_value`` so setup-status patches see it)."""+ extra = (getattr(config, "extra", None) or {}) if config is not None else {}+ if extra.get("phone_number_id") and extra.get("access_token"):+ return True+ import hermes_cli.gateway as gateway_mod+ return all((gateway_mod.get_env_value(name) or "").strip()+ for name in ("WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"))+++def _interactive_setup() -> None:+ """``hermes gateway setup`` entry: the same wizard ``hermes whatsapp-cloud`` runs."""+ from .setup_wizard import run_whatsapp_cloud_setup+ run_whatsapp_cloud_setup()+++def register(ctx) -> None:+ """Plugin entry point — called by the Hermes plugin system.++ No ``validate_config``: an unconfigured adapter still reaches ``connect()``, which records the+ ``whatsapp_cloud_unconfigured`` fatal error (same outcome as the former core wiring). No+ ``standalone_sender_fn`` / ``max_message_length``: out-of-process ``send_message`` had no+ WhatsApp Cloud sender in core either, and ``send()`` chunks itself."""+ ctx.register_platform(+ name="whatsapp_cloud", label="WhatsApp Business (Cloud)", adapter_factory=WhatsAppCloudAdapter,+ check_fn=check_whatsapp_cloud_requirements, is_connected=_is_connected,+ required_env=["WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"],+ install_hint="aiohttp/httpx missing — reinstall hermes-agent", setup_fn=_interactive_setup,+ allowed_users_env="WHATSAPP_CLOUD_ALLOWED_USERS", allow_all_env="WHATSAPP_CLOUD_ALLOW_ALL_USERS",+ cron_deliver_env_var="WHATSAPP_CLOUD_HOME_CHANNEL", emoji="📱", allow_update_command=False,+ )diff --git a/plugins/platforms/whatsapp_cloud/plugin.yaml b/plugins/platforms/whatsapp_cloud/plugin.yamlnew file mode 100644index 00000000000..38809cb47a2--- /dev/null+++ b/plugins/platforms/whatsapp_cloud/plugin.yaml@@ -0,0 +1,71 @@+name: whatsapp_cloud-platform+label: WhatsApp Business (Cloud)+kind: platform+version: 1.0.0+description: >+ WhatsApp Business Cloud API adapter for Hermes Agent.+ Connects to WhatsApp via Meta's official Cloud API (Business account and a+ public webhook URL required, token-based auth): Graph API for outbound,+ an aiohttp webhook receiver with X-Hub-Signature-256 verification for+ inbound. Supports text, media (image/video/audio/document), voice notes,+ interactive buttons, and DM allowlists. Complements the Baileys bridge+ (whatsapp) plugin; both share WhatsAppBehaviorMixin.+author: NousResearch+requires_env:+ - name: WHATSAPP_CLOUD_PHONE_NUMBER_ID+ description: "WhatsApp phone number ID from the Meta App Dashboard (WhatsApp → API Setup)"+ prompt: "WhatsApp Cloud phone number ID"+ password: false+ - name: WHATSAPP_CLOUD_ACCESS_TOKEN+ description: "System User permanent access token"+ prompt: "WhatsApp Cloud access token"+ password: true+optional_env:+ - name: WHATSAPP_CLOUD_APP_SECRET+ description: "App secret — HMAC key for X-Hub-Signature-256 webhook verification"+ prompt: "WhatsApp Cloud app secret"+ password: true+ - name: WHATSAPP_CLOUD_VERIFY_TOKEN+ description: "Shared secret for the webhook verification handshake (hub.verify_token)"+ prompt: "WhatsApp Cloud verify token"+ password: true+ - name: WHATSAPP_CLOUD_APP_ID+ description: "Meta app ID (optional)"+ prompt: "WhatsApp Cloud app ID"+ password: false+ - name: WHATSAPP_CLOUD_WABA_ID+ description: "WhatsApp Business Account ID; when set, inbound webhooks must match it"+ prompt: "WhatsApp Business Account ID"+ password: false+ - name: WHATSAPP_CLOUD_WEBHOOK_HOST+ description: "Webhook bind host (unset = dual-stack all interfaces)"+ prompt: "Webhook host"+ password: false+ - name: WHATSAPP_CLOUD_WEBHOOK_PORT+ description: "Webhook bind port (default: 8090)"+ prompt: "Webhook port"+ password: false+ - name: WHATSAPP_CLOUD_WEBHOOK_PATH+ description: "Webhook path (default: /whatsapp/webhook)"+ prompt: "Webhook path"+ password: false+ - name: WHATSAPP_CLOUD_API_VERSION+ description: "Graph API version (default: v20.0)"+ prompt: "Graph API version"+ password: false+ - name: WHATSAPP_CLOUD_ALLOWED_USERS+ description: "Comma-separated WhatsApp phone numbers allowed to talk to the bot"+ prompt: "Allowed phone numbers (comma-separated)"+ password: false+ - name: WHATSAPP_CLOUD_ALLOW_ALL_USERS+ description: "Allow any WhatsApp user to trigger the bot (dev only)"+ prompt: "Allow all users? (true/false)"+ password: false+ - name: WHATSAPP_CLOUD_DM_POLICY+ description: "DM policy: open | allowlist | disabled (falls back to WHATSAPP_DM_POLICY)"+ prompt: "DM policy"+ password: false+ - name: WHATSAPP_CLOUD_HOME_CHANNEL+ description: "Default phone number for cron / notification delivery"+ prompt: "Home channel phone number"+ password: falsediff --git a/hermes_cli/setup_whatsapp_cloud.py b/plugins/platforms/whatsapp_cloud/setup_wizard.pysimilarity index 100%rename from hermes_cli/setup_whatsapp_cloud.pyrename to plugins/platforms/whatsapp_cloud/setup_wizard.pydiff --git a/tests/fixtures/resolution_allowlist.json b/tests/fixtures/resolution_allowlist.jsonindex b56d7c86598..1b19ec5f8d6 100644--- a/tests/fixtures/resolution_allowlist.json+++ b/tests/fixtures/resolution_allowlist.json@@ -89,11 +89,6 @@"symbol": "_remux_aac_to_m4a","kind": "bare_which"},- {- "path": "gateway/platforms/whatsapp_cloud.py",- "symbol": "<module>",- "kind": "bare_which"- },{"path": "gateway/run.py","symbol": "_resolve_hermes_bin",diff --git a/tests/gateway/test_access_policy_mixin.py b/tests/gateway/test_access_policy_mixin.pyindex bf244bb2f66..308eb8c6c79 100644--- a/tests/gateway/test_access_policy_mixin.py+++ b/tests/gateway/test_access_policy_mixin.py@@ -31,7 +31,7 @@ def _hosts():"""One bare instance per own-policy class, attributes set exactly as the adapters do."""from gateway.platforms.qqbot.adapter import QQAdapterfrom gateway.platforms.weixin import WeixinAdapter- from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapterfrom gateway.platforms.whatsapp_common import WhatsAppBehaviorMixinfrom gateway.platforms.yuanbao import AccessPolicyfrom plugins.platforms.wecom.adapter import WeComAdapterdiff --git a/tests/gateway/test_media_cache.py b/tests/gateway/test_media_cache.pyindex 5fc5b8df6b8..80c8af8eea9 100644--- a/tests/gateway/test_media_cache.py+++ b/tests/gateway/test_media_cache.py@@ -75,5 +75,5 @@ class TestWhatsAppCloudParity:@pytest.mark.parametrize("mime,expected", sorted(CASES.items()))def test_pinned_overrides(self, mime, expected):- from gateway.platforms.whatsapp_cloud import _ext_for_mime+ from plugins.platforms.whatsapp_cloud.adapter import _ext_for_mimeassert _ext_for_mime(mime) == expecteddiff --git a/tests/gateway/test_whatsapp_cloud.py b/tests/gateway/test_whatsapp_cloud.pyindex 100a335c655..e1a046e0e28 100644--- a/tests/gateway/test_whatsapp_cloud.py+++ b/tests/gateway/test_whatsapp_cloud.py@@ -46,7 +46,7 @@ def _make_adapter(**overrides):Mirrors the pattern in tests/gateway/test_whatsapp_*.py."""- from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapteradapter = WhatsAppCloudAdapter.__new__(WhatsAppCloudAdapter)adapter.platform = Platform.WHATSAPP_CLOUD@@ -392,7 +392,7 @@ class TestWebhookSignature:def test_null_yaml_app_secret_is_unset_not_the_string_none(self):from gateway.config import PlatformConfig- from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapteradapter = WhatsAppCloudAdapter(PlatformConfig(enabled=True, extra={"app_secret": None, "verify_token": None}))assert adapter._app_secret == "" and adapter._verify_token == ""@@ -403,7 +403,7 @@ class TestWebhookReplay:def test_dedup_cache_evicts_oldest(self):- from gateway.platforms.whatsapp_cloud import WAMID_DEDUP_CACHE_SIZE+ from plugins.platforms.whatsapp_cloud.adapter import WAMID_DEDUP_CACHE_SIZEadapter = _make_adapter()# Fill the cache plus 5 extrafor i in range(WAMID_DEDUP_CACHE_SIZE + 5):@@ -787,7 +787,7 @@ class TestDownloadMedia:@pytest.mark.asyncioasync def test_two_step_download_writes_cache_file(self, tmp_path):- from gateway.platforms import whatsapp_cloud as wac+ from plugins.platforms.whatsapp_cloud import adapter as wacadapter = _make_adapter()adapter._http_client = MagicMock()@@ -836,7 +836,7 @@ class TestInboundMediaDispatch:@pytest.mark.asyncioasync def test_inbound_text_document_injected_into_body(self, tmp_path):"""A .txt document should have its content prepended to the body."""- from gateway.platforms import whatsapp_cloud as wac+ from plugins.platforms.whatsapp_cloud import adapter as wacadapter = _make_adapter(app_secret="key")captured: list = []@@ -912,7 +912,7 @@ class TestInboundMediaDispatch:"from": "1555", "id": "wamid.doc2", "timestamp": "0", "type": "document","document": {"id": "media_doc_abc", "mime_type": "text/plain", "filename": "notes.txt"},}- from gateway.platforms import whatsapp_cloud as wac+ from plugins.platforms.whatsapp_cloud import adapter as wacwith _patch.object(wac, "_INBOUND_MEDIA_CACHE", tmp_path):event = await adapter._build_message_event_from_cloud(raw_message, {"1555": "U"}, {"phone_number_id": "1"})@@ -1400,7 +1400,7 @@ class TestSendTyping:class TestAllowlistNormalization:def test_normalize_allow_ids_strips_jid_suffix_and_punctuation(self):- from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapterids = {"[email protected]", "+1 (555) 765-4321", "15550000000"}normalized = WhatsAppCloudAdapter._normalize_allow_ids(ids)@@ -1412,7 +1412,7 @@ class TestBoundedInteractiveState:from collections import OrderedDictfrom gateway.platforms.helpers import bounded_put- from gateway.platforms.whatsapp_cloud import INTERACTIVE_STATE_CACHE_SIZE+ from plugins.platforms.whatsapp_cloud.adapter import INTERACTIVE_STATE_CACHE_SIZEcache: OrderedDict = OrderedDict()for i in range(INTERACTIVE_STATE_CACHE_SIZE + 10):@@ -1503,3 +1503,30 @@ class TestReplyContextResolution:assert event.media_urls == [str(image)]assert event.media_types == ["image/png"]+++def test_plugin_register_shape():+ """whatsapp_cloud ships as a bundled platform plugin (formerly a core _BUILTIN_ADAPTERS row)."""+ from plugins.platforms.whatsapp_cloud import register+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapter, check_whatsapp_cloud_requirements+ from plugins.platforms.whatsapp_cloud.setup_wizard import run_whatsapp_cloud_setup++ captured: dict = {}++ class _Ctx:+ def register_platform(self, **kw):+ captured.update(kw)++ register(_Ctx())+ assert captured["name"] == "whatsapp_cloud"+ assert captured["label"] == "WhatsApp Business (Cloud)"+ assert captured["adapter_factory"] is WhatsAppCloudAdapter+ assert captured["check_fn"] is check_whatsapp_cloud_requirements+ assert captured["required_env"] == ["WHATSAPP_CLOUD_PHONE_NUMBER_ID", "WHATSAPP_CLOUD_ACCESS_TOKEN"]+ assert captured["allowed_users_env"] == "WHATSAPP_CLOUD_ALLOWED_USERS"+ assert captured["allow_all_env"] == "WHATSAPP_CLOUD_ALLOW_ALL_USERS"+ assert captured["cron_deliver_env_var"] == "WHATSAPP_CLOUD_HOME_CHANNEL"+ assert callable(captured["setup_fn"]) and callable(run_whatsapp_cloud_setup)+ from gateway.config import PlatformConfig+ is_connected = captured["is_connected"]+ assert is_connected(PlatformConfig(enabled=True, extra={"phone_number_id": "1", "access_token": "t"}))diff --git a/tests/gateway/test_whatsapp_cloud_allowed_users.py b/tests/gateway/test_whatsapp_cloud_allowed_users.pyindex 955e67cd4a8..98c102b566e 100644--- a/tests/gateway/test_whatsapp_cloud_allowed_users.py+++ b/tests/gateway/test_whatsapp_cloud_allowed_users.py@@ -19,7 +19,7 @@ from gateway.config import Platformdef _build_adapter(monkeypatch, env: dict[str, str], extra: dict | None = None):"""Construct a real WhatsAppCloudAdapter through __init__ with env vars."""- from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapterfor var in ("WHATSAPP_CLOUD_ALLOW_FROM",diff --git a/tests/gateway/test_whatsapp_multiplex_secret_scope.py b/tests/gateway/test_whatsapp_multiplex_secret_scope.pyindex ec487da2fda..6215f0884eb 100644--- a/tests/gateway/test_whatsapp_multiplex_secret_scope.py+++ b/tests/gateway/test_whatsapp_multiplex_secret_scope.py@@ -143,7 +143,7 @@ class TestWhatsAppCloudAdapterUsesSecretScope:(tmp_path / ".env").write_text("WHATSAPP_DM_POLICY=allowlist\n")tok = ss.set_secret_scope(ss.build_profile_secret_scope(tmp_path))try:- from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+ from plugins.platforms.whatsapp_cloud.adapter import WhatsAppCloudAdapter# Cloud adapter won't fully init without creds, but we can at least# verify the dm_policy assignment path doesn't crash under scope.diff --git a/tests/hermes_cli/test_whatsapp_cloud_setup.py b/tests/hermes_cli/test_whatsapp_cloud_setup.pyindex d375c6aea1e..cd795eccc00 100644--- a/tests/hermes_cli/test_whatsapp_cloud_setup.py+++ b/tests/hermes_cli/test_whatsapp_cloud_setup.py@@ -21,7 +21,7 @@ from pathlib import Pathimport pytest-from hermes_cli.setup_whatsapp_cloud import (+from plugins.platforms.whatsapp_cloud.setup_wizard import (_validate_phone_number_id,_validate_waba_id,_validate_app_id,diff --git a/website/docs/developer-guide/architecture.md b/website/docs/developer-guide/architecture.mdindex 1ceb6e1a6a0..e48a0017585 100644--- a/website/docs/developer-guide/architecture.md+++ b/website/docs/developer-guide/architecture.md@@ -118,12 +118,12 @@ hermes-agent/│ ├── status.py # Token locks, profile-scoped process tracking│ ├── builtin_hooks/ # Extension point for always-registered hooks (none shipped)│ └── platforms/ # Built-in adapters: signal, weixin, bluebubbles,-│ # qqbot, whatsapp_cloud, yuanbao, webhook, api_server+│ # qqbot, yuanbao, webhook, api_server│├── plugins/platforms/ # Bundled platform plugins: telegram, discord, slack,│ # whatsapp, matrix, mattermost, email, sms, dingtalk,│ # feishu, wecom, irc, line, teams, google_chat,-│ # buzz, ntfy, photon, raft, simplex+│ # buzz, ntfy, photon, raft, simplex, whatsapp_cloud│ # (Home Assistant: `homeassistant` catalog plugin)│├── acp_adapter/ # ACP server (VS Code / Zed / JetBrains)