The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(buzz): ingest verified native attachments
EmpireOperating00394acfae42
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 8b37cd73ca7..3ad1ea18d4f 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -2461,6 +2461,9 @@ class MessageEvent:# media_urls: local file paths (for vision tool access)media_urls: List[str] = field(default_factory=list)media_types: List[str] = field(default_factory=list)+ # Per-attachment text-inlining contract. None/absent preserves the legacy+ # assumption that text/* adapters already injected content into ``text``.+ media_text_inlined: List[Optional[bool]] = field(default_factory=list)# Reply contextreply_to_message_id: Optional[str] = None@@ -2845,10 +2848,22 @@ def merge_pending_message_event(incoming_is_photo = event.message_type == MessageType.PHOTOexisting_has_media = bool(existing.media_urls)incoming_has_media = bool(event.media_urls)+ incoming_inline_flags: List[Optional[bool]] = []+ if incoming_has_media:+ existing_inline_flags = list(getattr(existing, "media_text_inlined", []) or [])+ existing_inline_flags.extend(+ [None] * max(0, len(existing.media_urls) - len(existing_inline_flags))+ )+ incoming_inline_flags = list(getattr(event, "media_text_inlined", []) or [])+ incoming_inline_flags.extend(+ [None] * max(0, len(event.media_urls) - len(incoming_inline_flags))+ )+ existing.media_text_inlined = existing_inline_flagsif existing_is_photo and incoming_is_photo:existing.media_urls.extend(event.media_urls)existing.media_types.extend(event.media_types)+ existing.media_text_inlined.extend(incoming_inline_flags)if event.text:existing.text = BasePlatformAdapter._merge_caption(existing.text, event.text)_invalidate_pending_stt_cache(existing)@@ -2858,6 +2873,7 @@ def merge_pending_message_event(if incoming_has_media:existing.media_urls.extend(event.media_urls)existing.media_types.extend(event.media_types)+ existing.media_text_inlined.extend(incoming_inline_flags)if event.text:if existing.text:existing.text = BasePlatformAdapter._merge_caption(existing.text, event.text)diff --git a/gateway/run.py b/gateway/run.pyindex 12494bdba30..89aa4acde23 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -3531,11 +3531,18 @@ def _build_media_placeholder(event) -> str:return "\n".join(parts)-def _build_document_context_note(display_name: str, agent_path: str, mtype: str) -> str:+def _build_document_context_note(+ display_name: str,+ agent_path: str,+ mtype: str,+ *,+ content_inlined: bool = True,+) -> str:"""Context note prepended to a user turn when they attach a document.- Text documents (``text/*``) have their content inlined upstream by the- platform adapter, so the note just confirms that and records the path.+ Text documents (``text/*``) are usually inlined upstream by the platform+ adapter. ``content_inlined=False`` records adapters that cache the file+ without injecting its content, so the note tells the agent to read it.Binary documents (PDF, DOCX, XLSX, …) cannot be inlined as text. The notemust tell the agent to *extract* the text itself before answering — earlier@@ -3543,12 +3550,18 @@ def _build_document_context_note(display_name: str, agent_path: str, mtype: str)model into punting back to the user, which is why attached PDFs/DOCX looked"unreadable" to the agent even though it has the tools to read them."""- if mtype.startswith("text/"):+ if mtype.startswith("text/") and content_inlined:return (f"[The user sent a text document: '{display_name}'. "f"Its content has been included below. "f"The file is also saved at: {agent_path}]")+ if mtype.startswith("text/"):+ return (+ f"[The user sent a text document: '{display_name}'. It is saved at: {agent_path}. "+ f"Its content is not inlined here. Read the cached file yourself before answering "+ f"when the user's request involves its contents.]"+ )return (f"[The user sent a document: '{display_name}'. It is saved at: {agent_path}. "f"Its text is not inlined here (it's a binary format such as PDF or DOCX). "@@ -17831,6 +17844,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewmessage_id=event.message_id,media_urls=list(getattr(event, "media_urls", []) or []),media_types=list(getattr(event, "media_types", []) or []),+ media_text_inlined=list(getattr(event, "media_text_inlined", []) or []),reply_to_message_id=event.reply_to_message_id,reply_to_text=event.reply_to_text,reply_to_author_id=event.reply_to_author_id,@@ -19658,12 +19672,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# mis-routed here as an image and the provider 400s.if _event_media_is_image(event, i):image_paths.append(path)- # MessageType.AUDIO = audio file attachment (e.g. .mp3, .m4a) — never STT- # MessageType.VOICE = voice message (Opus/OGG) — always STT- if event.message_type == MessageType.AUDIO:- audio_file_paths.append(path)- elif not _pending_stt_prepared and _event_media_is_stt_input(event, i):- audio_paths.append(path)+ # MessageType.AUDIO = audio file attachment (e.g. .mp3, .m4a) — never STT.+ # Mixed DOCUMENT events also preserve audio as a file path instead of+ # dropping it or treating it as a voice note.+ if _event_media_is_audio(event, i):+ if event.message_type in {MessageType.AUDIO, MessageType.DOCUMENT}:+ audio_file_paths.append(path)+ elif not _pending_stt_prepared and _event_media_is_stt_input(event, i):+ audio_paths.append(path)if mtype.startswith("video/") or (not mtype and event.message_type == MessageType.VIDEO):video_paths.append(path)@@ -19835,7 +19851,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew# cache directories are auto-mounted at /root/.hermes/cache/* by get_cache_directory_mounts().agent_path = to_agent_visible_cache_path(path)- context_note = _build_document_context_note(display_name, agent_path, mtype)+ inline_flags = getattr(event, "media_text_inlined", None) or []+ inline_flag = inline_flags[i] if i < len(inline_flags) else None+ context_note = _build_document_context_note(+ display_name,+ agent_path,+ mtype,+ content_inlined=inline_flag is not False,+ )message_text = f"{context_note}\n\n{message_text}"# Discord: surface the triggering message id per-turn on the userdiff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex 4d37a3419b1..eb4be8f3f88 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -40,6 +40,7 @@ environment and is never logged."""import asyncio+import hashlibimport jsonimport loggingimport mimetypes@@ -168,9 +169,11 @@ logger = logging.getLogger(__name__)from gateway.platforms.base import (BasePlatformAdapter,+ CachedMedia,SendResult,MessageEvent,MessageType,+ cache_media_bytes,)from gateway.config import Platform@@ -242,6 +245,57 @@ _CLI_TIMEOUT = 30.0# display names change rarely, but must not survive a rename forever._MEMBER_CACHE_TTL = 60.0_PROFILE_NAME_TTL = 300.0+# Inbound attachment limits. Attachments are downloaded only after the sender,+# mention, and allow-list gates pass; each one must declare and match an exact+# size and SHA-256 in its NIP-94 ``imeta`` tag.+_MAX_INBOUND_ATTACHMENTS = 4+_MAX_INBOUND_ATTACHMENT_BYTES = 20 * 1024 * 1024+_ATTACHMENT_DOWNLOAD_TIMEOUT = 30.0+_MAX_ATTACHMENT_FILENAME_BYTES = 120+++def _safe_attachment_filename(value: str) -> str:+ """Return a basename that is safe for cache files and agent context."""+ name = str(value or "").replace("\\", "/").rsplit("/", 1)[-1]+ name = "".join(+ character+ for character in name+ if ord(character) >= 32 and character != "\x7f"+ ).strip()+ if name in {"", ".", ".."}:+ return "attachment.bin"++ suffix = Path(name).suffix+ if len(suffix.encode("utf-8")) > 20:+ suffix = ""+ stem = name[:-len(suffix)] if suffix else name+ byte_budget = _MAX_ATTACHMENT_FILENAME_BYTES - len(suffix.encode("utf-8"))+ safe_stem = (+ stem.encode("utf-8")[:byte_budget]+ .decode("utf-8", errors="ignore")+ .rstrip(" .")+ )+ if not safe_stem:+ safe_stem = "attachment"+ return f"{safe_stem}{suffix}"+++def _attachment_origin(value: str) -> Optional[tuple[str, int]]:+ """Normalize a configured host/URL to an exact HTTPS-equivalent origin."""+ raw = str(value or "").strip()+ if not raw:+ return None+ try:+ parsed = urlsplit(raw if "://" in raw else f"//{raw}")+ host = (parsed.hostname or "").lower().rstrip(".")+ port = parsed.port or 443+ except ValueError:+ return None+ if parsed.scheme and parsed.scheme not in {"https", "wss"}:+ return None+ if not host:+ return None+ return host, port# WebSocket transport (NIP-42 authenticated Nostr subscription).# kind 44100 is Buzz's channel-membership event — used for live DM discovery.@@ -690,6 +744,21 @@ class BuzzAdapter(BasePlatformAdapter):# env — the default profile's bridge output — is not consulted)_relay_raw = _scoped_platform_setting("BUZZ_RELAY_URL", extra, "relay_url")self.relay_url = (_relay_raw or extra.get("relay_url", "")).strip()++ configured_attachment_hosts = extra.get("attachment_hosts", [])+ if isinstance(configured_attachment_hosts, str):+ configured_attachment_hosts = configured_attachment_hosts.split(",")+ configured_origins = (+ _attachment_origin(host)+ for host in configured_attachment_hosts+ if isinstance(host, str)+ )+ self._attachment_origins = {+ origin for origin in configured_origins if origin is not None+ }+ relay_origin = _attachment_origin(self.relay_url)+ if relay_origin is not None:+ self._attachment_origins.add(relay_origin)_cli_raw = _scoped_platform_setting("BUZZ_CLI_PATH", extra, "cli_path")self.cli_path = _resolve_cli_path(str(_cli_raw or "").strip() or str(extra.get("cli_path", "") or "")@@ -1984,6 +2053,152 @@ class BuzzAdapter(BasePlatformAdapter):if self._cursor_mark(state) != before:self._save_cursors()+ @staticmethod+ def _imeta_attachments(event: dict) -> List[dict]:+ """Return bounded, structurally valid NIP-94 attachment metadata."""+ tags = event.get("tags")+ if not isinstance(tags, list):+ return []+ attachments: List[dict] = []+ total_declared_bytes = 0+ for tag in tags:+ if len(attachments) >= _MAX_INBOUND_ATTACHMENTS:+ break+ if not isinstance(tag, (list, tuple)) or not tag or tag[0] != "imeta":+ continue+ fields: Dict[str, str] = {}+ for raw_field in tag[1:]:+ if not isinstance(raw_field, str):+ continue+ key, separator, value = raw_field.partition(" ")+ if separator and key not in fields:+ fields[key] = value.strip()+ url = fields.get("url", "")+ digest = fields.get("x", "").lower()+ filename = fields.get("filename", "")+ mime_type = fields.get("m", "")+ try:+ size = int(fields.get("size", ""))+ except (TypeError, ValueError):+ continue+ try:+ parsed = urlsplit(url)+ parsed_hostname = parsed.hostname+ # Access validates malformed/non-numeric ports even though exact+ # origin authorization occurs immediately before downloading.+ parsed.port+ except ValueError:+ continue+ if (+ parsed.scheme != "https"+ or not parsed_hostname+ or parsed.username+ or parsed.password+ or parsed.fragment+ or not re.fullmatch(r"[0-9a-f]{64}", digest)+ or not 0 < size <= _MAX_INBOUND_ATTACHMENT_BYTES+ or total_declared_bytes + size > _MAX_INBOUND_ATTACHMENT_BYTES+ ):+ continue+ total_declared_bytes += size+ attachments.append(+ {+ "url": url,+ "sha256": digest,+ "size": size,+ "filename": _safe_attachment_filename(filename),+ "mime_type": mime_type[:255],+ }+ )+ return attachments++ async def _download_attachment(self, metadata: dict) -> Optional[CachedMedia]:+ """Download, integrity-check, and cache one authorized Buzz attachment."""+ url = metadata["url"]+ try:+ parsed_url = urlsplit(url)+ host = (parsed_url.hostname or "").lower().rstrip(".")+ origin = (host, parsed_url.port or 443)+ except ValueError:+ parsed_url = None+ origin = ("", 0)+ if (+ parsed_url is None+ or parsed_url.scheme != "https"+ or origin not in self._attachment_origins+ ):+ logger.warning(+ "Buzz: refusing attachment from untrusted origin %s:%s",+ origin[0] or "<missing>",+ origin[1],+ )+ return None++ import httpx++ try:+ timeout = httpx.Timeout(_ATTACHMENT_DOWNLOAD_TIMEOUT)+ async with asyncio.timeout(_ATTACHMENT_DOWNLOAD_TIMEOUT):+ async with httpx.AsyncClient(+ follow_redirects=False,+ timeout=timeout,+ headers={"Accept-Encoding": "identity"},+ ) as client:+ async with client.stream("GET", url) as response:+ if response.status_code != 200:+ logger.warning(+ "Buzz: attachment download returned HTTP %s",+ response.status_code,+ )+ return None+ content_length = response.headers.get("content-length")+ if content_length:+ try:+ declared_response_size = int(content_length)+ except ValueError:+ return None+ if declared_response_size != metadata["size"]:+ logger.warning(+ "Buzz: attachment Content-Length does not match imeta size"+ )+ return None+ data = bytearray()+ async for chunk in response.aiter_bytes():+ data.extend(chunk)+ if len(data) > metadata["size"]:+ logger.warning("Buzz: attachment exceeded its declared size")+ return None+ except (TimeoutError, httpx.HTTPError, OSError, ValueError) as exc:+ logger.warning("Buzz: attachment download failed: %s", exc)+ return None++ if len(data) != metadata["size"]:+ logger.warning("Buzz: attachment size does not match imeta")+ return None+ if hashlib.sha256(data).hexdigest() != metadata["sha256"]:+ logger.warning("Buzz: attachment SHA-256 does not match imeta")+ return None+ try:+ return cache_media_bytes(+ bytes(data),+ filename=metadata["filename"],+ mime_type=metadata["mime_type"],+ )+ except (OSError, ValueError) as exc:+ logger.warning("Buzz: attachment cache write failed: %s", exc)+ return None++ async def _cache_inbound_attachments(+ self,+ metadata_items: List[dict],+ ) -> List[CachedMedia]:+ cached: List[CachedMedia] = []+ for metadata in metadata_items:+ attachment = await self._download_attachment(metadata)+ if attachment is not None:+ cached.append(attachment)+ return cached+async def _handle_event(self, channel_id: str, state: dict, event: dict) -> None:"""De-dupe, filter, and dispatch a single ``messages get`` event."""event_id = str(event.get("id") or "")@@ -1997,7 +2212,12 @@ class BuzzAdapter(BasePlatformAdapter):returnpubkey = str(event.get("pubkey") or "").lower()content = event.get("content")- if not pubkey or not isinstance(content, str) or not content.strip():+ attachment_metadata = self._imeta_attachments(event)+ if (+ not pubkey+ or not isinstance(content, str)+ or (not content.strip() and not attachment_metadata)+ ):return# Feed the per-channel event cache before any early return so self-echo@@ -2065,6 +2285,30 @@ class BuzzAdapter(BasePlatformAdapter):# Remember where this message sits in the thread graph so our reply# can join the SAME thread rather than nesting a new one under it.self._record_thread_root(event_id, event)+ # Network and cache access deliberately happen only after self-echo,+ # addressing, and sender allow-list authorization have all passed.+ attachments = await self._cache_inbound_attachments(attachment_metadata)+ if attachment_metadata and len(attachments) < len(attachment_metadata):+ failed = len(attachment_metadata) - len(attachments)+ dispatch_text = (+ f"{dispatch_text}\n"+ f"[{failed} Buzz attachment(s) could not be downloaded or failed integrity checks.]"+ ).strip()++ message_type = MessageType.TEXT+ if attachments:+ attachment_kinds = {attachment.kind for attachment in attachments}+ if len(attachment_kinds) == 1:+ message_type = {+ "image": MessageType.PHOTO,+ "video": MessageType.VIDEO,+ "audio": MessageType.AUDIO,+ "document": MessageType.DOCUMENT,+ }.get(next(iter(attachment_kinds)), MessageType.DOCUMENT)+ else:+ # Mixed media must use document semantics so an audio member is+ # not mistaken for a voice note and sent through STT.+ message_type = MessageType.DOCUMENTawait self._dispatch_message(text=dispatch_text,@@ -2079,6 +2323,10 @@ class BuzzAdapter(BasePlatformAdapter):reply_to_text=reply_meta[1] if reply_meta else None,reply_to_author_id=reply_meta[0] if reply_meta else None,reply_to_is_own_message=reply_to_is_own,+ media_urls=[attachment.path for attachment in attachments],+ media_types=[attachment.media_type for attachment in attachments],+ message_type=message_type,+ raw_message=event,)# ── DM classification (issue #68871) ──────────────────────────────────@@ -2490,6 +2738,10 @@ class BuzzAdapter(BasePlatformAdapter):reply_to_text: Optional[str] = None,reply_to_author_id: Optional[str] = None,reply_to_is_own_message: bool = False,+ media_urls: Optional[List[str]] = None,+ media_types: Optional[List[str]] = None,+ message_type: MessageType = MessageType.TEXT,+ raw_message: Any = None,) -> None:"""Build a MessageEvent and hand it to the base class handler."""if not self._message_handler:@@ -2516,7 +2768,11 @@ class BuzzAdapter(BasePlatformAdapter):text=text,message_type=message_type,source=source,+ raw_message=raw_message,message_id=message_id,+ media_urls=list(media_urls or []),+ media_types=list(media_types or []),+ media_text_inlined=[False] * len(media_urls or []),timestamp=datetime.fromtimestamp(created_at) if created_at else datetime.now(),reply_to_message_id=reply_to_message_id,reply_to_text=reply_to_text,diff --git a/plugins/platforms/buzz/plugin.yaml b/plugins/platforms/buzz/plugin.yamlindex 18f76efa16e..fc3dc504e72 100644--- a/plugins/platforms/buzz/plugin.yaml+++ b/plugins/platforms/buzz/plugin.yaml@@ -6,8 +6,9 @@ description: >Buzz gateway adapter for Hermes Agent.Connects to a Buzz community relay (Block's open-source human+agentcollaboration platform built on Nostr) and relays messages between- channels/DMs and the Hermes agent. Pure stdlib — shells out to the- buzz CLI binary (JSON in/out); no Python packages required.+ channels/DMs and the Hermes agent. Relay operations shell out to the+ buzz CLI binary (JSON in/out); verified inbound media uses Hermes' bundled+ HTTP client.author: Nous Research# ``requires_env`` entries are surfaced in ``hermes config`` UI via the# platform-plugin env var injector in ``hermes_cli/config.py``.diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.pyindex a1d2868ccba..27c7d869891 100644--- a/tests/gateway/test_buzz_adapter.py+++ b/tests/gateway/test_buzz_adapter.py@@ -2,11 +2,14 @@import asyncioimport base64+import hashlibimport json+from pathlib import Pathimport pytestfrom unittest.mock import AsyncMock, MagicMock+from gateway.platforms.base import CachedMedia, MessageTypefrom tests.gateway._plugin_adapter_loader import load_plugin_adapterfrom gateway.platforms.base import MessageType@@ -660,6 +663,626 @@ class TestPollingDedupe:await adapter._poll_channel(CHANNEL)assert len(adapter._dispatched) == 1+ @pytest.mark.asyncio+ async def test_malformed_attachment_url_does_not_abort_following_event(self, adapter):+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ malformed = _event("malformed-attachment", content="background chatter", created_at=159)+ malformed["tags"].append([+ "imeta",+ "url https://[invalid/media.bin",+ "m application/octet-stream",+ "x " + "a" * 64,+ "size 1",+ "filename invalid.bin",+ ])+ valid = _event("following-valid", content="@Chip still there?", created_at=160)+ cli = _ScriptedCli()+ cli.script("messages", "get", [malformed, valid])+ adapter._run_cli = cli++ await adapter._poll_channel(CHANNEL)++ assert [item["message_id"] for item in adapter._dispatched] == ["following-valid"]++ @pytest.mark.asyncio+ async def test_addressed_attachment_is_cached_and_dispatched_to_agent(self, adapter):+ attachment = CachedMedia(+ path="/agent/cache/doc_handoff.txt",+ media_type="text/plain",+ kind="document",+ display_name="handoff.txt",+ )+ adapter._download_attachment = AsyncMock(return_value=attachment)+ adapter._user_names[OTHER_PUBKEY] = "Other"+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ event = _event("attachment-event", content="@Chip inspect this", created_at=160)+ event["tags"].append([+ "imeta",+ "url https://test.relay/media/abc.bin",+ "m text/plain",+ "x " + "a" * 64,+ "size 12",+ "filename handoff.txt",+ ])++ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)++ adapter._download_attachment.assert_awaited_once()+ dispatched = adapter._dispatched[-1]+ assert dispatched["media_urls"] == [attachment.path]+ assert dispatched["media_types"] == ["text/plain"]+ assert dispatched["message_type"] is MessageType.DOCUMENT+ assert attachment.context_note() not in dispatched["text"]+ assert dispatched["raw_message"] is event+++class TestInboundAttachments:++ def test_imeta_total_declared_bytes_are_bounded(self):+ event = _event("bounded", content="@Chip files")+ per_file_size = 6 * 1024 * 1024+ for index in range(4):+ event["tags"].append([+ "imeta",+ f"url https://test.relay/media/{index}.bin",+ "m application/octet-stream",+ "x " + format(index + 1, "064x"),+ f"size {per_file_size}",+ f"filename {index}.bin",+ ])++ attachments = BuzzAdapter._imeta_attachments(event)++ assert len(attachments) == 3+ assert sum(item["size"] for item in attachments) <= 20 * 1024 * 1024++ @pytest.mark.asyncio+ async def test_download_caches_only_exact_size_and_sha256(self, monkeypatch):+ import httpx++ payload = b"verified Buzz attachment"+ digest = hashlib.sha256(payload).hexdigest()+ real_async_client = httpx.AsyncClient++ def handler(request):+ assert request.url.host == "test.relay"+ return httpx.Response(+ 200,+ content=payload,+ headers={"content-length": str(len(payload))},+ )++ monkeypatch.setattr(+ httpx,+ "AsyncClient",+ lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(handler),+ **kwargs,+ ),+ )+ adapter = _make_adapter()++ cached = await adapter._download_attachment({+ "url": "https://test.relay/media/verified.bin",+ "sha256": digest,+ "size": len(payload),+ "filename": "verified.txt",+ "mime_type": "text/plain",+ })++ assert cached is not None+ assert cached.kind == "document"+ assert cached.media_type == "text/plain"+ assert Path(cached.path).read_bytes() == payload++ @pytest.mark.asyncio+ async def test_download_rejects_untrusted_attachment_host_before_network(self, monkeypatch):+ import httpx++ def must_not_create_client(**kwargs):+ raise AssertionError("network client must not be created")++ monkeypatch.setattr(httpx, "AsyncClient", must_not_create_client)+ adapter = _make_adapter()++ cached = await adapter._download_attachment({+ "url": "https://untrusted.example/media/file.bin",+ "sha256": "a" * 64,+ "size": 12,+ "filename": "file.bin",+ "mime_type": "application/octet-stream",+ })++ assert cached is None++ @pytest.mark.asyncio+ async def test_download_rejects_unconfigured_nondefault_port_before_network(self, monkeypatch):+ import httpx++ def must_not_create_client(**kwargs):+ raise AssertionError("network client must not be created")++ monkeypatch.setattr(httpx, "AsyncClient", must_not_create_client)+ adapter = _make_adapter()++ cached = await adapter._download_attachment({+ "url": "https://test.relay:8443/media/file.bin",+ "sha256": "a" * 64,+ "size": 12,+ "filename": "file.bin",+ "mime_type": "application/octet-stream",+ })++ assert cached is None++ @pytest.mark.asyncio+ async def test_download_allows_explicitly_configured_nondefault_port(self, monkeypatch):+ import httpx++ payload = b"x"+ real_async_client = httpx.AsyncClient++ def handler(request):+ assert request.url.port == 8443+ return httpx.Response(200, content=payload, headers={"content-length": "1"})++ monkeypatch.setattr(+ httpx,+ "AsyncClient",+ lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(handler),+ **kwargs,+ ),+ )+ adapter = _make_adapter({"attachment_hosts": ["test.relay:8443"]})++ cached = await adapter._download_attachment({+ "url": "https://test.relay:8443/media/file.bin",+ "sha256": hashlib.sha256(payload).hexdigest(),+ "size": 1,+ "filename": "file.bin",+ "mime_type": "application/octet-stream",+ })++ assert cached is not None++ @pytest.mark.asyncio+ async def test_unaddressed_channel_attachment_is_not_downloaded(self):+ adapter = _make_adapter()+ adapter._download_attachment = AsyncMock()+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ event = _event("unaddressed-attachment", content="shared file")+ event["tags"].append([+ "imeta",+ "url https://test.relay/media/file.bin",+ "m application/octet-stream",+ "x " + "a" * 64,+ "size 12",+ "filename file.bin",+ ])++ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)++ adapter._download_attachment.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_failed_attachment_download_is_visible_to_agent(self):+ adapter = _make_adapter()+ adapter._download_attachment = AsyncMock(return_value=None)+ adapter._user_names[OTHER_PUBKEY] = "Other"+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ dispatched = []++ async def capture(**kwargs):+ dispatched.append(kwargs)++ adapter._dispatch_message = capture+ event = _event("failed-attachment", content="@Chip inspect this")+ event["tags"].append([+ "imeta",+ "url https://test.relay/media/file.bin",+ "m application/octet-stream",+ "x " + "a" * 64,+ "size 12",+ "filename file.bin",+ ])++ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)++ assert "could not be downloaded" in dispatched[-1]["text"]+ assert dispatched[-1]["media_urls"] == []++ @pytest.mark.asyncio+ async def test_dispatch_builds_document_message_event_with_cached_path(self):+ adapter = _make_adapter()+ adapter._message_handler = AsyncMock()+ adapter.handle_message = AsyncMock()++ await adapter._dispatch_message(+ text="inspect",+ chat_id=CHANNEL,+ chat_type="group",+ user_id=OTHER_PUBKEY,+ user_name="Other",+ message_id="document-event",+ created_at=1000,+ media_urls=["/agent/cache/doc_report.pdf"],+ media_types=["application/pdf"],+ message_type=MessageType.DOCUMENT,+ raw_message={"id": "document-event"},+ )++ call = adapter.handle_message.await_args+ assert call is not None+ dispatched_event = call.args[0]+ assert dispatched_event.message_type is MessageType.DOCUMENT+ assert dispatched_event.media_urls == ["/agent/cache/doc_report.pdf"]+ assert dispatched_event.media_types == ["application/pdf"]+ assert dispatched_event.media_text_inlined == [False]+ assert dispatched_event.raw_message == {"id": "document-event"}++ def test_imeta_sanitizes_filename_and_rejects_incomplete_metadata(self):+ event = _event("metadata", content="@Chip files")+ event["tags"].extend([+ [+ "imeta",+ "url https://test.relay/media/valid.bin",+ "m text/plain",+ "x " + "a" * 64,+ "size 12",+ "filename ../../private/report.txt",+ ],+ [+ "imeta",+ "url http://test.relay/media/insecure.bin",+ "x " + "b" * 64,+ "size 12",+ "filename insecure.bin",+ ],+ [+ "imeta",+ "url https://test.relay/media/no-hash.bin",+ "size 12",+ "filename no-hash.bin",+ ],+ ])++ attachments = BuzzAdapter._imeta_attachments(event)++ assert len(attachments) == 1+ assert attachments[0]["filename"] == "report.txt"++ @pytest.mark.asyncio+ async def test_attachment_only_dm_is_downloaded_and_dispatched(self):+ adapter = _make_adapter()+ attachment = CachedMedia(+ path="/agent/cache/doc_attachment.bin",+ media_type="application/octet-stream",+ kind="document",+ display_name="attachment.bin",+ )+ adapter._download_attachment = AsyncMock(return_value=attachment)+ adapter._user_names[OTHER_PUBKEY] = "Other"+ adapter._channel_state[DM_CHANNEL] = {+ "chat_type": "dm",+ "last_ts": 0,+ "seen": {},+ }+ dispatched = []++ async def capture(**kwargs):+ dispatched.append(kwargs)++ adapter._dispatch_message = capture+ event = _event("attachment-only", content="")+ event["tags"].append([+ "imeta",+ "url https://test.relay/media/file.bin",+ "m application/octet-stream",+ "x " + "a" * 64,+ "size 12",+ "filename attachment.bin",+ ])++ await adapter._handle_event(+ DM_CHANNEL,+ adapter._channel_state[DM_CHANNEL],+ event,+ )++ adapter._download_attachment.assert_awaited_once()+ assert dispatched[-1]["media_urls"] == [attachment.path]+ assert dispatched[-1]["message_type"] is MessageType.DOCUMENT++ def test_imeta_bounds_filename_to_filesystem_safe_utf8_length(self):+ event = _event("long-name", content="@Chip file")+ event["tags"].append([+ "imeta",+ "url https://test.relay/media/file.bin",+ "m application/octet-stream",+ "x " + "a" * 64,+ "size 1",+ "filename " + ("é" * 180) + ".pdf",+ ])++ filename = BuzzAdapter._imeta_attachments(event)[0]["filename"]++ assert len(filename.encode("utf-8")) <= 120+ assert filename.endswith(".pdf")++ @pytest.mark.asyncio+ async def test_cache_write_failure_is_treated_as_failed_attachment(self, monkeypatch):+ import httpx++ payload = b"x"+ digest = hashlib.sha256(payload).hexdigest()+ real_async_client = httpx.AsyncClient+ monkeypatch.setattr(+ httpx,+ "AsyncClient",+ lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=payload,+ headers={"content-length": "1"},+ )+ ),+ **kwargs,+ ),+ )+ monkeypatch.setattr(+ _buzz_mod,+ "cache_media_bytes",+ MagicMock(side_effect=OSError(36, "File name too long")),+ )+ adapter = _make_adapter()++ cached = await adapter._download_attachment({+ "url": "https://test.relay/media/file.bin",+ "sha256": digest,+ "size": 1,+ "filename": "file.bin",+ "mime_type": "application/octet-stream",+ })++ assert cached is None++ @pytest.mark.asyncio+ async def test_download_has_total_deadline(self, monkeypatch):+ import httpx++ payload = b"x"+ real_async_client = httpx.AsyncClient++ async def slow_handler(_request):+ await asyncio.sleep(0.05)+ return httpx.Response(200, content=payload, headers={"content-length": "1"})++ monkeypatch.setattr(_buzz_mod, "_ATTACHMENT_DOWNLOAD_TIMEOUT", 0.01)+ monkeypatch.setattr(+ httpx,+ "AsyncClient",+ lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(slow_handler),+ **kwargs,+ ),+ )+ adapter = _make_adapter()++ cached = await adapter._download_attachment({+ "url": "https://test.relay/media/file.bin",+ "sha256": hashlib.sha256(payload).hexdigest(),+ "size": 1,+ "filename": "file.bin",+ "mime_type": "application/octet-stream",+ })++ assert cached is None++ @pytest.mark.asyncio+ async def test_multiple_mixed_attachments_use_document_semantics(self):+ adapter = _make_adapter()+ adapter._user_names[OTHER_PUBKEY] = "Other"+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ cached = [+ CachedMedia("/cache/image.png", "image/png", "image", "image.png"),+ CachedMedia("/cache/audio.mp3", "audio/mpeg", "audio", "audio.mp3"),+ ]+ adapter._cache_inbound_attachments = AsyncMock(return_value=cached)+ dispatched = []++ async def capture(**kwargs):+ dispatched.append(kwargs)++ adapter._dispatch_message = capture+ event = _event("mixed", content="@Chip inspect")+ for index, mime_type in enumerate(("image/png", "audio/mpeg")):+ event["tags"].append([+ "imeta",+ f"url https://test.relay/media/{index}.bin",+ f"m {mime_type}",+ "x " + format(index + 1, "064x"),+ "size 1",+ f"filename {index}.bin",+ ])++ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)++ assert dispatched[-1]["message_type"] is MessageType.DOCUMENT+ assert dispatched[-1]["media_types"] == ["image/png", "audio/mpeg"]++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("status", "payload", "headers", "declared_size", "expected_digest"),+ [+ (302, b"", {}, 1, "a" * 64),+ (200, b"x", {"content-length": "invalid"}, 1, hashlib.sha256(b"x").hexdigest()),+ (200, b"x", {}, 2, hashlib.sha256(b"x").hexdigest()),+ (200, b"xx", {}, 1, hashlib.sha256(b"xx").hexdigest()),+ (200, b"x", {}, 1, "a" * 64),+ ],+ )+ async def test_download_rejects_invalid_response_or_integrity(+ self,+ monkeypatch,+ status,+ payload,+ headers,+ declared_size,+ expected_digest,+ ):+ import httpx++ real_async_client = httpx.AsyncClient+ monkeypatch.setattr(+ httpx,+ "AsyncClient",+ lambda **kwargs: real_async_client(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(status, content=payload, headers=headers)+ ),+ **kwargs,+ ),+ )+ adapter = _make_adapter()++ cached = await adapter._download_attachment({+ "url": "https://test.relay/media/file.bin",+ "sha256": expected_digest,+ "size": declared_size,+ "filename": "file.bin",+ "mime_type": "application/octet-stream",+ })++ assert cached is None++ def test_imeta_rejects_url_credentials_and_fragments_and_caps_items(self):+ event = _event("url-safety", content="@Chip files")+ event["tags"].extend([+ [+ "imeta",+ "url https://user:[email protected]/media/private.bin",+ "x " + "a" * 64,+ "size 1",+ "filename private.bin",+ ],+ [+ "imeta",+ "url https://test.relay/media/fragment.bin#hidden",+ "x " + "b" * 64,+ "size 1",+ "filename fragment.bin",+ ],+ ])+ for index in range(6):+ event["tags"].append([+ "imeta",+ f"url https://test.relay/media/{index}.bin",+ "x " + format(index + 1, "064x"),+ "size 1",+ f"filename {index}.bin",+ ])++ attachments = BuzzAdapter._imeta_attachments(event)++ assert len(attachments) == 4+ assert all("@" not in item["url"] and "#" not in item["url"] for item in attachments)++ @pytest.mark.asyncio+ async def test_unauthorized_sender_attachment_is_not_downloaded(self):+ adapter = _make_adapter()+ adapter._allowed_pubkeys = {"f" * 64}+ adapter._download_attachment = AsyncMock()+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ event = _event("unauthorized-attachment", content="@Chip inspect")+ event["tags"].append([+ "imeta",+ "url https://test.relay/media/file.bin",+ "m application/octet-stream",+ "x " + "a" * 64,+ "size 1",+ "filename file.bin",+ ])++ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)++ adapter._download_attachment.assert_not_awaited()++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("kind", "mime_type", "expected_type"),+ [+ ("image", "image/png", MessageType.PHOTO),+ ("video", "video/mp4", MessageType.VIDEO),+ ("audio", "audio/mpeg", MessageType.AUDIO),+ ("document", "application/pdf", MessageType.DOCUMENT),+ ],+ )+ async def test_homogeneous_attachment_kind_sets_message_type(+ self,+ kind,+ mime_type,+ expected_type,+ ):+ adapter = _make_adapter()+ adapter._user_names[OTHER_PUBKEY] = "Other"+ adapter._channel_state[CHANNEL] = {+ "chat_type": "group",+ "last_ts": 0,+ "seen": {},+ }+ cached = CachedMedia(+ f"/cache/file-{kind}",+ mime_type,+ kind,+ f"file-{kind}",+ )+ adapter._cache_inbound_attachments = AsyncMock(return_value=[cached])+ dispatched = []++ async def capture(**kwargs):+ dispatched.append(kwargs)++ adapter._dispatch_message = capture+ event = _event(f"homogeneous-{kind}", content="@Chip inspect")+ event["tags"].append([+ "imeta",+ f"url https://test.relay/media/{kind}",+ f"m {mime_type}",+ "x " + "a" * 64,+ "size 1",+ f"filename file-{kind}",+ ])++ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)++ assert dispatched[-1]["message_type"] is expected_type+# ── Mention gating / DMs / authorization ──────────────────────────────────diff --git a/tests/gateway/test_document_context_note.py b/tests/gateway/test_document_context_note.pyindex cd5c8a0be79..42f4e45a1d1 100644--- a/tests/gateway/test_document_context_note.py+++ b/tests/gateway/test_document_context_note.py@@ -14,6 +14,11 @@ import importlibimport pytest+from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.base import MessageEvent, MessageType+from gateway.run import GatewayRunner+from gateway.session import SessionSource+gateway_run = importlib.import_module("gateway.run")_build_document_context_note = gateway_run._build_document_context_note@@ -27,6 +32,54 @@ class TestTextDocumentNote:assert "/cache/doc_notes.txt" in noteassert "included below" in note+ def test_non_inlined_text_note_tells_agent_to_read_cached_path(self):+ note = _build_document_context_note(+ "notes.txt",+ "/cache/doc_notes.txt",+ "text/plain",+ content_inlined=False,+ )+ assert "included below" not in note+ assert "/cache/doc_notes.txt" in note+ assert "read" in note.lower()++ @pytest.mark.asyncio+ async def test_event_contract_marks_non_inlined_text_and_preserves_path(self):+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="fake")}+ )+ runner.adapters = {}+ runner._pending_native_image_paths_by_session = {}+ runner._session_model_overrides = {}+ runner._session_reasoning_overrides = {}+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="text-document",+ chat_type="dm",+ user_id="42",+ user_name="Tester",+ )+ event = MessageEvent(+ text="summarize this",+ message_type=MessageType.DOCUMENT,+ source=source,+ media_urls=["/cache/notes.txt"],+ media_types=["text/plain"],+ media_text_inlined=[False],+ )++ prepared = await runner._prepare_inbound_message_text(+ event=event,+ source=source,+ history=[],+ )++ assert prepared is not None+ assert "/cache/notes.txt" in prepared+ assert "included below" not in prepared+ assert "read the cached file" in prepared.lower()+class TestBinaryDocumentNote:@pytest.mark.parametrize(diff --git a/tests/gateway/test_mixed_attachment_routing.py b/tests/gateway/test_mixed_attachment_routing.pyindex a93e7ab1dd1..f03fa3fb1e0 100644--- a/tests/gateway/test_mixed_attachment_routing.py+++ b/tests/gateway/test_mixed_attachment_routing.py@@ -19,13 +19,18 @@ populate media_types.from types import SimpleNamespace-from gateway.platforms.base import MessageType+import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.base import MessageEvent, MessageType, merge_pending_message_eventfrom gateway.run import (+ GatewayRunner,_build_media_placeholder,_event_media_is_audio,_event_media_is_image,_event_media_is_video,)+from gateway.session import SessionSourcedef _evt(media_urls, media_types, message_type):@@ -57,3 +62,68 @@ def test_placeholder_document_in_photo_message_is_not_an_image():assert "[User sent a file: /c/brief.md]" in out+async def test_mixed_document_event_preserves_audio_as_non_stt_file_path():+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="fake")}+ )+ runner.adapters = {}+ runner._pending_native_image_paths_by_session = {}+ runner._session_model_overrides = {}+ runner._session_reasoning_overrides = {}+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="mixed-audio",+ chat_type="dm",+ user_id="42",+ user_name="Tester",+ )+ event = MessageEvent(+ text="inspect both",+ message_type=MessageType.DOCUMENT,+ source=source,+ media_urls=["/cache/audio.mp3", "/cache/report.pdf"],+ media_types=["audio/mpeg", "application/pdf"],+ )++ prepared = await runner._prepare_inbound_message_text(+ event=event,+ source=source,+ history=[],+ )++ assert prepared is not None+ assert "/cache/audio.mp3" in prepared+ assert "/cache/report.pdf" in prepared+ assert "transcrib" in prepared.lower()+++def test_pending_media_merge_preserves_per_attachment_inline_contract():+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="merge",+ chat_type="dm",+ user_id="42",+ )+ existing = MessageEvent(+ text="first",+ message_type=MessageType.PHOTO,+ source=source,+ media_urls=["/cache/image.png"],+ media_types=["image/png"],+ )+ incoming = MessageEvent(+ text="second",+ message_type=MessageType.DOCUMENT,+ source=source,+ media_urls=["/cache/notes.txt"],+ media_types=["text/plain"],+ media_text_inlined=[False],+ )+ pending = {"session": existing}++ merge_pending_message_event(pending, "session", incoming)++ assert existing.media_urls == ["/cache/image.png", "/cache/notes.txt"]+ assert existing.media_text_inlined == [None, False]diff --git a/website/docs/user-guide/messaging/buzz.md b/website/docs/user-guide/messaging/buzz.mdindex 898a92a5d72..44c0cf732d4 100644--- a/website/docs/user-guide/messaging/buzz.md+++ b/website/docs/user-guide/messaging/buzz.md@@ -29,6 +29,7 @@ gateway:enabled: trueextra:relay_url: https://mycommunity.communities.buzz.xyz+ attachment_hosts: [] # additional exact HTTPS host[:port] origins for inbound fileschannels: # channel UUIDs to watch (empty = all joined)- ccc2bc1a-7a82-5a8f-8c4e-57a070cbe7cdhome_channel: ccc2bc1a-7a82-5a8f-8c4e-57a070cbe7cd@@ -74,6 +75,7 @@ gateway:enabled: trueextra:relay_url: https://mycommunity.communities.buzz.xyz+ attachment_hosts: [] # additional exact HTTPS host[:port] origins for inbound fileschannels: # channel UUIDs to watch (empty = all joined)- ccc2bc1a-7a82-5a8f-8c4e-57a070cbe7cdhome_channel: ccc2bc1a-7a82-5a8f-8c4e-57a070cbe7cd@@ -128,6 +130,21 @@ The allow-list also gates **inbound attachments**: relay media is fetched with tCron jobs and notifications (`deliver=buzz`) are delivered to the **home channel** — `BUZZ_HOME_CHANNEL` if set, otherwise the first watched channel — and work even when cron runs outside the gateway process.+## Inbound attachments++Buzz messages with native NIP-94 `imeta` tags can deliver images, audio,+video, and documents to the agent. Hermes downloads attachments only after+the message has passed self-echo, addressing, and sender authorization checks.+Each file must use HTTPS and declare an exact byte size and SHA-256 digest;+redirects, URL credentials, fragments, oversized payloads, and integrity+mismatches are rejected.++The relay's own HTTPS origin is trusted automatically. If a community stores+media on another public origin, add its exact `host` or `host:port` to+`attachment_hosts` under `gateway.platforms.buzz.extra`. Non-default ports+must be listed explicitly. Protected media that requires authenticated+retrieval through the Buzz CLI is not handled by this native public-URL path.+## Run the gateway```bash