Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
70 changes: 70 additions & 0 deletions docs/research/2026-11-19-telegram-checkmark-after-media.md
Original file line number Diff line number Diff line change
@@ -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:<path>`
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.<id>.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).
147 changes: 145 additions & 2 deletions hermes_plugin_kit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}


Expand Down Expand Up @@ -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 {
Expand All @@ -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
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand Down
15 changes: 15 additions & 0 deletions tests/test_hermes_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading