Skip to content

The agent that grows with you

refactor(agent): derive reasoning-promotion trust live in agent/reasoning_promotion

kshitijk4poor2f0efe8f6676
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 9cf04cae8b5..a384a412eec 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -2066,11 +2066,6 @@ 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
@@ -2308,7 +2303,6 @@ 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 f356a5da022..16a95fb3519 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1316,7 +1316,6 @@ 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")
@@ -1575,67 +1574,6 @@ 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 (the lookup
- # returns None on unreadable config).
- 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
-
- 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({
@@ -2612,7 +2550,6 @@ 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
@@ -3963,7 +3900,6 @@ __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 deb82d0bc64..db9ea4fa367 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -2191,8 +2191,6 @@ 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/reasoning_promotion.py b/agent/reasoning_promotion.py
new file mode 100644
index 00000000000..a9d3e27eeea
--- /dev/null
+++ b/agent/reasoning_promotion.py
@@ -0,0 +1,59 @@
+"""Whether a reasoning-only clean stop may be promoted to the visible answer.
+
+A field name is not provenance: OpenRouter, DeepSeek, Bedrock and several adapters all put
+private chain-of-thought in ``reasoning``. Promotion is therefore limited to trusted routes,
+decided from the agent's LIVE route on every call so fallback activation, primary restore and
+model switches never carry a decision to another route.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from utils import base_url_host_matches
+
+_ANSWER_IN_REASONING_CAPABILITY = "answer_in_reasoning"
+_NEMOTRON_PARSER_MODEL_MARKER = "nemotron-3.5-lightning"
+
+
+def answer_in_reasoning_capability(agent: Any) -> bool:
+ """True when the live route may return a clean-stop reasoning payload as the answer.
+
+ Trusted: an explicit ``answer_in_reasoning`` bool in ``runtime_capabilities``, a
+ custom_providers per-model ``answer_in_reasoning`` opt-in, or the local
+ Nemotron-3.5-Lightning parser route from #109205. OpenRouter and non-chat-completions
+ transports are never trusted.
+ """
+ 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
+
+ # Returns None on unreadable config, so no guard is needed here.
+ from hermes_cli.config import get_custom_provider_model_capability
+
+ model = str(getattr(agent, "model", "") or "")
+ configured = get_custom_provider_model_capability(
+ model=model,
+ base_url=base_url,
+ capability=_ANSWER_IN_REASONING_CAPABILITY,
+ custom_providers=getattr(agent, "_custom_providers", None),
+ )
+ if configured is not None:
+ return configured
+
+ if _NEMOTRON_PARSER_MODEL_MARKER not in model.lower():
+ return False
+ from agent.model_metadata import is_local_endpoint
+
+ return is_local_endpoint(base_url)
diff --git a/agent/turn_final_response.py b/agent/turn_final_response.py
index 33d24ae32d4..b64ec35be22 100644
--- a/agent/turn_final_response.py
+++ b/agent/turn_final_response.py
@@ -12,6 +12,7 @@ import logging
from typing import Any, Dict, Optional
from agent.message_metadata import append_message
+from agent.reasoning_promotion import answer_in_reasoning_capability
from agent.repetition_guard import STOP_PATH_MIN_CHARS, is_runaway_repetition
from agent.turn_failure_copy import stamp_failure
from agent.turn_empty_response import recover_empty_response
@@ -84,13 +85,10 @@ def finish_text_response(
result=result,
)
- # 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
- # BEFORE the ladder. ``length`` (cut off mid-thought) stays on the continuation path.
+ # Reasoning-only clean stop on a trusted route (elsewhere reasoning is private and takes the
+ # ladder): some parsers (vLLM nemotron_v3 past ~500K prompt tokens) file the whole answer as
+ # reasoning when the closing delimiter is missing; ``stop`` means generation is complete, so
+ # promote it BEFORE the ladder. ``length`` (cut off mid-thought) stays on the continuation path.
# The promoted text is RETURNED as the answer but never written into the assistant
# row's ``content``: chain-of-thought stored as ordinary content is indistinguishable
# from a real reply on every history surface (#111761). The row keeps ``content``
@@ -112,13 +110,9 @@ def finish_text_response(
)
for d in getattr(assistant_message, "reasoning_details", None) or ()
)
+ and answer_in_reasoning_capability(agent)
):
- from agent.agent_runtime_helpers import answer_in_reasoning_capability
-
- _promoted = (
- agent._extract_reasoning(assistant_message)
- if answer_in_reasoning_capability(agent) else None
- )
+ _promoted = agent._extract_reasoning(assistant_message) or 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_fallback_reasoning_override.py b/tests/agent/test_fallback_reasoning_override.py
index 1ebf4096e6b..40526e9a8c3 100644
--- a/tests/agent/test_fallback_reasoning_override.py
+++ b/tests/agent/test_fallback_reasoning_override.py
@@ -107,10 +107,7 @@ 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,
- "answer_in_reasoning": False,
- }
+ assert agent.runtime_capabilities == {"native_compaction": True}
def test_fallback_global_fallback_with_yaml_false(self):
"""Fallback global fallback must not coerce YAML boolean False.
diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.py
index a036d6122a7..758e3371a79 100644
--- a/tests/agent/test_run_agent.py
+++ b/tests/agent/test_run_agent.py
@@ -3525,7 +3525,6 @@ class TestRunConversation:
assert result["final_response"] == "reasoning only"
assert result["api_calls"] == 1
-
def test_truly_empty_response_stops_after_repeated_empty(self, agent):
"""Repeated empty responses stop after one retry and return an explanation."""
self._setup_agent(agent)
diff --git a/tests/agent/test_switch_model_context.py b/tests/agent/test_switch_model_context.py
index 8df2e3a9940..145aa0e82dd 100644
--- a/tests/agent/test_switch_model_context.py
+++ b/tests/agent/test_switch_model_context.py
@@ -193,10 +193,7 @@ 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,
- "answer_in_reasoning": False,
- }
+ assert agent.runtime_capabilities == {"native_compaction": True}
def test_cross_provider_switch_to_default_openai_preserves_native_capability():
@@ -211,10 +208,7 @@ 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,
- "answer_in_reasoning": False,
- }
+ assert agent.runtime_capabilities == {"native_compaction": True}
def test_direct_start_model_override_does_not_inherit_profile_context_length():