The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): cut a runaway repetition loop while it streams, callback or not
John Paul Solivab6aae42c3b88
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 7eb42e981b0..21efd7ae4d5 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -50,7 +50,7 @@ from agent.reasoning_summaries import (append_streamed_reasoning_detail, separate_glued_reasoning_blocks,streamed_reasoning_detail_text,)-from agent.repetition_guard import is_repetition_dominated+from agent.repetition_guard import RunawayStreamWatch, is_repetition_dominatedfrom agent.stream_single_writer import claim_stream_writer, stream_writer_is_currentfrom tools.terminal_tool_lifecycle import is_persistent_envfrom utils import base_url_host_matches, base_url_hostname, env_float, env_int@@ -3172,6 +3172,10 @@ class _StreamingCall(StreamingWaitMonitor):self._writer_token = self._attempt_request_client = self._attempt_stream_response = Nonefrom agent.chat_completion_helpers_relay import RelayChatAccumulatorrelay_response = RelayChatAccumulator()+ # The raw channels, not the callback-delivered text: cron, subagents and callback-less+ # gateway turns register no stream callback, so nothing else sees a loop mid-stream.+ content_watch, reasoning_watch = RunawayStreamWatch(), RunawayStreamWatch()+ runaway = Nonedef _open_stream(next_api_kwargs: dict[str, Any]):timeout = _httpx.Timeout(connect=conn_cap, read=read_timeout, write=base_timeout, pool=conn_cap)@@ -3194,18 +3198,20 @@ class _StreamingCall(StreamingWaitMonitor):# Hermes interrupts the managed stream; Relay alone closes the provider stream.self.clients.set_stream_handle(stream)+ def _close_half_read_stream(reason: str) -> None:+ # A half-read SSE response stays checked out of the httpx pool and the finally+ # would cache the client WITH the leaked connection: close on the owner first.+ try:+ stream.close()+ except Exception:+ # Still checked out: poison the slot so the finally really closes the pool.+ if self._attempt_request_client is not None:+ self.agent._abort_request_openai_client(self._attempt_request_client, reason=reason)+for chunk in _iter_provider_stream_chunks(stream, response=lambda: self._attempt_stream_response):self._count_chunk(_diag, chunk)if self.agent._interrupt_requested:- # A half-read SSE response stays checked out of the httpx pool and the finally- # would cache the client WITH the leaked connection: close on the owner first.- try:- stream.close()- except Exception:- # Still checked out: poison the slot so the finally really closes the pool.- if self._attempt_request_client is not None:- self.agent._abort_request_openai_client(- self._attempt_request_client, reason="interrupt_stream_close_failed")+ _close_half_read_stream("interrupt_stream_close_failed")breakif not self._stream_attempt_is_active(stream_attempt_id):self._discard_stale_stream_chunk(stream_attempt_id, chunk)@@ -3269,6 +3275,9 @@ class _StreamingCall(StreamingWaitMonitor):display_reasoning = detail_text or reasoning_textif display_reasoning:self._emit_reasoning(display_reasoning)+ if reasoning_watch.feed(display_reasoning):+ runaway = "reasoning"+ break# Not routed to the live display: the transport promotes a sole-payload# refusal to content + ``content_filter`` and the loop surfaces it terminally.delta_refusal = getattr(delta, "refusal", None)@@ -3282,6 +3291,9 @@ class _StreamingCall(StreamingWaitMonitor):delta_content = flatten_message_text(getattr(delta, "content", None), sep="")if delta_content:content_parts.append(delta_content)+ if content_watch.feed(delta_content):+ runaway = "content"+ breakif tool_calls_acc:self._route_suppressed_text(delta_content)elif (pending_text_parts or _provider_stream_text_may_be_sse(delta_content)@@ -3307,16 +3319,29 @@ class _StreamingCall(StreamingWaitMonitor):# complete instead of silently discarding the action.self.result["partial_tool_names"].append(name)+ if runaway:+ _close_half_read_stream("runaway_stream_close_failed")+ self._log_runaway_cut(runaway)tool_calls.materialize()self._close_managed_stream()if self._stream_attempt_was_cancelled(stream_attempt_id):raise _httpx.RemoteProtocolError(f"stream attempt {stream_attempt_id} was superseded")if stream.final_response is not None:return self._adopt_final_response(stream.final_response)- return self._finish_chat_stream(stream, role, content_parts, reasoning_parts, tool_calls_acc,- finish_reason, model_name, usage_obj, flush_pending=_flush_pending_stream_text,+ response = self._finish_chat_stream(stream, role, content_parts, reasoning_parts, tool_calls_acc,+ "length" if runaway else finish_reason, model_name, usage_obj, flush_pending=_flush_pending_stream_text,response_id=response_id, upstream_provider=upstream_provider, reasoning_details=reasoning_details,refusal_parts=refusal_parts)+ if runaway:+ # Cut, not finished: the length path ends the turn on this mark instead of continuing.+ response._runaway_repetition = True+ return response++ def _log_runaway_cut(self, channel: str) -> None:+ logger.warning(+ "%sStream cut: the %s turned into a runaway repetition loop (model=%s, provider=%s).",+ getattr(self.agent, "log_prefix", ""), channel, self.api_kwargs.get("model", "unknown"),+ getattr(self.agent, "provider", "") or "unknown")def _adopt_final_response(self, final_response):"""Adapter returned a completed response for ``stream=True``: switch the@@ -3483,6 +3508,8 @@ class _StreamingCall(StreamingWaitMonitor):self._attempt_request_client = request_client_stream_context = {"manager": None, "stream": None}base_final_message = None+ text_watch, thinking_watch = RunawayStreamWatch(), RunawayStreamWatch()+ runaway = Nonefrom agent import relay_llmfrom agent.anthropic_adapter import normalize_stream_usage, sanitize_anthropic_kwargs@@ -3537,10 +3564,16 @@ class _StreamingCall(StreamingWaitMonitor):text = getattr(delta, "text", "")if text and not has_tool_use:self._emit_text(text)+ if text_watch.feed(text):+ runaway = "content"+ breakelif delta_type == "thinking_delta" and getattr(delta, "thinking", ""):self._emit_reasoning(delta.thinking)+ if thinking_watch.feed(delta.thinking):+ runaway = "reasoning"+ breakraw_stream = _stream_context["stream"]- if not self.agent._interrupt_requested and raw_stream is not None:+ if not self.agent._interrupt_requested and raw_stream is not None and not runaway:if not saw_message_stop:raise EmptyStreamError("Anthropic Messages stream ended before message_stop (possible upstream stream drop)."@@ -3562,6 +3595,13 @@ class _StreamingCall(StreamingWaitMonitor):if self.agent._interrupt_requested:return None+ if runaway:+ self._log_runaway_cut(runaway)+ # No message_stop, so no final message: the SDK's snapshot is what streamed so far.+ message = accumulator.response(_stream_context["stream"].current_message_snapshot)+ message.stop_reason = "max_tokens"+ message._runaway_repetition = True # same hand-off as the chat_completions wire+ return messageif base_final_message is not None:self._check_anthropic_message(base_final_message, tool_drop=False)if not stream.output_modified:diff --git a/agent/repetition_guard.py b/agent/repetition_guard.pyindex e1088f35c99..f09b21e9be8 100644--- a/agent/repetition_guard.py+++ b/agent/repetition_guard.py@@ -1,4 +1,4 @@-"""Cheap content-sanity checks for completed model output.+"""Cheap content-sanity checks for model output, completed or still streaming.A model in a degenerate repetition loop can spend its ENTIRE output budget echoing one fragment;the ``finish_reason=length`` continuation would then stitch it into the final response with a@@ -45,6 +45,10 @@ _RUNAWAY_DISTINCT_LINE_RATIO = 0.5# identical table rows, templated YAML) stay in the low KB and must be delivered.STOP_PATH_MIN_CHARS = 16_000+# A live stream is judged on at most this much of its latest text, so one check stays bounded+# however long the reply grows.+_STREAM_TAIL_CHARS = 4 * STOP_PATH_MIN_CHARS+def is_repetition_dominated(text: str) -> bool:"""True when a contiguous run of at least five exact repetitions covers at least half@@ -154,3 +158,33 @@ def _line_repetition_dominated(text: str, n: int) -> bool:"""True when a single normalized line covers half the fragment via repeats."""counts = Counter(norm for norm in (line.strip() for line in text.splitlines()) if norm)return any(c >= _MIN_REPEAT_COUNT and c * len(line) >= n * _DOMINANCE_RATIO for line, c in counts.items())+++class RunawayStreamWatch:+ """The stop-path criterion applied WHILE one channel (visible text or reasoning) streams.++ A stream that keeps producing never reaches a completion check, and endpoints without an+ output cap (#127234) keep a looping model going for as long as the turn lives. The first+ check runs at ``STOP_PATH_MIN_CHARS`` (asked-for repeats stay below it, as on the stop path)+ and the next one each time the text doubles, so the total work stays linear in the output.+ """++ __slots__ = ("_parts", "_chars", "_next_check")++ def __init__(self) -> None:+ self._parts: list[str] = []+ self._chars = 0+ self._next_check = STOP_PATH_MIN_CHARS++ def feed(self, text: str) -> bool:+ """Add one delta; True once the channel has become a runaway loop."""+ if not text:+ return False+ self._parts.append(text)+ self._chars += len(text)+ if self._chars < self._next_check:+ return False+ self._next_check = 2 * self._chars+ tail = "".join(self._parts)[-_STREAM_TAIL_CHARS:]+ self._parts = [tail]+ return is_runaway_repetition(tail)diff --git a/agent/turn_truncation.py b/agent/turn_truncation.pyindex dbcdb42233d..e5e3e8ad39d 100644--- a/agent/turn_truncation.py+++ b/agent/turn_truncation.py@@ -119,6 +119,11 @@ _REPETITION_DOMINATED = repetition_copy("so continuing would only produce more repeated text. The partial response was discarded."," and was truncated mid-loop; refusing to continue a",)+_REPETITION_STREAM_CUT = repetition_copy(+ "the stream mid-loop",+ "so the stream was stopped instead of running on. The partial response was discarded.",+ " and the stream was cut mid-loop; discarding the",+)_CEILING_NO_TEXT = ("⚠️ **No visible answer was produced.** The model hit its output-token limit on every ""continuation attempt — its reasoning consumed the entire budget each time.\n\nTo fix this:\n"@@ -460,6 +465,12 @@ def recover_from_truncation(truncated_tool_call_retries=truncated_tool_call_retries, retry_count=retry_count,compression_attempts=compression_attempts,)+ if getattr(response, "_runaway_repetition", False):+ # The streaming call cut a live repetition loop: a continuation would only re-enter it,+ # whatever the partial or its tool calls look like.+ line, user_response, error = _REPETITION_STREAM_CUT+ agent._vprint(f"{agent.log_prefix}{line}", force=True, diagnostic=True)+ return st.end_turn(user_response, error)st.window_filled = _prompt_filled_window(agent, response)if st.is_stub and getattr(response, "_clean_eof", False):_banner = ("Response truncated — server ended the stream without ever sending finish_reason "diff --git a/tests/agent/test_stream_runaway_repetition.py b/tests/agent/test_stream_runaway_repetition.pynew file mode 100644index 00000000000..dd8dd4405bd--- /dev/null+++ b/tests/agent/test_stream_runaway_repetition.py@@ -0,0 +1,206 @@+"""A stream stuck in a repetition loop must not keep the turn alive for as long as it streams.++No output cap reaches an OpenAI-compatible endpoint by design (the server owns its generation+default), and the stale-stream detector fires only on silence, so a looping local model kept a+turn streaming indefinitely. Every repetition check ran after the stream ended, and the+callback-level attempts read only text a stream callback had accepted. These turns run with no+callback, the way cron, subagents and non-streaming gateway platforms call the model.++The loops are the ones reported: a Telegram gateway cycle (#125650), the fullwidth "!!!" echo+(#94224, the raw repeated characters of #125351) and a local model's status line (#78551).+"""++from __future__ import annotations++import json+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import pytest++from agent.repetition_guard import STOP_PATH_MIN_CHARS++_TURN_BOUND_S = 30.0++_CYCLE_125650 = (+ "De bot en de werkers blijven lopen. Ik zoek het punt waar de tekst binnenkomt. "+ "Daar stop ik de herhaling. De bot en de werkers blijven lopen. Ik zoek dat punt nu. "+)+_FULLWIDTH_ECHO_94224 = "!!!" * 12+_STATUS_LINE_78551 = "- **Texture** : `TEXTURE_LOCAL.md` (trace creative, emergence). Pas dans un Hermes stock.\n"++# Asked-for repetition stays below the stop path's scale floor (#121600's repeat-on-request case).+_ASKED_FOR_REPEAT = "Hello world, this is a sentence the user asked me to repeat many times.\n" * 50+# Distinct rows sharing a long suffix: repeated windows dominate, yet every line differs.+_DISTINCT_ROWS = "".join(+ f"| {i:05d} | status: pending review by the on-call engineer before the next release window |\n"+ for i in range(500)+)+++class _FakeEndpoint:+ """Local endpoint streaming one reply per request, on the chat or the Anthropic wire."""++ def __init__(self, channel: str, text: str, *, endless: bool) -> None:+ self.channel, self.text, self.endless = channel, text, endless+ self.requests = 0+ self._stop = threading.Event()+ endpoint = self++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def do_GET(self): # model metadata probes+ body = json.dumps({"object": "list", "data": [+ {"id": "fixture-local", "object": "model", "context_length": 131072}]}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self):+ self.rfile.read(int(self.headers.get("Content-Length") or 0))+ endpoint.requests += 1+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Connection", "close")+ self.end_headers()+ frames = endpoint._anthropic_frames() if self.path.endswith("/messages") else endpoint._chat_frames()+ try:+ for frame in frames:+ self.wfile.write(frame.encode())+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ pass++ def log_message(self, *args):+ pass++ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self._server.daemon_threads = True+ threading.Thread(target=self._server.serve_forever, daemon=True).start()+ self.url = f"http://127.0.0.1:{self._server.server_port}/v1"++ def _pieces(self):+ if not self.endless:+ yield from (self.text[i:i + 200] for i in range(0, len(self.text), 200))+ return+ while not self._stop.is_set():+ yield self.text+ time.sleep(0.001)++ def _chat_frames(self):+ field = "reasoning_content" if self.channel == "reasoning" else "content"++ def chunk(delta, finish_reason=None):+ return "data: " + json.dumps({+ "id": "chatcmpl-fixture", "object": "chat.completion.chunk", "created": 0, "model": "fixture-local",+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],+ }) + "\n\n"++ for piece in self._pieces():+ yield chunk({field: piece})+ yield chunk({}, "stop")+ yield "data: [DONE]\n\n"++ def _anthropic_frames(self):+ thinking = self.channel == "reasoning"++ def event(kind, **payload):+ return f"event: {kind}\ndata: {json.dumps({'type': kind, **payload})}\n\n"++ yield event("message_start", message={+ "id": "msg_fixture", "type": "message", "role": "assistant", "model": "fixture-local", "content": [],+ "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 0}})+ yield event("content_block_start", index=0, content_block=(+ {"type": "thinking", "thinking": "", "signature": ""} if thinking else {"type": "text", "text": ""}))+ for piece in self._pieces():+ yield event("content_block_delta", index=0, delta=(+ {"type": "thinking_delta", "thinking": piece} if thinking else {"type": "text_delta", "text": piece}))+ yield event("content_block_stop", index=0)+ yield event("message_delta", delta={"stop_reason": "end_turn", "stop_sequence": None},+ usage={"output_tokens": 1})+ yield event("message_stop")++ def close(self) -> None:+ self._stop.set()+ self._server.shutdown()+ self._server.server_close()+++def endpoint(monkeypatch):+ for var in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")+ started = []++ def start(channel: str, text: str, *, endless: bool) -> _FakeEndpoint:+ started.append(_FakeEndpoint(channel, text, endless=endless))+ return started[-1]++ yield start+ for server in started:+ server.close()+++def _run_turn(server: _FakeEndpoint, api_mode: str) -> dict:+ from run_agent import AIAgent++ agent = AIAgent(+ model="fixture-local", provider="custom", base_url=server.url, api_key="fixture", api_mode=api_mode,+ quiet_mode=True, skip_memory=True, skip_context_files=True, enabled_toolsets=[], max_iterations=3,+ )+ outcome: dict = {}++ def run():+ try:+ outcome["result"] = agent.run_conversation("Summarize the backlog.")+ except BaseException as exc: # surfaced below, on the test thread+ outcome["error"] = exc++ turn = threading.Thread(target=run, daemon=True)+ turn.start()+ turn.join(_TURN_BOUND_S)+ if turn.is_alive():+ agent.interrupt("test bound reached")+ turn.join(10)+ pytest.fail(f"turn still streaming after {_TURN_BOUND_S:.0f}s")+ if "error" in outcome:+ raise outcome["error"]+ return outcome["result"]+++ ("api_mode", "channel", "loop"),+ [+ ("chat_completions", "content", _CYCLE_125650),+ ("chat_completions", "reasoning", _FULLWIDTH_ECHO_94224),+ ("anthropic_messages", "content", _STATUS_LINE_78551),+ ("anthropic_messages", "reasoning", _CYCLE_125650),+ ],+ ids=["chat-content", "chat-reasoning", "anthropic-text", "anthropic-thinking"],+)+def test_looping_stream_is_cut_without_a_stream_callback(endpoint, api_mode, channel, loop):+ server = endpoint(channel, loop, endless=True)++ result = _run_turn(server, api_mode)++ assert (result["completed"], result["failure_reason"]) == (False, "truncated")+ assert "Repetition Detected" in result["final_response"]+ assert server.requests == 1 # cut once; never continued or retried into the same loop+ unit = loop.strip()[:40]+ assert not any(unit in json.dumps(m, ensure_ascii=False) for m in result["messages"])++[email protected]("text", [_ASKED_FOR_REPEAT, _DISTINCT_ROWS], ids=["asked-for-repeat", "distinct-rows"])+def test_repetitive_but_legitimate_stream_is_delivered(endpoint, text):+ assert (len(text) < STOP_PATH_MIN_CHARS) == (text is _ASKED_FOR_REPEAT)+ server = endpoint("content", text, endless=False)++ result = _run_turn(server, "chat_completions")++ assert result["completed"] is True+ assert result["final_response"] == text.strip()diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.mdindex 63664d476cb..a82447719de 100644--- a/website/docs/integrations/providers.md+++ b/website/docs/integrations/providers.md@@ -1270,6 +1270,10 @@ Hermes no longer reads `model.max_tokens`, `HERMES_MAX_TOKENS`, provider output-settings, or `model_overrides.*.*.max_output_tokens`. Remove these legacy settings.Custom OpenAI-compatible endpoints receive no automatic catalog-sized output cap.Their server defaults apply; these can be lower than the model maximum.+A reply that degenerates into a repetition loop is still stopped: once the looping text+(visible or reasoning) passes 16,000 characters while it streams, Hermes closes the stream+and ends the turn with a "Repetition Detected" notice, so an uncapped endpoint cannot keep a+looping model running.Native Anthropic Messages (including the native Anthropic Bedrock path) requires`max_tokens`, so Hermes supplies an internal value. Bedrock Converse is a separatediff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.mdindex c405c43b94c..36942cc8bb4 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/integrations/providers.md@@ -1090,7 +1090,7 @@ model::::note 两个设置,容易混淆**`context_length`** 是**总上下文窗口**——输入和输出 token 的合计预算(例如 Claude Opus 4.6 为 200,000)。Hermes 用它来决定何时压缩历史记录以及验证 API 请求。-**输出上限**限制单次响应,而非对话历史。Hermes 不再读取 `model.max_tokens`、`HERMES_MAX_TOKENS` 或提供商及模型的输出上限设置。兼容端点使用服务器默认值;该值不一定是模型最大值。原生 Anthropic Messages 仍要求 `max_tokens`,Hermes 会提供内部值。Bedrock Converse 的可选输出限制默认省略。+**输出上限**限制单次响应,而非对话历史。Hermes 不再读取 `model.max_tokens`、`HERMES_MAX_TOKENS` 或提供商及模型的输出上限设置。兼容端点使用服务器默认值;该值不一定是模型最大值。回复在流式输出中陷入重复循环时仍会被停止:循环文本(可见内容或推理内容)超过 16,000 个字符后,Hermes 会关闭该流并以“Repetition Detected”提示结束本轮,因此没有输出上限的端点也不会让循环中的模型一直运行下去。原生 Anthropic Messages 仍要求 `max_tokens`,Hermes 会提供内部值。Bedrock Converse 的可选输出限制默认省略。当自动检测获取的窗口大小不正确时,设置 `context_length`。请删除旧的用户输出上限配置;内部任务预算与 MCP 采样安全预算保持不变。