Skip to content

The agent that grows with you

feat(send): add WhatsApp native mentions

Andreyb34ebc084a20
diff --git a/gateway/whatsapp_identity.py b/gateway/whatsapp_identity.py
index f8ea45377c6..5dcad7c8bd2 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 digits and human separators.
+# "Just a phone number": optional ``+`` then ASCII digits and human separators.
# Anything carrying ``@`` is already a JID (``@g.us``, ``@lid``, ``status@broadcast``).
-_BARE_PHONE_RE = re.compile(r"^\+?[\d\s().\-]+$")
+_BARE_PHONE_RE = re.compile(r"^\+?[0-9\s().\-]+$")
def normalize_whatsapp_identifier(value: str) -> str:
@@ -46,12 +46,26 @@ def to_whatsapp_jid(value: str) -> str:
if "@" in normalized:
return normalized
if _BARE_PHONE_RE.fullmatch(normalized):
- digits = re.sub(r"\D+", "", normalized)
+ digits = re.sub(r"[^0-9]+", "", normalized)
if digits:
return f"{digits}@s.whatsapp.net"
return normalized
+def normalize_whatsapp_mention_jid(value: str) -> str:
+ """Return a valid participant JID for an outbound mention, or ``""``."""
+ jid = to_whatsapp_jid(value)
+ user, separator, domain = jid.partition("@")
+ return (
+ jid
+ if separator
+ and user.isascii()
+ and user.isdigit()
+ and domain in {"s.whatsapp.net", "lid"}
+ else ""
+ )
+
+
def expand_whatsapp_aliases(identifier: str) -> Set[str]:
"""All identifiers transitively reachable via the bridge's ``lid-mapping-*.json`` files;
always includes the normalized input itself (empty set if it normalizes to empty)."""
diff --git a/hermes_cli/send_cmd.py b/hermes_cli/send_cmd.py
index f977119bf5d..c7b02396e9b 100644
--- a/hermes_cli/send_cmd.py
+++ b/hermes_cli/send_cmd.py
@@ -52,6 +52,13 @@ def _read_message_body(positional: Optional[str], file_path: Optional[str]) -> O
return (sys.stdin.read() or None) if not sys.stdin.isatty() else None
+def _invalid_whatsapp_mentions(mentions: list[str]) -> list[str]:
+ """Return mention values that cannot identify a WhatsApp participant."""
+ from gateway.whatsapp_identity import normalize_whatsapp_mention_jid
+
+ return [mention for mention in mentions if not normalize_whatsapp_mention_jid(mention)]
+
+
def _emit_result(result_json: str, *, json_mode: bool, quiet: bool) -> int:
"""Print the ``send_message_tool`` JSON result in the requested format; return the exit code.
Unknown / unexpected shapes are failures so scripts notice."""
@@ -200,6 +207,15 @@ def cmd_send(args: argparse.Namespace) -> None:
" hermes send --to discord:#ops --file report.md\n"
" hermes send --list # list available targets",
_USAGE_EXIT)
+ 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 []
+ if invalid_mentions:
+ _fail(
+ "hermes send: invalid --mention value(s): "
+ f"{', '.join(invalid_mentions)}. Use a phone number or participant JID.",
+ _USAGE_EXIT)
message = _read_message_body(getattr(args, "message", None), getattr(args, "file", None))
if message is None or not message.strip():
_fail(
@@ -217,7 +233,10 @@ def cmd_send(args: argparse.Namespace) -> None:
# Routes to the platform adapter (bot-token path for built-ins, live-adapter path for plugin
# platforms); takes the standard tool-call dict and returns a JSON string.
- result = send_message_tool({"action": "send", "target": target, "message": message})
+ tool_args = {"action": "send", "target": target, "message": message}
+ if mentions:
+ tool_args["mentions"] = mentions
+ result = send_message_tool(tool_args)
sys.exit(_emit_result(result, json_mode=getattr(args, "json", False), quiet=getattr(args, "quiet", False)))
@@ -233,6 +252,9 @@ _SEND_ARGUMENTS = (
"Read message body from PATH (text only). Use '-' to force stdin. "
"To send an image/document as an attachment, use MEDIA:<path> in the message text instead."))),
(("-s", "--subject"), dict(metavar="LINE", default=None, help="Prepend a subject/header line before the message body.")),
+ (("--mention",), dict(dest="mentions", action="append", default=None, metavar="PHONE_OR_JID", help=(
+ "WhatsApp only: add a native participant mention. Repeat for multiple recipients; "
+ "bare phone numbers are normalized to JIDs. Include each matching @<number> near the start of the message text."))),
(("-l", "--list"), dict(dest="list_targets", action="store_true", default=False,
help="List available targets. Optional positional filter: `hermes send --list telegram`.")),
(("-q", "--quiet"), dict(action="store_true", default=False, help="Suppress stdout on success (exit code only).")),
@@ -261,6 +283,7 @@ def register_send_subparser(subparsers) -> argparse.ArgumentParser:
" echo \"RAM 92%\" | hermes send --to telegram:-1001234567890\n"
" hermes send --to discord:#ops --file /tmp/report.md\n"
" hermes send --to slack:#eng --subject \"[CI]\" --file build.log\n"
+ " hermes send --to whatsapp:[email protected] --mention 15551234567 \"@15551234567 hello\"\n"
" hermes send --to telegram \"MEDIA:/tmp/chart.png\" # send a media attachment\n"
" hermes send --list # all platforms\n"
" hermes send --list telegram # filter by platform\n"
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index bab4525237b..e32e5a32525 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -174,7 +174,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from gateway.config import Platform, PlatformConfig
from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin
-from gateway.whatsapp_identity import to_whatsapp_jid
+from gateway.whatsapp_identity import normalize_whatsapp_mention_jid, to_whatsapp_jid
from gateway.platforms.base import (
BasePlatformAdapter, SendResult, SUPPORTED_DOCUMENT_TYPES, cache_image_from_url, cache_audio_from_url,
)
@@ -884,7 +884,25 @@ 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")
-async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False, caption=None):
+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
+
+
+async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False,
+ caption=None, mentions=None):
"""Out-of-process delivery via the bridge HTTP API (standalone_sender_fn: cron apart from the gateway); ``caption`` rides on the media bubble."""
try:
import aiohttp
@@ -896,8 +914,28 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
media = media_files or []
# 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 None
+ pending_mentions = _normalize_outbound_mentions(mentions)
+
+ def _mention_first_payload(payload):
+ nonlocal pending_mentions
+ if pending_mentions:
+ payload["mentions"] = pending_mentions
+ pending_mentions = []
+ return payload
+
last_message_id = None
async with aiohttp.ClientSession() as session:
+ if pending_mentions:
+ async with session.get(
+ f"http://localhost:{bridge_port}/health",
+ timeout=aiohttp.ClientTimeout(total=5),
+ ) as resp:
+ health = await resp.json() if resp.status == 200 else {}
+ if not (health.get("capabilities") or {}).get("outboundMentions"):
+ return {"error": (
+ "WhatsApp bridge does not support native mentions; "
+ "restart it from the same Hermes version.")}
+
async def _post(path, payload, total, error_label=None):
"""``(messageId, None)`` on 200, else ``(None, error_dict)`` (body read only when labelled)."""
url = f"http://localhost:{bridge_port}/{path}"
@@ -907,7 +945,8 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
return None, {} if error_label is None else send_error(f"WhatsApp {error_label} error ({resp.status}): {await resp.text()}")
# 1) Text first (skipped when media-only or when the text rides as the caption).
if (message or "").strip() and not media_caption:
- last_message_id, err = await _post("send", {"chatId": normalized_chat_id, "message": message}, 30, "bridge")
+ payload = _mention_first_payload({"chatId": normalized_chat_id, "message": message})
+ last_message_id, err = await _post("send", payload, 30, "bridge")
if err:
return err
# 2) Each media file as a native attachment (mediaType picks the WhatsApp kind).
@@ -916,13 +955,15 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
# In caption mode the words would vanish with the missing file — deliver the caption as a plain message.
if media_caption:
try:
- await _post("send", {"chatId": normalized_chat_id, "message": media_caption}, 30)
+ payload = _mention_first_payload({"chatId": normalized_chat_id, "message": media_caption})
+ await _post("send", payload, 30)
except Exception:
logger.warning("WhatsApp caption-fallback send failed for missing media")
return send_error(f"WhatsApp media file not found: {media_path}")
media_type = _bridge_media_type(media_path, is_voice, force_document)
payload: Dict[str, Any] = {"chatId": normalized_chat_id, "filePath": media_path, "mediaType": media_type}
payload.update({k: v for k, v in (("fileName", os.path.basename(media_path) if media_type == "document" else None), ("caption", media_caption)) if v})
+ payload = _mention_first_payload(payload)
mid, err = await _post("send-media", payload, 120, "media")
if err:
return err
diff --git a/scripts/whatsapp-bridge/bridge.js b/scripts/whatsapp-bridge/bridge.js
index c91cd112811..b00a1fec026 100644
--- a/scripts/whatsapp-bridge/bridge.js
+++ b/scripts/whatsapp-bridge/bridge.js
@@ -7,9 +7,9 @@
*
* Endpoints (matches gateway/platforms/whatsapp.py expectations):
* GET /messages - Long-poll for new incoming messages
- * POST /send - Send a message { chatId, message, replyTo? }
+ * POST /send - Send a message { chatId, message, replyTo?, mentions? }
* POST /edit - Edit a sent message { chatId, messageId, message }
- * POST /send-media - Send media natively { chatId, filePath, mediaType?, caption?, fileName? }
+ * POST /send-media - Send media natively { chatId, filePath, mediaType?, caption?, fileName?, mentions? }
* POST /send-location - Send location pin { chatId, latitude, longitude, name?, address? }
* POST /typing - Send typing indicator { chatId }
* GET /chat/:id - Get chat info
@@ -34,6 +34,7 @@ import { matchesAllowedUser, parseAllowedUsers } from './allowlist.js';
import { createOutboundIdTracker } from './outbound_ids.js';
import { classifyOwnerMessageGate } from './owner_message_gate.js';
import {
+ addMentions,
buildPollPayload,
createReconnectScheduler,
createVersionResolver,
@@ -816,7 +817,7 @@ app.post('/send', async (req, res) => {
return res.status(503).json({ error: 'Not connected to WhatsApp' });
}
- const { chatId, message, replyTo } = req.body;
+ const { chatId, message, replyTo, mentions } = req.body;
if (!chatId || !message) {
return res.status(400).json({ error: 'chatId and message are required' });
}
@@ -828,6 +829,7 @@ app.post('/send', async (req, res) => {
const { content: payload, options } = buildTextSendPayload(chunks[i], {
chatId,
replyTo: i === 0 ? replyTo : undefined,
+ mentions: i === 0 ? mentions : undefined,
messageStore,
});
const sent = await sendWithTimeout(chatId, payload, options);
@@ -889,7 +891,7 @@ app.post('/send-media', async (req, res) => {
return res.status(503).json({ error: 'Not connected to WhatsApp' });
}
- const { chatId, filePath, mediaType, caption, fileName } = req.body;
+ const { chatId, filePath, mediaType, caption, fileName, mentions } = req.body;
if (!chatId || !filePath) {
return res.status(400).json({ error: 'chatId and filePath are required' });
}
@@ -973,6 +975,8 @@ app.post('/send-media', async (req, res) => {
break;
}
+ msgPayload = addMentions(msgPayload, mentions);
+
const sent = await sendWithTimeout(chatId, msgPayload);
trackSentMessageId(sent);
messageStore.remember(sent);
@@ -1102,6 +1106,7 @@ app.get('/health', (req, res) => {
uptime: process.uptime(),
scriptHash: SCRIPT_HASH,
sendReadReceipts: SEND_READ_RECEIPTS,
+ capabilities: { outboundMentions: true },
});
});
diff --git a/scripts/whatsapp-bridge/bridge.native.test.mjs b/scripts/whatsapp-bridge/bridge.native.test.mjs
index 87bfd48bd8e..2165e94630e 100644
--- a/scripts/whatsapp-bridge/bridge.native.test.mjs
+++ b/scripts/whatsapp-bridge/bridge.native.test.mjs
@@ -13,6 +13,7 @@ import path from 'node:path';
import { getAggregateVotesInPollMessage } from '@whiskeysockets/baileys';
import {
+ addMentions,
buildPollPayload,
buildTextSendPayload,
createBoundedMessageStore,
@@ -83,6 +84,16 @@ import {
console.log(' ✓ unresolved replyTo falls back to plain text');
}
+{
+ const mentions = ['[email protected]'];
+ const { content } = buildTextSendPayload('hello @15550001111', { mentions });
+ const media = addMentions({ image: Buffer.from('png'), caption: 'hello @15550001111' }, mentions);
+
+ assert.deepEqual(content.mentions, mentions);
+ assert.deepEqual(media.mentions, mentions);
+ console.log(' ✓ outbound text and media payloads preserve native mention JIDs');
+}
+
// -- inbound quote/media/native metadata --------------------------------
{
const event = await extractBridgeEvent({
diff --git a/scripts/whatsapp-bridge/bridge_helpers.js b/scripts/whatsapp-bridge/bridge_helpers.js
index 33a42152c6b..6769c734e5f 100644
--- a/scripts/whatsapp-bridge/bridge_helpers.js
+++ b/scripts/whatsapp-bridge/bridge_helpers.js
@@ -216,8 +216,15 @@ export function pollUpdateForAggregation({
return null;
}
-export function buildTextSendPayload(text, { replyTo, messageStore } = {}) {
- const content = { text };
+export function addMentions(payload, mentions) {
+ if (payload && Array.isArray(mentions) && mentions.length > 0) {
+ payload.mentions = mentions;
+ }
+ return payload;
+}
+
+export function buildTextSendPayload(text, { replyTo, messageStore, mentions } = {}) {
+ const content = addMentions({ text }, mentions);
const options = {};
const quoted = messageStore?.get(replyTo);
if (quoted?.key && quoted?.message) {
diff --git a/tests/hermes_cli/test_send_cmd.py b/tests/hermes_cli/test_send_cmd.py
index c88e634d2ae..d9c8022daa1 100644
--- a/tests/hermes_cli/test_send_cmd.py
+++ b/tests/hermes_cli/test_send_cmd.py
@@ -64,6 +64,143 @@ 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."""
+ import asyncio
+ from types import SimpleNamespace
+
+ import aiohttp
+
+ from gateway.config import Platform
+ from gateway.platform_registry import platform_registry
+ from hermes_cli.plugins import discover_plugins
+
+ calls = []
+ bridge_state = {"supports_mentions": True}
+
+ class BridgeResponse:
+ status = 200
+
+ def __init__(self, *, health=False):
+ self.health = health
+
+ async def json(self):
+ if self.health:
+ return {"capabilities": {"outboundMentions": bridge_state["supports_mentions"]}}
+ return {"messageId": f"m{len(calls)}"}
+
+ async def text(self):
+ return ""
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return False
+
+ class BridgeSession:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return False
+
+ def get(self, url, *, timeout):
+ return BridgeResponse(health=True)
+
+ def post(self, url, *, json, timeout):
+ calls.append((url, json))
+ return BridgeResponse()
+
+ discover_plugins()
+ whatsapp_config = SimpleNamespace(enabled=True, token=None, extra={"bridge_port": 3000})
+ config = SimpleNamespace(
+ platforms={Platform.WHATSAPP: whatsapp_config},
+ get_home_channel=lambda _platform: None,
+ )
+ monkeypatch.setattr(send_cmd, "_load_hermes_env", lambda: None)
+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
+ monkeypatch.setattr("tools.interrupt.is_interrupted", lambda: False)
+ monkeypatch.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())
+
+ 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
+ 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()
+
+ image = 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)
+ assert exc.value.code == 0
+ text_payloads = [payload for url, payload in calls if url.endswith("/send")]
+ assert len(text_payloads) >= 2
+ 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)
+ assert exc.value.code == 0
+ assert len(calls) == 1 and calls[0][0].endswith("/send-media")
+ assert calls[0][1]["mentions"] == ["[email protected]"]
+
+
@@ -213,7 +350,7 @@ def test_load_hermes_env_bridges_config_yaml_scalars(tmp_path, monkeypatch):
hermes_home = tmp_path / ".hermes"
hermes_home.mkdir()
- (hermes_home / ".env").write_text("SOME_TOKEN=abc123\n")
+ (hermes_home / ".env").write_text("SOME_TOKEN=abc123\n", encoding="utf-8")
(hermes_home / "config.yaml").write_text(
"TELEGRAM_HOME_CHANNEL: '5550001111'\nnested:\n ignored: true\n"
)
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py
index 1e1e3530172..8f6c1296355 100644
--- a/tools/send_message_senders.py
+++ b/tools/send_message_senders.py
@@ -2,6 +2,7 @@
import asyncio
import contextlib
+import inspect
import logging
import os
import re
@@ -337,6 +338,41 @@ async def _registry_standalone_send(platform_name, pconfig, chat_id, message, th
return 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.postMessage
needs a conversation ID); ``user_name:`` goes through users.list first (stable handle match
diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py
index 4d554de62ae..c8d88d1f30b 100644
--- a/tools/send_message_tool.py
+++ b/tools/send_message_tool.py
@@ -16,7 +16,8 @@ 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_yuanbao)
+ _send_matrix_via_adapter, _send_qqbot, _send_signal, _send_telegram, _send_weixin,
+ _send_whatsapp_with_mentions, _send_yuanbao)
from tools.registry import tool_error
# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model tool
@@ -263,11 +264,13 @@ 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.
handler_args = {"args": args} if entry is not None and entry.send_message_handler is not None else {}
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,
- **handler_args))
+ **mention_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})"
@@ -663,7 +666,8 @@ _TEXT_SENDERS = {
_MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp and slack"
-async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, media_files=None, force_document=False, args=None):
+async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, media_files=None,
+ force_document=False, mentions=None, args=None):
"""Route to the platform sender, chunking long text with the adapters' splitter. Order matters:
Weixin first (its native helper must not be blocked by unrelated optional imports such as
lark-oapi), Telegram (chunks itself), plugin standalone media, native chunked, generic text."""
@@ -680,6 +684,10 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
from gateway.platforms.base import BasePlatformAdapter
max_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):
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)