From 6cb4f53b0dd1da8fcf98358ef0acff22d40fdc93 Mon Sep 17 00:00:00 2001 From: Ben Davis <45952064+bmdavis419@users.noreply.github.com> Date: Mon, 27 Jul 2026 17:47:31 -0700 Subject: [PATCH] =?UTF-8?q?feat(hermes-plugin):=20protocol=20v4=20?= =?UTF-8?q?=E2=80=94=20send=20and=20receive=20media?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Outbound: the adapter overrides Hermes' native send_image_file/send_video/ send_voice/send_document to emit `media.deliver` with the identical queue-before-send, purge-only-on-ack lifecycle home deliveries use — the JSONL outbox stores raw frames keyed on deliveryId, so both frame types ride one queue. A _recent_turns record keeps a reply's media turn-scoped even when it lands just after its notify-completed turn (upstream sends text before media). Files are read eagerly so queued copies are self-contained; unreadable or >25MB files are skipped, never queued. Inbound: turn.start attachments are decoded to 0600 temp files in a 0700 per-turn dir (client-supplied names sanitized, extension preserved) and ride the MessageEvent's structured media_urls/media_types fields — Hermes' own platform-attachment channel, which feeds vision routing, STT, and document context notes. turn.steer is the exception: its handler injects only text, so steer attachments append as bracketed path notes. media_deliver() raises on empty/oversized payloads or a missing deliveryId rather than clamping — truncated bytes are a corrupt file, and a wire-invalid frame must never enter the durable queue. WebSocket max_size rises 2MB -> 64MB for v4 frames. 134 tests (was 106); ruff clean. Co-Authored-By: Claude Fable 5 --- .../hermes-t3-gateway/COMPATIBILITY.md | 32 +- integrations/hermes-t3-gateway/README.md | 2 +- integrations/hermes-t3-gateway/adapter.py | 269 ++++++++- integrations/hermes-t3-gateway/connection.py | 6 +- integrations/hermes-t3-gateway/home.py | 158 ++++-- integrations/hermes-t3-gateway/plugin.yaml | 2 +- integrations/hermes-t3-gateway/protocol.py | 159 +++++- .../hermes-t3-gateway/tests/test_adapter.py | 519 ++++++++++++++++-- .../tests/test_connection.py | 18 +- .../hermes-t3-gateway/tests/test_home.py | 130 ++++- .../hermes-t3-gateway/tests/test_protocol.py | 181 +++++- 11 files changed, 1362 insertions(+), 114 deletions(-) diff --git a/integrations/hermes-t3-gateway/COMPATIBILITY.md b/integrations/hermes-t3-gateway/COMPATIBILITY.md index 021addf840..79a334f263 100644 --- a/integrations/hermes-t3-gateway/COMPATIBILITY.md +++ b/integrations/hermes-t3-gateway/COMPATIBILITY.md @@ -66,11 +66,14 @@ Home-channel surfaces, added for protocol v3: | `HERMES_SESSION_USER_ID` binding | `gateway/run.py:17372` | | Session-context lifetime around a turn | `gateway/run.py:12972` → `:14626` | -This inventory describes gateway wire protocol v3. Protocol v2 added active-turn +This inventory describes gateway wire protocol v4. Protocol v2 added active-turn recovery in `session.ready` and authoritative `content.snapshot` replacement; v3 -adds `role` on `connection.hello`, `homeThreadId` on `connection.accepted`, and -the `home.deliver` / `home.deliver.ack` pair. Older server/plugin pairs are -rejected during the handshake — the version policy stays fail-closed. +added `role` on `connection.hello`, `homeThreadId` on `connection.accepted`, and +the `home.deliver` / `home.deliver.ack` pair; v4 adds media — optional inline +`attachments` on `turn.start` / `turn.steer`, the `media.deliver` / +`media.deliver.ack` pair, and the `attachments` capability flipping to the +literal `true`. Older server/plugin pairs are rejected during the handshake — +the version policy stays fail-closed. ## Mapped in the initial scope @@ -228,12 +231,21 @@ rejected during the handshake — the version policy stays fail-closed. `skillName` cannot be answered, because the response echoes the name back and the wire type is non-empty. That takes the ordinary correlated `protocol.error` path. -- Attachments are not accepted. They are the first planned post-stability - feature; the capability is reserved and fixed to `false` in protocol v3. The - `standalone_sender_fn` signature accepts `media_files` / `force_document` for - parity with `gateway/platform_registry.py:150-158`, but the v3 wire contract - has no attachment framing, so both are ignored (logged, not silently - dropped). +- Attachments are part of protocol v4; the capability is fixed to `true` + (T3's schema pins the literal, so a plugin that cannot handle them is a v3 + plugin and is rejected at the version gate). Inbound, `turn.start` / + `turn.steer` may carry inline base64 files (≤25MB each): turn-start files + are written to private temp files and ride `MessageEvent.media_urls` / + `media_types` into Hermes' own enrichment pipeline; steer files are + appended to the injected `/steer` text as path notes, because Hermes' + steer handler injects only text between tool iterations + (`gateway/run.py:11254`). Outbound, the adapter overrides + `send_image_file` / `send_video` / `send_voice` / `send_document` to emit + `media.deliver` frames (raw bytes ≤25MB, base64 on the wire) with the same + durable queue-then-ack lifecycle as `home.deliver`; the + `standalone_sender_fn` sends `media_files` the same way, and + `force_document` remains signature parity only — T3 derives rendering from + `mimeType`, so there is no document/photo distinction to force. - **Kind/label classification is heuristic.** `adapter.send()` carries no structured "this is a cron delivery" marker on every path, so the plugin reads what does exist (see "Home-channel delivery" below). A diff --git a/integrations/hermes-t3-gateway/README.md b/integrations/hermes-t3-gateway/README.md index 5e84c8aa77..b177f3067b 100644 --- a/integrations/hermes-t3-gateway/README.md +++ b/integrations/hermes-t3-gateway/README.md @@ -4,7 +4,7 @@ Experimental Hermes platform plugin for connecting one already-running Hermes process to T3 Code. The plugin makes an outbound WebSocket connection; Hermes does not need to listen on a public port. -The gateway wire protocol is v3. The T3 server and Hermes plugin must be updated +The gateway wire protocol is v4. The T3 server and Hermes plugin must be updated together; mismatched versions fail the connection handshake closed. Each T3 thread maps deterministically to one Hermes gateway session. A new T3 diff --git a/integrations/hermes-t3-gateway/adapter.py b/integrations/hermes-t3-gateway/adapter.py index 056f0d1128..034d21ca97 100644 --- a/integrations/hermes-t3-gateway/adapter.py +++ b/integrations/hermes-t3-gateway/adapter.py @@ -6,10 +6,13 @@ import asyncio import contextvars import logging import os +import re +import tempfile import uuid import weakref from collections.abc import Coroutine from dataclasses import dataclass, field +from pathlib import Path from typing import Any from gateway.config import Platform, PlatformConfig @@ -28,6 +31,7 @@ from .home import ( MAX_FLUSH_PER_CONNECT, HomeDeliveryQueue, build_delivery, + build_media_delivery, classify_delivery, home_thread_id, save_home_thread_id, @@ -42,6 +46,7 @@ from .protocol import ( protocol_error, skill_body, skill_body_response, + turn_attachments, validate_server_frame, ) @@ -72,6 +77,56 @@ def _hermes_version() -> str: return "unknown" +# Characters allowed to survive from a client-supplied filename into a temp +# file name. Everything else is dropped: the name arrived over the wire and +# must never influence the directory the file lands in. +_ATTACHMENT_NAME_SAFE_RE = re.compile(r"[^A-Za-z0-9._-]+") + + +def _materialize_attachments( + attachments: list[dict[str, Any]], +) -> tuple[list[str], list[str]]: + """Write inbound turn attachments to private temp files. + + Returns `(paths, mime_types)` aligned by index — the exact shape + `MessageEvent.media_urls` / `media_types` expect. + + Each turn gets its own `mkdtemp` directory (mode 0700) and each file is + created with `mkstemp` (mode 0600), so nothing is readable by other users + even mid-write. The extension is preserved from the wire `name` — after + sanitizing, because that name is client-supplied — since Hermes routes + files by suffix in several places (`should_send_media_as_audio`, the + text-document allowlist). The files are deliberately not deleted here: + Hermes reads them asynchronously during the turn (vision, STT, terminal + tools), there is no turn-end hook on this surface, and the OS tmp reaper + is the documented cleanup — the same pre-existing no-GC stance as T3's + attachment store. + """ + if not attachments: + return [], [] + directory = tempfile.mkdtemp(prefix="hermes-t3-attachments-") + paths: list[str] = [] + mime_types: list[str] = [] + for attachment in attachments: + wire_name = Path(str(attachment["name"])).name # strip any path parts + stem = _ATTACHMENT_NAME_SAFE_RE.sub("_", Path(wire_name).stem)[:48] + suffix = _ATTACHMENT_NAME_SAFE_RE.sub("", Path(wire_name).suffix)[:16] + if suffix and not suffix.startswith("."): + suffix = f".{suffix}" + if suffix == ".": + suffix = "" + handle, path = tempfile.mkstemp( + prefix=f"{stem or 'attachment'}-", + suffix=suffix, + dir=directory, + ) + with os.fdopen(handle, "wb") as stream: + stream.write(attachment["data"]) + paths.append(path) + mime_types.append(str(attachment["mimeType"])) + return paths, mime_types + + @dataclass class _TurnState: thread_id: str @@ -146,6 +201,14 @@ class T3PlatformAdapter(BasePlatformAdapter): self._active_session_threads: set[str] = set() self._thread_by_session: dict[str, str] = {} self._active_turns: dict[str, _TurnState] = {} + # The most recently COMPLETED turn per thread. The base adapter's + # delivery pipeline sends the final text (notify-marked, which + # completes the turn here) BEFORE it sends the reply's media files + # (`gateway/platforms/base.py:5326` then `:5383+`), so a turn reply's + # media routinely arrives moments after its turn closed. This record + # lets that media still be delivered turn-scoped instead of erroring + # with "no active T3 turn". + self._recent_turns: dict[str, _TurnState] = {} self._approval_requests: dict[str, tuple[str, str]] = {} self._user_input_requests: dict[str, tuple[str, str]] = {} self._home_queue = HomeDeliveryQueue() @@ -424,12 +487,179 @@ class T3PlatformAdapter(BasePlatformAdapter): return async def _acknowledge_home_delivery(self, message: dict[str, Any]) -> None: - """Purge a delivery T3 has durably written.""" + """Purge a delivery T3 has durably written. + + Serves `home.deliver.ack` and `media.deliver.ack` alike: both frame + types live in the same queue keyed on `deliveryId`, so the purge does + not care which kind of delivery was acknowledged. + """ delivery_id_value = str(message.get("deliveryId") or "").strip() if not delivery_id_value: - raise ValueError("home.deliver.ack requires a deliveryId") + raise ValueError("a delivery ack requires a deliveryId") self._home_queue.purge(delivery_id_value) + # ── outbound media ───────────────────────────────────────────────── + + def _media_turn_scope( + self, + thread_id: str, + content: str, + metadata: dict[str, Any] | None, + ) -> _TurnState | None: + """Resolve the turn a media send belongs to, or None for home delivery. + + Same provenance gate as `_is_proactive_delivery`, with one addition: + the base adapter's delivery pipeline sends a reply's final text — + notify-marked, which completes the turn here — BEFORE it dispatches + the reply's media files (`gateway/platforms/base.py:5326` then + `:5383+`), so turn media routinely arrives moments after its turn + closed. The most recently completed turn per thread is therefore an + accepted scope when the send still carries that turn's session key. + """ + turn = self._active_turns.get(thread_id) + recent = self._recent_turns.get(thread_id) + session_key = self._gateway_session_key() + if turn is not None and session_key == turn.session_id: + return turn + if turn is None and recent is not None and session_key == recent.session_id: + return recent + home = home_thread_id() + if not home or thread_id != home: + # Not home: media belongs to the live turn or has nowhere to go — + # exactly the text path's scope rule. A stale completed turn is + # NOT a scope here; only the session-key-matched case above may + # reach back past completion. + return turn + if turn is None: + return None + _kind, _label, certain = classify_delivery( + content, + metadata, + session_user_id=self._session_user_id(), + ) + # Conservative half of the gate, mirroring text: an unattributable + # media send during a live home turn stays with the turn. + return None if certain else turn + + async def _deliver_media_file( + self, + chat_id: str, + path: str, + *, + caption: str | None = None, + name: str | None = None, + metadata: dict[str, Any] | None = None, + ) -> SendResult: + """Emit one `media.deliver`, queueing it until T3 acknowledges it. + + The same durable lifecycle as `_deliver_to_home`: persist BEFORE + sending, report success once queued, purge only on the ack. The one + divergence is a payload that cannot be built at all — unreadable file, + empty, over the 25MB ceiling — which fails the send immediately + instead of queueing a frame T3 would reject on every future flush. + """ + thread_id = str(chat_id) + content = str(caption or "") + turn = self._media_turn_scope(thread_id, content, metadata) + if turn is None: + home = home_thread_id() + if not home or thread_id != home: + return SendResult(success=False, error="no active T3 turn") + kind, label, _certain = classify_delivery( + content, + metadata, + session_user_id=self._session_user_id(), + ) + try: + delivery = build_media_delivery( + thread_id=thread_id, + path=str(path), + kind=kind, + label=label, + turn_id=turn.turn_id if turn is not None else None, + caption=caption, + name=name, + ) + except Exception as exc: # noqa: BLE001 - adapter send must return SendResult + logger.warning("T3 media delivery for %s failed to build: %s", path, exc) + return SendResult(success=False, error=str(exc)) + delivery_id_value = str(delivery["deliveryId"]) + self._home_queue.append(delivery) + try: + await self._send_frame(delivery) + except Exception as exc: # noqa: BLE001 - adapter send must return SendResult + logger.warning( + "T3 media delivery %s could not be sent (%s); it is queued for " + "the next connect", + delivery_id_value, + exc, + ) + return SendResult(success=True, message_id=delivery_id_value) + + async def send_image_file( + self, + chat_id: str, + image_path: str, + caption: str | None = None, + reply_to: str | None = None, + metadata: dict[str, Any] | None = None, + **kwargs: Any, + ) -> SendResult: + del reply_to, kwargs + return await self._deliver_media_file( + chat_id, image_path, caption=caption, metadata=metadata + ) + + async def send_video( + self, + chat_id: str, + video_path: str, + caption: str | None = None, + reply_to: str | None = None, + metadata: dict[str, Any] | None = None, + **kwargs: Any, + ) -> SendResult: + del reply_to, kwargs + return await self._deliver_media_file( + chat_id, video_path, caption=caption, metadata=metadata + ) + + async def send_voice( + self, + chat_id: str, + audio_path: str, + caption: str | None = None, + reply_to: str | None = None, + metadata: dict[str, Any] | None = None, + **kwargs: Any, + ) -> SendResult: + # T3 renders audio as a download card (no native player in v1), which + # is still strictly better than the base fallback's "couldn't deliver + # the audio attachment" notice. + del reply_to, kwargs + return await self._deliver_media_file( + chat_id, audio_path, caption=caption, metadata=metadata + ) + + async def send_document( + self, + chat_id: str, + file_path: str, + caption: str | None = None, + file_name: str | None = None, + reply_to: str | None = None, + metadata: dict[str, Any] | None = None, + **kwargs: Any, + ) -> SendResult: + del reply_to, kwargs + return await self._deliver_media_file( + chat_id, + file_path, + caption=caption, + name=file_name, + metadata=metadata, + ) + @staticmethod def _session_user_id() -> str: """Read the bound session's user id, for `/handoff` classification. @@ -588,7 +818,7 @@ class T3PlatformAdapter(BasePlatformAdapter): await self._describe(message) elif frame_type == "skill.body.request": await self._send_skill_body(message) - elif frame_type == "home.deliver.ack": + elif frame_type in {"home.deliver.ack", "media.deliver.ack"}: await self._acknowledge_home_delivery(message) except ValueError as exc: await self._send_frame( @@ -698,6 +928,20 @@ class T3PlatformAdapter(BasePlatformAdapter): ) ) return + # Decode and materialize attachments BEFORE any turn state exists: a + # malformed attachment raises ValueError into the correlated + # `protocol.error` path with no half-started turn to clean up. + # + # Surfacing choice: the temp file paths ride the MessageEvent's own + # `media_urls` / `media_types` fields — Hermes' structured channel for + # exactly this (`gateway/platforms/base.py:1800`). The gateway's + # enrichment pipeline then does everything a bundled platform gets: + # vision routing for images, STT for voice, and path-pointing context + # notes for documents (`gateway/run.py:12420+`). No prompt-text + # injection is needed on this path. + media_paths, media_types = _materialize_attachments( + turn_attachments(message) + ) turn = _TurnState( thread_id=thread_id, session_id=session_id, @@ -726,6 +970,8 @@ class T3PlatformAdapter(BasePlatformAdapter): source=self._source(thread_id, turn.request_id), message_id=turn.request_id, metadata={"t3_turn_id": turn.turn_id}, + media_urls=media_paths, + media_types=media_types, ) ) @@ -741,6 +987,18 @@ class T3PlatformAdapter(BasePlatformAdapter): ) ) return + # Attachments on a steer cannot ride `media_urls`: Hermes' `/steer` + # handler injects only the command's text between tool iterations + # (`gateway/run.py:11254`) and never reads the event's media fields. + # The paths are appended to the injected text instead — mid-turn the + # agent reaches files through its tools anyway, so a path note is the + # natural (and only) channel here. + steer_text = str(message["text"]) + media_paths, media_types = _materialize_attachments( + turn_attachments(message) + ) + for path, mime in zip(media_paths, media_types): + steer_text += f"\n[The user attached a file ({mime}): {path}]" # `/steer` is Hermes' official active-run injection surface. The base # adapter dispatches active slash commands inline, then sends the # command's textual acknowledgement back through this adapter with @@ -755,7 +1013,7 @@ class T3PlatformAdapter(BasePlatformAdapter): try: await self.handle_message( MessageEvent( - text=f"/steer {message['text']}", + text=f"/steer {steer_text}", message_type=MessageType.COMMAND, source=self._source(turn.thread_id, control.request_id), message_id=control.request_id, @@ -1086,6 +1344,9 @@ class T3PlatformAdapter(BasePlatformAdapter): ) ) self._active_turns.pop(turn.thread_id, None) + # Remembered for media scoping: the base adapter sends a reply's + # media files AFTER its notify-marked text, i.e. after this point. + self._recent_turns[turn.thread_id] = turn await self._send_status() async def _emit_generic_activity(self, turn: _TurnState, detail: str) -> None: diff --git a/integrations/hermes-t3-gateway/connection.py b/integrations/hermes-t3-gateway/connection.py index 4eec7fc98f..afa8649bf8 100644 --- a/integrations/hermes-t3-gateway/connection.py +++ b/integrations/hermes-t3-gateway/connection.py @@ -63,7 +63,11 @@ async def _open_socket(url: str): ping_interval=20, ping_timeout=20, close_timeout=5, - max_size=2 * 1024 * 1024, + # Protocol v4 turn frames may carry inline base64 attachments up to + # 25MB raw (~34MB encoded, `protocol.MAX_MEDIA_BYTES`). 64MB leaves + # room for the JSON envelope and T3's per-turn total while still + # bounding a pathological frame. + max_size=64 * 1024 * 1024, ) diff --git a/integrations/hermes-t3-gateway/home.py b/integrations/hermes-t3-gateway/home.py index 16ec05c5e5..12299447cd 100644 --- a/integrations/hermes-t3-gateway/home.py +++ b/integrations/hermes-t3-gateway/home.py @@ -22,6 +22,7 @@ from __future__ import annotations import json import logging +import mimetypes import os import threading from pathlib import Path @@ -32,6 +33,7 @@ from .protocol import ( delivery_id, home_deliver, iso_now, + media_deliver, ) logger = logging.getLogger(__name__) @@ -147,7 +149,14 @@ def save_home_thread_id(thread_id: str) -> bool: class HomeDeliveryQueue: - """Append-only JSONL outbox of unacknowledged `home.deliver` frames. + """Append-only JSONL outbox of unacknowledged delivery frames. + + Entries are stored as raw wire frames keyed on `deliveryId`, so the queue + carries `home.deliver` and `media.deliver` alike: flushing replays the + frame verbatim and T3 discriminates on `type`. A media entry is large (up + to ~34MB of base64 on one line), so the entry cap doubles as a coarse disk + bound; a genuinely wedged connection under heavy media output trades disk + for durability, which is the documented preference. Correctness rests on one rule: an entry is removed **only** when T3 acks its `deliveryId`. Everything else — a socket that dropped mid-send, a @@ -436,6 +445,47 @@ def build_delivery( ) +def build_media_delivery( + *, + thread_id: str, + path: str, + kind: str = "message", + label: str = "Hermes", + turn_id: str | None = None, + caption: str | None = None, + name: str | None = None, + created_at: str | None = None, +) -> dict[str, Any]: + """Mint one `media.deliver` frame from a local file, id and timestamp included. + + Reads the file eagerly so the queued copy is self-contained: Hermes' media + files live in temp/cache directories that may be gone by the time a queued + delivery flushes after an outage, and a queue entry pointing at a dead path + would be unsendable forever. `createdAt` is stamped here for the same + reason as `build_delivery`. + + Raises `OSError` when the file cannot be read and `ValueError` when it is + empty or over the 25MB wire ceiling — the caller decides whether that is a + logged skip (adapter) or a reported error (standalone sender). + """ + file_path = Path(path) + data = file_path.read_bytes() + display_name = str(name or "").strip() or file_path.name + mime, _encoding = mimetypes.guess_type(display_name) + return media_deliver( + delivery_id_value=delivery_id(), + thread_id=thread_id, + kind=kind if kind in HOME_DELIVERY_KINDS else "other", + label=label, + name=display_name, + mime_type=mime or "application/octet-stream", + data=data, + turn_id=turn_id, + caption=caption, + created_at=created_at or iso_now(), + ) + + # ── standalone (out-of-process) sender ──────────────────────────────────── @@ -466,17 +516,15 @@ async def standalone_send( disk before the socket is opened, so the job reports success-with-queued and the live gateway flushes it on its next `connection.accepted`. - `media_files` and `force_document` are accepted for signature parity - (`gateway/platform_registry.py:150-158`); the v3 wire contract carries no - attachment framing, so they are ignored. + `media_files` rides the v4 wire as one `media.deliver` frame per file + (upstream passes `(path, is_voice)` tuples; bare path strings are accepted + too). A file that cannot be read or exceeds the 25MB frame ceiling is + reported in `detail` and skipped — never queued, because a queued frame + that T3 will always reject would sit in the outbox forever. `force_document` + remains signature parity only: T3 derives rendering from `mimeType`, so + there is no document/photo distinction to force. """ del force_document - if media_files: - logger.info( - "T3 standalone send ignoring %d media file(s): the v3 gateway " - "contract has no attachment framing", - len(media_files), - ) extra = getattr(pconfig, "extra", None) or {} @@ -506,18 +554,49 @@ async def standalone_send( } kind, label, _certain = classify_delivery(message, None) - frame = build_delivery(thread_id=target, text=message, kind=kind, label=label) - delivery = str(frame["deliveryId"]) + frames: list[dict[str, Any]] = [] + skipped: list[str] = [] + # The text frame is skipped only when media makes the send non-empty + # anyway; a bare text send keeps today's behaviour (empty text normalizes + # inside `home_deliver`). + if str(message or "").strip() or not media_files: + frames.append( + build_delivery(thread_id=target, text=message, kind=kind, label=label) + ) + for entry in media_files or []: + media_path = entry[0] if isinstance(entry, (tuple, list)) else entry + try: + frames.append( + build_media_delivery( + thread_id=target, + path=str(media_path), + kind=kind, + label=label, + ) + ) + except Exception as exc: # noqa: BLE001 - one bad file must not sink the send + # Never queued: a frame T3 will always reject (unreadable then, + # oversized forever) would otherwise sit in the outbox for good. + logger.warning( + "T3 standalone send skipping media file %s: %s", media_path, exc + ) + skipped.append(f"{media_path}: {exc}") + if not frames: + return { + "error": "T3 standalone send: no deliverable content " + + "; ".join(skipped) + } + delivery = str(frames[0]["deliveryId"]) queue = HomeDeliveryQueue() - queued = queue.append(frame) + queued = all(queue.append(frame) for frame in frames) try: acked = await _deliver_over_short_lived_socket( url=url, instance_id=instance_id, credential=credential, - frame=frame, + frames=frames, ) except Exception as exc: # noqa: BLE001 - cron delivery must not raise logger.debug("T3 standalone send raised", exc_info=True) @@ -530,15 +609,23 @@ async def standalone_send( } return {"error": f"T3 standalone send failed: {exc}"} - if acked: - queue.purge(delivery) - return {"success": True, "message_id": delivery} + for acked_id in acked: + queue.purge(acked_id) + result_detail = "; ".join(f"skipped {entry}" for entry in skipped) + if len(acked) == len(frames): + result: dict[str, Any] = {"success": True, "message_id": delivery} + if result_detail: + result["detail"] = result_detail + return result if queued: return { "success": True, "message_id": delivery, "queued": True, - "detail": "T3 did not acknowledge the delivery; queued for retry", + "detail": ( + "T3 did not acknowledge every delivery; queued for retry" + + (f" ({result_detail})" if result_detail else "") + ), } return {"error": "T3 standalone send: the delivery was neither acked nor queued"} @@ -548,15 +635,22 @@ async def _deliver_over_short_lived_socket( url: str, instance_id: str, credential: str, - frame: dict[str, Any], + frames: list[dict[str, Any]], timeout: float = 20.0, -) -> bool: - """Open, authenticate as `delivery`, send, await the ack, close.""" +) -> set[str]: + """Open, authenticate as `delivery`, send, await the acks, close. + + Returns the set of `deliveryId`s T3 acknowledged (`home.deliver.ack` and + `media.deliver.ack` are equivalent here). A timeout returns whatever was + acked so far — the caller purges exactly those and leaves the rest queued. + """ import asyncio from .connection import _open_socket, authenticate_socket hermes_version = _hermes_version() + expected = {str(frame["deliveryId"]) for frame in frames} + acked: set[str] = set() socket = await _open_socket(url) try: await authenticate_socket( @@ -569,15 +663,16 @@ async def _deliver_over_short_lived_socket( hermes_version=hermes_version, role="delivery", ) - await socket.send( - json.dumps(frame, separators=(",", ":"), ensure_ascii=False) - ) + for frame in frames: + await socket.send( + json.dumps(frame, separators=(",", ":"), ensure_ascii=False) + ) loop = asyncio.get_running_loop() deadline = loop.time() + timeout - while True: + while acked != expected: remaining = deadline - loop.time() if remaining <= 0: - return False + return acked raw = await asyncio.wait_for(socket.recv(), timeout=remaining) try: reply = json.loads(raw) @@ -585,12 +680,13 @@ async def _deliver_over_short_lived_socket( continue if not isinstance(reply, dict): continue - if reply.get("type") == "home.deliver.ack" and str( - reply.get("deliveryId") or "" - ) == str(frame["deliveryId"]): - return True + if reply.get("type") in {"home.deliver.ack", "media.deliver.ack"}: + delivery_id_value = str(reply.get("deliveryId") or "") + if delivery_id_value in expected: + acked.add(delivery_id_value) # Anything else (a liveness ping, an unrelated frame) is ignored: - # this socket exists only to hand over one delivery. + # this socket exists only to hand over these deliveries. + return acked finally: try: await socket.close() diff --git a/integrations/hermes-t3-gateway/plugin.yaml b/integrations/hermes-t3-gateway/plugin.yaml index dfd86b14bd..71eac11582 100644 --- a/integrations/hermes-t3-gateway/plugin.yaml +++ b/integrations/hermes-t3-gateway/plugin.yaml @@ -1,7 +1,7 @@ name: hermes-t3-gateway label: T3 Code kind: platform -version: 0.3.0 +version: 0.4.0 description: > Experimental outbound gateway that exposes one Hermes Agent process as a named T3 Code provider instance over an authenticated WebSocket. diff --git a/integrations/hermes-t3-gateway/protocol.py b/integrations/hermes-t3-gateway/protocol.py index 8d661b5518..f76c3b0fe4 100644 --- a/integrations/hermes-t3-gateway/protocol.py +++ b/integrations/hermes-t3-gateway/protocol.py @@ -2,13 +2,15 @@ from __future__ import annotations +import base64 +import binascii import json import uuid from datetime import datetime, timezone from typing import Any -PROTOCOL_VERSION = 3 -PLUGIN_VERSION = "0.3.0" +PROTOCOL_VERSION = 4 +PLUGIN_VERSION = "0.4.0" WEBSOCKET_PATH = "/api/hermes-gateway/ws" # What a connecting socket intends to be. `gateway` is the instance's one live @@ -24,9 +26,10 @@ CAPABILITIES = { "activity": True, "approvals": True, "userInput": True, - # First post-stability feature: advertise false until binary/media framing - # and bounded attachment transfer are implemented end to end. - "attachments": False, + # Part of the v4 contract itself, not a negotiated option: the T3 schema + # pins `attachments` to the literal `true`, so a plugin that cannot handle + # them is a v3 plugin and is rejected at the version gate. + "attachments": True, } SERVER_COMMANDS = frozenset( @@ -42,6 +45,7 @@ SERVER_COMMANDS = frozenset( "describe.request", "skill.body.request", "home.deliver.ack", + "media.deliver.ack", } ) @@ -61,6 +65,21 @@ MAX_HOME_DELIVERY_TEXT_CHARS = 120_000 # SKILL.md while still bounding a pathological file from stalling the socket. MAX_SKILL_BODY_CHARS = 512_000 +# Raw-byte ceiling for a single `media.deliver` frame, and for each attachment +# riding an inbound turn frame. Mirrors `HERMES_MEDIA_MAX_BYTES` in the T3 +# contract: 25MB of raw bytes is ~34MB of base64, and the schema bound there is +# on the encoded string so an oversized frame fails at decode. Deliberately no +# chunking — a file that does not fit does not send, with a clear error. +MAX_MEDIA_BYTES = 25 * 1024 * 1024 + +# Wire bounds from the T3 contract (`HermesGatewayMediaDeliver`): `name` is a +# trimmed non-empty string of at most 255 chars, `mimeType` at most 100, and +# `caption` at most 2000. Enforced here for the same reason as the +# `home.deliver` bounds: a queued frame must already be wire-valid on disk. +MAX_MEDIA_NAME_CHARS = 255 +MAX_MEDIA_MIME_CHARS = 100 +MAX_MEDIA_CAPTION_CHARS = 2_000 + def request_id() -> str: return str(uuid.uuid4()) @@ -362,6 +381,136 @@ def home_deliver( text=normalized_text, createdAt=created_at or iso_now(), ) + + +def media_deliver( + *, + delivery_id_value: str, + thread_id: str, + kind: str, + label: str, + name: str, + mime_type: str, + data: bytes, + turn_id: str | None = None, + caption: str | None = None, + created_at: str | None = None, +) -> dict[str, Any]: + """Build a `media.deliver` frame with every wire bound already applied. + + Mirrors `home_deliver`: normalizing here rather than at the call sites + means a queued delivery is already wire-valid on disk, so a flush after a + plugin upgrade cannot resurrect a payload the server will reject — the + plugin would purge it only on an ack that never comes. + + The clamp-vs-reject split follows what each field can survive. Provenance + (`kind`, `label`) and presentation (`caption`) degrade exactly like + `home_deliver`'s — a wrong badge or a shortened caption is the documented + worst case. The payload itself cannot degrade: truncated bytes are a + corrupt file, so an empty payload, a payload over `MAX_MEDIA_BYTES`, or a + missing `deliveryId` raises `ValueError` instead — better a loud send-time + failure than a poisoned queue entry T3 rejects forever. + + `data` is raw bytes; base64 encoding happens here so no call site can get + the wire encoding wrong, and `sizeBytes` is derived from the same bytes so + the two can never disagree. + """ + if not str(delivery_id_value or "").strip(): + raise ValueError("media.deliver requires a deliveryId") + if not isinstance(data, (bytes, bytearray)): + raise TypeError("media.deliver data must be bytes") + if len(data) == 0: + raise ValueError("media.deliver requires a non-empty payload") + if len(data) > MAX_MEDIA_BYTES: + raise ValueError( + f"media.deliver payload is {len(data)} bytes; " + f"the wire ceiling is {MAX_MEDIA_BYTES} bytes (25MB)" + ) + normalized_kind = str(kind or "").strip().lower() + if normalized_kind not in HOME_DELIVERY_KINDS: + normalized_kind = "other" + normalized_label = str(label or "").strip()[:MAX_HOME_DELIVERY_LABEL_CHARS].strip() + if not normalized_label: + normalized_label = "Hermes" + normalized_name = str(name or "").strip()[:MAX_MEDIA_NAME_CHARS].strip() + if not normalized_name: + normalized_name = "attachment.bin" + normalized_mime = str(mime_type or "").strip()[:MAX_MEDIA_MIME_CHARS].strip() + if not normalized_mime: + normalized_mime = "application/octet-stream" + payload: dict[str, Any] = { + "deliveryId": delivery_id_value, + "threadId": str(thread_id), + "kind": normalized_kind, + "label": normalized_label, + "name": normalized_name, + "mimeType": normalized_mime, + "sizeBytes": len(data), + "data": base64.b64encode(bytes(data)).decode("ascii"), + "createdAt": created_at or iso_now(), + } + # Optional on the wire: omit rather than send null/empty, matching the + # T3 schema's `Schema.optional` fields. + if turn_id: + payload["turnId"] = str(turn_id) + normalized_caption = str(caption or "")[:MAX_MEDIA_CAPTION_CHARS] + if normalized_caption: + payload["caption"] = normalized_caption + return frame("media.deliver", **payload) + + +def turn_attachments(message: dict[str, Any]) -> list[dict[str, Any]]: + """Decode the optional `attachments` on a `turn.start` / `turn.steer`. + + Returns `[{"name", "mimeType", "data": bytes}, ...]` with the base64 + already decoded and each payload bounded by `MAX_MEDIA_BYTES`. The wire + `sizeBytes` is advisory — the decoded length is the truth, so it is what + callers get. + + A malformed entry raises `ValueError` rather than being skipped: T3 + validates these frames against its own schema before sending, so a bad + entry here means version drift, and silently dropping a file the user + attached is worse than a correlated `protocol.error` they can see. + """ + raw = message.get("attachments") + if raw is None: + return [] + if not isinstance(raw, list): + raise ValueError("turn attachments must be a list") + attachments: list[dict[str, Any]] = [] + for index, entry in enumerate(raw): + if not isinstance(entry, dict): + raise ValueError(f"turn attachment {index} must be an object") + name = str(entry.get("name") or "").strip() + if not name: + raise ValueError(f"turn attachment {index} is missing a name") + encoded = entry.get("data") + if not isinstance(encoded, str) or not encoded: + raise ValueError(f"turn attachment {name!r} carries no data") + try: + data = base64.b64decode(encoded, validate=True) + except (binascii.Error, ValueError) as exc: + raise ValueError( + f"turn attachment {name!r} is not valid base64" + ) from exc + if len(data) == 0: + raise ValueError(f"turn attachment {name!r} decoded to zero bytes") + if len(data) > MAX_MEDIA_BYTES: + raise ValueError( + f"turn attachment {name!r} is {len(data)} bytes; " + f"the wire ceiling is {MAX_MEDIA_BYTES} bytes (25MB)" + ) + mime = str(entry.get("mimeType") or "").strip() + attachments.append( + { + "name": name, + "mimeType": mime or "application/octet-stream", + "data": data, + } + ) + return attachments + + def protocol_error( code: str, message: str, diff --git a/integrations/hermes-t3-gateway/tests/test_adapter.py b/integrations/hermes-t3-gateway/tests/test_adapter.py index baac40b698..ec0670aee1 100644 --- a/integrations/hermes-t3-gateway/tests/test_adapter.py +++ b/integrations/hermes-t3-gateway/tests/test_adapter.py @@ -44,6 +44,10 @@ class MessageEvent: source: object message_id: str metadata: dict + # Media attachments, defaulted exactly like upstream + # (`gateway/platforms/base.py:1801`): local file paths plus aligned MIMEs. + media_urls: list = dataclasses.field(default_factory=list) + media_types: list = dataclasses.field(default_factory=list) @dataclasses.dataclass @@ -219,7 +223,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": f"ensure-{thread_id}", "threadId": thread_id, } @@ -228,7 +232,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": f"start-{thread_id}", "threadId": thread_id, "sessionId": session_id, @@ -242,7 +246,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "ensure-1", "threadId": "thread-1", } @@ -255,7 +259,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "start-1", "threadId": "thread-1", "sessionId": ready["sessionId"], @@ -835,7 +839,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "ensure-reconnect", "threadId": "thread-reconnect", "resumeSessionId": session_id, @@ -851,7 +855,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "ensure-2", "threadId": "thread-2", } @@ -860,7 +864,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "start-2", "threadId": "thread-2", "sessionId": session_id, @@ -879,7 +883,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "steer-2", "threadId": "thread-2", "sessionId": session_id, @@ -951,7 +955,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "steer-race", "threadId": "thread-steer-race", "sessionId": session_id, @@ -1000,7 +1004,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "steer-edit", "threadId": "thread-steer-edit", "sessionId": session_id, @@ -1019,7 +1023,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "ensure-rejected-steer", "threadId": "thread-rejected-steer", } @@ -1028,7 +1032,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "start-rejected-steer", "threadId": "thread-rejected-steer", "sessionId": session_id, @@ -1045,7 +1049,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "steer-rejected", "threadId": "thread-rejected-steer", "sessionId": session_id, @@ -1092,7 +1096,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "ensure-failed-steer", "threadId": "thread-failed-steer", } @@ -1101,7 +1105,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "start-failed-steer", "threadId": "thread-failed-steer", "sessionId": session_id, @@ -1118,7 +1122,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.steer", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "steer-failed", "threadId": "thread-failed-steer", "sessionId": session_id, @@ -1206,7 +1210,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "ensure-3", "threadId": "thread-3", } @@ -1216,7 +1220,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.stop", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "stop-3", "threadId": "thread-3", "sessionId": session_id, @@ -1237,7 +1241,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "describe.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "describe-1", } ) @@ -1246,7 +1250,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): self.assertEqual(reply["type"], "describe.response") # Correlation, exactly like ping -> pong. self.assertEqual(reply["requestId"], "describe-1") - self.assertEqual(reply["protocolVersion"], 3) + self.assertEqual(reply["protocolVersion"], 4) self.assertEqual(reply["hermesVersion"], "0.19.0") self.assertIsInstance(reply["skills"], list) self.assertIn("capabilities", reply) @@ -1260,7 +1264,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "describe.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "describe-degraded", } ) @@ -1277,7 +1281,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "body-degraded", "skillName": "codex", } @@ -1295,7 +1299,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "body-1", "skillName": "codex", } @@ -1312,7 +1316,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "body-2", "skillName": "does-not-exist", } @@ -1332,7 +1336,7 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "skill.body.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "body-3", } ) @@ -1346,12 +1350,12 @@ class AdapterTests(unittest.IsolatedAsyncioTestCase): for message in ( { "type": "describe.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "describe-no-error", }, { "type": "skill.body.request", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "body-no-error", "skillName": "codex", }, @@ -1631,7 +1635,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "session.ensure", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": f"ensure-{thread_id}", "threadId": thread_id, } @@ -1640,7 +1644,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "turn.start", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": f"start-{thread_id}", "threadId": thread_id, "sessionId": session_id, @@ -1662,7 +1666,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): frames = self.connection.messages[frames_before:] self.assertEqual([frame["type"] for frame in frames], ["home.deliver"]) delivery = frames[0] - self.assertEqual(delivery["protocolVersion"], 3) + self.assertEqual(delivery["protocolVersion"], 4) self.assertEqual(delivery["threadId"], self.HOME) self.assertEqual(delivery["kind"], "cron") self.assertEqual(delivery["label"], "Cron: nightly") @@ -1811,7 +1815,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "home.deliver.ack", - "protocolVersion": 3, + "protocolVersion": 4, "deliveryId": delivery_id, } ) @@ -1841,7 +1845,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_connection_accepted( { "type": "connection.accepted", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "hello-1", "instanceId": "instance", "nickname": "Hermes", @@ -1859,7 +1863,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_server_frame( { "type": "home.deliver.ack", - "protocolVersion": 3, + "protocolVersion": 4, "deliveryId": offline.message_id, } ) @@ -1896,7 +1900,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_connection_accepted( { "type": "connection.accepted", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "hello-1", "instanceId": "instance", "nickname": "Hermes", @@ -1913,7 +1917,7 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): await self.adapter._handle_connection_accepted( { "type": "connection.accepted", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "hello-1", "instanceId": "instance", "nickname": "Hermes", @@ -1924,13 +1928,456 @@ class HomeDeliveryTests(unittest.IsolatedAsyncioTestCase): async def test_a_nameless_ack_is_a_correlated_protocol_error(self): await self.adapter._handle_server_frame( - {"type": "home.deliver.ack", "protocolVersion": 3, "requestId": "ack-1"} + {"type": "home.deliver.ack", "protocolVersion": 4, "requestId": "ack-1"} ) reply = self.connection.messages[-1] self.assertEqual(reply["type"], "protocol.error") self.assertEqual(reply["code"], "unsupported-message") +class InboundAttachmentTests(unittest.IsolatedAsyncioTestCase): + """v4 turn attachments: base64 on the frame → temp files → media_urls.""" + + async def asyncSetUp(self): + self.adapter = adapter_module.T3PlatformAdapter( + PlatformConfig( + extra={ + "url": "wss://t3.example/api/hermes-gateway/ws", + "instance_id": "instance", + "credential": "credential", + } + ) + ) + self.connection = FakeConnection() + self.adapter._connection = self.connection + + async def _ensure(self, thread_id: str) -> str: + await self.adapter._handle_server_frame( + { + "type": "session.ensure", + "protocolVersion": 4, + "requestId": f"ensure-{thread_id}", + "threadId": thread_id, + } + ) + return self.adapter._sessions[thread_id] + + async def test_turn_attachments_land_as_local_files_on_the_message_event(self): + import base64 + + session_id = await self._ensure("thread-attach") + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-attach", + "threadId": "thread-attach", + "sessionId": session_id, + "turnId": "turn-attach", + "text": "Describe this image", + "attachments": [ + { + "name": "photo.png", + "mimeType": "image/png", + "sizeBytes": 9, + "data": base64.b64encode(b"PNG bytes").decode("ascii"), + }, + { + "name": "notes.txt", + "mimeType": "text/plain", + "sizeBytes": 5, + "data": base64.b64encode(b"hello").decode("ascii"), + }, + ], + } + ) + + event = self.adapter.messages[-1] + self.assertEqual(event.text, "Describe this image") + # Aligned pairs, exactly the shape Hermes' enrichment pipeline reads. + self.assertEqual(event.media_types, ["image/png", "text/plain"]) + self.assertEqual(len(event.media_urls), 2) + for path, payload in zip(event.media_urls, [b"PNG bytes", b"hello"]): + self.addCleanup( + lambda p=path: pathlib.Path(p).unlink(missing_ok=True) + ) + self.assertEqual(pathlib.Path(path).read_bytes(), payload) + # Secure perms: owner-only file in an owner-only directory. + self.assertEqual(pathlib.Path(path).stat().st_mode & 0o777, 0o600) + self.assertEqual( + pathlib.Path(path).parent.stat().st_mode & 0o777, 0o700 + ) + # The extension survives — Hermes routes files by suffix in several + # places (audio-vs-document, the text-document allowlist). + self.assertTrue(event.media_urls[0].endswith(".png")) + self.assertTrue(event.media_urls[1].endswith(".txt")) + + async def test_a_hostile_attachment_name_cannot_escape_the_temp_directory(self): + import base64 + + session_id = await self._ensure("thread-hostile") + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-hostile", + "threadId": "thread-hostile", + "sessionId": session_id, + "turnId": "turn-hostile", + "text": "Look at this", + "attachments": [ + { + "name": "../../etc/passwd", + "mimeType": "text/plain", + "sizeBytes": 4, + "data": base64.b64encode(b"evil").decode("ascii"), + } + ], + } + ) + event = self.adapter.messages[-1] + path = pathlib.Path(event.media_urls[0]) + self.addCleanup(lambda: path.unlink(missing_ok=True)) + self.assertTrue( + path.parent.name.startswith("hermes-t3-attachments-"), + path, + ) + self.assertNotIn("..", path.name) + + async def test_a_turn_without_attachments_carries_no_media(self): + session_id = await self._ensure("thread-plain") + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-plain", + "threadId": "thread-plain", + "sessionId": session_id, + "turnId": "turn-plain", + "text": "Just text", + } + ) + event = self.adapter.messages[-1] + self.assertEqual(event.media_urls, []) + self.assertEqual(event.media_types, []) + + async def test_a_malformed_attachment_errors_before_any_turn_starts(self): + session_id = await self._ensure("thread-bad-attach") + frames_before = len(self.connection.messages) + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-bad", + "threadId": "thread-bad-attach", + "sessionId": session_id, + "turnId": "turn-bad", + "text": "With a broken file", + "attachments": [{"name": "x.bin", "data": "!!! not base64 !!!"}], + } + ) + frames = self.connection.messages[frames_before:] + self.assertEqual([frame["type"] for frame in frames], ["protocol.error"]) + self.assertEqual(frames[0]["requestId"], "start-bad") + # No half-started turn to clean up, and nothing reached Hermes. + self.assertNotIn("thread-bad-attach", self.adapter._active_turns) + self.assertEqual( + [event.text for event in self.adapter.messages + if getattr(event, "message_id", "") == "start-bad"], + [], + ) + + async def test_steer_attachments_ride_the_injected_text_as_path_notes(self): + import base64 + + session_id = await self._ensure("thread-steer-attach") + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": "start-steer-attach", + "threadId": "thread-steer-attach", + "sessionId": session_id, + "turnId": "turn-steer-attach", + "text": "Start", + } + ) + + async def accept_steer(_event): + return "⏩ Steer queued — arrives after the next tool call" + + self.adapter._message_handler = accept_steer + await self.adapter._handle_server_frame( + { + "type": "turn.steer", + "protocolVersion": 4, + "requestId": "steer-attach", + "threadId": "thread-steer-attach", + "sessionId": session_id, + "turnId": "turn-steer-attach", + "text": "Use this file", + "attachments": [ + { + "name": "data.csv", + "mimeType": "text/csv", + "sizeBytes": 3, + "data": base64.b64encode(b"a,b").decode("ascii"), + } + ], + } + ) + steer_event = self.adapter.messages[-1] + # Hermes' /steer handler injects only text between tool iterations + # (`gateway/run.py:11254`), so the file rides the command as a path + # note the mid-turn agent can open with its tools. + self.assertTrue(steer_event.text.startswith("/steer Use this file\n")) + self.assertIn("[The user attached a file (text/csv): ", steer_event.text) + path = steer_event.text.rsplit(": ", 1)[1].rstrip("]") + self.addCleanup(lambda: pathlib.Path(path).unlink(missing_ok=True)) + self.assertEqual(pathlib.Path(path).read_bytes(), b"a,b") + + +class MediaDeliveryTests(unittest.IsolatedAsyncioTestCase): + """Outbound `media.deliver`: turn scoping plus the durable ack lifecycle.""" + + HOME = "home-thread" + + async def asyncSetUp(self): + self.adapter = adapter_module.T3PlatformAdapter( + PlatformConfig( + extra={ + "url": "wss://t3.example/api/hermes-gateway/ws", + "instance_id": "instance", + "credential": "credential", + } + ) + ) + self.connection = FakeConnection() + self.adapter._connection = self.connection + + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + queue_file = pathlib.Path(self._tmp.name) / "gateway" / "queue.jsonl" + self.queue = home_module.HomeDeliveryQueue(path=queue_file) + self.adapter._home_queue = self.queue + + self.chart = pathlib.Path(self._tmp.name) / "chart.png" + self.chart.write_bytes(b"\x89PNG fake bytes") + + environment = unittest.mock.patch.dict( + adapter_module.os.environ, + {home_module.HOME_CHANNEL_ENV: self.HOME}, + ) + environment.start() + self.addCleanup(environment.stop) + + for name in ("_gateway_session_key", "_session_user_id"): + patch = unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, name, staticmethod(lambda: "") + ) + patch.start() + self.addCleanup(patch.stop) + + async def _start_turn(self, thread_id: str, turn_id: str) -> str: + await self.adapter._handle_server_frame( + { + "type": "session.ensure", + "protocolVersion": 4, + "requestId": f"ensure-{thread_id}", + "threadId": thread_id, + } + ) + session_id = self.adapter._sessions[thread_id] + await self.adapter._handle_server_frame( + { + "type": "turn.start", + "protocolVersion": 4, + "requestId": f"start-{thread_id}", + "threadId": thread_id, + "sessionId": session_id, + "turnId": turn_id, + "text": "Start", + } + ) + return session_id + + async def test_turn_media_is_delivered_turn_scoped(self): + await self._start_turn("thread-media", "turn-media") + frames_before = len(self.connection.messages) + + result = await self.adapter.send_image_file( + "thread-media", str(self.chart), caption="A chart" + ) + + frames = self.connection.messages[frames_before:] + self.assertEqual([frame["type"] for frame in frames], ["media.deliver"]) + delivery = frames[0] + self.assertEqual(delivery["protocolVersion"], 4) + self.assertEqual(delivery["threadId"], "thread-media") + self.assertEqual(delivery["turnId"], "turn-media") + self.assertEqual(delivery["name"], "chart.png") + self.assertEqual(delivery["mimeType"], "image/png") + self.assertEqual(delivery["caption"], "A chart") + self.assertTrue(result.success) + self.assertEqual(result.message_id, delivery["deliveryId"]) + # Media never touches the turn machinery: the turn is still live and + # no turn/item frame was emitted for the file. + self.assertIn("thread-media", self.adapter._active_turns) + + async def test_reply_media_arriving_just_after_completion_keeps_its_turn(self): + """The base adapter sends a reply's text BEFORE its media files + (`gateway/platforms/base.py:5326` then `:5383+`), and the notify-marked + text completes the T3 turn — so a reply's chart routinely arrives + moments after its turn closed and must still land turn-scoped.""" + session_id = await self._start_turn("thread-late-media", "turn-late") + with unittest.mock.patch.object( + adapter_module.T3PlatformAdapter, + "_gateway_session_key", + staticmethod(lambda: session_id), + ): + await self.adapter.send( + "thread-late-media", "Here is the chart", metadata={"notify": True} + ) + self.assertNotIn("thread-late-media", self.adapter._active_turns) + frames_before = len(self.connection.messages) + + result = await self.adapter.send_image_file( + "thread-late-media", str(self.chart) + ) + + self.assertTrue(result.success) + delivery = self.connection.messages[frames_before:][0] + self.assertEqual(delivery["type"], "media.deliver") + self.assertEqual(delivery["turnId"], "turn-late") + + async def test_proactive_media_to_home_is_turnless_with_provenance(self): + frames_before = len(self.connection.messages) + + result = await self.adapter.send_document( + self.HOME, + str(self.chart), + caption=( + "Cronjob Response: nightly\n(job_id: nightly)\n" + "-------------\n\nDone." + ), + ) + + frames = self.connection.messages[frames_before:] + self.assertEqual([frame["type"] for frame in frames], ["media.deliver"]) + delivery = frames[0] + self.assertNotIn("turnId", delivery) + self.assertEqual(delivery["kind"], "cron") + self.assertEqual(delivery["label"], "Cron: nightly") + self.assertTrue(result.success) + self.assertEqual(self.adapter._active_turns, {}) + + async def test_media_to_a_non_home_thread_without_a_turn_errors(self): + """"Send media to any thread unprompted" stays out of scope.""" + result = await self.adapter.send_document( + "some-other-thread", str(self.chart) + ) + self.assertFalse(result.success) + self.assertEqual(result.error, "no active T3 turn") + self.assertEqual(self.connection.messages, []) + self.assertEqual(self.queue.entries(), []) + + async def test_media_is_queued_before_it_is_sent_and_purged_only_on_ack(self): + result = await self.adapter.send_video(self.HOME, str(self.chart)) + delivery_id = result.message_id + self.assertEqual( + [entry["deliveryId"] for entry in self.queue.entries()], [delivery_id] + ) + + # A home.deliver.ack for some OTHER delivery purges nothing. + await self.adapter._handle_server_frame( + { + "type": "media.deliver.ack", + "protocolVersion": 4, + "deliveryId": "unrelated", + } + ) + self.assertEqual(len(self.queue.entries()), 1) + + await self.adapter._handle_server_frame( + { + "type": "media.deliver.ack", + "protocolVersion": 4, + "deliveryId": delivery_id, + } + ) + self.assertEqual(self.queue.entries(), []) + + async def test_queued_media_survives_a_dead_socket_and_flushes_on_reconnect(self): + class DeadConnection: + connected = False + + async def send(self, message): + raise ConnectionError("T3 Code gateway is offline") + + self.adapter._connection = DeadConnection() + with self.assertLogs(adapter_module.logger, level="WARNING"): + offline = await self.adapter.send_document(self.HOME, str(self.chart)) + # Reported successful: durably queued, WILL arrive. + self.assertTrue(offline.success) + self.assertEqual(len(self.queue.entries()), 1) + + self.adapter._connection = self.connection + await self.adapter._handle_connection_accepted( + { + "type": "connection.accepted", + "protocolVersion": 4, + "requestId": "hello-1", + "instanceId": "instance", + "nickname": "Hermes", + "homeThreadId": self.HOME, + } + ) + flushed = self.connection.messages + self.assertEqual([frame["type"] for frame in flushed], ["media.deliver"]) + self.assertEqual(flushed[0]["deliveryId"], offline.message_id) + self.assertEqual(flushed[0]["name"], "chart.png") + # Still queued — only the ack purges it. + self.assertEqual(len(self.queue.entries()), 1) + + await self.adapter._handle_server_frame( + { + "type": "media.deliver.ack", + "protocolVersion": 4, + "deliveryId": offline.message_id, + } + ) + self.assertEqual(self.queue.entries(), []) + + async def test_an_unreadable_file_fails_the_send_and_queues_nothing(self): + """A frame T3 would reject forever must never enter the outbox.""" + await self._start_turn("thread-bad-file", "turn-bad-file") + with self.assertLogs(adapter_module.logger, level="WARNING"): + result = await self.adapter.send_image_file( + "thread-bad-file", str(pathlib.Path(self._tmp.name) / "gone.png") + ) + self.assertFalse(result.success) + self.assertEqual(self.queue.entries(), []) + self.assertNotIn( + "media.deliver", + [frame["type"] for frame in self.connection.messages], + ) + + async def test_audio_rides_the_same_media_frame_instead_of_the_fallback(self): + """T3 renders audio as a download card — still strictly better than + the base class's "couldn't deliver the audio attachment" notice.""" + audio = pathlib.Path(self._tmp.name) / "reply.mp3" + audio.write_bytes(b"ID3 fake audio") + await self._start_turn("thread-audio", "turn-audio") + frames_before = len(self.connection.messages) + + result = await self.adapter.send_voice("thread-audio", str(audio)) + + self.assertTrue(result.success) + delivery = self.connection.messages[frames_before:][0] + self.assertEqual(delivery["type"], "media.deliver") + self.assertEqual(delivery["mimeType"], "audio/mpeg") + + class EnvEnablementTests(unittest.TestCase): """`home_channel` is the magic key that makes `get_home_channel` resolve.""" diff --git a/integrations/hermes-t3-gateway/tests/test_connection.py b/integrations/hermes-t3-gateway/tests/test_connection.py index a4095a8f5b..852a539536 100644 --- a/integrations/hermes-t3-gateway/tests/test_connection.py +++ b/integrations/hermes-t3-gateway/tests/test_connection.py @@ -64,7 +64,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): socket = FakeSocket( { "type": "connection.accepted", - "protocolVersion": 3, + "protocolVersion": 4, "instanceId": "provider-instance", "nickname": "Research", "credential": "persistent-secret", @@ -85,9 +85,9 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): socket = FakeSocket( { "type": "connection.accepted", - # A v2 server: the version policy stays fail-closed across the - # v3 bump, so this must not be silently accepted. - "protocolVersion": 2, + # A v3 server: the version policy stays fail-closed across the + # v4 bump, so this must not be silently accepted. + "protocolVersion": 3, "instanceId": "provider-instance", "nickname": "Research", } @@ -109,7 +109,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): "type": "connection.rejected", "code": "version-incompatible", "message": "upgrade required", - "expectedProtocolVersion": 3, + "expectedProtocolVersion": 4, } ) with self.assertRaises(connection.ConnectionRejected) as raised: @@ -149,14 +149,14 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): json.dumps( { "type": "ping", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": "server-ping-1", } ), json.dumps( { "type": "connection.accepted", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": hello_id, "instanceId": "provider-instance", "nickname": "Hermes", @@ -207,7 +207,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): return json.dumps( { "type": "connection.accepted", - "protocolVersion": 3, + "protocolVersion": 4, "requestId": self.sent[0]["requestId"], "instanceId": "provider-instance", "nickname": "Hermes", @@ -221,7 +221,7 @@ class ConnectionTests(unittest.IsolatedAsyncioTestCase): async def frames(): yield json.dumps({"type": "turn.start", "requestId": "turn-1"}) yield json.dumps( - {"type": "ping", "protocolVersion": 3, "requestId": "ping-1"} + {"type": "ping", "protocolVersion": 4, "requestId": "ping-1"} ) await released.wait() diff --git a/integrations/hermes-t3-gateway/tests/test_home.py b/integrations/hermes-t3-gateway/tests/test_home.py index ef2bb64f67..b2fb6e7aaf 100644 --- a/integrations/hermes-t3-gateway/tests/test_home.py +++ b/integrations/hermes-t3-gateway/tests/test_home.py @@ -216,7 +216,7 @@ class FrameTests(unittest.TestCase): created_at="2026-07-26T00:00:00Z", ) self.assertEqual(frame["type"], "home.deliver") - self.assertEqual(frame["protocolVersion"], 3) + self.assertEqual(frame["protocolVersion"], 4) self.assertEqual(frame["deliveryId"], "delivery-1") self.assertEqual(frame["threadId"], "home-thread") self.assertEqual(frame["kind"], "cron") @@ -241,9 +241,50 @@ class FrameTests(unittest.TestCase): self.assertTrue(len(frame["text"]) >= 1) def test_home_deliver_ack_is_an_accepted_server_command(self): - message = {"type": "home.deliver.ack", "protocolVersion": 3} + message = {"type": "home.deliver.ack", "protocolVersion": 4} self.assertEqual(protocol.validate_server_frame(message), message) + def test_build_media_delivery_reads_the_file_and_guesses_the_mime(self): + import base64 + + with tempfile.TemporaryDirectory() as tmp: + chart = pathlib.Path(tmp) / "chart.png" + chart.write_bytes(b"\x89PNG fake bytes") + frame = home.build_media_delivery( + thread_id="home-thread", + path=str(chart), + kind="cron", + label="Cron: nightly", + caption="Nightly chart", + ) + self.assertEqual(frame["type"], "media.deliver") + self.assertEqual(frame["kind"], "cron") + self.assertEqual(frame["name"], "chart.png") + self.assertEqual(frame["mimeType"], "image/png") + self.assertEqual(frame["sizeBytes"], len(b"\x89PNG fake bytes")) + self.assertEqual(base64.b64decode(frame["data"]), b"\x89PNG fake bytes") + self.assertEqual(frame["caption"], "Nightly chart") + self.assertTrue(frame["deliveryId"]) + # Self-contained on disk: the frame carries the bytes, not the path, + # so a queued copy survives the source temp file being reaped. + self.assertNotIn("path", frame) + + def test_build_media_delivery_fails_loudly_on_unreadable_or_oversized_files(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(OSError): + home.build_media_delivery( + thread_id="home-thread", + path=str(pathlib.Path(tmp) / "missing.png"), + ) + empty = pathlib.Path(tmp) / "empty.bin" + empty.write_bytes(b"") + # An empty or oversized payload must never reach the durable + # queue: T3 would reject it on every flush, forever. + with self.assertRaises(ValueError): + home.build_media_delivery( + thread_id="home-thread", path=str(empty) + ) + def test_hello_declares_its_connection_role(self): gateway = protocol.connection_hello( hermes_version="0.19.0", @@ -291,11 +332,15 @@ class MockDeliveryServer: } ) ) - elif message.get("type") == "home.deliver" and self.ack: + elif message.get("type") in {"home.deliver", "media.deliver"} and self.ack: self._outbox.append( json.dumps( { - "type": "home.deliver.ack", + "type": ( + "media.deliver.ack" + if message["type"] == "media.deliver" + else "home.deliver.ack" + ), "protocolVersion": protocol.PROTOCOL_VERSION, "deliveryId": message["deliveryId"], } @@ -362,7 +407,7 @@ class StandaloneSenderTests(unittest.IsolatedAsyncioTestCase): ) hello, delivery = server.sent self.assertEqual(hello["role"], "delivery") - self.assertEqual(hello["protocolVersion"], 3) + self.assertEqual(hello["protocolVersion"], 4) self.assertEqual( hello["authentication"], { @@ -399,7 +444,7 @@ class StandaloneSenderTests(unittest.IsolatedAsyncioTestCase): """No ack, no purge — the live gateway retries it on the next connect.""" server = MockDeliveryServer(ack=False) with self._serve(server), unittest.mock.patch.object( - home, "_deliver_over_short_lived_socket", return_value=False + home, "_deliver_over_short_lived_socket", return_value=set() ): result = await home.standalone_send(None, "home-thread", "Unacked brief") @@ -424,6 +469,79 @@ class StandaloneSenderTests(unittest.IsolatedAsyncioTestCase): self.assertTrue(result["success"]) self.assertEqual(server.sent[1]["threadId"], "home-thread") + async def test_standalone_send_delivers_media_files_as_media_frames(self): + """`deliver=t3` cron output with files rides the v4 media framing.""" + chart = pathlib.Path(self._tmp.name) / "chart.png" + chart.write_bytes(b"\x89PNG fake bytes") + server = MockDeliveryServer() + with self._serve(server): + result = await home.standalone_send( + None, + "home-thread", + "Cronjob Response: nightly\n(job_id: nightly)\n-------------\n\nDone.", + media_files=[(str(chart), False)], + ) + + self.assertTrue(result["success"]) + self.assertEqual( + [message["type"] for message in server.sent], + ["connection.hello", "home.deliver", "media.deliver"], + ) + media = server.sent[2] + # Media inherits the text's provenance so the chart gets the same + # badge as the brief it accompanies. + self.assertEqual(media["kind"], "cron") + self.assertEqual(media["label"], "Cron: nightly") + self.assertEqual(media["name"], "chart.png") + self.assertEqual(media["mimeType"], "image/png") + # Both frames were acked, so nothing stays queued. + self.assertEqual(home.HomeDeliveryQueue().entries(), []) + + async def test_standalone_send_skips_an_unreadable_media_file(self): + """One bad file must not sink the brief — and must never be queued.""" + server = MockDeliveryServer() + with self._serve(server), self.assertLogs(home.logger, level="WARNING"): + result = await home.standalone_send( + None, + "home-thread", + "Brief with a dead attachment", + media_files=[(str(pathlib.Path(self._tmp.name) / "gone.png"), False)], + ) + + self.assertTrue(result["success"]) + self.assertIn("skipped", result["detail"]) + self.assertEqual( + [message["type"] for message in server.sent], + ["connection.hello", "home.deliver"], + ) + self.assertEqual(home.HomeDeliveryQueue().entries(), []) + + async def test_unacked_media_stays_queued_for_the_next_connect(self): + """The durable lifecycle applies to media exactly as it does to text.""" + chart = pathlib.Path(self._tmp.name) / "chart.png" + chart.write_bytes(b"\x89PNG fake bytes") + + async def _refuse(_url): + raise ConnectionRefusedError("T3 is down") + + with unittest.mock.patch.object(connection, "_open_socket", _refuse): + result = await home.standalone_send( + None, + "home-thread", + "Nightly brief", + media_files=[(str(chart), False)], + ) + + self.assertTrue(result["success"]) + self.assertTrue(result["queued"]) + queued = home.HomeDeliveryQueue().entries() + self.assertEqual( + [entry["type"] for entry in queued], ["home.deliver", "media.deliver"] + ) + # The queued media frame is self-contained: bytes, not a path. + self.assertEqual(queued[1]["name"], "chart.png") + self.assertTrue(queued[1]["data"]) + class DesignationTests(unittest.TestCase): def test_saving_the_designation_mirrors_it_into_this_process(self): diff --git a/integrations/hermes-t3-gateway/tests/test_protocol.py b/integrations/hermes-t3-gateway/tests/test_protocol.py index 8438383241..081b98fb1f 100644 --- a/integrations/hermes-t3-gateway/tests/test_protocol.py +++ b/integrations/hermes-t3-gateway/tests/test_protocol.py @@ -66,7 +66,7 @@ def fake_hermes_skills(skills_list=None, skill_view=None): class ProtocolTests(unittest.TestCase): - def test_hello_matches_v3_contract(self): + def test_hello_matches_v4_contract(self): hello = protocol.connection_hello( hermes_version="0.19.0", authentication={"type": "enrollment-token", "token": "once"}, @@ -75,8 +75,10 @@ class ProtocolTests(unittest.TestCase): ) self.assertEqual(hello["type"], "connection.hello") self.assertEqual(hello["requestId"], "request-1") - self.assertEqual(hello["protocolVersion"], 3) - self.assertFalse(hello["capabilities"]["attachments"]) + self.assertEqual(hello["protocolVersion"], 4) + # v4 pins `attachments` to the literal true — it is part of the + # contract, not a negotiated option. + self.assertTrue(hello["capabilities"]["attachments"]) self.assertTrue(hello["capabilities"]["streaming"]) self.assertEqual(hello["model"], "gpt-5.6-terra") @@ -125,15 +127,15 @@ class ProtocolTests(unittest.TestCase): def test_server_frame_validation_is_closed(self): with self.assertRaisesRegex(ValueError, "unsupported"): - protocol.validate_server_frame({"type": "made.up", "protocolVersion": 3}) + protocol.validate_server_frame({"type": "made.up", "protocolVersion": 4}) with self.assertRaisesRegex(ValueError, "version"): - # Protocol v2 peers must upgrade before sending runtime frames. - protocol.validate_server_frame({"type": "ping", "protocolVersion": 2}) + # Protocol v3 peers must upgrade before sending runtime frames. + protocol.validate_server_frame({"type": "ping", "protocolVersion": 3}) def test_describe_frames_are_accepted_server_commands(self): for frame_type in ("describe.request", "skill.body.request"): with self.subTest(frame_type=frame_type): - message = {"type": frame_type, "protocolVersion": 3} + message = {"type": frame_type, "protocolVersion": 4} self.assertEqual(protocol.validate_server_frame(message), message) # ── describe.response ────────────────────────────────────────────── @@ -151,13 +153,13 @@ class ProtocolTests(unittest.TestCase): ) self.assertEqual(response["type"], "describe.response") self.assertEqual(response["requestId"], "describe-1") - self.assertEqual(response["protocolVersion"], 3) + self.assertEqual(response["protocolVersion"], 4) self.assertEqual(response["pluginVersion"], protocol.PLUGIN_VERSION) self.assertEqual(response["hermesVersion"], "0.19.0") self.assertEqual(response["model"], "gpt-5.6-terra") self.assertEqual(response["reasoningEffort"], "medium") self.assertEqual(response["skills"], skills) - self.assertFalse(response["capabilities"]["attachments"]) + self.assertTrue(response["capabilities"]["attachments"]) self.assertTrue(response["describedAt"].endswith("Z")) # Skill dicts are copied out: mutating the reply must not reach back # into whatever the caller passed in. @@ -282,7 +284,7 @@ class ProtocolTests(unittest.TestCase): ) self.assertEqual(response["type"], "skill.body.response") self.assertEqual(response["requestId"], "body-1") - self.assertEqual(response["protocolVersion"], 3) + self.assertEqual(response["protocolVersion"], 4) self.assertEqual(response["skillName"], "codex") self.assertEqual(response["markdown"], "# Codex\n\nDelegate coding.") @@ -373,6 +375,165 @@ class ProtocolTests(unittest.TestCase): ) ) + # ── media.deliver ────────────────────────────────────────────────── + + def test_media_deliver_encodes_the_payload_and_applies_every_wire_bound(self): + import base64 + + payload = b"\x89PNG fake bytes" + frame = protocol.media_deliver( + delivery_id_value="media-1", + thread_id="home-thread", + kind="cron", + label=" " + "L" * 400 + " ", + name="chart.png", + mime_type="image/png", + data=payload, + turn_id="turn-9", + caption="c" * (protocol.MAX_MEDIA_CAPTION_CHARS + 50), + created_at="2026-07-27T00:00:00Z", + ) + self.assertEqual(frame["type"], "media.deliver") + self.assertEqual(frame["protocolVersion"], 4) + self.assertEqual(frame["deliveryId"], "media-1") + self.assertEqual(frame["threadId"], "home-thread") + self.assertEqual(frame["turnId"], "turn-9") + self.assertEqual(frame["kind"], "cron") + self.assertEqual(len(frame["label"]), protocol.MAX_HOME_DELIVERY_LABEL_CHARS) + self.assertEqual(frame["name"], "chart.png") + self.assertEqual(frame["mimeType"], "image/png") + # `sizeBytes` and `data` are derived from the same bytes, so they can + # never disagree — and the payload round-trips exactly. + self.assertEqual(frame["sizeBytes"], len(payload)) + self.assertEqual(base64.b64decode(frame["data"]), payload) + self.assertEqual(len(frame["caption"]), protocol.MAX_MEDIA_CAPTION_CHARS) + self.assertEqual(frame["createdAt"], "2026-07-27T00:00:00Z") + + def test_media_deliver_omits_optional_fields_rather_than_sending_empty(self): + frame = protocol.media_deliver( + delivery_id_value="media-2", + thread_id="home-thread", + kind="message", + label="Hermes", + name="brief.pdf", + mime_type="application/pdf", + data=b"%PDF", + ) + self.assertNotIn("turnId", frame) + self.assertNotIn("caption", frame) + + def test_media_deliver_degrades_provenance_but_never_the_payload_shape(self): + frame = protocol.media_deliver( + delivery_id_value="media-3", + thread_id="home-thread", + kind="not-a-kind", + label=" ", + name=" ", + mime_type="", + data=b"x", + ) + # A misclassification must cost a badge, never a server rejection of a + # delivery the plugin has already queued. + self.assertEqual(frame["kind"], "other") + self.assertEqual(frame["label"], "Hermes") + self.assertEqual(frame["name"], "attachment.bin") + self.assertEqual(frame["mimeType"], "application/octet-stream") + + def test_media_deliver_requires_a_delivery_id(self): + with self.assertRaisesRegex(ValueError, "deliveryId"): + protocol.media_deliver( + delivery_id_value=" ", + thread_id="home-thread", + kind="message", + label="Hermes", + name="a.bin", + mime_type="application/octet-stream", + data=b"x", + ) + + def test_media_deliver_rejects_an_empty_or_oversized_payload(self): + # Truncation would corrupt the file, so unlike text these fail loudly + # instead of being clamped — and never reach the durable queue. + for data, pattern in ( + (b"", "non-empty"), + (b"x" * (protocol.MAX_MEDIA_BYTES + 1), "ceiling"), + ): + with self.subTest(size=len(data)): + with self.assertRaisesRegex(ValueError, pattern): + protocol.media_deliver( + delivery_id_value="media-4", + thread_id="home-thread", + kind="message", + label="Hermes", + name="big.bin", + mime_type="application/octet-stream", + data=data, + ) + + def test_media_deliver_ack_is_an_accepted_server_command(self): + message = {"type": "media.deliver.ack", "protocolVersion": 4} + self.assertEqual(protocol.validate_server_frame(message), message) + + # ── inbound turn attachments ─────────────────────────────────────── + + def test_turn_attachments_decode_base64_to_bytes(self): + import base64 + + message = { + "type": "turn.start", + "attachments": [ + { + "name": "notes.txt", + "mimeType": "text/plain", + "sizeBytes": 5, + "data": base64.b64encode(b"hello").decode("ascii"), + }, + {"name": "blob", "data": base64.b64encode(b"\x00\x01").decode()}, + ], + } + decoded = protocol.turn_attachments(message) + self.assertEqual( + decoded, + [ + {"name": "notes.txt", "mimeType": "text/plain", "data": b"hello"}, + # A missing MIME degrades to octet-stream, never empty. + { + "name": "blob", + "mimeType": "application/octet-stream", + "data": b"\x00\x01", + }, + ], + ) + + def test_a_frame_without_attachments_decodes_to_an_empty_list(self): + self.assertEqual(protocol.turn_attachments({"type": "turn.start"}), []) + + def test_malformed_turn_attachments_raise_rather_than_dropping_files(self): + # T3 validates against its schema before sending, so a bad entry here + # is version drift; silently losing a user's file is worse than a + # correlated protocol.error they can see. + for attachments in ( + "not-a-list", + [{"mimeType": "text/plain", "data": "aGk="}], # no name + [{"name": "x.txt"}], # no data + [{"name": "x.txt", "data": "!!! not base64 !!!"}], + [{"name": "x.txt", "data": ""}], + ): + with self.subTest(attachments=attachments): + with self.assertRaises(ValueError): + protocol.turn_attachments({"attachments": attachments}) + + def test_an_oversized_turn_attachment_is_rejected(self): + import base64 + + oversized = base64.b64encode( + b"x" * (protocol.MAX_MEDIA_BYTES + 1) + ).decode("ascii") + with self.assertRaisesRegex(ValueError, "ceiling"): + protocol.turn_attachments( + {"attachments": [{"name": "huge.bin", "data": oversized}]} + ) + if __name__ == "__main__": unittest.main()