Skip to content

The agent that grows with you

fix(gateway): suppress leaked terminal EOS tokens

Chris Cush2bf7a4aa9534
diff --git a/gateway/run.py b/gateway/run.py
index 68ec17950f8..5cabf97da4d 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -700,6 +700,15 @@ def _sanitize_gateway_final_response(platform: Any, text: str) -> str:
text = _sanitize_surrogates(str(text))
+ # Some OpenAI-compatible providers leak their exact end-of-sequence control token into
+ # ``final_response`` even though finish_reason is already ``stop``. It is transport metadata,
+ # not an assistant message; without filtering, chat adapters send a literal ``<|eos|>`` bubble.
+ # Reuse the MEDIA boundary's exact, terminal-only recognizer (#111046 / #111348): examples
+ # mentioning the token mid-response and non-exact variants remain byte-identical.
+ _eos_start = _terminal_sentinel_start(text)
+ if _eos_start >= 0:
+ text = text[:_eos_start].rstrip()
+
# Cancellation metadata, not prose; ACP/TUI already suppress this sentinel, chat surfaces should too.
# See #7921.
if str(text).strip().startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX):
@@ -2157,6 +2166,7 @@ from gateway.run_profile_reconcile import GatewayProfileReconcileMixin
from gateway.platforms.base import (
BasePlatformAdapter,
_reply_anchor_for_event,
+ _terminal_sentinel_start,
)
from gateway.platforms.event import MessageEvent, MessageType
from gateway.restart import (
diff --git a/tests/gateway/test_telegram_noise_filter.py b/tests/gateway/test_telegram_noise_filter.py
index bb453783a68..9a716fa437c 100644
--- a/tests/gateway/test_telegram_noise_filter.py
+++ b/tests/gateway/test_telegram_noise_filter.py
@@ -253,6 +253,29 @@ def test_chat_gateways_drop_interrupt_sentinel(platform):
assert _sanitize_gateway_final_response("local", sentinel) == sentinel
[email protected]("platform", [*CHAT_PLATFORMS, Platform.BLUEBUBBLES])
+ ("raw", "expected"),
+ [
+ ("<|eos|>", ""),
+ ("<|eos|><|eos|>\n", ""),
+ ("normal answer<|eos|>", "normal answer"),
+ ("normal answer<|eos|> \n", "normal answer"),
+ ("literal <|eos|> in the middle stays visible", "literal <|eos|> in the middle stays visible"),
+ ("case variant remains literal: <|EOS|>", "case variant remains literal: <|EOS|>"),
+ ("inline code remains literal: `<|eos|>`", "inline code remains literal: `<|eos|>`"),
+ ],
+)
+def test_chat_gateways_strip_terminal_eos_control_tokens(platform, raw, expected):
+ """Provider EOS control tokens are transport metadata, never user-facing chat bubbles."""
+ assert _sanitize_gateway_final_response(platform, raw) == expected
+
+
+def test_local_surface_keeps_terminal_eos_control_token():
+ """Raw/programmatic surfaces retain provider output byte-for-byte."""
+ assert _sanitize_gateway_final_response("local", "normal answer<|eos|>") == "normal answer<|eos|>"
+
+
def test_telegram_status_sanitizes_raw_provider_security_errors():
"""Provider policy/security bodies should be replaced before chat delivery."""
raw = (