feat(gateway,send_message): plugin platform target parsing via PlatformEntry.parse_target_ref_fn and verbatim fallback (#67941 #33547)

This commit is contained in:
Kevin Anderson
2026-07-21 18:59:23 -06:00
committed by Teknium
parent 274214d3c9
commit a37192546e
4 changed files with 322 additions and 7 deletions
+15
View File
@@ -162,6 +162,21 @@ class PlatformEntry:
# resolve the default chat/room ID. Empty = no cron home-channel support.
cron_deliver_env_var: str = ""
# ── Target parsing ──
# Optional: callable that parses a raw target string for this platform into
# a (chat_id, thread_id) tuple, or None if the string is not a recognized
# explicit target. Invoked by ``tools/send_message_tool._parse_target_ref``
# before channel-directory fallback so plugin platforms can declare their
# own native target syntax (e.g. ``fmsg:@alice@example.com``) without
# hard-casing in Hermes core.
#
# Signature:
# (target_ref: str) -> Optional[tuple[str, Optional[str]]]
#
# If the callable returns None the target proceeds to the usual directory
# resolution / verbatim fallback path.
parse_target_ref_fn: Optional[Callable[[str], Optional[tuple[str, Optional[str]]]]] = None
# ── Standalone (out-of-process) sending ──
# Optional: async coroutine that delivers a message without a live
# gateway adapter. Called by ``tools/send_message_tool._send_via_adapter``
+112
View File
@@ -53,6 +53,118 @@ class TestParseTargetRef:
assert is_explicit is False
class TestPlatformEntryTargetParsing:
def test_parse_target_ref_fn_is_used(self):
"""PlatformEntry.parse_target_ref_fn is consulted for explicit targets."""
from gateway.platform_registry import PlatformEntry, platform_registry
platform_name = "fmsg-parse-test"
def _parser(ref):
if ref.startswith("@") and "@" in ref[1:]:
return ref, None
return None
entry = PlatformEntry(
name=platform_name,
label="Fmsg parse test",
adapter_factory=lambda cfg: None,
check_fn=lambda: True,
parse_target_ref_fn=_parser,
)
platform_registry.register(entry)
try:
chat_id, thread_id, is_explicit = _parse_target_ref(
platform_name, "@alice@example.com"
)
assert chat_id == "@alice@example.com"
assert thread_id is None
assert is_explicit is True
finally:
platform_registry.unregister(platform_name)
def test_parse_target_ref_fn_returns_none_falls_through(self):
"""When parse_target_ref_fn returns None, target falls through to enricher."""
from gateway.platform_registry import PlatformEntry, platform_registry
platform_name = "fmsg-fallback-test"
def _parser(ref):
return None
entry = PlatformEntry(
name=platform_name,
label="Fmsg fallback test",
adapter_factory=lambda cfg: None,
check_fn=lambda: True,
parse_target_ref_fn=_parser,
)
platform_registry.register(entry)
register_send_message_enricher(platform_name, AsyncMock())
try:
chat_id, thread_id, is_explicit = _parse_target_ref(
platform_name, "anything"
)
assert chat_id == "anything"
assert thread_id is None
assert is_explicit is True
finally:
platform_registry.unregister(platform_name)
def test_parse_target_ref_fn_thread_id(self):
"""parse_target_ref_fn can return a thread_id alongside chat_id."""
from gateway.platform_registry import PlatformEntry, platform_registry
platform_name = "threaded-parse-test"
def _parser(ref):
if ":" in ref:
room, thread = ref.split(":", 1)
return room, thread
return None
entry = PlatformEntry(
name=platform_name,
label="Threaded parse test",
adapter_factory=lambda cfg: None,
check_fn=lambda: True,
parse_target_ref_fn=_parser,
)
platform_registry.register(entry)
try:
chat_id, thread_id, is_explicit = _parse_target_ref(
platform_name, "room-1:thread-99"
)
assert chat_id == "room-1"
assert thread_id == "thread-99"
assert is_explicit is True
finally:
platform_registry.unregister(platform_name)
def test_builtin_platform_ignores_parse_target_ref_fn(self):
"""Built-in platform parsers win over a rogue PlatformEntry parser."""
from gateway.platform_registry import PlatformEntry, platform_registry
def _parser(ref):
return "SHOULD_NOT_RETURN", None
entry = PlatformEntry(
name="telegram",
label="Telegram rogue",
adapter_factory=lambda cfg: None,
check_fn=lambda: True,
parse_target_ref_fn=_parser,
)
platform_registry.register(entry)
try:
chat_id, thread_id, is_explicit = _parse_target_ref("telegram", "12345")
assert chat_id == "12345"
assert thread_id is None
assert is_explicit is True
finally:
platform_registry.unregister("telegram")
class TestSchemaMerge:
def test_schema_fragment_stored(self):
"""Schema fragments are stored in _SEND_MESSAGE_SCHEMA_FRAGMENTS."""
@@ -65,3 +65,152 @@ def test_send_message_routes_whatsapp_group_jid_without_home_fallback() -> None:
args={"action": "send", "target": "whatsapp:120363408391911677@g.us", "message": "hello group"},
)
def test_resolved_opaque_plugin_target_uses_directory_id():
from gateway.platform_registry import PlatformEntry, platform_registry
platform_name = "opaque-resolved-test"
entry = PlatformEntry(
name=platform_name,
label="Opaque resolved test",
adapter_factory=lambda cfg: None,
check_fn=lambda: True,
)
platform_registry.register(entry)
platform = Platform(platform_name)
pconfig = SimpleNamespace(enabled=True, token=None, extra={})
config = SimpleNamespace(
platforms={platform: pconfig},
get_home_channel=lambda _platform: None,
)
try:
with patch("gateway.config.load_gateway_config", return_value=config), \
patch("tools.interrupt.is_interrupted", return_value=False), \
patch(
"gateway.channel_directory.resolve_channel_name",
return_value="opaque:directory-id",
), \
patch("model_tools._run_async", side_effect=_run_async_immediately), \
patch(
"tools.send_message_tool._send_to_platform",
new=AsyncMock(return_value={"success": True}),
) as send_mock, \
patch("gateway.mirror.mirror_to_session", return_value=True):
result = json.loads(
send_message_tool(
{
"action": "send",
"target": f"{platform_name}:Friendly name",
"message": "hello",
}
)
)
finally:
platform_registry.unregister(platform_name)
assert result["success"] is True
send_mock.assert_awaited_once_with(
platform,
pconfig,
"opaque:directory-id",
"hello",
thread_id=None,
media_files=[],
force_document=False,
args={"action": "send", "target": f"{platform_name}:Friendly name", "message": "hello"},
)
def test_unresolved_opaque_plugin_target_passes_through_verbatim():
from gateway.platform_registry import PlatformEntry, platform_registry
platform_name = "opaque-verbatim-test"
entry = PlatformEntry(
name=platform_name,
label="Opaque verbatim test",
adapter_factory=lambda cfg: None,
check_fn=lambda: True,
)
platform_registry.register(entry)
platform = Platform(platform_name)
# Simulate a fresh `hermes send` process: the dynamic Platform member
# is known from config, but plugin discovery has not registered its
# adapter entry yet.
platform_registry.unregister(platform_name)
pconfig = SimpleNamespace(enabled=True, token=None, extra={})
config = SimpleNamespace(
platforms={platform: pconfig},
get_home_channel=lambda _platform: None,
)
try:
with patch("gateway.config.load_gateway_config", return_value=config), \
patch("tools.interrupt.is_interrupted", return_value=False), \
patch(
"gateway.channel_directory.resolve_channel_name",
return_value=None,
), \
patch(
"hermes_cli.plugins.discover_plugins",
side_effect=lambda: platform_registry.register(entry),
) as discover_mock, \
patch("model_tools._run_async", side_effect=_run_async_immediately), \
patch(
"tools.send_message_tool._send_to_platform",
new=AsyncMock(return_value={"success": True}),
) as send_mock, \
patch("gateway.mirror.mirror_to_session", return_value=True):
result = json.loads(
send_message_tool(
{
"action": "send",
"target": f"{platform_name}:dm:panyaozhen",
"message": "hello",
}
)
)
finally:
platform_registry.unregister(platform_name)
assert result["success"] is True
discover_mock.assert_called_once_with()
send_mock.assert_awaited_once_with(
platform,
pconfig,
"dm:panyaozhen",
"hello",
thread_id=None,
media_files=[],
force_document=False,
args={"action": "send", "target": f"{platform_name}:dm:panyaozhen", "message": "hello"},
)
def test_unresolved_builtin_target_keeps_directory_error():
telegram_cfg = SimpleNamespace(enabled=True, token="***", extra={})
config = SimpleNamespace(
platforms={Platform.TELEGRAM: telegram_cfg},
get_home_channel=lambda _platform: None,
)
with patch("gateway.config.load_gateway_config", return_value=config), \
patch("gateway.channel_directory.resolve_channel_name", return_value=None), \
patch(
"tools.send_message_tool._send_to_platform",
new=AsyncMock(return_value={"success": True}),
) as send_mock:
result = json.loads(
send_message_tool(
{
"action": "send",
"target": "telegram:missing-room",
"message": "hello",
}
)
)
assert result == {
"error": "Could not resolve 'missing-room' on telegram. "
"Use send_message(action='list') to see available targets."
}
send_mock.assert_not_awaited()
+46 -7
View File
@@ -423,21 +423,45 @@ def _handle_send(args):
# Resolve human-friendly channel names to numeric IDs
if target_ref and not is_explicit:
resolution_failed = False
try:
from gateway.channel_directory import resolve_channel_name
resolved = resolve_channel_name(platform_name, target_ref)
if resolved:
chat_id, thread_id, _ = _parse_target_ref(platform_name, resolved)
parsed_chat_id, parsed_thread_id, _ = _parse_target_ref(
platform_name, resolved
)
# Directory entries are trusted platform IDs. Preserve an
# opaque plugin ID even when no built-in parser recognizes it.
chat_id = parsed_chat_id or resolved
if parsed_thread_id is not None:
thread_id = parsed_thread_id
except Exception:
resolved = None
resolution_failed = True
if not resolved:
from gateway.config import Platform
from gateway.platform_registry import platform_registry
from hermes_cli.plugins import discover_plugins
discover_plugins()
entry = platform_registry.get(platform_name)
is_builtin = platform_name in {member.value for member in Platform}
if entry is not None and entry.source == "plugin" and not is_builtin:
# Registered plugin platforms may use opaque IDs unknown to
# core. Their adapter owns final target validation.
chat_id = target_ref
elif resolution_failed:
return json.dumps({
"error": f"Could not resolve '{target_ref}' on {platform_name}. "
f"Try using a numeric channel ID instead."
})
else:
return tool_error(
f"Could not resolve '{target_ref}' on {platform_name}. "
f"Use send_message(action='list') to see available targets."
)
except Exception:
return tool_error(
f"Could not resolve '{target_ref}' on {platform_name}. "
f"Try using a numeric channel ID instead."
)
from tools.interrupt import is_interrupted
if is_interrupted():
@@ -669,7 +693,22 @@ def _parse_target_ref(platform_name: str, target_ref: str):
# XMPP JIDs (user@server or room@conference.server) are explicit
if platform_name == "xmpp" and "@" in target_ref:
return target_ref, None, True
# Plugin-enriched platforms
# Plugin platforms may register a custom target parser via PlatformEntry.
# This is evaluated before the blanket enricher fallback so plugins can
# opt individual target shapes in/out explicitly.
try:
from gateway.platform_registry import platform_registry
entry = platform_registry.get(platform_name)
if entry is not None and entry.parse_target_ref_fn is not None:
parsed = entry.parse_target_ref_fn(target_ref)
if parsed is not None:
chat_id, thread_id = parsed
return chat_id, thread_id, True
except Exception:
pass
# Plugin-enriched platforms (legacy blanket fallback)
if platform_name in _SEND_MESSAGE_ENRICHERS:
if target_ref:
return target_ref, None, True