From b9b16e20cc2c0bbe22f828659d1581a4387de85b Mon Sep 17 00:00:00 2001 From: Offending Commit Date: Thu, 19 Nov 2026 10:43:41 -0600 Subject: [PATCH] feat(media): let an origin attachment be the turn's reply (as_reply) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After a successful deliver_media, the final reply is replaced with a lone "✅" because Hermes refuses a bare NO_REPLY on a turn that expects a reply. On Telegram that ✅ arrives as a second message and reads as a reaction. deliver_media(..., as_reply=True) to the origin target now sends nothing at tool time. transform_media_delivery_output makes the attachment the final reply: the model's own words (minus silence markers, copied send notes and repeated MEDIA lines) followed by the MEDIA directive, so a NO_REPLY turn sends the voice note alone. Hermes delivers a MEDIA-only reply as one attachment with no text (BasePlatformAdapter._extract_response_content). If the reply never carries it (failed, interrupted or empty turn, or another transform won), clear_media_delivery_state, which Hermes fires after every turn, sends it directly, so a deferred attachment is never lost. Opt-in because success now means "accepted", not "sent": sirens' video lane records a confirmed-send receipt and must keep the direct send. Explicit targets and spoiler media always send directly; existing callers are unchanged. Claude-Session: https://claude.ai/code/session_01B6XeAXSoBKaEUbBRt5xcfB --- AGENTS.md | 5 + README.md | 33 ++++ ...26-11-19-telegram-checkmark-after-media.md | 70 +++++++++ hermes_plugin_kit/__init__.py | 147 +++++++++++++++++- tests/test_hermes_contract.py | 15 ++ tests/test_kit.py | 139 +++++++++++++++++ 6 files changed, 407 insertions(+), 2 deletions(-) create mode 100644 docs/research/2026-11-19-telegram-checkmark-after-media.md diff --git a/AGENTS.md b/AGENTS.md index 64c1f0c..481233a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,11 @@ plugin. `transform_llm_output` hook and `clear_media_delivery_state` as `on_session_end`; they must not recreate those contracts or substitute OpenClaw response shapes. +- `deliver_media(..., as_reply=True)` to `origin` defers the attachment into + the turn's final reply instead of sending it plus a ✅. It must stay opt-in: + its `success` means "accepted", not "sent". `clear_media_delivery_state` + must keep sending any deferred attachment the reply did not carry, so a + failed or interrupted turn never loses it. - Use `tool_name(namespace, verb, noun)` for new tools and prefer explicit verbs such as `read`, `write`, and `patch`. Do not use Hermes agent-loop names (`memory`, `todo`, `session_search`, `delegate_task`) as plugin tools. diff --git a/README.md b/README.md index 2214b72..46a483e 100644 --- a/README.md +++ b/README.md @@ -765,6 +765,39 @@ a reply and sends the user a warning instead. Failed delivery does not arm suppression, and `on_session_end` clears any unconsumed marker. These are Hermes-agent lifecycle and response contracts; they are not OpenClaw shapes. +### Media as the reply (`as_reply=True`) + +The ✅ is still a second message. When the attachment is the answer to the +user's own message, pass `as_reply=True` with the `origin` target: + +```python +result = deliver_media( + MediaPayload(path, MediaType.VOICE), + target="origin", + as_reply=True, + **runtime_context, +) +# result.deferred is True: nothing has been sent yet. +``` + +Nothing is sent at tool time. `transform_media_delivery_output` makes the +attachment the turn's final reply instead: the model's own words, if any, +followed by the `MEDIA:` directive. Silence markers (`NO_REPLY`), copied +`[Sent voice message]` notes and repeated `MEDIA:` lines are dropped, so a +model that answers `NO_REPLY` sends the attachment alone. Several `as_reply` +calls in one turn all ride the same reply, in order. + +If the final reply never carries the attachment (the turn failed or was +interrupted, the reply was empty, or another plugin's `transform_llm_output` +won), `clear_media_delivery_state` sends it directly when the turn ends, which +Hermes reports through `on_session_end` after every turn. A deferred attachment +is therefore never lost; at worst it arrives the old way. + +Costs: the attachment arrives when the turn ends, not when the tool ran, and +`success` means "accepted for the reply", so a caller that records a confirmed +send (a durable receipt, for example) must not use `as_reply`. Explicit targets +and `spoiler=True` media always send directly. + For non-media host calls, `invoke_host_tool` remains the lower-level seam. `invoke_host_tool` resolves the supported direct host handler and wraps the nested operation with Hermes `pre_tool_call` and `post_tool_call` hooks. A blocking hook diff --git a/docs/research/2026-11-19-telegram-checkmark-after-media.md b/docs/research/2026-11-19-telegram-checkmark-after-media.md new file mode 100644 index 0000000..f70c813 --- /dev/null +++ b/docs/research/2026-11-19-telegram-checkmark-after-media.md @@ -0,0 +1,70 @@ +# Why a ✅ follows every Telegram media send (2026-11-19) + +## Symptom + +After a member sends a voice memo or image on Telegram, a separate message +holding only "✅" arrives. Telegram shows a lone emoji large, so it reads as a +reaction. + +## Cause + +`transform_media_delivery_output` replaces the turn's final reply with +`MEDIA_DELIVERED_REPLY` ("✅") after any successful `deliver_media` +(offendingcommit/hermes-plugin-kit#43, 2026-10-30). It replaced `NO_REPLY` +because Hermes refuses a bare silence marker on a turn that expects a reply +and sends a warning instead. + +Live evidence, `hermes-private` Amber log, 2026-11-18 22:31 UTC: +`media_delivery_completed … success=True`, `media_final_response_suppression_armed`, +`media_final_response_suppressed original_chars=8` (the model wrote `NO_REPLY`, +as persona-voice's `response_contract` tells it to), then +`Turn ended … response_len=1`. + +## Ruled out (Hermes v0.23.0, upstream 2bd378ed, read in the pod) + +- Native Telegram reactions: `plugins/platforms/telegram/adapter.py` + `_reactions_enabled` reads `TELEGRAM_REACTIONS` then `extra.reactions`; unset + for amber, beatrice and dizzy, and the effective config has + `telegram.reactions: false`. No reaction calls in any container log. +- Agent-initiated reactions: `send_message(action="react")` needs + `add_reaction` on the adapter; the Telegram adapter has none. +- A second process on the same bot: token hashes differ across every + hermes-agent pod. + +## Hermes facts the fix relies on + +- `agent/turn_finalizer.py` `apply_llm_output_transform` fires + `transform_llm_output` once per turn, first string wins, and returns early + on an empty `final_response`. +- `BasePlatformAdapter._extract_response_content` extracts `MEDIA:` tags from + the final reply; a reply that is only `[[audio_as_voice]]\nMEDIA:` + becomes one voice note with no text and no recovery notice. Tagged media is + not deduplicated against history (only bare paths are). +- Final-reply media and `send_message` use the same + `validate_media_delivery_path`. +- Plugin `on_session_end` fires at the end of every turn with + `completed/failed/interrupted` (`agent/turn_finalizer.py`). +- `silence_allowed` permits `NO_REPLY` only on machinery turns, unaddressed + messages, or a channel with `channel_overrides..allow_silence: true`. +- An empty reply after tool work becomes a "work done" notice + (`gateway/run.py` `_normalize_empty_agent_response`). + +## Options weighed + +1. Media is the reply (chosen by the owner, 2026-11-19): opt-in + `deliver_media(as_reply=True)`; one message, no ✅. Costs: arrives at turn + end; `success` means accepted. Turn-end fallback sends directly. +2. `allow_silence` on the private DMs plus `NO_REPLY`: lets the model go silent + on any healthy turn in those chats; the kit cannot see which chats opted in. +3. Let the model's text through: still two messages, and the model writes + `NO_REPLY` there, so it would need a filler line. +4. Leave the ✅. + +## Not checked + +- A live turn with the change (needs the persona-voice/sirens pin bumps and an + infra promotion). +- sirens' video lane: it records a confirmed-send receipt, so it must keep the + direct send. +- Whether another plugin's `transform_llm_output` returns a string before the + kit's on these profiles (the 2026-11-18 log shows memory_sync returning None). diff --git a/hermes_plugin_kit/__init__.py b/hermes_plugin_kit/__init__.py index e65f667..4ef718e 100644 --- a/hermes_plugin_kit/__init__.py +++ b/hermes_plugin_kit/__init__.py @@ -186,6 +186,9 @@ def register(ctx): _MEDIA_DELIVERY_STATE_TTL_SECONDS = 300.0 _MEDIA_DELIVERY_STATE: dict[str, float] = {} _MEDIA_DELIVERY_STATE_LOCK = threading.Lock() +# Media an ``as_reply`` delivery left for the turn's final reply, keyed by both +# session_id and task_id (one shared entry, so consuming either key consumes it). +_PENDING_REPLY_MEDIA: dict[str, "_PendingReplyMedia"] = {} _TELEGRAM_SPOILER_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} @@ -724,6 +727,8 @@ class MediaDeliveryResult: path: Path host_result: dict[str, Any] spoiler: bool = False + # True when nothing was sent yet: the attachment rides this turn's final reply. + deferred: bool = False def as_dict(self) -> dict[str, Any]: return { @@ -734,9 +739,19 @@ def as_dict(self) -> dict[str, Any]: "path": str(self.path), "host_result": self.host_result, "spoiler": self.spoiler, + "deferred": self.deferred, } +@dataclass +class _PendingReplyMedia: + created_at: float + keys: tuple[str, ...] + host_target: str + context: dict[str, Any] + messages: list[str] + + # --------------------------------------------------------------------------- # Tool naming # --------------------------------------------------------------------------- @@ -1956,6 +1971,12 @@ def _prune_media_delivery_state(now: float) -> None: ] for key in expired: _MEDIA_DELIVERY_STATE.pop(key, None) + for key in [ + key + for key, entry in _PENDING_REPLY_MEDIA.items() + if now - entry.created_at > _MEDIA_DELIVERY_STATE_TTL_SECONDS + ]: + _PENDING_REPLY_MEDIA.pop(key, None) def _mark_media_delivery_success(context: dict[str, Any]) -> None: @@ -1983,6 +2004,60 @@ def _mark_media_delivery_success(context: dict[str, Any]) -> None: ) +def _defer_media_to_reply( + media: MediaPayload, resolved: ResolvedDeliveryTarget, context: dict[str, Any] +) -> bool: + """Keep ``media`` for this turn's final reply; False when the turn has no identity.""" + keys = _media_delivery_context_ids(context) + if not keys: + return False + now = time.monotonic() + with _MEDIA_DELIVERY_STATE_LOCK: + _prune_media_delivery_state(now) + entry = next((_PENDING_REPLY_MEDIA[k] for k in keys if k in _PENDING_REPLY_MEDIA), None) + if entry is None: + entry = _PendingReplyMedia(now, keys, resolved.host_target, dict(context), []) + entry.messages.append(media.to_message()) + for key in (*entry.keys, *keys): + _PENDING_REPLY_MEDIA[key] = entry + entry.keys = tuple(dict.fromkeys((*entry.keys, *keys))) + return True + + +def _pop_pending_reply_media(*context_ids: str) -> _PendingReplyMedia | None: + with _MEDIA_DELIVERY_STATE_LOCK: + _prune_media_delivery_state(time.monotonic()) + entry = next( + (_PENDING_REPLY_MEDIA[k] for k in context_ids if k and k in _PENDING_REPLY_MEDIA), + None, + ) + if entry is not None: + for key in entry.keys: + _PENDING_REPLY_MEDIA.pop(key, None) + _MEDIA_DELIVERY_STATE.pop(key, None) + return entry + + +# shortcut: mirrors Hermes' gateway.response_filters.LIVE_GATEWAY_SILENT_MARKERS without +# importing the gateway; the contract suite pins it to the host's own set. +_SILENCE_MARKERS = frozenset({"[SILENT]", "SILENT", "NO_REPLY", "NO REPLY", "[静默]", "静默", "[沉默]", "沉默"}) +_MEDIA_REPLY_LINE = re.compile(r"(?:MEDIA:\S+|\[\[(?:audio_as_voice|as_document)\]\])") + + +def _reply_with_pending_media(response_text: str, entry: _PendingReplyMedia) -> str: + """The model's own words, minus silence markers, copied send notes and media + directives, followed by the deferred attachments.""" + kept = [ + line + for line in str(response_text or "").splitlines() + if line.strip() not in _SILENCE_MARKERS + and not _MEDIA_MIRROR_LINE.fullmatch(line.strip()) + and not _MEDIA_REPLY_LINE.fullmatch(line.strip()) + ] + text = re.sub(r"\n{3,}", "\n\n", "\n".join(kept)).strip() + return "\n".join(filter(None, (text, *entry.messages))) + + def strip_media_mirror_lines(response_text: str) -> str | None: """Remove whole lines that copy Hermes' sent-media history notes from a final reply. @@ -2014,6 +2089,15 @@ def transform_media_delivery_output( context_id = str(session_id or "").strip() if not context_id: return None + pending = _pop_pending_reply_media(context_id) + if pending is not None: + reply = _reply_with_pending_media(response_text, pending) + logging.getLogger("hermes_plugin_kit").info( + "event=media_reply_attached attachments=%d original_chars=%d", + len(pending.messages), + len(str(response_text or "")), + ) + return reply now = time.monotonic() with _MEDIA_DELIVERY_STATE_LOCK: _prune_media_delivery_state(now) @@ -2032,7 +2116,16 @@ def clear_media_delivery_state( task_id: str = "", **_: Any, ) -> None: - """Hermes ``on_session_end`` cleanup for an unconsumed suppression marker.""" + """Hermes ``on_session_end`` (fired after every turn) cleanup. + + Drops an unconsumed suppression marker. Media an ``as_reply`` delivery left + for a final reply that never carried it (a failed, interrupted or empty + turn, or another plugin's rewrite won) is sent directly instead, so a + deferred attachment is never lost. + """ + pending = _pop_pending_reply_media(str(session_id or "").strip(), str(task_id or "").strip()) + if pending is not None: + _send_pending_reply_media(pending) context_ids = tuple( dict.fromkeys( value @@ -2189,13 +2282,42 @@ async def send() -> dict[str, Any]: return _run_async(send()) +def _send_pending_reply_media(entry: _PendingReplyMedia) -> None: + log = logging.getLogger("hermes_plugin_kit") + for message in entry.messages: + try: + raw = invoke_host_tool( + "send_message", + {"action": "send", "target": entry.host_target, "message": message}, + **entry.context, + ) + success = _host_result_fields(raw)[0] == "success" + except Exception as exc: # the turn is over; log, never raise into the host + log.warning("event=media_reply_fallback_failed error=%s", type(exc).__name__) + continue + (log.info if success else log.warning)( + "event=media_reply_fallback_sent target=%s success=%s", + _display_delivery_target(entry.host_target), + success, + ) + + def deliver_media( media: MediaPayload, *, target: str | ResolvedDeliveryTarget = "origin", + as_reply: bool = False, **context: Any, ) -> MediaDeliveryResult: - """Deliver typed local media through Hermes' guarded host messaging seam.""" + """Deliver typed local media through Hermes' guarded host messaging seam. + + ``as_reply=True`` with the ``origin`` target sends nothing now: the + attachment becomes this turn's final reply (``transform_media_delivery_output`` + appends it), so the chat gets the media alone instead of the media plus a + separate confirmation. The result has ``deferred=True``. If the final reply + never carries it, ``clear_media_delivery_state`` sends it directly at turn + end. Spoiler media and explicit targets always send directly. + """ if not isinstance(media, MediaPayload): raise TypeError("media must be a MediaPayload") if not media.path.is_file() or media.path.stat().st_size <= 0: @@ -2206,6 +2328,27 @@ def deliver_media( else resolve_delivery_target(target) ) log = logging.getLogger("hermes_plugin_kit") + if ( + as_reply + and resolved.requested == "origin" + and not media.spoiler + and _defer_media_to_reply(media, resolved, context) + ): + log.info( + "event=media_delivery_deferred target=%s media_type=%s path=%s", + resolved.display, + media.media_type.value, + media.path, + ) + return MediaDeliveryResult( + success=True, + requested_target=resolved.requested, + display_target=resolved.display, + media_type=media.media_type, + path=media.path, + host_result={"deferred": "final_reply"}, + deferred=True, + ) log.info( "event=media_delivery_started target=%s media_type=%s path=%s", resolved.display, diff --git a/tests/test_hermes_contract.py b/tests/test_hermes_contract.py index 8c7b89f..f1be51a 100644 --- a/tests/test_hermes_contract.py +++ b/tests/test_hermes_contract.py @@ -696,6 +696,21 @@ def test_media_delivered_reply_is_not_a_hermes_silence_marker(self) -> None: self.assertTrue(is_intentional_silence_response("NO_REPLY")) self.assertFalse(is_intentional_silence_response(hpk.MEDIA_DELIVERED_REPLY)) + def test_kit_silence_markers_match_the_host(self) -> None: + """A deferred-media reply drops the model's silence marker using the host's own set.""" + from gateway.response_filters import LIVE_GATEWAY_SILENT_MARKERS # type: ignore + + self.assertEqual(hpk._SILENCE_MARKERS, frozenset(LIVE_GATEWAY_SILENT_MARKERS)) + + def test_deferred_media_reply_is_delivered_as_a_voice_note_alone(self) -> None: + """The final reply an as_reply delivery produces parses to one voice attachment, no text.""" + from gateway.platforms.base import BasePlatformAdapter # type: ignore + + reply = hpk.MediaPayload("/m/memo.ogg", hpk.MediaType.VOICE).to_message() + media, text = BasePlatformAdapter.extract_media(reply) + self.assertEqual(media, [("/m/memo.ogg", True)]) + self.assertEqual(text.strip(), "") + def test_strip_media_mirror_lines_matches_every_hermes_mirror_shape(self) -> None: """Each note Hermes' send_message writes into history must be strippable.""" from tools.send_message_tool import _describe_media_for_mirror # type: ignore diff --git a/tests/test_kit.py b/tests/test_kit.py index 18ea8c0..59533e7 100644 --- a/tests/test_kit.py +++ b/tests/test_kit.py @@ -1352,6 +1352,145 @@ def test_session_end_clears_unconsumed_delivery_state(self) -> None: ) ) + def _origin_modules(self) -> dict: + session_context = types.ModuleType("gateway.session_context") + values = {"HERMES_SESSION_PLATFORM": "telegram", "HERMES_SESSION_CHAT_ID": "8670382527"} + session_context.get_session_env = lambda name, default="": values.get(name, default) + gateway = types.ModuleType("gateway") + gateway.__path__ = [] + gateway.session_context = session_context + return {"gateway": gateway, "gateway.session_context": session_context} + + def test_as_reply_origin_media_becomes_the_final_reply(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "memo.ogg" + path.write_bytes(b"OggS" + b"\x00" * 16) + with patch.dict(sys.modules, self._origin_modules()), patch.object( + hpk, "invoke_host_tool" + ) as invoke: + result = hpk.deliver_media( + hpk.MediaPayload(path, hpk.MediaType.VOICE), + as_reply=True, + session_id="session-1", + task_id="task-1", + ) + + invoke.assert_not_called() + self.assertTrue(result.success) + self.assertTrue(result.deferred) + self.assertEqual(result.display_target, "telegram:…2527") + self.assertEqual(result.host_result, {"deferred": "final_reply"}) + self.assertEqual( + hpk.transform_media_delivery_output(response_text="NO_REPLY", session_id="session-1"), + f"[[audio_as_voice]]\nMEDIA:{path}", + ) + self.assertIsNone( + hpk.transform_media_delivery_output(response_text="next turn", session_id="session-1") + ) + + def test_as_reply_keeps_the_model_words_and_drops_copied_media_lines(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "memo.ogg" + path.write_bytes(b"OggS" + b"\x00" * 16) + with patch.dict(sys.modules, self._origin_modules()): + hpk.deliver_media( + hpk.MediaPayload(path, hpk.MediaType.VOICE), + as_reply=True, + session_id="session-1", + ) + + self.assertEqual( + hpk.transform_media_delivery_output( + response_text=f"Here you go.\n[Sent voice message]\n[[audio_as_voice]]\nMEDIA:{path}", + session_id="session-1", + ), + f"Here you go.\n[[audio_as_voice]]\nMEDIA:{path}", + ) + + def test_as_reply_carries_every_deferred_attachment_in_order(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + memo = Path(tmp) / "memo.ogg" + memo.write_bytes(b"OggS" + b"\x00" * 16) + pic = Path(tmp) / "pic.png" + pic.write_bytes(b"\x89PNG" + b"\x00" * 16) + with patch.dict(sys.modules, self._origin_modules()): + hpk.deliver_media( + hpk.MediaPayload(memo, hpk.MediaType.VOICE), as_reply=True, session_id="session-1" + ) + hpk.deliver_media(hpk.MediaPayload(pic), as_reply=True, session_id="session-1") + + self.assertEqual( + hpk.transform_media_delivery_output(response_text="NO_REPLY", session_id="session-1"), + f"[[audio_as_voice]]\nMEDIA:{memo}\nMEDIA:{pic}", + ) + + def test_turn_end_sends_deferred_media_the_reply_never_carried(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "memo.ogg" + path.write_bytes(b"OggS" + b"\x00" * 16) + with patch.dict(sys.modules, self._origin_modules()): + hpk.deliver_media( + hpk.MediaPayload(path, hpk.MediaType.VOICE), + as_reply=True, + session_id="session-1", + task_id="task-1", + ) + # A failed turn never runs the transform; compression may also rotate session_id. + with patch.object( + hpk, "invoke_host_tool", return_value=json.dumps({"success": True}) + ) as invoke: + hpk.clear_media_delivery_state(session_id="session-rotated", task_id="task-1") + hpk.clear_media_delivery_state(session_id="session-1", task_id="task-1") + + invoke.assert_called_once_with( + "send_message", + { + "action": "send", + "target": "telegram:8670382527", + "message": f"[[audio_as_voice]]\nMEDIA:{path}", + }, + session_id="session-1", + task_id="task-1", + ) + self.assertIsNone( + hpk.transform_media_delivery_output(response_text="next turn", session_id="session-1") + ) + + def test_turn_end_sends_nothing_once_the_reply_carried_the_media(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "memo.ogg" + path.write_bytes(b"OggS" + b"\x00" * 16) + with patch.dict(sys.modules, self._origin_modules()): + hpk.deliver_media( + hpk.MediaPayload(path, hpk.MediaType.VOICE), as_reply=True, session_id="session-1" + ) + hpk.transform_media_delivery_output(response_text="NO_REPLY", session_id="session-1") + with patch.object(hpk, "invoke_host_tool") as invoke: + hpk.clear_media_delivery_state(session_id="session-1") + + invoke.assert_not_called() + + def test_as_reply_to_an_explicit_target_still_sends_directly(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "memo.ogg" + path.write_bytes(b"OggS" + b"\x00" * 16) + with patch.object( + hpk, "invoke_host_tool", return_value=json.dumps({"success": True}) + ) as invoke: + result = hpk.deliver_media( + hpk.MediaPayload(path, hpk.MediaType.VOICE), + target="telegram:8670382527", + as_reply=True, + session_id="session-1", + ) + + invoke.assert_called_once() + self.assertFalse(result.deferred) + self.assertEqual( + hpk.transform_media_delivery_output(response_text="NO_REPLY", session_id="session-1"), + "✅", + ) + def test_delivery_result_redacts_raw_route_from_host_errors(self) -> None: with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "memo.ogg"