Skip to content

The agent that grows with you

fix(agent): stop reporting transport/router truncation as an output-length limit (#91717)

rainbowgitsd43d97d1c3bb
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
index 45e812d019f..f15409f192a 100644
--- a/agent/turn_failure_copy.py
+++ b/agent/turn_failure_copy.py
@@ -313,6 +313,14 @@ _ONE_OFF_COPY: Dict[str, str] = {
"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."
),
+ # Rides failure_reason="truncated": args were cut mid-JSON but the model never reported
+ # an output-length stop, so don't claim it hit one (#91717).
+ "truncated_unreported": (
+ "The model's action arrived cut off partway through (finish_reason={finish_reason}), so "
+ "Hermes didn't run it. Nothing was changed. The model didn't report hitting its output "
+ "limit, so this was most likely a dropped connection or a provider/router cutting the "
+ "reply short. Send /retry; if it keeps happening, ask for the work in smaller steps."
+ ),
"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_tool_validation.py b/agent/turn_tool_validation.py
index a3146887170..88090b463ef 100644
--- a/agent/turn_tool_validation.py
+++ b/agent/turn_tool_validation.py
@@ -177,8 +177,14 @@ def validate_tool_calls(
)
agent._invalid_json_retries = 0
agent._cleanup_task_resources(effective_task_id)
+ # Blame the output cap only when the model reported one; otherwise the args
+ # were cut by a stream break or a router rewriting finish_reason (#91717).
+ _copy = (
+ site_copy("truncated") if finish_reason == "length"
+ else site_copy("truncated_unreported", finish_reason=repr(finish_reason))
+ )
return _verdict("return", _partial_exit(
- agent, messages, conversation_history, api_call_count, site_copy("truncated"),
+ agent, messages, conversation_history, api_call_count, _copy,
))
agent._invalid_json_retries += 1
diff --git a/tests/agent/test_partial_stream_finish_reason.py b/tests/agent/test_partial_stream_finish_reason.py
index e678256bc20..d51a32ac820 100644
--- a/tests/agent/test_partial_stream_finish_reason.py
+++ b/tests/agent/test_partial_stream_finish_reason.py
@@ -1098,3 +1098,121 @@ class TestMergedFinishChunkSurvivesSSEGuard:
assert response.id != PARTIAL_STREAM_STUB_ID
assert response.choices[0].finish_reason == "stop"
assert response.choices[0].message.content == "Hello."
+
+
+class TestRouterRewriteTruncationMessageIsHonest:
+ """Regression for #91717: the invalid-JSON truncation detector (the
+ secondary path that fires when the primary finish_reason='length' handler
+ was bypassed) must NOT blame the output-length limit when the model never
+ reported one.
+
+ Scenario: after a transport timeout, OpenRouter's router delivers a retry
+ whose finish_reason is rewritten from 'length' to 'tool_calls', and whose
+ tool-call arguments are cut off mid-JSON. The old code hardcoded
+ 'Response truncated due to output length limit', misleading operators into
+ tuning max_tokens / switching models when the real cause is transport /
+ router corruption.
+ """
+
+ def _router_rewrite_response(self):
+ # finish_reason='tool_calls' (NOT 'length') + truncated JSON args
+ # ('{"cmd": "ls' — no closing brace), on a normal generation id (not
+ # the partial-stream stub). This bypasses the length handler and lands
+ # in the invalid-JSON truncation detector.
+ msg = SimpleNamespace(
+ role="assistant",
+ content="",
+ tool_calls=[SimpleNamespace(
+ id="call_1", type="function",
+ function=SimpleNamespace(name="terminal", arguments='{"cmd": "ls'),
+ )],
+ reasoning_content=None,
+ )
+ return SimpleNamespace(
+ id="gen-router-rewrite-xyz",
+ model="deepseek/deepseek-v4-flash",
+ choices=[SimpleNamespace(
+ index=0, message=msg, finish_reason="tool_calls",
+ )],
+ usage=None,
+ )
+
+ def test_router_rewrite_truncation_does_not_claim_output_length_limit(
+ self, loop_agent,
+ ):
+ loop_agent.valid_tool_names = {"terminal"}
+ loop_agent.client.chat.completions.create.side_effect = (
+ lambda *a, **kw: self._router_rewrite_response()
+ )
+
+ with (
+ patch.object(loop_agent, "_persist_session"),
+ patch.object(loop_agent, "_save_trajectory"),
+ patch.object(loop_agent, "_cleanup_task_resources"),
+ ):
+ result = loop_agent.run_conversation("list the files")
+
+ final = result["final_response"] or ""
+ error = result["error"] or ""
+
+ # The misleading output-length-limit label must be gone: finish_reason
+ # was 'tool_calls', never 'length'.
+ assert "output length limit" not in final, (
+ "Router-rewrite / transport truncation must not be reported as an "
+ "output-length limit (#91717)."
+ )
+ assert "output length limit" not in error
+ # The honest message names the real suspect and surfaces finish_reason.
+ assert "finish_reason='tool_calls'" in final
+ assert (
+ "transport" in final or "router" in final
+ ), "Honest message must point at transport/router corruption."
+ # Recovery invariants preserved: incomplete tool args never execute.
+ assert result["completed"] is False
+ assert result["partial"] is True
+
+ def _genuine_length_truncated_tool_call(self):
+ # finish_reason='length' (the model truly hit its output cap) with a
+ # tool call whose JSON args are cut off. On a normal generation id, so
+ # it is NOT treated as a partial-stream network stub. After the loop
+ # exhausts its truncated-tool-call retries this lands on the primary
+ # length handler's tool-call path (scenario 1 in the issue's table).
+ msg = SimpleNamespace(
+ role="assistant",
+ content="",
+ tool_calls=[SimpleNamespace(
+ id="call_1", type="function",
+ function=SimpleNamespace(name="terminal", arguments='{"cmd": "ls'),
+ )],
+ reasoning_content=None,
+ )
+ return SimpleNamespace(
+ id="gen-real-length",
+ model="test/model",
+ choices=[SimpleNamespace(index=0, message=msg, finish_reason="length")],
+ usage=None,
+ )
+
+ def test_genuine_length_truncation_keeps_output_limit_wording(self, loop_agent):
+ """The primary length handler (finish_reason='length', real
+ output-cap exhaustion) must keep the accurate 'output length limit'
+ wording — scenario 1 in the issue's table is correct and must not
+ regress from the honest-message fix."""
+ loop_agent.valid_tool_names = {"terminal"}
+ loop_agent.client.chat.completions.create.side_effect = (
+ lambda *a, **kw: self._genuine_length_truncated_tool_call()
+ )
+
+ with (
+ patch.object(loop_agent, "_persist_session"),
+ patch.object(loop_agent, "_save_trajectory"),
+ patch.object(loop_agent, "_cleanup_task_resources"),
+ ):
+ result = loop_agent.run_conversation("run a long command")
+
+ blob = (result.get("final_response") or "") + (result.get("error") or "")
+ assert "output length limit" in blob, (
+ "A genuine finish_reason='length' truncation must still reference "
+ "the output length limit — the honest-message fix must not blank "
+ "out the accurate case (#91717 scenario 1)."
+ )