Skip to content

The agent that grows with you

send_message: plugin enricher registry for custom platforms

Kevin Anderson482682db785a
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 1318726a162..d2d8e28bb29 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -1272,6 +1272,38 @@ class PluginContext:
self.manifest.name, provider.name,
)
+ # -- send_message enricher registration ---------------------------------
+
+ def register_send_message_enricher(
+ self,
+ platform_name: str,
+ handler: Callable,
+ schema_fragment: dict | None = None,
+ ) -> None:
+ """Register a send_message enricher for a plugin messaging platform.
+
+ Lets plugin platforms extend ``send_message`` with custom target
+ prefixes, schema fields, and send handlers without modifying core code.
+
+ Args:
+ platform_name: Platform key used in target strings
+ (e.g. ``"myplatform"`` → ``myplatform:chat_id``).
+ handler: Async or sync callable receiving
+ ``(args, chat_id, platform_name, pconfig)`` and returning
+ a dict like ``{"success": True, "message_id": "..."}``
+ or ``{"error": "..."}``.
+ schema_fragment: Optional dict of JSON-schema properties to merge
+ into ``send_message``'s parameter schema so the LLM sees the
+ custom fields.
+ """
+ from tools.send_message_tool import register_send_message_enricher as _register_enricher
+ _register_enricher(platform_name, handler, schema_fragment=schema_fragment)
+ logger.debug(
+ "Plugin %s registered send_message enricher: %s",
+ self.manifest.name,
+ platform_name,
+ )
+
# -- platform adapter registration ---------------------------------------
def register_platform(
diff --git a/tests/tools/test_send_message_enrichers.py b/tests/tools/test_send_message_enrichers.py
new file mode 100644
index 00000000000..7a8694cf18e
--- /dev/null
+++ b/tests/tools/test_send_message_enrichers.py
@@ -0,0 +1,162 @@
+"""Tests for send_message plugin enrichers."""
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from tools.send_message_tool import (
+ SEND_MESSAGE_SCHEMA,
+ _SEND_MESSAGE_ENRICHERS,
+ _parse_target_ref,
+ _send_to_platform,
+ register_send_message_enricher,
+)
+
+
[email protected](autouse=True)
+def _reset_enrichers():
+ """Clear the enricher registry before and after every test."""
+ _SEND_MESSAGE_ENRICHERS.clear()
+ # Also clear any schema fragments injected by previous tests
+ for key in list(SEND_MESSAGE_SCHEMA["parameters"]["properties"]):
+ if key not in {
+ "action",
+ "target",
+ "message",
+ "emoji",
+ "message_id",
+ }:
+ SEND_MESSAGE_SCHEMA["parameters"]["properties"].pop(key, None)
+ yield
+ _SEND_MESSAGE_ENRICHERS.clear()
+ for key in list(SEND_MESSAGE_SCHEMA["parameters"]["properties"]):
+ if key not in {
+ "action",
+ "target",
+ "message",
+ "emoji",
+ "message_id",
+ }:
+ SEND_MESSAGE_SCHEMA["parameters"]["properties"].pop(key, None)
+
+
+class TestParseTargetRef:
+ def test_enricher_target_parsing(self):
+ """Plugin-enriched platforms treat the target_ref as explicit."""
+ register_send_message_enricher("myplatform", AsyncMock())
+ chat_id, thread_id, is_explicit = _parse_target_ref("myplatform", "+123")
+ assert chat_id == "+123"
+ assert thread_id is None
+ assert is_explicit is True
+
+ def test_builtin_precedence(self):
+ """Built-in platforms win over enrichers with the same name."""
+ register_send_message_enricher("telegram", AsyncMock())
+ chat_id, thread_id, is_explicit = _parse_target_ref("telegram", "777")
+ assert chat_id == "777"
+ assert thread_id is None
+ assert is_explicit is True
+
+ def test_enricher_empty_target_ref(self):
+ """Empty target_ref for an enriched platform is not explicit."""
+ register_send_message_enricher("myplatform", AsyncMock())
+ chat_id, thread_id, is_explicit = _parse_target_ref("myplatform", "")
+ assert chat_id is None
+ assert thread_id is None
+ assert is_explicit is False
+
+
+class TestSchemaMerge:
+ def test_schema_fragment_merged(self):
+ """Schema fragments are injected into SEND_MESSAGE_SCHEMA."""
+ register_send_message_enricher(
+ "myplatform",
+ AsyncMock(),
+ schema_fragment={"voice": {"type": "string", "description": "Voice setting"}},
+ )
+ props = SEND_MESSAGE_SCHEMA["parameters"]["properties"]
+ assert "voice" in props
+ assert props["voice"]["type"] == "string"
+
+ def test_schema_fragment_without_registration(self):
+ """No fragment is added when schema_fragment is omitted."""
+ register_send_message_enricher("myplatform", AsyncMock())
+ props = SEND_MESSAGE_SCHEMA["parameters"]["properties"]
+ assert "voice" not in props
+
+
+class TestHandlerRouting:
+ def test_enricher_handler_invoked(self):
+ """The enricher handler receives correct arguments."""
+ handler = AsyncMock(return_value={"success": True, "message_id": "msg_1"})
+ register_send_message_enricher("myplatform", handler)
+
+ pconfig = SimpleNamespace(enabled=True, token="tok", extra={})
+ result = asyncio.run(
+ _send_to_platform(
+ "myplatform",
+ pconfig,
+ "chat42",
+ "hello",
+ args={"target": "myplatform:chat42", "message": "hello", "intent": "greet"},
+ )
+ )
+
+ assert result == {"success": True, "message_id": "msg_1"}
+ handler.assert_awaited_once()
+ call_args = handler.await_args.args
+ assert call_args[0] == {"target": "myplatform:chat42", "message": "hello", "intent": "greet"}
+ assert call_args[1] == "chat42"
+ assert call_args[2] == "myplatform"
+ assert call_args[3] is pconfig
+
+ def test_enricher_handler_result(self):
+ """Enricher result is returned verbatim."""
+ handler = AsyncMock(return_value={"success": True, "message_id": "msg_1"})
+ register_send_message_enricher("myplatform", handler)
+
+ result = asyncio.run(
+ _send_to_platform(
+ "myplatform",
+ SimpleNamespace(enabled=True, token="tok", extra={}),
+ "chat42",
+ "hello",
+ )
+ )
+ assert result == {"success": True, "message_id": "msg_1"}
+
+ def test_enricher_handler_error(self):
+ """Enricher exceptions are caught and surfaced as error dicts."""
+ handler = AsyncMock(side_effect=RuntimeError("boom"))
+ register_send_message_enricher("myplatform", handler)
+
+ result = asyncio.run(
+ _send_to_platform(
+ "myplatform",
+ SimpleNamespace(enabled=True, token="tok", extra={}),
+ "chat42",
+ "hello",
+ )
+ )
+ assert "error" in result
+ assert "boom" in result["error"]
+
+
+class TestFallback:
+ def test_no_enricher_falls_through(self):
+ """Platforms without an enricher still reach _send_via_adapter."""
+ result = asyncio.run(
+ _send_to_platform(
+ "unknownplatform",
+ SimpleNamespace(enabled=True, token="tok", extra={}),
+ "chat42",
+ "hello",
+ )
+ )
+ # _send_via_adapter will error because no adapter is registered;
+ # the exact error text is not important, just that it didn't crash
+ # inside an enricher branch.
+ assert isinstance(result, dict)
+ assert "error" in result
diff --git a/tests/tools/test_send_message_target_parse.py b/tests/tools/test_send_message_target_parse.py
index 761eabb2802..0c5971a0a86 100644
--- a/tests/tools/test_send_message_target_parse.py
+++ b/tests/tools/test_send_message_target_parse.py
@@ -62,5 +62,6 @@ def test_send_message_routes_whatsapp_group_jid_without_home_fallback() -> None:
thread_id=None,
media_files=[],
force_document=False,
+ args={"action": "send", "target": "whatsapp:[email protected]", "message": "hello group"},
)
diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py
index 2853c6275c4..7b926fb4658 100644
--- a/tools/send_message_tool.py
+++ b/tools/send_message_tool.py
@@ -11,6 +11,7 @@ import logging
import os
import re
import time
+from typing import Any, Awaitable, Callable
from agent.redact import redact_sensitive_text
from agent.secret_scope import get_secret
@@ -85,6 +86,32 @@ _CAPTIONABLE_EXTS = _IMAGE_EXTS | _VIDEO_EXTS | {
_TELEGRAM_CAPTION_LIMIT = 1024
_DEFAULT_CAPTION_LIMIT = 4096
+# ---------------------------------------------------------------------------
+# Plugin enricher registry for send_message
+# ---------------------------------------------------------------------------
+
+SendMessageEnricher = Callable[[dict, str, str, Any], Awaitable[dict]]
+"""Callable receiving (args, chat_id, platform_name, pconfig) -> dict result."""
+
+_SEND_MESSAGE_ENRICHERS: dict[str, SendMessageEnricher] = {}
+"""platform_name -> enricher handler."""
+
+
+def register_send_message_enricher(
+ platform_name: str,
+ handler: SendMessageEnricher,
+ schema_fragment: dict | None = None,
+) -> None:
+ """Register a platform-specific enricher for the send_message tool.
+
+ Enrichers let plugin platforms extend send_message with custom target
+ parsing, schema fields, and send logic without modifying core code.
+ """
+ _SEND_MESSAGE_ENRICHERS[platform_name] = handler
+ if schema_fragment:
+ for key, spec in schema_fragment.items():
+ SEND_MESSAGE_SCHEMA["parameters"]["properties"][key] = spec
+
def _media_caption_split(text, media_files, *, max_caption_len):
"""Decide whether the accompanying text should ride on the media bubble.
@@ -406,7 +433,10 @@ def _handle_send(args):
try:
platform = Platform(platform_name)
except (ValueError, KeyError):
- return tool_error(f"Unknown platform: {platform_name}")
+ if platform_name in _SEND_MESSAGE_ENRICHERS:
+ platform = platform_name
+ else:
+ return tool_error(f"Unknown platform: {platform_name}")
pconfig = config.platforms.get(platform)
if not pconfig or not pconfig.enabled:
@@ -496,6 +526,7 @@ def _handle_send(args):
thread_id=thread_id,
media_files=media_files,
force_document=force_document_attachments,
+ args=args,
)
)
if used_home_channel and isinstance(result, dict) and result.get("success"):
@@ -617,6 +648,11 @@ def _parse_target_ref(platform_name: str, target_ref: str):
# XMPP JIDs (user@server or [email protected]) are explicit
if platform_name == "xmpp" and "@" in target_ref:
return target_ref, None, True
+ # Plugin-enriched platforms
+ if platform_name in _SEND_MESSAGE_ENRICHERS:
+ if target_ref:
+ return target_ref, None, True
+ return None, None, False
return None, None, False
@@ -780,7 +816,7 @@ async def _send_via_adapter(
}
-async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, media_files=None, force_document=False):
+async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None, media_files=None, force_document=False, args=None):
"""Route a message to the appropriate platform sender.
Long messages are automatically chunked to fit within platform limits
@@ -789,6 +825,8 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
"""
from gateway.config import Platform
+ platform_name = platform.value if hasattr(platform, "value") else str(platform)
+
media_files = media_files or []
# Weixin handles text/media delivery inside its native helper and does not
@@ -1141,6 +1179,14 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
elif platform == Platform.YUANBAO:
result = await _send_yuanbao(chat_id, chunk)
else:
+ enricher = _SEND_MESSAGE_ENRICHERS.get(platform_name)
+ if enricher:
+ if args is None:
+ args = {}
+ try:
+ return await enricher(args, chat_id, platform_name, pconfig)
+ except Exception as e:
+ return {"error": f"Enricher send failed: {e}"}
# Plugin platform: route through the gateway's live adapter if
# available, otherwise the plugin's standalone_sender_fn.
result = await _send_via_adapter(