The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): extract telegram format + gateway-loop dispatch helpers, compact media descriptors
Teknium3106c534c298
diff --git a/tools/react_to_message_tool.py b/tools/react_to_message_tool.pyindex 4859d25f38d..c4fe4247695 100644--- a/tools/react_to_message_tool.py+++ b/tools/react_to_message_tool.py@@ -1,13 +1,8 @@#!/usr/bin/env python3-"""Let the agent react to a message with an emoji in the Hermes desktop app.--The conversational counterpart to the user's tapback: same reaction store, same-one-per-author semantics, written with ``author="agent"``. Lives in the ``desktop_ui``-toolset so it costs nothing on other surfaces (platform adapters expose reactions via-``send_message(action="react")``). Defaults to the message that triggered this turn so-the model needn't thread row ids through tool calls, and emits ``message.reaction`` so-the renderer paints it without a resume.-"""+"""Agent emoji reaction in the Hermes desktop app: the counterpart to the user's tapback+(same store, one-per-author, ``author="agent"``). Lives in the ``desktop_ui`` toolset so it+costs nothing elsewhere (adapters expose reactions via ``send_message(action="react")``);+defaults to the triggering message and emits ``message.reaction`` for live painting."""import json@@ -30,9 +25,8 @@ def _react(emoji: str, message_row_id, messages_back, *, db, session_key: str) -row_id = message_row_idtarget_role = "user"if row_id is None:- # Default target: the latest user message. `messages_back` steps to earlier user- # turns (1 = the one before) — ids aren't visible to the model and quoting text is- # ambiguous, but "two messages ago" is how a person thinks.+ # Default: the latest user message; `messages_back` steps to earlier user turns+ # (ids aren't visible to the model; "two messages ago" is how a person thinks).back = max(0, int(messages_back or 0))row_id = db.latest_message_row_id(session_key, role="user", offset=back)if row_id is None:@@ -48,9 +42,8 @@ def _react(emoji: str, message_row_id, messages_back, *, db, session_key: str) -if reactions is None:return tool_error(f"Message {row_id} is not part of this conversation.")- # Paint it live. A missing bridge (non-desktop surface) is not an error — the reaction- # is persisted and shows on next load. `role` lets the renderer match a live message- # that doesn't know its durable row id yet (learned on resume).+ # Paint it live; a missing bridge (non-desktop) is not an error — the reaction is+ # persisted. `role` lets the renderer match a live message without a durable row id.try:desktop_ui.emit("message.reaction", {"row_id": int(row_id), "reactions": reactions, "role": target_role})diff --git a/tools/send_message_senders.py b/tools/send_message_senders.pyindex 68bbe156f38..54a6ebed514 100644--- a/tools/send_message_senders.py+++ b/tools/send_message_senders.py@@ -219,67 +219,63 @@ async def _telegram_send_one_media(the file because the first attempt consumed it."""ext = os.path.splitext(media_path)[1].lower()voice_note = ext in _VOICE_EXTS and is_voice- with open(media_path, "rb") as f:- media_kwargs = dict(thread_kwargs)- # ``caption`` is only set for a single captionable file, so this never- # double-captions a multi-file send or a voice note.- if caption is not None and not voice_note:- media_kwargs["caption"] = caption- media_kwargs["parse_mode"] = parse_mode- if voice_note or ext in _TELEGRAM_SEND_AUDIO_EXTS:- try:- from plugins.platforms.telegram.adapter import _probe_voice_duration_seconds- duration = await asyncio.to_thread(_probe_voice_duration_seconds, media_path)- if duration is not None:- media_kwargs["duration"] = duration- except Exception:- pass-- async def _send(**kw):- return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **kw)+ media_kwargs = dict(thread_kwargs)+ # ``caption`` is only set for a single captionable file, so this never+ # double-captions a multi-file send or a voice note.+ if caption is not None and not voice_note:+ media_kwargs.update(caption=caption, parse_mode=parse_mode)+ if voice_note or ext in _TELEGRAM_SEND_AUDIO_EXTS:+ try:+ from plugins.platforms.telegram.adapter import _probe_voice_duration_seconds+ duration = await asyncio.to_thread(_probe_voice_duration_seconds, media_path)+ if duration is not None:+ media_kwargs["duration"] = duration+ except Exception:+ pass+ with open(media_path, "rb") as f:try:- return await _send(**media_kwargs)+ return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)except Exception as media_err:+ err_text = str(media_err).lower()if _is_telegram_thread_not_found(media_err) and media_kwargs.get("message_thread_id"):logger.warning("Thread %s not found for media send, retrying without message_thread_id",- media_kwargs["message_thread_id"])- f.seek(0)- media_kwargs.pop("message_thread_id", None)- return await _send(**media_kwargs)- err_text = str(media_err).lower()- if media_kwargs.get("parse_mode") and ("parse" in err_text or "caption" in err_text):+ media_kwargs.pop("message_thread_id"))+ elif media_kwargs.get("parse_mode") and ("parse" in err_text or "caption" in err_text):logger.warning("Caption parse failed for media send, retrying plain: %s",_sanitize_error_text(media_err))- f.seek(0)media_kwargs.pop("parse_mode", None)if not has_html and media_kwargs.get("caption"):media_kwargs["caption"] = _strip_mdv2_safe(media_kwargs["caption"])- return await _send(**media_kwargs)- raise+ else:+ raise+ f.seek(0)+ return await _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)-async def _send_telegram(token, chat_id, message, media_files=None, thread_id=None, disable_link_previews=False, force_document=False):- """One-shot Telegram Bot API send. Markdown -> MarkdownV2 via the adapter's- ``format_message``; text already containing HTML tags is sent as HTML instead.- Parse failures fall back to plain text so the message still delivers."""+def _telegram_format(message):+ """``(formatted, parse_mode, has_html)``: text already containing HTML tags is sent as+ HTML; otherwise Markdown -> MarkdownV2 via the adapter's ``format_message``."""+ from telegram.constants import ParseMode++ has_html = bool(re.search(r'<[a-zA-Z/][^>]*>', message))+ if has_html:+ return message, ParseMode.HTML, Truetry:- from telegram.constants import ParseMode+ from plugins.platforms.telegram.adapter import TelegramAdapter+ formatted = TelegramAdapter.__new__(TelegramAdapter).format_message(message)+ except Exception:+ formatted = message # formatting unavailable: send as-is+ return formatted, ParseMode.MARKDOWN_V2, False- _has_html = bool(re.search(r'<[a-zA-Z/][^>]*>', message))- if _has_html:- formatted = message- send_parse_mode = ParseMode.HTML- else:- try:- from plugins.platforms.telegram.adapter import TelegramAdapter- formatted = TelegramAdapter.__new__(TelegramAdapter).format_message(message)- except Exception:- formatted = message # formatting unavailable: send as-is- send_parse_mode = ParseMode.MARKDOWN_V2+async def _send_telegram(token, chat_id, message, media_files=None, thread_id=None, disable_link_previews=False, force_document=False):+ """One-shot Telegram Bot API send; parse failures fall back to plain text so the+ message still delivers."""+ try:+ formatted, send_parse_mode, _has_html = _telegram_format(message)bot = _telegram_bot(token)from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id@@ -291,9 +287,7 @@ async def _send_telegram(token, chat_id, message, media_files=None, thread_id=Notext_kwargs = dict(thread_kwargs)if disable_link_previews:text_kwargs["disable_web_page_preview"] = True-- last_msg = None- warnings = []+ last_msg, warnings = None, []# MEDIA caption: a single captionable file + short text rides on the bubble as# its *formatted* caption. Formatting can inflate a raw <1024 string past@@ -421,18 +415,14 @@ async def _resolve_slack_user_target(token, chat_id):query = name.strip().lstrip("@").lower()matches, cursor = [], Nonefor _page in range(20):- payload = {"limit": 200}- if cursor:- payload["cursor"] = cursor+ payload = {"limit": 200, **({"cursor": cursor} if cursor else {})}data = await post_api(session, "users.list", payload)if not data.get("ok"):return None, f"Slack users.list error: {data.get('error', 'unknown')}"- for member in data.get("members", []):- if member.get("deleted") or member.get("is_bot"):- continue- # Stable handle only: display/real names are mutable and non-unique.- if str(member.get("name", "")).strip().lower() == query:- matches.append(member)+ # Stable handle only: display/real names are mutable and non-unique.+ matches += [m for m in data.get("members", [])+ if not (m.get("deleted") or m.get("is_bot"))+ and str(m.get("name", "")).strip().lower() == query]cursor = (data.get("response_metadata") or {}).get("next_cursor")if not cursor:break@@ -476,15 +466,12 @@ async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batif "error" not in data:await scheduler.report_rpc_duration(_rpc_duration, n)return None-err = data["error"]if not rl._is_signal_rate_limit_error(err):return _error(f"Signal RPC error on batch {idx + 1}/{n_batches}: {err}")-server_retry_after = rl._extract_retry_after_seconds(err)scheduler.feedback(server_retry_after, n)retry_after_label = f"{server_retry_after:.0f}s" if server_retry_after else "unknown"-if attempt >= rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS:logger.error("Signal: rate-limit retries exhausted on batch %d/%d "diff --git a/tools/send_message_targets.py b/tools/send_message_targets.pyindex 73aa28afb11..1b80c59c158 100644--- a/tools/send_message_targets.py+++ b/tools/send_message_targets.py@@ -8,9 +8,8 @@ logger = logging.getLogger("tools.send_message_tool")_TELEGRAM_TOPIC_TARGET_RE = re.compile(r"^\s*(-?\d+)(?::(\d+))?\s*$")_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 before-# chat.postMessage (posting straight to a U/W id fails); ``@handle`` -> ``user_name:...``-# is resolved through users.list first.+# 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*$")@@ -21,15 +20,14 @@ _WEIXIN_TARGET_RE = re.compile(r"^\s*((?:wxid|gh|v\d+|wm|wb)_[A-Za-z0-9_-]+|[A-Z_YUANBAO_TARGET_RE = re.compile(r"^\s*((?:group|direct):[^:]+)\s*$")# Discord snowflake IDs are numeric, same regex pattern as Telegram topic targets._NUMERIC_TOPIC_RE = _TELEGRAM_TOPIC_TARGET_RE-# Platforms addressing recipients by E.164 phone number ("+1555..."): without this the-# '+' fails the isdigit() rule and falls through to channel-name resolution, which cannot-# resolve a raw number. The '+' is kept because the adapters expect the E.164 form.+# Platforms addressing recipients by E.164 phone number ("+1555..."): the '+' fails the+# isdigit() rule and channel-name resolution cannot resolve a raw number; keep the '+'._PHONE_PLATFORMS = frozenset({"photon", "signal", "sms", "whatsapp"})_E164_TARGET_RE = re.compile(r"^\s*\+(\d{7,15})\s*$")# Photon DM chat GUID (mirrors _DM_CHAT_GUID_RE in the photon adapter)._PHOTON_DM_GUID_RE = re.compile(r"^any;-;\+\d{6,}$")-# WhatsApp JIDs (groups <digits>@g.us, users <phone>@s.whatsapp.net, linked ids @lid,-# broadcast/newsletter): native targets the bridge accepts verbatim — never home-channel.+# WhatsApp JIDs (@g.us groups, @s.whatsapp.net users, @lid, broadcast/newsletter): native+# targets the bridge accepts verbatim — never home-channel._WHATSAPP_JID_RE = re.compile(r"^\s*[\w-]+@(?:g\.us|s\.whatsapp\.net|lid|broadcast|newsletter)\s*$", re.IGNORECASE)# Buzz channels/DMs are native UUIDs: explicit targets, never the home channel.@@ -37,16 +35,14 @@ _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)# A valid address is an explicit email target, not a channel name to resolve._EMAIL_TARGET_RE = re.compile(r"^\s*[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\s*$")-# Home-channel env var exceptions to "<PLATFORM>_HOME_CHANNEL" (email reads-# EMAIL_HOME_ADDRESS, see gateway/config.py) so the error guidance is actionable.+# Exceptions to "<PLATFORM>_HOME_CHANNEL" (email reads EMAIL_HOME_ADDRESS) for error hints._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. Order inside each-# parser matters (e.g. Slack thread form before bare conversation id).+# 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)."""def parse(ref):@@ -94,7 +90,7 @@ def _parse_slack(ref):def _parse_matrix(ref):# "<room>:$<event_id>" addresses a thread (rfind: room ids contain ':'). Bare "!room" /- # "@user" are explicit too, but via the generic rule so the numeric check keeps precedence.+ # "@user" go via the generic rule so the numeric check keeps precedence.trimmed = ref.strip()split_idx = trimmed.rfind(":$")if split_idx > 0:@@ -103,8 +99,7 @@ def _parse_matrix(ref):def _parse_yuanbao(ref):- # "group:<code>" / "direct:<id>"; a bare number is a group code, never a generic- # numeric chat id (yuanbao never falls through to the generic rules).+ # "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@@ -114,8 +109,7 @@ def _parse_yuanbao(ref):def _parse_nonempty(ref):- # ntfy topics and WeCom ids (wr/wc groups, wo/bare users — the adapter picks the- # send command) are explicit whenever non-empty.+ # 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@@ -149,12 +143,9 @@ _PLATFORM_PARSERS = {def _parse_target_ref(platform_name: str, target_ref: str):- """Parse a tool target into (chat_id, thread_id, explicit).-- Platform parser first, then the shared rules in this order: E.164 phone numbers- (keeping the '+' the signal/sms/whatsapp adapters expect), bare numeric ids, Matrix- ``!room``/``@user``, XMPP JIDs. Anything else goes to channel-directory resolution.- """+ """(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.+ Anything else goes to channel-directory resolution."""parser = _PLATFORM_PARSERS.get(platform_name)if parser is not None:parsed = parser(target_ref)@@ -178,18 +169,13 @@ def resolve_send_target() -> tuple[str | None, str | None, str | None]:"""Resolve one send target the same way for every caller (model tool, CLI, cron).- Channel-directory IDs are trusted. Plugin platforms must explicitly parse native- target syntax; for the model-facing send tool (the default) an unresolvable target- is an error the model can read and pick a listed target instead.-- ``pass_unresolved_references=True`` is for callers with no model in the loop (cron- delivering a stored job's output, react/unreact on platform-native message ids): an- unresolvable target on a built-in platform, or on a plugin platform that declares no- parser, is handed to the adapter exactly as written and the adapter decides. A plugin- platform that DOES declare a parser stays strict for every caller.-- The optional validator has the final say over parser-normalized, directory-resolved,- and passed-through IDs alike.+ Channel-directory IDs are trusted; plugin parsers are the authority on native syntax.+ By default an unresolvable target is an error the model can read and pick a listed+ target instead. ``pass_unresolved_references=True`` (no model in the loop: cron,+ react/unreact on native message ids) hands an unresolvable target on a built-in+ platform, or a plugin platform declaring no parser, to the adapter exactly as written;+ a plugin platform WITH a parser stays strict for every caller. The optional validator+ has the final say over parser-normalized, directory-resolved and passed-through IDs."""from gateway.config import Platformfrom gateway.platform_registry import platform_registrydiff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex 209fee15d63..c1377ee67b4 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -1,9 +1,5 @@-"""Send Message Tool -- cross-channel messaging via platform APIs.--Sends a message to a user or channel on any connected messaging platform-(Telegram, Discord, Slack, ...), lists available targets and resolves-human-friendly channel names to IDs. Works in both CLI and gateway contexts.-"""+"""Send Message Tool -- cross-channel messaging via platform APIs (send, list targets,+react); works in both CLI and gateway contexts."""import asyncioimport json@@ -25,10 +21,9 @@ from tools.send_message_senders import ( # noqa: F401_send_weixin, _send_yuanbao)from tools.registry import tool_error-# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model-# tool (the agent must not fire cross-platform messages on its own). The send engine-# here is the shared transport for cron delivery, the ``hermes send`` CLI, the gateway-# kanban notifier and the opt-in MCP server, which import the helpers directly.+# 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.def prepare_send_message_platforms() -> None:@@ -55,8 +50,8 @@ def _split_target(target: str):def _resolve_tool_target(target: str, *, pass_unresolved_references: bool = False):- """Split and resolve a tool ``target``; returns ``(platform_name, chat_id, thread_id, error)``.- ``chat_id`` is None when no ref was given (caller falls back to the home channel)."""+ """``(platform_name, chat_id, thread_id, error)`` for a tool ``target``; ``chat_id`` is+ None when no ref was given (caller falls back to the home channel)."""platform_name, target_ref = _split_target(target)prepare_send_message_platforms()if not target_ref:@@ -76,10 +71,9 @@ def _handle_list():def _handle_react(args, remove=False):- """Attach (or with ``remove=True`` retract) an emoji reaction via a live gateway- adapter exposing ``add_reaction(chat_id, emoji, message_id)`` /- ``remove_reaction(chat_id, message_id)`` (e.g. photon/iMessage tapbacks). No- standalone fallback: reacting needs the adapter's live message-id state."""+ """Attach (``remove=True``: retract) an emoji reaction via a live gateway adapter's+ ``add_reaction`` / ``remove_reaction``. No standalone fallback: reacting needs the+ adapter's live message-id state."""target = args.get("target", "")emoji = (args.get("emoji") or "").strip()message_id = (args.get("message_id") or "").strip() or None@@ -87,21 +81,19 @@ def _handle_react(args, remove=False):return tool_error("'target' is required when action='unreact'" if removeelse "Both 'target' and 'emoji' are required when action='react'")- # Platform-native ids (e.g. photon GUIDs) match no parser/directory entry; hand- # them to the adapter unchanged and let it validate.+ # Platform-native ids (e.g. photon GUIDs) match no parser/directory entry; the+ # adapter validates them.platform_name, chat_id, _thread_id, resolution_error = _resolve_tool_target(target, pass_unresolved_references=True)if resolution_error:return tool_error(resolution_error)- try:- from gateway.config import Platform, load_gateway_config- platform = Platform(platform_name)- except (ValueError, KeyError):- return tool_error(f"Unknown platform: {platform_name}")-+ platform, err = _platform_enum(platform_name)+ if err:+ return tool_error(err)if not chat_id:try:+ from gateway.config import load_gateway_confighome = load_gateway_config().get_home_channel(platform)except Exception:home = None@@ -158,9 +150,8 @@ def _handle_send(args):from gateway.platforms.base import BasePlatformAdapter- # Capture [[as_document]] before extract_media strips it: image files then go- # through send_document so the original bytes survive (Telegram's sendPhoto- # recompresses to 1280px).+ # Capture [[as_document]] before extract_media strips it: images then go through+ # send_document so the original bytes survive (Telegram's sendPhoto recompresses).force_document_attachments = "[[as_document]]" in messagemedia_files, cleaned_message = BasePlatformAdapter.extract_media(message)@@ -186,8 +177,7 @@ def _handle_send(args):from model_tools import _run_asyncsend_kwargs = {"thread_id": thread_id, "media_files": media_files,"force_document": force_document_attachments}- # Only custom plugin handlers receive the complete typed request; the- # built-in call contract stays exact.+ # Only custom plugin handlers receive the complete typed request.if entry is not None and entry.send_message_handler is not None:send_kwargs["args"] = argsresult = _run_async(_send_to_platform(platform, pconfig, chat_id, cleaned_message, **send_kwargs))@@ -204,24 +194,28 @@ def _handle_send(args):return json.dumps(_error(f"Send failed: {e}"))-def _resolve_platform_config(platform_name, config):- """Return ``(platform, pconfig, registry_entry, error)`` for a send.+def _platform_enum(platform_name):+ """``(Platform, None)`` or ``(None, error)`` for a platform name."""+ from gateway.config import Platform+ try:+ return Platform(platform_name), None+ except (ValueError, KeyError):+ return None, f"Unknown platform: {platform_name}"+- Plugin platforms must be registered; disabled/missing platforms error, except- Weixin, which may be configured purely via .env (synthesized pconfig so- send_message and cron delivery work without a gateway.yaml entry).- """+def _resolve_platform_config(platform_name, config):+ """``(platform, pconfig, registry_entry, error)`` for a send. Plugin platforms must be+ registered; disabled/missing platforms error, except Weixin, which may be configured+ purely via .env (synthesized pconfig so cron delivery works without gateway.yaml)."""from gateway.config import Platformfrom gateway.platform_registry import platform_registryentry = platform_registry.get(platform_name)- is_builtin = platform_name in {member.value for member in Platform}- if not is_builtin and entry is None:+ if entry is None and platform_name not in {member.value for member in Platform}:return None, None, None, f"Unknown or unregistered plugin platform: {platform_name}"- try:- platform = Platform(platform_name)- except (ValueError, KeyError):- return None, None, None, f"Unknown platform: {platform_name}"+ platform, err = _platform_enum(platform_name)+ if err:+ return None, None, None, errpconfig = config.platforms.get(platform)if not pconfig or not pconfig.enabled:@@ -252,9 +246,9 @@ def _home_chat_id(config, platform, platform_name):def _slack_dm_chat_id(pconfig, chat_id):- """Open Slack user targets as DM conversations: ``user:U...`` / ``user_name:@handle``- from the parser, or a bare U... id from session metadata / home-channel config.- chat.postMessage needs a conversation ID. Returns ``(chat_id, None)`` or ``(None, error_dict)``."""+ """Open Slack user targets (``user:U...`` / ``user_name:@handle`` from the parser, or a+ bare U... id from session metadata / home-channel config) as DM conversations —+ chat.postMessage needs a conversation ID. ``(chat_id, None)`` or ``(None, error_dict)``."""dm_target = chat_idif dm_target.startswith("U") and _SLACK_USER_ID_RE.fullmatch(dm_target):dm_target = f"user:{dm_target}"@@ -352,9 +346,8 @@ def _live_media_method(ext, is_voice, force_document):async def _send_live_adapter_media(adapter, chat_id, message, media_files, *, thread_id=None, metadata=None, force_document=False):- """Deliver text and every media descriptor through adapter media APIs.- Adapters that only inherit the BasePlatformAdapter stub for a media kind- are treated as unsupported rather than silently no-op'd."""+ """Deliver text and every media descriptor through adapter media APIs. Adapters that+ only inherit the BasePlatformAdapter stub for a kind are unsupported, not no-op'd."""caption, separate_text = _media_caption_split(message, media_files, max_caption_len=_DEFAULT_CAPTION_LIMIT)last_result = None@@ -367,13 +360,10 @@ async def _send_live_adapter_media(total = len(media_files)for index, descriptor in enumerate(media_files):- invalid = {"error": f"Adapter media send failed: invalid media descriptor {index + 1}/{total}"}- if not isinstance(descriptor, (list, tuple)) or not descriptor:- return invalid- media_path = descriptor[0]- is_voice = bool(descriptor[1]) if len(descriptor) > 1 else False+ media_path = descriptor[0] if isinstance(descriptor, (list, tuple)) and descriptor else Noneif not isinstance(media_path, str) or not media_path:- return invalid+ return {"error": f"Adapter media send failed: invalid media descriptor {index + 1}/{total}"}+ is_voice = bool(descriptor[1]) if len(descriptor) > 1 else Falseif not os.path.exists(media_path):return {"error": f"Adapter media send failed: media file {index + 1}/{total} was not found"}@@ -381,10 +371,8 @@ async def _send_live_adapter_media(method_name, media_kind = _live_media_method(ext, is_voice, force_document)adapter_method = getattr(type(adapter), method_name, None)if adapter_method is None or adapter_method is getattr(BasePlatformAdapter, method_name):- return {- "error": (- f"Live adapter does not implement native {media_kind} delivery; "- f"media file {index + 1}/{total} was not sent")}+ return {"error": (f"Live adapter does not implement native {media_kind} delivery; "+ f"media file {index + 1}/{total} was not sent")}kwargs = {"caption": caption if index == 0 else None, "reply_to": thread_id, "metadata": metadata}try:last_result = await getattr(adapter, method_name)(chat_id, media_path, **kwargs)@@ -403,12 +391,33 @@ async def _send_live_adapter_media(return {"success": True, "message_id": last_result.message_id, "media_delivered": True}+async def _dispatch_on_gateway_loop(runner, make_coro, log_message):+ """Await ``make_coro()`` on the gateway's loop. adapter.send() uses queues/tasks bound+ to that loop; awaiting it from another loop (the tool worker thread) deadlocks, so+ cross-loop calls are scheduled threadsafe onto it."""+ gateway_loop = getattr(runner, "_gateway_loop", None)+ try:+ current_loop = asyncio.get_running_loop()+ except RuntimeError:+ current_loop = None+ if gateway_loop is None or current_loop is gateway_loop:+ return await make_coro() # same loop / no gateway loop (CLI, tests)+ if not gateway_loop.is_running():+ return {"error": "Gateway loop is not running; cannot dispatch adapter send"}+ from agent.async_utils import safe_schedule_threadsafe+ fut = safe_schedule_threadsafe(make_coro(), gateway_loop, logger=logger, log_message=log_message)+ if fut is None:+ return {"error": "Gateway loop unavailable for send dispatch"}+ # shield: a cancelled caller (agent interrupt) must not cancel the enqueued send or a+ # retry would duplicate it. No timeout: the adapter and outer _run_async bound the wait.+ return await asyncio.shield(asyncio.wrap_future(fut))++async def _send_via_adapter(platform, pconfig, chat_id, chunk, *, thread_id=None, media_files=None, force_document=False):- """Send via the live in-process gateway adapter (``_gateway_runner_ref``), else the- plugin's ``standalone_sender_fn`` (gateway not in this process, e.g. cron — the runner- weakref is None), else a descriptive error naming both options. Media descriptors go- through the adapter's native media APIs under the same cross-loop rules as text."""+ """Live in-process gateway adapter first, else the plugin's ``standalone_sender_fn``+ (gateway not in this process, e.g. cron), else an error naming both options. Media+ goes through the adapter's native media APIs under the same cross-loop rules."""platform_name = platform.value if hasattr(platform, "value") else str(platform)runner, adapter = _live_adapter(platform)if adapter is not None:@@ -419,39 +428,15 @@ async def _send_via_adapter(if platform_name == "ntfy" and chat_id:metadata["publish_topic"] = chat_idmetadata = metadata or None- # adapter.send() uses queues/tasks bound to the gateway's loop. Awaiting it- # from another loop (the tool worker thread) deadlocks on a cross-loop- # Future, so dispatch onto the gateway loop instead.- gateway_loop = getattr(runner, "_gateway_loop", None)- try:- current_loop = asyncio.get_running_loop()- except RuntimeError:- current_loop = None- cross_loop = gateway_loop is not None and current_loop is not gateway_loop-- async def _dispatch(make_coro, log_message):- if not cross_loop:- return await make_coro() # same loop / no gateway loop (CLI, tests)- if not gateway_loop.is_running():- return {"error": "Gateway loop is not running; cannot dispatch adapter send"}- from agent.async_utils import safe_schedule_threadsafe- fut = safe_schedule_threadsafe(- make_coro(), gateway_loop, logger=logger, log_message=log_message)- if fut is None:- return {"error": "Gateway loop unavailable for send dispatch"}- # shield: a cancelled caller (agent interrupt) must not cancel the- # already-enqueued gateway send, or a retry would duplicate it. No timeout- # here — the adapter's request timeout and the outer _run_async bound the wait.- return await asyncio.shield(asyncio.wrap_future(fut))-if media_files:- return await _dispatch(+ return await _dispatch_on_gateway_loop(+ runner,lambda: _send_live_adapter_media(adapter, chat_id, chunk, media_files,thread_id=thread_id, metadata=metadata, force_document=force_document),"send_message: failed to schedule media send on gateway loop")- result = await _dispatch(- lambda: adapter.send(chat_id=chat_id, content=chunk, metadata=metadata),+ result = await _dispatch_on_gateway_loop(+ runner, lambda: adapter.send(chat_id=chat_id, content=chunk, metadata=metadata),"send_message: failed to schedule on gateway loop")except asyncio.CancelledError:raise@@ -494,8 +479,7 @@ async def _send_via_adapter(async def _send_chunks(chunks, send_one):- """Send chunks in order via ``send_one(chunk, is_last)``; stop at the first- error dict, otherwise return the last result."""+ """``send_one(chunk, is_last)`` in order; stop at the first error dict, else last result."""last_result = Nonefor i, chunk in enumerate(chunks):result = await send_one(chunk, i == len(chunks) - 1)@@ -506,10 +490,9 @@ async def _send_chunks(chunks, send_one):def _platform_max_length(platform):- """Max message length for chunking: the adapter constant for Signal (its raw- JSON-RPC path never sees SignalAdapter's own chunking, so signal-cli would reject- long sends whole), the registry's ``max_message_length`` for plugins (Slack,- Feishu, ...), else None (no chunking)."""+ """Chunking limit: the adapter constant for Signal (its raw JSON-RPC path bypasses+ SignalAdapter's own chunking), the registry's ``max_message_length`` for plugins,+ else None (no chunking)."""from gateway.config import Platformif platform == Platform.SIGNAL:@@ -528,11 +511,10 @@ def _platform_max_length(platform):return None-# Plugin platforms whose media (and, for Discord, all) sends go straight to the registry-# ``standalone_sender_fn`` — bypassing the live adapter on purpose: Discord's plugin-# ``_standalone_send`` handles forum channels, threads and multipart uploads-# (historically the only Discord path); Slack uploads via files_upload_v2; WhatsApp-# posts each file to the Baileys bridge /send-media so media arrive as native bubbles.+# Plugin platforms whose media (Discord: all) sends bypass the live adapter on purpose for+# the registry ``standalone_sender_fn``: Discord's handles forum channels/threads/multipart+# uploads; Slack uploads via files_upload_v2; WhatsApp posts to the Baileys bridge+# /send-media so media arrive as native bubbles.# platform -> (error label, run discover_plugins first, caption-capable,# media_files sentinel for non-final chunks, forward force_document)_PLUGIN_STANDALONE_MEDIA = {@@ -545,8 +527,8 @@ _PLUGIN_STANDALONE_MEDIA = {async def _send_plugin_standalone(platform_name, pconfig, chat_id, message, chunks, media_files, *, thread_id, max_len, force_document):- """Chunked send through a plugin's standalone_sender_fn, with the single- captionable file + short text case riding as the media caption."""+ """Chunked send through a plugin's standalone_sender_fn; a single captionable file ++ short text rides as the media caption."""label, discover, captionable, empty_media, pass_force = _PLUGIN_STANDALONE_MEDIA[platform_name]sender, err = _plugin_standalone_sender(platform_name, label=label, discover=discover)if err:@@ -568,17 +550,13 @@ async def _send_plugin_standalone(# Native-media chunked routes for built-in platforms; media rides on the final chunk,-# non-final chunks get the platform's empty-media sentinel.-# platform -> (media required, empty-media sentinel,-# sender(platform, pconfig, chat_id, chunk, media, thread_id, force_document))-# Matrix: ALL sends go through the native adapter so text is encrypted in E2EE rooms-# too (the raw-HTTP standalone path is not encryption-aware).+# non-final chunks get the empty-media sentinel. platform -> (media required, sentinel,+# sender(platform, pconfig, chat_id, chunk, media, thread_id, force_document)).+# Matrix: ALL sends use the native adapter so text is encrypted in E2EE rooms too.# Signal: attachments ride the JSON-RPC ``attachments`` param.-# Yuanbao: media needs the running gateway adapter's WebSocket.-# Slack (text; media was intercepted above): prefer the live adapter — multi-workspace-# aware and honors adapter gates like ignored_channels, while the standalone Web-API-# path may only have a token list — else the plugin's standalone sender.-# WeCom: native media only through the live gateway adapter.+# Yuanbao / WeCom: media needs the running gateway adapter.+# Slack (text; media intercepted above): prefer the live adapter — multi-workspace aware,+# honors gates like ignored_channels — else the plugin's standalone sender.# Names resolve at call time so tests can monkeypatch e.g. ``_send_signal``.def _via_adapter_route(p, pc, cid, chunk, media, tid, fd):return _send_via_adapter(p, pc, cid, chunk, thread_id=tid, media_files=media, force_document=fd)@@ -612,14 +590,10 @@ _MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feiasync 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 chunked with the adapters' smart splitter (code-block aware,- part indicators). Branch order matters: Weixin first (its native helper must not- be blocked by unrelated optional imports such as lark-oapi's heavy Feishu path),- Telegram (chunks itself), plugin standalone media routes, native chunked routes,- then the generic text path that drops media with a warning.- """+ """Route a message to the platform sender, chunking long text with the adapters' smart+ splitter. Branch 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 routes, native chunked routes, then the generic text path."""from gateway.config import Platformplatform_name = platform.value if hasattr(platform, "value") else str(platform)@@ -628,8 +602,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,if platform == Platform.WEIXIN:return await _send_weixin(pconfig, chat_id, message, media_files=media_files)- # Telegram chunks internally on the *formatted* text in UTF-16 units (MarkdownV2/HTML- # escaping inflates length), so it gets the whole message; media attaches after all text.+ # Telegram chunks internally on the *formatted* text (escaping inflates length).if platform == Platform.TELEGRAM:disable_link_previews = bool(getattr(pconfig, "extra", {}) and pconfig.extra.get("disable_link_previews"))return await _send_telegram(@@ -654,9 +627,8 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,platform, pconfig, chat_id, chunk,media_files if is_last else empty_media, thread_id, force_document))- # --- Generic path: text only. Buzz is a plugin platform with verified native media- # delivery through _send_via_adapter (media-only sends included), so it is exempt- # from the media error/warning.+ # Generic path: text only. Buzz has verified native media delivery through+ # _send_via_adapter (media-only sends included), so it is exempt from the warning.warning = Noneif media_files and platform_name != "buzz":if not message.strip():