Skip to content

The agent that grows with you

fix(agent+discord): guard truncated-response continuation loops and cap Discord split delivery (#86581)

webtecnicab48ab1b4ad03
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index ba11804a97b..9b37cbfa90d 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -87,6 +87,7 @@ from agent.retry_utils import (
jittered_backoff,
zai_coding_overload_retry_ceiling,
)
+from agent.repetition_guard import is_repetition_dominated
from agent.trajectory import has_incomplete_scratchpad
# Bind before the turn starts so a source-tree swap cannot load a skewed
# finalizer at turn end.
@@ -3518,6 +3519,60 @@ def run_conversation(
"error": _exhaust_error,
}
+ # ── Detect repetition-dominated truncation (#86581) ──
+ # A model in a degenerate repetition loop can spend its
+ # ENTIRE output budget echoing one fragment. The
+ # continuation nudge below would then stitch the
+ # pathological fragment into the final response — in the
+ # #86581 incident one turn produced a 60,698-char
+ # response delivered as 31 Discord messages. Abort with
+ # a clear user-facing error instead, mirroring the
+ # _thinking_exhausted guard above. Reasoning blocks are
+ # stripped first (repeated scratchpad lines are not
+ # evidence of a degenerate visible response).
+ _visible_trunc = (
+ agent._strip_think_blocks(_trunc_content)
+ if isinstance(_trunc_content, str)
+ else _trunc_content
+ )
+ _repetition_dominated = (
+ not _trunc_has_tool_calls
+ and bool(_visible_trunc)
+ and is_repetition_dominated(_visible_trunc)
+ )
+ if _repetition_dominated:
+ _rep_error = (
+ "Model output entered a repetition loop and was "
+ "truncated mid-loop; refusing to continue a "
+ "degenerate response."
+ )
+ agent._vprint(
+ f"{agent.log_prefix}🔁 Response dominated by "
+ f"repeated text — stopping instead of "
+ f"continuing a degenerate response.",
+ force=True,
+ )
+ _rep_response = (
+ "⚠️ **Response Stopped — Repetition Detected**\n\n"
+ "The model fell into a repetition loop while "
+ "writing this response, so continuing would only "
+ "produce more repeated text. The partial response "
+ "was discarded.\n\n"
+ "→ Switch to a different model with `/model`\n"
+ "→ Or resend your message (your conversation "
+ "history is preserved)"
+ )
+ agent._cleanup_task_resources(effective_task_id)
+ agent._persist_session(messages, conversation_history)
+ return {
+ "final_response": _rep_response,
+ "messages": messages,
+ "api_calls": api_call_count,
+ "completed": False,
+ "partial": True,
+ "error": _rep_error,
+ }
+
if agent.api_mode in {"chat_completions", "bedrock_converse", "anthropic_messages"}:
assistant_message = _trunc_msg
# ── Content-filter stream stall → fallback (#32421) ──
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.py
new file mode 100644
index 00000000000..6a1d466e923
--- /dev/null
+++ b/agent/repetition_guard.py
@@ -0,0 +1,95 @@
+"""Cheap content-sanity checks for the truncated-response continuation path.
+
+Issue #86581: a model in a degenerate repetition loop can spend its ENTIRE
+output budget echoing one fragment. The ``finish_reason=length``
+continuation path in ``conversation_loop.py`` would then retry with a
+"continue, don't repeat" nudge — stitching a pathological fragment into the
+final response with no content-sanity check. In the incident behind #86581
+a single turn produced a 60,698-char response delivered as 31 Discord
+messages.
+
+These helpers detect repetition-dominated fragments BEFORE the continuation
+nudge is appended so the turn can abort with a clear user-facing error
+(mirroring the existing ``_thinking_exhausted`` guard) instead of flooding.
+
+The detection is deliberately conservative: only LONG verbatim repeats
+(60+ chars) whose occurrences cover a majority of the fragment trip the
+guard, so ordinary truncated responses (a sentence cut mid-word, a heading
+repeated, code with similar-looking lines) are never blocked.
+"""
+
+from __future__ import annotations
+
+import math
+
+# A fragment must be at least this long before the repetition check runs at
+# all. Short truncations (a sentence cut mid-word) can trivially contain
+# repeated tokens and are legitimately continued.
+MIN_FRAGMENT_LENGTH = 400
+
+# Length of the exact-repeat window. A verbatim repeat of this many chars
+# is far beyond ordinary phrasing reuse (citations, headings, similar code).
+_REPEAT_WINDOW = 60
+
+# A window that repeats at least this many times is a repetition signal,
+# even for short fragments.
+_MIN_REPEAT_COUNT = 5
+
+# A fragment is "repetition-dominated" when repeated windows account for at
+# least this fraction of its characters.
+_DOMINANCE_RATIO = 0.5
+
+
+def is_repetition_dominated(text: str) -> bool:
+ """True when ``text`` is dominated by verbatim repeated fragments.
+
+ A truncated response is "repetition-dominated" when a single 60+ char
+ substring appears often enough that its occurrences cover at least half
+ of the fragment. That shape is the signature of a model repetition
+ loop (issue #86581), and continuing such a fragment is pointless — the
+ continuation nudge would just stitch more repeated text into the final
+ response.
+
+ Returns False for non-string / empty / short inputs (fail-open: never
+ blocks a continuation the guard cannot confidently judge).
+ """
+ if not isinstance(text, str):
+ return False
+ n = len(text)
+ if n < MIN_FRAGMENT_LENGTH:
+ return False
+
+ # Fast path: one normalized line duplicated often enough to cover half
+ # the fragment (the most common echo shape — a repeated paragraph or
+ # sentence on its own line). Cheap, no big allocations.
+ if _line_repetition_dominated(text, n):
+ return True
+
+ # General path: fixed-size exact-repeat windows, sliding one char at a
+ # time. Catches repetition loops that do not align to line boundaries.
+ window = _REPEAT_WINDOW
+ # A window must appear this many times for its occurrences to cover
+ # >= DOMINANCE_RATIO of the fragment (and at least _MIN_REPEAT_COUNT).
+ needed = max(_MIN_REPEAT_COUNT, math.ceil(n * _DOMINANCE_RATIO / window))
+ counts: dict[str, int] = {}
+ for i in range(n - window + 1):
+ key = text[i : i + window]
+ c = counts.get(key, 0) + 1
+ if c >= needed:
+ return True
+ counts[key] = c
+ return False
+
+
+def _line_repetition_dominated(text: str, n: int) -> bool:
+ """True when a single normalized line covers half the fragment via repeats."""
+ counts: dict[str, int] = {}
+ for line in text.splitlines():
+ norm = line.strip()
+ if not norm:
+ continue
+ counts[norm] = counts.get(norm, 0) + 1
+ for line, c in counts.items():
+ if c >= _MIN_REPEAT_COUNT and c * len(line) >= n * _DOMINANCE_RATIO:
+ return True
+ return False
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index b5a1f4ffa83..ef0cdd14d74 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -1043,6 +1043,12 @@ class DiscordAdapter(BasePlatformAdapter):
_SPLIT_THRESHOLD = 1900 # near the 2000-char split point
supports_code_blocks = True # Discord markdown renders fenced code blocks natively
splits_long_messages = True # send() chunks via truncate_message(MAX_MESSAGE_LENGTH)
+ # Safety ceiling on split deliveries (#86581): a degenerate turn can
+ # produce tens of thousands of characters — without a cap the adapter
+ # posts every 2000-char chunk back-to-back and floods the channel (the
+ # incident delivered 60,698 chars as 31 messages). Chunks beyond the
+ # cap are replaced by a short notice.
+ MAX_SPLIT_MESSAGES = 8
# Auto-disconnect from voice channel after this many seconds of inactivity.
# Config key: discord.voice_channel_inactivity_timeout_seconds (0 disables)
@@ -3397,6 +3403,29 @@ class DiscordAdapter(BasePlatformAdapter):
logger.debug("Could not build reply-to reference: %s", e)
return None
+ def _cap_split_chunks(self, chunks: List[str]) -> List[str]:
+ """Cap the number of chunks sent for one logical response (#86581).
+
+ A degenerate turn can produce tens of thousands of characters; the
+ #86581 incident delivered 60,698 chars as 31 back-to-back Discord
+ messages. When ``chunks`` exceeds ``MAX_SPLIT_MESSAGES``, keep the
+ first ``N-1`` chunks and replace the rest with a short notice so the
+ user sees a clear signal instead of a flood. The full response
+ remains available in the gateway session history / logs.
+ """
+ if len(chunks) <= self.MAX_SPLIT_MESSAGES:
+ return chunks
+ kept = chunks[: self.MAX_SPLIT_MESSAGES - 1]
+ dropped_chars = sum(len(c) for c in chunks[self.MAX_SPLIT_MESSAGES - 1 :])
+ notice = (
+ f"\n\n⚠️ **Response truncated** — this reply exceeded the "
+ f"delivery limit ({self.MAX_SPLIT_MESSAGES} messages). "
+ f"{dropped_chars} characters were not delivered; the full "
+ f"response is in the session logs."
+ )
+ kept.append(notice)
+ return kept
+
async def send(
self,
chat_id: str,
@@ -3475,7 +3504,9 @@ class DiscordAdapter(BasePlatformAdapter):
# Format and split message if needed
formatted = self.format_message(content)
- chunks = self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
+ chunks = self._cap_split_chunks(
+ self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
+ )
message_ids = []
# Build the reference from ids — no fetch_message round trip.
@@ -3565,7 +3596,9 @@ class DiscordAdapter(BasePlatformAdapter):
# module — no cross-module import needed.
formatted = self.format_message(content)
- chunks = self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
+ chunks = self._cap_split_chunks(
+ self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
+ )
thread_name = _derive_forum_thread_name(content)
@@ -3832,7 +3865,9 @@ class DiscordAdapter(BasePlatformAdapter):
returns ``success=False`` (a real adapter problem, not overflow).
"""
formatted = self.format_message(content)
- chunks = self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
+ chunks = self._cap_split_chunks(
+ self.truncate_message(formatted, self.MAX_MESSAGE_LENGTH)
+ )
if len(chunks) <= 1:
# Defensive: caller's pre-flight should guarantee >1 chunk, but if
# not, just edit normally.
diff --git a/tests/agent/test_repetition_guard.py b/tests/agent/test_repetition_guard.py
new file mode 100644
index 00000000000..369ab213657
--- /dev/null
+++ b/tests/agent/test_repetition_guard.py
@@ -0,0 +1,50 @@
+"""Unit tests for the truncated-response repetition guard (issue #86581)."""
+
+from __future__ import annotations
+
+from agent.repetition_guard import MIN_FRAGMENT_LENGTH, is_repetition_dominated
+
+# The exact sentence from the #86581 incident (echoed hundreds of times by
+# the model before the provider cut it off at finish_reason=length).
+_INCIDENT_ECHO = "好,你幫我更改成 Google Gemini 4 31B。"
+
+
+class TestRepetitionGuard:
+ def test_incident_shape_flags_repetition(self):
+ # Narration + the echoed sentence on its own line, repeated (line path).
+ text = ("We need to verify the model setting.\n" + _INCIDENT_ECHO + "\n") * 800
+ assert is_repetition_dominated(text) is True
+
+ def test_repeated_sentence_without_line_breaks_flags(self):
+ # Repetition loop with no line breaks — exercises the window path.
+ text = _INCIDENT_ECHO * 2000
+ assert len(text) >= MIN_FRAGMENT_LENGTH
+ assert is_repetition_dominated(text) is True
+
+ def test_long_legitimate_text_not_flagged(self):
+ # Long, unique prose — no 60-char window ever repeats.
+ text = " ".join(
+ f"Sentence number {i} describes a distinct topic with unique words "
+ f"such as quasar-{i} and nebula-{i} to keep every window distinct."
+ for i in range(1200)
+ )
+ assert len(text) >= MIN_FRAGMENT_LENGTH
+ assert is_repetition_dominated(text) is False
+
+ def test_short_fragment_never_flagged(self):
+ # Below MIN_FRAGMENT_LENGTH the guard fails open — short truncations
+ # are legitimately continued even if they look repetitive.
+ assert is_repetition_dominated("A. " * 50) is False
+ assert is_repetition_dominated("hello ") is False
+
+ def test_repeat_not_dominant_not_flagged(self):
+ # A repeated sentence scattered through a long unique text: repeated
+ # windows exist but cover far less than half of the fragment.
+ filler = " ".join(f"unique filler token {i}" for i in range(3000))
+ text = filler + ("\n" + _INCIDENT_ECHO + "\n") * 30
+ assert is_repetition_dominated(text) is False
+
+ def test_non_string_inputs(self):
+ assert is_repetition_dominated("") is False
+ assert is_repetition_dominated(None) is False
+ assert is_repetition_dominated(12345) is False
diff --git a/tests/gateway/test_discord_split_cap.py b/tests/gateway/test_discord_split_cap.py
new file mode 100644
index 00000000000..05f0f6b2475
--- /dev/null
+++ b/tests/gateway/test_discord_split_cap.py
@@ -0,0 +1,156 @@
+"""Regression tests for the Discord split-delivery cap (issue #86581).
+
+A degenerate turn can produce tens of thousands of characters. Without a
+ceiling, the adapter posts every 2000-char chunk back-to-back and floods the
+channel — the #86581 incident delivered 60,698 chars as 31 messages. The
+cap keeps the first ``MAX_SPLIT_MESSAGES`` chunks and replaces the remainder
+with a short notice.
+"""
+
+from __future__ import annotations
+
+import sys
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+
+
+def _ensure_discord_mock():
+ if "discord" in sys.modules and hasattr(sys.modules["discord"], "__file__"):
+ return
+ discord_mod = MagicMock()
+ discord_mod.Intents.default.return_value = MagicMock()
+ discord_mod.Client = MagicMock
+ discord_mod.File = MagicMock
+ discord_mod.DMChannel = type("DMChannel", (), {})
+ discord_mod.Thread = type("Thread", (), {})
+ discord_mod.ForumChannel = type("ForumChannel", (), {})
+ ext_mod = MagicMock()
+ commands_mod = MagicMock()
+ commands_mod.Bot = MagicMock
+ ext_mod.commands = commands_mod
+ sys.modules.setdefault("discord", discord_mod)
+ sys.modules.setdefault("discord.ext", ext_mod)
+ sys.modules.setdefault("discord.ext.commands", commands_mod)
+
+
+_ensure_discord_mock()
+
+from plugins.platforms.discord.adapter import DiscordAdapter # noqa: E402
+
+
+MAX = DiscordAdapter.MAX_MESSAGE_LENGTH
+CAP = DiscordAdapter.MAX_SPLIT_MESSAGES
+
+
+def _make_adapter():
+ return DiscordAdapter(PlatformConfig(enabled=True, token="***"))
+
+
+def _huge_content(chars: int = 60_000) -> str:
+ # Distinct filler — this test is about SIZE, not repetition.
+ return " ".join(f"word-{i}-" + "x" * 12 for i in range(chars // 20))
+
+
+class TestCapSplitChunks:
+ def test_below_cap_unchanged(self):
+ adapter = _make_adapter()
+ chunks = ["a", "b", "c"]
+ assert adapter._cap_split_chunks(chunks) == chunks
+
+ def test_over_cap_keeps_n_minus_1_plus_notice(self):
+ adapter = _make_adapter()
+ chunks = [f"chunk-{i}-" + "z" * 100 for i in range(40)]
+ capped = adapter._cap_split_chunks(chunks)
+ assert len(capped) == CAP
+ assert capped[0] == chunks[0]
+ assert "Response truncated" in capped[-1]
+ assert "delivery limit" in capped[-1]
+ # The notice itself must stay under Discord's per-message cap.
+ assert len(capped[-1]) <= MAX
+
+
+class TestSendCap:
+ @pytest.mark.asyncio
+ async def test_send_caps_split_flood(self, monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ adapter = _make_adapter()
+ sends = []
+
+ async def fake_send(*, content, reference=None):
+ sends.append(content)
+ return SimpleNamespace(id=9000 + len(sends))
+
+ channel = SimpleNamespace(id=555, send=AsyncMock(side_effect=fake_send))
+ adapter._client = SimpleNamespace(
+ get_channel=lambda _cid: channel,
+ fetch_channel=AsyncMock(),
+ )
+
+ result = await adapter.send("555", _huge_content())
+
+ assert result.success is True
+ assert len(sends) == CAP
+ assert "Response truncated" in sends[-1]
+
+
+class TestForumCap:
+ @pytest.mark.asyncio
+ async def test_send_to_forum_caps_followup_chunks(self, monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ adapter = _make_adapter()
+ thread_sends = []
+
+ async def fake_thread_send(*, content):
+ thread_sends.append(content)
+ return SimpleNamespace(id=8000 + len(thread_sends))
+
+ thread_channel = SimpleNamespace(
+ id=777, send=AsyncMock(side_effect=fake_thread_send)
+ )
+ forum_channel = SimpleNamespace(
+ id=666,
+ type=SimpleNamespace(value=15),
+ create_thread=AsyncMock(return_value=SimpleNamespace(
+ id=777,
+ thread=thread_channel,
+ message=SimpleNamespace(id=8000),
+ )),
+ )
+
+ result = await adapter._send_to_forum(forum_channel, _huge_content())
+
+ assert result.success is True
+ # 1 starter message + at most (CAP - 1) follow-up chunks.
+ assert len(thread_sends) <= CAP - 1
+ assert "Response truncated" in thread_sends[-1]
+
+
+class TestEditOverflowCap:
+ @pytest.mark.asyncio
+ async def test_edit_overflow_split_capped(self, monkeypatch, tmp_path):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ adapter = _make_adapter()
+ edits = []
+ sends = []
+
+ async def fake_edit(*, content):
+ edits.append(content)
+
+ async def fake_send(*, content, reference=None):
+ sends.append(content)
+ return SimpleNamespace(id=9000 + len(sends))
+
+ msg = SimpleNamespace(id=42, edit=AsyncMock(side_effect=fake_edit))
+ channel = SimpleNamespace(id=555, send=AsyncMock(side_effect=fake_send))
+
+ result = await adapter._edit_overflow_split(channel, msg, "42", _huge_content())
+
+ assert result.success is True
+ # 1 in-place edit + at most (CAP - 1) continuation sends.
+ assert len(edits) == 1
+ assert len(sends) <= CAP - 1
+ assert "Response truncated" in (sends[-1] if sends else edits[-1])
diff --git a/tests/run_agent/test_continuation_repetition_guard.py b/tests/run_agent/test_continuation_repetition_guard.py
new file mode 100644
index 00000000000..80223e21f0e
--- /dev/null
+++ b/tests/run_agent/test_continuation_repetition_guard.py
@@ -0,0 +1,99 @@
+"""Regression tests for the truncated-response repetition guard (#86581).
+
+A truncated response (``finish_reason=length``) dominated by verbatim
+repeated text must NOT be continued: the continuation nudge would stitch the
+pathological fragment into the final response (the #86581 incident delivered
+60,698 chars as 31 Discord messages). The turn aborts with a clear
+user-facing error instead, mirroring the existing thinking-budget guard.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from hermes_constants import FINISH_REASON_LENGTH, PARTIAL_STREAM_STUB_ID
+
+# The exact sentence from the #86581 incident.
+_INCIDENT_ECHO = "好,你幫我更改成 Google Gemini 4 31B。"
+
+
+def loop_agent():
+ from run_agent import AIAgent
+
+ with (
+ patch("run_agent.get_tool_definitions", return_value=[]),
+ patch("run_agent.check_toolset_requirements", return_value={}),
+ patch("run_agent.OpenAI"),
+ ):
+ a = AIAgent(
+ api_key="test-key-1234567890",
+ base_url="https://openrouter.ai/api/v1",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ a.client = MagicMock()
+ a._cached_system_prompt = "You are helpful."
+ a._use_prompt_caching = False
+ a.compression_enabled = False
+ a.save_trajectories = False
+ return a
+
+
+def _stub(content):
+ from tests.run_agent.test_run_agent import _mock_assistant_msg
+
+ return SimpleNamespace(
+ id=PARTIAL_STREAM_STUB_ID,
+ model="test/model",
+ choices=[SimpleNamespace(
+ index=0,
+ message=_mock_assistant_msg(content=content),
+ finish_reason=FINISH_REASON_LENGTH,
+ )],
+ usage=None,
+ )
+
+
+def _run(agent, message):
+ with (
+ patch.object(agent, "_persist_session"),
+ patch.object(agent, "_save_trajectory"),
+ patch.object(agent, "_cleanup_task_resources"),
+ ):
+ return agent.run_conversation(message)
+
+
+class TestContinuationRepetitionGuard:
+ def test_repetition_dominated_truncation_aborts(self, loop_agent):
+ echo = _INCIDENT_ECHO * 2000
+ loop_agent.client.chat.completions.create.side_effect = [_stub(echo)]
+
+ result = _run(loop_agent, "write me a long report")
+
+ assert result["completed"] is False
+ assert result["partial"] is True
+ assert "Repetition" in (result["final_response"] or "")
+ # The pathological fragment must NOT be appended to the history.
+ assert not any(
+ isinstance(m, dict) and m.get("_length_continuation_fragment")
+ for m in result["messages"]
+ )
+ # Exactly one API call — no continuation was attempted.
+ assert loop_agent.client.chat.completions.create.call_count == 1
+
+ def test_legit_truncation_still_continues(self, loop_agent):
+ # Ordinary short truncated fragments still get continuation retries.
+ loop_agent.client.chat.completions.create.side_effect = [
+ _stub("part one "), _stub("part two "),
+ _stub("part three "), _stub("part four."),
+ ]
+
+ result = _run(loop_agent, "write me a long report")
+
+ assert result["partial"] is True
+ assert loop_agent.client.chat.completions.create.call_count == 4