Skip to content

The agent that grows with you

fix(gateway): drop a silence marker that ends a real reply

Tekniumfbb0d63a92de
diff --git a/gateway/response_filters.py b/gateway/response_filters.py
index d930075a2ed..0b8b993faca 100644
--- a/gateway/response_filters.py
+++ b/gateway/response_filters.py
@@ -82,6 +82,36 @@ def is_intentional_silence_response(response: Any) -> bool:
return any(c in LIVE_GATEWAY_SILENT_MARKERS for c in _canonical_silence_candidates(response))
+def _split_trailing_line(text: str) -> tuple[str, str]:
+ """``(head, last line)`` of ``text`` with trailing blank space ignored; head is ``""`` when
+ there is only one line."""
+ head, _, tail = text.rstrip().rpartition("\n")
+ return head.rstrip(), tail
+
+
+def strip_trailing_silence_marker(response: Any) -> Any:
+ """Drop a silence marker that closes a real reply on its own line.
+
+ ``"Here is the answer.\\n\\nNO_REPLY"`` delivers ``"Here is the answer."``: the model
+ answered, then also said it has nothing more to add, and the token is not meant for the
+ reader. A bare marker is returned unchanged (that is the silence verdict, decided by
+ :func:`is_intentional_silence_response`), and a marker inside a line is prose.
+ """
+ if not isinstance(response, str):
+ return response
+ head, tail = _split_trailing_line(response)
+ return head if head.strip() and is_intentional_silence_response(tail) else response
+
+
+def ends_with_partial_silence_marker(text: Any) -> bool:
+ """True while a streamed reply's last line could still become a trailing silence marker
+ (``"answer\\n\\nNO_RE"``), so a stream preview never shows a marker it later retracts."""
+ if not isinstance(text, str):
+ return False
+ head, tail = _split_trailing_line(text)
+ return bool(head.strip()) and is_partial_silence_marker(tail)
+
+
def is_autonomous_silence_response(response: Any) -> bool:
"""Loose silence matcher for autonomous lanes (cron, webhook).
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 423e41276c7..f0969d610bf 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -819,6 +819,7 @@ class GatewayStartupMixin:
from gateway.platforms.base import _strip_media_directives
from gateway.response_filters import (
is_intentional_silence_response, is_machinery_display_kind, silence_allowed,
+ strip_trailing_silence_marker,
)
from gateway.run import _sanitize_gateway_final_response
from gateway.run_turn import _unexpected_silence_reply
@@ -843,7 +844,8 @@ class GatewayStartupMixin:
silent_ok = silence_allowed(
prompt.get("display_kind"), (prompt.get("display_metadata") or {}).get("reply_expected"))
return "" if silent_ok else _unexpected_silence_reply()
- return _strip_media_directives(_sanitize_gateway_final_response(origin.platform, last["content"])).strip() or None
+ reply = strip_trailing_silence_marker(last["content"])
+ return _strip_media_directives(_sanitize_gateway_final_response(origin.platform, reply)).strip() or None
@staticmethod
def _start_hosted_room_worker_sync():
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 279d949a429..81dafa69034 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -78,7 +78,9 @@ class GatewayTurnPersistenceMixin:
# A queued (/queue) chain's TERMINAL turn owns the silence verdict, not the event that
# opened the chain: an internal follow-up, or a message not addressed to the bot, may go
# silent; any other human one must not.
- from gateway.response_filters import is_machinery_display_kind, silence_allowed
+ from gateway.response_filters import (
+ is_machinery_display_kind, silence_allowed, strip_trailing_silence_marker,
+ )
from gateway.run_turn import _unexpected_silence_reply
_silence_kind = agent_result.get("queued_terminal_display_kind", persist_user_display_kind)
_silence_reply_expected = agent_result.get("queued_terminal_reply_expected", reply_expected)
@@ -122,6 +124,7 @@ class GatewayTurnPersistenceMixin:
# Normalize empty responses: surface errors, partial failures, and work-without-text.
# Fix for #18765.
if not _intentional_silence:
+ response = strip_trailing_silence_marker(response)
response = _normalize_empty_agent_response(agent_result, response, history_len=len(history))
response = _sanitize_gateway_final_response(source.platform, response)
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 9e59421a422..a5e099129ff 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -423,9 +423,9 @@ def _admission_outcome(authority, admission_id, fallback=None):
# A successful bare silence marker is a delivery decision (same rule as the gateway and
# the live Bot Chat completion): the turn stays in the target's transcript, the sender
# never sees the marker as prose.
- from gateway.response_filters import is_intentional_silence_response
- if status == 'settled' and is_intentional_silence_response(reply):
- reply = ''
+ from gateway.response_filters import is_intentional_silence_response, strip_trailing_silence_marker
+ if status == 'settled':
+ reply = '' if is_intentional_silence_response(reply) else strip_trailing_silence_marker(reply)
elif fallback is not None and fallback.get('status') in {'settled', 'failed'}:
status = fallback['status']
return status, reply
diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.py
index 8fb33ff3954..92a477b6be1 100644
--- a/gateway/stream_consumer.py
+++ b/gateway/stream_consumer.py
@@ -29,7 +29,9 @@ from gateway.config import (
DEFAULT_STREAMING_CURSOR as _DEFAULT_STREAMING_CURSOR)
from gateway.response_filters import (
is_intentional_silence_response as _is_intentional_silence_response,
- is_partial_silence_marker as _is_partial_silence_marker)
+ is_partial_silence_marker as _is_partial_silence_marker,
+ ends_with_partial_silence_marker as _ends_with_partial_silence_marker,
+ strip_trailing_silence_marker as _strip_trailing_silence_marker)
from gateway.stream_consumer_directives import has_pending_media_directive, strip_image_tags_for_display
from gateway.stream_consumer_fences import ensure_closed_code_fences
from gateway.stream_consumer_transport import StreamTransportMixin
@@ -784,12 +786,16 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
or (len(self._accumulated) >= self.cfg.buffer_threshold
and not self._flood_strikes))
# Defer mid-stream edits while the buffer could still resolve to a silence
- # marker ("NO"→"NO_REPLY"); got_done always resolves the buffer.
+ # marker ("NO"→"NO_REPLY"), or a reply's last line could still become a trailing one
+ # ("answer\n\nNO"); got_done always resolves the buffer.
# Likewise defer while a MEDIA:/[[…]] directive is still being typed: the cleaner
# only strips complete deliverable tags, so a half-streamed one would be shown, and
# a media-only reply cleans to "" at finish, which never edits the bubble away.
cleaned = self._clean_for_display(self._accumulated)
return (should_edit and not _is_partial_silence_marker(cleaned)
+ # Raw buffer: the cleaner already drops a COMPLETE trailing marker, but an interim
+ # frame carries the cursor after it, which hides the marker from the cleaner.
+ and not _ends_with_partial_silence_marker(self._accumulated)
and not has_pending_media_directive(cleaned))
async def _split_first_send(self, tick: _Tick) -> bool:
@@ -1022,6 +1028,8 @@ class GatewayStreamConsumer(StreamTransportMixin, StreamFallbackMixin, StreamThi
Image tags are the ones the non-streaming path's ``extract_images`` split attaches: once a
tag becomes an attachment it must not also render as text — on Discord ``![alt](url)``
shows as ``!alt`` plus an unfurl (#141806). The tag is removed without trimming the text
- around it, so interim frames stay prefix-stable.
+ around it, so interim frames stay prefix-stable. A silence marker closing the reply on its own
+ line is dropped (``strip_trailing_silence_marker``); a bare marker is left for the silence check.
"""
- return strip_image_tags_for_display(_BasePlatformAdapter.strip_media_directives_for_display(text))
+ return _strip_trailing_silence_marker(
+ strip_image_tags_for_display(_BasePlatformAdapter.strip_media_directives_for_display(text)))
diff --git a/gateway/stream_consumer_fallback.py b/gateway/stream_consumer_fallback.py
index f6c571747c6..461f987b85d 100644
--- a/gateway/stream_consumer_fallback.py
+++ b/gateway/stream_consumer_fallback.py
@@ -316,10 +316,11 @@ class StreamFallbackMixin:
if not self._fallback_final_send:
await self._try_strip_cursor()
visible = self._fallback_prefix or self._visible_prefix()
- tail = self._accumulated
+ # Clean the whole buffer before cutting: a trailing silence marker cut off on its own
+ # would read as a bare marker and survive the cleaner.
+ tail = self._clean_for_display(self._accumulated)
if visible and tail.startswith(visible):
tail = tail[len(visible):].lstrip()
- tail = self._clean_for_display(tail)
if not tail.strip():
return
try:
diff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.py
index a23f644b42d..a6b89689a9f 100644
--- a/hermes_cli/subcommands/peer.py
+++ b/hermes_cli/subcommands/peer.py
@@ -429,9 +429,8 @@ def _peer_dm(args, message: str, peer_name: str, profile: str | None, base: str,
# Bot Chat completion, the Desktop bot_relay.deliver RPC and the one-shot
# local `hermes chat -Q` transport (tools/bot_mode_dm.py) — this is the
# 4th Bot Mode delivery door and was missing the same check.
- from gateway.response_filters import is_intentional_silence_response
- if is_intentional_silence_response(reply):
- reply = ""
+ from gateway.response_filters import is_intentional_silence_response, strip_trailing_silence_marker
+ reply = "" if is_intentional_silence_response(reply) else strip_trailing_silence_marker(reply)
payload = {"peer": peer_name, "profile": profile,
"session_id": result.get("session_id") or session_id, "reply": reply}
return _emit(args, payload, [reply or "(no reply)"])
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index 961e828ef3f..094c1169ff2 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -24,8 +24,10 @@ def _bot_mode_delivery_text(response: Any, *, successful: bool) -> Any:
Mode delivery boundary. Failed turns intentionally fail open so their
diagnostic text is never swallowed.
"""
- from gateway.response_filters import is_intentional_silence_response
- return "" if successful and is_intentional_silence_response(response) else response
+ from gateway.response_filters import is_intentional_silence_response, strip_trailing_silence_marker
+ if not successful:
+ return response
+ return "" if is_intentional_silence_response(response) else strip_trailing_silence_marker(response)
def _is_bot_mode_session(session: dict) -> bool: