Skip to content

The agent that grows with you

fix(agent): gate reasoning-only answer promotion by route

Mohamad Kanso71c1669404e7
diff --git a/agent/agent_init.py b/agent/agent_init.py
index a384a412eec..9cf04cae8b5 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2066,6 +2066,11 @@ def _build_context_engine(agent, _agent_cfg, cs, _custom_providers, _effective_c
model=agent.model, base_url=agent.base_url, provider=agent.provider,
is_codex_backend=(agent.provider or "").strip().lower() == "openai-codex",
)
+ from agent.agent_runtime_helpers import _ensure_answer_in_reasoning_capability
+ explicit_answer_capability = getattr(agent, "capabilities", {}).get("answer_in_reasoning")
+ if isinstance(explicit_answer_capability, bool):
+ agent.runtime_capabilities["answer_in_reasoning"] = explicit_answer_capability
+ _ensure_answer_in_reasoning_capability(agent)
agent.max_compression_attempts = cs.max_attempts
agent.compression_idle_compact_after_seconds = cs.idle_compact_after_seconds
@@ -2303,6 +2308,7 @@ def _snapshot_primary_runtime(agent):
"use_prompt_caching": agent._use_prompt_caching,
"use_native_cache_layout": agent._use_native_cache_layout,
"reasoning_echo_flag": getattr(agent, "_reasoning_echo_flag", False),
+ "runtime_capabilities": dict(getattr(agent, "runtime_capabilities", {}) or {}),
# Engine state _try_activate_fallback() overwrites (getattr: plugin engines may lack them).
"compressor_model": getattr(_cc, "model", agent.model),
"compressor_base_url": getattr(_cc, "base_url", agent.base_url),
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 16a95fb3519..55bca8a4309 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1316,6 +1316,7 @@ def _restore_runtime_capabilities(agent, rt: Dict[str, Any]) -> None:
raw = rt["runtime_capabilities"] if "runtime_capabilities" in rt else rt.get("capabilities")
if isinstance(raw, dict):
agent.runtime_capabilities = dict(raw)
+ _ensure_answer_in_reasoning_capability(agent)
elif "runtime_capabilities" in rt:
logger.warning("Ignoring malformed runtime capabilities snapshot")
@@ -1574,6 +1575,70 @@ def extract_reasoning(agent, assistant_message) -> Optional[str]:
return "\n\n".join(parts) if parts else None
+_ANSWER_IN_REASONING_CAPABILITY = "answer_in_reasoning"
+_NEMOTRON_PARSER_MODEL_MARKER = "nemotron-3.5-lightning"
+
+
+def answer_in_reasoning_capability(agent: Any) -> bool:
+ """Return whether a clean-stop reasoning payload is allowed to become the answer.
+
+ A field name is not provenance: OpenRouter, Bedrock, and several adapters can all put
+ private reasoning in ``reasoning``. The compatibility fallback is deliberately narrow to
+ the local Nemotron-3.5-Lightning chat route from #109205. A custom provider can opt in
+ an exact model through its existing per-model capability map, or a trusted caller can
+ pass the same capability in ``runtime_capabilities``.
+ """
+ base_url = str(getattr(agent, "base_url", "") or "")
+ provider = str(getattr(agent, "provider", "") or "").strip().lower()
+ if provider == "openrouter" or base_url_host_matches(base_url, "openrouter.ai"):
+ return False
+
+ api_mode = str(getattr(agent, "api_mode", "") or "").strip().lower()
+ if api_mode and api_mode != "chat_completions":
+ return False
+
+ runtime_capabilities = getattr(agent, "runtime_capabilities", None)
+ if isinstance(runtime_capabilities, dict):
+ configured = runtime_capabilities.get(_ANSWER_IN_REASONING_CAPABILITY)
+ if isinstance(configured, bool):
+ return configured
+
+ # Custom model maps already support exact per-route boolean capabilities. Keep the
+ # lookup best-effort: a malformed optional config must not break response handling.
+ try:
+ from hermes_cli.config import get_custom_provider_model_capability
+
+ configured = get_custom_provider_model_capability(
+ model=str(getattr(agent, "model", "") or ""),
+ base_url=base_url,
+ capability=_ANSWER_IN_REASONING_CAPABILITY,
+ custom_providers=getattr(agent, "_custom_providers", None),
+ )
+ if configured is not None:
+ return configured
+ except Exception:
+ logger.debug("answer-in-reasoning capability lookup failed", exc_info=True)
+
+ model = str(getattr(agent, "model", "") or "").strip().lower()
+ if _NEMOTRON_PARSER_MODEL_MARKER not in model:
+ return False
+ from agent.model_metadata import is_local_endpoint
+
+ return is_local_endpoint(base_url)
+
+
+def _ensure_answer_in_reasoning_capability(agent: Any) -> None:
+ """Keep the answer-in-reasoning decision in the live route capability map.
+
+ Runtime capability maps are rebuilt during startup, fallback activation, restore, and
+ model switches. Add the decision only when the caller did not provide an explicit value,
+ so a trusted route opt-in survives those rebuilds without carrying it to another route.
+ """
+ capabilities = getattr(agent, "runtime_capabilities", None)
+ if isinstance(capabilities, dict) and _ANSWER_IN_REASONING_CAPABILITY not in capabilities:
+ capabilities[_ANSWER_IN_REASONING_CAPABILITY] = answer_in_reasoning_capability(agent)
+
+
def _api_error_debug_info(error: Exception) -> Dict[str, Any]:
info: Dict[str, Any] = {"type": type(error).__name__, "message": str(error)}
info.update({
@@ -2550,6 +2615,7 @@ def switch_model(
# Publish the destination capability map only after every runtime setup above has succeeded.
# Failed switches must leave the old map intact.
agent.runtime_capabilities = destination_capabilities
+ _ensure_answer_in_reasoning_capability(agent)
# Reset the cross-turn stale-call circuit breaker; otherwise the latched streak keeps
# short-circuiting the freshly selected healthy provider.
from agent.chat_completion_helpers import _reset_stale_streak
@@ -3900,6 +3966,7 @@ __all__ = [
"convert_to_trajectory_format", "sanitize_tool_call_arguments", "repair_message_sequence",
"strip_think_blocks", "recover_with_credential_pool", "try_recover_primary_transport",
"drop_thinking_only_and_merge_users", "restore_primary_runtime", "extract_reasoning",
+ "answer_in_reasoning_capability",
"dump_api_request_debug", "prompt_caching_disabled_from_config", "blank_cache_policy_stub",
"plan_cache_sections_for_destination", "anthropic_prompt_cache_policy", "create_openai_client",
"switch_model", "invoke_tool", "repair_tool_call", "sanitize_api_messages",
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index db9ea4fa367..deb82d0bc64 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -2191,6 +2191,8 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None, reset_a
from agent.native_compaction import resolve_native_compaction_capabilities
agent.runtime_capabilities = resolve_native_compaction_capabilities(
model=agent.model, base_url=agent.base_url, provider=fb_provider, is_codex_backend=fb_provider == "openai-codex")
+ from agent.agent_runtime_helpers import _ensure_answer_in_reasoning_capability
+ _ensure_answer_in_reasoning_capability(agent)
return True
except Exception as e:
if fb_provider == "nous":
diff --git a/agent/turn_empty_response.py b/agent/turn_empty_response.py
index dda33917a25..8788d648db7 100644
--- a/agent/turn_empty_response.py
+++ b/agent/turn_empty_response.py
@@ -17,7 +17,6 @@ from typing import Any, Dict, List, Optional
from agent import empty_response_guard as _empty_guard
from agent.message_metadata import append_message
from agent.turn_context_compaction import _refund_api_call
-from agent.turn_failure_copy import site_copy
from agent.turn_recovery import interruptible_backoff_sleep
logger = logging.getLogger("agent.conversation_loop")
@@ -97,8 +96,8 @@ def _retry_empty(
def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, messages: Any) -> str:
"""Retries and fallback exhausted: persist the ``(empty)`` sentinel row and return the
- delivery text. Reasoning is surfaced ONLY here, for delivery — the persisted row keeps
- the sentinel so later "continue" turns don't replay it and loop on empties."""
+ delivery text. Reasoning is never copied into the delivery text here — the persisted row
+ keeps the sentinel so later "continue" turns don't replay it and loop on empties."""
_streak_cost = _empty_guard.streak_cost_usd(agent)
if _streak_cost is not None:
agent._buffer_diagnostic_status(
@@ -127,14 +126,15 @@ def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, mess
)
return "(empty)"
- reasoning_preview = reasoning_text[:500] + "..." if len(reasoning_text) > 500 else reasoning_text
logger.warning(
- "Reasoning-only response (no visible content) after exhausting retries and fallback. Reasoning: %s", reasoning_preview,
+ "Reasoning-only response after %d retries; keeping it out of the terminal result "
+ "(model=%s provider=%s)",
+ agent._empty_content_retries, agent.model, agent.provider,
)
agent._emit_diagnostic_status(
"⚠️ Model produced reasoning but no visible response after all retries. Returning empty."
)
- return site_copy("reasoning_only", model=agent.model, preview=reasoning_preview)
+ return "(empty)"
def recover_empty_response(
diff --git a/agent/turn_final_response.py b/agent/turn_final_response.py
index 5d299c6c2bf..33d24ae32d4 100644
--- a/agent/turn_final_response.py
+++ b/agent/turn_final_response.py
@@ -84,8 +84,9 @@ def finish_text_response(
result=result,
)
- # Reasoning-only clean stop: some reasoning parsers (vLLM nemotron_v3 past ~500K
- # prompt tokens) file the whole answer as reasoning when the model omits the closing
+ # Reasoning-only clean stop on a trusted route (``answer_in_reasoning_capability``; on
+ # any other route reasoning is private and takes the recovery ladder): some reasoning
+ # parsers (vLLM nemotron_v3 past ~500K prompt tokens) file the whole answer as reasoning when the model omits the closing
# delimiter. ``finish_reason == "stop"`` means the provider considers generation
# complete, so the empty-response ladder would only re-bill the same input to arrive
# at a truncated preview of this text; promote the reasoning to the visible answer
@@ -112,7 +113,12 @@ def finish_text_response(
for d in getattr(assistant_message, "reasoning_details", None) or ()
)
):
- _promoted = agent._extract_reasoning(assistant_message) or None
+ from agent.agent_runtime_helpers import answer_in_reasoning_capability
+
+ _promoted = (
+ agent._extract_reasoning(assistant_message)
+ if answer_in_reasoning_capability(agent) else None
+ )
if _promoted:
# WARNING, not INFO: a model that keeps ending turns this way is stalled
# (planning monologue, zero tool calls) while the turn reports "complete".
diff --git a/tests/agent/test_empty_terminal_reasoning_surface.py b/tests/agent/test_empty_terminal_reasoning_surface.py
index 6711a329f0e..5dd9024186e 100644
--- a/tests/agent/test_empty_terminal_reasoning_surface.py
+++ b/tests/agent/test_empty_terminal_reasoning_surface.py
@@ -1,12 +1,12 @@
"""Tests for reasoning-only final responses.
A clean-stop response (``finish_reason == "stop"``) with no ordinary content but
-structured reasoning IS the answer: the reasoning is promoted to the visible reply and
-persisted as assistant content without entering the empty-response recovery ladder
-(every rung re-bills the full prompt). Idea credit: PR #48795 (@ligl0325).
+structured reasoning is promoted only for an explicitly trusted route; private reasoning
+stays in the recovery path and never becomes the visible reply. Idea credit: PR #48795
+(@ligl0325).
Invariants pinned here:
-- Clean-stop reasoning-only → returned and persisted after ONE API call.
+- Trusted clean-stop reasoning-only → returned and persisted after ONE API call.
- ``finish_reason == "length"`` reasoning is unfinished: never promoted, the
continuation path still owns it.
- A truly empty response (no reasoning either) still reaches the ladder terminal.
@@ -42,6 +42,9 @@ def _build_agent(tmp_path, monkeypatch):
# Route through the non-streaming _interruptible_api_call path so the
# monkeypatched fake responses are what the loop consumes.
agent._disable_streaming = True
+ # This fixture represents the explicit parser-compatible route. Private reasoning
+ # tests clear the capability and use an OpenRouter route instead.
+ agent.runtime_capabilities["answer_in_reasoning"] = True
return agent
@@ -79,6 +82,96 @@ def _truly_empty_response():
)
+def _private_reasoning_only_response():
+ return SimpleNamespace(
+ choices=[SimpleNamespace(
+ message=SimpleNamespace(
+ content=None,
+ reasoning="private thoughts that must not be shown",
+ reasoning_content="private thoughts that must not be shown",
+ reasoning_details=None,
+ tool_calls=None,
+ ),
+ finish_reason="stop",
+ )],
+ usage=None,
+ model="deepseek/deepseek-v4.1",
+ )
+
+
+def test_answer_in_reasoning_requires_a_trusted_route():
+ """A generic reasoning field is not enough to opt into answer promotion."""
+ from agent.agent_runtime_helpers import answer_in_reasoning_capability
+
+ agent = SimpleNamespace(
+ model="nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4",
+ base_url="http://127.0.0.1:8000/v1",
+ provider="vllm",
+ api_mode="chat_completions",
+ runtime_capabilities={},
+ _custom_providers=[],
+ )
+ assert answer_in_reasoning_capability(agent) is True
+
+ agent.provider = "openrouter"
+ agent.base_url = "https://openrouter.ai/api/v1"
+ assert answer_in_reasoning_capability(agent) is False
+
+ agent.provider = "vllm"
+ agent.base_url = "http://127.0.0.1:8000/v1"
+ agent.model = "deepseek/deepseek-v4.1"
+ assert answer_in_reasoning_capability(agent) is False
+
+
+def test_answer_in_reasoning_capability_survives_route_map_rebuild():
+ """Route refreshes add the decision without carrying it to another route."""
+ from agent.agent_runtime_helpers import _ensure_answer_in_reasoning_capability
+
+ agent = SimpleNamespace(
+ model="nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4",
+ base_url="http://127.0.0.1:8000/v1",
+ provider="vllm",
+ api_mode="chat_completions",
+ runtime_capabilities={"native_compaction": False},
+ _custom_providers=[],
+ )
+ _ensure_answer_in_reasoning_capability(agent)
+ assert agent.runtime_capabilities["answer_in_reasoning"] is True
+
+ agent.model = "deepseek/deepseek-v4.1"
+ agent.runtime_capabilities = {"native_compaction": False}
+ _ensure_answer_in_reasoning_capability(agent)
+ assert agent.runtime_capabilities["answer_in_reasoning"] is False
+
+ agent.runtime_capabilities["answer_in_reasoning"] = True
+ _ensure_answer_in_reasoning_capability(agent)
+ assert agent.runtime_capabilities["answer_in_reasoning"] is True
+
+
+def test_constructor_capability_reaches_runtime_map_and_primary_snapshot(tmp_path, monkeypatch):
+ """An explicit startup opt-in must drive the live route and its restore snapshot."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / ".env").write_text("", encoding="utf-8")
+ (tmp_path / "config.yaml").write_text("{}\n", encoding="utf-8")
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ model="test-model",
+ api_key="sk-dummy",
+ provider="vllm",
+ api_mode="chat_completions",
+ base_url="http://127.0.0.1:8000/v1",
+ capabilities={"answer_in_reasoning": True},
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ platform="cli",
+ )
+
+ assert agent.runtime_capabilities["answer_in_reasoning"] is True
+ assert agent._primary_runtime["runtime_capabilities"]["answer_in_reasoning"] is True
+
+
def test_clean_stop_reasoning_only_returns_on_first_call(tmp_path, monkeypatch):
"""A clean stop promotes structured reasoning without a recovery call."""
agent = _build_agent(tmp_path, monkeypatch)
@@ -148,3 +241,50 @@ def test_length_cut_reasoning_is_not_promoted(tmp_path, monkeypatch):
assert result["final_response"] == "42."
assert result["api_calls"] == 2
+
+
+def test_private_reasoning_retries_to_visible_answer(tmp_path, monkeypatch):
+ """A provider's private reasoning stays out of the answer, even when both generic
+ reasoning fields contain the same text."""
+ agent = _build_agent(tmp_path, monkeypatch)
+ agent.runtime_capabilities["answer_in_reasoning"] = False
+ agent.provider = "openrouter"
+ agent.base_url = "https://openrouter.ai/api/v1"
+ responses = [
+ _private_reasoning_only_response(),
+ SimpleNamespace(
+ choices=[SimpleNamespace(
+ message=SimpleNamespace(
+ content="the visible answer",
+ reasoning=None,
+ reasoning_content=None,
+ reasoning_details=None,
+ tool_calls=None,
+ ),
+ finish_reason="stop",
+ )],
+ usage=None,
+ model="deepseek/deepseek-v4.1",
+ ),
+ ]
+ monkeypatch.setattr(agent, "_interruptible_api_call", lambda api_kwargs: responses.pop(0))
+
+ result = agent.run_conversation("what is the answer?")
+
+ assert result["final_response"] == "the visible answer"
+ assert result["api_calls"] == 2 # the visible retry follows one thinking-prefill call
+ assert all("private thoughts" not in str(message.get("content", "")) for message in result["messages"])
+
+
+def test_private_reasoning_is_not_echoed_when_recovery_exhausts(tmp_path, monkeypatch):
+ """Exhausted recovery returns the empty sentinel without exposing a private preview."""
+ agent = _build_agent(tmp_path, monkeypatch)
+ agent.runtime_capabilities["answer_in_reasoning"] = False
+ agent.provider = "openrouter"
+ agent.base_url = "https://openrouter.ai/api/v1"
+ monkeypatch.setattr(agent, "_interruptible_api_call", lambda api_kwargs: _private_reasoning_only_response())
+
+ result = agent.run_conversation("hello?")
+
+ assert "private thoughts" not in result["final_response"]
+ assert all("private thoughts" not in str(message.get("content", "")) for message in result["messages"])
diff --git a/tests/agent/test_fallback_reasoning_override.py b/tests/agent/test_fallback_reasoning_override.py
index 40526e9a8c3..8ea276dbcde 100644
--- a/tests/agent/test_fallback_reasoning_override.py
+++ b/tests/agent/test_fallback_reasoning_override.py
@@ -107,7 +107,10 @@ class TestFallbackReasoningOverride:
assert result is True
# reasoning_config should be restored to primary's value (medium)
assert agent.reasoning_config == {"enabled": True, "effort": "medium"}
- assert agent.runtime_capabilities == {"native_compaction": True}
+ assert agent.runtime_capabilities == {
+ "native_compaction": True,
+ "answer_in_reasoning": False,
+ }
def test_fallback_global_fallback_with_yaml_false(self):
"""Fallback global fallback must not coerce YAML boolean False.
@@ -135,3 +138,55 @@ class TestFallbackReasoningOverride:
assert result is not None
assert result.get("enabled") is False
+
+
[email protected]("primary_answer, fallback_answer", [(False, True), (True, False)])
+def test_fallback_restore_preserves_primary_answer_capability(primary_answer, fallback_answer):
+ """Restoring a route must restore its own reasoning capability, not the fallback's."""
+ from agent.agent_runtime_helpers import restore_primary_runtime
+
+ agent = MagicMock()
+ agent._primary_runtime = {
+ "model": "primary-model",
+ "provider": "primary-provider",
+ "base_url": "",
+ "api_mode": "openai",
+ "api_key": "key",
+ "client_kwargs": {},
+ "use_prompt_caching": False,
+ "use_native_cache_layout": False,
+ "runtime_capabilities": {
+ "native_compaction": True,
+ "answer_in_reasoning": primary_answer,
+ },
+ "reasoning_config": {"enabled": True, "effort": "medium"},
+ "compressor_model": "primary-model",
+ "compressor_base_url": "",
+ "compressor_api_key": "",
+ "compressor_provider": "primary-provider",
+ "compressor_context_length": 0,
+ "compressor_api_mode": "",
+ "compressor_threshold_tokens": 0,
+ }
+ agent._fallback_activated = True
+ agent._fallback_index = 0
+ agent._fallback_chain = []
+ agent._fallback_model = None
+ agent._transport_cache = {}
+ agent._config_context_length = None
+ agent._rate_limited_until = 0
+ agent.model = "fallback-model"
+ agent.provider = "fallback-provider"
+ agent.reasoning_config = {"enabled": True, "effort": "xhigh"}
+ agent.runtime_capabilities = {
+ "native_compaction": False,
+ "answer_in_reasoning": fallback_answer,
+ }
+ agent.context_compressor = MagicMock()
+ agent.base_url = ""
+ agent._anthropic_prompt_cache_policy = MagicMock(return_value=(False, False))
+ agent._create_openai_client = MagicMock(return_value=MagicMock())
+ agent._ensure_lmstudio_runtime_loaded = MagicMock()
+
+ assert restore_primary_runtime(agent) is True
+ assert agent.runtime_capabilities["answer_in_reasoning"] is primary_answer
diff --git a/tests/agent/test_reasoning_only_stop_persistence.py b/tests/agent/test_reasoning_only_stop_persistence.py
index 507d34dcad9..61dc3c725bc 100644
--- a/tests/agent/test_reasoning_only_stop_persistence.py
+++ b/tests/agent/test_reasoning_only_stop_persistence.py
@@ -27,9 +27,9 @@ def loop_agent():
):
agent = AIAgent(
api_key="test-key-1234567890",
- base_url="https://api.deepseek.com/v1",
- model="deepseek-reasoner",
- provider="deepseek",
+ base_url="http://127.0.0.1:8000/v1",
+ model="nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4",
+ provider="vllm",
quiet_mode=True,
skip_context_files=True,
skip_memory=True,
diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.py
index 76c2e4b305b..a036d6122a7 100644
--- a/tests/agent/test_run_agent.py
+++ b/tests/agent/test_run_agent.py
@@ -3498,6 +3498,7 @@ class TestRunConversation:
def test_reasoning_only_local_clean_stop_returns_immediately(self, agent):
"""A clean-stop reasoning answer returns without compression or recovery."""
self._setup_agent(agent)
+ agent.runtime_capabilities["answer_in_reasoning"] = True
agent.base_url = "http://127.0.0.1:1234/v1"
agent.compression_enabled = True
empty_resp = _mock_response(
diff --git a/tests/agent/test_switch_model_context.py b/tests/agent/test_switch_model_context.py
index 145aa0e82dd..8df2e3a9940 100644
--- a/tests/agent/test_switch_model_context.py
+++ b/tests/agent/test_switch_model_context.py
@@ -193,7 +193,10 @@ def test_switch_model_omitted_base_url_preserves_direct_openai_capability():
agent.switch_model("gpt-5.6", "openai", api_key="sk-new")
assert agent.base_url == "https://api.openai.com/v1"
- assert agent.runtime_capabilities == {"native_compaction": True}
+ assert agent.runtime_capabilities == {
+ "native_compaction": True,
+ "answer_in_reasoning": False,
+ }
def test_cross_provider_switch_to_default_openai_preserves_native_capability():
@@ -208,7 +211,10 @@ def test_cross_provider_switch_to_default_openai_preserves_native_capability():
agent.switch_model("gpt-5.6", "openai", api_key="sk-new")
assert agent.base_url == "https://api.openai.com/v1"
- assert agent.runtime_capabilities == {"native_compaction": True}
+ assert agent.runtime_capabilities == {
+ "native_compaction": True,
+ "answer_in_reasoning": False,
+ }
def test_direct_start_model_override_does_not_inherit_profile_context_length():