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.

feat(brain): the per-turn override's value object, effort typing and tests — the manager half landed in 19f10327d

rubenluetke10-beep9ae106b1af3b
diff --git a/jarvis/brain/dispatcher.py b/jarvis/brain/dispatcher.py
index 6d6ccecd59..6db0082fdc 100644
--- a/jarvis/brain/dispatcher.py
+++ b/jarvis/brain/dispatcher.py
@@ -9,13 +9,21 @@ and exposes two main methods:
The dispatcher is intentionally simple and holds NO conversation state —
that is the responsibility of `BrainManager` (so we can switch between providers).
"""
+
from __future__ import annotations
from collections.abc import AsyncIterator, Awaitable, Callable
-from typing import Any, Literal
+from typing import Any
from uuid import UUID, uuid4
-from jarvis.core.protocols import Brain, BrainMessage, BrainRequest, ImageBlock, Tool
+from jarvis.core.protocols import (
+ Brain,
+ BrainMessage,
+ BrainRequest,
+ ImageBlock,
+ ReasoningEffort,
+ Tool,
+)
from jarvis.safety.tool_executor import ToolExecutor
from .iteration_budget import IterationBudget
@@ -37,7 +45,7 @@ class BrainDispatcher:
max_tokens_total: int = 2_000_000,
max_tokens: int = 32_768,
deadline_s: float | None = None,
- reasoning_effort: Literal["none"] | None = None,
+ reasoning_effort: ReasoningEffort | None = None,
tool_context: dict[str, Any] | None = None,
) -> None:
self._brain = brain
@@ -173,6 +181,7 @@ class BrainDispatcher:
reasoning_effort=self._reasoning_effort,
)
if text_consumer is not None:
+
def _delta_progress(_delta: object) -> None:
if on_progress is not None:
on_progress()
@@ -183,6 +192,7 @@ class BrainDispatcher:
delta_consumer=_delta_progress if on_progress is not None else None,
)
from .streaming import aggregate
+
return await aggregate(self._brain.complete(req))
async def stream_text(
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.py
index 1f1ca82145..a299a261f2 100644
--- a/jarvis/brain/tool_use_loop.py
+++ b/jarvis/brain/tool_use_loop.py
@@ -17,7 +17,7 @@ import logging
import re
import time
from collections.abc import Awaitable, Callable
-from typing import Any, Literal
+from typing import Any
from uuid import UUID, uuid4
from jarvis.brain.cu_gate import (
@@ -31,7 +31,14 @@ from jarvis.brain.spawn_gate import (
names_spawn_vehicle,
spawn_blocked_feedback,
)
-from jarvis.core.protocols import Brain, BrainMessage, BrainRequest, ImageBlock, Tool
+from jarvis.core.protocols import (
+ Brain,
+ BrainMessage,
+ BrainRequest,
+ ImageBlock,
+ ReasoningEffort,
+ Tool,
+)
from jarvis.core.turn_language import resolve_output_language, resolve_turn_language
from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL, ToolExecutor
@@ -582,7 +589,7 @@ class ToolUseLoop:
budget: IterationBudget | None = None,
max_tokens: int = 32_768,
deadline_s: float | None = None,
- reasoning_effort: Literal["none"] | None = None,
+ reasoning_effort: ReasoningEffort | None = None,
tool_context: dict[str, Any] | None = None,
) -> None:
self._brain = brain
diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.py
new file mode 100644
index 0000000000..c8cac4c163
--- /dev/null
+++ b/jarvis/brain/turn_override.py
@@ -0,0 +1,117 @@
+"""A per-turn pick for ``BrainManager.generate``: which brain, with what hands.
+
+The front page's typed chat is Jarvis with a keyboard — the same harness the
+microphone drives — but the person picks the provider, the model and the
+reasoning effort for THAT chat in its composer, and that pick must not move
+the live brain the voice runs on. The first attempt at this (2026-08-24)
+called ``BrainManager.switch`` and ``apply_provider_model`` per chat turn,
+which changed the voice brain as a side effect and was reverted. This is the
+replacement: a value object the caller hands to ``generate(turn_override=…)``,
+carried in a ContextVar for the length of that one turn, read where the
+manager builds its provider chain, its tool surface and its dispatcher —
+and nowhere else. The manager's own state (``_active_name``, the provider
+config, the dead-lists, the shared brain cache) is never written by it.
+
+Import-light on purpose: ``jarvis.agent_chat`` builds these without pulling
+the manager in, and the manager imports this module at the top level.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass, field
+from typing import Any
+
+from jarvis.core.protocols import ReasoningEffort, Tool
+
+
+@dataclass(slots=True)
+class TurnReceipt:
+ """What the turn actually cost and who answered — filled by the manager.
+
+ Mutable by design: the override is frozen, the receipt is its one output
+ channel, so a caller reads the answer's provider, model and usage without
+ guessing them from bus events another turn may have published.
+ """
+
+ provider: str = ""
+ model: str = ""
+ tokens_in: int = 0
+ tokens_out: int = 0
+ cost_usd: float = 0.0
+ finish_reason: str = ""
+
+ def record(
+ self,
+ *,
+ provider: str,
+ model: str | None,
+ tokens_in: int,
+ tokens_out: int,
+ cost_usd: float,
+ finish_reason: str,
+ ) -> None:
+ self.provider = provider
+ self.model = model or ""
+ self.tokens_in = int(tokens_in)
+ self.tokens_out = int(tokens_out)
+ self.cost_usd = float(cost_usd)
+ self.finish_reason = finish_reason
+
+ def usage(self) -> dict[str, Any]:
+ """The ``usage`` dict an agent-chat ``turn_finished`` event carries."""
+ out: dict[str, Any] = {}
+ if self.tokens_in:
+ out["input_tokens"] = self.tokens_in
+ if self.tokens_out:
+ out["output_tokens"] = self.tokens_out
+ if self.cost_usd:
+ out["cost_usd"] = self.cost_usd
+ return out
+
+
+@dataclass(frozen=True, slots=True)
+class TurnOverride:
+ """The pick for one ``generate`` call.
+
+ ``provider`` / ``model``
+ The chain is exactly this pair — no cross-provider fallback: a person
+ who picked a model must get that model or an honest error, never a
+ silent stand-in. When the pick cannot call tools at all (a text-only
+ brain), the manager's intelligent-router lead still runs in front of
+ it, as it does for a tool-incapable voice brain.
+ ``reasoning_effort``
+ Forwarded onto every request of the turn; ``None`` keeps the
+ provider's default.
+ ``tools_extra``
+ Merged INTO the turn's tool surface after every gate the manager
+ applies (the folder tools of a chat, scoped to its working directory).
+ ``tool_filter``
+ Applied last; a plan-mode caller keeps the read-only tools only.
+ ``tool_context``
+ Extra keys for every tool's ``ExecutionContext.config`` this turn —
+ the approval surface, the working directory, written delivery.
+ ``credential_scope``
+ Namespaces the brain instance in the manager's cache so the chat's
+ client never shares a resolved credential with the voice brain.
+ ``max_turns``
+ A loop ceiling for the dispatcher; ``None`` keeps its default.
+ ``allow_force_spawn``
+ Whether the deterministic force-spawn heuristic may hand the turn to
+ a background worker. A chat that IS the worker in its folder says no;
+ an explicit "spawn an agent for this" still spawns either way.
+ """
+
+ provider: str
+ model: str | None = None
+ reasoning_effort: ReasoningEffort | None = None
+ tools_extra: Mapping[str, Tool] = field(default_factory=dict)
+ tool_filter: Callable[[dict[str, Tool]], dict[str, Tool]] | None = None
+ tool_context: Mapping[str, Any] = field(default_factory=dict)
+ credential_scope: str = "agent"
+ max_turns: int | None = None
+ allow_force_spawn: bool = False
+ receipt: TurnReceipt = field(default_factory=TurnReceipt)
+
+
+__all__ = ["TurnOverride", "TurnReceipt"]
diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.py
index f46d43632c..f7aed4ad46 100644
--- a/jarvis/core/protocols.py
+++ b/jarvis/core/protocols.py
@@ -98,6 +98,12 @@ class BrainMessage:
images: tuple[ImageBlock, ...] = ()
+#: The reasoning-effort ladder a request may ask for, ascending. Providers
+#: without a knob ignore it; one that lacks a level snaps to the nearest it
+#: has (see ``jarvis.agent_chat.effort``).
+ReasoningEffort = Literal["none", "minimal", "low", "medium", "high", "xhigh", "max"]
+
+
@dataclass(frozen=True, slots=True)
class BrainRequest:
"""Request to a brain provider."""
@@ -116,8 +122,11 @@ class BrainRequest:
# files". The graded levels remain for callers whose OUTPUT is still
# judgement work (the work splitter still passes "medium").
# ``None`` keeps the provider default; providers without a reasoning knob
- # ignore the field (capability hint, never a hard switch).
- reasoning_effort: Literal["none", "low", "medium", "high"] | None = None
+ # ignore the field (capability hint, never a hard switch). The wider
+ # levels ("minimal", "xhigh", "max") exist for the agent chat, where the
+ # person picks the level by hand; a provider that does not know a level
+ # treats it like the nearest one it does (see jarvis.agent_chat.effort).
+ reasoning_effort: ReasoningEffort | None = None
@dataclass(frozen=True, slots=True)
diff --git a/tests/unit/brain/test_turn_override.py b/tests/unit/brain/test_turn_override.py
new file mode 100644
index 0000000000..cab364eab6
--- /dev/null
+++ b/tests/unit/brain/test_turn_override.py
@@ -0,0 +1,228 @@
+"""The per-turn override: a caller-picked brain that never moves the live one.
+
+The typed chat picks provider / model / effort per chat. The first attempt at
+that (2026-08-24, reverted) switched the manager's active brain for the pick,
+so the voice changed provider as a side effect. These tests pin the contract
+of the replacement (``jarvis/brain/turn_override.py``): the chain is exactly
+the pick, the pick runs on its own cached instance, the effort and tool
+context reach the request, and every piece of manager state a voice turn
+reads is untouched afterwards.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import _TURN_OVERRIDE, BrainManager
+from jarvis.brain.turn_override import TurnOverride, TurnReceipt
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+from tests.fixtures.brain.fake_brain import FakeBrain
+
+TALKER = "openrouter"
+TALKER_MODEL = "openrouter-model"
+PICK = "openai"
+PICK_MODEL = "gpt-x"
+
+
+def _manager() -> BrainManager:
+ cfg = JarvisConfig()
+ cfg.brain.routing.intelligent_router = True
+ cfg.brain.primary = TALKER
+ cfg.brain.providers[TALKER] = BrainProviderConfig(model=TALKER_MODEL, deep_model=TALKER_MODEL)
+ mgr = BrainManager(config=cfg, bus=EventBus(), tools={})
+ mgr._registry._loaded = True
+ return mgr
+
+
+def _seed(
+ mgr: BrainManager, *, scoped_text: str, unscoped_text: str = "WRONG_SEAT"
+) -> tuple[FakeBrain, FakeBrain]:
+ """The pick twice: the chat's scoped instance and the voice's unscoped one."""
+ scoped = FakeBrain(text_response=scoped_text)
+ unscoped = FakeBrain(text_response=unscoped_text)
+ mgr._brain_cache[(f"{PICK}@agent", PICK_MODEL)] = scoped
+ mgr._brain_cache[(PICK, PICK_MODEL)] = unscoped
+ return scoped, unscoped
+
+
+class _Tool:
+ def __init__(self, name: str, risk_tier: str = "safe") -> None:
+ self.name = name
+ self.risk_tier = risk_tier
+ self.schema: dict[str, Any] = {}
+
+
+# ------------------------------------------------------------------ chain
+
+
+def test_override_chain_is_exactly_the_pick() -> None:
+ mgr = _manager()
+ _seed(mgr, scoped_text="x")
+ mgr._turn_substantive = True
+ token = _TURN_OVERRIDE.set(TurnOverride(provider=PICK, model=PICK_MODEL))
+ try:
+ chain = mgr._build_fallback_chain("deep")
+ finally:
+ _TURN_OVERRIDE.reset(token)
+ assert chain == [(PICK, PICK_MODEL)], "no cross-provider stand-in for a picked model"
+ assert mgr._router_lead_key is None
+
+
+def test_override_on_a_tool_incapable_pick_keeps_the_router_lead() -> None:
+ mgr = _manager()
+ scoped, unscoped = _seed(mgr, scoped_text="x")
+ unscoped.supports_tools = False # the capability probe reads the unscoped instance
+ mgr._turn_substantive = True
+ seen: dict[str, Any] = {}
+
+ def _first(level: str, *, exclude: str | None = None) -> tuple[str, str | None]:
+ seen["exclude"] = exclude
+ return ("gemini", "gemini-flash")
+
+ mgr._first_tool_capable_provider = _first # type: ignore[assignment]
+ token = _TURN_OVERRIDE.set(TurnOverride(provider=PICK, model=PICK_MODEL))
+ try:
+ chain = mgr._build_fallback_chain("deep")
+ finally:
+ _TURN_OVERRIDE.reset(token)
+ assert chain == [("gemini", "gemini-flash"), (PICK, PICK_MODEL)]
+ assert mgr._router_lead_key == ("gemini", "gemini-flash")
+ assert seen["exclude"] == PICK, "the lead is picked around the PICK, not the active brain"
+
+
+def test_without_an_override_the_chain_is_the_classic_one() -> None:
+ mgr = _manager()
+ mgr._turn_substantive = False
+ assert _TURN_OVERRIDE.get() is None
+ chain = mgr._build_fallback_chain("fast")
+ assert chain and chain[0][0] == TALKER
+
+
+# --------------------------------------------------------------- generate
+
+
+async def test_override_never_moves_the_live_brain() -> None:
+ """The regression that got the first attempt reverted: a chat pick changed the voice brain."""
+ mgr = _manager()
+ scoped, unscoped = _seed(mgr, scoped_text="PICK_ANSWER")
+ active_before = mgr._active_name
+ providers_before = {k: v.model for k, v in mgr._config.brain.providers.items()}
+ dead_before = set(mgr._dead_providers)
+ history_before = list(mgr._history)
+ override = TurnOverride(provider=PICK, model=PICK_MODEL, reasoning_effort="xhigh")
+
+ reply = await mgr.generate(
+ "Erzähl mir bitte etwas über die Geschichte von Rom", # i18n-allow: a substantive turn
+ use_history=False,
+ turn_override=override,
+ )
+
+ assert "PICK_ANSWER" in reply
+ assert scoped.calls and unscoped.calls == [], "the answer came from the chat's own seat"
+ assert scoped.calls[0].reasoning_effort == "xhigh"
+ assert mgr._active_name == active_before
+ assert {k: v.model for k, v in mgr._config.brain.providers.items()} == providers_before
+ assert set(mgr._dead_providers) == dead_before
+ assert list(mgr._history) == history_before
+ assert _TURN_OVERRIDE.get() is None, "the override is reset after the turn"
+ assert override.receipt.provider == PICK and override.receipt.model == PICK_MODEL
+ assert override.receipt.finish_reason
+
+
+async def test_a_dead_listed_provider_still_answers_under_an_override() -> None:
+ mgr = _manager()
+ scoped, _ = _seed(mgr, scoped_text="STILL_HERE")
+ mgr._dead_providers.add(PICK) # the voice's key for it failed earlier this session
+ reply = await mgr.generate(
+ "Erzähl mir bitte etwas über die Geschichte von Rom", # i18n-allow: a substantive turn
+ use_history=False,
+ turn_override=TurnOverride(provider=PICK, model=PICK_MODEL),
+ )
+ assert "STILL_HERE" in reply
+ assert PICK in mgr._dead_providers, "and the voice's dead-list is not rewritten either"
+
+
+async def test_a_failing_override_turn_does_not_dead_list_the_provider_for_the_voice() -> None:
+ mgr = _manager()
+ mgr._brain_cache[(f"{PICK}@agent", PICK_MODEL)] = FakeBrain(fail_on_call=0)
+ mgr._brain_cache[(PICK, PICK_MODEL)] = FakeBrain(text_response="unused")
+ await mgr.generate(
+ "Erzähl mir bitte etwas über die Geschichte von Rom", # i18n-allow: a substantive turn
+ use_history=False,
+ turn_override=TurnOverride(provider=PICK, model=PICK_MODEL),
+ )
+ assert PICK not in mgr._dead_providers
+ assert (PICK, PICK_MODEL) not in mgr._dead_provider_models
+
+
+# ------------------------------------------------------- tools and kwargs
+
+
+def test_override_tools_merge_after_the_gates_and_plan_filters_last() -> None:
+ mgr = _manager()
+ base = {"run_shell": _Tool("run_shell", "ask"), "wiki_recall": _Tool("wiki_recall")}
+ extra = {"Read": _Tool("Read"), "Write": _Tool("Write", "ask")}
+ merged = mgr._apply_turn_override_tools(base, TurnOverride(provider=PICK, tools_extra=extra))
+ assert set(merged) == {"run_shell", "wiki_recall", "Read", "Write"}
+
+ def read_only(tools: dict[str, Any]) -> dict[str, Any]:
+ return {n: t for n, t in tools.items() if getattr(t, "risk_tier", "") == "safe"}
+
+ planned = mgr._apply_turn_override_tools(
+ base, TurnOverride(provider=PICK, tools_extra=extra, tool_filter=read_only)
+ )
+ assert set(planned) == {"wiki_recall", "Read"}
+ # A None surface means "the manager's own tools" — the override adds to those.
+ assert set(
+ mgr._apply_turn_override_tools(None, TurnOverride(provider=PICK, tools_extra=extra))
+ ) == set(extra)
+
+
+def test_override_dispatch_kwargs_carry_effort_context_and_ceiling() -> None:
+ assert BrainManager._override_dispatch_kwargs(None) == {}
+ plain = TurnOverride(provider=PICK)
+ assert BrainManager._override_dispatch_kwargs(plain) == {}
+ full = TurnOverride(
+ provider=PICK,
+ reasoning_effort="low",
+ tool_context={"approval_surface": "interactive", "cwd": "/work"},
+ max_turns=7,
+ )
+ assert BrainManager._override_dispatch_kwargs(full) == {
+ "reasoning_effort": "low",
+ "tool_context": {"approval_surface": "interactive", "cwd": "/work"},
+ "max_turns": 7,
+ }
+
+
+# ------------------------------------------------------------ cache scope
+
+
+def test_scoped_instances_are_separate_and_evicted_with_their_provider() -> None:
+ mgr = _manager()
+ scoped, unscoped = _seed(mgr, scoped_text="x")
+ assert mgr._get_brain(PICK, PICK_MODEL, scope="agent") is scoped
+ assert mgr._get_brain(PICK, PICK_MODEL) is unscoped
+ mgr.apply_provider_model(PICK, "gpt-y")
+ assert (f"{PICK}@agent", PICK_MODEL) not in mgr._brain_cache
+ assert (PICK, PICK_MODEL) not in mgr._brain_cache
+
+
+def test_receipt_usage_is_the_agent_chat_shape() -> None:
+ receipt = TurnReceipt()
+ assert receipt.usage() == {}
+ receipt.record(
+ provider=PICK,
+ model=PICK_MODEL,
+ tokens_in=10,
+ tokens_out=3,
+ cost_usd=0.5,
+ finish_reason="ok",
+ )
+ assert receipt.usage() == {"input_tokens": 10, "output_tokens": 3, "cost_usd": 0.5}