The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(send): read send_message target syntax and standalone routing from the plugin registry
Tekniume24f12c69fb9
diff --git a/gateway/platform_registry.py b/gateway/platform_registry.pyindex 197ce49662b..c26c82730f3 100644--- a/gateway/platform_registry.py+++ b/gateway/platform_registry.py@@ -138,6 +138,14 @@ class PlatformEntry:# either resolves "open" without ``allow_all_env`` / GATEWAY_ALLOW_ALL_USERS, startup is refused.# A "" member = that policy is YAML-only (QQ Bot). None = no own policy, never checked.own_policy_env: Optional[tuple] = None+ # --- send ---+ # send_message native target syntax, see ``gateway.platforms.send_targets``. A hint, not an+ # authority like ``parse_target_ref_fn``: None / NOT_EXPLICIT fall back to core's generic id+ # rules / channel directory, it also re-parses channel-directory hits, and it keeps+ # ``pass_unresolved_references`` lenient.+ target_ref_syntax_fn: Optional[Callable[[str], Any]] = None+ # ``gateway.platforms.send_targets.StandaloneSendPolicy`` or None (generic send routing).+ standalone_send: Optional[Any] = Nonedef core_ships_platform(name: str) -> bool:diff --git a/gateway/platforms/send_targets.py b/gateway/platforms/send_targets.pynew file mode 100644index 00000000000..dbc0ff57083--- /dev/null+++ b/gateway/platforms/send_targets.py@@ -0,0 +1,52 @@+"""Public send_message contract pieces a platform plugin declares on its ``PlatformEntry``.++Plugins import these instead of core-private helpers in ``tools/send_message_*``:++* ``target_ref_syntax_fn`` parsers — ``(target_ref) -> (chat_id, thread_id) | None | NOT_EXPLICIT``.+ None falls through to core's generic id rules (E.164, numeric, Matrix ``!``/``@``); ``NOT_EXPLICIT``+ skips them and goes straight to the channel directory.+* ``StandaloneSendPolicy`` — when send_message bypasses the live adapter for ``standalone_sender_fn``.++Pure ``re``/dataclasses: core imports this module before any adapter is materialized.+"""++from dataclasses import dataclass++NOT_EXPLICIT = object() # sentinel: stop parsing, target is NOT explicit (skip generic rules)+++def regex_groups_parser(regex, *, thread_group=True):+ """Explicit when ``regex`` fully matches: chat_id = group 1, thread = group 2 (or None)."""+ return lambda ref: ((m.group(1), m.group(2) if thread_group else None)+ if (m := regex.fullmatch(ref)) else None)+++def regex_stripped_parser(regex):+ """Explicit when ``regex`` fully matches; returns the stripped ref verbatim."""+ return lambda ref: (ref.strip(), None) if regex.fullmatch(ref) else None+++def parse_nonempty(ref):+ # ntfy topics and WeCom ids (the adapter picks the send command) are explicit when non-empty.+ stripped = ref.strip()+ return (stripped, None) if stripped else None+++@dataclass(frozen=True)+class StandaloneSendPolicy:+ """How send_message routes a platform through its ``standalone_sender_fn`` instead of the+ live adapter (Discord: forums/threads/multipart; Slack: files_upload_v2; WhatsApp: Baileys+ /send-media; Signal: attachments ride the JSON-RPC param on the final chunk)."""++ label: str = "" # names the platform in "<label> plugin not registered ..." errors+ media: bool = False # sends that carry media bypass the live adapter+ all_sends: bool = False # every send bypasses it, text included (Discord)+ captionable: bool = False # one captionable file + short text ride as the media caption+ # Non-final chunks get ``media_files=[]`` (True) or ``media_files=None`` (False).+ empty_list_between_chunks: bool = False+ forward_force_document: bool = False # pass ``force_document`` through to the sender+ # ``mentions`` (re-pinged per message, so only the first payload carries them) force this route.+ mentions: bool = False+ # Generic text-only path: call the sender per chunk directly, skipping the live adapter and+ # any ``send_message_handler``.+ text_direct: bool = Falsediff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 042ca1dd7d6..46d3b004c37 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -1891,7 +1891,6 @@ def _apply_yaml_config(yaml_cfg: dict, buzz_cfg: dict) -> Optional[dict]:return _apply_yaml_bridge(extra, _YAML_BRIDGE)-def _env_enablement() -> Optional[dict]:"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from the owning profile's env so env-only setupsshow in gateway status; None if unconfigured. Reads go through the profile scope: a served secondary sees@@ -1908,7 +1907,6 @@ def _env_enablement() -> Optional[dict]:return {"relay_url": relay, **seed, **home}-async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Optional[str] = None,media_files: Optional[list[Any]] = None, force_document: bool = False,@@ -2005,7 +2003,9 @@ def interactive_setup() -> None:def register(ctx):"""Plugin entry point: called by the Hermes plugin system."""+ from plugins.platforms.buzz.send_targets import SEND_ENTRY_KWARGSctx.register_platform(+ **SEND_ENTRY_KWARGS, # send_message target syntax + routingname="buzz", label="Buzz", adapter_factory=lambda cfg: BuzzAdapter(cfg), check_fn=check_requirements,validate_config=validate_config, is_connected=is_connected, required_env=["BUZZ_RELAY_URL", "BUZZ_PRIVATE_KEY"],install_hint="Requires the buzz CLI binary (https://github.com/block/buzz) on PATH or at BUZZ_CLI_PATH",diff --git a/plugins/platforms/buzz/send_targets.py b/plugins/platforms/buzz/send_targets.pynew file mode 100644index 00000000000..803f719b27a--- /dev/null+++ b/plugins/platforms/buzz/send_targets.py@@ -0,0 +1,10 @@+"""send_message declarations for the Buzz ``PlatformEntry`` (kept out of the adapter module)."""++import re++from gateway.platforms.send_targets import regex_stripped_parser++# Buzz UUIDs are native targets the adapter accepts verbatim — explicit, never home-channel.+_SEND_UUID_RE = re.compile(r"^\s*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\s*$", re.IGNORECASE)++SEND_ENTRY_KWARGS = {"target_ref_syntax_fn": regex_stripped_parser(_SEND_UUID_RE)}diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.pyindex dc616004c87..472823676cd 100644--- a/plugins/platforms/dingtalk/adapter.py+++ b/plugins/platforms/dingtalk/adapter.py@@ -55,6 +55,7 @@ from gateway.platforms._shared import (apply_yaml_bridge as _apply_yaml_bridge, decode_json_list_literal as _decode_json_list_literal,extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret, send_error)+from gateway.platforms.send_targets import StandaloneSendPolicyfrom plugins.platforms.dingtalk.inbound import collect_download_codes, extract_media, extract_text@@ -849,6 +850,7 @@ def _is_connected(config) -> bool:def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(+ standalone_send=StandaloneSendPolicy(text_direct=True),name="dingtalk", label="DingTalk", adapter_factory=DingTalkAdapter, check_fn=dingtalk_deps_present,ensure_deps_fn=ensure_dingtalk_deps, is_connected=_is_connected, validate_config=_is_connected,required_env=["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"], install_hint="pip install 'dingtalk-stream>=0.20' httpx",diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 0bd974c5a51..b8a7db873bd 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -322,7 +322,6 @@ from gateway.platforms._shared import ()-def _unauthorized() -> str:"""Every refusal (slash command, approval button, picker, prompt) says the same thing — resolvedper click so the active language applies (never bound at import)."""@@ -7377,9 +7376,11 @@ _is_connected = _env_is_connected("DISCORD_BOT_TOKEN")def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""from plugins.platforms.discord.adapter_hint import PLATFORM_HINT+ from plugins.platforms.discord.send_targets import SEND_ENTRY_KWARGSfrom plugins.platforms.discord.onboarding import interactive_setupctx.register_platform(+ **SEND_ENTRY_KWARGS, # send_message target syntax + routingname="discord",label="Discord",adapter_factory=DiscordAdapter,diff --git a/plugins/platforms/discord/send_targets.py b/plugins/platforms/discord/send_targets.pynew file mode 100644index 00000000000..e73021ce54c--- /dev/null+++ b/plugins/platforms/discord/send_targets.py@@ -0,0 +1,15 @@+"""send_message declarations for the Discord ``PlatformEntry`` (kept out of the adapter module)."""++import re++from gateway.platforms.send_targets import StandaloneSendPolicy, regex_groups_parser++# "<channel>[:<thread>]" snowflakes: numeric, same shape as Telegram's "<id>[:<topic>]".+_SEND_TARGET_RE = re.compile(r"^\s*(-?\d+)(?::(\d+))?\s*$")++SEND_ENTRY_KWARGS = {+ "target_ref_syntax_fn": regex_groups_parser(_SEND_TARGET_RE),+ # Every send (text too) bypasses the live adapter: forums/threads/multipart via REST.+ "standalone_send": StandaloneSendPolicy(label="Discord", media=True, all_sends=True, captionable=True,+ empty_list_between_chunks=True),+}diff --git a/plugins/platforms/email/adapter.py b/plugins/platforms/email/adapter.pyindex 34a0797446f..0accaad7ae1 100644--- a/plugins/platforms/email/adapter.py+++ b/plugins/platforms/email/adapter.py@@ -33,6 +33,7 @@ from gateway.platforms.event import MessageEvent, MessageTypefrom gateway.config import Platform, PlatformConfigfrom utils import is_truthy_valuefrom gateway.platforms._shared import get_scoped_secret as _get_secret, coerce_port, decode_json_list_literal, send_error+from gateway.platforms.send_targets import StandaloneSendPolicy, regex_stripped_parserlogger = logging.getLogger(__name__)@@ -1005,9 +1006,14 @@ _PLATFORM_HINT = ()+_SEND_TARGET_RE = re.compile(r"^\s*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\s*$")++def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(+ target_ref_syntax_fn=regex_stripped_parser(_SEND_TARGET_RE),+ standalone_send=StandaloneSendPolicy(text_direct=True),name="email", label="Email", adapter_factory=EmailAdapter, check_fn=check_email_requirements, is_connected=_is_connected,required_env=["EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_SMTP_HOST"],install_hint="Email uses the Python stdlib (smtplib/imaplib) — no extra deps", allowed_users_env="EMAIL_ALLOWED_USERS",diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.pyindex a7d512333d5..63e190e76ba 100644--- a/plugins/platforms/feishu/adapter.py+++ b/plugins/platforms/feishu/adapter.py@@ -4480,7 +4480,9 @@ def _is_connected(config) -> bool:def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""from plugins.platforms.feishu.adapter_hint import PLATFORM_HINT+ from plugins.platforms.feishu.send_targets import SEND_ENTRY_KWARGSctx.register_platform(+ **SEND_ENTRY_KWARGS, # send_message target syntax + routingname="feishu", label="Feishu / Lark", adapter_factory=FeishuAdapter,check_fn=feishu_deps_present, ensure_deps_fn=check_feishu_requirements,is_connected=_is_connected, validate_config=_is_connected,diff --git a/plugins/platforms/feishu/send_targets.py b/plugins/platforms/feishu/send_targets.pynew file mode 100644index 00000000000..88885f5536c--- /dev/null+++ b/plugins/platforms/feishu/send_targets.py@@ -0,0 +1,12 @@+"""send_message declarations for the Feishu ``PlatformEntry`` (kept out of the adapter module)."""++import re++from gateway.platforms.send_targets import StandaloneSendPolicy, regex_groups_parser++_SEND_TARGET_RE = re.compile(r"^\s*((?:oc|ou|on|chat|open)_[-A-Za-z0-9]+)(?::([-A-Za-z0-9_]+))?\s*$")++SEND_ENTRY_KWARGS = {+ "target_ref_syntax_fn": regex_groups_parser(_SEND_TARGET_RE),+ "standalone_send": StandaloneSendPolicy(label="Feishu", media=True, text_direct=True),+}diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex e8ae89a256c..e6bcce93fc7 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -3244,7 +3244,6 @@ def _apply_yaml_config(yaml_cfg: dict, matrix_cfg: dict) -> dict | None:return _apply_yaml_bridge(matrix_cfg, _YAML_BRIDGE)-def _is_connected(config) -> bool:"""Connected = homeserver + token (or password). Reads via hermes_cli.gateway.get_env_value sosetup-status callers that patch it see the same value; PlatformConfig extras are honored."""@@ -3258,7 +3257,9 @@ def _is_connected(config) -> bool:def register(ctx) -> None:from plugins.platforms.matrix.adapter_hint import PLATFORM_HINT+ from plugins.platforms.matrix.send_targets import SEND_ENTRY_KWARGSctx.register_platform(+ **SEND_ENTRY_KWARGS, # send_message target syntax + routingname="matrix", label="Matrix", adapter_factory=MatrixAdapter, check_fn=matrix_deps_present,ensure_deps_fn=ensure_matrix_deps, is_connected=_is_connected,required_env=["MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"], install_hint="pip install 'mautrix[encryption]'",diff --git a/plugins/platforms/matrix/send_targets.py b/plugins/platforms/matrix/send_targets.pynew file mode 100644index 00000000000..e377387e011--- /dev/null+++ b/plugins/platforms/matrix/send_targets.py@@ -0,0 +1,12 @@+"""send_message declarations for the Matrix ``PlatformEntry`` (kept out of the adapter module)."""+++def _parse_send_target(ref):+ # "<room>:$<event_id>" addresses a thread (rfind: room ids contain ':'). Bare "!room" /+ # "@user" go via the generic rule so the numeric check keeps precedence.+ trimmed = ref.strip()+ split_idx = trimmed.rfind(":$")+ return (trimmed[:split_idx], trimmed[split_idx + 1:]) if split_idx > 0 else None+++SEND_ENTRY_KWARGS = {"target_ref_syntax_fn": _parse_send_target}diff --git a/plugins/platforms/ntfy/adapter.py b/plugins/platforms/ntfy/adapter.pyindex c5747db9c54..d3852888914 100644--- a/plugins/platforms/ntfy/adapter.py+++ b/plugins/platforms/ntfy/adapter.py@@ -32,6 +32,7 @@ from gateway.platforms.helpers import MessageDeduplicatorfrom gateway.platforms._shared import (extra_or_secret as _extra_or_secret, seed_extra_from_env as _seed_extra_from_env)+from gateway.platforms.send_targets import parse_nonemptylogger = logging.getLogger(__name__)@@ -357,6 +358,7 @@ async def _standalone_send(def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system at startup."""ctx.register_platform(+ target_ref_syntax_fn=parse_nonempty,name="ntfy", label="ntfy", adapter_factory=lambda cfg: NtfyAdapter(cfg),check_fn=check_requirements, validate_config=validate_config, is_connected=is_connected,required_env=["NTFY_TOPIC"], install_hint="pip install httpx # already a Hermes dependency",diff --git a/plugins/platforms/photon/adapter.py b/plugins/platforms/photon/adapter.pyindex ca8d3be4d63..07dad6b845c 100644--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@ -44,6 +44,7 @@ from gateway.platforms.base import BasePlatformAdapter, SendResultfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.platforms.helpers import compile_mention_patterns, strip_markdownfrom gateway.platforms.helpers import MessageDeduplicator, bounded_put, cancel_task+from gateway.platforms.send_targets import regex_stripped_parserfrom utils import atomic_json_writefrom .auth import load_project_credentials@@ -1692,10 +1693,15 @@ async def _standalone_send(# -- Plugin entry point ----------------------------------------------------------+_SEND_DM_GUID_RE = re.compile(r"^any;-;\+\d{6,}$") # mirrors PhotonAdapter._DM_CHAT_GUID_RE++def register(ctx) -> None:"""Called by the Hermes plugin loader at startup."""from . import cli as _cli # local: avoid argparse work at module loadctx.register_platform(+ # DM GUIDs are adapter-native ids (mirrors the react handler).+ target_ref_syntax_fn=regex_stripped_parser(_SEND_DM_GUID_RE),name="photon", label="iMessage via Photon", adapter_factory=lambda cfg: PhotonAdapter(cfg),check_fn=check_requirements, validate_config=validate_config, is_connected=is_connected,required_env=["PHOTON_PROJECT_ID", "PHOTON_PROJECT_SECRET"],diff --git a/plugins/platforms/qqbot/register.py b/plugins/platforms/qqbot/register.pyindex fede1f86e93..9c5554e413f 100644--- a/plugins/platforms/qqbot/register.py+++ b/plugins/platforms/qqbot/register.py@@ -9,6 +9,7 @@ from __future__ import annotationsfrom gateway.platforms._shared import env_is_connectedfrom gateway.platforms._shared import config_connected_extra+from gateway.platforms.send_targets import StandaloneSendPolicyfrom .adapter import QQAdapter, check_qq_requirements@@ -132,6 +133,7 @@ _PLATFORM_HINT = (def register(ctx) -> None:ctx.register_platform(+ standalone_send=StandaloneSendPolicy(label="QQ Bot", media=True, captionable=True, text_direct=True),name="qqbot",label="QQ Bot",adapter_factory=QQAdapter,diff --git a/plugins/platforms/signal/register.py b/plugins/platforms/signal/register.pyindex f726fe92589..ec844d97cb0 100644--- a/plugins/platforms/signal/register.py+++ b/plugins/platforms/signal/register.py@@ -5,6 +5,7 @@ import loggingfrom gateway.config import PlatformConfigfrom gateway.platforms._shared import env_is_connectedfrom gateway.platforms._shared import config_connected_extra+from gateway.platforms.send_targets import NOT_EXPLICIT, StandaloneSendPolicy# Absolute imports (see __init__.py): one canonical module per file.from plugins.platforms.signal.adapter import (@@ -39,11 +40,22 @@ _PLATFORM_HINT = ("You can send files natively: write MEDIA:/absolute/path/to/file in your response. ""Images (.png, .jpg, .webp) send as photos, other files as documents;  sends as photos.")+def _parse_send_target(ref):+ # "group:<id>" is a native group target; an empty id is not explicit.+ stripped = ref.strip()+ if not stripped.startswith("group:"):+ return None+ group_id = stripped[len("group:"):].strip()+ return (f"group:{group_id}", None) if group_id else NOT_EXPLICITdef register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(+ target_ref_syntax_fn=_parse_send_target,+ # Attachments ride the JSON-RPC param on the final chunk.+ standalone_send=StandaloneSendPolicy(label="Signal", media=True, empty_list_between_chunks=True,+ text_direct=True),name="signal", label="Signal", adapter_factory=SignalAdapter,check_fn=check_signal_requirements, validate_config=_validate_config,is_connected=_is_connected, required_env=["SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"],diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex 5787db25f76..aa3b8fcd9e0 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -6905,14 +6905,15 @@ def _apply_yaml_config(yaml_cfg: dict, slack_cfg: dict) -> dict | None:return _apply_yaml_bridge(slack_cfg, _YAML_BRIDGE)-_is_connected = _env_is_connected("SLACK_BOT_TOKEN")def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""from plugins.platforms.slack.adapter_hint import PLATFORM_HINT+ from plugins.platforms.slack.send_targets import SEND_ENTRY_KWARGSctx.register_platform(+ **SEND_ENTRY_KWARGS, # send_message target syntax + routingname="slack",label="Slack",adapter_factory=SlackAdapter,diff --git a/plugins/platforms/slack/send_targets.py b/plugins/platforms/slack/send_targets.pynew file mode 100644index 00000000000..8d3fab65c57--- /dev/null+++ b/plugins/platforms/slack/send_targets.py@@ -0,0 +1,32 @@+"""send_message declarations for the Slack ``PlatformEntry`` (kept out of the adapter module)."""++import re++from gateway.platforms.send_targets import StandaloneSendPolicy++# Slack conversation IDs: C (public), G (private/group), D (DM); uppercase alnum, 9+ chars. User IDs+# (U...) become ``user:U...`` and are opened as D... conversations first (posting straight to a U/W+# id fails); ``@handle`` -> ``user_name:...`` resolves via users.list.+_SEND_TARGET_RE = re.compile(r"^\s*([CGD][A-Z0-9]{8,})\s*$")+_SEND_USER_ID_RE = re.compile(r"^\s*(U[A-Z0-9]{8,})\s*$")+_SEND_USER_NAME_RE = re.compile(r"^\s*@([A-Za-z0-9._-]{1,80})\s*$")+_SEND_MENTION_RE = re.compile(r"^\s*<@(U[A-Z0-9]{8,})(?:\|[^>]+)?>\s*$")+# Session-derived Slack thread targets use "<conversation_id>:<thread_ts>".+_SEND_THREAD_TARGET_RE = re.compile(r"^\s*([CGD][A-Z0-9]{8,}):([^\s:]+)\s*$")+# (regex, chat_id template, thread comes from group 2) — thread form before bare id.+_SEND_FORMS = ((_SEND_THREAD_TARGET_RE, "{}", True), (_SEND_TARGET_RE, "{}", False),+ (_SEND_USER_ID_RE, "user:{}", False), (_SEND_MENTION_RE, "user:{}", False),+ (_SEND_USER_NAME_RE, "user_name:{}", False))+++def _parse_send_target(ref):+ return next(((template.format(m.group(1)), m.group(2) if has_thread else None)+ for regex, template, has_thread in _SEND_FORMS if (m := regex.fullmatch(ref))), None)+++SEND_ENTRY_KWARGS = {+ "target_ref_syntax_fn": _parse_send_target,+ # Media goes through files_upload_v2 in the standalone sender.+ "standalone_send": StandaloneSendPolicy(label="Slack", media=True, captionable=True,+ empty_list_between_chunks=True),+}diff --git a/plugins/platforms/sms/adapter.py b/plugins/platforms/sms/adapter.pyindex a671a120bd0..3f0935ad2e1 100644--- a/plugins/platforms/sms/adapter.py+++ b/plugins/platforms/sms/adapter.py@@ -27,6 +27,7 @@ from gateway.platforms.helpers import redact_phone, send_chunks, strip_markdownfrom gateway.platforms._shared import (env_is_connected as _env_is_connected, get_scoped_secret as _get_scoped_secret, send_error)+from gateway.platforms.send_targets import StandaloneSendPolicytry:import aiohttp@@ -339,6 +340,7 @@ _PLATFORM_HINT = (def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(+ standalone_send=StandaloneSendPolicy(text_direct=True),name="sms", label="SMS (Twilio)", adapter_factory=SmsAdapter,check_fn=check_sms_requirements, is_connected=_is_connected,required_env=["TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN", "TWILIO_PHONE_NUMBER"],diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 497ef9479e9..0facabfa8a1 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -181,7 +181,7 @@ _MEDIA_KIND_KEYS = {from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcomefrom plugins.platforms.telegram.telegram_entities import expand_link_entitiesfrom plugins.platforms.telegram.telegram_held_inbound import TelegramHeldInboundMixin-from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id+from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id, parse_send_targetfrom plugins.platforms.telegram.telegram_network import (SEED_FALLBACK_IPS, TelegramFallbackTransport, discover_fallback_ips, parse_fallback_ip_env, tcp_keepalive_socket_options)from utils import env_float, env_int@@ -7322,4 +7322,5 @@ def register(ctx) -> None:display_tier="high",# Mobile inbox: quiet tool_progress / busy-ack, but keep interim commentary and heartbeats.display_overrides={"tool_progress": "off", "busy_ack_detail": False},+ target_ref_syntax_fn=parse_send_target,)diff --git a/plugins/platforms/telegram/telegram_ids.py b/plugins/platforms/telegram/telegram_ids.pyindex 8007e9d1f50..21879d4c3b6 100644--- a/plugins/platforms/telegram/telegram_ids.py+++ b/plugins/platforms/telegram/telegram_ids.py@@ -6,6 +6,8 @@ from __future__ import annotationsimport refrom typing import Any, Union+from gateway.platforms.send_targets import parse_nonempty, regex_groups_parser+# Usernames are 5-32 chars (letters, digits, underscores) with a leading "@"; 4-char legacy handles are tolerated._TELEGRAM_USERNAME_RE = re.compile(r"@[A-Za-z0-9_]{4,32}")@@ -29,3 +31,15 @@ def parse_telegram_username_target(target_ref: Any) -> str | None:"""Return the value when it is an ``@username`` target, else ``None``."""value = str(target_ref).strip()return value if looks_like_telegram_username(value) else None+++_SEND_TARGET_RE = re.compile(r"^\s*(-?\d+)(?::(\d+))?\s*$")+++def parse_send_target(ref):+ """``target_ref_syntax_fn`` for the Telegram ``PlatformEntry``."""+ # "<chat_id>[:<topic_id>]" or an @username (usernames must not be force-int'd).+ parsed = regex_groups_parser(_SEND_TARGET_RE)(ref)+ if parsed:+ return parsed+ return parse_nonempty(parse_telegram_username_target(ref) or "")diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.pyindex 2feed9acc84..56b4fe37c4f 100644--- a/plugins/platforms/wecom/adapter.py+++ b/plugins/platforms/wecom/adapter.py@@ -35,6 +35,7 @@ from gateway.platforms.event import MessageEvent, MessageTypefrom utils import env_floatfrom gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error+from gateway.platforms.send_targets import StandaloneSendPolicy, parse_nonemptyfrom plugins.platforms.wecom.send_queue import ChatSendQueueMixinfrom plugins.platforms.wecom.media import WeComMediaMixin, APP_CMD_SENDfrom plugins.platforms.wecom.streaming import (@@ -847,6 +848,8 @@ _WECOM_PLATFORM_HINT = (def register(ctx) -> None:common = dict(install_hint="Run `hermes setup` to install WeCom support.", emoji="💼", allow_update_command=True)ctx.register_platform(+ target_ref_syntax_fn=parse_nonempty,+ standalone_send=StandaloneSendPolicy(text_direct=True),name="wecom", label="WeCom (Enterprise WeChat)", adapter_factory=WeComAdapter, check_fn=check_wecom_requirements,is_connected=_is_connected, validate_config=_is_connected, required_env=["WECOM_BOT_ID", "WECOM_SECRET"],setup_fn=interactive_setup, allowed_users_env="WECOM_ALLOWED_USERS", allow_all_env="WECOM_ALLOW_ALL_USERS",diff --git a/plugins/platforms/weixin/adapter.py b/plugins/platforms/weixin/adapter.pyindex 36138c317af..b469445f1c9 100644--- a/plugins/platforms/weixin/adapter.py+++ b/plugins/platforms/weixin/adapter.py@@ -39,6 +39,7 @@ from gateway.platforms.event import MessageEvent, MessageTypefrom hermes_constants import get_hermes_homefrom utils import atomic_json_writefrom gateway.platforms._shared import env_is_connected, extra_or_secret as _extra_or_env, get_scoped_secret as _wx_secret+from gateway.platforms.send_targets import StandaloneSendPolicy, regex_groups_parserdef _extra_or_secret(extra: dict[str, Any], key: str, default: str = "") -> str:@@ -1398,11 +1399,14 @@ _PLATFORM_HINT = ("supported, and other files arrive as downloadable documents. You can also include image URLs in markdown ""format  and they will be downloaded and sent as native media when possible.")+_SEND_TARGET_RE = re.compile(r"^\s*((?:wxid|gh|v\d+|wm|wb)_[A-Za-z0-9_-]+|[A-Za-z0-9._-]+@chatroom|filehelper)\s*$")def register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(+ target_ref_syntax_fn=regex_groups_parser(_SEND_TARGET_RE, thread_group=False),+ standalone_send=StandaloneSendPolicy(label="Weixin", media=True),name="weixin", label="Weixin / WeChat", adapter_factory=WeixinAdapter, check_fn=check_weixin_requirements,is_connected=_is_connected, required_env=["WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"], install_hint=_INSTALL_HINT,config_connected_fn=_config_connected,diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 0ab4800111b..b5188859158 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -17,6 +17,7 @@ from typing import Dict, Optional, Anyfrom gateway.platforms._shared import (apply_yaml_bridge as _apply_yaml_bridge, extra_or_secret as _extra_or_secret, get_scoped_secret, send_error)+from gateway.platforms.send_targets import StandaloneSendPolicy, regex_stripped_parserfrom hermes_cli._subprocess_compat import windows_detach_popen_kwargsfrom hermes_constants import (find_node_executable, get_hermes_dir, with_hermes_node_path)@@ -1240,8 +1241,17 @@ _PLATFORM_HINT = ()+# WhatsApp JIDs (@g.us, @s.whatsapp.net, @lid, broadcast/newsletter) are native targets the adapter+# accepts verbatim — explicit, never home-channel. E.164 numbers use core's phone rule.+_SEND_JID_RE = re.compile(r"^\s*[\w-]+@(?:g\.us|s\.whatsapp\.net|lid|broadcast|newsletter)\s*$", re.IGNORECASE)++def register(ctx) -> None:ctx.register_platform(+ target_ref_syntax_fn=regex_stripped_parser(_SEND_JID_RE),+ # Media goes through Baileys /send-media; ``mentions`` force the standalone route too.+ standalone_send=StandaloneSendPolicy(label="WhatsApp", media=True, captionable=True,+ forward_force_document=True, mentions=True, text_direct=True),name="whatsapp", label="WhatsApp", adapter_factory=WhatsAppAdapter, check_fn=check_whatsapp_requirements,is_connected=_is_connected, required_env=["WHATSAPP_ENABLED"],install_hint="WhatsApp requires a Node.js bridge — see the WhatsApp messaging docs",diff --git a/plugins/platforms/yuanbao/register.py b/plugins/platforms/yuanbao/register.pyindex 67227b9a877..a5433f0aeb0 100644--- a/plugins/platforms/yuanbao/register.py+++ b/plugins/platforms/yuanbao/register.py@@ -1,9 +1,11 @@"""Yuanbao plugin registration: setup row, configured check, standalone sender, ``register``."""+import reimport loggingfrom gateway.platforms._shared import send_errorfrom gateway.platforms._shared import config_connected_extra+from gateway.platforms.send_targets import NOT_EXPLICIT, StandaloneSendPolicy# Absolute import (see __init__.py): one ``YuanbaoAdapter`` class object for the registry,# tools/yuanbao_tools.py and the standalone sender.@@ -77,11 +79,22 @@ _PLATFORM_HINT = ("keyword, then yb_send_sticker with the chosen id \u2014 which send a real native sticker. Never ""draw sticker-like PNGs and send them as images, and bare Unicode emoji is not a substitute.")+_SEND_TARGET_RE = re.compile(r"^\s*((?:group|direct):[^:]+)\s*$")+++def _parse_send_target(ref):+ # "group:<code>" / "direct:<id>"; a bare number is a group code (never generic rules).+ match = _SEND_TARGET_RE.fullmatch(ref)+ if match:+ return match.group(1), None+ return (f"group:{ref.strip()}", None) if ref.strip().isdigit() else NOT_EXPLICITdef register(ctx) -> None:"""Plugin entry point — called by the Hermes plugin system."""ctx.register_platform(+ target_ref_syntax_fn=_parse_send_target,+ standalone_send=StandaloneSendPolicy(label="Yuanbao", media=True, text_direct=True),name="yuanbao", label="Yuanbao", adapter_factory=YuanbaoAdapter,check_fn=check_yuanbao_requirements, is_connected=_is_connected,config_connected_fn=config_connected_extra("app_id", "app_secret"),diff --git a/tests/gateway/test_bluebubbles_plugin.py b/tests/gateway/test_bluebubbles_plugin.pyindex 6da0a6b437f..650ce66c386 100644--- a/tests/gateway/test_bluebubbles_plugin.py+++ b/tests/gateway/test_bluebubbles_plugin.py@@ -620,6 +620,8 @@ class TestBlueBubblesPluginRegistration:from hermes_cli import gateway_setup_wizard as wizassert Platform.BLUEBUBBLES not in _BUILTIN_ADAPTERS- assert "bluebubbles" not in smt._TEXT_SENDERS+ # Text is not routed straight to a standalone sender (was: not a _TEXT_SENDERS row).+ policy = smt._standalone_send_policy("bluebubbles")+ assert policy is None or not policy.text_directassert not hasattr(senders, "_send_bluebubbles")assert all(p["key"] != "bluebubbles" for p in wiz._PLATFORMS)diff --git a/tests/gateway/test_yuanbao_plugin_registration.py b/tests/gateway/test_yuanbao_plugin_registration.pyindex 666ddf442d7..6e95c88389b 100644--- a/tests/gateway/test_yuanbao_plugin_registration.py+++ b/tests/gateway/test_yuanbao_plugin_registration.py@@ -35,4 +35,5 @@ def test_register_shape_and_core_wiring_removed():assert Platform.YUANBAO not in _BUILTIN_ADAPTERSassert all(p["key"] != "yuanbao" for p in _PLATFORMS)assert "yuanbao" not in smt._CHUNKED_ROUTES- assert "yuanbao" in smt._PLUGIN_STANDALONE_MEDIA+ # Media sends bypass the live adapter for the standalone sender (was a _PLUGIN_STANDALONE_MEDIA row).+ assert kw["standalone_send"].media is Truediff --git a/tests/tools/test_send_message_plugin_extensibility.py b/tests/tools/test_send_message_plugin_extensibility.pyindex f542b80e498..b30fcc5d6a6 100644--- a/tests/tools/test_send_message_plugin_extensibility.py+++ b/tests/tools/test_send_message_plugin_extensibility.py@@ -265,3 +265,42 @@ print(json.dumps({"host_send": host_send, "cron": cron,assert payload["host_send"]["chat_id"] == "@[email protected]"assert payload["cron"]["chat_id"] == "@[email protected]"assert payload["model_registered"] is False+++def test_declared_target_syntax_and_standalone_policy_drive_send_routing():+ """Core routes from the entry's ``target_ref_syntax_fn`` / ``standalone_send``, not a per-platform+ table: a third-party plugin declaring them gets the bundled platforms' semantics."""+ import asyncio++ from gateway.platforms.send_targets import NOT_EXPLICIT, StandaloneSendPolicy+ from tools.send_message_tool import _send_to_platform++ calls: list[dict] = []++ async def sender(pconfig, chat_id, message, **kw):+ calls.append({"chat_id": chat_id, "message": message, **kw})+ return {"success": True}++ def syntax(ref):+ if ref.startswith("room-"):+ return ref.partition(":")[::2] if ":" in ref else (ref, None)+ return NOT_EXPLICIT if ref == "7" else None++ name = "fmsg-syntax-test"+ platform_registry.register(PlatformEntry(+ name=name, label="Fixture Syntax", adapter_factory=lambda cfg: None, check_fn=lambda: True,+ target_ref_syntax_fn=syntax, standalone_sender_fn=sender,+ standalone_send=StandaloneSendPolicy(label="Fixture", media=True, captionable=True)))+ try:+ with patch("gateway.channel_directory.resolve_channel_name", return_value=None):+ assert resolve_send_target(name, "room-1:th") == ("room-1", "th", None)+ # NOT_EXPLICIT skips the generic numeric rule; None falls through to it.+ assert resolve_send_target(name, "42") == ("42", None, None)+ assert resolve_send_target(name, "7")[2]+ media = [(os.path.abspath(__file__).replace(".py", ".png"), False)]+ result = asyncio.run(_send_to_platform(Platform(name), SimpleNamespace(extra={}), "room-1", "hi",+ media_files=media))+ finally:+ platform_registry.unregister(name)+ assert result == {"success": True}+ assert calls == [{"chat_id": "room-1", "message": "", "thread_id": None, "media_files": media, "caption": "hi"}]diff --git a/tools/send_message_targets.py b/tools/send_message_targets.pyindex 3d8acae0663..553671717f5 100644--- a/tools/send_message_targets.py+++ b/tools/send_message_targets.py@@ -5,127 +5,35 @@ import relogger = logging.getLogger("tools.send_message_tool")-_TELEGRAM_TOPIC_TARGET_RE = re.compile(r"^\s*(-?\d+)(?::(\d+))?\s*$")-_NUMERIC_TOPIC_RE = _TELEGRAM_TOPIC_TARGET_RE # Discord snowflakes: numeric, same "<id>[:<thread>]" shape-_FEISHU_TARGET_RE = re.compile(r"^\s*((?:oc|ou|on|chat|open)_[-A-Za-z0-9]+)(?::([-A-Za-z0-9_]+))?\s*$")-# Slack conversation IDs: C (public), G (private/group), D (DM); uppercase alnum, 9+ chars. User IDs-# (U...) become ``user:U...`` and are opened as D... conversations first (posting straight to a U/W-# id fails); ``@handle`` -> ``user_name:...`` resolves via users.list.-_SLACK_TARGET_RE = re.compile(r"^\s*([CGD][A-Z0-9]{8,})\s*$")-_SLACK_USER_ID_RE = re.compile(r"^\s*(U[A-Z0-9]{8,})\s*$")-_SLACK_USER_NAME_RE = re.compile(r"^\s*@([A-Za-z0-9._-]{1,80})\s*$")-_SLACK_MENTION_RE = re.compile(r"^\s*<@(U[A-Z0-9]{8,})(?:\|[^>]+)?>\s*$")-# Session-derived Slack thread targets use "<conversation_id>:<thread_ts>".-_SLACK_THREAD_TARGET_RE = re.compile(r"^\s*([CGD][A-Z0-9]{8,}):([^\s:]+)\s*$")-_WEIXIN_TARGET_RE = re.compile(r"^\s*((?:wxid|gh|v\d+|wm|wb)_[A-Za-z0-9_-]+|[A-Za-z0-9._-]+@chatroom|filehelper)\s*$")-_YUANBAO_TARGET_RE = re.compile(r"^\s*((?:group|direct):[^:]+)\s*$")# E.164 phone recipients ("+1555..."): the '+' fails the isdigit() rule and the channel directory# cannot resolve a raw number, so keep the '+' and treat it as explicit._PHONE_PLATFORMS = frozenset({"photon", "signal", "sms", "whatsapp"})_E164_TARGET_RE = re.compile(r"^\s*\+(\d{7,15})\s*$")-_PHOTON_DM_GUID_RE = re.compile(r"^any;-;\+\d{6,}$") # mirrors _DM_CHAT_GUID_RE in the photon adapter-# WhatsApp JIDs (@g.us, @s.whatsapp.net, @lid, broadcast/newsletter) and Buzz UUIDs are native targets-# the adapter accepts verbatim — explicit, never home-channel. A valid email address likewise.-_WHATSAPP_JID_RE = re.compile(r"^\s*[\w-]+@(?:g\.us|s\.whatsapp\.net|lid|broadcast|newsletter)\s*$", re.IGNORECASE)-_BUZZ_UUID_RE = re.compile(r"^\s*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\s*$", re.IGNORECASE)-_EMAIL_TARGET_RE = re.compile(r"^\s*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\s*$")# Exceptions to "<PLATFORM>_HOME_CHANNEL" for error hints (email reads EMAIL_HOME_ADDRESS)._HOME_CHANNEL_ENV_OVERRIDES = {"email": "EMAIL_HOME_ADDRESS"}-_UNRESOLVED = object() # sentinel: stop parsing, target is NOT explicit (skip generic rules)--# Per-platform explicit-target parsers: target_ref -> (chat_id, thread_id), None to fall-# through to the generic rules in _parse_target_ref, or _UNRESOLVED.-def _parse_regex_groups(regex, *, thread_group=True):- """Explicit when ``regex`` fully matches: chat_id = group 1, thread = group 2 (or None)."""- return lambda ref: ((m.group(1), m.group(2) if thread_group else None)- if (m := regex.fullmatch(ref)) else None)---def _parse_regex_stripped(regex):- """Explicit when ``regex`` fully matches; returns the stripped ref verbatim."""- return lambda ref: (ref.strip(), None) if regex.fullmatch(ref) else None---def _parse_nonempty(ref):- # ntfy topics and WeCom ids (the adapter picks the send command) are explicit when non-empty.- stripped = ref.strip()- return (stripped, None) if stripped else None---def _parse_telegram(ref):- # "<chat_id>[:<topic_id>]" or an @username (usernames must not be force-int'd).- parsed = _parse_regex_groups(_TELEGRAM_TOPIC_TARGET_RE)(ref)- if parsed:- return parsed- from plugins.platforms.telegram.telegram_ids import parse_telegram_username_target- return _parse_nonempty(parse_telegram_username_target(ref) or "")---# (regex, chat_id template, thread comes from group 2) — thread form before bare id.-_SLACK_FORMS = ((_SLACK_THREAD_TARGET_RE, "{}", True), (_SLACK_TARGET_RE, "{}", False),- (_SLACK_USER_ID_RE, "user:{}", False), (_SLACK_MENTION_RE, "user:{}", False),- (_SLACK_USER_NAME_RE, "user_name:{}", False))---def _parse_slack(ref):- return next(((template.format(m.group(1)), m.group(2) if has_thread else None)- for regex, template, has_thread in _SLACK_FORMS if (m := regex.fullmatch(ref))), None)---def _parse_matrix(ref):- # "<room>:$<event_id>" addresses a thread (rfind: room ids contain ':'). Bare "!room" /- # "@user" go via the generic rule so the numeric check keeps precedence.- trimmed = ref.strip()- split_idx = trimmed.rfind(":$")- return (trimmed[:split_idx], trimmed[split_idx + 1:]) if split_idx > 0 else None---def _parse_yuanbao(ref):- # "group:<code>" / "direct:<id>"; a bare number is a group code (never generic rules).- match = _YUANBAO_TARGET_RE.fullmatch(ref)- if match:- return match.group(1), None- return (f"group:{ref.strip()}", None) if ref.strip().isdigit() else _UNRESOLVED---def _parse_signal(ref):- # "group:<id>" is a native group target; an empty id is not explicit.- stripped = ref.strip()- if not stripped.startswith("group:"):- return None- group_id = stripped[len("group:"):].strip()- return (f"group:{group_id}", None) if group_id else _UNRESOLVED---_PLATFORM_PARSERS = {- "telegram": _parse_telegram,- "feishu": _parse_regex_groups(_FEISHU_TARGET_RE),- "discord": _parse_regex_groups(_NUMERIC_TOPIC_RE), # "<channel>[:<thread>]" snowflakes- "slack": _parse_slack,- "matrix": _parse_matrix,- "weixin": _parse_regex_groups(_WEIXIN_TARGET_RE, thread_group=False),- "yuanbao": _parse_yuanbao,- "ntfy": _parse_nonempty,- "email": _parse_regex_stripped(_EMAIL_TARGET_RE),- # Native WhatsApp JIDs pass through verbatim; E.164 numbers use the phone rule.- "whatsapp": _parse_regex_stripped(_WHATSAPP_JID_RE),- "buzz": _parse_regex_stripped(_BUZZ_UUID_RE),- "signal": _parse_signal,- "wecom": _parse_nonempty,- # Photon DM GUIDs are adapter-native ids (mirrors the react handler).- "photon": _parse_regex_stripped(_PHOTON_DM_GUID_RE)}+def _target_syntax_fn(platform_name: str):+ """The plugin's declared native target syntax, or None. A fresh CLI/cron process can parse a+ target before plugin discovery registered the platform, so discover first when the name is+ unknown (idempotent manifest scan; only this platform's adapter is materialized)."""+ from gateway.platform_registry import platform_registry+ if not platform_registry.is_registered(platform_name):+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ entry = platform_registry.get(platform_name)+ return entry.target_ref_syntax_fn if entry is not None else Nonedef _parse_target_ref(platform_name: str, target_ref: str):- """(chat_id, thread_id, explicit): platform parser first, then in order E.164 phone- numbers (keeping the '+'), bare numeric ids, Matrix ``!room``/``@user``, XMPP JIDs.+ """(chat_id, thread_id, explicit): the plugin's ``target_ref_syntax_fn`` first, then in order+ E.164 phone numbers (keeping the '+'), bare numeric ids, Matrix ``!room``/``@user``, XMPP JIDs.Anything else goes to channel-directory resolution."""- parser = _PLATFORM_PARSERS.get(platform_name)+ from gateway.platforms.send_targets import NOT_EXPLICIT+ parser = _target_syntax_fn(platform_name)if parser is not None:parsed = parser(target_ref)- if parsed is _UNRESOLVED:+ if parsed is NOT_EXPLICIT:return None, None, Falseif parsed is not None:return parsed[0], parsed[1], Truediff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex cee7755fa6d..913cae0d4f9 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -5,14 +5,14 @@ import asyncioimport jsonimport loggingimport os-from functools import partial+import refrom agent.secret_scope import get_secretlogger = logging.getLogger(__name__)from tools.send_message_targets import (- _HOME_CHANNEL_ENV_OVERRIDES, _SLACK_USER_ID_RE, resolve_send_target, unknown_platform_error,+ _HOME_CHANNEL_ENV_OVERRIDES, resolve_send_target, unknown_platform_error,)from tools.send_message_senders import (_AUDIO_EXTS, _DEFAULT_CAPTION_LIMIT, _IMAGE_EXTS, _NO_DELIVERABLE, _VIDEO_EXTS, _VOICE_EXTS,@@ -21,6 +21,10 @@ from tools.send_message_senders import (_send_matrix_via_adapter, _send_telegram)from tools.registry import tool_error+# A bare Slack user id (session metadata / home-channel config) is opened as a DM; same shape the+# slack plugin's target parser turns into ``user:U...``.+_SLACK_USER_ID_RE = re.compile(r"^\s*(U[A-Z0-9]{8,})\s*$")+# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model tool# (the agent must not fire cross-platform messages on its own); cron delivery, the# ``hermes send`` CLI, the kanban notifier and the opt-in MCP server import the helpers.@@ -266,11 +270,12 @@ def _handle_send(args):try:from model_tools import _run_async- # 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.+ # Only custom plugin handlers receive the complete typed request. ``mentions`` is only for platforms+ # whose StandaloneSendPolicy declares it (WhatsApp; 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":+ if mentions and entry is not None and entry.standalone_send is not None and entry.standalone_send.mentions: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,@@ -612,17 +617,16 @@ def _platform_max_length(platform):return None-# Plugin platforms whose media (Discord: all) sends deliberately bypass the live adapter for the-# registry ``standalone_sender_fn`` (Discord: forums/threads/multipart; Slack: files_upload_v2;-# WhatsApp: Baileys /send-media). platform -> (error label, run discover_plugins first,-# caption-capable, media_files sentinel for non-final chunks, forward force_document)-_PLUGIN_STANDALONE_MEDIA = {"discord": ("Discord", False, True, [], False), "feishu": ("Feishu", True, False, None, False),- "qqbot": ("QQ Bot", True, True, None, False),- "slack": ("Slack", True, True, [], False), "whatsapp": ("WhatsApp", True, True, None, True),- # Signal: attachments ride the JSON-RPC param on the final chunk.- "signal": ("Signal", True, False, [], False),- "weixin": ("Weixin", True, False, None, False),- "yuanbao": ("Yuanbao", True, False, None, False)}+def _standalone_send_policy(platform_name):+ """The plugin's ``StandaloneSendPolicy`` (None = generic routing). Cron calls+ ``_send_to_platform`` directly, so discover first when the name is not yet registered+ (idempotent manifest scan; only this platform's adapter is materialized)."""+ from gateway.platform_registry import platform_registry+ if not platform_registry.is_registered(platform_name):+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ entry = platform_registry.get(platform_name)+ return entry.standalone_send if entry is not None else Noneasync def _send_plugin_standalone(platform_name, pconfig, chat_id, message, chunks, media_files, *, thread_id,@@ -630,13 +634,15 @@ async def _send_plugin_standalone(platform_name, pconfig, chat_id, message, chun"""Chunked send through a plugin's standalone_sender_fn; one captionable file + short textrides 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)+ from gateway.platforms.send_targets import StandaloneSendPolicy+ policy = _standalone_send_policy(platform_name) or StandaloneSendPolicy()+ sender, err = _plugin_standalone_sender(platform_name, label=policy.label or None)if err:return err- extra = {"force_document": force_document} if pass_force else {}+ extra = {"force_document": force_document} if policy.forward_force_document else {}first_only = {"mentions": mentions} if mentions else {}- if captionable:+ empty_media = [] if policy.empty_list_between_chunks else None+ if policy.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:@@ -666,11 +672,6 @@ _CHUNKED_ROUTES = {"slack": (False, [], _via_adapter_route),"wecom": (True, None, _via_adapter_route)}-# Text-only senders for built-in platforms (generic path; media is dropped with a-# warning). Signature: (pconfig, chat_id, chunk, thread_id) -> result.-_TEXT_SENDERS = {name: partial(_registry_standalone_send, name)- for name in ("whatsapp", "email", "sms", "dingtalk", "feishu", "wecom", "signal", "qqbot", "yuanbao")}-_MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp, slack and qqbot"@@ -693,8 +694,8 @@ 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 == "discord" or (platform_name == "whatsapp" and mentions)- or (media_files and platform_name in _PLUGIN_STANDALONE_MEDIA)):+ policy = _standalone_send_policy(platform_name)+ if policy is not None and (policy.all_sends or (policy.mentions and mentions) or (media_files and policy.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,mentions=mentions)@@ -712,9 +713,9 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,f"target {platform_name} had only media attachments")}warning = (f"MEDIA attachments were omitted for {platform_name}; "f"native send_message media delivery is currently only supported for {_MEDIA_PLATFORMS_NOTE}")- text_sender = _TEXT_SENDERS.get(platform_name)- if text_sender is not None:- send_one = lambda chunk, is_last: text_sender(pconfig, chat_id, chunk, thread_id)+ if policy is not None and policy.text_direct:+ # Text-only straight to the plugin's standalone sender (media dropped with the warning above).+ send_one = lambda chunk, is_last: _registry_standalone_send(platform_name, pconfig, chat_id, chunk, thread_id)else:from gateway.platform_registry import platform_registryentry = platform_registry.get(platform_name)