The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(buzz): verify live media delivery receipts
EmpireOperating9c2570425774
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 2a34362a9d4..cb8e672d2dd 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -663,20 +663,53 @@ async def _exec_buzz()-def _cli_error_message(stderr: str, returncode: int) -> str:- """Extract the human-readable message from the CLI's JSON error contract.+_MAX_CLI_MESSAGE_CHARS = 900- stderr is ``{"error": "<category>", "message": "<detail>"}`` on failure;- fall back to the raw (stripped) stderr when it isn't JSON.- """++def _bounded_cli_message(message: str) -> str:+ """Keep untrusted CLI detail useful without exposing unbounded output."""+ if len(message) <= _MAX_CLI_MESSAGE_CHARS:+ return message+ return f"{message[: _MAX_CLI_MESSAGE_CHARS - 3]}..."+++def _cli_error_message(stderr: str, returncode: int) -> str:+ """Extract a bounded human-readable message from the CLI error contract."""text = (stderr or "").strip()try:data = json.loads(text)- if isinstance(data, dict) and data.get("message"):- return f"{data.get('error', 'error')}: {data['message']} (exit {returncode})"+ if isinstance(data, dict):+ detail = data.get("message")+ category = data.get("error")+ if isinstance(detail, str) and detail.strip():+ label = category.strip() if isinstance(category, str) and category.strip() else "error"+ return _bounded_cli_message(+ f"{label}: {detail.strip()} (exit {returncode})"+ )except ValueError:pass- return text or f"buzz CLI failed with exit code {returncode}"+ return _bounded_cli_message(text or f"buzz CLI failed with exit code {returncode}")+++def _parse_send_receipt(stdout: str) -> Tuple[Optional[str], Optional[str]]:+ """Validate the buzz-cli success receipt and return ``(event_id, error)``."""+ try:+ data = json.loads(stdout or "{}")+ except ValueError:+ return None, "invalid CLI response"+ if not isinstance(data, dict):+ return None, "invalid CLI response"+ if data.get("accepted") is False:+ detail = data.get("message")+ if not isinstance(detail, str) or not detail.strip():+ detail = "message was not accepted"+ return None, _bounded_cli_message(detail.strip())+ if data.get("accepted") is not True:+ return None, "invalid CLI response"+ event_id = data.get("event_id")+ if not isinstance(event_id, str) or not event_id.strip():+ return None, "invalid CLI response"+ return event_id.strip(), Nonedef _parse_json_list(stdout: str) -> List[dict]:@@ -1322,25 +1355,19 @@ class BuzzAdapter(BasePlatformAdapter):error=_cli_error_message(err, code),retryable=code == 2,)- try:- data = json.loads(out or "{}")- except ValueError:- data = {}- event_id = data.get("event_id")- if event_id:- # Belt-and-braces echo suppression: the poll loop already skips- # our own pubkey, but marking the id seen makes de-dupe explicit.- # Also record event_meta so a thread reply to this send matches- # even if the WS/poll echo never arrives (#75826).- self._mark_seen(str(chat_id), str(event_id))- self._remember_event_meta(- str(chat_id), str(event_id), self._self_pubkey, content- )- return SendResult(- success=bool(data.get("accepted", True)),- message_id=str(event_id) if event_id else None,- raw_response=data,+ event_id, receipt_error = _parse_send_receipt(out)+ if receipt_error:+ return SendResult(success=False, error=receipt_error)+ assert event_id is not None+ # Belt-and-braces echo suppression: the poll loop already skips our own+ # pubkey, but marking the verified id seen makes de-dupe explicit.+ # Also record event_meta so a thread reply to this send matches even+ # if the WS/poll echo never arrives (#75826).+ self._mark_seen(str(chat_id), event_id)+ self._remember_event_meta(+ str(chat_id), event_id, self._self_pubkey, content)+ return SendResult(success=True, message_id=event_id)async def send_typing(self, chat_id: str, metadata=None) -> None:"""Buzz has no typing indicator API — no-op."""@@ -1447,6 +1474,43 @@ class BuzzAdapter(BasePlatformAdapter):self._mark_seen(str(chat_id), str(event_id))return bool(data.get("accepted", True))+ async def _send_local_file(+ self,+ chat_id: str,+ file_path: str,+ caption: Optional[str] = None,+ reply_to: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None,+ ) -> SendResult:+ """Upload one local file through the Buzz CLI and verify its receipt."""+ local = Path(file_path).expanduser()+ if not local.is_file():+ return SendResult(success=False, error="Media file not found")+ args = [+ "messages", "send",+ "--channel", str(chat_id),+ "--file", str(local),+ "--content", "-",+ ]+ reply_target = self._resolve_reply_anchor(+ (metadata or {}).get("thread_id") or reply_to+ )+ if reply_target and self._reply_to_mode != "off":+ args += ["--reply-to", str(reply_target)]+ code, out, err = await self._run_cli(args, input_text=caption or "")+ if code != 0:+ return SendResult(+ success=False,+ error=_cli_error_message(err, code),+ retryable=code == 2,+ )+ event_id, receipt_error = _parse_send_receipt(out)+ if receipt_error:+ return SendResult(success=False, error=receipt_error)+ assert event_id is not None+ self._mark_seen(str(chat_id), event_id)+ return SendResult(success=True, message_id=event_id)+async def send_image(self,chat_id: str,@@ -1488,7 +1552,8 @@ class BuzzAdapter(BasePlatformAdapter):"""local = Path(file_path).expanduser()if probe and not local.is_file():- return SendResult(success=False, error=f"File not found: {local}")+ # Never leak host filesystem paths into chat-visible errors.+ return SendResult(success=False, error="Media file not found")args = ["messages", "send","--channel", str(chat_id),@@ -1507,18 +1572,12 @@ class BuzzAdapter(BasePlatformAdapter):error=_cli_error_message(err, code),retryable=code == 2,)- try:- data = json.loads(out or "{}")- except ValueError:- data = {}- event_id = data.get("event_id")- if event_id:- self._mark_seen(str(chat_id), str(event_id))- return SendResult(- success=bool(data.get("accepted", True)),- message_id=str(event_id) if event_id else None,- raw_response=data,- )+ event_id, receipt_error = _parse_send_receipt(out)+ if receipt_error:+ return SendResult(success=False, error=receipt_error)+ assert event_id is not None+ self._mark_seen(str(chat_id), event_id)+ return SendResult(success=True, message_id=event_id)async def send_image_file(self,@@ -3204,14 +3263,14 @@ async def _standalone_send(except asyncio.CancelledError:raiseexcept OSError as e:- return {"error": f"Buzz standalone send failed to launch CLI: {e}"}+ detail = _bounded_cli_message(str(e))+ return {"error": f"Buzz standalone send failed to launch CLI: {detail}"}if code != 0:return {"error": f"Buzz standalone send failed: {_cli_error_message(err, code)}"}- try:- data = json.loads(out or "{}")- except ValueError:- data = {}- result = {"success": True, "message_id": str(data.get("event_id") or "")}+ event_id, receipt_error = _parse_send_receipt(out)+ if receipt_error:+ return {"error": f"Buzz standalone send failed: {receipt_error}"}+ result = {"success": True, "message_id": event_id}if media_files:result["media_delivered"] = Truereturn resultdiff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.pyindex dc4abe60cf8..a654caa49b2 100644--- a/tests/gateway/test_buzz_adapter.py+++ b/tests/gateway/test_buzz_adapter.py@@ -5,6 +5,7 @@ import base64import hashlibimport jsonfrom pathlib import Path+from types import SimpleNamespaceimport pytestfrom unittest.mock import AsyncMock, MagicMock@@ -610,6 +611,18 @@ class TestCliErrorContract:msg = _cli_error_message('{"error":"relay_error","message":"boom","retryable":false}', 2)assert "relay_error" in msg and "boom" in msg and "exit 2" in msg+ @pytest.mark.parametrize(+ "stderr",+ [+ "x" * 100_000,+ json.dumps({"error": "relay_error", "message": "x" * 100_000}),+ ],+ )+ def test_bounds_untrusted_cli_error_output(self, stderr):+ msg = _cli_error_message(stderr, 2)+ assert len(msg) <= 900+ assert msg.endswith("...")+# ── Seeding / high-water mark / de-dupe ───────────────────────────────────@@ -2211,7 +2224,66 @@ class TestBuzzAdapterSend:args, _stdin = cli.calls[0]assert args[args.index("--reply-to") + 1] == "stable-root"+ @pytest.mark.parametrize(+ ("stdout", "error_fragment"),+ [+ ("not json", "invalid CLI response"),+ (json.dumps([]), "invalid CLI response"),+ (json.dumps({"event_id": "evt"}), "invalid CLI response"),+ (json.dumps({"accepted": True}), "invalid CLI response"),+ (json.dumps({"accepted": True, "event_id": " "}), "invalid CLI response"),+ ],+ )+ async def test_send_rejects_invalid_zero_exit_receipt(self, stdout, error_fragment):+ adapter = _make_adapter()+ adapter._run_cli = AsyncMock(return_value=(0, stdout, ""))++ result = await adapter.send(CHANNEL, "hello")++ assert result.success is False+ assert error_fragment in result.error+ assert result.message_id is None+ assert result.raw_response is None++ @pytest.mark.asyncio+ async def test_send_rejection_is_useful_and_bounded(self):+ adapter = _make_adapter()+ adapter._run_cli = AsyncMock(+ return_value=(+ 0,+ json.dumps({"accepted": False, "message": "upload rejected " + "x" * 100_000}),+ "",+ )+ )++ result = await adapter.send(CHANNEL, "hello")++ assert result.success is False+ assert "upload rejected" in result.error+ assert len(result.error) <= 1024+ assert result.raw_response is None++ @pytest.mark.asyncio+ async def test_send_success_exposes_only_verified_receipt(self):+ adapter = _make_adapter()+ adapter._run_cli = AsyncMock(+ return_value=(+ 0,+ json.dumps({+ "accepted": True,+ "event_id": " evt-safe ",+ "message": "x" * 100_000,+ "raw_response": "y" * 100_000,+ }),+ "",+ )+ )++ result = await adapter.send(CHANNEL, "hello")+ assert result.success is True+ assert result.message_id == "evt-safe"+ assert result.raw_response is None@pytest.mark.asyncioasync def test_send_image_local_file_uses_file_flag(self, tmp_path):@@ -2935,6 +3007,101 @@ class TestInboundMediaAuthorizationGate:+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("method_name", "suffix"),+ [+ ("send_image_file", ".png"),+ ("send_video", ".mp4"),+ ("send_voice", ".ogg"),+ ("send_document", ".pdf"),+ ],+ )+ async def test_live_media_capabilities_upload_local_file_with_caption_and_reply(+ self, tmp_path, method_name, suffix+ ):+ media = tmp_path / f"attachment{suffix}"+ media.write_bytes(b"media")+ adapter = _make_adapter()+ cli = _ScriptedCli()+ cli.script("messages", "send", {"accepted": True, "event_id": "evt-media"})+ adapter._run_cli = cli++ result = await getattr(adapter, method_name)(+ CHANNEL,+ str(media),+ caption="caption",+ reply_to="root-event",+ metadata={"thread_id": "ignored-thread"},+ )++ assert result.success is True+ assert result.message_id == "evt-media"+ args, stdin_text = cli.calls[0]+ assert args[args.index("--file") + 1] == str(media)+ assert args[args.index("--reply-to") + 1] == "root-event"+ assert stdin_text == "caption"++ @pytest.mark.asyncio+ async def test_live_media_rejects_zero_exit_without_verified_event_id(self, tmp_path):+ media = tmp_path / "attachment.pdf"+ media.write_bytes(b"media")+ adapter = _make_adapter()+ adapter._run_cli = AsyncMock(+ return_value=(0, json.dumps({"accepted": True}), "")+ )++ result = await adapter.send_document(CHANNEL, str(media))++ assert result.success is False+ assert result.error == "invalid CLI response"+ assert result.raw_response is None++ @pytest.mark.asyncio+ async def test_send_to_platform_live_buzz_delivers_all_media(self, monkeypatch, tmp_path):+ from gateway.config import Platform+ from tools.send_message_tool import _send_to_platform++ first = tmp_path / "first.txt"+ second = tmp_path / "second.pdf"+ first.write_text("first", encoding="utf-8")+ second.write_text("second", encoding="utf-8")+ adapter = _make_adapter()+ cli = _ScriptedCli()+ cli.script("messages", "send", {"accepted": True, "event_id": "evt-text"})+ cli.script("messages", "send", {"accepted": True, "event_id": "evt-first"})+ cli.script("messages", "send", {"accepted": True, "event_id": "evt-second"})+ adapter._run_cli = cli+ platform = Platform("buzz")+ runner = SimpleNamespace(adapters={platform: adapter})+ monkeypatch.setattr("gateway.run._gateway_runner_ref", lambda: runner)++ result = await _send_to_platform(+ platform,+ SimpleNamespace(enabled=True, token=None, extra={}),+ CHANNEL,+ "attached files",+ thread_id="root-event",+ media_files=[(str(first), False), (str(second), False)],+ )++ assert result == {+ "success": True,+ "message_id": "evt-second",+ "media_delivered": True,+ }+ assert len(cli.calls) == 3+ assert cli.calls[0][1] == "attached files"+ assert [call[0][call[0].index("--file") + 1] for call in cli.calls[1:]] == [+ str(first),+ str(second),+ ]+ assert all(+ call[0][call[0].index("--reply-to") + 1] == "root-event"+ for call in cli.calls+ )++# ── Lifecycle ─────────────────────────────────────────────────────────────@@ -3419,6 +3586,73 @@ class TestBuzzAdapterEdit:assert await adapter.delete_message(CHANNEL, "") is Falseassert cli.calls == []+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "stdout",+ [+ "not json",+ json.dumps([]),+ json.dumps({"event_id": "evt"}),+ json.dumps({"accepted": True}),+ json.dumps({"accepted": True, "event_id": ""}),+ ],+ )+ async def test_standalone_send_rejects_invalid_zero_exit_receipt(+ self, monkeypatch, tmp_path, stdout+ ):+ from gateway.config import PlatformConfig++ fake_cli = tmp_path / "buzz"+ fake_cli.write_text("#!/bin/sh\n", encoding="utf-8")+ monkeypatch.setenv("BUZZ_RELAY_URL", "https://r")+ monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec1x")+ monkeypatch.setenv("BUZZ_CLI_PATH", str(fake_cli))+ monkeypatch.setattr(+ _buzz_mod,+ "_exec_buzz",+ AsyncMock(return_value=(0, stdout, "")),+ )++ result = await _standalone_send(+ PlatformConfig(enabled=True, extra={}), CHANNEL, "hello"+ )++ assert result == {"error": "Buzz standalone send failed: invalid CLI response"}++ @pytest.mark.asyncio+ async def test_standalone_send_rejection_is_useful_bounded_and_not_delivered(+ self, monkeypatch, tmp_path+ ):+ from gateway.config import PlatformConfig++ fake_cli = tmp_path / "buzz"+ fake_cli.write_text("#!/bin/sh\n", encoding="utf-8")+ monkeypatch.setenv("BUZZ_RELAY_URL", "https://r")+ monkeypatch.setenv("BUZZ_PRIVATE_KEY", "nsec1x")+ monkeypatch.setenv("BUZZ_CLI_PATH", str(fake_cli))+ monkeypatch.setattr(+ _buzz_mod,+ "_exec_buzz",+ AsyncMock(+ return_value=(+ 0,+ json.dumps({"accepted": False, "message": "upload rejected " + "x" * 100_000}),+ "",+ )+ ),+ )++ result = await _standalone_send(+ PlatformConfig(enabled=True, extra={}),+ CHANNEL,+ "hello",+ media_files=[("/tmp/report.txt", False)],+ )++ assert "upload rejected" in result["error"]+ assert len(result["error"]) <= 1024+ assert "success" not in result+ assert "media_delivered" not in result# ── Durable channel cursors across restart (#90464) ───────────────────────@@ -3569,4 +3803,3 @@ class TestChannelCursorPersistence:await adapter._poll_channel(CHANNEL)assert path.stat().st_mtime_ns == before-diff --git a/tests/tools/test_send_message_target_parse.py b/tests/tools/test_send_message_target_parse.pyindex ed8e64defe9..36f75f12916 100644--- a/tests/tools/test_send_message_target_parse.py+++ b/tests/tools/test_send_message_target_parse.py@@ -23,29 +23,174 @@ def test_buzz_uuid_target_is_explicit() -> None:assert _parse_target_ref("buzz", channel_id) == (channel_id, None, True)-def test_plugin_media_receipt_suppresses_omitted_warning() -> None:- media_result = {+def test_live_buzz_media_delivers_every_file_with_reply_metadata(tmp_path) -> None:+ from gateway.platforms.base import SendResult++ platform = Platform("buzz")+ first = tmp_path / "first.txt"+ second = tmp_path / "second.pdf"+ first.write_text("first", encoding="utf-8")+ second.write_text("second", encoding="utf-8")+ calls = []++ class Adapter:+ async def send(self, *, chat_id, content, metadata=None):+ calls.append(("text", content, metadata))+ return SendResult(success=True, message_id="evt-text")++ async def send_document(self, chat_id, file_path, **kwargs):+ calls.append(("document", file_path, kwargs))+ return SendResult(success=True, message_id=f"evt-{len(calls)}")++ runner = SimpleNamespace(adapters={platform: Adapter()})+ with patch("gateway.run._gateway_runner_ref", return_value=runner):+ result = asyncio.run(+ _send_to_platform(+ platform,+ SimpleNamespace(enabled=True, token=None, extra={}),+ "31b543d5-80d4-4df5-8a5c-cefca1a58fdd",+ "attached files",+ thread_id="reply-root",+ media_files=[(str(first), False), (str(second), False)],+ )+ )++ assert result["success"] is True+ assert result["media_delivered"] is True+ assert calls == [+ ("text", "attached files", {"thread_id": "reply-root"}),+ ("document", str(first), {"caption": None, "reply_to": "reply-root", "metadata": {"thread_id": "reply-root"}}),+ ("document", str(second), {"caption": None, "reply_to": "reply-root", "metadata": {"thread_id": "reply-root"}}),+ ]+++def test_live_buzz_single_image_uses_caption_without_duplicate_text(tmp_path) -> None:+ from gateway.platforms.base import SendResult++ platform = Platform("buzz")+ image = tmp_path / "shot.png"+ image.write_bytes(b"png")+ calls = []++ class Adapter:+ async def send(self, **kwargs):+ calls.append(("text", kwargs))+ return SendResult(success=True, message_id="unexpected")++ async def send_image_file(self, chat_id, image_path, **kwargs):+ calls.append(("image", image_path, kwargs))+ return SendResult(success=True, message_id="evt-image")++ runner = SimpleNamespace(adapters={platform: Adapter()})+ with patch("gateway.run._gateway_runner_ref", return_value=runner):+ result = asyncio.run(+ _send_to_platform(+ platform,+ SimpleNamespace(enabled=True, token=None, extra={}),+ "31b543d5-80d4-4df5-8a5c-cefca1a58fdd",+ "screenshot caption",+ thread_id="reply-root",+ media_files=[(str(image), False)],+ )+ )++ assert result == {"success": True,- "message_id": "evt-media",+ "message_id": "evt-image","media_delivered": True,}+ assert calls == [+ ("image", str(image), {"caption": "screenshot caption", "reply_to": "reply-root", "metadata": {"thread_id": "reply-root"}})+ ]+++def test_live_buzz_media_failure_is_explicit_not_omitted(tmp_path) -> None:+ from gateway.platforms.base import SendResult++ platform = Platform("buzz")+ first = tmp_path / "first.txt"+ second = tmp_path / "second.txt"+ first.write_text("first", encoding="utf-8")+ second.write_text("second", encoding="utf-8")+ media_calls = []++ class Adapter:+ async def send(self, **kwargs):+ return SendResult(success=True, message_id="evt-text")- with patch(- "tools.send_message_tool._send_via_adapter",- new=AsyncMock(return_value=media_result),- ):+ async def send_document(self, chat_id, file_path, **kwargs):+ media_calls.append(file_path)+ if file_path == str(second):+ return SendResult(success=False, error="relay rejected upload")+ return SendResult(success=True, message_id="evt-first")++ runner = SimpleNamespace(adapters={platform: Adapter()})+ with patch("gateway.run._gateway_runner_ref", return_value=runner):result = asyncio.run(_send_to_platform(- Platform("buzz"),+ platform,+ SimpleNamespace(enabled=True, token=None, extra={}),+ "31b543d5-80d4-4df5-8a5c-cefca1a58fdd",+ "attached files",+ media_files=[(str(first), False), (str(second), False)],+ )+ )++ assert media_calls == [str(first), str(second)]+ assert "relay rejected upload" in result["error"]+ assert "media_delivered" not in result+++def test_live_adapter_inherited_media_fallback_is_not_claimed_as_delivery(tmp_path) -> None:+ from gateway.platforms.base import BasePlatformAdapter, SendResult++ platform = Platform("buzz")+ document = tmp_path / "report.txt"+ document.write_text("report", encoding="utf-8")++ class Adapter:+ name = "Fallback-only"+ send_document = BasePlatformAdapter.send_document++ async def send(self, **kwargs):+ return SendResult(success=True, message_id="warning-text-only")++ runner = SimpleNamespace(adapters={platform: Adapter()})+ with patch("gateway.run._gateway_runner_ref", return_value=runner):+ result = asyncio.run(+ _send_to_platform(+ platform,SimpleNamespace(enabled=True, token=None, extra={}),"31b543d5-80d4-4df5-8a5c-cefca1a58fdd","attached",- media_files=[("/tmp/report.txt", False)],+ media_files=[(str(document), False)],+ )+ )++ assert "does not implement native document delivery" in result["error"]+ assert "media_delivered" not in result+++def test_live_buzz_adapter_exception_is_bounded() -> None:+ platform = Platform("buzz")++ class Adapter:+ async def send(self, **kwargs):+ raise RuntimeError("x" * 100_000)++ runner = SimpleNamespace(adapters={platform: Adapter()})+ with patch("gateway.run._gateway_runner_ref", return_value=runner):+ result = asyncio.run(+ _send_to_platform(+ platform,+ SimpleNamespace(enabled=True, token=None, extra={}),+ "31b543d5-80d4-4df5-8a5c-cefca1a58fdd",+ "hello",))- assert result == media_result- assert "warnings" not in result+ assert result["error"].startswith("Plugin platform send failed: ")+ assert len(result["error"]) <= 1024def test_send_message_routes_buzz_uuid_without_home_fallback() -> None:diff --git a/tools/send_message_tool.py b/tools/send_message_tool.pyindex 3eb072b7bdd..dfc9c40be6c 100644--- a/tools/send_message_tool.py+++ b/tools/send_message_tool.py@@ -843,6 +843,96 @@ def _maybe_skip_cron_duplicate_send(platform_name: str, chat_id: str, thread_id:}+def _bounded_send_error(detail, max_chars=900):+ """Bound untrusted adapter/plugin error detail returned by send_message."""+ text = str(detail or "send failed")+ if len(text) <= max_chars:+ return text+ return 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."""+ caption, separate_text = _media_caption_split(+ message, media_files, max_caption_len=_DEFAULT_CAPTION_LIMIT+ )+ last_result = None+ if 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)}"}++ total = len(media_files)+ for index, descriptor in enumerate(media_files):+ if not isinstance(descriptor, (list, tuple)) or not descriptor:+ return {"error": f"Adapter media send failed: invalid media descriptor {index + 1}/{total}"}+ media_path = descriptor[0]+ is_voice = bool(descriptor[1]) if len(descriptor) > 1 else False+ if not isinstance(media_path, str) or not media_path:+ return {"error": f"Adapter media send failed: invalid media descriptor {index + 1}/{total}"}+ 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()+ kwargs = {+ "caption": caption if index == 0 else None,+ "reply_to": thread_id,+ "metadata": metadata,+ }+ if force_document:+ method_name = "send_document"+ media_kind = "document"+ elif ext in _IMAGE_EXTS:+ method_name = "send_image_file"+ media_kind = "image"+ elif ext in _VIDEO_EXTS:+ method_name = "send_video"+ media_kind = "video"+ elif is_voice or ext in _AUDIO_EXTS:+ method_name = "send_voice"+ media_kind = "audio"+ else:+ method_name = "send_document"+ media_kind = "document"++ from gateway.platforms.base import BasePlatformAdapter++ adapter_method = getattr(type(adapter), method_name, None)+ base_fallback = getattr(BasePlatformAdapter, method_name)+ if adapter_method is None or adapter_method is base_fallback:+ return {+ "error": (+ f"Live adapter does not implement native {media_kind} delivery; "+ f"media file {index + 1}/{total} was not sent"+ )+ }+ last_result = await getattr(adapter, method_name)(chat_id, media_path, **kwargs)+ if not last_result.success:+ detail = _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 text or media remained after processing MEDIA tags"}+ return {+ "success": True,+ "message_id": last_result.message_id,+ "media_delivered": True,+ }++async def _send_via_adapter(platform,pconfig,@@ -886,7 +976,6 @@ async def _send_via_adapter(metadata["publish_topic"] = chat_idif not metadata:metadata = None-# The adapter's send() uses asyncio.Queue + worker tasks bound# to the gateway's main event loop. Calling send() from a# different thread/loop (the agent's tool worker thread) causes@@ -905,6 +994,35 @@ async def _send_via_adapter(and _current_loop is not gateway_loop)+ # Media descriptors route through the adapter's native media+ # APIs (same cross-loop rules apply — the media helper awaits+ # adapter methods bound to the gateway loop).+ if media_files:+ def _media_coro():+ return _send_live_adapter_media(+ adapter,+ chat_id,+ chunk,+ media_files,+ thread_id=thread_id,+ metadata=metadata,+ force_document=force_document,+ )+ if _need_cross_loop:+ if not gateway_loop.is_running():+ return {"error": "Gateway loop is not running; cannot dispatch adapter send"}+ from agent.async_utils import safe_schedule_threadsafe+ media_fut = safe_schedule_threadsafe(+ _media_coro(),+ gateway_loop,+ logger=logger,+ log_message="send_message: failed to schedule media send on gateway loop",+ )+ if media_fut is None:+ return {"error": "Gateway loop unavailable for send dispatch"}+ return await asyncio.shield(asyncio.wrap_future(media_fut))+ return await _media_coro()+if _need_cross_loop:if not gateway_loop.is_running():return {"error": "Gateway loop is not running; cannot dispatch adapter send"}@@ -931,10 +1049,10 @@ async def _send_via_adapter(except asyncio.CancelledError:raiseexcept Exception as e:- return {"error": f"Plugin platform send failed: {e}"}+ return {"error": f"Plugin platform send failed: {_bounded_send_error(e)}"}if result.success:return {"success": True, "message_id": result.message_id}- return {"error": f"Adapter send failed: {result.error}"}+ return {"error": f"Adapter send failed: {_bounded_send_error(result.error)}"}entry = Nonetry:@@ -957,9 +1075,11 @@ async def _send_via_adapter(raiseexcept Exception as e:logger.debug("Plugin standalone send for %s raised", platform_name, exc_info=True)- return {"error": f"Plugin standalone send failed: {e}"}+ 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 resultreturn {"error": (@@ -1351,7 +1471,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,)last_result = None- for chunk in chunks:+ for i, chunk in enumerate(chunks):if platform == Platform.WHATSAPP:result = await _registry_standalone_send("whatsapp", pconfig, chat_id, chunk, thread_id)elif platform == Platform.SIGNAL:@@ -1395,7 +1515,7 @@ async def _send_to_platform(platform, pconfig, chat_id, message, thread_id=None,chat_id,chunk,thread_id=thread_id,- media_files=media_files,+ media_files=media_files if i == len(chunks) - 1 else [],force_document=force_document,)