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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(brain): the tool surface fits the model's context window, and "too large" is no longer "check the network"
rubenluetke10-beep8cca5ab273da
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex dbb98ec371..48bf493ddc 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -13342,3 +13342,76 @@ whether there was anything to measure. And when the backend goes to thetrouble of reporting three states, no layer on the way to the user may foldtwo of them together: an honest "unconfirmed" turned into a confident "notsent" is a lie the user acts on.++## BUG-187: a typed "Hallo" on a local 32k model answered "I can't reach my provider — check the network": 221 tool schemas went out with every turn, nothing read the model's context window, and the 400 that named the size was filed as a network failure (HIGH, FIXED 2026-08-27)++**Symptom.** Front-page chat, 2026-08-27 10:11 (the same at 2026-08-26 20:32+and 20:58). The session ran on `ollama / qwen3.8-16gb:latest`; the user typed+"Hallo" and after 16 s read "Entschuldige — ich erreiche meinen Anbieter+gerade nicht, vermutlich ein Netzwerk- oder Anbieterproblem." The log:+`POST http://localhost:11434/v1/chat/completions "HTTP/1.1 400 Bad Request"`,+`request (67852 tokens) exceeds the available context size (32768 tokens)`,+then `Alle 1 Provider-Versuche fehlgeschlagen` and `Spoken fallback used+instead of chain diagnostic: Provider ollama unerreichbar. Netzwerk pruefen.`+The maintainer's reading: "typing into the chat does not work with any+provider" — and the day before, Gemini and OpenRouter had indeed failed on+the same surface for two unrelated reasons (see the note at the end).++**Root cause.** Two defects in `jarvis/brain/manager.py`, one framing error.++1. *No budget.* The tool registry held 221 tools — 78 built-in, 44 GitHub ++ 32 NotebookLM + 55 Linear from three connected MCP servers, 12 CLIs — and+ a smalltalk turn hides only the spawn vehicles (`_smalltalk_tool_override`,+ by design since 2026-08-17). So ~215 JSON schemas plus the system prompt+ went out for "Hallo": ~68k tokens. `Brain.context_window` exists in the+ protocol, and the Ollama plugin even narrows it to the model's `num_ctx`+ "so the manager budgets against the real window" — but nothing in the+ manager ever read it. Cloud brains declare 128k–1M, so the defect was+ invisible until a local model answered the chat.+2. *Wrong cause.* `_classify_provider_error` knew credentials, billing,+ model ids and rate limits; a size refusal fell through to `call_fail`,+ which `_primary_provider_down_cause` reads as "unreachable" — the one+ category whose spoken phrase blames the network. The server had answered+ promptly and said exactly what was wrong.+3. *One-provider chain.* A chat session's pick is a `TurnOverride`, and an+ override runs on exactly that provider — no fallback family (correct: the+ user chose the model). So a per-request failure on it is the whole turn,+ which makes an honest cause phrase the only recovery path.++**Fix.**+- `_fit_tools_to_context_window` (pure) + `BrainManager._fit_tools_to_brain`,+ called from `_build_dispatcher` after the system prompt is built and before+ the plugin usage cards: estimates prompt + history + a 4096-token reserve+ against `brain.context_window`, and while the tool surface does not fit,+ drops connected-server tools first (`MCPToolAdapter.is_mcp_tool`, new+ flag), then the largest remaining tools. The tool a deterministic gate+ mandated this turn and `run-skill` on a skill match are never dropped. A+ brain without a declared window, and every cloud-sized window, is left+ untouched. The attempt loop now hands `history` to `_build_dispatcher`.+ One WARNING line per trimmed turn names the brain, the counts, the window+ and the first hidden tools.+- `_is_context_overflow_exc` → kind `context_overflow` (llama.cpp/Ollama,+ OpenAI/OpenRouter, Anthropic and Gemini wordings). Not dead-listed, no+ cooldown. Its own cause phrase in de/en/es ("this request is too large+ for the configured model … pick a model with a larger context or start a+ new chat") and its own line in the developer diagnostic; the "check the+ network" fallback no longer fires for it.++**Regression tests.** `tests/unit/brain/test_context_window_fit.py` — the+drop order, the kept names, the cloud-window no-op, the live 221-tool shape+on a 32k window, the live 400 string and four other provider wordings, the+phrase and the diagnostic.++**Not this bug, same afternoon.** Gemini on the same chat failed with+`81 validation errors for GenerateContentConfig … x-mcp-header` — the GitHub+MCP server's schema extension key, fixed by the allow-list in `c78a97345`+(2026-08-26 20:27); the running app had started at 10:32 and still ran the+old code. OpenRouter answered `402 Insufficient credits`. Three providers,+three causes, one symptom on the surface.++**Lesson.** A capability the protocol declares and a plugin fills in is not+a feature until a caller reads it — `context_window` was documented as "so+the manager budgets" for months while the manager budgeted nothing. And an+error the provider spells out must reach the user in its own words: filing+an unknown 4xx as "network" turns a one-line fix into a day of "nothing+works".diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 96ca3da933..2d229e3ece 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -2491,6 +2491,23 @@ _PROVIDER_DOWN_CAUSE_PHRASES: dict[str, dict[str, str]] = {"proveedor. Revisa la selección de modelo en los ajustes."),},+ "context_overflow": {+ "de": (+ "Entschuldige — diese Anfrage ist für das eingestellte Modell zu " # i18n-allow+ "groß, sein Kontextfenster reicht dafür nicht. Wähle ein Modell " # i18n-allow+ "mit größerem Kontext oder starte einen neuen Chat." # i18n-allow+ ),+ "en": (+ "Sorry — this request is too large for the configured model; its "+ "context window is too small for it. Pick a model with a larger "+ "context or start a new chat."+ ),+ "es": (+ "Lo siento: esta solicitud es demasiado grande para el modelo "+ "configurado; su ventana de contexto no alcanza. Elige un modelo "+ "con más contexto o empieza un chat nuevo."+ ),+ },"unreachable": {"de": ("Entschuldige — ich erreiche meinen Anbieter gerade nicht, " # i18n-allow@@ -2519,6 +2536,7 @@ _PROVIDER_DOWN_CAUSE_PRIORITY: tuple[str, ...] = ("bad_key","account_blocked","invalid_model",+ "context_overflow","rate_limit","unreachable",)@@ -2538,6 +2556,7 @@ def _primary_provider_down_cause("bad_key","account_blocked","invalid_model",+ "context_overflow","rate_limit","skipped_cooldown","empty_response",@@ -3481,9 +3500,21 @@ class BrainManager:(``_DELEGATE_VOICE_DIRECTIVE``) — batch lookups, no repeats, answeras soon as evidence suffices — to the system prompt of delegatedvoice turns only, so classic chat prompts stay byte-identical.++ The tool surface is then sized to the brain's context window+ (2026-08-27, ``_fit_tools_to_brain``); the turn's message log counts+ toward that — a delegated turn's from ``_TURN_HISTORY_OVERRIDE``, a+ classic turn's from the live ``self._history`` (the same two sources+ ``_cu_context_lines`` reads)."""tools = tools_override if tools_override is not None else self._toolssystem_prompt = self._build_system_prompt()+ history = _TURN_HISTORY_OVERRIDE.get()+ if history is None:+ history = tuple(getattr(self, "_history", None) or ())+ tools = self._fit_tools_to_brain(+ tools, brain, system_prompt=system_prompt, history=history+ )# Per-plugin usage guidance for whichever plugins are active this turn# (the "MCP + thin skill" reliability layer). Appended last so it sits# closest to the turn; only present when a plugin tool is in scope.@@ -6451,6 +6482,70 @@ class BrainManager:)return {n: t for n, t in tools.items() if n != "screenshot"}+ def _fit_tools_to_brain(+ self,+ tools: dict[str, Tool],+ brain: Any,+ *,+ system_prompt: str,+ history: Sequence[BrainMessage] | None,+ ) -> dict[str, Tool]:+ """Size the turn's tool surface to the answering brain's context window.++ Live 2026-08-27 10:11 (and 2026-08-26 20:32, 20:58): the front page's+ chat ran on a local 32k model, the registry held 221 tools (78+ built-in, 131 from three connected MCP servers, 12 CLIs) and a plain+ "Hallo" went out as 67,852 tokens. The server refused it with a 400,+ the one-provider chain was exhausted, and the user read "I can't+ reach my provider — check the network". Nothing had ever read+ ``Brain.context_window``: the Ollama plugin narrows it to the model's+ ``num_ctx`` so the manager can budget, and the manager budgeted+ nothing. Cloud brains declare 128k–1M and are never touched here; a+ brain without a declared window is left alone as well.++ The tool a deterministic gate mandated this turn and ``run-skill`` on+ a skill match are never dropped. Everything else follows the order in+ ``_fit_tools_to_context_window``. A tool the model cannot see is one+ capability lost for one turn; a request the server refuses is the+ whole turn lost.+ """+ if not isinstance(tools, dict) or not tools:+ return tools+ try:+ window = int(getattr(brain, "context_window", 0) or 0)+ except (TypeError, ValueError):+ window = 0+ if window <= 0:+ return tools+ used = (+ _approx_tokens(system_prompt)+ + _approx_history_tokens(history)+ + _CONTEXT_FIT_RESERVE_TOKENS+ )+ keep: set[str] = set()+ mandated = getattr(self, "_evidence_required_tool", None)+ if mandated:+ keep.add(str(mandated))+ if getattr(self, "_skill_turn_match", None) is not None:+ keep.add("run-skill")+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=window, used_tokens=used, keep=keep+ )+ if dropped:+ log.warning(+ "Tool surface trimmed for %s: %d of %d tools hidden this turn so "+ "the request fits the model's %d-token window (prompt+history "+ "~%d tokens, budget for tools %d). First hidden: %s",+ getattr(brain, "name", type(brain).__name__),+ len(dropped),+ len(tools),+ window,+ used,+ max(window - used, 0),+ ", ".join(dropped[:5]),+ )+ return fitted+def _hide_spawn_on_knowledge_question(self, tools: dict[str, Tool], user_text: str) -> dict[str, Tool]:@@ -13232,6 +13327,127 @@ def _is_invalid_model_exc(msg: str) -> bool:))+#: Tokens held back from a brain's context window before its tool surface is+#: sized: the user's turn text, the per-turn context block, the plugin usage+#: cards and the first answer or tool round. Only a local brain has a window+#: small enough for this to matter — see ``_fit_tools_to_context_window``.+_CONTEXT_FIT_RESERVE_TOKENS = 4096++#: Chars per token for the size estimate. Deliberately low: tool schemas are+#: JSON, which tokenizes denser than prose, and over-estimating costs a few+#: tools on a 32k window while under-estimating costs the whole turn.+_CONTEXT_FIT_CHARS_PER_TOKEN = 3+++def _approx_tokens(text: str) -> int:+ """A conservative token estimate for ``text`` — no tokenizer needed."""+ return len(text) // _CONTEXT_FIT_CHARS_PER_TOKEN + 1+++def _approx_history_tokens(history: Sequence[BrainMessage] | None) -> int:+ """What the message log costs on the wire, by the same estimate."""+ if not history:+ return 0+ total = 0+ for msg in history:+ content = getattr(msg, "content", "")+ if isinstance(content, str):+ total += _approx_tokens(content)+ continue+ try:+ total += _approx_tokens(json.dumps(content, ensure_ascii=False, default=str))+ except (TypeError, ValueError):+ total += _approx_tokens(str(content))+ return total+++def _tool_surface_tokens(name: str, tool: Any) -> int:+ """What ONE tool costs on the wire: name, description and schema."""+ description = getattr(tool, "description", "") or ""+ schema = getattr(tool, "schema", None) or {}+ try:+ wire = json.dumps(+ {"name": name, "description": description, "input_schema": schema},+ ensure_ascii=False,+ default=str,+ )+ except (TypeError, ValueError):+ wire = f"{name} {description} {schema}"+ return _approx_tokens(wire)+++def _fit_tools_to_context_window(+ tools: dict[str, Tool],+ *,+ context_window: int,+ used_tokens: int,+ keep: Iterable[str] = (),+) -> tuple[dict[str, Tool], list[str]]:+ """Shrink a tool surface until it fits ``context_window``.++ Returns ``(surviving tools, dropped names in drop order)``. A window of+ ``0`` or less means the brain declared none, and the surface comes back+ untouched. ``used_tokens`` is everything else the request carries (system+ prompt, history, reserve); what remains is the budget for tools.++ Drop order, deliberately: connected-server tools first — they are+ additions to Jarvis's own surface, each one a full JSON schema, and on a+ small window they are what does not fit (live 2026-08-27: 131 of 221+ tools came from three MCP servers). Within a group the largest go first,+ so as many hands as possible stay. Names in ``keep`` are never dropped.+ When even the prompt alone exceeds the window every droppable tool goes+ and the caller's log says so; the request still fails, but honestly.+ """+ if context_window <= 0 or not tools:+ return tools, []+ costs = {name: _tool_surface_tokens(name, tool) for name, tool in tools.items()}+ budget = context_window - used_tokens+ total = sum(costs.values())+ if total <= budget:+ return tools, []+ kept = set(keep)+ droppable = [name for name in tools if name not in kept]+ # A stable sort keeps the registry order inside each (group, size) tie.+ droppable.sort(+ key=lambda name: (+ 0 if getattr(tools[name], "is_mcp_tool", False) else 1,+ -costs[name],+ )+ )+ dropped: list[str] = []+ for name in droppable:+ if total <= budget:+ break+ total -= costs[name]+ dropped.append(name)+ gone = set(dropped)+ return {name: tool for name, tool in tools.items() if name not in gone}, dropped+++#: Wordings with which providers refuse a request larger than the model's+#: context window. Per request, never per credential — so NOT in+#: ``_DEAD_LIST_KINDS`` and never a cooldown.+_CONTEXT_OVERFLOW_MARKERS: tuple[str, ...] = (+ "exceeds the available context size", # llama.cpp / Ollama (live 2026-08-27)+ "exceed_context_size", # the same server's error type+ "context_length_exceeded", # OpenAI-compatible error code+ "maximum context length", # OpenAI / OpenRouter wording+ "prompt is too long", # Anthropic+ "exceeds the maximum number of tokens", # Gemini ("input token count …")+)+++def _is_context_overflow_exc(msg: str) -> bool:+ """True when the provider refused the request for its SIZE.++ Until 2026-08-27 this fell through to the generic ``call_fail`` and the+ user read "I can't reach my provider — check the network" for a request+ the server had answered perfectly well, with a 400 that named the cause.+ """+ m = msg.lower()+ return any(marker in m for marker in _CONTEXT_OVERFLOW_MARKERS)++def _classify_provider_error(msg: str, *, default: str) -> str:"""Central classifier for provider error strings.@@ -13239,6 +13455,9 @@ def _classify_provider_error(msg: str, *, default: str) -> str:1. missing_key (auth/config — important for the dead-list).2. account_blocked (credit/quota/tier/budget — also dead-list, by wording).3. invalid_model (config bug — different action: fix jarvis.toml).+ 3b. context_overflow (the request is larger than the model's window —+ per request, so neither dead-list nor cooldown; the spoken cause+ names the size, not the network).4. code-first terminal: a bare 401 -> bad_key, a bare 402 -> account_blocked(dead-list; catches a live invalid key / Payment-Required that carries thenumeric code but no known wording).@@ -13259,6 +13478,8 @@ def _classify_provider_error(msg: str, *, default: str) -> str:return "account_blocked"if _is_invalid_model_exc(msg):return "invalid_model"+ if _is_context_overflow_exc(msg):+ return "context_overflow"m = msg.lower()# Code-first terminal fallback for a 401/402 that carries the numeric HTTP code# but NONE of the known wordings (a bare live "Error code: 401 - invalid x-api-key"@@ -13343,6 +13564,7 @@ def _format_provider_chain_error(invalid_keys: list[str] = []account_blocked: list[str] = []invalid_models: list[str] = []+ context_overflow: list[str] = []rate_limited: list[str] = []empty_responses: list[str] = []other_fails: list[str] = []@@ -13355,6 +13577,8 @@ def _format_provider_chain_error(account_blocked.append(prov_name)elif kind == "invalid_model":invalid_models.append(prov_name)+ elif kind == "context_overflow":+ context_overflow.append(prov_name)elif kind in ("rate_limit", "skipped_cooldown"):rate_limited.append(prov_name)elif kind == "empty_response":@@ -13376,6 +13600,7 @@ def _format_provider_chain_error(invalid_keys = _uniq(invalid_keys)account_blocked = _uniq(account_blocked)invalid_models = _uniq(invalid_models)+ context_overflow = _uniq(context_overflow)rate_limited = _uniq(rate_limited)empty_responses = _uniq(empty_responses)other_fails = _uniq(other_fails)@@ -13412,6 +13637,15 @@ def _format_provider_chain_error(f"Ungueltige Model-ID bei {', '.join(invalid_models)}. ""jarvis.toml und TIER_DEFAULTS_BY_PROVIDER pruefen.")+ # 1c. The request was larger than the model's context window — a size+ # problem of THIS request, not a network one (live 2026-08-27: a 32k+ # local model, 221 tools, "check the network").+ if context_overflow:+ parts.append(+ f"Anfrage zu gross fuer das Kontextfenster von {', '.join(context_overflow)}. "+ "Modell mit groesserem Kontext waehlen, verbundene MCP-Server "+ "reduzieren oder einen neuen Chat starten."+ )# 2. Rate limits are listed as supplementary infoif rate_limited:prefix = "Ausserdem rate" if parts else "Rate"@@ -13427,8 +13661,8 @@ def _format_provider_chain_error("Provider per UI aktivieren.")# 4. Other failures only mentioned when there is no clear root cause- if (not missing_keys and not invalid_models and not rate_limited- and not empty_responses and other_fails):+ if (not missing_keys and not invalid_models and not context_overflow+ and not rate_limited and not empty_responses and other_fails):parts.append(f"Provider {', '.join(other_fails)} unerreichbar. ""Netzwerk pruefen."diff --git a/jarvis/mcp/adapter.py b/jarvis/mcp/adapter.pyindex 688f6f4399..48171346e4 100644--- a/jarvis/mcp/adapter.py+++ b/jarvis/mcp/adapter.py@@ -237,6 +237,10 @@ class MCPToolAdapter:)# Flag for the tool-use-loop guard: MCP tools are always action-centric.self.is_action_tool: bool = True+ # Flag for the context-window fit (BrainManager._fit_tools_to_brain):+ # a connected server's tools are the first to leave a surface that+ # does not fit a small local model's window.+ self.is_mcp_tool: bool = Trueself.risk_tier: RiskTier = risk_tier# Register with the global CapabilityRegistry so the voice pathdiff --git a/tests/fixtures/brain/fake_brain.py b/tests/fixtures/brain/fake_brain.pyindex b1d893e802..ee715b36d5 100644--- a/tests/fixtures/brain/fake_brain.py+++ b/tests/fixtures/brain/fake_brain.py@@ -19,7 +19,10 @@ class FakeBrain:"""Fake brain provider for tests."""name: str = "fake-brain"- context_window: int = 8192+ # A hosted-provider window. The manager sizes the tool surface to this+ # (BUG-187); a test that wants the small-local-model behaviour sets a+ # small window explicitly on its own fake.+ context_window: int = 200_000supports_tools: bool = Truesupports_vision: bool = Falsediff --git a/tests/unit/brain/test_context_window_fit.py b/tests/unit/brain/test_context_window_fit.pynew file mode 100644index 0000000000..21f56a9556--- /dev/null+++ b/tests/unit/brain/test_context_window_fit.py@@ -0,0 +1,250 @@+"""The tool surface fits the answering brain's context window (BUG-187).++Live 2026-08-27 10:11 (and 2026-08-26 20:32, 20:58): the front page's chat+ran on a local 32k model, the registry held 221 tools (78 built-in, 131 from+three connected MCP servers, 12 CLIs) and a plain "Hallo" went out as 67,852+tokens. The server refused it with a 400 that named the cause, the+one-provider chain was exhausted, and the user read "I can't reach my provider+— check the network". Two defects, two guards:++1. Nothing read ``Brain.context_window`` — ``_fit_tools_to_context_window``+ now sizes the surface: connected-server tools leave first, then the largest+ remaining ones, mandated tools never.+2. The 400 was classified as a generic call failure —+ ``_classify_provider_error`` now returns ``context_overflow`` and the cause+ phrase / diagnostic name the size, not the network.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++import pytest++from jarvis.brain.manager import (+ _DEAD_LIST_KINDS,+ _PROVIDER_DOWN_CAUSE_PHRASES,+ BrainManager,+ _classify_provider_error,+ _fit_tools_to_context_window,+ _format_provider_chain_error,+ _primary_provider_down_cause,+ _provider_down_phrase,+ _tool_surface_tokens,+)++# The exact server refusal from the live log (Ollama over the OpenAI route).+_LIVE_OLLAMA_400 = (+ "Error code: 400 - {'error': {'message': '{\"error\":{\"code\":400,"+ "\"message\":\"request (67852 tokens) exceeds the available context size "+ "(32768 tokens), try increasing it\",\"type\":\"exceed_context_size_error\","+ "\"n_prompt_tokens\":67852,\"n_ctx\":32768}}', 'type': 'invalid_request_error'}}"+)+++@dataclass+class _FakeTool:+ name: str+ description: str = "does a thing"+ schema: dict[str, Any] = field(default_factory=lambda: {"type": "object", "properties": {}})+ is_mcp_tool: bool = False+++def _tool(name: str, *, size: int = 1, mcp: bool = False) -> _FakeTool:+ """A tool whose wire size scales with ``size`` (schema padding)."""+ props = {f"arg{i}": {"type": "string", "description": "x" * 40} for i in range(size)}+ return _FakeTool(+ name=name,+ schema={"type": "object", "properties": props},+ is_mcp_tool=mcp,+ )+++class _FakeBrain:+ name = "fake"+ context_window = 0+ supports_vision = False++ def __init__(self, window: int) -> None:+ self.context_window = window+++# --------------------------------------------------------------- the fit+++class TestFitToolsToContextWindow:+ def test_no_declared_window_leaves_the_surface_alone(self) -> None:+ tools = {"a": _tool("a", size=50), "b": _tool("b", size=50)}+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=0, used_tokens=1_000_000+ )+ assert fitted is tools+ assert dropped == []++ def test_a_surface_that_fits_is_untouched(self) -> None:+ tools = {"a": _tool("a"), "b": _tool("b", mcp=True)}+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=100_000, used_tokens=10_000+ )+ assert fitted is tools+ assert dropped == []++ def test_connected_server_tools_leave_before_built_in_ones(self) -> None:+ # Two small built-ins and two LARGE MCP tools; the budget holds only+ # the built-ins. Size alone would keep nothing built-in either way —+ # the group order is what protects Jarvis's own hands.+ tools = {+ "run_shell": _tool("run_shell", size=2),+ "search_web": _tool("search_web", size=2),+ "github/create_issue": _tool("github/create_issue", size=20, mcp=True),+ "linear/list_issues": _tool("linear/list_issues", size=20, mcp=True),+ }+ built_in_cost = sum(+ _tool_surface_tokens(n, t) for n, t in tools.items() if not t.is_mcp_tool+ )+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=built_in_cost + 100, used_tokens=100+ )+ assert set(fitted) == {"run_shell", "search_web"}+ assert dropped == ["linear/list_issues", "github/create_issue"] or dropped == [+ "github/create_issue",+ "linear/list_issues",+ ]++ def test_then_the_largest_remaining_tools_go_first(self) -> None:+ tools = {+ "tiny": _tool("tiny", size=1),+ "huge": _tool("huge", size=40),+ "medium": _tool("medium", size=5),+ }+ budget = _tool_surface_tokens("tiny", tools["tiny"]) + _tool_surface_tokens(+ "medium", tools["medium"]+ )+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=budget, used_tokens=0+ )+ assert dropped == ["huge"]+ assert list(fitted) == ["tiny", "medium"] # registry order preserved++ def test_kept_names_are_never_dropped(self) -> None:+ tools = {+ "mandated": _tool("mandated", size=40),+ "other": _tool("other", size=1),+ }+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=10, used_tokens=0, keep={"mandated"}+ )+ assert "mandated" in fitted+ assert dropped == ["other"]++ def test_prompt_larger_than_window_drops_every_droppable_tool(self) -> None:+ tools = {"a": _tool("a"), "b": _tool("b", mcp=True)}+ fitted, dropped = _fit_tools_to_context_window(+ tools, context_window=1_000, used_tokens=5_000+ )+ assert fitted == {}+ assert set(dropped) == {"a", "b"}+++class TestFitOnTheManager:+ def _mgr(self) -> BrainManager:+ m = BrainManager.__new__(BrainManager) # bypass heavy __init__+ m._tools = {}+ m._evidence_required_tool = None+ m._skill_turn_match = None+ return m++ def test_cloud_sized_window_keeps_the_whole_surface(self) -> None:+ m = self._mgr()+ tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}+ fitted = m._fit_tools_to_brain(+ tools, _FakeBrain(1_048_576), system_prompt="x" * 40_000, history=None+ )+ assert fitted is tools++ def test_local_window_trims_the_live_shape(self) -> None:+ # 221 tools, a long system prompt, a 32k window: the surface shrinks+ # and the connected-server tools are the ones that went.+ m = self._mgr()+ tools = {f"t{i}": _tool(f"t{i}", size=10, mcp=i % 2 == 0) for i in range(221)}+ fitted = m._fit_tools_to_brain(+ tools, _FakeBrain(32_768), system_prompt="x" * 30_000, history=None+ )+ assert 0 < len(fitted) < 221+ assert not any(t.is_mcp_tool for t in fitted.values())++ def test_mandated_tool_survives_a_local_window(self) -> None:+ m = self._mgr()+ m._evidence_required_tool = "search_web"+ m._skill_turn_match = object()+ tools = {+ "search_web": _tool("search_web", size=60),+ "run-skill": _tool("run-skill", size=60),+ "github/x": _tool("github/x", size=60, mcp=True),+ }+ fitted = m._fit_tools_to_brain(+ tools, _FakeBrain(4_200), system_prompt="", history=None+ )+ assert {"search_web", "run-skill"} <= set(fitted)+ assert "github/x" not in fitted++ def test_undeclared_window_is_left_alone(self) -> None:+ m = self._mgr()++ class _Windowless:+ name = "w"++ tools = {"a": _tool("a", size=60)}+ assert m._fit_tools_to_brain(tools, _Windowless(), system_prompt="", history=None) is tools+++# ---------------------------------------------------------- the cause+++class TestContextOverflowCause:+ @pytest.mark.parametrize(+ "msg",+ [+ _LIVE_OLLAMA_400,+ "Error code: 400 - This model's maximum context length is 128000 tokens.",+ "Error code: 400 - context_length_exceeded",+ "prompt is too long: 213462 tokens > 200000 maximum",+ "400 INVALID_ARGUMENT. The input token count (2000000) exceeds the "+ "maximum number of tokens allowed (1048576).",+ ],+ )+ def test_size_refusals_classify_as_context_overflow(self, msg: str) -> None:+ assert _classify_provider_error(msg, default="call_fail") == "context_overflow"++ def test_overflow_never_dead_lists_the_provider(self) -> None:+ assert "context_overflow" not in _DEAD_LIST_KINDS++ def test_a_plain_400_still_falls_through(self) -> None:+ kind = _classify_provider_error("Error code: 400 - bad request", default="call_fail")+ assert kind == "call_fail"++ def test_spoken_cause_names_the_size_not_the_network(self) -> None:+ errors = [("ollama", "qwen3.8-16gb:latest", "context_overflow", _LIVE_OLLAMA_400)]+ cause = _primary_provider_down_cause(errors)+ assert cause == "context_overflow"+ for lang in ("de", "en", "es"):+ phrase = _provider_down_phrase(lang, 0, cause)+ assert phrase == _PROVIDER_DOWN_CAUSE_PHRASES["context_overflow"][lang]+ low = phrase.lower()+ assert "netzwerk" not in low and "network" not in low and "red" != low+ assert "ollama" not in low # voice-safe: no provider names++ def test_missing_key_still_outranks_an_overflow(self) -> None:+ errors = [+ ("ollama", "m", "context_overflow", "…"),+ ("gemini", "g", "missing_key", "…"),+ ]+ assert _primary_provider_down_cause(errors) == "missing_key"++ def test_developer_diagnostic_stops_blaming_the_network(self) -> None:+ text = _format_provider_chain_error(+ [("ollama", "qwen3.8-16gb:latest", "context_overflow", _LIVE_OLLAMA_400)]+ )+ assert "Kontextfenster" in text # i18n-allow: the diagnostic is German+ assert "ollama" in text+ assert "Netzwerk" not in text # i18n-allow