Skip to content

The agent that grows with you

refactor(tools): unify adapter media-method selection across matrix and live-adapter sends

Tekniumc9d52c05b2b9
diff --git a/tools/send_message_senders.py b/tools/send_message_senders.py
index 6e4ed17ade5..d3ad91f8a90 100644
--- a/tools/send_message_senders.py
+++ b/tools/send_message_senders.py
@@ -57,8 +57,7 @@ _GENERIC_SECRET_ASSIGN_RE = re.compile(
def _sanitize_error_text(text) -> str:
"""Redact secrets from error text before surfacing it to users/models."""
- redacted = redact_sensitive_text(text)
- redacted = _URL_SECRET_QUERY_RE.sub(lambda m: f"{m.group(1)}***", redacted)
+ redacted = _URL_SECRET_QUERY_RE.sub(lambda m: f"{m.group(1)}***", redact_sensitive_text(text))
return _GENERIC_SECRET_ASSIGN_RE.sub(lambda m: f"{m.group(1)}=***", redacted)
@@ -69,17 +68,13 @@ def _error(message: str) -> dict:
def _success(platform: str, chat_id, warnings=None, **fields) -> dict:
"""Standard success payload; ``warnings`` is only included when non-empty."""
- result = {"success": True, "platform": platform, "chat_id": chat_id, **fields}
- if warnings:
- result["warnings"] = warnings
- return result
+ return {"success": True, "platform": platform, "chat_id": chat_id, **fields,
+ **({"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."""
- if platform_name == "signal" and str(chat_id).startswith("group:"):
- return "group:***"
- return chat_id
+ 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"
@@ -98,13 +93,10 @@ def _telegram_retry_delay(exc: Exception, attempt: int) -> float | None:
return max(float(retry_after), 0.0)
except (TypeError, ValueError):
return 1.0
-
text = str(exc).lower()
if "timed out" in text or "timeout" in text:
return None
- if any(marker in text for marker in _TELEGRAM_TRANSIENT_MARKERS):
- return float(2 ** attempt)
- return None
+ return float(2 ** attempt) if any(marker in text for marker in _TELEGRAM_TRANSIENT_MARKERS) else None
async def _send_telegram_message_with_retry(bot, *, attempts: int = 3, **kwargs):
@@ -170,6 +162,18 @@ def _strip_mdv2_safe(text):
return 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)."""
+ if force_document:
+ return "send_document", "document"
+ if ext in _IMAGE_EXTS:
+ return "send_image_file", "image"
+ if ext in _VIDEO_EXTS:
+ return "send_video", "video"
+ return ("send_voice", "audio") if voice else ("send_document", "document")
+
+
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."""
@@ -584,7 +588,6 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,
messages — so the ephemeral connect/disconnect path is only for standalone/cron."""
media_files = media_files or []
metadata = {"thread_id": thread_id} if thread_id else None
-
from gateway.config import Platform
_, live_adapter = _live_adapter(
Platform.MATRIX,
@@ -619,7 +622,6 @@ async def _send_matrix_via_adapter(pconfig, chat_id, message, media_files=None,
async def _matrix_send_core(adapter, chat_id, message, media_files, metadata):
"""Core send logic shared by live and ephemeral Matrix adapters."""
last_result = None
-
if message.strip():
last_result = await adapter.send(chat_id, message, metadata=metadata)
if not last_result.success:
@@ -630,21 +632,13 @@ async def _matrix_send_core(adapter, chat_id, message, media_files, metadata):
return _error(f"Media file not found: {media_path}")
ext = os.path.splitext(media_path)[1].lower()
- if ext in _IMAGE_EXTS:
- method = adapter.send_image_file
- elif ext in _VIDEO_EXTS:
- method = adapter.send_video
- elif (ext in _VOICE_EXTS and is_voice) or ext in _AUDIO_EXTS:
- method = adapter.send_voice
- else:
- method = adapter.send_document
- last_result = await method(chat_id, media_path, metadata=metadata)
+ 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}")
- if last_result is None:
- return {"error": _NO_DELIVERABLE}
- return _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):
diff --git a/tools/send_message_tool.py b/tools/send_message_tool.py
index c65c2102942..832b28254b4 100644
--- a/tools/send_message_tool.py
+++ b/tools/send_message_tool.py
@@ -15,7 +15,7 @@ from tools.send_message_targets import ( # noqa: F401
_HOME_CHANNEL_ENV_OVERRIDES, _SLACK_USER_ID_RE, _parse_target_ref, resolve_send_target)
from tools.send_message_senders import ( # noqa: F401
_AUDIO_EXTS, _DEFAULT_CAPTION_LIMIT, _IMAGE_EXTS, _TELEGRAM_CAPTION_LIMIT, _VIDEO_EXTS,
- _VOICE_EXTS, _error, _live_adapter, _media_caption_split, _plugin_standalone_sender,
+ _VOICE_EXTS, _adapter_media_method, _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)
@@ -147,11 +147,9 @@ def _handle_send(args):
# Capture [[as_document]] before extract_media strips it: images then go through
# send_document so the original bytes survive (Telegram's sendPhoto recompresses).
force_document_attachments = "[[as_document]]" in message
-
media_files, cleaned_message = BasePlatformAdapter.extract_media(message)
media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)
mirror_text = cleaned_message.strip() or _describe_media_for_mirror(media_files)
-
used_home_channel = not chat_id
if used_home_channel:
chat_id, err = _home_chat_id(config, platform, platform_name)
@@ -316,19 +314,6 @@ def _bounded_send_error(detail, max_chars=900):
return text if len(text) <= max_chars else f"{text[: max_chars - 3]}..."
-def _live_media_method(ext, is_voice, force_document):
- """Adapter media method name and kind for one live-adapter media file."""
- if force_document:
- return "send_document", "document"
- if ext in _IMAGE_EXTS:
- return "send_image_file", "image"
- if ext in _VIDEO_EXTS:
- return "send_video", "video"
- if is_voice or ext in _AUDIO_EXTS:
- return "send_voice", "audio"
- return "send_document", "document"
-
-
async def _send_live_adapter_media(
adapter, chat_id, message, media_files, *, thread_id=None, metadata=None, force_document=False):
"""Deliver text and every media descriptor through adapter media APIs. Adapters that
@@ -352,7 +337,7 @@ async def _send_live_adapter_media(
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 = _live_media_method(ext, is_voice, force_document)
+ 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)
if adapter_method is None or adapter_method is getattr(BasePlatformAdapter, method_name):
return {"error": (f"Live adapter does not implement native {media_kind} delivery; "
@@ -406,12 +391,8 @@ async def _send_via_adapter(
runner, adapter = _live_adapter(platform)
if adapter is not None:
try:
- metadata = {}
- if thread_id:
- metadata["thread_id"] = thread_id
- if platform_name == "ntfy" and chat_id:
- metadata["publish_topic"] = chat_id
- metadata = metadata or None
+ 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,
@@ -580,7 +561,6 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
from gateway.config import Platform
platform_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)
@@ -595,7 +575,6 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,
from gateway.platforms.base import BasePlatformAdapter
max_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,