The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(send): route WhatsApp mentions through the existing standalone chunker
kshitijk4poor8503ee445931
diff --git a/gateway/whatsapp_identity.py b/gateway/whatsapp_identity.pyindex 5dcad7c8bd2..3bc431081a2 100644--- a/gateway/whatsapp_identity.py+++ b/gateway/whatsapp_identity.py@@ -21,9 +21,9 @@ logger = logging.getLogger(__name__)# Explicit ASCII class so full-width digits / Unicode word chars can't sneak through._SAFE_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9@.+\-]+$")-# "Just a phone number": optional ``+`` then ASCII digits and human separators.+# "Just a phone number": optional ``+`` then digits and human separators.# Anything carrying ``@`` is already a JID (``@g.us``, ``@lid``, ``status@broadcast``).-_BARE_PHONE_RE = re.compile(r"^\+?[0-9\s().\-]+$")+_BARE_PHONE_RE = re.compile(r"^\+?[\d\s().\-]+$")def normalize_whatsapp_identifier(value: str) -> str:@@ -46,7 +46,7 @@ def to_whatsapp_jid(value: str) -> str:if "@" in normalized:return normalizedif _BARE_PHONE_RE.fullmatch(normalized):- digits = re.sub(r"[^0-9]+", "", normalized)+ digits = re.sub(r"\D+", "", normalized)if digits:return f"{digits}@s.whatsapp.net"return normalizeddiff --git a/hermes_cli/send_cmd.py b/hermes_cli/send_cmd.pyindex c7b02396e9b..ec3c5efc39c 100644--- a/hermes_cli/send_cmd.py+++ b/hermes_cli/send_cmd.py@@ -210,7 +210,7 @@ def cmd_send(args: argparse.Namespace) -> None:mentions = list(getattr(args, "mentions", None) or [])if mentions and target.split(":", 1)[0].strip().lower() != "whatsapp":_fail("hermes send: --mention is only supported for WhatsApp targets.", _USAGE_EXIT)- invalid_mentions = _invalid_whatsapp_mentions(mentions) if mentions else []+ invalid_mentions = _invalid_whatsapp_mentions(mentions)if invalid_mentions:_fail("hermes send: invalid --mention value(s): "diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex e32e5a32525..81185b4663a 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -884,21 +884,9 @@ def _bridge_media_type(file_path: str, is_voice: bool, force_document: bool) ->return "document" if force_document else "audio" if is_voice else _WA_EXT_MEDIA_TYPE.get(os.path.splitext(file_path)[1].lower(), "document")-def _normalize_outbound_mentions(mentions: Any) -> list[str]:- """Normalize valid outbound phone numbers and participant JIDs, preserving order."""- if not isinstance(mentions, (list, tuple)):- return []- seen: set[str] = set()- normalized: list[str] = []- for candidate in mentions:- if not isinstance(candidate, str):- continue- jid = normalize_whatsapp_mention_jid(candidate)- if not jid or jid in seen:- continue- seen.add(jid)- normalized.append(jid)- return normalized+def _normalize_outbound_mentions(mentions: list[str] | None) -> list[str]:+ """Valid participant JIDs, deduplicated, order preserved."""+ return list(dict.fromkeys(jid for m in mentions or () if (jid := normalize_whatsapp_mention_jid(m))))async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False,diff --git a/tests/hermes_cli/test_send_cmd.py b/tests/hermes_cli/test_send_cmd.pyindex d9c8022daa1..875cacc1ca7 100644--- a/tests/hermes_cli/test_send_cmd.py+++ b/tests/hermes_cli/test_send_cmd.py@@ -64,19 +64,20 @@ def fake_tool(monkeypatch):# ----------------------------------------------------------------------------def test_whatsapp_mentions_validate_and_reach_native_text_and_media_payloads(monkeypatch, tmp_path, capsys):- """The CLI-only option stays scoped, normalizes JIDs, and pings once per logical send."""+def whatsapp_bridge(monkeypatch):+ """Route ``hermes send --to whatsapp:...`` through the real plugin standalone sender into a fake+ bridge; returns the recorded ``(path, payload)`` posts and a mutable ``supports_mentions`` flag."""import asynciofrom types import SimpleNamespaceimport aiohttpfrom gateway.config import Platform- from gateway.platform_registry import platform_registryfrom hermes_cli.plugins import discover_pluginscalls = []- bridge_state = {"supports_mentions": True}+ state = {"supports_mentions": True}class BridgeResponse:status = 200@@ -86,7 +87,7 @@ def test_whatsapp_mentions_validate_and_reach_native_text_and_media_payloads(monasync def json(self):if self.health:- return {"capabilities": {"outboundMentions": bridge_state["supports_mentions"]}}+ return {"capabilities": {"outboundMentions": state["supports_mentions"]}}return {"messageId": f"m{len(calls)}"}async def text(self):@@ -109,13 +110,12 @@ def test_whatsapp_mentions_validate_and_reach_native_text_and_media_payloads(monreturn BridgeResponse(health=True)def post(self, url, *, json, timeout):- calls.append((url, json))+ calls.append((url.rsplit("/", 1)[-1], json))return BridgeResponse()discover_plugins()- whatsapp_config = SimpleNamespace(enabled=True, token=None, extra={"bridge_port": 3000})config = SimpleNamespace(- platforms={Platform.WHATSAPP: whatsapp_config},+ platforms={Platform.WHATSAPP: SimpleNamespace(enabled=True, token=None, extra={"bridge_port": 3000})},get_home_channel=lambda _platform: None,)monkeypatch.setattr(send_cmd, "_load_hermes_env", lambda: None)@@ -124,96 +124,62 @@ def test_whatsapp_mentions_validate_and_reach_native_text_and_media_payloads(monmonkeypatch.setattr("model_tools._run_async", lambda coro: asyncio.run(coro))monkeypatch.setattr("tools.send_message_tool._mirror_sent_message", lambda *_args: False)monkeypatch.setattr(aiohttp, "ClientSession", lambda *_args, **_kwargs: BridgeSession())+ return SimpleNamespace(calls=calls, state=state)+++_GROUP = "whatsapp:[email protected]"- for argv in (- ["--to", "telegram", "--mention", "15550000001", "hello"],- ["--to", "whatsapp:[email protected]", "--mention", "not-a-phone", "hello"],- ["--to", "whatsapp:[email protected]", "--mention", "١٥٥٥٠٠٠٠٠٠١", "hello"],- [- "--to", "whatsapp:[email protected]",- "--mention", "١٥٥٥٠٠٠٠٠٠١@s.whatsapp.net", "hello",- ],- ):- with pytest.raises(SystemExit) as exc:- send_cmd.cmd_send(_parse(argv))- assert exc.value.code == 2- assert calls == []- capsys.readouterr()-- async def legacy_sender(_config, _chat_id, _message, *, thread_id=None):- return {"success": True}-- whatsapp_entry = platform_registry.get("whatsapp")- assert whatsapp_entry is not None- current_sender = whatsapp_entry.standalone_sender_fn- whatsapp_entry.standalone_sender_fn = legacy_sender- try:- with pytest.raises(SystemExit) as exc:- send_cmd.cmd_send(_parse([- "--to", "whatsapp:[email protected]",- "--mention", "15550000001", "hello @15550000001",- ]))- assert exc.value.code == 1- assert "does not support native mentions" in capsys.readouterr().err- finally:- whatsapp_entry.standalone_sender_fn = current_sender- assert calls == []- bridge_state["supports_mentions"] = False[email protected]("argv", [+ ["--to", "telegram", "--mention", "15550000001", "hello"],+ ["--to", _GROUP, "--mention", "not-a-phone", "hello"],+ ["--to", _GROUP, "--mention", "\u0661\u0665\u0665\u0665\u0660\u0660\u0660\u0660\u0660\u0660\u0661", "hello"],+ ["--to", _GROUP, "--mention", "\u0661\u0665\u0665\u0665\u0660\u0660\u0660\u0660\u0660\u0660\[email protected]", "hello"],+])+def test_whatsapp_mention_rejections_never_reach_the_bridge(whatsapp_bridge, capsys, argv):+ """Non-WhatsApp targets and non-ASCII / non-numeric mention values are usage errors (exit 2)+ raised before any delivery attempt."""with pytest.raises(SystemExit) as exc:- send_cmd.cmd_send(_parse([- "--to", "whatsapp:[email protected]",- "--mention", "15550000001", "hello @15550000001",- ]))- assert exc.value.code == 1- assert "does not support native mentions" in capsys.readouterr().err- bridge_state["supports_mentions"] = True- calls.clear()+ send_cmd.cmd_send(_parse(argv))+ assert exc.value.code == 2+ assert "mention" in capsys.readouterr().err.lower()+ assert whatsapp_bridge.calls == []++def test_whatsapp_mentions_ride_the_first_bridge_payload_only(whatsapp_bridge, tmp_path, capsys):+ """Across chunked text and text+media, exactly one bridge payload carries the normalized,+ deduplicated JIDs; a captioned single-media send carries them on the media payload; a bridge+ without native-mention support fails closed instead of silently sending an unmentioned message."""+ calls = whatsapp_bridge.callsimage = tmp_path / "photo.png"image.write_bytes(b"\x89PNG\r\n\x1a\n")long_message = "@15550000001 " + "word " * 1000- text_args = _parse([- "--to", "whatsapp:[email protected]",- "--mention", "+1 (555) 000-0001",- "--mention", "[email protected]",- f"{long_message} MEDIA:{image}",- ])+with pytest.raises(SystemExit) as exc:- send_cmd.cmd_send(text_args)+ send_cmd.cmd_send(_parse([+ "--to", _GROUP, "--mention", "+1 (555) 000-0001", "--mention", "[email protected]",+ f"{long_message} MEDIA:{image}",+ ]))assert exc.value.code == 0- text_payloads = [payload for url, payload in calls if url.endswith("/send")]- assert len(text_payloads) >= 2+ text_payloads = [payload for path, payload in calls if path == "send"]+ assert len(text_payloads) >= 2 and calls[-1][0] == "send-media"assert text_payloads[0]["mentions"] == ["[email protected]"]- assert calls[-1][0].endswith("/send-media")assert all("mentions" not in payload for _, payload in calls[1:])calls.clear()- media_args = _parse([- "--to", "whatsapp:[email protected]",- "--mention", "15550000001",- f"hello @15550000001 MEDIA:{image}",- ])with pytest.raises(SystemExit) as exc:- send_cmd.cmd_send(media_args)+ send_cmd.cmd_send(_parse(["--to", _GROUP, "--mention", "15550000001", f"hello @15550000001 MEDIA:{image}"]))assert exc.value.code == 0- assert len(calls) == 1 and calls[0][0].endswith("/send-media")+ assert [path for path, _ in calls] == ["send-media"]assert calls[0][1]["mentions"] == ["[email protected]"]----------# ----------------------------------------------------------------------------# Error paths-# -----------------------------------------------------------------------------+ calls.clear()+ whatsapp_bridge.state["supports_mentions"] = False+ with pytest.raises(SystemExit) as exc:+ send_cmd.cmd_send(_parse(["--to", _GROUP, "--mention", "15550000001", "hello @15550000001"]))+ assert exc.value.code == 1+ assert "does not support native mentions" in capsys.readouterr().err+ assert calls == []def test_file_decode_error_suggests_media_directive(fake_tool, capsys, monkeypatch, tmp_path):diff --git a/tools/send_message_senders.py b/tools/send_message_senders.pyindex 8f6c1296355..1e1e3530172 100644--- a/tools/send_message_senders.py+++ b/tools/send_message_senders.py@@ -2,7 +2,6 @@import asyncioimport contextlib-import inspectimport loggingimport osimport re@@ -338,41 +337,6 @@ async def _registry_standalone_send(platform_name, pconfig, chat_id, message, threturn err or await sender(pconfig, chat_id, message, thread_id=thread_id)-async def _send_whatsapp_with_mentions(pconfig, chat_id, message, chunks, media_files, *, thread_id,- max_len, force_document, mentions):- """Send WhatsApp text/media while attaching native mention JIDs to the first payload only."""- sender, err = _plugin_standalone_sender("whatsapp", label="WhatsApp")- if sender is None:- return err- try:- parameters = inspect.signature(sender).parameters.values()- except (TypeError, ValueError):- parameters = ()- if not any(- parameter.name == "mentions" or parameter.kind is inspect.Parameter.VAR_KEYWORD- for parameter in parameters- ):- return {"error": "Registered WhatsApp sender does not support native mentions; update the plugin."}- caption, _ = _media_caption_split(message, media_files, max_caption_len=(max_len or _DEFAULT_CAPTION_LIMIT))- if caption is not None:- return await sender(- pconfig, chat_id, "", thread_id=thread_id, media_files=media_files,- caption=caption, force_document=force_document, mentions=mentions)- result = None- for index, chunk in enumerate(chunks):- kwargs = {- "thread_id": thread_id,- "media_files": media_files if index == len(chunks) - 1 else None,- "force_document": force_document,- }- if index == 0:- kwargs["mentions"] = mentions- result = await sender(pconfig, chat_id, chunk, **kwargs)- if isinstance(result, dict) and result.get("error"):- break- return result--async def _resolve_slack_user_target(token, chat_id):"""Resolve ``user:U...`` / ``user_name:<handle>`` to a D... DM conversation (chat.postMessageneeds a conversation ID); ``user_name:`` goes through users.list first (stable handle matchdiff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex c8d88d1f30b..70fd88e5581 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -16,8 +16,7 @@ from tools.send_message_senders import (_AUDIO_EXTS, _DEFAULT_CAPTION_LIMIT, _IMAGE_EXTS, _NO_DELIVERABLE, _VIDEO_EXTS, _VOICE_EXTS,_adapter_media_method, _error, _live_adapter, _media_caption_split, _plugin_standalone_sender,_registry_standalone_send, _resolve_slack_user_target, _sanitize_error_text, _send_bluebubbles,- _send_matrix_via_adapter, _send_qqbot, _send_signal, _send_telegram, _send_weixin,- _send_whatsapp_with_mentions, _send_yuanbao)+ _send_matrix_via_adapter, _send_qqbot, _send_signal, _send_telegram, _send_weixin, _send_yuanbao)from tools.registry import tool_error# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model tool@@ -264,13 +263,15 @@ def _handle_send(args):try:from model_tools import _run_async- mention_args = ({"mentions": args["mentions"]}- if platform_name == "whatsapp" and args.get("mentions") else {})- # Only custom plugin handlers receive the complete typed request.+ # Only custom plugin handlers receive the complete typed request. ``mentions`` is a WhatsApp-only+ # contract (the CLI rejects it elsewhere); other platforms' standalone senders don't accept the kwarg.handler_args = {"args": args} if entry is not None and entry.send_message_handler is not None else {}+ mentions = args.get("mentions")+ if mentions and platform_name == "whatsapp":+ handler_args["mentions"] = [mentions] if isinstance(mentions, str) else list(mentions)result = _run_async(_send_to_platform(platform, pconfig, chat_id, cleaned_message, thread_id=thread_id,media_files=media_files, force_document=force_document_attachments,- **mention_args, **handler_args))+ **handler_args))if isinstance(result, dict) and result.get("success"):if used_home_channel:result["note"] = f"Sent to {platform_name} home channel (chat_id: {chat_id})"@@ -616,22 +617,29 @@ _PLUGIN_STANDALONE_MEDIA = {"discord": ("Discord", False, True, [], False), "feiasync def _send_plugin_standalone(platform_name, pconfig, chat_id, message, chunks, media_files, *, thread_id,- max_len, force_document):+ max_len, force_document, mentions=None):"""Chunked send through a plugin's standalone_sender_fn; one captionable file + short text- rides as the media caption."""+ rides as the media caption. WhatsApp re-pings recipients on every message that carries+ ``mentions``, so only the first payload of a logical send gets them."""label, discover, captionable, empty_media, pass_force = _PLUGIN_STANDALONE_MEDIA[platform_name]sender, err = _plugin_standalone_sender(platform_name, label=label, discover=discover)if err:return errextra = {"force_document": force_document} if pass_force else {}+ first_only = {"mentions": mentions} if mentions else {}if captionable:# Cap on the platform's own message limit so the caption is deliverable.caption, _ = _media_caption_split(message, media_files, max_caption_len=(max_len or _DEFAULT_CAPTION_LIMIT))if caption is not None:return await sender(pconfig, chat_id, "", thread_id=thread_id, media_files=media_files,- caption=caption, **extra)- return await _send_chunks(chunks, lambda chunk, is_last: sender(- pconfig, chat_id, chunk, thread_id=thread_id, media_files=media_files if is_last else empty_media, **extra))+ caption=caption, **extra, **first_only)++ def send_one(chunk, is_last):+ kwargs = {**extra, **first_only}+ first_only.clear()+ return sender(pconfig, chat_id, chunk, thread_id=thread_id,+ media_files=media_files if is_last else empty_media, **kwargs)+ return await _send_chunks(chunks, send_one)def _via_adapter_route(p, pc, cid, chunk, media, tid, fd):@@ -684,13 +692,11 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,from gateway.platforms.base import BasePlatformAdaptermax_len = _platform_max_length(platform)chunks = BasePlatformAdapter.truncate_message(message, max_len) if max_len else [message]- if platform_name == "whatsapp" and mentions:- return await _send_whatsapp_with_mentions(- pconfig, chat_id, message, chunks, media_files, thread_id=thread_id,- max_len=max_len, force_document=force_document, mentions=mentions)- if platform_name == "discord" or (media_files and platform_name in _PLUGIN_STANDALONE_MEDIA):+ if (platform_name == "discord" or (platform_name == "whatsapp" and mentions)+ or (media_files and platform_name in _PLUGIN_STANDALONE_MEDIA)):return await _send_plugin_standalone(platform_name, pconfig, chat_id, message, chunks, media_files,- thread_id=thread_id, max_len=max_len, force_document=force_document)+ thread_id=thread_id, max_len=max_len, force_document=force_document,+ mentions=mentions)route = _CHUNKED_ROUTES.get(platform_name)if route is not None and (media_files or not route[0]):_, empty_media, sender = route