Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(brain): keep a provider that requires reasoning instead of dropping it

Ruben Lütke1d9467606ece
diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.py
index 3078bcd71d..285680f2c1 100644
--- a/jarvis/plugins/brain/_openai_base.py
+++ b/jarvis/plugins/brain/_openai_base.py
@@ -428,6 +428,59 @@ def _rejection_confidence(exc: Exception, parameter: str) -> str | None:
return "message" if parameter in message else None
+#: An endpoint may REQUIRE internal reasoning and refuse every attempt to turn
+#: it off. That is a different complaint from "unsupported parameter": the knob
+#: is understood, its OFF value is refused — so it carries none of the markers
+#: above, names no parameter, and every degradation path here is blind to it by
+#: construction. Field-found on OpenRouter's ``google/gemini-3.5-flash``
+#: (2026-07-26): "Reasoning is mandatory for this endpoint and cannot be
+#: disabled" dropped the first provider out of every delegated voice turn.
+_REASONING_MANDATORY_MARKERS = (
+ "cannot be disabled",
+ "can not be disabled",
+ "cannot be turned off",
+ "is mandatory",
+ "is required",
+)
+
+
+def _rejects_disabling_reasoning(exc: Exception) -> bool:
+ """Whether an API error refuses to let reasoning be switched OFF."""
+ _, _, message = _error_metadata(exc)
+ if "reasoning" not in message:
+ return False
+ return any(marker in message for marker in _REASONING_MANDATORY_MARKERS)
+
+
+def _without_reasoning_opt_out(kwargs: dict[str, Any]) -> dict[str, Any] | None:
+ """*kwargs* with every "turn reasoning off" directive removed.
+
+ Both spellings go in ONE step — the native ``reasoning_effort="none"`` and
+ a gateway's ``reasoning={"enabled": False}`` object. Dropping one and
+ retrying re-sends the other and earns the identical rejection, which is
+ what made a live turn pay two HTTP 400s before moving on. Unrelated
+ ``extra_body`` entries (a gateway's own routing knobs) are preserved.
+ Returns ``None`` when the request asks for no opt-out at all — a graded
+ effort like ``"medium"`` is not an opt-out and has nothing to give up.
+ """
+ adapted = dict(kwargs)
+ changed = False
+ if adapted.get("reasoning_effort") == "none":
+ adapted.pop("reasoning_effort", None)
+ changed = True
+ extra_body = adapted.get("extra_body")
+ if isinstance(extra_body, dict):
+ directive = extra_body.get("reasoning")
+ if isinstance(directive, dict) and directive.get("enabled") is False:
+ trimmed = {k: v for k, v in extra_body.items() if k != "reasoning"}
+ if trimmed:
+ adapted["extra_body"] = trimmed
+ else:
+ adapted.pop("extra_body", None)
+ changed = True
+ return adapted if changed else None
+
+
def _explicitly_rejects_parameter(exc: Exception, parameter: str) -> bool:
"""Whether an API error explicitly rejects one request parameter.
@@ -460,6 +513,8 @@ def _apply_adaptation(kwargs: dict[str, Any], field: str) -> dict[str, Any] | No
adapted = dict(kwargs)
adapted["reasoning_effort"] = "minimal"
return adapted
+ if field == "reasoning:mandatory":
+ return _without_reasoning_opt_out(kwargs)
if field in kwargs:
adapted = dict(kwargs)
adapted.pop(field, None)
@@ -507,6 +562,18 @@ def _compatible_retry_kwargs(
)
return retry_kwargs, "temperature", cacheable
+ # An endpoint that REQUIRES reasoning refuses the OFF value without ever
+ # calling any parameter "unsupported", so the graded degradation below
+ # cannot see it. Checked first, and it clears BOTH spellings of "off" at
+ # once: recovering one at a time re-sends the other and earns the same
+ # rejection. Cacheable on the message alone — "reasoning ... cannot be
+ # disabled" is an unambiguous statement about the endpoint, in the same
+ # class as the server's own "use max_completion_tokens" hint above.
+ if "reasoning:mandatory" not in adaptations and _rejects_disabling_reasoning(exc):
+ retry_kwargs = _without_reasoning_opt_out(kwargs)
+ if retry_kwargs is not None:
+ return retry_kwargs, "reasoning:mandatory", True
+
# Reasoning effort degrades in two steps: a model that knows the knob but
# not the value "none" (o-series, gpt-5 base) still honors "minimal" —
# keeping the thought budget capped, which is the caller's whole intent —
@@ -596,6 +663,11 @@ async def _create_with_token_param_retry(client: Any, kwargs: dict[str, Any]) ->
"provider rejected reasoning_effort='none' — retrying "
"with the lowest supported effort 'minimal'."
)
+ elif field == "reasoning:mandatory":
+ log.info(
+ "endpoint requires internal reasoning — retrying without "
+ "the opt-out; this model cannot serve the low-latency hint."
+ )
else:
log.info(
"provider rejected optional '%s' — retrying without it.",
diff --git a/jarvis/plugins/brain/openrouter.py b/jarvis/plugins/brain/openrouter.py
index 33e6fdeee6..584133f954 100644
--- a/jarvis/plugins/brain/openrouter.py
+++ b/jarvis/plugins/brain/openrouter.py
@@ -6,6 +6,7 @@ Model names are namespaced ("anthropic/claude-opus-4.7", "openai/gpt-5").
from __future__ import annotations
from collections.abc import AsyncIterator
+from dataclasses import replace
from typing import Any
from jarvis.core import config as cfg
@@ -98,7 +99,16 @@ class OpenRouterBrain:
# retry once without it; unrelated errors propagate unchanged.
if "reasoning" not in str(exc).lower():
raise
- async for delta in stream_complete(client, self._model, req):
+ # Drop the hint from the REQUEST too, not just the gateway object:
+ # ``stream_complete`` rebuilds the native ``reasoning_effort``
+ # kwarg from ``req`` whenever no gateway directive is present, so
+ # passing the original request re-sends the very opt-out the
+ # upstream just refused — under its other name (live 2026-07-26:
+ # two identical 400s per delegated voice turn against
+ # google/gemini-3.5-flash, whose endpoint requires reasoning).
+ async for delta in stream_complete(
+ client, self._model, replace(req, reasoning_effort=None)
+ ):
yield delta
return
yield first
diff --git a/tests/unit/brain/test_openrouter_reasoning_effort.py b/tests/unit/brain/test_openrouter_reasoning_effort.py
index 1fe84a3fc2..4d6f3f0e32 100644
--- a/tests/unit/brain/test_openrouter_reasoning_effort.py
+++ b/tests/unit/brain/test_openrouter_reasoning_effort.py
@@ -106,6 +106,41 @@ async def test_rejected_reasoning_parameter_retries_without_it(
assert any(d.content == "fallback ok" for d in deltas)
+async def test_retry_also_drops_the_native_reasoning_knob(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The fail-open retry must not re-send the opt-out under its other name.
+
+ ``stream_complete`` derives the native ``reasoning_effort`` kwarg from the
+ REQUEST whenever no gateway directive is present. Retrying with the same
+ request therefore restored exactly what the upstream had just refused, and
+ the "fail open" path earned a second identical 400 (live 2026-07-26:
+ "Reasoning is mandatory for this endpoint and cannot be disabled", twice
+ per delegated voice turn, before the provider dropped out of the chain).
+ """
+ seen_efforts: list[Any] = []
+
+ async def fake_stream_complete(
+ client: Any, model: str, req: BrainRequest, *, extra_body: Any = None, **_: Any
+ ) -> AsyncIterator[BrainDelta]:
+ seen_efforts.append(getattr(req, "reasoning_effort", None))
+ if extra_body is not None:
+ raise RuntimeError("400: reasoning is mandatory and cannot be disabled")
+ yield BrainDelta(content="fallback ok")
+
+ monkeypatch.setattr(openrouter_mod, "stream_complete", fake_stream_complete)
+ brain = _brain(monkeypatch)
+
+ deltas = [d async for d in brain.complete(_req(reasoning_effort="none"))]
+
+ assert seen_efforts == ["none", None], (
+ "the retry must carry no opt-out at all — neither the gateway object "
+ "nor the native kwarg the base layer rebuilds from the request"
+ )
+ assert any(d.content == "fallback ok" for d in deltas)
+
+
@pytest.mark.asyncio
async def test_unrelated_error_propagates_unchanged(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/plugins/brain/test_openai_reasoning_mandatory.py b/tests/unit/plugins/brain/test_openai_reasoning_mandatory.py
new file mode 100644
index 0000000000..dd4afe8475
--- /dev/null
+++ b/tests/unit/plugins/brain/test_openai_reasoning_mandatory.py
@@ -0,0 +1,205 @@
+"""Recovery from an endpoint that REQUIRES internal reasoning.
+
+Field report (2026-07-26, delegated realtime voice turn): every turn opened
+with two HTTP 400s from OpenRouter's ``google/gemini-3.5-flash`` —
+
+ Reasoning is mandatory for this endpoint and cannot be disabled.
+
+— after which the provider dropped out of the chain entirely and the turn fell
+through to the next family. Two tool-loop rounds of that took 41 s against a
+20 s deadline, and the user heard "the search took a bit long" instead of an
+answer.
+
+The complaint is NOT "unsupported parameter": the endpoint understands the
+knob and refuses its OFF value, so none of the ``unsupported``-marker
+degradation paths in ``_compatible_retry_kwargs`` match it. It also arrives
+for BOTH spellings of "off" — OpenAI's native ``reasoning_effort="none"`` and
+a gateway's ``reasoning={"enabled": False}`` — which is why the pre-existing
+fail-open retry in the OpenRouter plugin could not save it either: dropping
+the gateway object let this base layer re-add the native parameter, earning
+the identical 400.
+
+Contract under test:
+ 1. A mandatory-reasoning rejection retries with BOTH opt-outs removed, in
+ ONE step, and the call streams.
+ 2. The adaptation is remembered per (endpoint, model), so a tool loop pays
+ the rejection once rather than on every round.
+ 3. A request that never asked to disable reasoning is left alone, and
+ unrelated errors still propagate — this must not become a blanket retry.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.plugins.brain import _openai_base
+from jarvis.plugins.brain._openai_base import _create_with_token_param_retry
+
+#: The verbatim upstream complaint. It carries no ``param``/``code`` metadata
+#: and never spells the parameter name, so both the structured and the
+#: substring rejection paths are blind to it by construction.
+_MANDATORY_400 = (
+ "Error code: 400 - {'error': {'message': 'Reasoning is mandatory for "
+ "this endpoint and cannot be disabled.', 'code': 400}}"
+)
+
+_GATEWAY_OFF = {"reasoning": {"enabled": False}}
+
+
[email protected](autouse=True)
+def _fresh_adaptation_cache(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The rejected-param memory is process-global; isolate it per test."""
+ monkeypatch.setattr(_openai_base, "_PARAM_ADAPTATION_CACHE", {})
+
+
+class _EmptyStream:
+ def __aiter__(self) -> _EmptyStream:
+ return self
+
+ async def __anext__(self) -> Any:
+ raise StopAsyncIteration
+
+
+class _SequenceClient:
+ """create() raises the queued errors first, then returns an empty stream."""
+
+ def __init__(
+ self, errors: list[Exception] | None = None, *, base_url: str = "https://gw/api"
+ ) -> None:
+ self.calls: list[dict[str, Any]] = []
+ self.base_url = base_url
+ self._errors = list(errors or [])
+ chat = type("Chat", (), {})()
+ chat.completions = type("Completions", (), {})()
+ chat.completions.create = self._create
+ self.chat = chat
+
+ async def _create(self, **kwargs: Any):
+ self.calls.append(kwargs)
+ if self._errors:
+ raise self._errors.pop(0)
+ return _EmptyStream()
+
+
+def _kwargs(**extra: Any) -> dict[str, Any]:
+ return {"model": "google/gemini-3.5-flash", "messages": [], **extra}
+
+
+# ---------------------------------------------------------------------------
+# 1. One retry clears BOTH opt-outs.
+# ---------------------------------------------------------------------------
+
+
+async def test_mandatory_reasoning_drops_the_native_knob() -> None:
+ client = _SequenceClient([RuntimeError(_MANDATORY_400)])
+
+ await _create_with_token_param_retry(
+ client, _kwargs(reasoning_effort="none")
+ )
+
+ assert client.calls[0]["reasoning_effort"] == "none"
+ assert "reasoning_effort" not in client.calls[1], (
+ "an endpoint that refuses to disable reasoning must lose the OFF "
+ "knob, not be retried with it"
+ )
+
+
+async def test_mandatory_reasoning_drops_the_gateway_directive() -> None:
+ client = _SequenceClient([RuntimeError(_MANDATORY_400)])
+
+ await _create_with_token_param_retry(
+ client, _kwargs(extra_body=dict(_GATEWAY_OFF))
+ )
+
+ assert client.calls[0]["extra_body"] == _GATEWAY_OFF
+ assert "reasoning" not in client.calls[1].get("extra_body", {})
+
+
+async def test_both_opt_outs_are_cleared_in_a_single_retry() -> None:
+ """The two spellings must not cost one rejection round-trip each.
+
+ Removing only one re-sends the other and earns the identical 400 — the
+ exact loop that made a live turn spend two 400s before moving on.
+ """
+ client = _SequenceClient([RuntimeError(_MANDATORY_400)])
+
+ await _create_with_token_param_retry(
+ client,
+ _kwargs(reasoning_effort="none", extra_body=dict(_GATEWAY_OFF)),
+ )
+
+ assert len(client.calls) == 2, "one rejection, one recovery — no second 400"
+ recovered = client.calls[1]
+ assert "reasoning_effort" not in recovered
+ assert "reasoning" not in recovered.get("extra_body", {})
+
+
+async def test_unrelated_extra_body_entries_survive_the_retry() -> None:
+ client = _SequenceClient([RuntimeError(_MANDATORY_400)])
+
+ await _create_with_token_param_retry(
+ client,
+ _kwargs(extra_body={**_GATEWAY_OFF, "transforms": ["middle-out"]}),
+ )
+
+ assert client.calls[1]["extra_body"] == {"transforms": ["middle-out"]}
+
+
+# ---------------------------------------------------------------------------
+# 2. Remembered per endpoint — a tool loop pays it once.
+# ---------------------------------------------------------------------------
+
+
+async def test_the_endpoint_is_remembered_so_later_rounds_skip_the_400() -> None:
+ first = _SequenceClient([RuntimeError(_MANDATORY_400)])
+ await _create_with_token_param_retry(
+ first, _kwargs(reasoning_effort="none", extra_body=dict(_GATEWAY_OFF))
+ )
+
+ # Same endpoint + model, fresh client: a tool loop's next round.
+ second = _SequenceClient()
+ await _create_with_token_param_retry(
+ second, _kwargs(reasoning_effort="none", extra_body=dict(_GATEWAY_OFF))
+ )
+
+ assert len(second.calls) == 1, "the remembered endpoint must not re-probe"
+ assert "reasoning_effort" not in second.calls[0]
+ assert "reasoning" not in second.calls[0].get("extra_body", {})
+
+
+async def test_a_different_model_still_gets_its_own_chance() -> None:
+ """The memory is keyed by (endpoint, model) — never a blanket rule."""
+ first = _SequenceClient([RuntimeError(_MANDATORY_400)])
+ await _create_with_token_param_retry(first, _kwargs(reasoning_effort="none"))
+
+ other = _SequenceClient()
+ await _create_with_token_param_retry(
+ other, {"model": "openai/gpt-5.5", "messages": [], "reasoning_effort": "none"}
+ )
+
+ assert other.calls[0]["reasoning_effort"] == "none"
+
+
+# ---------------------------------------------------------------------------
+# 3. Narrow by construction.
+# ---------------------------------------------------------------------------
+
+
+async def test_unrelated_error_propagates_unchanged() -> None:
+ client = _SequenceClient([RuntimeError("Error code: 401 - invalid api key")])
+
+ with pytest.raises(RuntimeError, match="invalid api key"):
+ await _create_with_token_param_retry(
+ client, _kwargs(reasoning_effort="none")
+ )
+
+
+async def test_a_request_that_never_disabled_reasoning_is_not_retried() -> None:
+ """"medium" is not an opt-out; there is nothing here to give up."""
+ client = _SequenceClient([RuntimeError(_MANDATORY_400)])
+
+ with pytest.raises(RuntimeError, match="mandatory"):
+ await _create_with_token_param_retry(
+ client, _kwargs(reasoning_effort="medium")
+ )