The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): send_message wave-2 cut — table-driven telegram media, shared platform-module guard, flattened slack/target resolution, compact docs
Teknium691e2f7d9f98
diff --git a/tools/react_to_message_tool.py b/tools/react_to_message_tool.pyindex 9b28c805cd1..f8056fccae1 100644--- a/tools/react_to_message_tool.py+++ b/tools/react_to_message_tool.py@@ -4,6 +4,7 @@costs nothing elsewhere (adapters expose reactions via ``send_message(action="react")``);defaults to the triggering message and emits ``message.reaction`` for live painting."""+import contextlibimport jsonfrom gateway.session_context import get_session_env@@ -20,56 +21,41 @@ def _open_session_db():return None-def _react(emoji: str, message_row_id, messages_back, *, db, session_key: str) -> str:- row_id = message_row_id- target_role = "user"- if row_id is None:- # 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:- return tool_error(- f"No user message found {back} back." if back else "No user message to react to yet.")- else:- target_role = db.get_message_role(session_key, int(row_id)) or "user"-- try:- reactions = db.set_message_reaction(session_key, int(row_id), emoji or None, author="agent")- except Exception as exc:- return tool_error(f"Failed to set the reaction: {exc}")- 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) 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})- except Exception:- pass-- return json.dumps({"success": True, "row_id": int(row_id), "reactions": reactions}, ensure_ascii=False)--def react_to_message_tool(emoji: str, message_row_id=None, messages_back=None) -> str:"""Attach (or with an empty ``emoji`` retract) the agent's reaction."""emoji = (emoji or "").strip()session_key = get_session_env("HERMES_SESSION_KEY", "") or get_session_env("HERMES_SESSION_ID", "")if not session_key:return tool_error("No active session — reactions need a persisted conversation.")-db = _open_session_db()if db is None:return tool_error("Session storage is unavailable.")try:- return _react(emoji, message_row_id, messages_back, db=db, session_key=session_key)- finally:+ row_id, target_role = message_row_id, "user"+ if row_id is None:+ # 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:+ return tool_error(f"No user message found {back} back." if back else "No user message to react to yet.")+ else:+ target_role = db.get_message_role(session_key, int(row_id)) or "user"try:+ reactions = db.set_message_reaction(session_key, int(row_id), emoji or None, author="agent")+ except Exception as exc:+ return tool_error(f"Failed to set the reaction: {exc}")+ 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) is not an error — the reaction is+ # persisted. `role` lets the renderer match a live message without a durable row id.+ with contextlib.suppress(Exception):+ desktop_ui.emit("message.reaction", {"row_id": int(row_id), "reactions": reactions, "role": target_role})+ return json.dumps({"success": True, "row_id": int(row_id), "reactions": reactions}, ensure_ascii=False)+ finally:+ with contextlib.suppress(Exception):from hermes_state import release_or_closerelease_or_close(db)- except Exception:- passdef check_react_requirements() -> bool:diff --git a/tools/send_message_senders.py b/tools/send_message_senders.pyindex e3721cb14bb..d287f033596 100644--- a/tools/send_message_senders.py+++ b/tools/send_message_senders.py@@ -1,6 +1,7 @@"""Standalone per-platform senders and error helpers for send_message."""import asyncio+import contextlibimport loggingimport osimport re@@ -14,33 +15,24 @@ _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".m2a", ".wav", ".m4a", ".flac"}_VOICE_EXTS = {".ogg", ".opus"}-# Telegram's sendAudio only accepts MP3 / M4A; other audio goes via sendVoice (Opus/OGG) or document.-_TELEGRAM_SEND_AUDIO_EXTS = {".mp3", ".m4a"}--# Extensions carrying a native caption on the media bubble. Voice/audio notes are excluded:-# a caption on a voice note reads as a separate label, so the text stays its own message.+_TELEGRAM_SEND_AUDIO_EXTS = {".mp3", ".m4a"} # sendAudio accepts only these; other audio -> sendVoice / document+# Captionable on the media bubble; voice/audio notes excluded (a caption there reads as a separate label)._CAPTIONABLE_EXTS = _IMAGE_EXTS | _VIDEO_EXTS | {".pdf", ".doc", ".docx", ".txt", ".md", ".csv", ".xlsx", ".zip"}-# Native caption limits (chars): Telegram caps photo/video at 1024; one conservative shared ceiling elsewhere._TELEGRAM_CAPTION_LIMIT = 1024_DEFAULT_CAPTION_LIMIT = 4096def _media_caption_split(text, media_files, *, max_caption_len):- """Single chokepoint deciding whether text rides on the media bubble as its caption.-- ``(caption, "")`` only for exactly one captionable file (not a voice/audio note)- whose text fits ``max_caption_len``; otherwise ``(None, text)`` — multi-file- caption→file association is ambiguous. Length is codepoints, which never- under-counts Telegram's UTF-16 units for BMP text (over-counting fails safe);- the Telegram sender re-checks the *formatted* caption since escaping inflates it.- """+ """Single chokepoint deciding whether text rides on the media bubble as its caption:+ ``(caption, "")`` only for exactly one captionable file (not a voice/audio note) whose+ text fits ``max_caption_len``, else ``(None, text)`` — multi-file caption→file association+ is ambiguous. Length is codepoints (never under-counts Telegram's UTF-16 units for BMP+ text); the Telegram sender re-checks the *formatted* caption since escaping inflates it."""stripped = (text or "").strip()media = media_files or []- if not stripped or len(media) != 1 or len(stripped) > max_caption_len:- return None, text- media_path, is_voice = media[0]- if is_voice or os.path.splitext(media_path)[1].lower() not in _CAPTIONABLE_EXTS:+ if (not stripped or len(media) != 1 or len(stripped) > max_caption_len or media[0][1]+ or os.path.splitext(media[0][0])[1].lower() not in _CAPTIONABLE_EXTS):return None, textreturn stripped, ""@@ -68,20 +60,15 @@ def _success(platform: str, chat_id, warnings=None, **fields) -> dict:**({"warnings": warnings} if warnings else {})}-def _display_chat_id(platform_name: str, chat_id: str) -> str:- """Return a result-safe chat identifier for tool transcripts/log consumers."""- return "group:***" if platform_name == "signal" and str(chat_id).startswith("group:") else chat_id--_NO_DELIVERABLE = "No deliverable text or media remained after processing MEDIA tags"-_TELEGRAM_TRANSIENT_MARKERS = ("bad gateway", "502", "too many requests", "429",- "service unavailable", "503", "gateway timeout", "504")+_TELEGRAM_TRANSIENT_MARKERS = ("bad gateway", "502", "too many requests", "429", "service unavailable", "503",+ "gateway timeout", "504")def _telegram_retry_delay(exc: Exception, attempt: int) -> float | None:- """Seconds to wait before retrying, or None when final. Honours ``retry_after``;- timeouts are never retried (the send may have gone through); 5xx/429 back off."""+ """Retry delay in seconds, or None when final: honours ``retry_after``; timeouts are+ never retried (the send may have gone through); 5xx/429 back off exponentially."""retry_after = getattr(exc, "retry_after", None)if retry_after is not None:try:@@ -114,22 +101,19 @@ def _is_telegram_thread_not_found(error: Exception) -> bool:def _telegram_bot(token):- """Bot honouring TELEGRAM_PROXY (``telegram.proxy_url``) — without it the standalone- path times out where api.telegram.org is blocked. Falls back to a direct connection."""+ """Bot honouring TELEGRAM_PROXY (standalone sends time out where api.telegram.org is+ blocked); falls back to a direct connection."""from telegram import Bottry:from gateway.platforms.base import resolve_proxy_urlproxy = resolve_proxy_url("TELEGRAM_PROXY", target_hosts=["api.telegram.org"])- except Exception:- proxy = None- if proxy:- try:- from telegram.request import HTTPXRequest- logger.info("send_message: standalone Telegram send routed through proxy %s", proxy)- return Bot(token=token, request=HTTPXRequest(proxy=proxy),- get_updates_request=HTTPXRequest(proxy=proxy))- except Exception as proxy_err:- logger.warning("send_message: failed to attach Telegram proxy (%s), falling back to direct connection", proxy_err)+ if not proxy:+ return Bot(token=token)+ from telegram.request import HTTPXRequest+ logger.info("send_message: standalone Telegram send routed through proxy %s", proxy)+ return Bot(token=token, request=HTTPXRequest(proxy=proxy), get_updates_request=HTTPXRequest(proxy=proxy))+ except Exception as proxy_err:+ logger.warning("send_message: failed to attach Telegram proxy (%s), falling back to direct connection", proxy_err)return Bot(token=token)@@ -141,8 +125,7 @@ def _telegram_thread_kwargs(thread_id):try:from plugins.platforms.telegram.adapter import TelegramAdaptereffective = TelegramAdapter._message_thread_id_for_send(str(thread_id))- except Exception:- # Explicit mapping if the adapter import fails (python-telegram-bot missing).+ except Exception: # adapter import failed (python-telegram-bot missing): explicit mappingeffective = None if str(thread_id) == "1" else int(thread_id)return {} if effective is None else {"message_thread_id": effective}@@ -157,8 +140,8 @@ def _strip_mdv2_safe(text):def _adapter_media_method(ext, voice, force_document=False):- """Adapter media method name + kind for one file: document when forced, else image /- video / voice by extension (``voice`` already folds in the caller's audio rule)."""+ """``(adapter method, kind)``: document when forced, else image / video / voice by+ extension (``voice`` already folds in the caller's audio rule)."""if force_document:return "send_document", "document"if ext in _IMAGE_EXTS:@@ -169,33 +152,26 @@ def _adapter_media_method(ext, voice, force_document=False):async def _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **kwargs):- """Bot API media method by extension: photo (unless forced document), video, voice- note, sendAudio (MP3/M4A only), else document."""- if ext in _IMAGE_EXTS and not force_document:- return await bot.send_photo(chat_id=chat_id, photo=f, **kwargs)- if ext in _VIDEO_EXTS:- return await bot.send_video(chat_id=chat_id, video=f, **kwargs)- if ext in _VOICE_EXTS and is_voice:- return await bot.send_voice(chat_id=chat_id, voice=f, **kwargs)- if ext in _TELEGRAM_SEND_AUDIO_EXTS:- return await bot.send_audio(chat_id=chat_id, audio=f, **kwargs)- return await bot.send_document(chat_id=chat_id, document=f, **kwargs)+ """Bot API media method by extension: photo (unless forced document), video, voice note,+ sendAudio (MP3/M4A only), else document."""+ kind = next((k for exts, k in ((() if force_document else _IMAGE_EXTS, "photo"), (_VIDEO_EXTS, "video"),+ (_VOICE_EXTS if is_voice else (), "voice"), (_TELEGRAM_SEND_AUDIO_EXTS, "audio"))+ if ext in exts), "document")+ return await getattr(bot, f"send_{kind}")(chat_id=chat_id, **{kind: f}, **kwargs)async def _telegram_send_text_chunk(bot, chat_id, chunk, parse_mode, has_html, text_kwargs):- """One formatted text chunk with adapter-matching fallbacks: thread-not-found -> retry- without ``message_thread_id`` (dropped from ``text_kwargs`` for later chunks too);- parse failure -> plain text."""+ """One text chunk with adapter-matching fallbacks: thread-not-found -> retry without+ ``message_thread_id`` (dropped from ``text_kwargs`` for later chunks too); parse failure+ -> plain text."""async def send(text, mode):return await _send_telegram_message_with_retry(bot, chat_id=chat_id, text=text, parse_mode=mode, **text_kwargs)-try:return await send(chunk, parse_mode)except Exception as md_error:if _is_telegram_thread_not_found(md_error) and text_kwargs.get("message_thread_id") is not None:logger.warning("Thread %s not found in _send_telegram, retrying without message_thread_id",- text_kwargs.get("message_thread_id"))- text_kwargs.pop("message_thread_id", None)+ text_kwargs.pop("message_thread_id"))return await send(chunk, parse_mode)err_text = str(md_error).lower()if "parse" in err_text or "markdown" in err_text or "html" in err_text:@@ -205,28 +181,22 @@ async def _telegram_send_text_chunk(bot, chat_id, chunk, parse_mode, has_html, traise-async def _telegram_send_one_media(- bot, chat_id, media_path, is_voice, *, caption, parse_mode, has_html, thread_kwargs, force_document-):+async def _telegram_send_one_media(bot, chat_id, media_path, is_voice, *, caption, parse_mode, has_html,+ thread_kwargs, force_document):"""Upload one file with adapter-matching fallbacks (thread-not-found -> no- ``message_thread_id``; caption parse failure -> plain caption). Retries re-seek- the file because the first attempt consumed it."""+ ``message_thread_id``; caption parse failure -> plain caption); retries re-seek the file."""ext = os.path.splitext(media_path)[1].lower()voice_note = ext in _VOICE_EXTS and is_voice- 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)+ # ``caption`` is only set for a single captionable file, so this never double-captions+ # a multi-file send or a voice note.+ media_kwargs = {**thread_kwargs, **({"caption": caption, "parse_mode": parse_mode}+ if caption is not None and not voice_note else {})}if voice_note or ext in _TELEGRAM_SEND_AUDIO_EXTS:- try:+ with contextlib.suppress(Exception):from plugins.platforms.telegram.adapter import _probe_voice_duration_secondsduration = 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 _telegram_send_media(bot, chat_id, f, ext, is_voice, force_document, **media_kwargs)@@ -255,54 +225,42 @@ def _telegram_format(message):return message, ParseMode.HTML, Truetry:from plugins.platforms.telegram.adapter import TelegramAdapter- formatted = TelegramAdapter.__new__(TelegramAdapter).format_message(message)+ return TelegramAdapter.__new__(TelegramAdapter).format_message(message), ParseMode.MARKDOWN_V2, Falseexcept Exception:- formatted = message # formatting unavailable: send as-is- return formatted, ParseMode.MARKDOWN_V2, False+ return message, ParseMode.MARKDOWN_V2, False # formatting unavailable: send as-isasync 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."""+ """One-shot Telegram Bot API send; parse failures fall back to plain text."""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+ from gateway.platforms.base import BasePlatformAdapter, utf16_len# Telegram accepts a numeric chat_id OR an @username string; never force-int.int_chat_id = normalize_telegram_chat_id(chat_id)media_files = media_files or []thread_kwargs = _telegram_thread_kwargs(thread_id)# disable_web_page_preview is only valid for send_message, not media sends.text_kwargs = {**thread_kwargs, **({"disable_web_page_preview": True} if disable_link_previews else {})}- 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 Telegram's- # cap, so re-check in UTF-16 units and fall back to a separate body.- _tg_caption = None- from gateway.platforms.base import BasePlatformAdapter, utf16_len+ last_msg, warnings, _tg_caption = None, [], None+ # MEDIA caption rides on the bubble as its *formatted* caption; formatting can inflate a+ # raw <1024 string past Telegram's cap, so re-check in UTF-16 units._cap, _ = _media_caption_split(message, media_files, max_caption_len=_TELEGRAM_CAPTION_LIMIT)if _cap is not None and utf16_len(formatted) <= _TELEGRAM_CAPTION_LIMIT:_tg_caption, formatted = formatted, "" # suppress the separate text send below-- if formatted.strip():- # Chunk *after* formatting, in UTF-16 units: MarkdownV2/HTML escaping inflates- # text, so a raw-<4096 message can exceed the limit once formatted.- for chunk in BasePlatformAdapter.truncate_message(formatted, 4096, len_fn=utf16_len):- last_msg = await _telegram_send_text_chunk(- bot, int_chat_id, chunk, send_parse_mode, _has_html, text_kwargs)-+ # Chunk *after* formatting, in UTF-16 units: escaping can push a raw-<4096 message over.+ for chunk in BasePlatformAdapter.truncate_message(formatted, 4096, len_fn=utf16_len) if formatted.strip() else ():+ last_msg = await _telegram_send_text_chunk(bot, int_chat_id, chunk, send_parse_mode, _has_html, text_kwargs)for media_path, is_voice in media_files:if not os.path.exists(media_path):warnings.append(f"Media file not found, skipping: {media_path}")logger.warning(warnings[-1])- # Caption mode suppressed the text send; if the file it was meant to- # caption is gone, deliver the words on their own.+ # Caption mode suppressed the text send; the file is gone, so deliver the words alone.if _tg_caption is not None and last_msg is None:try:last_msg = await _send_telegram_message_with_retry(- bot, chat_id=int_chat_id, text=_tg_caption,- parse_mode=send_parse_mode, **text_kwargs)+ bot, chat_id=int_chat_id, text=_tg_caption, parse_mode=send_parse_mode, **text_kwargs)_tg_caption = None # delivered — don't re-caption a later fileexcept Exception as _cap_err:logger.warning("Telegram caption-fallback send failed for missing media: %s",@@ -310,13 +268,11 @@ async def _send_telegram(token, chat_id, message, media_files=None, thread_id=Nocontinuetry:last_msg = await _telegram_send_one_media(- bot, int_chat_id, media_path, is_voice,- caption=_tg_caption, parse_mode=send_parse_mode, has_html=_has_html,- thread_kwargs=thread_kwargs, force_document=force_document)+ bot, int_chat_id, media_path, is_voice, caption=_tg_caption, parse_mode=send_parse_mode,+ has_html=_has_html, thread_kwargs=thread_kwargs, force_document=force_document)except Exception as e:warnings.append(_sanitize_error_text(f"Failed to send media {media_path}: {e}"))logger.error(warnings[-1])-if last_msg is None:return {"error": _NO_DELIVERABLE, **({"warnings": warnings} if warnings else {})}return _success("telegram", chat_id, warnings, message_id=str(last_msg.message_id))@@ -326,20 +282,15 @@ async def _send_telegram(token, chat_id, message, media_files=None, thread_id=Noreturn _error(f"Telegram send failed: {e}")-def _live_runner():- """Return the in-process gateway runner, or None (standalone/cron)."""+def _live_adapter(platform, *, lookup_failed_warning=None):+ """``(runner, adapter)`` for the in-process gateway; ``(None, None)`` standalone (cron);+ ``(runner, None)`` when the lookup fails — logged when a warning is given, never silently+ swallowed (a silent fall-through could recreate a reconnect storm)."""try:from gateway.run import _gateway_runner_ref- return _gateway_runner_ref()+ runner = _gateway_runner_ref()except Exception:- return None---def _live_adapter(platform, *, lookup_failed_warning=None):- """Return ``(runner, adapter)`` for the running gateway, or ``(runner, None)``.- A runner whose adapter lookup raises is logged when a warning is given, never- silently swallowed (a silent fall-through could recreate a reconnect storm)."""- runner = _live_runner()+ runner = Noneif runner is None:return None, Nonetry:@@ -366,16 +317,13 @@ def _plugin_standalone_sender(platform_name, *, label=None, discover=True):async def _registry_standalone_send(platform_name, pconfig, chat_id, message, thread_id=None):"""One-shot text send through a plugin's ``standalone_sender_fn``."""sender, err = _plugin_standalone_sender(platform_name)- if err:- return err- return await sender(pconfig, chat_id, message, thread_id=thread_id)+ return err or await sender(pconfig, chat_id, message, thread_id=thread_id)async def _resolve_slack_user_target(token, chat_id):- """Resolve ``user:U...`` / ``user_name:<handle>`` to a D... DM conversation- (chat.postMessage needs a conversation ID). ``user_name:`` maps to a user id via- users.list first (stable handle match only); other ids pass through unchanged.- Returns ``(chat_id, None)`` or ``(None, error_dict)``."""+ """Resolve ``user:U...`` / ``user_name:<handle>`` to a D... DM conversation (chat.postMessage+ needs a conversation ID); ``user_name:`` goes through users.list first (stable handle match+ only); other ids pass through. ``(chat_id, None)`` or ``(None, error_dict)``."""if not (chat_id.startswith("user:") or chat_id.startswith("user_name:")):return chat_id, Nonetry:@@ -386,65 +334,52 @@ async def _resolve_slack_user_target(token, chat_id):from gateway.platforms.base import resolve_proxy_url, proxy_kwargs_for_aiohttp_sess_kw, _req_kw = proxy_kwargs_for_aiohttp(resolve_proxy_url())headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}-- async def post_api(session, method, payload):- async with session.post(- f"https://slack.com/api/{method}", headers=headers, json=payload, **_req_kw) as resp:- return await resp.json()-- async def resolve_user_name(session, name):- query = name.strip().lstrip("@").lower()- matches, cursor = [], None- for _page in range(20):- 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')}"- # 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- if not matches:- return None, f"Could not resolve Slack user '@{name}'."- if len(matches) > 1:- return None, f"Slack user '@{name}' matched multiple Slack users. Use a Slack user ID instead."- return matches[0].get("id"), None-async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30), **_sess_kw) as session:- if chat_id.startswith("user_name:"):- user_id, error = await resolve_user_name(session, chat_id[len("user_name:"):])- if error:- return None, _error(error)- chat_id = f"user:{user_id}"+ async def post_api(method, payload):+ async with session.post(f"https://slack.com/api/{method}", headers=headers, json=payload,+ **_req_kw) as resp:+ return await resp.json()- user_id = chat_id[len("user:"):]- opened = await post_api(session, "conversations.open", {"users": user_id})+ if chat_id.startswith("user_name:"):+ name = chat_id[len("user_name:"):]+ query = name.strip().lstrip("@").lower()+ matches, cursor = [], None+ for _page in range(20):+ data = await post_api("users.list", {"limit": 200, **({"cursor": cursor} if cursor else {})})+ if not data.get("ok"):+ return None, _error(f"Slack users.list error: {data.get('error', 'unknown')}")+ # 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+ if not matches:+ return None, _error(f"Could not resolve Slack user '@{name}'.")+ if len(matches) > 1:+ return None, _error(f"Slack user '@{name}' matched multiple Slack users. Use a Slack user ID instead.")+ chat_id = f"user:{matches[0].get('id')}"+ opened = await post_api("conversations.open", {"users": chat_id[len("user:"):]})if not opened.get("ok"):return None, _error(f"Slack conversations.open error: {opened.get('error', 'unknown')}. ""Check bot permissions (im:write).")dm_id = (opened.get("channel") or {}).get("id")- if not dm_id:- return None, _error("Slack conversations.open did not return a DM channel ID")- return dm_id, None+ return (dm_id, None) if dm_id else (None, _error("Slack conversations.open did not return a DM channel ID"))except Exception as e:return None, _error(f"Slack DM resolution failed: {e}")async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batch_message):- """One Signal batch under the scheduler with rate-limit retries. None on success,- False when retries were exhausted (batch lost), error dict for a non-rate-limit RPC error."""+ """One Signal batch under the scheduler with rate-limit retries: None on success, False when+ retries were exhausted (batch lost), error dict for a non-rate-limit RPC error."""n, max_attempts = len(att_batch), rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTSfor attempt in range(1, max_attempts + 1):try:await scheduler.acquire(n)_rpc_t0 = time.monotonic()data = await post(att_batch, batch_message)- _rpc_duration = time.monotonic() - _rpc_t0if "error" not in data:- await scheduler.report_rpc_duration(_rpc_duration, n)+ await scheduler.report_rpc_duration(time.monotonic() - _rpc_t0, n)return Noneerr = data["error"]if not rl._is_signal_rate_limit_error(err):@@ -453,12 +388,10 @@ async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batscheduler.feedback(server_retry_after, n)retry_after_label = f"{server_retry_after:.0f}s" if server_retry_after else "unknown"if attempt >= max_attempts:- logger.error("Signal: rate-limit retries exhausted on batch %d/%d "- "(%d attachments lost, server retry_after=%s)",- idx + 1, n_batches, n, retry_after_label)+ logger.error("Signal: rate-limit retries exhausted on batch %d/%d (%d attachments lost, "+ "server retry_after=%s)", idx + 1, n_batches, n, retry_after_label)return False- logger.warning("Signal: rate-limited on batch %d/%d "- "(attempt %d/%d, server retry_after=%s); "+ logger.warning("Signal: rate-limited on batch %d/%d (attempt %d/%d, server retry_after=%s); ""scheduler will pace the retry",idx + 1, n_batches, attempt, max_attempts, retry_after_label)except Exception as e:@@ -471,34 +404,29 @@ async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batasync def _send_signal(extra, chat_id, message, media_files=None):- """signal-cli JSON-RPC send. Attachments go in SIGNAL_MAX_ATTACHMENTS_PER_MSG batches- metered by the process-wide SignalAttachmentScheduler — the same bucket the gateway- adapter uses, so tool sends and inbound replies share rate-limit state."""+ """signal-cli JSON-RPC send; attachments go in SIGNAL_MAX_ATTACHMENTS_PER_MSG batches metered+ by the process-wide SignalAttachmentScheduler (shared with the gateway adapter's rate-limit state)."""try:import httpxexcept ImportError:return {"error": "httpx not installed"}-from gateway.platforms import signal_rate_limit as rlfrom gateway.platforms.signal_format import markdown_to_signaltry:- http_url = extra.get("http_url", "http://127.0.0.1:8080").rstrip("/")- account = extra.get("account", "")+ http_url, account = extra.get("http_url", "http://127.0.0.1:8080").rstrip("/"), extra.get("account", "")if not account:return {"error": "Signal account not configured"}-valid_media = media_files or []- attachment_paths = [path for path, _is_voice in valid_media if os.path.exists(path)]+ attachment_paths = []for media_path, _is_voice in valid_media:- if not os.path.exists(media_path):+ if os.path.exists(media_path):+ attachment_paths.append(media_path)+ else:logger.warning("Signal media file not found, skipping: %s", media_path)- # No attachments still means one (text-only) batch; with attachments- # the text rides on batch #0 so it isn't repeated per batch.+ # No attachments still means one (text-only) batch; text rides on batch #0 only.per_batch = rl.SIGNAL_MAX_ATTACHMENTS_PER_MSG- att_batches = [attachment_paths[i:i + per_batch]- for i in range(0, len(attachment_paths), per_batch)] or [[]]- n_batches = len(att_batches)- plain_text, text_styles = markdown_to_signal(message)+ att_batches = [attachment_paths[i:i + per_batch] for i in range(0, len(attachment_paths), per_batch)] or [[]]+ n_batches, (plain_text, text_styles) = len(att_batches), markdown_to_signal(message)recipient = {"groupId": chat_id[6:]} if chat_id.startswith("group:") else {"recipient": [chat_id]}async def _rpc_send(text, *, id_prefix, timeout, attachments=None, styled=False):@@ -518,20 +446,17 @@ async def _send_signal(extra, chat_id, message, media_files=None):timeout=rl._signal_send_timeout(len(batch_attachments)))resp.raise_for_status()return resp.json()-scheduler = rl.get_scheduler()logger.info("send_message Signal: scheduler state=%s, %d attachment(s) in %d batch(es)",scheduler.state(), len(attachment_paths), n_batches)failed_batches: list[int] = []for idx, att_batch in enumerate(att_batches):n = len(att_batch)- estimated = scheduler.estimate_wait(n) if n > 0 else 0.0- if n > 0 and estimated >= rl.SIGNAL_BATCH_PACING_NOTICE_THRESHOLD:+ if n > 0 and (estimated := scheduler.estimate_wait(n)) >= rl.SIGNAL_BATCH_PACING_NOTICE_THRESHOLD:# Best-effort one-shot RPC for a user-facing pacing notice.- notice = (f"(More images coming — pausing ~{rl._format_wait(estimated)} "- f"for Signal rate limit, batch {idx + 1}/{n_batches}.)")try:- await _rpc_send(notice, id_prefix="notice", timeout=30.0)+ await _rpc_send(f"(More images coming — pausing ~{rl._format_wait(estimated)} "+ f"for Signal rate limit, batch {idx + 1}/{n_batches}.)", id_prefix="notice", timeout=30.0)except Exception as _e:logger.warning("Signal: inline notice failed: %s", _e)outcome = await _signal_send_batch(_post, scheduler, rl, idx, n_batches, att_batch,@@ -540,7 +465,6 @@ async def _send_signal(extra, chat_id, message, media_files=None):failed_batches.append(idx + 1)elif outcome is not None:return outcome-warnings = []if len(attachment_paths) < len(valid_media):warnings.append("Some media files were skipped (not found on disk)")@@ -549,16 +473,16 @@ async def _send_signal(extra, chat_id, message, media_files=None):f"(#{', #'.join(str(b) for b in failed_batches)})")if failed_batches and len(failed_batches) == n_batches:return _error(f"Signal: every batch ({n_batches}) hit rate limit; no attachments delivered")- return _success("signal", _display_chat_id("signal", chat_id), warnings)+ # Result-safe chat identifier for tool transcripts/log consumers.+ return _success("signal", "group:***" if str(chat_id).startswith("group:") else chat_id, warnings)except Exception as e:return _error(f"Signal send failed: {e}")async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None, thread_id=None):- """Matrix adapter send (native media preserved). Prefer the live gateway adapter's- persistent olm/megolm session: ephemeral per-send connects re-init E2EE and claim- one-time keys, which under bursts exhausts recipient OTKs and silently drops- messages — so the ephemeral connect/disconnect path is only for standalone/cron."""+ """Matrix adapter send (native media preserved). Prefer the live gateway adapter's persistent+ olm/megolm session: ephemeral per-send connects re-init E2EE and claim one-time keys, which+ under bursts exhausts recipient OTKs and silently drops messages — ephemeral is cron-only."""media_files = media_files or []metadata = {"thread_id": thread_id} if thread_id else Nonefrom gateway.config import Platform@@ -566,16 +490,12 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,"Matrix: live gateway adapter lookup failed; falling back to an ""ephemeral connect (may re-init E2EE per send)"))if live_adapter is not None:- # Owned by the gateway — must NOT be disconnected; return before the- # ephemeral adapter (and its ``finally`` disconnect) exists.+ # Owned by the gateway — must NOT be disconnected (return before the ephemeral ``finally``).return await _matrix_send_core(live_adapter, chat_id, message, media_files, metadata)-- # --- Fallback: ephemeral adapter (standalone / cron context) ---try:from plugins.platforms.matrix.adapter import MatrixAdapterexcept ImportError:return {"error": "Matrix dependencies not installed. Run: pip install 'mautrix[encryption]'"}-adapter = MatrixAdapter(pconfig)try:if not await adapter.connect():@@ -584,10 +504,8 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,except Exception as e:return _error(f"Matrix send failed: {e}")finally:- try:+ with contextlib.suppress(Exception):await adapter.disconnect()- except Exception:- passasync def _matrix_send_core(adapter, chat_id, message, media_files, metadata):@@ -597,58 +515,58 @@ async def _matrix_send_core(adapter, chat_id, message, media_files, metadata):last_result = await adapter.send(chat_id, message, metadata=metadata)if not last_result.success:return _error(f"Matrix send failed: {last_result.error}")-for media_path, is_voice in media_files:if not os.path.exists(media_path):return _error(f"Media file not found: {media_path}")-ext = os.path.splitext(media_path)[1].lower()method, _ = _adapter_media_method(ext, (ext in _VOICE_EXTS and is_voice) or ext in _AUDIO_EXTS)last_result = await getattr(adapter, method)(chat_id, media_path, metadata=metadata)if not last_result.success:return _error(f"Matrix media send failed: {last_result.error}")-- return {"error": _NO_DELIVERABLE} if last_result is None else _success(- "matrix", chat_id, message_id=last_result.message_id)+ return {"error": _NO_DELIVERABLE} if last_result is None else _success("matrix", chat_id, message_id=last_result.message_id)-async def _send_weixin(pconfig, chat_id, message, media_files=None):- """Send via Weixin iLink using the native adapter helper."""+def _gateway_platform_module(name, *, unavailable, unmet):+ """``(gateway.platforms.<name>, None)`` once its ``check_<name>_requirements`` passes, else ``(None, error)``."""+ import importlibtry:- from gateway.platforms.weixin import check_weixin_requirements, send_weixin_direct- if not check_weixin_requirements():- return {"error": "Weixin requirements not met. Need aiohttp + cryptography."}+ module = importlib.import_module(f"gateway.platforms.{name}")except ImportError:- return {"error": "Weixin adapter not available."}+ return None, {"error": unavailable}+ return (module, None) if getattr(module, f"check_{name}_requirements")() else (None, {"error": unmet})++async def _send_weixin(pconfig, chat_id, message, media_files=None):+ """Send via Weixin iLink using the native adapter helper."""+ wx, err = _gateway_platform_module("weixin", unavailable="Weixin adapter not available.",+ unmet="Weixin requirements not met. Need aiohttp + cryptography.")+ if err:+ return errtry:- return await send_weixin_direct(extra=pconfig.extra, token=pconfig.token, chat_id=chat_id,- message=message, media_files=media_files)+ return await wx.send_weixin_direct(extra=pconfig.extra, token=pconfig.token, chat_id=chat_id,+ message=message, media_files=media_files)except Exception as e:return _error(f"Weixin send failed: {e}")async def _send_bluebubbles(extra, chat_id, message):"""Send via BlueBubbles iMessage server using the adapter's REST API."""- try:- from gateway.platforms.bluebubbles import BlueBubblesAdapter, check_bluebubbles_requirements- if not check_bluebubbles_requirements():- return {"error": "BlueBubbles requirements not met (need aiohttp + httpx)."}- except ImportError:- return {"error": "BlueBubbles adapter not available."}-+ bb, err = _gateway_platform_module("bluebubbles", unavailable="BlueBubbles adapter not available.",+ unmet="BlueBubbles requirements not met (need aiohttp + httpx).")+ if err:+ return errtry:from gateway.config import PlatformConfig- adapter = BlueBubblesAdapter(PlatformConfig(extra=extra))+ adapter = bb.BlueBubblesAdapter(PlatformConfig(extra=extra))if not await adapter.connect():return _error("BlueBubbles: failed to connect to server")try:result = await adapter.send(chat_id, message)- if not result.success:- return _error(f"BlueBubbles send failed: {result.error}")- return _success("bluebubbles", chat_id, message_id=result.message_id)finally:await adapter.disconnect()+ if not result.success:+ return _error(f"BlueBubbles send failed: {result.error}")+ return _success("bluebubbles", chat_id, message_id=result.message_id)except Exception as e:return _error(f"BlueBubbles send failed: {e}")@@ -667,7 +585,6 @@ async def _send_qqbot(pconfig, chat_id, message):secret = pconfig.token or extra.get("client_secret") or _getenv("QQ_CLIENT_SECRET", "")if not appid or not secret:return _error("QQBot: QQ_APP_ID / QQ_CLIENT_SECRET not configured.")-try:async with httpx.AsyncClient(timeout=15) as client:token_resp = await client.post("https://bots.qq.com/app/getAppAccessToken",@@ -681,10 +598,9 @@ async def _send_qqbot(pconfig, chat_id, message):# Separate endpoints for guild channels, C2C (private) and groups; first 2xx wins.headers = {"Authorization": f"QQBot {access_token}", "Content-Type": "application/json"}payload = {"content": message[:4000], "msg_type": 0}- endpoints = (- ("channel", f"https://api.sgroup.qq.com/channels/{chat_id}/messages"),- ("c2c", f"https://api.sgroup.qq.com/v2/users/{chat_id}/messages"),- ("group", f"https://api.sgroup.qq.com/v2/groups/{chat_id}/messages"))+ endpoints = (("channel", f"https://api.sgroup.qq.com/channels/{chat_id}/messages"),+ ("c2c", f"https://api.sgroup.qq.com/v2/users/{chat_id}/messages"),+ ("group", f"https://api.sgroup.qq.com/v2/groups/{chat_id}/messages"))statuses = []for kind, url in endpoints:resp = await client.post(url, json=payload, headers=headers)@@ -697,17 +613,14 @@ async def _send_qqbot(pconfig, chat_id, message):async def _send_yuanbao(chat_id, message, media_files=None):- """Send via the running Yuanbao adapter's persistent WebSocket (no throwaway client- possible). chat_id: ``group:<code>``, ``direct:<id>`` or ``<id>``."""+ """Send via the running Yuanbao adapter's persistent WebSocket (no throwaway client possible)."""try:from gateway.platforms.yuanbao import get_active_adapter, send_yuanbao_directexcept ImportError:return _error("Yuanbao adapter module not available.")-adapter = get_active_adapter()if adapter is None:return _error("Yuanbao adapter is not running. Start the gateway with yuanbao platform enabled first.")-try:return await send_yuanbao_direct(adapter, chat_id, message, media_files=media_files)except Exception as e:diff --git a/tools/send_message_targets.py b/tools/send_message_targets.pyindex 4a3d1188d3c..7e630b471e3 100644--- a/tools/send_message_targets.py+++ b/tools/send_message_targets.py@@ -6,10 +6,11 @@ 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 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*$")@@ -18,24 +19,17 @@ _SLACK_MENTION_RE = re.compile(r"^\s*<@(U[A-Z0-9]{8,})(?:\|[^>]+)?>\s*$")_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*$")-# 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..."): the '+' fails the-# isdigit() rule and channel-name resolution cannot resolve a raw number; keep the '+'.+# 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 chat GUID (mirrors _DM_CHAT_GUID_RE in the photon adapter).-_PHOTON_DM_GUID_RE = re.compile(r"^any;-;\+\d{6,}$")-# 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.-_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.+_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" (email reads EMAIL_HOME_ADDRESS) for error hints.+# 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)@@ -45,17 +39,19 @@ _UNRESOLVED = object() # sentinel: stop parsing, target is NOT explicit (skip g# 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):- match = regex.fullmatch(ref)- return (match.group(1), match.group(2) if thread_group else None) if match else None- return parse+ 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."""- def parse(ref):- return (ref.strip(), None) if regex.fullmatch(ref) else None- return parse+ 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 Nonedef _parse_telegram(ref):@@ -68,20 +64,14 @@ def _parse_telegram(ref):# (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))+_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):- for regex, template, has_thread in _SLACK_FORMS:- match = regex.fullmatch(ref)- if match:- return template.format(match.group(1)), (match.group(2) if has_thread else None)- return None+ 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):@@ -89,9 +79,7 @@ def _parse_matrix(ref):# "@user" go via the generic rule so the numeric check keeps precedence.trimmed = ref.strip()split_idx = trimmed.rfind(":$")- if split_idx > 0:- return trimmed[:split_idx], trimmed[split_idx + 1 :]- return None+ return (trimmed[:split_idx], trimmed[split_idx + 1:]) if split_idx > 0 else Nonedef _parse_yuanbao(ref):@@ -99,24 +87,16 @@ def _parse_yuanbao(ref):match = _YUANBAO_TARGET_RE.fullmatch(ref)if match:return match.group(1), None- if ref.strip().isdigit():- return f"group:{ref.strip()}", None- return _UNRESOLVED---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+ return (f"group:{ref.strip()}", None) if ref.strip().isdigit() else _UNRESOLVEDdef _parse_signal(ref):# "group:<id>" is a native group target; an empty id is not explicit.stripped = ref.strip()- if stripped.startswith("group:"):- group_id = stripped[len("group:"):].strip()- return (f"group:{group_id}", None) if group_id else _UNRESOLVED- return None+ 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 = {@@ -161,36 +141,28 @@ def resolve_send_target(platform_name: str, target_ref: str, *, pass_unresolved_references: bool = False) -> 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 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.- """+ Channel-directory IDs are trusted; plugin parsers are the authority on native syntax. By+ default an unresolvable target is an error the model can act on. ``pass_unresolved_references``+ (no model in the loop: cron, react/unreact on native ids) hands an unresolvable target on a+ built-in platform, or a plugin platform without a parser, to the adapter as written; a plugin+ WITH a parser stays strict. The optional validator has the final say over every returned id."""from gateway.config import Platformfrom gateway.platform_registry import platform_registryentry = platform_registry.get(platform_name)- def _validate(candidate: str) -> str | None:+ def _validated(chat_id, thread_id):+ """``(chat_id, thread_id, None)`` when the plugin validator (if any) accepts, else an error."""if entry is None or entry.validate_target_ref_fn is None:- return None+ return chat_id, thread_id, Nonetry:- verdict = entry.validate_target_ref_fn(candidate)+ verdict = entry.validate_target_ref_fn(chat_id)except Exception:logger.debug("Plugin target validator failed for %s", platform_name, exc_info=True)- return f"Target validator failed for platform '{platform_name}'"+ return None, None, f"Target validator failed for platform '{platform_name}'"if verdict is True:- return None+ return chat_id, thread_id, Nonedetail = f": {verdict}" if isinstance(verdict, str) and verdict else ""- return f"Invalid target '{target_ref}' on {platform_name}{detail}"-- def _validated(chat_id, thread_id):- error = _validate(chat_id)- return (None, None, error) if error else (chat_id, thread_id, None)-+ return None, None, f"Invalid target '{target_ref}' on {platform_name}{detail}"if entry is not None and entry.parse_target_ref_fn is not None:try:parsed = entry.parse_target_ref_fn(target_ref)@@ -202,11 +174,9 @@ def resolve_send_target(or not parsed[0] or (parsed[1] is not None and not isinstance(parsed[1], str))):return None, None, f"Target parser for platform '{platform_name}' returned an invalid result"return _validated(*parsed)-parsed_chat_id, parsed_thread_id, explicit = _parse_target_ref(platform_name, target_ref)if explicit and parsed_chat_id is not None:return _validated(parsed_chat_id, parsed_thread_id)-resolution_failed = Falsetry:from gateway.channel_directory import resolve_channel_name@@ -217,27 +187,21 @@ def resolve_send_target(if resolved:parsed_chat_id, parsed_thread_id, _ = _parse_target_ref(platform_name, resolved)return _validated(parsed_chat_id or resolved, parsed_thread_id)-is_builtin = platform_name in {member.value for member in Platform}if entry is None and not is_builtin:return None, None, f"Unknown or unregistered plugin platform: {platform_name}"-- def _pass_through_unresolved():- """Hand the raw target to the adapter unchanged (it validates)."""- error = _validate(target_ref)- if error:- return None, None, error- logger.debug("Handing unresolved target '%s' to the %s adapter unchanged "- "(the adapter validates it)", target_ref, platform_name)- return target_ref, None, None-- if entry is not None and entry.source == "plugin" and not is_builtin:- if pass_unresolved_references and entry.parse_target_ref_fn is None:- return _pass_through_unresolved()- return (None, None, f"Could not resolve '{target_ref}' on {platform_name}. "- "The plugin parser did not recognize it and no channel-directory entry matched.")- if pass_unresolved_references:- return _pass_through_unresolved()- hint = ("Try using a numeric channel ID instead." if resolution_failed- else "Use send_message(action='list') to see available targets.")+ is_plugin = entry is not None and entry.source == "plugin" and not is_builtin+ if pass_unresolved_references and (not is_plugin or entry.parse_target_ref_fn is None):+ # Hand the raw target to the adapter unchanged (it validates).+ chat_id, thread_id, error = _validated(target_ref, None)+ if not error:+ logger.debug("Handing unresolved target '%s' to the %s adapter unchanged "+ "(the adapter validates it)", target_ref, platform_name)+ return chat_id, thread_id, error+ if is_plugin:+ hint = "The plugin parser did not recognize it and no channel-directory entry matched."+ elif resolution_failed:+ hint = "Try using a numeric channel ID instead."+ else:+ hint = "Use send_message(action='list') to see available targets."return None, None, f"Could not resolve '{target_ref}' on {platform_name}. {hint}"diff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex d4e3c08ea8a..53c87729f8e 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -44,20 +44,18 @@ def send_message_tool(args, **kw):def _resolve_tool_target(target: str, *, pass_unresolved_references: bool = False):- """``(platform_name, chat_id, thread_id, error)`` for a ``platform[:ref]`` target;- ``chat_id`` is None when no ref was given (caller falls back to the home channel)."""+ """``(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, _, target_ref = target.partition(":")platform_name, target_ref = platform_name.strip().lower(), target_ref.strip() or Noneprepare_send_message_platforms()if not target_ref:return platform_name, None, None, None- chat_id, thread_id, resolution_error = resolve_send_target(- platform_name, target_ref, pass_unresolved_references=pass_unresolved_references)- return platform_name, chat_id, thread_id, resolution_error+ return platform_name, *resolve_send_target(platform_name, target_ref,+ pass_unresolved_references=pass_unresolved_references)def _handle_list():- """Return formatted list of available messaging targets."""try:from gateway.channel_directory import format_directory_for_displayreturn json.dumps({"targets": format_directory_for_display()})@@ -66,37 +64,28 @@ def _handle_list():def _handle_react(args, remove=False):- """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()+ """Attach (``remove=True``: retract) an emoji reaction via the live gateway adapter; no+ standalone fallback because reacting needs the adapter's live message-id state."""+ target, emoji = args.get("target", ""), (args.get("emoji") or "").strip()message_id = (args.get("message_id") or "").strip() or Noneif not target or (not remove and not emoji):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; the- # adapter validates them.- platform_name, chat_id, _thread_id, resolution_error = _resolve_tool_target(- target, pass_unresolved_references=True)+ # Platform-native ids (e.g. photon GUIDs) match no parser/directory entry; the adapter validates.+ platform_name, chat_id, _thread_id, resolution_error = _resolve_tool_target(target, pass_unresolved_references=True)if resolution_error:return tool_error(resolution_error)-platform, err = _platform_enum(platform_name)if err:return tool_error(err)if not chat_id:try:from gateway.config import load_gateway_config- home = load_gateway_config().get_home_channel(platform)+ chat_id = load_gateway_config().get_home_channel(platform).chat_idexcept Exception:- home = None- if not home:return tool_error(f"No chat specified and no home channel set for {platform_name}. "f"Use '{platform_name}:chat_id'.")- chat_id = home.chat_id-_, adapter = _live_adapter(platform)if adapter is None:return tool_error(f"Reactions require a live {platform_name} adapter in the running "@@ -104,45 +93,34 @@ def _handle_react(args, remove=False):react_fn = getattr(adapter, "remove_reaction" if remove else "add_reaction", None)if not callable(react_fn):return tool_error(f"Platform '{platform_name}' does not support message reactions.")-- kwargs = {"chat_id": chat_id, "message_id": message_id, **({} if remove else {"emoji": emoji})}try:from model_tools import _run_async- result = _run_async(react_fn(**kwargs))+ result = _run_async(react_fn(chat_id=chat_id, message_id=message_id, **({} if remove else {"emoji": emoji})))except Exception as e:return json.dumps(_error(f"Reaction failed: {e}"))return json.dumps(result if isinstance(result, dict) else {"success": bool(result)})def _handle_send(args):- """Send a message to a platform target."""- target = args.get("target", "")- message = args.get("message", "")+ target, message = args.get("target", ""), args.get("message", "")if not target or not message:return tool_error("Both 'target' and 'message' are required when action='send'")-platform_name, chat_id, thread_id, resolution_error = _resolve_tool_target(target)if resolution_error:return tool_error(resolution_error)-from tools.interrupt import is_interruptedif is_interrupted():return tool_error("Interrupted")-try:from gateway.config import load_gateway_configconfig = load_gateway_config()except Exception as e:return json.dumps(_error(f"Failed to load gateway config: {e}"))-platform, pconfig, entry, err = _resolve_platform_config(platform_name, config)if err:return tool_error(err)-from gateway.platforms.base import BasePlatformAdapter-- # Capture [[as_document]] before extract_media strips it: images then go through- # send_document so the original bytes survive (Telegram's sendPhoto recompresses).+ # Capture [[as_document]] before extract_media strips it (images keep original bytes via send_document).force_document_attachments = "[[as_document]]" in messagemedia_files, cleaned_message = BasePlatformAdapter.extract_media(message)media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)@@ -152,30 +130,24 @@ def _handle_send(args):chat_id, err = _home_chat_id(config, platform, platform_name)if err:return tool_error(err)-- duplicate_skip = _maybe_skip_cron_duplicate_send(platform_name, chat_id, thread_id)- if duplicate_skip:+ if duplicate_skip := _maybe_skip_cron_duplicate_send(platform_name, chat_id, thread_id):return json.dumps(duplicate_skip)-if platform_name == "slack" and chat_id:chat_id, resolve_err = _slack_dm_chat_id(pconfig, chat_id)if resolve_err:return json.dumps(resolve_err)-try:from model_tools import _run_async- send_kwargs = {"thread_id": thread_id, "media_files": media_files,- "force_document": force_document_attachments}# 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"] = args- result = _run_async(_send_to_platform(platform, pconfig, chat_id, cleaned_message, **send_kwargs))+ handler_args = {"args": args} if entry is not None and entry.send_message_handler is not None else {}+ result = _run_async(_send_to_platform(platform, pconfig, chat_id, cleaned_message, thread_id=thread_id,+ media_files=media_files, force_document=force_document_attachments,+ **handler_args))if isinstance(result, dict) and result.get("success"):if used_home_channel:result["note"] = f"Sent to {platform_name} home channel (chat_id: {chat_id})"if mirror_text and _mirror_sent_message(platform_name, chat_id, mirror_text, thread_id):result["mirrored"] = True-if isinstance(result, dict) and "error" in result:result["error"] = _sanitize_error_text(result["error"])return json.dumps(result)@@ -193,9 +165,8 @@ def _platform_enum(platform_name):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)."""+ """``(platform, pconfig, registry_entry, error)``. Plugin platforms must be registered;+ disabled/missing platforms error, except Weixin, which may be configured purely via .env."""from gateway.config import Platformfrom gateway.platform_registry import platform_registryentry = platform_registry.get(platform_name)@@ -204,7 +175,6 @@ def _resolve_platform_config(platform_name, config):platform, err = _platform_enum(platform_name)if err:return None, None, None, err-pconfig = config.platforms.get(platform)if not pconfig or not pconfig.enabled:pconfig = _weixin_env_pconfig() if platform_name == "weixin" else None@@ -215,8 +185,7 @@ def _resolve_platform_config(platform_name, config):def _home_chat_id(config, platform, platform_name):- """Return ``(home chat_id, None)`` or ``(None, actionable error)``.- Weixin additionally honours the WEIXIN_HOME_CHANNEL env var."""+ """``(home chat_id, None)`` or ``(None, actionable error)``; Weixin also honours WEIXIN_HOME_CHANNEL."""home = config.get_home_channel(platform)if home:return home.chat_id, None@@ -230,9 +199,8 @@ def _home_chat_id(config, platform, platform_name):def _slack_dm_chat_id(pconfig, chat_id):- """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)``."""+ """Open Slack user targets (``user:``/``user_name:`` from the parser, or a bare U... id from+ session metadata / home-channel config) as DM conversations. ``(chat_id, None)`` or ``(None, error_dict)``."""dm_target = f"user:{chat_id}" if chat_id.startswith("U") and _SLACK_USER_ID_RE.fullmatch(chat_id) else chat_idif not dm_target.startswith(("user:", "user_name:")):return chat_id, None@@ -261,8 +229,7 @@ def _weixin_env_pconfig():return Nonefrom gateway.config import PlatformConfigreturn PlatformConfig(enabled=True, token=wx_token, extra={- "account_id": wx_account,- "base_url": get_secret("WEIXIN_BASE_URL", "").strip(),+ "account_id": wx_account, "base_url": get_secret("WEIXIN_BASE_URL", "").strip(),"cdn_base_url": get_secret("WEIXIN_CDN_BASE_URL", "").strip()})@@ -286,14 +253,11 @@ def _maybe_skip_cron_duplicate_send(platform_name: str, chat_id: str, thread_id:from gateway.session_context import get_session_envauto_platform = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM", "").strip().lower()auto_chat_id = get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID", "").strip()- if not auto_platform or not auto_chat_id:- return None- auto_thread_id = get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID", "").strip() or None- if not (auto_platform == platform_name and auto_chat_id == str(chat_id) and auto_thread_id == thread_id):+ if not (auto_platform and auto_chat_id and auto_platform == platform_name and auto_chat_id == str(chat_id)+ and (get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID", "").strip() or None) == thread_id):return Nonetarget_label = f"{platform_name}:{chat_id}" + (f":{thread_id}" if thread_id is not None else "")- return {- "success": True, "skipped": True, "reason": "cron_auto_delivery_duplicate_target", "target": target_label,+ return {"success": True, "skipped": True, "reason": "cron_auto_delivery_duplicate_target", "target": target_label,"note": (f"Skipped send_message to {target_label}. This cron job will already auto-deliver ""its final response to that same target. Put the intended user-facing content in ""your final response instead, or use a different target if you want an additional message.")}@@ -305,28 +269,25 @@ def _bounded_send_error(detail, max_chars=900):return text if len(text) <= max_chars else f"{text[: max_chars - 3]}..."-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 kind are unsupported, not no-op'd."""- caption, separate_text = _media_caption_split(- message, media_files, max_caption_len=_DEFAULT_CAPTION_LIMIT)+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 kind are unsupported, not no-op'd."""+ caption, separate_text = _media_caption_split(message, media_files, max_caption_len=_DEFAULT_CAPTION_LIMIT)last_result = Noneif separate_text and separate_text.strip():last_result = await adapter.send(chat_id=chat_id, content=separate_text, metadata=metadata)if not last_result.success:return {"error": f"Adapter send failed: {_bounded_send_error(last_result.error)}"}-from gateway.platforms.base import BasePlatformAdaptertotal = len(media_files)for index, descriptor in enumerate(media_files):media_path = descriptor[0] if isinstance(descriptor, (list, tuple)) and descriptor else Noneif not isinstance(media_path, str) or not media_path:return {"error": f"Adapter media send failed: invalid media descriptor {index + 1}/{total}"}- is_voice = bool(descriptor[1]) if len(descriptor) > 1 else False+ is_voice = len(descriptor) > 1 and bool(descriptor[1])if not os.path.exists(media_path):return {"error": f"Adapter media send failed: media file {index + 1}/{total} was not found"}-ext = os.path.splitext(media_path)[1].lower()method_name, media_kind = _adapter_media_method(ext, is_voice or ext in _AUDIO_EXTS, force_document)adapter_method = getattr(type(adapter), method_name, None)@@ -345,22 +306,16 @@ async def _send_live_adapter_media(continuedetail = _bounded_send_error(last_result.error or "media send failed")return {"error": f"Adapter media send failed after {index}/{total} files: {detail}"}-if last_result is None:return {"error": _NO_DELIVERABLE}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."""+ """Await ``make_coro()`` on the gateway's loop: adapter.send() uses queues/tasks bound to it,+ so awaiting from another loop (the tool worker thread) deadlocks."""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:+ if gateway_loop is None or asyncio.get_running_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"}@@ -368,31 +323,29 @@ async def _dispatch_on_gateway_loop(runner, make_coro, log_message):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.+ # shield: a cancelled caller must not cancel the enqueued send (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):- """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."""+async def _send_via_adapter(platform, pconfig, chat_id, chunk, *, thread_id=None, media_files=None,+ force_document=False):+ """Live in-process gateway adapter first, else the plugin's ``standalone_sender_fn`` (cron),+ else an error naming both; media uses the adapter's native media APIs under the same rules."""platform_name = platform.value if hasattr(platform, "value") else str(platform)runner, adapter = _live_adapter(platform)if adapter is not None:try:metadata = {**({"thread_id": thread_id} if thread_id else {}),**({"publish_topic": chat_id} if platform_name == "ntfy" and chat_id else {})} or None- if media_files:- 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")+ if media_files: # always a dict result, returned as-is below+ make_coro = lambda: _send_live_adapter_media( # noqa: E731+ adapter, chat_id, chunk, media_files, thread_id=thread_id, metadata=metadata,+ force_document=force_document)+ else:+ make_coro = lambda: adapter.send(chat_id=chat_id, content=chunk, metadata=metadata) # noqa: E731result = 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")+ runner, make_coro, f"send_message: failed to schedule{' media send' if media_files else ''} on gateway loop")except asyncio.CancelledError:raiseexcept Exception as e:@@ -402,48 +355,42 @@ async def _send_via_adapter(if result.success:return {"success": True, "message_id": result.message_id}return {"error": f"Adapter send failed: {_bounded_send_error(result.error)}"}-try:from gateway.platform_registry import platform_registry- entry = platform_registry.get(platform_name)+ sender = platform_registry.get(platform_name).standalone_sender_fnexcept Exception:- entry = None- if entry is None or entry.standalone_sender_fn is None:- return {"error": (- f"No live adapter for platform '{platform_name}'. Is the gateway running with this platform "- f"connected? For out-of-process delivery (e.g. cron in a separate process), the platform "- f"plugin must register a standalone_sender_fn on its PlatformEntry.")}+ sender = None+ if sender is None:+ return {"error": (f"No live adapter for platform '{platform_name}'. Is the gateway running with this platform "+ f"connected? For out-of-process delivery (e.g. cron in a separate process), the platform "+ f"plugin must register a standalone_sender_fn on its PlatformEntry.")}try:- result = await entry.standalone_sender_fn(pconfig, chat_id, chunk, thread_id=thread_id,- media_files=media_files, force_document=force_document)+ result = await sender(pconfig, chat_id, chunk, thread_id=thread_id, media_files=media_files,+ force_document=force_document)except asyncio.CancelledError:raiseexcept Exception as e:logger.debug("Plugin standalone send for %s raised", platform_name, exc_info=True)return {"error": f"Plugin standalone send failed: {_bounded_send_error(e)}"}if isinstance(result, dict) and (result.get("success") or result.get("error")):- if result.get("error"):- return {**result, "error": _bounded_send_error(result["error"])}- return result+ return {**result, "error": _bounded_send_error(result["error"])} if result.get("error") else resultreturn {"error": (f"Plugin standalone send for '{platform_name}' returned an invalid result: "f"expected a dict with 'success' or 'error' keys, got {type(result).__name__}")}async def _send_chunks(chunks, send_one):"""``send_one(chunk, is_last)`` in order; stop at the first error dict, else last result."""- last_result = None+ result = Nonefor i, chunk in enumerate(chunks):result = await send_one(chunk, i == len(chunks) - 1)if isinstance(result, dict) and result.get("error"):- return result- last_result = result- return last_result+ break+ return resultdef _platform_max_length(platform):- """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)."""+ """Chunking limit: Signal's adapter constant (its raw JSON-RPC path bypasses the adapter's+ chunking), the registry's ``max_message_length`` for plugins, else None (no chunking)."""from gateway.config import Platformif platform == Platform.SIGNAL:try:@@ -459,24 +406,18 @@ def _platform_max_length(platform):return None-# 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 = {- "discord": ("Discord", False, True, [], False),- "feishu": ("Feishu", True, False, None, False),- "slack": ("Slack", True, True, [], False),- "whatsapp": ("WhatsApp", True, True, None, True)}---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; a single captionable file +- short text rides as the media caption."""+# 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),+ "slack": ("Slack", True, True, [], False), "whatsapp": ("WhatsApp", True, True, None, True)}+++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; one 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:@@ -492,30 +433,25 @@ async def _send_plugin_standalone(pconfig, chat_id, chunk, thread_id=thread_id, media_files=media_files if is_last else empty_media, **extra))-# Native-media chunked routes for built-in platforms; media rides on the final chunk,-# 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 / 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)+# Native-media chunked routes for built-in platforms; media rides on the final chunk, non-final+# chunks get the sentinel. platform -> (media required, sentinel, sender(platform, pconfig,+# chat_id, chunk, media, thread_id, force_document)). Matrix: ALL sends use the native adapter+# (E2EE text). Signal: attachments ride the JSON-RPC param. Yuanbao / WeCom: media needs the+# running gateway. Slack text: live adapter (multi-workspace, ignored_channels gates) else the+# plugin's standalone sender. Names resolve at call time so tests can monkeypatch ``_send_signal``._CHUNKED_ROUTES = {"matrix": (False, [], lambda p, pc, cid, chunk, media, tid, fd: _send_matrix_via_adapter(pc, cid, chunk, media_files=media, thread_id=tid)),"signal": (True, [], lambda p, pc, cid, chunk, media, tid, fd: _send_signal(pc.extra, cid, chunk, media_files=media)),- "yuanbao": (True, None, lambda p, pc, cid, chunk, media, tid, fd: _send_yuanbao(- cid, chunk, media_files=media)),+ "yuanbao": (True, None, lambda p, pc, cid, chunk, media, tid, fd: _send_yuanbao(cid, chunk, media_files=media)),"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 = {@@ -530,66 +466,56 @@ _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 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."""+ """Route to the platform sender, chunking long text with the adapters' splitter. Order matters:+ Weixin first (its native helper must not be blocked by unrelated optional imports such as+ lark-oapi), Telegram (chunks itself), plugin standalone media, native chunked, generic text."""from gateway.config import Platformplatform_name = platform.value if hasattr(platform, "value") else str(platform)media_files = media_files or []if platform == Platform.WEIXIN:return await _send_weixin(pconfig, chat_id, message, media_files=media_files)-# 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(pconfig.token, chat_id, message, media_files=media_files, thread_id=thread_id,- disable_link_previews=disable_link_previews, force_document=force_document)-+ return await _send_telegram(+ pconfig.token, chat_id, message, media_files=media_files, thread_id=thread_id, force_document=force_document,+ disable_link_previews=bool(getattr(pconfig, "extra", {}) and pconfig.extra.get("disable_link_previews")))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 (media_files and platform_name in _PLUGIN_STANDALONE_MEDIA):return await _send_plugin_standalone(platform_name, pconfig, chat_id, message, chunks, media_files,thread_id=thread_id, max_len=max_len, force_document=force_document)-route = _CHUNKED_ROUTES.get(platform_name)if route is not None and (media_files or not route[0]):_, empty_media, sender = routereturn await _send_chunks(chunks, lambda chunk, is_last: sender(platform, pconfig, chat_id, chunk, media_files if is_last else empty_media, thread_id, force_document))- # 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.+ # Generic path: text only. Buzz delivers media natively via _send_via_adapter, so no warning.warning = Noneif media_files and platform_name != "buzz":if not message.strip():- return {"error": (- f"send_message MEDIA delivery is currently only supported for {_MEDIA_PLATFORMS_NOTE}; "- 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}")-+ return {"error": (f"send_message MEDIA delivery is currently only supported for {_MEDIA_PLATFORMS_NOTE}; "+ 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) # noqa: E731else:from gateway.platform_registry import platform_registryentry = platform_registry.get(platform_name)- handler = entry.send_message_handler if entry is not None else None- if handler is not None:+ if entry is not None and entry.send_message_handler is not None:# Custom handler receives the full typed request once (not per chunk).try:import inspect- result = handler(args or {}, chat_id, platform_name, pconfig)+ result = entry.send_message_handler(args or {}, chat_id, platform_name, pconfig)return await result if inspect.isawaitable(result) else resultexcept Exception as e:return {"error": f"Plugin send_message handler failed: {e}"}# Plugin platform: live gateway adapter if available, else standalone_sender_fn.send_one = lambda chunk, is_last: _via_adapter_route( # noqa: E731platform, pconfig, chat_id, chunk, media_files if is_last else [], thread_id, force_document)-last_result = await _send_chunks(chunks, send_one)if (warning and isinstance(last_result, dict) and last_result.get("success")and not last_result.get("media_delivered")):