Skip to content

The agent that grows with you

feat(config): per-provider reasoning_echo opt-in for custom providers

Yingliang Zhang73243b0d2e4c
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 938e13f6128..155ddba5787 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -913,6 +913,16 @@ def init_agent(
# Model response configuration
agent.max_tokens = max_tokens # None = use model default
agent.reasoning_config = reasoning_config # None = use default (medium for OpenRouter)
+ # Per-provider reasoning_content echo opt-in (see _reasoning_echo_opt_in).
+ # Read once at init; switch_model / try_activate_fallback / restore
+ # keep it in sync with the active provider.
+ try:
+ from hermes_cli.config import load_config_readonly
+ agent._reasoning_echo_flag = bool(
+ (load_config_readonly().get("model") or {}).get("reasoning_echo")
+ )
+ except Exception:
+ agent._reasoning_echo_flag = False
agent.service_tier = service_tier
agent.request_overrides = dict(request_overrides or {})
agent.prefill_messages = prefill_messages or [] # Prefilled conversation turns
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 79cfe58135c..451b3a09278 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1349,6 +1349,7 @@ def try_recover_primary_transport(
if hasattr(agent, "_transport_cache"):
agent._transport_cache.clear()
agent.api_key = rt["api_key"]
+ agent._reasoning_echo_flag = rt.get("reasoning_echo_flag", False)
if agent.api_mode == "anthropic_messages":
from agent.anthropic_adapter import build_anthropic_client
@@ -1579,6 +1580,7 @@ def restore_primary_runtime(agent) -> bool:
if hasattr(agent, "_transport_cache"):
agent._transport_cache.clear()
agent.api_key = rt["api_key"]
+ agent._reasoning_echo_flag = rt.get("reasoning_echo_flag", False)
agent._client_kwargs = dict(rt["client_kwargs"])
agent._use_prompt_caching = rt["use_prompt_caching"]
# Default to native layout when the restored snapshot predates the
@@ -2685,6 +2687,15 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo
agent.model = new_model
agent.provider = new_provider
agent.requested_provider = new_provider
+ # Re-read reasoning_echo from config so the flag reflects the new
+ # primary model's setting (see _reasoning_echo_opt_in).
+ try:
+ from hermes_cli.config import load_config_readonly
+ agent._reasoning_echo_flag = bool(
+ (load_config_readonly().get("model") or {}).get("reasoning_echo")
+ )
+ except Exception:
+ agent._reasoning_echo_flag = False
# Use the new base_url when provided. When it's empty AND the
# provider is actually changing, do NOT fall back to the current
# (old provider's) URL — that silently pairs the new provider label
@@ -2970,6 +2981,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo
"use_prompt_caching": agent._use_prompt_caching,
"use_native_cache_layout": agent._use_native_cache_layout,
"reasoning_config": dict(agent.reasoning_config) if getattr(agent, "reasoning_config", None) else None,
+ "reasoning_echo_flag": getattr(agent, "_reasoning_echo_flag", False),
"compressor_model": getattr(_cc, "model", agent.model) if _cc else agent.model,
"compressor_base_url": getattr(_cc, "base_url", agent.base_url) if _cc else agent.base_url,
"compressor_api_key": getattr(_cc, "api_key", "") if _cc else "",
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 48053627312..7af486dc5bb 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -2652,6 +2652,10 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool
agent.requested_provider = fb_provider
agent.base_url = fb_base_url
agent.api_mode = fb_api_mode
+ # Per-provider reasoning_content echo opt-in (see _reasoning_echo_opt_in).
+ # Read from the fallback entry so the flag travels with the active
+ # provider; restore_primary_runtime will revert it from the snapshot.
+ agent._reasoning_echo_flag = bool(fb.get("reasoning_echo", False))
if hasattr(agent, "_transport_cache"):
agent._transport_cache.clear()
agent._fallback_activated = True
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 29ae25d7f70..e55b3d923d7 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -328,6 +328,20 @@ DEFAULT_CONFIG = {
# matches a key in this dict.
# Edit directly in config.yaml (no CLI support due to dots in keys).
"reasoning_overrides": {},
+
+ # Per-provider opt-in to preserve assistant ``reasoning_content``
+ # when replaying history. The built-in echo families (DeepSeek,
+ # Kimi/Moonshot, Xiaomi MiMo) are auto-detected by provider name
+ # and base-URL host. Custom providers and OpenAI-compatible
+ # gateways that proxy those same models (or other thinking-mode
+ # backends) are not covered by the host-based rules.
+ #
+ # Set ``reasoning_echo: true`` on a ``model:`` entry (primary) or a
+ # ``fallback_providers:`` entry (per-fallback) to preserve
+ # ``reasoning_content`` on replay for that provider only. Default
+ # ``false`` keeps the historical strict-provider behavior (Mistral,
+ # Groq, Cerebras reject the field with HTTP 400).
+ "reasoning_echo": False,
},
"terminal": {
diff --git a/run_agent.py b/run_agent.py
index b4308f27a6c..548c9953d83 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -7760,10 +7760,36 @@ class AIAgent:
self._needs_deepseek_tool_reasoning()
or self._needs_kimi_tool_reasoning()
or self._needs_mimo_tool_reasoning()
+ or self._reasoning_echo_opt_in()
)
self._thinking_pad_cache = (key, result)
return result
+ def _reasoning_echo_opt_in(self) -> bool:
+ """Return True when the user has opted in to ``reasoning_content``
+ echo-back for the *current* provider via config.
+
+ This covers custom providers and OpenAI-compatible gateways that
+ proxy thinking-mode models (e.g. a reverse proxy fronting Kimi K3
+ or GLM-5.2) but are not matched by the built-in host-based
+ ``_REASONING_ECHO_RULES`` (DeepSeek / Kimi / MiMo).
+
+ The flag is per-active-provider:
+
+ * **Primary** — read from ``model.reasoning_echo`` in config.yaml
+ at agent init and on ``switch_model()``.
+ * **Fallback** — set by ``try_activate_fallback()`` from the
+ fallback entry's ``reasoning_echo`` field.
+ * **Restore** — ``restore_primary_runtime()`` copies the snapshot
+ saved by ``switch_model()``.
+
+ Unlike a global toggle, this flag travels with the active
+ provider, so falling back to a strict provider (Mistral, Groq,
+ Cerebras) correctly strips ``reasoning_content`` even when the
+ primary had the flag enabled.
+ """
+ return bool(getattr(self, "_reasoning_echo_flag", False))
+
def _needs_kimi_tool_reasoning(self) -> bool:
"""Return True when the current provider is Kimi / Moonshot thinking mode.
diff --git a/tests/agent/test_message_sanitization_policy.py b/tests/agent/test_message_sanitization_policy.py
index b363b73ff2a..683d2d8df0f 100644
--- a/tests/agent/test_message_sanitization_policy.py
+++ b/tests/agent/test_message_sanitization_policy.py
@@ -294,3 +294,187 @@ class TestReapplyReasoningEcho:
assert reapply_reasoning_echo(msgs, True) == 0
reapply_reasoning_echo(msgs, False)
assert reapply_reasoning_echo(msgs, False) == 0
+
+
+# ---------------------------------------------------------------------------
+# Per-provider reasoning_echo config opt-in — preserves reasoning_content
+# on replay for custom providers / OpenAI-compatible gateways that proxy
+# thinking-mode models but are not matched by the built-in host-based
+# _REASONING_ECHO_RULES (DeepSeek / Kimi / MiMo).
+#
+# The flag is per-active-provider:
+# - Primary: read from ``model.reasoning_echo`` in config at init / switch_model
+# - Fallback: set by try_activate_fallback from the fallback entry's field
+# - Restore: restore_primary_runtime copies the snapshot saved by switch_model
+#
+# Unlike a global toggle, the flag travels with the active provider, so
+# falling back to a strict provider (Mistral, Groq, Cerebras) correctly
+# strips reasoning_content even when the primary had the flag enabled.
+# ---------------------------------------------------------------------------
+
+class TestPerProviderReasoningEcho:
+ """Verify the per-provider reasoning_echo opt-in flag."""
+
+ def _make_agent(self, reasoning_echo_flag=False, provider="custom",
+ model="my-model", base_url="https://gw.example.com/v1"):
+ """Build a minimal AIAgent-shaped object without full init."""
+ from run_agent import AIAgent
+ agent = object.__new__(AIAgent)
+ agent.provider = provider
+ agent.model = model
+ agent.base_url = base_url
+ agent._base_url_lower = base_url.lower()
+ agent._thinking_pad_cache = None
+ agent._reasoning_echo_flag = reasoning_echo_flag
+ agent._needs_deepseek_tool_reasoning = lambda: False
+ agent._needs_kimi_tool_reasoning = lambda: False
+ agent._needs_mimo_tool_reasoning = lambda: False
+ return agent
+
+ def test_default_false_strips_for_custom_provider(self):
+ """Default (flag=False): a custom gateway is NOT an echo family,
+ so reasoning_content is stripped — historical behavior."""
+ agent = self._make_agent(reasoning_echo_flag=False)
+ assert agent._needs_thinking_reasoning_pad() is False
+ assert agent._reasoning_echo_opt_in() is False
+
+ def test_opt_in_preserves_for_custom_provider(self):
+ """Flag on: even a non-echo-family custom gateway keeps
+ reasoning_content on replay."""
+ agent = self._make_agent(reasoning_echo_flag=True)
+ assert agent._needs_thinking_reasoning_pad() is True
+ assert agent._reasoning_echo_opt_in() is True
+
+ def test_opt_in_does_not_replace_family_detection(self):
+ """Kimi-coding family still gets echo-back regardless of the flag."""
+ agent = self._make_agent(
+ reasoning_echo_flag=False,
+ provider="kimi-coding",
+ model="t9s/kimi-k3",
+ )
+ agent._needs_kimi_tool_reasoning = lambda: True
+ assert agent._needs_thinking_reasoning_pad() is True
+
+ def test_opt_in_additive_with_family_detection(self):
+ """Flag on AND family match: both paths agree, still True."""
+ agent = self._make_agent(
+ reasoning_echo_flag=True,
+ provider="deepseek",
+ model="deepseek-v4-pro",
+ )
+ agent._needs_deepseek_tool_reasoning = lambda: True
+ assert agent._needs_thinking_reasoning_pad() is True
+
+ def test_strict_fallback_strips_despite_primary_opt_in(self):
+ """Primary has flag=True, fallback switches to a strict provider.
+ The fallback reconciling path (reapply_reasoning_echo_for_provider)
+ uses _needs_thinking_reasoning_pad which checks the *current*
+ provider's flag — strict providers have flag=False, so the field
+ is stripped (no HTTP 400)."""
+ agent = self._make_agent(reasoning_echo_flag=True) # primary opt-in
+ # Simulate fallback to a strict provider
+ agent.provider = "mistral"
+ agent.model = "mistral-large"
+ agent.base_url = "https://api.mistral.ai/v1"
+ agent._base_url_lower = "https://api.mistral.ai/v1"
+ agent._thinking_pad_cache = None # invalidate per-provider cache
+ agent._reasoning_echo_flag = False # fallback entry has no opt-in
+ assert agent._needs_thinking_reasoning_pad() is False
+ # End-to-end: reapply_reasoning_echo strips the field
+ from agent.agent_runtime_helpers import reapply_reasoning_echo_for_provider
+ api_msgs = [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "hi", "reasoning_content": "thoughts"},
+ {"role": "assistant", "content": "hi2", "reasoning_content": " "},
+ {"role": "user", "content": "bye"},
+ ]
+ changed = reapply_reasoning_echo_for_provider(agent, api_msgs)
+ assert changed == 2
+ for m in api_msgs:
+ if m["role"] == "assistant":
+ assert "reasoning_content" not in m
+
+ def test_fallback_opt_in_preserves_reasoning(self):
+ """Fallback to a custom provider with reasoning_echo=True:
+ the field is preserved/re-padded."""
+ agent = self._make_agent(reasoning_echo_flag=False) # primary no opt-in
+ # Simulate fallback to a custom provider with opt-in
+ agent.provider = "custom"
+ agent.model = "t9s/kimi-k3"
+ agent.base_url = "https://gw.example.com/v1"
+ agent._base_url_lower = "https://gw.example.com/v1"
+ agent._thinking_pad_cache = None
+ agent._reasoning_echo_flag = True # fallback entry has opt-in
+ assert agent._needs_thinking_reasoning_pad() is True
+ # End-to-end: reapply_reasoning_echo re-pads
+ from agent.agent_runtime_helpers import reapply_reasoning_echo_for_provider
+ api_msgs = [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "hi"}, # no reasoning_content
+ {"role": "user", "content": "bye"},
+ ]
+ changed = reapply_reasoning_echo_for_provider(agent, api_msgs)
+ assert changed == 1
+ assert api_msgs[1].get("reasoning_content") == " "
+
+ def test_restore_primary_reverts_flag(self):
+ """After fallback, restore_primary_runtime reverts the flag
+ from the snapshot saved by switch_model."""
+ from run_agent import AIAgent
+ agent = object.__new__(AIAgent)
+ agent._reasoning_echo_flag = True # primary had opt-in
+ agent._fallback_activated = True
+ agent._rate_limited_until = 0
+ agent._primary_runtime = {
+ "model": "glm-5.2",
+ "provider": "custom",
+ "requested_provider": "custom",
+ "base_url": "https://gw.example.com/v1",
+ "api_mode": "chat_completions",
+ "api_key": "sk-test",
+ "client_kwargs": {"api_key": "sk-test", "base_url": "https://gw.example.com/v1"},
+ "use_prompt_caching": True,
+ "use_native_cache_layout": False,
+ "reasoning_echo_flag": True, # snapshot saved by switch_model
+ }
+ agent._transport_cache = {}
+ agent.client = None
+ agent._client_kwargs = {"api_key": "sk-fallback", "base_url": "https://fallback.com/v1"}
+ agent._use_prompt_caching = False
+ agent._use_native_cache_layout = False
+ agent.api_mode = "chat_completions"
+ agent.api_key = "sk-fallback"
+ agent.model = "fallback-model"
+ agent.provider = "fallback-provider"
+ agent.requested_provider = "fallback-provider"
+ agent.base_url = "https://fallback.com/v1"
+ agent.context_compressor = None
+ agent._config_context_length = None
+
+ # Simulate: fallback set the flag to False
+ agent._reasoning_echo_flag = False
+
+ from agent.agent_runtime_helpers import restore_primary_runtime
+ restore_primary_runtime(agent)
+
+ # Flag should be restored from snapshot
+ assert agent._reasoning_echo_flag is True
+ assert agent.model == "glm-5.2"
+
+ def test_apply_policy_preserves_with_opt_in(self):
+ """apply_reasoning_content_policy preserves reasoning_content
+ when needs_thinking_pad is True (via opt-in)."""
+ from agent.message_sanitization import apply_reasoning_content_policy
+ source = {"role": "assistant", "content": "hi", "reasoning_content": "my thoughts"}
+ api_msg = {"role": "assistant", "content": "hi"}
+ apply_reasoning_content_policy(source, api_msg, needs_thinking_pad=True)
+ assert api_msg["reasoning_content"] == "my thoughts"
+
+ def test_apply_policy_strips_without_opt_in(self):
+ """apply_reasoning_content_policy strips reasoning_content
+ when needs_thinking_pad is False (no opt-in, not echo family)."""
+ from agent.message_sanitization import apply_reasoning_content_policy
+ source = {"role": "assistant", "content": "hi", "reasoning_content": "my thoughts"}
+ api_msg = {"role": "assistant", "content": "hi"}
+ apply_reasoning_content_policy(source, api_msg, needs_thinking_pad=False)
+ assert "reasoning_content" not in api_msg