Skip to content

The agent that grows with you

fix(agent): a server context rejection the transcript cannot explain is no longer "conversation too long"

teknium15e950506089f
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
index ffd7f06beaa..e8337db5b68 100644
--- a/agent/turn_failure_copy.py
+++ b/agent/turn_failure_copy.py
@@ -253,6 +253,17 @@ _ONE_OFF_COPY: Dict[str, str] = {
"your settings (compression.enabled). Run /compress to shrink it now, /new to start "
"fresh, or pick a model with a bigger context window."
),
+ # Wording deliberately avoids the overflow phrases gateway/run_turn.py matches on
+ # (``_CONTEXT_OVERFLOW_ERROR_PHRASES``): this failure is transient, so the user's
+ # message must stay in the transcript and the session must not be auto-reset.
+ "server_context_rejection": (
+ "The model server rejected this request as too large, but this conversation is only "
+ "about {tokens:,} tokens — well under the {window:,}-token window Hermes knows for "
+ "{model} — so shrinking it would not help. Another request on the same server (for "
+ "example a background memory review from an earlier session) was probably holding its "
+ "capacity, or the server runs {model} with a smaller window than Hermes assumes. Wait a "
+ "moment and send /retry; if it keeps happening, check the server's context setting."
+ ),
"stream_dropped_tool_call": (
"The connection to {label} kept dropping while the model was writing a large action, "
"so nothing was run. Check your network and send /retry; asking for the file in smaller "
diff --git a/agent/turn_overflow.py b/agent/turn_overflow.py
index 925a328ccb8..e4b0066843e 100644
--- a/agent/turn_overflow.py
+++ b/agent/turn_overflow.py
@@ -10,6 +10,7 @@ estimators that tests patch on the loop module are imported lazily inside the ha
from __future__ import annotations
import logging
+import re
import time
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
@@ -33,6 +34,11 @@ logger = logging.getLogger("agent.conversation_loop")
_RETRY_HINT = " 💡 Try /new to start a fresh conversation, or /compress to retry compression."
+# A provider "context exceeded" whose request (incl. the output reservation) is under this share
+# of the known window is not explained by the transcript; the rough estimator is ±30%, so a real
+# overflow (request ≈ window) never lands below half.
+_UNEXPLAINED_REJECTION_FRACTION = 0.5
+
_GITHUB_MODELS_HINT = (
" 💡 GitHub Models free tier (models.inference.ai.azure.com) caps every",
" request at ~8K tokens. Hermes' system prompt + tool schemas baseline",
@@ -88,7 +94,8 @@ class _Recovery(OverflowVerdict):
def fail_turn(
self, final_response: str, *, notices: tuple = (), log: Optional[tuple] = None,
- compression_exhausted: bool = True, **extra: Any,
+ compression_exhausted: bool = True, reason: str = "context_overflow",
+ retryable: bool = False, **extra: Any,
) -> OverflowVerdict:
"""End the turn as failed/partial. ``notices`` flush the buffered retry trace
first so the user sees what compression attempts were made."""
@@ -108,7 +115,7 @@ class _Recovery(OverflowVerdict):
"error": final_response,
"partial": True,
"failed": True,
- }, "context_overflow", False)
+ }, reason, retryable)
if compression_exhausted:
# Reuse the gateway's existing context-recovery contract (#98722, salvaged from #98741). The
# bloated transcript remains intact while future input can move to a clean session instead of
@@ -346,12 +353,12 @@ def _adopt_provider_context_limit(st: _Recovery, error_msg: str, old_ctx: int) -
if is_minimax_provider and "context window exceeds limit (" in error_msg:
agent._buffer_vprint(
f"Provider reported overflow amount only; "
- f"keeping context_length at {old_ctx:,} tokens and compressing."
+ f"keeping context_length at {old_ctx:,} tokens."
)
else:
agent._buffer_vprint(
f"⚠️ Context length exceeded, but provider did not report a max context length; "
- f"keeping context_length at {old_ctx:,} tokens and compressing."
+ f"keeping context_length at {old_ctx:,} tokens."
)
return None
@@ -387,6 +394,35 @@ def _recover_context_length(st: _Recovery, _retry: TurnRetryState, error_msg: st
new_ctx = _adopt_provider_context_limit(st, error_msg, old_ctx)
+ # A rejection the transcript cannot explain (#114644): the request sits far below the window
+ # Hermes knows for this model (after adopting any limit the server reported), so compressing
+ # would destroy history for nothing. Single-slot local servers reject like this while ANOTHER
+ # request — a background review from an earlier session — holds their context. Name that,
+ # keep the turn retryable and transient: no "conversation too long", no gateway auto-reset.
+ # Only when the server quoted NO measurement of its own: "prompt is too long: 233153 tokens
+ # > 200000" is the server's count and beats the local estimate.
+ window = agent.context_compressor.context_length
+ request_tokens = st.request_tokens() + max(0, int(getattr(agent, "max_tokens", 0) or 0))
+ if (
+ not re.search(r"\d{4,}", error_msg)
+ and isinstance(window, int) and window > 0
+ and request_tokens < window * _UNEXPLAINED_REJECTION_FRACTION
+ ):
+ return st.fail_turn(
+ site_copy("server_context_rejection", model=agent.model, tokens=request_tokens, window=window),
+ notices=(
+ f"❌ The server rejected the request as too large, but it is only ~{request_tokens:,} "
+ f"tokens against a {window:,}-token window — not compressing.",
+ " 💡 Wait a moment and /retry; another request on the same server (e.g. a background "
+ "review) may have been holding its context.",
+ ),
+ log=(
+ "%sProvider context rejection not explained by request size (~%s of %s tokens); "
+ "skipping compression: %s", agent.log_prefix, f"{request_tokens:,}", f"{window:,}", error_msg[:200],
+ ),
+ compression_exhausted=False, reason=FailoverReason.server_error.value, retryable=True,
+ )
+
exhausted = st.count_attempt()
if exhausted is not None:
return exhausted
diff --git a/website/docs/reference/faq.md b/website/docs/reference/faq.md
index 62fc20ec60f..05d025c63a6 100644
--- a/website/docs/reference/faq.md
+++ b/website/docs/reference/faq.md
@@ -323,6 +323,8 @@ Look at the CLI startup line — it shows the detected context length (e.g., `
**Local servers (llama.cpp, Ollama) that go silent instead of erroring:** when a provider rejects a request as too large, Hermes compacts the conversation and rebuilds the request. Hermes re-measures the *complete* rebuilt request (system prompt + tool schemas + messages) before retrying, and runs further bounded compaction passes if it is still over the threshold. If the request still cannot fit, the turn ends with `Context length exceeded: compression could not reduce the rebuilt request below the safe threshold` rather than sending an oversized request that llama.cpp would silently truncate (`stop processing: n_tokens = 65535, truncated = 1` in the server log). If you hit that message, the fix is almost always the configured `context_length` above: make it match the server's actual `-c` / `--ctx-size`.
+**"The model server rejected this request as too large, but this conversation is only about N tokens…":** the server said "context exceeded" without quoting any measurement, while Hermes's own estimate of the request is far below the window it knows for the model — so it does **not** compress or blame the conversation, and the turn stays retryable. On single-slot local servers (LM Studio, Ollama) this is almost always another request holding the server's context at that moment — typically a background memory review from an earlier session (`thread=bg-review` in `logs/agent.log`). Wait a moment and `/retry`. If it recurs with no other Hermes process running, the server is loading the model with a smaller window than Hermes assumes: raise the server's context setting or lower `model.context_length` to match it.
+
To fix context detection, set it explicitly:
```yaml