From da8388c759642b06cb12862938047263fa5d7431 Mon Sep 17 00:00:00 2001 From: liuhao1024 Date: Sat, 19 Sep 2026 02:34:17 +0800 Subject: [PATCH 1/4] fix(agent): match enum-style reasoning_effort rejections with no unsupported marker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commandcode.ai rejects the top-level `reasoning_effort: "none"` (the disabled-reasoning encoding CustomProfile projects) with an enum 400 — "Invalid option: expected one of \"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"" — whose message carries no "unsupported" marker at all: the field name appears only in the structured 'param' tail, outside the ±32 near-window of the token match, and no UNSUPPORTED_PARAM_MARKERS entry matches the enum wording. is_reasoning_field_rejection never fires, so the strip-and-retry rung (#112781) is skipped and title generation fails outright (#115277). Add the enum wording to UNSUPPORTED_PARAM_MARKERS so both surfaces (the main-loop reasoning_mandatory rung and the auxiliary ladder) recognise it; a non-reasoning 'param' (temperature) stays unmatched because no reasoning field token appears anywhere. --- agent/error_classifier.py | 5 ++++- .../test_auxiliary_parameter_rung_chaining.py | 17 +++++++++++++++++ tests/agent/test_error_classifier.py | 10 +++++++--- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/agent/error_classifier.py b/agent/error_classifier.py index d6b0088d32..1e7f209d74 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -456,13 +456,16 @@ _REASONING_MANDATORY_PATTERN = "reasoning is mandatory" # rejects sampling params for reasoning-first models with the contraction ("This model doesn't # support the temperature field", xAI Grok) and inference-profile Claude with "`temperature` is # deprecated for this model" (#111043); strict pydantic gateways (Fireworks) name the unknown -# field as "extra inputs are not permitted" (#109774). Shared with the auxiliary retry ladder +# field as "extra inputs are not permitted" (#109774). Enum-rejecting aggregators (commandcode.ai) +# say "Invalid option: expected one of ..." with no "unsupported" anywhere, naming the field only +# in the structured 'param' tail (#115277). Shared with the auxiliary retry ladder # (``agent.auxiliary_client._is_unsupported_parameter_error``). UNSUPPORTED_PARAM_MARKERS = ( "unsupported parameter", "unsupported_parameter", "not supported", "does not support", "doesn't support", "is deprecated for this model", "unknown parameter", "unrecognized request argument", "unrecognized parameter", "invalid parameter", "extra inputs are not permitted", + "invalid option: expected one of", ) # Reasoning wire-field names (the profile reasoning controls minus ``verbosity``), longest first. diff --git a/tests/agent/test_auxiliary_parameter_rung_chaining.py b/tests/agent/test_auxiliary_parameter_rung_chaining.py index e588ccdc07..5ff70b7d50 100644 --- a/tests/agent/test_auxiliary_parameter_rung_chaining.py +++ b/tests/agent/test_auxiliary_parameter_rung_chaining.py @@ -81,6 +81,23 @@ def test_reasoning_effort_none_unsupported_reversed_wording(): assert not _is_reasoning_field_rejection(_Bad400("reasoning models: tool_choice 'required' is unsupported")) +def test_enum_rejection_with_field_in_structured_param_tail(): + """commandcode.ai rejects ``reasoning_effort: "none"`` as an enum violation whose message carries + no "unsupported" marker at all — the field name appears only in the structured ``'param'`` tail + (#115277). The enum wording still fires the strip-and-retry rung, while the same wording against + a non-reasoning parameter does not (no reasoning field token anywhere).""" + assert _is_reasoning_field_rejection(_Bad400( + "Error code: 400 - {'error': {'message': 'Invalid option: expected one of " + "\"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"', 'type': 'invalid_request_error', " + "'param': 'reasoning_effort'}}" + )) + assert not _is_reasoning_field_rejection(_Bad400( + "Error code: 400 - {'error': {'message': 'Invalid option: expected one of " + "\"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"', 'type': 'invalid_request_error', " + "'param': 'temperature'}}" + )) + + def test_fallback_candidate_recovers_from_rejected_temperature(): client = _rejecting_client("temperature") resp = _call_fallback_candidate_sync( diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.py index 8e8dab5aa1..dbc35f6342 100644 --- a/tests/agent/test_error_classifier.py +++ b/tests/agent/test_error_classifier.py @@ -893,12 +893,16 @@ class TestClassifyApiError: def test_reasoning_field_rejection_is_reasoning_mandatory(self): """A 400 rejecting a reasoning wire control by name — reversed ("reasoning_effort 'none' - unsupported; use ...", #114460) or forward ("Unrecognized request argument supplied: - reasoning_effort") — takes the drop-the-disable rung, not the format_error abort; a - model-id segment (kimi-k2-thinking) stays route gating.""" + unsupported; use ...", #114460), forward ("Unrecognized request argument supplied: + reasoning_effort"), or an enum rejection whose only field name sits in the structured + 'param' tail (commandcode.ai, #115277) — takes the drop-the-disable rung, not the + format_error abort; a model-id segment (kimi-k2-thinking) stays route gating.""" for msg in ( "Error code: 400 - reasoning_effort 'none' unsupported; use minimal|low|medium|high|xhigh", "Unrecognized request argument supplied: reasoning_effort", + "Error code: 400 - {'error': {'message': 'Invalid option: expected one of " + "\"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"', 'type': 'invalid_request_error', " + "'param': 'reasoning_effort'}}", ): result = classify_api_error(MockAPIError(msg, status_code=400), provider="custom", model="m") assert result.reason == FailoverReason.reasoning_mandatory, msg From e343fbd28b3705c9e2c77beb259e30bf6169b6be Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:34:36 -0700 Subject: [PATCH 2/4] fix: recognize structured reasoning-field 400s (param / invalid_reasoning_effort) as reasoning rejections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A custom OpenAI-compatible Responses relay rejects an unsupported `reasoning.effort` with a message-less structured 400 — `{"error": {"param": "reasoning.effort", "error_code": "invalid_reasoning_effort", "retryable": false}}` (#100536). No wording rule in `is_reasoning_field_rejection` could match an empty message, so the 400 fell through `_classify_400` to the generic large-session overflow heuristic and the loop compressed a conversation that had nothing to do with context size ("Context length exceeded (77 tokens). Cannot compress further."). Read the structured signal from the stringified body instead: a `param` naming a reasoning wire field (`reasoning_effort`, `reasoning.effort`, `thinking_config`, ...) or an `invalid_reasoning_effort` code is a reasoning-field rejection whatever the message says. This is the same predicate the auxiliary strip-and-retry rung uses, so title generation recovers too. The main loop then takes the existing one-shot reasoning-disable retry and, when spent, the fallback chain that surfaces the provider's real error — never compression. Control: a genuine context-window 400 still classifies context_overflow with should_compress on; a `param: temperature` enum rejection does not match. --- agent/error_classifier.py | 16 +++++++++++++++- tests/agent/test_error_classifier.py | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/agent/error_classifier.py b/agent/error_classifier.py index 1e7f209d74..d4e091d1d8 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -477,6 +477,16 @@ _REASONING_FIELD_TOKEN = re.compile( r"|thinkingbudget|reasoning|thinking|think)(?![\w\-/])(?!\s+models?\b)" ) +# Structured rejection of a reasoning field, read from the stringified body: OpenAI-style +# ``param`` naming a reasoning field (``reasoning_effort`` on chat, ``reasoning.effort`` on +# Responses) or an ``invalid_reasoning_effort`` code. Custom Responses relays send this with NO +# message at all (#100536), so no wording rule can match it — and without a match the message-less +# 400 fell through to the generic large-session overflow heuristic and started compression. +_REASONING_PARAM_REJECTION = re.compile( + r"""['"]param['"]\s*:\s*['"](?:reasoning(?:[._]effort)?|thinking(?:_config|_budget)?|enable_thinking)['"]""" + r"""|invalid_reasoning_effort""" +) + def is_reasoning_field_rejection(error_msg: str) -> bool: """Provider 400 rejecting a reasoning wire control by name (``reasoning_effort``, ``reasoning``, @@ -484,13 +494,17 @@ def is_reasoning_field_rejection(error_msg: str) -> bool: request argument supplied: reasoning_effort", #112781) or a standalone "unsupported" next to the field in either word order ("unsupported reasoning_effort"; "reasoning_effort 'none' unsupported; use minimal|low|medium|high|xhigh", #114460). The route default is the right answer for such a - model, so both the main loop and the auxiliary ladder retry once without the disable. + model, so both the main loop and the auxiliary ladder retry once without the disable. A body + whose structured ``param``/code names the reasoning field (``'param': 'reasoning.effort'``, + ``invalid_reasoning_effort``, #100536) is a rejection whatever the message says — even none. Known trade-off: a 400 about a thinking *state* ("Function calling is not supported when thinking is enabled") also matches — the marker sits right next to the token, so no proximity rule separates it from the forward wordings. Cost is one dropped-disable retry before the spent path takes the fallback chain; the auxiliary ladder already treated it this way.""" msg = (error_msg or "").lower() + if _REASONING_PARAM_REJECTION.search(msg): + return True token = _REASONING_FIELD_TOKEN.search(msg) if token is None: return False diff --git a/tests/agent/test_error_classifier.py b/tests/agent/test_error_classifier.py index dbc35f6342..1f386b75c8 100644 --- a/tests/agent/test_error_classifier.py +++ b/tests/agent/test_error_classifier.py @@ -913,6 +913,28 @@ class TestClassifyApiError: ) assert gated.reason != FailoverReason.reasoning_mandatory + def test_structured_invalid_reasoning_effort_400_never_compresses(self): + """A custom Responses relay rejects an unsupported ``reasoning.effort`` with a message-less + structured 400 (``param`` + ``error_code: invalid_reasoning_effort``, #100536). No wording rule + can match it; before, the empty message fell to the large-session overflow heuristic and the + loop compressed a tiny conversation. Now it is a reasoning-field rejection with + ``should_compress`` off on every session size; a genuine context-window 400 still compresses.""" + body = {"error": {"param": "reasoning.effort", "error_code": "invalid_reasoning_effort", "retryable": False}} + for approx_tokens, num_messages in ((77, 3), (90000, 100)): + result = classify_api_error( + MockAPIError(f"Error code: 400 - {body}", status_code=400, body=body), + provider="custom", model="m", approx_tokens=approx_tokens, context_length=200000, + num_messages=num_messages, + ) + assert result.reason == FailoverReason.reasoning_mandatory, approx_tokens + assert result.should_compress is False + overflow = classify_api_error( + MockAPIError("This model's maximum context length is 128000 tokens. Please reduce the length " + "of the messages.", status_code=400), + provider="custom", model="m", approx_tokens=77, num_messages=3, + ) + assert overflow.reason == FailoverReason.context_overflow and overflow.should_compress is True + # ── Provider-specific: llama.cpp grammar-parse ── def test_llama_cpp_unable_to_generate_parser_template(self): From 64dceb9c2632d997a088fc0c798efa5411502092 Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sat, 19 Sep 2026 01:19:57 -0700 Subject: [PATCH 3/4] fix: drop the reasoning fields when the route rejects an enabled reasoning level MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A structured reasoning-field 400 on an ENABLED config (#100536: `reasoning.effort: max` on a Responses relay) reached the reasoning_mandatory rung, which only knows how to drop a disable: for an enabled config _reasoning_config_for_wire returned the config unchanged, so the one-shot retry resent the identical request (a guaranteed second 400) under a notice that blamed 'disabling reasoning'. Record what the wire builder actually sent (agent._wire_reasoning_config) and, when the rejected request carried an enabled effort, omit the reasoning fields for the rest of the session — the route default, as the auxiliary ladder's _without_reasoning_fields already does — under a 'rejects reasoning effort ' notice. A rejected disable keeps the existing contract: the user's own config goes out verbatim on the retry. Test drives classify_api_error -> recover_after_classification -> _build_api_kwargs_for_mode and asserts the retry's reasoning_config is None; control keeps the disable copy and the verbatim resend. --- agent/chat_completion_helpers.py | 11 +++ agent/turn_recovery.py | 9 +++ .../agent/test_reasoning_disable_recovery.py | 73 +++++++++++++++++++ 3 files changed, 93 insertions(+) diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index f1a9d4541a..338274a350 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -1254,6 +1254,12 @@ def _reasoning_config_for_wire(agent): """ cfg = agent.reasoning_config ephemeral_off = _consume_ephemeral_reasoning_off(agent) + if getattr(agent, "_reasoning_effort_rejected", False): + # The route rejected the configured reasoning LEVEL itself (#100536: ``reasoning.effort: + # max`` on an enabled config). Omit the reasoning fields for the rest of the session — + # the route default — as the auxiliary ladder does; resending would 400 identically. + agent._wire_reasoning_config = None + return None if getattr(agent, "_reasoning_disable_rejected", False): # The route rejects disables. Resend exactly what the session has # been sending — the user's own config — so the retry lands on the @@ -1263,10 +1269,15 @@ def _reasoning_config_for_wire(agent): if isinstance(cfg, dict) and ( cfg.get("enabled") is False or cfg.get("effort") == "none" ): + agent._wire_reasoning_config = None return None + agent._wire_reasoning_config = cfg return cfg if ephemeral_off: cfg = {**(cfg or {}), "enabled": False, "effort": "none"} + # What actually went out: the reasoning-rejection rung reads it to tell a rejected + # disable (drop the disable) from a rejected level (drop the reasoning fields). + agent._wire_reasoning_config = cfg return cfg diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py index 008b3b3649..4ebd362e59 100644 --- a/agent/turn_recovery.py +++ b/agent/turn_recovery.py @@ -608,6 +608,15 @@ def recover_after_classification( and not _retry.reasoning_mandatory_retry_attempted ): _retry.reasoning_mandatory_retry_attempted = True + sent = getattr(agent, "_wire_reasoning_config", None) + if isinstance(sent, dict) and sent.get("enabled") is not False and sent.get("effort") not in (None, "none"): + # The rejected request carried an ENABLED config: the route refuses that reasoning + # level (#100536: ``reasoning.effort: max`` on a Responses relay). Dropping a disable + # would resend the identical request; omit the reasoning fields instead (route default). + agent._reasoning_effort_rejected = True + _vlines(agent, f"⚠️ {agent.model} rejects reasoning effort {sent['effort']} — using the route's default for this session, retrying...") + logger.warning("%sReasoning-effort recovery: dropping reasoning config for %s", agent.log_prefix, agent.model) + return True, recovered_with_pool agent._reasoning_disable_rejected = True try: from hermes_cli.models_reasoning_caps import refresh_reasoning_caps_async diff --git a/tests/agent/test_reasoning_disable_recovery.py b/tests/agent/test_reasoning_disable_recovery.py index 081a1c087f..eacf2936ec 100644 --- a/tests/agent/test_reasoning_disable_recovery.py +++ b/tests/agent/test_reasoning_disable_recovery.py @@ -9,6 +9,7 @@ from types import SimpleNamespace from unittest.mock import patch from agent.error_classifier import FailoverReason, classify_api_error +from agent.turn_retry_state import TurnRetryState _REVERSED_400 = "reasoning_effort 'none' unsupported; use minimal|low|medium|high|xhigh" @@ -88,3 +89,75 @@ def test_spent_disable_drop_falls_back_instead_of_replaying_the_request(): agent, verdict = _settle(disable_drop_attempted=False) assert verdict.action == "fallthrough" assert agent.activated == [] + + +# #100536: a Responses relay rejects an unsupported reasoning LEVEL (``reasoning.effort: max`` on +# an ENABLED config) with a message-less structured 400. The classifier routes it to +# reasoning_mandatory; the rung must drop the effort for the retry instead of resending it. +_STRUCTURED_LEVEL_400 = ( + "Error code: 400 - {'error': {'param': 'reasoning.effort', " + "'error_code': 'invalid_reasoning_effort', 'retryable': False}}" +) + + +class _WireAgent(_Agent): + api_mode = "chat_completions" + base_url = "http://relay.example/v1" + request_overrides = None + + def __init__(self, reasoning_config): + super().__init__() + self.reasoning_config = reasoning_config + self.notices = [] + # ``_Agent.__getattr__`` fabricates callables for unknown names; wire flags must read False. + self._ephemeral_reasoning_off = False + self._reasoning_effort_rejected = False + self._fast_until = 0.0 + self.service_tier = None + + def _vprint(self, line, **kwargs): + self.notices.append(line) + + +def _wire_reasoning_config(agent): + """What the main-loop request builder hands the transport as ``reasoning_config``.""" + from agent.chat_completion_helpers import _build_api_kwargs_for_mode + + def _capture(agent, api_messages, tools_for_api, reasoning_config, request_overrides, cache_scope_id): + return {"reasoning_config": reasoning_config} + + with patch("agent.chat_completion_helpers._build_chat_completions_kwargs", _capture): + return _build_api_kwargs_for_mode(agent, [], [])["reasoning_config"] + + +def _recover(agent, message): + from agent.turn_recovery import recover_after_classification + + err = _FakeApiError(400, message) + classified = classify_api_error(err, provider="custom", model=agent.model) + assert classified.reason == FailoverReason.reasoning_mandatory + retry = TurnRetryState() + with patch("hermes_cli.models_reasoning_caps.refresh_reasoning_caps_async", lambda provider: None): + retry_now, _ = recover_after_classification( + agent, err, classified, retry, status_code=400, error_context={}, messages=[], api_messages=[], + ) + assert retry_now is True + return agent + + +def test_rejected_reasoning_level_retries_without_the_effort(): + agent = _WireAgent({"enabled": True, "effort": "max"}) + assert _wire_reasoning_config(agent) == {"enabled": True, "effort": "max"} # the request that 400ed + _recover(agent, _STRUCTURED_LEVEL_400) + assert _wire_reasoning_config(agent) is None, "retry must not resend reasoning.effort=max" + assert any("rejects reasoning effort max" in n for n in agent.notices) + assert not any("rejects disabling reasoning" in n for n in agent.notices) + + # Control: a rejected DISABLE keeps the existing contract — the user's own enabled config + # goes out verbatim on the retry and the notice names the disable. + agent = _WireAgent({"enabled": True, "effort": "high"}) + agent._ephemeral_reasoning_off = True + assert _wire_reasoning_config(agent) == {"enabled": False, "effort": "none"} # the request that 400ed + _recover(agent, _REVERSED_400) + assert _wire_reasoning_config(agent) == {"enabled": True, "effort": "high"} + assert any("rejects disabling reasoning" in n for n in agent.notices) From b5e96a8142a7792fa0ceb330bde045392e9a11cf Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sat, 19 Sep 2026 01:19:57 -0700 Subject: [PATCH 4/4] test: drive the auxiliary strip-and-retry rung with the structured reasoning-field 400 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the direct _is_reasoning_field_rejection predicate test with one that runs _call_fallback_candidate_sync against a client returning the message-less structured body (#100536) and asserts the retry goes out without reasoning_effort — unwiring the structured match from the classifier now turns this test red. --- .../test_auxiliary_parameter_rung_chaining.py | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/tests/agent/test_auxiliary_parameter_rung_chaining.py b/tests/agent/test_auxiliary_parameter_rung_chaining.py index 5ff70b7d50..4df7b3ac43 100644 --- a/tests/agent/test_auxiliary_parameter_rung_chaining.py +++ b/tests/agent/test_auxiliary_parameter_rung_chaining.py @@ -81,21 +81,32 @@ def test_reasoning_effort_none_unsupported_reversed_wording(): assert not _is_reasoning_field_rejection(_Bad400("reasoning models: tool_choice 'required' is unsupported")) -def test_enum_rejection_with_field_in_structured_param_tail(): - """commandcode.ai rejects ``reasoning_effort: "none"`` as an enum violation whose message carries - no "unsupported" marker at all — the field name appears only in the structured ``'param'`` tail - (#115277). The enum wording still fires the strip-and-retry rung, while the same wording against - a non-reasoning parameter does not (no reasoning field token anywhere).""" - assert _is_reasoning_field_rejection(_Bad400( - "Error code: 400 - {'error': {'message': 'Invalid option: expected one of " - "\"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"', 'type': 'invalid_request_error', " - "'param': 'reasoning_effort'}}" - )) - assert not _is_reasoning_field_rejection(_Bad400( - "Error code: 400 - {'error': {'message': 'Invalid option: expected one of " - "\"low\"|\"medium\"|\"high\"|\"xhigh\"|\"max\"', 'type': 'invalid_request_error', " - "'param': 'temperature'}}" - )) +def test_structured_param_rejection_strips_reasoning_effort_on_retry(): + """commandcode.ai rejects ``reasoning_effort`` as an enum violation with no "unsupported" marker + (#115277) and a custom Responses relay sends a message-less structured 400 whose only signal is + ``param`` / ``invalid_reasoning_effort`` (#100536). Both must land the strip-and-retry rung: the + second call goes out without ``reasoning_effort`` and succeeds.""" + client = MagicMock(base_url="https://api.example/v1") + + def create(**kwargs): + body = dict(kwargs) + body.update(body.pop("extra_body", None) or {}) + if "reasoning_effort" in body: + raise _Bad400( + "Error code: 400 - {'error': {'param': 'reasoning.effort', " + "'error_code': 'invalid_reasoning_effort', 'retryable': False}}" + ) + return _ok() + + client.chat.completions.create.side_effect = create + resp = _call_fallback_candidate_sync( + client, "custom-relay", "fallback_chain[0](custom)", task="title_generation", + messages=[{"role": "user", "content": "hi"}], temperature=0.3, max_tokens=16, tools=None, + effective_timeout=30.0, effective_extra_body={}, reasoning_config={"enabled": True, "effort": "max"}, + ) + assert resp.choices[0].message.content == "ok" + sent = [c.kwargs for c in client.chat.completions.create.call_args_list] + assert [("reasoning_effort" in k) for k in sent] == [True, False] def test_fallback_candidate_recovers_from_rejected_temperature():