diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index f4b8b2fbae..0ab19ac93b 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -1234,6 +1234,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 @@ -1248,11 +1254,18 @@ def _reasoning_config_for_wire(agent): ): if getattr(agent, "_reasoning_floor_required", False): from agent.auxiliary_reasoning_floor import REASONING_FLOOR_EFFORT - return {**cfg, "enabled": True, "effort": REASONING_FLOOR_EFFORT} + floored = {**cfg, "enabled": True, "effort": REASONING_FLOOR_EFFORT} + agent._wire_reasoning_config = floored + return floored + 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/error_classifier.py b/agent/error_classifier.py index 7b88e2f2de..f015dc48bb 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -478,13 +478,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. @@ -496,6 +499,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""" +) + _REASONING_REQUIRED_MARKERS = ( "mandatory", "cannot be disabled", "can't be disabled", "must be enabled", "is required", @@ -523,13 +536,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/agent/turn_recovery.py b/agent/turn_recovery.py index 7d7c955ca0..daa2154fbc 100644 --- a/agent/turn_recovery.py +++ b/agent/turn_recovery.py @@ -637,6 +637,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 # "Reasoning is mandatory ... cannot be disabled" understands the field and refuses only the # OFF: step up to the floor effort (the closest the route allows to what the user asked for) diff --git a/tests/agent/test_auxiliary_parameter_rung_chaining.py b/tests/agent/test_auxiliary_parameter_rung_chaining.py index e588ccdc07..4df7b3ac43 100644 --- a/tests/agent/test_auxiliary_parameter_rung_chaining.py +++ b/tests/agent/test_auxiliary_parameter_rung_chaining.py @@ -81,6 +81,34 @@ def test_reasoning_effort_none_unsupported_reversed_wording(): assert not _is_reasoning_field_rejection(_Bad400("reasoning models: tool_choice 'required' is unsupported")) +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(): 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 2e7ed82670..1180c892c5 100644 --- a/tests/agent/test_error_classifier.py +++ b/tests/agent/test_error_classifier.py @@ -926,12 +926,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 @@ -942,6 +946,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 + def test_openai_unsupported_none_effort_body_is_reasoning_mandatory(self): """OpenAI's real 400 for ``reasoning.effort: none`` on a model whose ladder has no ``none`` (o3/o4-mini, gpt-5/gpt-5-codex; ``none`` is gpt-5.1+): the SDK message carries the body — ``param: reasoning.effort`` 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)