The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): share live-adapter lookup, prune unused re-exports, hug brackets in send_message
Tekniumb99a74a3c763
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.pyindex 4357f78856c..9bf603f8d1d 100644--- a/tools/send_message_senders.py+++ b/tools/send_message_senders.py@@ -21,9 +21,7 @@ _TELEGRAM_SEND_AUDIO_EXTS = {".mp3", ".m4a"}# Extensions that carry a native caption on the media bubble (photo/video/document).# Voice/audio notes are excluded: a caption on a voice note reads as a separate label,# so the accompanying text stays its own message.-_CAPTIONABLE_EXTS = _IMAGE_EXTS | _VIDEO_EXTS | {- ".pdf", ".doc", ".docx", ".txt", ".md", ".csv", ".xlsx", ".zip",-}+_CAPTIONABLE_EXTS = _IMAGE_EXTS | _VIDEO_EXTS | {".pdf", ".doc", ".docx", ".txt", ".md", ".csv", ".xlsx", ".zip"}# Native caption length limits (characters). Telegram's photo/video cap is 1024;# WhatsApp/Discord are far more generous, so one conservative shared ceiling.@@ -58,12 +56,9 @@ def _media_caption_split(text, media_files, *, max_caption_len):_URL_SECRET_QUERY_RE = re.compile(r"([?&](?:access_token|api[_-]?key|auth[_-]?token|token|signature|sig)=)([^&#\s]+)",- re.IGNORECASE,-)+ re.IGNORECASE)_GENERIC_SECRET_ASSIGN_RE = re.compile(- r"\b(access_token|api[_-]?key|auth[_-]?token|signature|sig)\s*=\s*([^\s,;]+)",- re.IGNORECASE,-)+ r"\b(access_token|api[_-]?key|auth[_-]?token|signature|sig)\s*=\s*([^\s,;]+)", re.IGNORECASE)def _sanitize_error_text(text) -> str:@@ -97,8 +92,7 @@ _NO_DELIVERABLE = "No deliverable text or media remained after processing MEDIA_TELEGRAM_TRANSIENT_MARKERS = ("bad gateway", "502", "too many requests", "429",- "service unavailable", "503", "gateway timeout", "504",-)+ "service unavailable", "503", "gateway timeout", "504")def _telegram_retry_delay(exc: Exception, attempt: int) -> float | None:@@ -131,8 +125,7 @@ async def _send_telegram_message_with_retry(bot, *, attempts: int = 3, **kwargs)raiselogger.warning("Transient Telegram send failure (attempt %d/%d), retrying in %.1fs: %s",- attempt + 1, attempts, delay, _sanitize_error_text(exc),- )+ attempt + 1, attempts, delay, _sanitize_error_text(exc))await asyncio.sleep(delay)@@ -156,11 +149,8 @@ def _telegram_bot(token):try:from telegram.request import HTTPXRequestlogger.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),- )+ 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)@@ -218,16 +208,14 @@ async def _telegram_send_text_chunk(bot, chat_id, chunk, parse_mode, has_html, tif _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.get("message_thread_id"))text_kwargs.pop("message_thread_id", None)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:logger.warning("Parse mode %s failed in _send_telegram, falling back to plain text: %s",- parse_mode, _sanitize_error_text(md_error),- )+ parse_mode, _sanitize_error_text(md_error))return await send(chunk if has_html else _strip_mdv2_safe(chunk), None)raise@@ -265,8 +253,7 @@ async def _telegram_send_one_media(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"],- )+ media_kwargs["message_thread_id"])f.seek(0)media_kwargs.pop("message_thread_id", None)return await _send(**media_kwargs)@@ -274,8 +261,7 @@ async def _telegram_send_one_media(if 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),- )+ _sanitize_error_text(media_err))f.seek(0)media_kwargs.pop("parse_mode", None)if not has_html and media_kwargs.get("caption"):@@ -351,31 +337,26 @@ async def _send_telegram(token, chat_id, message, media_files=None, thread_id=Notry:last_msg = await _send_telegram_message_with_retry(bot, chat_id=int_chat_id, text=_tg_caption,- parse_mode=send_parse_mode, **text_kwargs- )+ 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",- _sanitize_error_text(_cap_err),- )+ _sanitize_error_text(_cap_err))continuetry: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,- )+ thread_kwargs=thread_kwargs, force_document=force_document)except Exception as e:warning = _sanitize_error_text(f"Failed to send media {media_path}: {e}")logger.error(warning)warnings.append(warning)if last_msg is None:- if warnings:- return {"error": _NO_DELIVERABLE, "warnings": warnings}- return {"error": _NO_DELIVERABLE}+ return {"error": _NO_DELIVERABLE, **({"warnings": warnings} if warnings else {})}return _success("telegram", chat_id, warnings, message_id=str(last_msg.message_id))except ImportError:return {"error": "python-telegram-bot not installed. Run: pip install python-telegram-bot"}@@ -392,6 +373,21 @@ def _live_runner():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()+ if runner is None:+ return None, None+ try:+ return runner, runner.adapters.get(platform)+ except Exception:+ if lookup_failed_warning:+ logger.warning(lookup_failed_warning, exc_info=True)+ return runner, None++def _plugin_standalone_sender(platform_name, *, label=None, discover=True):"""Return ``(standalone_sender_fn, None)`` for a registered platform plugin,or ``(None, error_dict)``. ``discover`` runs the idempotent plugin scan first."""@@ -431,19 +427,17 @@ async def _resolve_slack_user_target(token, chat_id):return None, {"error": "aiohttp not installed. Run: pip install aiohttp"}try:from gateway.platforms.base import resolve_proxy_url, proxy_kwargs_for_aiohttp- _proxy = resolve_proxy_url()- _sess_kw, _req_kw = proxy_kwargs_for_aiohttp(_proxy)- base_url = "https://slack.com/api"+ _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"{base_url}/{method}", headers=headers, json=payload, **_req_kw) as resp:+ 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+ matches, cursor = [], Nonefor _page in range(20):payload = {"limit": 200}if cursor:@@ -479,8 +473,7 @@ async def _resolve_slack_user_target(token, chat_id):if not opened.get("ok"):return None, _error(f"Slack conversations.open error: {opened.get('error', 'unknown')}. "- "Check bot permissions (im:write)."- )+ "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")@@ -516,26 +509,22 @@ async def _signal_send_batch(post, scheduler, rl, idx, n_batches, att_batch, batlogger.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,- )+ idx + 1, n_batches, n, retry_after_label)return Falselogger.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, rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS, retry_after_label,- )+ idx + 1, n_batches, attempt, rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS, retry_after_label)except Exception as e:if attempt >= rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS:logger.error("Signal: send error on batch %d/%d after %d attempts: %s",- idx + 1, n_batches, attempt, str(e)- )+ idx + 1, n_batches, attempt, str(e))return Falselogger.warning("Signal: transient error on batch %d/%d (attempt %d/%d): %s; will retry",- idx + 1, n_batches, attempt, rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS, str(e)- )+ idx + 1, n_batches, attempt, rl.SIGNAL_RATE_LIMIT_MAX_ATTEMPTS, str(e))async def _send_signal(extra, chat_id, message, media_files=None):@@ -560,11 +549,9 @@ async def _send_signal(extra, chat_id, message, media_files=None):return {"error": "Signal account not configured"}valid_media = media_files or []- attachment_paths = []+ attachment_paths = [path for path, _is_voice in valid_media if os.path.exists(path)]for media_path, _is_voice in valid_media:- if os.path.exists(media_path):- attachment_paths.append(media_path)- else:+ if not os.path.exists(media_path):logger.warning("Signal media file not found, skipping: %s", media_path)# No attachments still means one (text-only) batch; with attachments@@ -577,43 +564,38 @@ async def _send_signal(extra, chat_id, message, media_files=None):plain_text, text_styles = markdown_to_signal(message)- def _rpc_params(text):+ async def _rpc_send(text, *, id_prefix, timeout, attachments=None, styled=False):params = {"account": account, "message": text}if chat_id.startswith("group:"):params["groupId"] = chat_id[6:]else:params["recipient"] = [chat_id]- return params-- async def _rpc_send(params, *, id_prefix, timeout):+ if styled and text and text_styles:+ if len(text_styles) == 1:+ params["textStyle"] = text_styles[0]+ else:+ params["textStyles"] = text_styles+ if attachments:+ params["attachments"] = attachmentspayload = {"jsonrpc": "2.0","method": "send","params": params,- "id": f"{id_prefix}_{int(time.time() * 1000)}",- }+ "id": f"{id_prefix}_{int(time.time() * 1000)}"}async with httpx.AsyncClient(timeout=timeout) as client:return await client.post(f"{http_url}/api/v1/rpc", json=payload)async def _post(batch_attachments, batch_message):- params = _rpc_params(batch_message)- if batch_message and text_styles:- if len(text_styles) == 1:- params["textStyle"] = text_styles[0]- else:- params["textStyles"] = text_styles- if batch_attachments:- params["attachments"] = batch_attachments- timeout = rl._signal_send_timeout(len(batch_attachments) if batch_attachments else 0)- resp = await _rpc_send(params, id_prefix="send", timeout=timeout)+ resp = await _rpc_send(+ batch_message, id_prefix="send", timeout=rl._signal_send_timeout(len(batch_attachments)),+ attachments=batch_attachments, styled=True)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,- )+ scheduler.state(), len(attachment_paths), n_batches)failed_batches: list[int] = []for idx, att_batch in enumerate(att_batches):n = len(att_batch)@@ -623,10 +605,9 @@ async def _send_signal(extra, chat_id, message, media_files=None):# 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}.)"- )+ f"for Signal rate limit, batch {idx + 1}/{n_batches}.)")try:- await _rpc_send(_rpc_params(notice), id_prefix="notice", timeout=30.0)+ await _rpc_send(notice, id_prefix="notice", timeout=30.0)except Exception as _e:logger.warning("Signal: inline notice failed: %s", _e)@@ -643,14 +624,11 @@ async def _send_signal(extra, chat_id, message, media_files=None):if failed_batches:warnings.append(f"Signal rate-limited {len(failed_batches)} batch(es) "- f"(#{', #'.join(str(b) for b in failed_batches)})"- )+ 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; "- f"no attachments delivered"- )+ f"Signal: every batch ({n_batches}) hit rate limit; no attachments delivered")return _success("signal", _display_chat_id("signal", chat_id), warnings)except Exception as e:@@ -668,22 +646,12 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,media_files = media_files or []metadata = {"thread_id": thread_id} if thread_id else None- # A runner that exists but whose adapter lookup fails is logged, not- # swallowed: a silent fall-through would recreate the reconnect storm.- live_adapter = None- runner = _live_runner()- if runner is not None:- try:- from gateway.config import Platform- live_adapter = runner.adapters.get(Platform.MATRIX)- except Exception:- logger.warning(- "Matrix: live gateway adapter lookup failed; falling back to an "- "ephemeral connect (may re-init E2EE per send)",- exc_info=True,- )- live_adapter = None-+ from gateway.config import Platform+ _, live_adapter = _live_adapter(+ Platform.MATRIX,+ lookup_failed_warning=(+ "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.@@ -697,8 +665,7 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,adapter = MatrixAdapter(pconfig)try:- connected = await adapter.connect()- if not connected:+ if not await adapter.connect():return _error("Matrix connect failed")return await _matrix_send_core(adapter, chat_id, message, media_files, metadata)except Exception as e:@@ -733,7 +700,6 @@ async def _matrix_send_core(adapter, chat_id, message, media_files, metadata):else:method = adapter.send_documentlast_result = await method(chat_id, media_path, metadata=metadata)-if not last_result.success:return _error(f"Matrix media send failed: {last_result.error}")@@ -754,8 +720,7 @@ async def _send_weixin(pconfig, chat_id, message, media_files=None):try:return await send_weixin_direct(extra=pconfig.extra, token=pconfig.token, chat_id=chat_id,- message=message, media_files=media_files,- )+ message=message, media_files=media_files)except Exception as e:return _error(f"Weixin send failed: {e}")@@ -772,8 +737,7 @@ async def _send_bluebubbles(extra, chat_id, message):try:from gateway.config import PlatformConfigadapter = BlueBubblesAdapter(PlatformConfig(extra=extra))- connected = await adapter.connect()- if not connected:+ if not await adapter.connect():return _error("BlueBubbles: failed to connect to server")try:result = await adapter.send(chat_id, message)@@ -808,8 +772,7 @@ async def _send_qqbot(pconfig, chat_id, message):async with httpx.AsyncClient(timeout=15) as client:token_resp = await client.post("https://bots.qq.com/app/getAppAccessToken",- json={"appId": str(appid), "clientSecret": str(secret)},- )+ json={"appId": str(appid), "clientSecret": str(secret)})if token_resp.status_code != 200:return _error(f"QQBot token request failed: {token_resp.status_code}")access_token = token_resp.json().get("access_token")@@ -819,15 +782,12 @@ async def _send_qqbot(pconfig, chat_id, message):# QQ Bot API has separate endpoints for guild channels, C2C (private)# and groups; try them in that order, first 2xx wins.headers = {- "Authorization": f"QQBot {access_token}",- "Content-Type": "application/json",- }+ "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"),- )+ ("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)@@ -851,8 +811,7 @@ async def _send_yuanbao(chat_id, message, media_files=None):if adapter is None:return _error("Yuanbao adapter is not running. "- "Start the gateway with yuanbao platform enabled first."- )+ "Start the gateway with yuanbao platform enabled first.")try:return await send_yuanbao_direct(adapter, chat_id, message, media_files=media_files)diff --git a/tools/send_message_targets.py b/tools/send_message_targets.pyindex 1cd5c57a2f2..73aa28afb11 100644--- a/tools/send_message_targets.py+++ b/tools/send_message_targets.py@@ -81,8 +81,7 @@ _SLACK_FORMS = ((_SLACK_TARGET_RE, "{}", False),(_SLACK_USER_ID_RE, "user:{}", False),(_SLACK_MENTION_RE, "user:{}", False),- (_SLACK_USER_NAME_RE, "user_name:{}", False),-)+ (_SLACK_USER_NAME_RE, "user_name:{}", False))def _parse_slack(ref):@@ -146,8 +145,7 @@ _PLATFORM_PARSERS = {"signal": _parse_signal,"wecom": _parse_nonempty,# Photon DM GUIDs are adapter-native ids (mirrors the react handler).- "photon": _parse_regex_stripped(_PHOTON_DM_GUID_RE),-}+ "photon": _parse_regex_stripped(_PHOTON_DM_GUID_RE)}def _parse_target_ref(platform_name: str, target_ref: str):@@ -228,12 +226,10 @@ def resolve_send_target(or len(parsed) != 2or not isinstance(parsed[0], str)or not parsed[0]- or (parsed[1] is not None and not isinstance(parsed[1], str))- ):+ 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",- )+ 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)@@ -264,8 +260,7 @@ def resolve_send_target(logger.debug("Handing unresolved target '%s' to the %s adapter unchanged ""(the adapter validates it)",- target_ref, platform_name,- )+ target_ref, platform_name)return target_ref, None, Noneif entry is not None and entry.source == "plugin" and not is_builtin:@@ -274,13 +269,11 @@ def resolve_send_target(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.",- )+ "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."- )+ else "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 988a449b452..e7345a5a643 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -16,57 +16,13 @@ logger = logging.getLogger(__name__)# Re-exported: tests and sibling modules import these via tools.send_message_tool.from tools.send_message_targets import ( # noqa: F401- _BUZZ_UUID_RE,- _E164_TARGET_RE,- _EMAIL_TARGET_RE,- _FEISHU_TARGET_RE,- _HOME_CHANNEL_ENV_OVERRIDES,- _NUMERIC_TOPIC_RE,- _PHONE_PLATFORMS,- _PHOTON_DM_GUID_RE,- _SLACK_MENTION_RE,- _SLACK_TARGET_RE,- _SLACK_THREAD_TARGET_RE,- _SLACK_USER_ID_RE,- _SLACK_USER_NAME_RE,- _TELEGRAM_TOPIC_TARGET_RE,- _WEIXIN_TARGET_RE,- _WHATSAPP_JID_RE,- _YUANBAO_TARGET_RE,- _parse_target_ref,- resolve_send_target,-)+ _HOME_CHANNEL_ENV_OVERRIDES, _SLACK_USER_ID_RE, _parse_target_ref, resolve_send_target)from tools.send_message_senders import ( # noqa: F401- _AUDIO_EXTS,- _CAPTIONABLE_EXTS,- _DEFAULT_CAPTION_LIMIT,- _GENERIC_SECRET_ASSIGN_RE,- _IMAGE_EXTS,- _TELEGRAM_CAPTION_LIMIT,- _TELEGRAM_SEND_AUDIO_EXTS,- _URL_SECRET_QUERY_RE,- _VIDEO_EXTS,- _VOICE_EXTS,- _display_chat_id,- _error,- _is_telegram_thread_not_found,- _live_runner,- _matrix_send_core,- _media_caption_split,- _plugin_standalone_sender,- _registry_standalone_send,- _resolve_slack_user_target,- _sanitize_error_text,- _send_bluebubbles,- _send_matrix_via_adapter,- _send_qqbot,- _send_signal,- _send_telegram,- _send_telegram_message_with_retry,- _send_weixin,- _send_yuanbao,- _telegram_retry_delay,-)+ _AUDIO_EXTS, _DEFAULT_CAPTION_LIMIT, _IMAGE_EXTS, _TELEGRAM_CAPTION_LIMIT, _VIDEO_EXTS,+ _VOICE_EXTS, _error, _live_adapter, _media_caption_split, _plugin_standalone_sender,+ _registry_standalone_send, _resolve_slack_user_target, _sanitize_error_text,+ _send_bluebubbles, _send_matrix_via_adapter, _send_qqbot, _send_signal, _send_telegram,+ _send_weixin, _send_yuanbao)from tools.registry import tool_error# NOTE: ``send_message`` is intentionally NOT registered as an agent-callable model@@ -110,12 +66,6 @@ def _resolve_tool_target(target: str, *, pass_unresolved_references: bool = Falsreturn platform_name, chat_id, thread_id, resolution_error-def _live_adapter(platform):- """Return the running gateway's adapter for ``platform``, or None."""- runner = _live_runner()- return runner.adapters.get(platform) if runner is not None else None--def _handle_list():"""Return formatted list of available messaging targets."""try:@@ -137,8 +87,7 @@ def _handle_react(args, remove=False):return tool_error("Both 'target' and 'emoji' are required when action='react'"if not remove- else "'target' is required when action='unreact'"- )+ else "'target' is required when action='unreact'")# Platform-native ids (e.g. photon GUIDs) match no parser/directory entry; hand# them to the adapter unchanged and let it validate.@@ -161,16 +110,14 @@ def _handle_react(args, remove=False):if not home:return tool_error(f"No chat specified and no home channel set for {platform_name}. "- f"Use '{platform_name}:chat_id'."- )+ f"Use '{platform_name}:chat_id'.")chat_id = home.chat_id- adapter = _live_adapter(platform)+ _, adapter = _live_adapter(platform)if adapter is None:return tool_error(f"Reactions require a live {platform_name} adapter in the running "- "gateway (not available from cron/standalone contexts)."- )+ "gateway (not available from cron/standalone contexts).")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.")@@ -244,8 +191,7 @@ def _handle_send(args):send_kwargs = {"thread_id": thread_id,"media_files": media_files,- "force_document": force_document_attachments,- }+ "force_document": force_document_attachments}# Only custom plugin handlers receive the complete typed request; the# built-in call contract stays exact.if entry is not None and entry.send_message_handler is not None:@@ -290,8 +236,7 @@ def _resolve_platform_config(platform_name, config):if pconfig is None:return None, None, None, (f"Platform '{platform_name}' is not configured. Set up credentials in "- "~/.hermes/config.yaml or environment variables."- )+ "~/.hermes/config.yaml or environment variables.")return platform, pconfig, entry, None@@ -310,8 +255,7 @@ def _home_chat_id(config, platform, platform_name):return None, (f"No home channel set for {platform_name} to determine where to send the message. "f"Either specify a channel directly with '{platform_name}:CHANNEL_NAME', "- f"or set a home channel via: hermes config set {home_env} <channel_id>"- )+ f"or set a home channel via: hermes config set {home_env} <channel_id>")def _slack_dm_chat_id(pconfig, chat_id):@@ -336,8 +280,7 @@ def _mirror_sent_message(platform_name, chat_id, mirror_text, thread_id):platform_name, chat_id, mirror_text,source_label=get_session_env("HERMES_SESSION_PLATFORM", "cli"),thread_id=thread_id,- user_id=get_session_env("HERMES_SESSION_USER_ID", "") or None,- ))+ user_id=get_session_env("HERMES_SESSION_USER_ID", "") or None))except Exception:return False@@ -355,9 +298,7 @@ def _weixin_env_pconfig():extra={"account_id": wx_account,"base_url": get_secret("WEIXIN_BASE_URL", "").strip(),- "cdn_base_url": get_secret("WEIXIN_CDN_BASE_URL", "").strip(),- },- )+ "cdn_base_url": get_secret("WEIXIN_CDN_BASE_URL", "").strip()})def _describe_media_for_mirror(media_files):@@ -400,8 +341,7 @@ def _maybe_skip_cron_duplicate_send(platform_name: str, chat_id: str, thread_id: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."- ),- }+ )}def _bounded_send_error(detail, max_chars=900):@@ -426,8 +366,7 @@ 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-):+ 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 kindare treated as unsupported rather than silently no-op'd."""@@ -460,9 +399,7 @@ async def _send_live_adapter_media(return {"error": (f"Live adapter does not implement native {media_kind} delivery; "- f"media file {index + 1}/{total} was not sent"- )- }+ 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)@@ -482,20 +419,13 @@ async def _send_live_adapter_media(async def _send_via_adapter(- platform, pconfig, chat_id, chunk, *, thread_id=None, media_files=None, force_document=False-):+ 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 theplugin's ``standalone_sender_fn`` (gateway not in this process, e.g. cron — the runnerweakref is None), else a descriptive error naming both options. Media descriptors gothrough the adapter's native media APIs under the same cross-loop rules as text."""platform_name = platform.value if hasattr(platform, "value") else str(platform)- runner = _live_runner()- adapter = None- if runner is not None:- try:- adapter = runner.adapters.get(platform)- except Exception:- adapter = None+ runner, adapter = _live_adapter(platform)if adapter is not None:try:metadata = {}@@ -533,14 +463,11 @@ async def _send_via_adapter(return await _dispatch(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",- )+ 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),- "send_message: failed to schedule on gateway loop",- )+ "send_message: failed to schedule on gateway loop")except asyncio.CancelledError:raiseexcept Exception as e:@@ -561,8 +488,7 @@ async def _send_via_adapter(try:result = await entry.standalone_sender_fn(pconfig, chat_id, chunk,- thread_id=thread_id, media_files=media_files, force_document=force_document,- )+ thread_id=thread_id, media_files=media_files, force_document=force_document)except asyncio.CancelledError:raiseexcept Exception as e:@@ -577,18 +503,14 @@ async def _send_via_adapter("error": (f"Plugin standalone send for '{platform_name}' returned an "f"invalid result: expected a dict with 'success' or 'error' "- f"keys, got {type(result).__name__}"- )- }+ f"keys, got {type(result).__name__}")}return {"error": (f"No live adapter for platform '{platform_name}'. Is the gateway "f"running with this platform connected? For out-of-process delivery "f"(e.g. cron in a separate process), the platform plugin must "- f"register a standalone_sender_fn on its PlatformEntry."- )- }+ f"register a standalone_sender_fn on its PlatformEntry.")}async def _send_chunks(chunks, send_one):@@ -637,8 +559,7 @@ _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),-}+ "whatsapp": ("WhatsApp", True, True, None, True)}async def _send_plugin_standalone(@@ -658,15 +579,12 @@ async def _send_plugin_standalone(if caption is not None:return await sender(pconfig, chat_id, "", thread_id=thread_id, media_files=media_files,- caption=caption, **extra,- )+ caption=caption, **extra)return await _send_chunks(chunks,lambda chunk, is_last: sender(pconfig, chat_id, chunk, thread_id=thread_id,- media_files=media_files if is_last else empty_media, **extra,- ),- )+ 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,@@ -692,8 +610,7 @@ _CHUNKED_ROUTES = {"slack": (False, [], lambda p, pc, cid, chunk, media, tid, fd: _send_via_adapter(p, pc, cid, chunk, thread_id=tid, media_files=media, force_document=fd)),"wecom": (True, None, lambda p, pc, cid, chunk, media, tid, fd: _send_via_adapter(- p, pc, cid, chunk, thread_id=tid, media_files=media, force_document=fd)),-}+ p, pc, cid, chunk, thread_id=tid, media_files=media, force_document=fd))}def _registry_text_sender(name):@@ -707,8 +624,7 @@ _TEXT_SENDERS = {"signal": lambda pc, cid, chunk, tid: _send_signal(pc.extra, cid, chunk),"bluebubbles": lambda pc, cid, chunk, tid: _send_bluebubbles(pc.extra, cid, chunk),"qqbot": lambda pc, cid, chunk, tid: _send_qqbot(pc, cid, chunk),- "yuanbao": lambda pc, cid, chunk, tid: _send_yuanbao(cid, chunk),-}+ "yuanbao": lambda pc, cid, chunk, tid: _send_yuanbao(cid, chunk)}_MEDIA_PLATFORMS_NOTE = "telegram, discord, matrix, weixin, signal, yuanbao, feishu, whatsapp and slack"@@ -737,8 +653,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,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,- )+ disable_link_previews=disable_link_previews, force_document=force_document)from gateway.platforms.base import BasePlatformAdapter@@ -748,16 +663,14 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,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,- )+ 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,- ))+ 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@@ -768,9 +681,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,return {"error": (f"send_message MEDIA delivery is currently only supported for {_MEDIA_PLATFORMS_NOTE}; "- f"target {platform_name} had only media attachments"- )- }+ 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}"@@ -798,15 +709,13 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,# Plugin platform: live gateway adapter if available, else standalone_sender_fn.send_one = lambda chunk, is_last: _send_via_adapter( # noqa: E731platform, pconfig, chat_id, chunk, thread_id=thread_id,- media_files=media_files if is_last else [], force_document=force_document,- )+ media_files=media_files if is_last else [], force_document=force_document)last_result = await _send_chunks(chunks, send_one)if (warningand isinstance(last_result, dict)and last_result.get("success")- and not last_result.get("media_delivered")- ):+ and not last_result.get("media_delivered")):last_result["warnings"] = [*last_result.get("warnings", []), warning]return last_result