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): never let a local server shorten a prompt unnoticed (#611)

Ruben Lütke06d2adf3720a
diff --git a/jarvis/brain/local_context.py b/jarvis/brain/local_context.py
new file mode 100644
index 0000000000..ac3b419717
--- /dev/null
+++ b/jarvis/brain/local_context.py
@@ -0,0 +1,588 @@
+"""Context-window honesty for local model servers.
+
+A hosted model declares its window and refuses a request that exceeds it. A
+local server does neither reliably: Ollama serves a small default window unless
+one is baked into the model, LM Studio loads whatever context length the load
+dialog holds, llama.cpp and vLLM take theirs from the command line — and several
+of them cut an oversized prompt from the front without an error. The system
+prompt and the first tool schemas are what goes missing, so the model answers
+without ever having seen the tools it was offered.
+
+Three layers keep that from happening silently:
+
+1. **Know the window.** :func:`probe_server_window` asks an OpenAI-compatible
+ server what it actually runs (never what the model could run). The Ollama
+ brain sets its own and verifies it against ``/api/ps``.
+2. **Refuse before sending.** :func:`ensure_fits` raises
+ :class:`LocalContextError` when a request certainly exceeds a known window.
+ The message names the size needed and where to change it.
+3. **Notice afterwards.** A server that tells nothing is judged by what it
+ reports having read (:func:`judge_reported_prompt`). That signal is a
+ suspicion: it needs two responses in a row, it only tightens the next
+ turn's budget, and it lapses by itself.
+
+Only the two local brains call into this module. The brain manager imports the
+marker constant to classify the error and nothing else, so no hosted provider
+or subscription runs any of it.
+
+Pure helpers plus one small process-level registry; no I/O at import time
+(AP-26).
+"""
+
+from __future__ import annotations
+
+import itertools
+import json
+import logging
+import time
+from dataclasses import dataclass
+from typing import Any, Final
+
+import httpx
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "LOCAL_CONTEXT_MARKER",
+ "LocalContextError",
+ "ServerWindow",
+ "certain_tokens",
+ "ensure_fits",
+ "fix_hint",
+ "forget_window",
+ "is_overflow_refusal",
+ "judge_reported_prompt",
+ "known_window",
+ "known_window_for_model",
+ "probe_server_window",
+ "recommended_window",
+ "refusal_error",
+ "remember_window",
+ "reported_prompt_tokens",
+ "reset_registry",
+ "truncation_suspected",
+]
+
+#: Stable wording the brain manager classifies on. Never reword without
+#: updating ``_classify_provider_error`` in ``jarvis/brain/manager.py``.
+LOCAL_CONTEXT_MARKER: Final[str] = "local context window too small"
+
+# Token counts in these sentences are written WITHOUT thousands separators.
+# Several classifiers in this app read a free-standing three-digit group as an
+# HTTP status: "18,401 tokens" was recorded as a rejected key and "65,536" as an
+# unreachable server. A run of digits has no such group.
+
+#: Chars per token for the "certainly too large" check. Deliberately high:
+#: real tokenizers land between 3 and 4.5 chars per token on this app's
+#: prompts, so a request that exceeds the window even at 4 does not fit.
+_CERTAIN_CHARS_PER_TOKEN: Final[int] = 4
+#: Chars per token for the upper estimate, the same figure the brain manager
+#: budgets tools with.
+_BUDGET_CHARS_PER_TOKEN: Final[int] = 3
+#: The least an image costs on any current vision model. A lower bound on
+#: purpose: the certain check must never refuse a picture that would fit.
+_IMAGE_TOKENS_MIN: Final[int] = 256
+#: Keys under which a content block carries encoded bytes rather than text.
+_BINARY_KEYS: Final[frozenset[str]] = frozenset({"data", "b64_json", "image_base64", "bytes"})
+
+#: A response that reports less than this share of the upper estimate read a
+#: shortened prompt. Honest tokenizers report 65 % or more of that estimate.
+_TRUNCATION_RATIO: Final[float] = 0.5
+#: Below this size the ratio is noise.
+_TRUNCATION_MIN_ESTIMATE: Final[int] = 4_000
+#: A truncated prompt still fills a real window; a small count is a server
+#: that reports only the tokens it newly evaluated after a cache hit.
+_TRUNCATION_MIN_REPORTED: Final[int] = 2_000
+#: Suspicious responses in a row before the budget is tightened.
+_SUSPICIONS_NEEDED: Final[int] = 2
+
+#: Windows a person can actually select, smallest first.
+_WINDOW_STEPS: Final[tuple[int, ...]] = (8_192, 16_384, 32_768, 65_536, 131_072, 262_144)
+#: Headroom on top of the prompt for the answer and the next tool round.
+_RECOMMEND_HEADROOM: Final[float] = 1.25
+
+#: How long a server's answer about its own window is trusted. Short, because
+#: the fix for a too-small window is to reload the model and ask again.
+_SERVER_TTL_S: Final[float] = 30.0
+#: How long "this server tells nothing" is trusted.
+_SILENT_TTL_S: Final[float] = 300.0
+#: How long a window inferred from reported usage tightens the budget. It is a
+#: suspicion, so it lapses by itself and has to be observed again.
+_OBSERVED_TTL_S: Final[float] = 600.0
+
+# Four small GETs against the user's own server; a dead port must not hold a
+# turn, and a live one answers a status route at once.
+_PROBE_TIMEOUT: Final[httpx.Timeout] = httpx.Timeout(connect=1.0, read=2.0, write=2.0, pool=2.0)
+
+_FIX_HINTS: Final[dict[str, str]] = {
+ "ollama": (
+ "Open Local Models, choose Tune for this model and set the context "
+ "length to at least {tokens} tokens."
+ ),
+ "lm-studio": (
+ "In LM Studio, open this model's load settings, raise Context Length "
+ "to at least {tokens} and reload the model."
+ ),
+ "llama.cpp": "Restart llama-server with --ctx-size {tokens} (short form: -c {tokens}).",
+ "vllm": (
+ "Restart vLLM with --max-model-len {tokens}, or serve a model whose own "
+ "limit is at least that large."
+ ),
+ "tgi": "Restart the server with --max-total-tokens {tokens} or more.",
+ "unknown": (
+ "Raise the context length of the loaded model in your local server to "
+ "at least {tokens} tokens (LM Studio: model load settings, Context "
+ "Length; llama.cpp: --ctx-size; vLLM: --max-model-len), then ask again."
+ ),
+}
+
+#: Wordings with which a local server refuses an oversized request.
+_OVERFLOW_REFUSALS: Final[tuple[str, ...]] = (
+ "exceeds the available context size",
+ "exceed_context_size",
+ "context_length_exceeded",
+ "maximum context length",
+ "context length exceeded",
+ "prompt is too long",
+)
+
+
+class LocalContextError(RuntimeError):
+ """A request does not fit the window a local server really runs.
+
+ ``truncated``: the server had already cut the prompt when this was
+ noticed. ``refused``: the server rejected the request itself; its own
+ count includes the reply allowance, so the sentence then does not claim a
+ prompt size that might be below the window.
+ """
+
+ def __init__(
+ self,
+ *,
+ provider: str,
+ model: str,
+ needed_tokens: int,
+ window_tokens: int,
+ how_to_fix: str,
+ truncated: bool = False,
+ refused: bool = False,
+ ) -> None:
+ self.provider = provider
+ self.model = model
+ self.needed_tokens = needed_tokens
+ self.window_tokens = window_tokens
+ self.how_to_fix = how_to_fix
+ self.truncated = truncated
+ self.refused = refused
+ name = model or "the model"
+ runs = f"with {window_tokens} tokens" if window_tokens > 0 else "with too little context"
+ if refused:
+ body = (
+ f"{provider} runs {name} {runs} and refused this request as too large "
+ f"(a prompt of about {needed_tokens} tokens plus room for the reply)."
+ )
+ else:
+ lead = "the server cut this request short" if truncated else "this request was not sent"
+ body = (
+ f"{provider} runs {name} {runs} and the request needs about "
+ f"{needed_tokens}, so {lead}."
+ )
+ super().__init__(f"{LOCAL_CONTEXT_MARKER.capitalize()}: {body} {how_to_fix}")
+
+
+@dataclass(frozen=True, slots=True)
+class ServerWindow:
+ """What a server said about the context it runs ``model`` with."""
+
+ tokens: int
+ #: ``lm-studio`` | ``llama.cpp`` | ``vllm`` | ``tgi``.
+ kind: str
+
+
+@dataclass(slots=True)
+class _Entry:
+ tokens: int
+ #: ``server`` (the server said so) | ``plan`` (what this app asked the
+ #: server to run) | ``observed`` (inferred from reported usage).
+ source: str
+ kind: str
+ at: float
+ #: Insertion order; the clock is too coarse to order two records.
+ seq: int = 0
+
+
+_REGISTRY: dict[tuple[str, str, str], _Entry] = {}
+_SILENT_ROOTS: dict[str, float] = {}
+_SUSPICIONS: dict[tuple[str, str, str], int] = {}
+_SEQUENCE = itertools.count(1)
+
+
+# ── Request size ─────────────────────────────────────────────────────────
+
+
+def _text_chars(value: Any) -> int:
+ """Characters of TEXT in a content block, encoded bytes left out.
+
+ A block may carry a screenshot as base64; counting that as prose would
+ refuse an image turn outright.
+ """
+ if isinstance(value, str):
+ return 0 if value.startswith("data:") else len(value)
+ if isinstance(value, dict):
+ return sum(
+ _text_chars(item)
+ for key, item in value.items()
+ if not (key in _BINARY_KEYS and isinstance(item, str))
+ )
+ if isinstance(value, (list, tuple)):
+ return sum(_text_chars(item) for item in value)
+ return len(str(value)) if value is not None else 0
+
+
+def _request_chars(req: Any) -> tuple[int, int]:
+ """``(characters, images)`` a request puts on the wire."""
+ chars = len(getattr(req, "system", None) or "")
+ tools = getattr(req, "tools", None) or ()
+ if tools:
+ try:
+ chars += len(json.dumps(list(tools), ensure_ascii=False, default=str))
+ except (TypeError, ValueError): # unserialisable schema: size its repr instead
+ chars += len(str(tools))
+ images = 0
+ for message in getattr(req, "messages", None) or ():
+ chars += _text_chars(getattr(message, "content", ""))
+ images += len(getattr(message, "images", ()) or ())
+ return chars, images
+
+
+def certain_tokens(req: Any) -> int:
+ """A LOWER estimate of the prompt: a request above it surely does not fit."""
+ chars, images = _request_chars(req)
+ return chars // _CERTAIN_CHARS_PER_TOKEN + images * _IMAGE_TOKENS_MIN
+
+
+def _budget_tokens(req: Any) -> int:
+ chars, images = _request_chars(req)
+ return chars // _BUDGET_CHARS_PER_TOKEN + images * _IMAGE_TOKENS_MIN
+
+
+def recommended_window(needed_tokens: int) -> int:
+ """The smallest selectable window that holds ``needed_tokens`` with headroom."""
+ target = int(needed_tokens * _RECOMMEND_HEADROOM)
+ for step in _WINDOW_STEPS:
+ if step >= target:
+ return step
+ return _WINDOW_STEPS[-1]
+
+
+def fix_hint(kind: str, needed_tokens: int, *, ceiling: int | None = None) -> str:
+ """One sentence that says where to raise the window, for this server kind.
+
+ ``ceiling`` is the model's own window when known: a size above it cannot
+ be set anywhere, so the sentence then says to pick another model.
+ """
+ wanted = recommended_window(needed_tokens)
+ if ceiling and wanted > ceiling:
+ return (
+ f"This model's own window is {ceiling} tokens, which the request "
+ "exceeds; choose a model with a larger context window."
+ )
+ template = _FIX_HINTS.get(kind) or _FIX_HINTS["unknown"]
+ return template.format(tokens=wanted)
+
+
+def ensure_fits(
+ req: Any,
+ window_tokens: int,
+ *,
+ provider: str,
+ model: str,
+ kind: str,
+ ceiling: int | None = None,
+ truncated: bool = False,
+) -> None:
+ """Raise :class:`LocalContextError` when ``req`` certainly exceeds the window.
+
+ A window of ``0`` or less means "unknown" and never raises. The check uses
+ the lower estimate on purpose: a borderline request is left to the server,
+ which is the only party that can count it exactly.
+ """
+ if window_tokens <= 0:
+ return
+ needed = certain_tokens(req)
+ if needed <= window_tokens:
+ return
+ raise LocalContextError(
+ provider=provider,
+ model=model,
+ needed_tokens=needed,
+ window_tokens=window_tokens,
+ how_to_fix=fix_hint(kind, needed, ceiling=ceiling),
+ truncated=truncated,
+ )
+
+
+def refusal_error(
+ req: Any, *, provider: str, model: str, kind: str, window_tokens: int = 0
+) -> LocalContextError:
+ """The error for a request the SERVER rejected as too large."""
+ needed = certain_tokens(req)
+ return LocalContextError(
+ provider=provider,
+ model=model,
+ needed_tokens=needed,
+ window_tokens=window_tokens,
+ # The server counted prompt plus reply, so the next window up from
+ # the larger of the two figures is the one that helps.
+ how_to_fix=fix_hint(kind, max(needed, window_tokens)),
+ refused=True,
+ )
+
+
+def is_overflow_refusal(message: str) -> bool:
+ """Whether a server's error text says the request was too large."""
+ low = (message or "").lower()
+ return any(marker in low for marker in _OVERFLOW_REFUSALS)
+
+
+# ── What the server reported ─────────────────────────────────────────────
+
+
+def reported_prompt_tokens(usage: dict[str, int] | None) -> int | None:
+ """The whole prompt the server says it read, cached share included."""
+ if not usage:
+ return None
+ try:
+ total = int(usage.get("input_tokens", 0) or 0) + int(usage.get("cache_hit_tokens", 0) or 0)
+ except (TypeError, ValueError): # a malformed usage block reports nothing
+ return None
+ return total if total > 0 else None
+
+
+def truncation_suspected(req: Any, reported: int | None) -> bool:
+ """Whether the server read far less than was sent.
+
+ A suspicion, not a proof: a server that reports only the tokens it newly
+ evaluated after a prompt-cache hit looks the same. Callers therefore use
+ this to tighten a budget, never to fail a turn.
+ """
+ if reported is None or reported < _TRUNCATION_MIN_REPORTED:
+ return False
+ estimate = _budget_tokens(req)
+ if estimate < _TRUNCATION_MIN_ESTIMATE:
+ return False
+ return reported < estimate * _TRUNCATION_RATIO
+
+
+def judge_reported_prompt(
+ provider: str, root: str, model: str, req: Any, reported: int | None
+) -> tuple[str, int]:
+ """Decide what a response from a server that states no window means.
+
+ Returns ``("tighten", tokens)`` when the server has now twice in a row
+ read far less than it was sent — the next turn is then planned for what
+ it demonstrably holds; ``("restore", 0)`` when a response disproves an
+ earlier suspicion; ``("keep", 0)`` otherwise. One odd response changes
+ nothing, and a recorded suspicion lapses after :data:`_OBSERVED_TTL_S`.
+ """
+ key = _key(provider, root, model)
+ if reported is not None and truncation_suspected(req, reported):
+ count = _SUSPICIONS.get(key, 0) + 1
+ _SUSPICIONS[key] = count
+ if count < _SUSPICIONS_NEEDED:
+ return "keep", 0
+ remember_window(provider, root, model, reported, source="observed")
+ return "tighten", reported
+ _SUSPICIONS.pop(key, None)
+ known = known_window(provider, root, model)
+ if known is not None and known[1] == "observed" and (reported or 0) > known[0]:
+ forget_window(provider, root, model)
+ return "restore", 0
+ return "keep", 0
+
+
+# ── Registry ─────────────────────────────────────────────────────────────
+
+
+def _key(provider: str, root: str, model: str) -> tuple[str, str, str]:
+ return provider, (root or "").rstrip("/"), (model or "").removesuffix(":latest")
+
+
+def remember_window(
+ provider: str, root: str, model: str, tokens: int, *, source: str, kind: str = "unknown"
+) -> None:
+ """Record the window ``model`` runs with on ``root``."""
+ if tokens <= 0 or not model:
+ return
+ _REGISTRY[_key(provider, root, model)] = _Entry(
+ tokens=int(tokens), source=source, kind=kind, at=time.monotonic(), seq=next(_SEQUENCE)
+ )
+
+
+def forget_window(provider: str, root: str, model: str) -> None:
+ _REGISTRY.pop(_key(provider, root, model), None)
+
+
+def _lapsed(entry: _Entry) -> bool:
+ return entry.source == "observed" and time.monotonic() - entry.at > _OBSERVED_TTL_S
+
+
+def known_window(provider: str, root: str, model: str) -> tuple[int, str, str] | None:
+ """``(tokens, source, kind)`` recorded for this model, or ``None``."""
+ key = _key(provider, root, model)
+ entry = _REGISTRY.get(key)
+ if entry is None:
+ return None
+ if _lapsed(entry):
+ del _REGISTRY[key]
+ return None
+ return entry.tokens, entry.source, entry.kind
+
+
+def known_window_for_model(provider: str, model: str) -> int | None:
+ """The most recently recorded window of ``model`` on any server root.
+
+ For a brain's constructor, which must publish a budget before it may touch
+ the network or resolve an endpoint. A brain without a model has no record
+ of its own, so an empty name answers ``None`` rather than some other
+ model's window.
+ """
+ wanted = (model or "").removesuffix(":latest")
+ if not wanted:
+ return None
+ best: _Entry | None = None
+ for (prov, _root, name), entry in _REGISTRY.items():
+ if prov != provider or name != wanted or _lapsed(entry):
+ continue
+ if best is None or entry.seq > best.seq:
+ best = entry
+ return best.tokens if best is not None else None
+
+
+def reset_registry() -> None:
+ """Forget every recorded window (tests, or a changed endpoint)."""
+ _REGISTRY.clear()
+ _SILENT_ROOTS.clear()
+ _SUSPICIONS.clear()
+
+
+# ── Asking an OpenAI-compatible server ───────────────────────────────────
+
+
+def _positive(value: Any) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ return int(value) if value > 0 else None
+
+
+def _same_id(row_id: Any, model: str) -> bool:
+ return bool(model) and str(row_id or "").strip() == model
+
+
+async def _get_json(client: httpx.AsyncClient, url: str) -> Any:
+ resp = await client.get(url)
+ if resp.status_code != 200:
+ return None
+ try:
+ return resp.json()
+ except ValueError: # an HTML error page on this path means "not this server kind"
+ return None
+
+
+def _from_openai_models(payload: Any, model: str) -> ServerWindow | None:
+ """vLLM publishes the limit it was started with as ``max_model_len``."""
+ rows = payload.get("data") if isinstance(payload, dict) else None
+ for row in rows or ():
+ if isinstance(row, dict) and _same_id(row.get("id"), model):
+ tokens = _positive(row.get("max_model_len"))
+ if tokens:
+ return ServerWindow(tokens, "vllm")
+ return None
+
+
+def _from_lm_studio(payload: Any, model: str) -> ServerWindow | None:
+ """LM Studio reports the context a model is LOADED with, per model."""
+ rows = payload.get("data") if isinstance(payload, dict) else None
+ for row in rows or ():
+ if not isinstance(row, dict) or not _same_id(row.get("id"), model):
+ continue
+ if str(row.get("state") or "").lower() != "loaded":
+ # Not loaded yet: the first request loads it with the stored
+ # setting, which this endpoint does not reveal in advance.
+ return None
+ tokens = _positive(row.get("loaded_context_length"))
+ if tokens:
+ return ServerWindow(tokens, "lm-studio")
+ return None
+
+
+def _from_llama_cpp(payload: Any) -> ServerWindow | None:
+ """llama-server reports the per-slot context under ``/props``."""
+ if not isinstance(payload, dict):
+ return None
+ settings = payload.get("default_generation_settings")
+ tokens = _positive(settings.get("n_ctx")) if isinstance(settings, dict) else None
+ return ServerWindow(tokens, "llama.cpp") if tokens else None
+
+
+def _from_tgi(payload: Any) -> ServerWindow | None:
+ if not isinstance(payload, dict):
+ return None
+ tokens = _positive(payload.get("max_total_tokens"))
+ return ServerWindow(tokens, "tgi") if tokens else None
+
+
+async def probe_server_window(
+ root: str,
+ model: str,
+ *,
+ headers: dict[str, str] | None = None,
+ transport: httpx.AsyncBaseTransport | None = None,
+ fresh: bool = False,
+) -> ServerWindow | None:
+ """Ask an OpenAI-compatible server which context it runs ``model`` with.
+
+ Answers only from what the server states about the RUNNING model; a
+ model's native or maximum window is never taken for the running one.
+ ``None`` means the server does not say. Results are cached briefly;
+ ``fresh`` skips that cache (after the first token, when a server that
+ loads on demand has just loaded the model). A server that stayed silent
+ even then is left alone for :data:`_SILENT_TTL_S`, fresh or not, so no
+ turn waits on a probe that cannot answer. Never raises.
+
+ ``transport`` exists for tests (``httpx.MockTransport``).
+ """
+ root = (root or "").rstrip("/")
+ now = time.monotonic()
+ silent_since = _SILENT_ROOTS.get(root)
+ if silent_since is not None and now - silent_since < _SILENT_TTL_S:
+ return None
+ if not fresh:
+ hit = _REGISTRY.get(_key("local-openai", root, model))
+ if hit is not None and hit.source == "server" and now - hit.at < _SERVER_TTL_S:
+ return ServerWindow(hit.tokens, hit.kind)
+ found: ServerWindow | None = None
+ try:
+ async with httpx.AsyncClient(
+ timeout=_PROBE_TIMEOUT, transport=transport, headers=headers or {}
+ ) as client:
+ found = _from_openai_models(await _get_json(client, f"{root}/v1/models"), model)
+ if found is None:
+ found = _from_lm_studio(await _get_json(client, f"{root}/api/v0/models"), model)
+ if found is None:
+ found = _from_llama_cpp(await _get_json(client, f"{root}/props"))
+ if found is None:
+ found = _from_tgi(await _get_json(client, f"{root}/info"))
+ except Exception as exc: # noqa: BLE001 — a probe must never fail the turn it serves
+ # An unreachable server is reported by the request itself, with a
+ # better message than a probe could give.
+ log.debug("local context: window probe failed at %s: %s", root, exc)
+ return None
+ if found is None:
+ if fresh:
+ # Asked while the model was demonstrably loaded and still got no
+ # answer: this server does not publish its window.
+ _SILENT_ROOTS[root] = now
+ return None
+ remember_window("local-openai", root, model, found.tokens, source="server", kind=found.kind)
+ return found
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 74640ce786..487e10a379 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -45,6 +45,7 @@ from uuid import UUID, uuid4
# Real turn outcomes feed the passive health record behind the status dots.
from jarvis.brain import provider_health_ledger as _health_ledger
+from jarvis.brain.local_context import LOCAL_CONTEXT_MARKER
# ONE canonical billing/budget/quota marker list, shared with the test-badge
# classifier (provider_test.classify_provider_error) so the live fallback chain and
@@ -2702,6 +2703,38 @@ _PROVIDER_DOWN_CAUSE_PHRASES: dict[str, dict[str, str]] = {
"contexto não chega. Escolhe um modelo com mais contexto ou começa uma conversa nova."
),
},
+ # A LOCAL server runs the model with a window too small for the request
+ # (``jarvis.brain.local_context``). Unlike ``context_overflow`` the remedy
+ # is not another model or a new chat but one setting on the user's own
+ # machine, so the phrase names that setting.
+ "local_context": {
+ "de": (
+ "Entschuldige — dein lokales Modell läuft mit einem zu kleinen " # i18n-allow
+ "Kontextfenster für diese Anfrage. Stell in deinem lokalen " # i18n-allow
+ "Modell-Server eine größere Kontextlänge ein und lade das Modell " # i18n-allow
+ "neu; bei den Modellen unter Lokale Modelle geht das über Tune. " # i18n-allow
+ "Die nötige Größe steht im Protokoll." # i18n-allow
+ ),
+ "en": (
+ "Sorry — your local model runs with a context window too small "
+ "for this request. Raise the context length in your local model "
+ "server and reload the model; for the models under Local Models, "
+ "use Tune. The log names the size it needs."
+ ),
+ "es": (
+ "Lo siento: tu modelo local funciona con una ventana de contexto "
+ "demasiado pequeña para esta solicitud. Aumenta la longitud de "
+ "contexto en tu servidor de modelos local y vuelve a cargar el "
+ "modelo; para los modelos de Modelos locales, usa Tune. El "
+ "registro indica el tamaño necesario."
+ ),
+ "pt": (
+ "Desculpa: o teu modelo local corre com uma janela de contexto demasiado pequena "
+ "para este pedido. Aumenta o comprimento de contexto no teu servidor de modelos "
+ "local e recarrega o modelo; para os modelos em Modelos locais, usa Tune. O "
+ "registo indica o tamanho necessário."
+ ),
+ },
"unreachable": {
"de": (
"Entschuldige — ich erreiche meinen Anbieter gerade nicht, " # i18n-allow
@@ -2761,6 +2794,7 @@ _PROVIDER_DOWN_CAUSE_PRIORITY: tuple[str, ...] = (
"account_blocked",
"vision_unsupported",
"invalid_model",
+ "local_context",
"context_overflow",
"rate_limit",
"unreachable",
@@ -2782,6 +2816,7 @@ def _primary_provider_down_cause(
"account_blocked",
"vision_unsupported",
"invalid_model",
+ "local_context",
"context_overflow",
"rate_limit",
"skipped_cooldown",
@@ -12320,6 +12355,7 @@ class BrainManager:
if prefer_tool_model
else self._override_dispatch_kwargs(turn_override)
)
+ await _settle_context_window(brain)
disp = self._build_dispatcher(
brain, tools_override=_turn_tools, **_disp_kwargs
)
@@ -12591,7 +12627,10 @@ class BrainManager:
# router bricked the whole turn even though OpenRouter was funded
# — AP-22). Only a genuinely transient 429 takes the cooldown path.
kind = _classify_provider_error(msg, default="call_fail")
- if turn_override is None:
+ # A window too small for one request says nothing about whether
+ # the provider works; recording it would turn its status dot
+ # red for a setting, not a fault.
+ if turn_override is None and kind != "local_context":
_health_ledger.record_failure(
prov_name, _health_ledger.MODALITY_BRAIN, exc, model=model
)
@@ -12633,7 +12672,10 @@ class BrainManager:
"Provider %s fuer diese Session deaktiviert (%s) — die Kette "
"weicht auf einen anderen verfuegbaren Anbieter aus. "
"Setup: Sidebar -> API-Keys.", prov_name, kind)
- provider_errors.append((prov_name, model, kind, msg[:200]))
+ # The local-context sentence ends with the setting to
+ # change; cutting it at 200 chars would drop exactly that.
+ detail = msg if kind == "local_context" else msg[:200]
+ provider_errors.append((prov_name, model, kind, detail))
# NOTE BUG-019 (2026-05-11): this generic ``continue`` does
# not touch the failing provider's *internal* state. For
# most providers that's correct (an HTTP error is purely
@@ -13776,6 +13818,7 @@ class BrainManager:
for index, (name, model) in enumerate(attempts):
try:
brain = self._get_brain(name, model)
+ await _settle_context_window(brain)
dispatcher = self._build_dispatcher(
brain, tools_override=tools,
# ``unattended``: the tool-use loop feeds an unknown tool
@@ -14146,6 +14189,36 @@ def _is_invalid_model_exc(msg: str) -> bool:
))
+#: How long a brain may take to say which context window it really has before
+#: the turn goes ahead with the figure it already published.
+_CONTEXT_SETTLE_TIMEOUT_S = 3.0
+
+
+async def _settle_context_window(brain: Any) -> None:
+ """Let a brain that has to ASK for its window do so before tools are fitted.
+
+ A hosted model's window is a constant on its class. A local server's is
+ whatever that server was started or loaded with, so the two local brains
+ expose ``prepare_context_window`` and learn it with one or two cached
+ round-trips. Without this the first turn is budgeted for a figure the
+ server may not run, and is then refused whole instead of having its tool
+ surface trimmed. Gated on the capability, never a provider name (AP-21);
+ a brain without the method is untouched. Bounded and never raises: a slow
+ or failing probe costs nothing but the better budget.
+ """
+ prepare = getattr(brain, "prepare_context_window", None)
+ if not callable(prepare):
+ return
+ try:
+ await asyncio.wait_for(prepare(), timeout=_CONTEXT_SETTLE_TIMEOUT_S)
+ except Exception as exc: # noqa: BLE001 — the turn runs on the published figure
+ log.debug(
+ "Context window of %s not settled before the turn: %s",
+ getattr(brain, "name", type(brain).__name__),
+ exc,
+ )
+
+
#: 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
@@ -14278,6 +14351,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).
+ 0. local_context (a local server runs the model with a window too small
+ for this request — our own guard's wording, so it is checked first;
+ per request, never a dead-list or cooldown).
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).
@@ -14295,6 +14371,10 @@ def _classify_provider_error(msg: str, *, default: str) -> str:
contain "limit" (e.g. "exceeded the rate limit for this resource") is not
incorrectly classified as a 429 cooldown.
"""
+ # A local server's window is named by our own guard with a fixed wording;
+ # checked first so no other heuristic can read the sentence differently.
+ if LOCAL_CONTEXT_MARKER in msg.lower():
+ return "local_context"
if _is_missing_key_exc(msg):
return "missing_key"
if _is_account_blocked_exc(msg):
@@ -14389,6 +14469,7 @@ def _format_provider_chain_error(
vision_unsupported: list[str] = []
invalid_models: list[str] = []
context_overflow: list[str] = []
+ local_context: list[str] = []
rate_limited: list[str] = []
empty_responses: list[str] = []
other_fails: list[str] = []
@@ -14405,6 +14486,9 @@ def _format_provider_chain_error(
invalid_models.append(prov_name)
elif kind == "context_overflow":
context_overflow.append(prov_name)
+ elif kind == "local_context":
+ # The guard's own sentence carries the sizes and the setting.
+ local_context.append(_detail or prov_name)
elif kind in ("rate_limit", "skipped_cooldown"):
rate_limited.append(prov_name)
elif kind == "empty_response":
@@ -14479,6 +14563,8 @@ def _format_provider_chain_error(
"Modell mit groesserem Kontext waehlen, verbundene MCP-Server "
"reduzieren oder einen neuen Chat starten."
)
+ if local_context:
+ parts.append(" ".join(_uniq(local_context)))
# 2. Rate limits are listed as supplementary info
if rate_limited:
prefix = "Ausserdem rate" if parts else "Rate"
@@ -14495,6 +14581,7 @@ def _format_provider_chain_error(
)
# 4. Other failures only mentioned when there is no clear root cause
if (not missing_keys and not invalid_models and not context_overflow
+ and not local_context
and not rate_limited and not empty_responses and other_fails):
parts.append(
f"Provider {', '.join(other_fails)} unerreichbar. "
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.py
index 603fb31c40..4edddd973e 100644
--- a/jarvis/brain/model_catalog.py
+++ b/jarvis/brain/model_catalog.py
@@ -1058,6 +1058,27 @@ def model_capabilities(provider: str, model_id: str) -> dict[str, bool | None]:
return {"vision": None, "tools": None}
+def model_context_length(provider: str, model_id: str) -> int | None:
+ """A model's declared context window, read SYNCHRONOUSLY from the cached
+ catalog; ``None`` when the cache does not know it.
+
+ For a brain constructor that has to publish a budget before it may touch
+ the network (same route and same reason as :func:`model_capabilities`).
+ """
+ from jarvis.core import config as _cfg
+
+ cache_path = _cfg.DATA_DIR / "model_catalog_cache.json"
+ wanted = {(model_id or "").strip(), (model_id or "").strip().removesuffix(":latest")}
+ try:
+ data = json.loads(cache_path.read_text(encoding="utf-8"))
+ for m in data.get(provider, {}).get("models", []):
+ if str(m.get("id") or "").removesuffix(":latest") in wanted:
+ return _positive_limit(m.get("context_length"))
+ except Exception: # noqa: BLE001, S110 — missing/corrupt cache means unknown
+ pass
+ return None
+
+
def pick_vision_model(provider: str) -> str | None:
"""The best vision-capable brain model of ``provider``, from the cached
``/v1/models`` catalog — or ``None`` when the catalog carries no modality
diff --git a/jarvis/brain/ollama_profiles.py b/jarvis/brain/ollama_profiles.py
index ed2f908e99..588f1617b1 100644
--- a/jarvis/brain/ollama_profiles.py
+++ b/jarvis/brain/ollama_profiles.py
@@ -60,6 +60,10 @@ _PROFILE_ALIAS_RE = re.compile(r"^(?P<prefix>.+)-jarvis-(?P<hash>[0-9a-f]{8})$")
#: Context ladder :func:`suggest_options` picks from (tokens).
_CONTEXT_LADDER: tuple[int, ...] = (4096, 8192, 16384, 32768, 65536, 131072)
+#: Bounds of the window a model gets when the person set none
+#: (:func:`automatic_context`).
+AUTOMATIC_CONTEXT_FLOOR = 16_384
+AUTOMATIC_CONTEXT_CEILING = 32_768
#: Rough KV-cache cost in GB per 1k tokens, scaled by the model's on-disk size
#: (a 4 GB model ~0.12 GB/1k, an 18 GB model ~0.54 GB/1k). An estimate: the
#: real figure depends on the architecture and the KV cache type, which is why
@@ -269,6 +273,50 @@ def largest_context_for(
return chosen
+def automatic_context(
+ *,
+ size_gb: float | None,
+ native_context: int | None,
+ accelerator_gb: float,
+ ram_gb: float | None,
+) -> tuple[int, str]:
+ """``(num_ctx, reason)`` for a model the person set no context for.
+
+ Ollama serves a small default window unless one is baked into the model,
+ and it shortens a longer prompt without an error — the system prompt and
+ the first tool schemas are what goes missing. So a model always gets an
+ explicit window: the largest ladder rung that fits this machine's memory,
+ held between :data:`AUTOMATIC_CONTEXT_FLOOR` (the app's prompt and a
+ working set of tools do not fit below it, so memory only warns here and
+ never refuses) and :data:`AUTOMATIC_CONTEXT_CEILING` (Ollama allocates the
+ whole cache up front; a larger window is the person's own choice in
+ Local Models → Tune), and never above the model's own window.
+ """
+ if accelerator_gb > 0:
+ budget: float | None = accelerator_gb
+ where = f"{accelerator_gb:.0f} GB of accelerator memory"
+ elif ram_gb:
+ budget = ram_gb * _RAM_SHARE
+ where = f"{_RAM_SHARE:.0%} of {ram_gb:g} GB RAM"
+ else:
+ budget = None
+ where = "unreadable memory"
+ fitted = (
+ largest_context_for(size_gb=size_gb, native_context=native_context, budget_gb=budget)
+ if size_gb is not None
+ else _CONTEXT_LADDER[0]
+ )
+ chosen = min(max(fitted, AUTOMATIC_CONTEXT_FLOOR), AUTOMATIC_CONTEXT_CEILING)
+ if native_context:
+ chosen = min(chosen, native_context)
+ note = (
+ ""
+ if fitted >= chosen
+ else f"; {fitted:,} would fit comfortably, the floor of {chosen:,} applies"
+ )
+ return chosen, f"num_ctx {chosen:,} sized from {where}{note}"
+
+
def suggest_options(
*,
size_gb: float,
diff --git a/jarvis/plugins/brain/local_openai.py b/jarvis/plugins/brain/local_openai.py
index 4c2d776d46..37ed578599 100644
--- a/jarvis/plugins/brain/local_openai.py
+++ b/jarvis/plugins/brain/local_openai.py
@@ -35,6 +35,7 @@ from typing import Any
import httpx
+from jarvis.brain import local_context
from jarvis.core import config as cfg
from jarvis.core.protocols import BrainDelta, BrainRequest
@@ -90,6 +91,11 @@ class LocalOpenAIBrain:
self._server_root: str | None = None
self._credential: str | None = None
self.supports_vision = _declared_vision_support(self._model)
+ # Tool fitting happens before complete(): publish the window this
+ # model was last seen running with, so the budget is the real one.
+ seen = local_context.known_window_for_model(self.name, self._model) if self._model else None
+ if seen:
+ self.context_window = seen
def can_call_tools(self) -> bool:
return self.supports_tools
@@ -151,6 +157,78 @@ class LocalOpenAIBrain:
log.info("local-openai: no model configured — using first served: %s", self._model)
return self._model
+ def _probe_headers(self) -> dict[str, str]:
+ return {"Authorization": f"Bearer {self._credential}"} if self._credential else {}
+
+ async def _guard_window(
+ self, req: BrainRequest, root: str, model: str, *, fresh: bool = False
+ ) -> bool:
+ """Refuse ``req`` when the server's own window cannot hold it.
+
+ Returns whether the server stated its window. A stated window also
+ becomes this brain's ``context_window``, so the next turn's tool
+ surface is budgeted against what really runs.
+ """
+ window = await local_context.probe_server_window(
+ root, model, headers=self._probe_headers(), fresh=fresh
+ )
+ if window is None:
+ return False
+ self.context_window = window.tokens
+ local_context.ensure_fits(
+ req, window.tokens, provider=self.name, model=model, kind=window.kind
+ )
+ return True
+
+ async def prepare_context_window(self) -> None:
+ """Settle ``context_window`` before the caller budgets a turn.
+
+ Tools are fitted before ``complete()`` runs, so the first turn after a
+ model was chosen would otherwise be planned for the class figure and
+ refused whole instead of having its tools trimmed. One cached question
+ to the server; a brain still discovering its model skips it. Never
+ raises.
+ """
+ if not self._model:
+ return
+ try:
+ root = self._resolve_root()
+ window = await local_context.probe_server_window(
+ root, self._model, headers=self._probe_headers()
+ )
+ except Exception as exc: # noqa: BLE001 — sizing must never cost the turn
+ log.debug("local-openai: could not settle the context window early: %s", exc)
+ return
+ if window is not None:
+ self.context_window = window.tokens
+
+ def _judge_reported_prompt(
+ self, req: BrainRequest, root: str, model: str, reported: int | None
+ ) -> None:
+ """Compare what a server that states no window says it read.
+
+ Two responses in a row that read far less than was sent tighten the
+ budget of the next turn; one that read more than a recorded suspicion
+ clears it. Never fails the turn: the signal is a suspicion.
+ """
+ verdict, tokens = local_context.judge_reported_prompt(
+ self.name, root, model, req, reported
+ )
+ if verdict == "tighten":
+ self.context_window = tokens
+ log.warning(
+ "local-openai: %s at %s twice read about %d prompt tokens of requests "
+ "at least twice that size, so the server is most likely cutting the "
+ "prompt short. Planning the next turn for %d tokens. %s",
+ model,
+ root,
+ tokens,
+ tokens,
+ local_context.fix_hint("unknown", local_context.certain_tokens(req)),
+ )
+ elif verdict == "restore":
+ self.context_window = type(self).context_window
+
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
client = self._client
if client is None:
@@ -158,10 +236,43 @@ class LocalOpenAIBrain:
# the event loop (BUG-189; see claude_api.py for the measurement).
client = await asyncio.to_thread(self._ensure_client)
model = await self._resolve_model()
- async for delta in stream_complete(
- client, model, req, supports_vision=self.supports_vision
- ):
- yield delta
+ root = self._resolve_root()
+ stated = await self._guard_window(req, root, model)
+ reported: int | None = None
+ stream = stream_complete(client, model, req, supports_vision=self.supports_vision)
+ try:
+ first = True
+ async for delta in stream:
+ if first and not stated:
+ # A server that loads on demand only knows its window once
+ # the model is in memory, which the first token proves.
+ # Ask again before anything is handed on, so a prompt that
+ # was cut short never reaches the caller as an answer.
+ stated = await self._guard_window(req, root, model, fresh=True)
+ first = False
+ if delta.usage:
+ reported = local_context.reported_prompt_tokens(delta.usage)
+ yield delta
+ except local_context.LocalContextError:
+ raise
+ except Exception as exc:
+ if not local_context.is_overflow_refusal(str(exc)):
+ raise
+ # The server refused the size itself. Say how large it has to be
+ # and where to change it instead of passing a bare HTTP 400 on.
+ known = local_context.known_window(self.name, root, model)
+ stated_window = known is not None and known[1] == "server"
+ raise local_context.refusal_error(
+ req,
+ provider=self.name,
+ model=model,
+ kind=known[2] if known is not None and stated_window else "unknown",
+ window_tokens=known[0] if known is not None and stated_window else 0,
+ ) from exc
+ finally:
+ await stream.aclose()
+ if not stated:
+ self._judge_reported_prompt(req, root, model, reported)
def estimate_cost(self, req: BrainRequest) -> float:
# Local inference has no per-token bill.
diff --git a/jarvis/plugins/brain/ollama.py b/jarvis/plugins/brain/ollama.py
index ed495e6c09..facb74a566 100644
--- a/jarvis/plugins/brain/ollama.py
+++ b/jarvis/plugins/brain/ollama.py
@@ -37,12 +37,16 @@ from __future__ import annotations
import asyncio
import logging
import os
+import re
+import time
from collections.abc import AsyncIterator
-from dataclasses import fields, replace
+from dataclasses import dataclass, fields, replace
from typing import Any
+from urllib.parse import urlsplit
import httpx
+from jarvis.brain import local_context
from jarvis.core import config as cfg
from jarvis.core.config import OllamaModelOptions
from jarvis.core.protocols import BrainDelta, BrainRequest
@@ -67,6 +71,61 @@ RECOMMENDED_VISION_PULL = "qwen3-vl"
# for minutes — hence the wide read timeout.
CLIENT_TIMEOUT = httpx.Timeout(connect=2.0, read=120.0, write=30.0, pool=30.0)
+# The automatic window per (server root, model): sized once per process, since
+# a changed ``num_ctx`` makes Ollama reload the weights.
+_AUTOMATIC_CONTEXT: dict[tuple[str, str], int] = {}
+# What ``/api/ps`` last reported per (server root, running model): the context
+# (``None`` when the server does not report one) and when it was read.
+_RUNNING_CONTEXT: dict[tuple[str, str], tuple[int | None, float]] = {}
+_RUNNING_TTL_S = 300.0
+# (server root, profile alias) the server refused to create, and when.
+_PROFILE_REFUSED: dict[tuple[str, str], float] = {}
+_PROFILE_REFUSED_TTL_S = 300.0
+
+_NUM_CTX_PARAMETER_RE = re.compile(r"^\s*num_ctx\s+(\d+)\s*$", re.MULTILINE)
+_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "[::1]"})
+
+
+@dataclass(frozen=True, slots=True)
+class _PreparedCall:
+ """What one ``complete()`` streams with. Per call, never per instance."""
+
+ run_model: str
+ req: BrainRequest
+ #: The context this call should run with, or ``None`` when nothing set one.
+ planned: int | None
+ #: Whether the server is known to run ``planned`` (a created profile, or
+ #: the model's own declaration).
+ confirmed: bool
+
+
+def reset_context_memo() -> None:
+ """Forget sized and verified windows (tests, or a changed endpoint)."""
+ _AUTOMATIC_CONTEXT.clear()
+ _RUNNING_CONTEXT.clear()
+ _PROFILE_REFUSED.clear()
+
+
+def _running_memo(root: str, run_model: str) -> int | None:
+ """The context ``/api/ps`` last reported for ``run_model``, if still fresh."""
+ memo = _RUNNING_CONTEXT.get((root, run_model.removesuffix(":latest")))
+ if memo is None or time.monotonic() - memo[1] > _RUNNING_TTL_S:
+ return None
+ return memo[0]
+
+
+def _is_this_machine(root: str) -> bool:
+ """Whether the server root points at the machine this app runs on."""
+ return (urlsplit(root).hostname or "").lower() in _LOOPBACK_HOSTS
+
+
+def _declared_num_ctx(parameters: Any) -> int | None:
+ """The ``num_ctx`` a model's own Modelfile sets, from ``/api/show``."""
+ if not isinstance(parameters, str):
+ return None
+ match = _NUM_CTX_PARAMETER_RE.search(parameters)
+ return int(match.group(1)) if match else None
+
def normalize_server_root(url: str) -> str:
"""Normalize a user/env-supplied Ollama address to a bare server root.
@@ -172,16 +231,26 @@ class OllamaBrain:
# Per-model ``/api/show`` capability cache, shared by discovery and the
# image path so one turn never probes the same download twice.
self._caps_cache: dict[str, set[str] | None] = {}
+ # The same answer's native context window, for the automatic sizing,
+ # and the ``num_ctx`` the model's own Modelfile declares, if any.
+ self._native_context: dict[str, int | None] = {}
+ self._declared_context: dict[str, int | None] = {}
self.supports_vision = _declared_vision_support(self._model)
if self._model:
from jarvis.brain.model_catalog import model_capabilities
self.supports_tools = model_capabilities("ollama", self._model)["tools"] is not False
- # Tool fitting and history compaction happen before complete().
- # Publish an explicit local context limit before either budgets.
- options = self._model_options(self._model)
- if options is not None and options.num_ctx:
- self.context_window = options.num_ctx
+ # Tool fitting and history compaction happen before complete().
+ # Publish an explicit local context limit before either budgets: the
+ # person's own, else the window this model was last given, else the
+ # floor every automatic window starts from (never the class figure,
+ # which the server does not run unless it is asked to).
+ options = self._model_options(self._model) if self._model else None
+ if options is not None and options.num_ctx:
+ self.context_window = options.num_ctx
+ else:
+ seen = local_context.known_window_for_model(self.name, self._model)
+ self.context_window = seen or self._unconfirmed_budget(self._model)
def can_call_tools(self) -> bool:
return self.supports_tools
@@ -348,9 +417,16 @@ class OllamaBrain:
) as client:
resp = await client.post(f"{root}/api/show", json={"model": name})
resp.raise_for_status()
- caps = resp.json().get("capabilities")
+ shown = resp.json()
+ caps = shown.get("capabilities")
if isinstance(caps, list):
caps_set = {str(c) for c in caps}
+ from jarvis.brain.ollama_inventory import ( # noqa: PLC0415 — lazy (AP-26)
+ native_context_length,
+ )
+
+ self._native_context[name] = native_context_length(shown.get("model_info"))
+ self._declared_context[name] = _declared_num_ctx(shown.get("parameters"))
except Exception: # noqa: BLE001 — retry unavailable metadata on the next turn
log.debug("ollama: capability lookup failed for %s", name, exc_info=True)
caps_set = None
@@ -400,7 +476,19 @@ class OllamaBrain:
# The negotiated model DOES see — keep the instance flag honest for
# the next synchronous resolver question.
self.supports_vision = True
- run_model, req = await self._apply_model_options(model, req)
+ call = await self._prepare_call(model, req)
+ req = call.req
+ root = self._resolve_root()
+ native = self._native_context.get(model)
+ # Refuse before sending what the window certainly cannot hold. Until
+ # the server confirmed a window (a created profile, or an earlier
+ # look at the loaded model) there is nothing to hold the request to.
+ window = self._effective_window(call, root)
+ if window:
+ self.context_window = window
+ local_context.ensure_fits(
+ req, window, provider=self.name, model=model, kind="ollama", ceiling=native
+ )
# A temperature the person set on the model card is sent even to an
# agent that chose none; otherwise the agent request profile decides.
options = self._model_options(model)
@@ -408,10 +496,253 @@ class OllamaBrain:
# Invariant at this point: either the request carries no images, or the
# model just negotiated declares ``vision`` — so the streamer may encode
# them.
- async for delta in stream_complete(
- client, run_model, req, supports_vision=True, send_temperature=send_temperature
- ):
- yield delta
+ stream = stream_complete(
+ client, call.run_model, req, supports_vision=True, send_temperature=send_temperature
+ )
+ reported: int | None = None
+ try:
+ first = True
+ async for delta in stream:
+ if first:
+ # The first token proves the model is loaded, so the server
+ # can now say which window it really runs. Checked before
+ # anything is handed on: a prompt that was cut short must
+ # never reach the caller as an answer.
+ window = await self._verify_running_context(call, root, model) or window
+ if window:
+ self.context_window = window
+ local_context.ensure_fits(
+ req,
+ window,
+ provider=self.name,
+ model=model,
+ kind="ollama",
+ ceiling=native,
+ truncated=True,
+ )
+ first = False
+ if delta.usage:
+ reported = local_context.reported_prompt_tokens(delta.usage)
+ yield delta
+ except local_context.LocalContextError:
+ raise
+ except Exception as exc:
+ if not local_context.is_overflow_refusal(str(exc)):
+ raise
+ # The server refused the size itself. Say how large the window has
+ # to be and where to set it instead of passing a bare HTTP 400 on.
+ raise local_context.refusal_error(
+ req, provider=self.name, model=model, kind="ollama", window_tokens=window or 0
+ ) from exc
+ finally:
+ await stream.aclose()
+ if not window:
+ # No profile and a server that does not report its window: judge
+ # it by what it says it read.
+ self._judge_reported_prompt(req, root, model, reported)
+
+ def _judge_reported_prompt(
+ self, req: BrainRequest, root: str, model: str, reported: int | None
+ ) -> None:
+ verdict, tokens = local_context.judge_reported_prompt(
+ self.name, root, model, req, reported
+ )
+ if verdict == "tighten":
+ self.context_window = tokens
+ log.warning(
+ "ollama: %s twice read about %d prompt tokens of requests at least "
+ "twice that size, so the prompt is most likely being cut short. "
+ "Planning the next turn for %d tokens. %s",
+ model,
+ tokens,
+ tokens,
+ local_context.fix_hint("ollama", local_context.certain_tokens(req)),
+ )
+ elif verdict == "restore":
+ self.context_window = self._unconfirmed_budget(model)
+
+ def _unconfirmed_budget(self, model: str) -> int:
+ """What to budget for before any window is confirmed for ``model``.
+
+ The floor every automatic window starts from, held to the model's own
+ window where the cached catalog knows it — never the class figure,
+ which the server does not run unless it is asked to.
+ """
+ from jarvis.brain.ollama_profiles import ( # noqa: PLC0415 — lazy (AP-26)
+ AUTOMATIC_CONTEXT_FLOOR,
+ )
+
+ native = self._native_context.get(model)
+ if native is None and model:
+ try:
+ from jarvis.brain.model_catalog import ( # noqa: PLC0415 — lazy (AP-26)
+ model_context_length,
+ )
+
+ native = model_context_length("ollama", model)
+ except Exception: # noqa: BLE001 — an unreadable catalog means "unknown"
+ log.debug("ollama: cached context length unavailable for %s", model)
+ return min(AUTOMATIC_CONTEXT_FLOOR, native) if native else AUTOMATIC_CONTEXT_FLOOR
+
+ async def prepare_context_window(self) -> None:
+ """Settle ``context_window`` before the caller budgets a turn.
+
+ Tools are fitted before ``complete()`` runs, so a brain that only
+ learned its window there would have its first turn planned for the
+ wrong size. With a pinned model this sizes the window once (two local
+ round-trips, then cached); a discovering brain keeps the floor until
+ its first call picked a model. Never raises.
+ """
+ if not self._model or self._requested_context_window is not None:
+ return
+ try:
+ root = self._resolve_root()
+ options = self._model_options(self._model)
+ planned = (
+ options.num_ctx
+ if options is not None and options.num_ctx
+ else await self._planned_window(self._model)
+ )
+ # What the server was last seen running for this model wins over
+ # the plan: a refused profile or a capped window is already known.
+ seen = local_context.known_window(self.name, root, self._model)
+ reported = seen[0] if seen is not None and seen[1] == "server" else None
+ self.context_window = min(planned, reported) if reported else planned
+ except Exception as exc: # noqa: BLE001 — sizing must never cost the turn
+ log.debug("ollama: could not settle the context window early: %s", exc)
+
+ async def _planned_window(self, model: str) -> int:
+ """The window ``model`` should run with when the person set none.
+
+ The larger of what the model declares for itself (a Modelfile
+ ``num_ctx``) and the automatic size: a model that already asks for
+ more than the automatic window must not be shrunk by it.
+ """
+ automatic = await self._automatic_context(model)
+ return max(automatic, self._declared_context.get(model) or 0)
+
+ async def _automatic_context(self, model: str) -> int:
+ """The window sized for this machine, once per server and model.
+
+ Remembered for the life of the process, because a changed ``num_ctx``
+ makes Ollama reload the weights. Only a complete answer is remembered:
+ when the size or the model facts could not be read (a server still
+ starting), the conservative result stands for this call and the next
+ one asks again. Never raises.
+ """
+ root = self._resolve_root()
+ key = (root, model.removesuffix(":latest"))
+ cached = _AUTOMATIC_CONTEXT.get(key)
+ if cached is not None:
+ return cached
+ from jarvis.brain import ollama_pull # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.brain.ollama_inventory import same_model # noqa: PLC0415
+ from jarvis.brain.ollama_profiles import automatic_context # noqa: PLC0415
+
+ size_gb: float | None = None
+ try:
+ async with httpx.AsyncClient(
+ timeout=CLIENT_TIMEOUT, headers=self._native_headers(),
+ ) as client:
+ resp = await client.get(f"{root}/api/tags")
+ resp.raise_for_status()
+ rows = resp.json().get("models") or []
+ for row in rows:
+ if same_model(str(row.get("name") or ""), model):
+ size = int(row.get("size") or 0)
+ size_gb = size / (1024**3) if size > 0 else None
+ break
+ except Exception as exc: # noqa: BLE001 — an unreadable size means the floor
+ log.debug("ollama: size lookup for %s failed: %s", model, exc)
+ if model not in self._native_context:
+ await self._capabilities(model, root)
+ if _is_this_machine(root):
+ accelerator_gb, _source = await asyncio.to_thread(ollama_pull.accelerator_gb)
+ ram_gb = await asyncio.to_thread(ollama_pull.total_memory_gb)
+ else:
+ # The server is another machine; this one's memory says nothing
+ # about what fits there.
+ accelerator_gb, ram_gb = 0.0, None
+ tokens, reason = automatic_context(
+ size_gb=size_gb,
+ native_context=self._native_context.get(model),
+ accelerator_gb=accelerator_gb,
+ ram_gb=ram_gb,
+ )
+ if size_gb is not None and model in self._native_context:
+ _AUTOMATIC_CONTEXT[key] = tokens
+ # A brain built for the next turn budgets for this from the start.
+ local_context.remember_window(
+ self.name, root, model, tokens, source="plan", kind="ollama"
+ )
+ log.info("ollama: %s has no context set, using %s", model, reason)
+ return tokens
+
+ def _effective_window(self, call: _PreparedCall, root: str) -> int | None:
+ """The window this call is known to run with, or ``None``.
+
+ What the server last reported for the model about to stream wins,
+ held to the plan; otherwise the plan counts only when the server
+ accepted it.
+ """
+ running = _running_memo(root, call.run_model)
+ if running:
+ return min(running, call.planned) if call.planned else running
+ return call.planned if call.confirmed else None
+
+ async def _verify_running_context(
+ self, call: _PreparedCall, root: str, model: str
+ ) -> int | None:
+ """Read the window the server RUNS and return the one this call has.
+
+ ``/api/ps`` reports the context a loaded model was given. A smaller
+ one than planned means the profile was not applied or the server
+ capped it; the caller then refuses a request that already exceeds it
+ instead of answering from a shortened prompt. The answer is kept for
+ a few minutes per server and running model, and it is applied on
+ every call, not only the one that fetched it. A server that does not
+ report the figure leaves the plan standing.
+ """
+ key = (root, call.run_model.removesuffix(":latest"))
+ memo = _RUNNING_CONTEXT.get(key)
+ if memo is None or time.monotonic() - memo[1] > _RUNNING_TTL_S:
+ from jarvis.brain.ollama_inventory import same_model # noqa: PLC0415 — lazy (AP-26)
+
+ running: int | None = None
+ try:
+ async with httpx.AsyncClient(
+ timeout=CLIENT_TIMEOUT, headers=self._native_headers(),
+ ) as client:
+ resp = await client.get(f"{root}/api/ps")
+ resp.raise_for_status()
+ rows = resp.json().get("models") or []
+ for row in rows:
+ if same_model(str(row.get("name") or row.get("model") or ""), call.run_model):
+ value = row.get("context_length")
+ if isinstance(value, (int, float)) and value > 0:
+ running = int(value)
+ break
+ except Exception as exc: # noqa: BLE001 — verification is best-effort
+ log.debug("ollama: running-context check for %s failed: %s", call.run_model, exc)
+ return self._effective_window(call, root)
+ _RUNNING_CONTEXT[key] = (running, time.monotonic())
+ if running is not None:
+ effective = min(running, call.planned) if call.planned else running
+ local_context.remember_window(
+ self.name, root, model, effective, source="server", kind="ollama"
+ )
+ if call.planned and running < call.planned:
+ log.warning(
+ "ollama: %s runs with %d tokens of context, not the %d that "
+ "were prepared. %s",
+ call.run_model,
+ running,
+ call.planned,
+ local_context.fix_hint(
+ "ollama", call.planned, ceiling=self._native_context.get(model)
+ ),
+ )
+ return self._effective_window(call, root)
def _model_options(self, model: str) -> OllamaModelOptions | None:
"""The user's per-model knobs for ``model`` from
@@ -433,60 +764,108 @@ class OllamaBrain:
or provider.models.get(f"{model}:latest"))
async def _apply_model_options(self, model: str, req: BrainRequest) -> tuple[str, BrainRequest]:
- """Turn the per-model options into ``(model to stream, request)``.
+ """``(model to stream, request)`` for ``model`` — see ``_prepare_call``."""
+ call = await self._prepare_call(model, req)
+ return call.run_model, call.req
+
+ async def _prepare_call(self, model: str, req: BrainRequest) -> _PreparedCall:
+ """Turn the per-model options into what one call streams with.
Bakeable knobs go through a derived profile alias (``/api/create``);
``keep_alive`` through the warm ping; ``temperature`` / ``num_predict``
/ ``think`` override the request — but only where the caller left the
field at its default, so a deterministic tool step that asked for
``temperature=0`` or ``reasoning_effort="none"`` keeps its own choice.
- ``num_ctx`` also narrows ``context_window`` so the manager budgets
- against the real window instead of the class floor.
+
+ The context window is never left to the server's default, which is
+ small and shortens a longer prompt without an error: the runtime's
+ allocation wins, then the person's own ``num_ctx``, then the larger of
+ the model's own declaration and the automatic size. Everything this
+ call needs afterwards is returned, not kept on the instance: one
+ brain serves concurrent calls.
"""
opts = self._model_options(model)
+ # ``confirmed``: the server is known to run ``planned`` without a
+ # profile, because the model itself declares it.
+ confirmed = False
if self._requested_context_window is not None:
if opts is not None and opts.num_ctx and opts.num_ctx < self._requested_context_window:
raise RuntimeError("The local model context changed. Start the turn again.")
opts = (opts or OllamaModelOptions()).model_copy(
update={"num_ctx": self._requested_context_window}
)
- if opts is None:
- return model, req
+ planned: int | None = self._requested_context_window
+ elif opts is not None and opts.num_ctx:
+ planned = opts.num_ctx
+ else:
+ planned = await self._planned_window(model)
+ declared = self._declared_context.get(model)
+ if declared and declared >= planned:
+ confirmed = True
+ else:
+ opts = (opts or OllamaModelOptions()).model_copy(update={"num_ctx": planned})
from jarvis.brain.ollama_profiles import ( # noqa: PLC0415 — lazy (AP-26)
ensure_profile,
has_bakeable,
+ profile_name,
to_v1_kwargs,
warm,
)
root = self._resolve_root()
run_model = model
- if has_bakeable(opts):
- try:
- run_model = await ensure_profile(root, model, opts, headers=self._native_headers())
- except Exception as exc: # noqa: BLE001 — degrade to the base model, say so
- if self._requested_context_window is not None:
- # The runtime already budgets against this window. Sending
- # to the base model would silently serve a smaller context.
- raise RuntimeError(
- "Could not prepare the selected local model context."
- ) from exc
- log.warning(
- "ollama: profile for %s unavailable, running the base model (%s)",
- model,
- exc,
- )
- run_model = model
- if opts.num_ctx:
- self.context_window = opts.num_ctx
- if opts.keep_alive is not None:
+ if opts is not None and has_bakeable(opts):
+ refused_key = (root, profile_name(model, opts))
+ refused_at = _PROFILE_REFUSED.get(refused_key)
+ if refused_at is not None and time.monotonic() - refused_at < _PROFILE_REFUSED_TTL_S:
+ # This server said no a moment ago; asking again on every turn
+ # costs two round-trips and a warning each time.
+ created = False
+ else:
+ try:
+ run_model = await ensure_profile(
+ root, model, opts, headers=self._native_headers()
+ )
+ created = True
+ _PROFILE_REFUSED.pop(refused_key, None)
+ except Exception as exc: # noqa: BLE001 — degrade to the base model, say so
+ if self._requested_context_window is not None:
+ # The runtime already budgets against this window.
+ # Sending to the base model would silently serve a
+ # smaller context.
+ raise RuntimeError(
+ "Could not prepare the selected local model context."
+ ) from exc
+ _PROFILE_REFUSED[refused_key] = time.monotonic()
+ log.warning(
+ "ollama: profile for %s unavailable, running the base model with "
+ "the server's own context instead of %s tokens (%s)",
+ model,
+ opts.num_ctx,
+ exc,
+ )
+ created = False
+ if opts.num_ctx:
+ confirmed = created
+ if opts is not None and opts.keep_alive is not None:
await warm(root, run_model, opts.keep_alive, headers=self._native_headers())
overrides: dict[str, Any] = {}
defaults = {f.name: f.default for f in fields(BrainRequest)}
for key, value in to_v1_kwargs(opts).items():
if getattr(req, key, None) == defaults.get(key):
overrides[key] = value
- return run_model, (replace(req, **overrides) if overrides else req)
+ if planned and confirmed:
+ # Only a window the server accepted is published for the next
+ # turn's budget. After a refused profile the running window is
+ # whatever the server defaults to; ``_verify_running_context``
+ # reads it once the model has loaded.
+ self.context_window = planned
+ return _PreparedCall(
+ run_model=run_model,
+ req=replace(req, **overrides) if overrides else req,
+ planned=planned,
+ confirmed=bool(planned and confirmed),
+ )
def estimate_cost(self, req: BrainRequest) -> float:
# Local inference has no per-token bill.
diff --git a/tests/unit/brain/test_context_window_fit.py b/tests/unit/brain/test_context_window_fit.py
index d39edf2ce1..0a082950fa 100644
--- a/tests/unit/brain/test_context_window_fit.py
+++ b/tests/unit/brain/test_context_window_fit.py
@@ -250,6 +250,101 @@ class TestContextOverflowCause:
assert "Netzwerk" not in text # i18n-allow
+class TestLocalContextCause:
+ """A local server runs the model with a window too small for the request.
+
+ The remedy is one setting on the person's own machine, not another model
+ or a new chat, so the cause is its own and says so.
+ """
+
+ @staticmethod
+ def _error() -> str:
+ from jarvis.brain.local_context import LocalContextError, fix_hint
+
+ return str(
+ LocalContextError(
+ provider="local-openai",
+ model="qwen",
+ needed_tokens=18_000,
+ window_tokens=4_096,
+ how_to_fix=fix_hint("lm-studio", 18_000),
+ )
+ )
+
+ def test_the_guards_own_sentence_classifies_as_local_context(self) -> None:
+ assert _classify_provider_error(self._error(), default="call_fail") == "local_context"
+
+ def test_it_never_dead_lists_the_provider(self) -> None:
+ assert "local_context" not in _DEAD_LIST_KINDS
+
+ def test_spoken_cause_names_the_setting_to_change(self) -> None:
+ errors = [("local-openai", "qwen", "local_context", self._error())]
+ cause = _primary_provider_down_cause(errors)
+ assert cause == "local_context"
+ phrase = _provider_down_phrase("en", 0, cause)
+ assert phrase == _PROVIDER_DOWN_CAUSE_PHRASES["local_context"]["en"]
+ low = phrase.lower()
+ assert "context length" in low and "local" in low
+ assert "network" not in low
+
+ def test_it_outranks_the_generic_overflow_wording(self) -> None:
+ errors = [
+ ("openrouter", "m", "context_overflow", "…"),
+ ("ollama", "qwen", "local_context", self._error()),
+ ]
+ assert _primary_provider_down_cause(errors) == "local_context"
+
+ def test_developer_diagnostic_keeps_the_size_and_the_setting(self) -> None:
+ text = _format_provider_chain_error(
+ [("local-openai", "qwen", "local_context", self._error())]
+ )
+ assert "4096" in text and "18000" in text
+ assert "Context Length" in text
+ assert "Netzwerk" not in text # i18n-allow
+
+
+class TestWindowIsSettledBeforeFitting:
+ """A local server's window is whatever it was started with, so the brain
+ has to ask. That must happen before tools are fitted, or the first turn is
+ budgeted for a figure the server does not run."""
+
+ async def test_a_brain_that_can_ask_is_asked_first(self) -> None:
+ from jarvis.brain.manager import _settle_context_window
+
+ class _Asking(_FakeBrain):
+ async def prepare_context_window(self) -> None:
+ self.context_window = 4_096
+
+ brain = _Asking(32_768)
+ await _settle_context_window(brain)
+ assert brain.context_window == 4_096
+
+ async def test_a_hosted_brain_is_not_touched(self) -> None:
+ from jarvis.brain.manager import _settle_context_window
+
+ brain = _FakeBrain(1_000_000)
+ await _settle_context_window(brain)
+ assert brain.context_window == 1_000_000
+
+ async def test_a_failing_or_slow_probe_never_costs_the_turn(self, monkeypatch) -> None:
+ import asyncio
+
+ import jarvis.brain.manager as manager
+
+ class _Broken(_FakeBrain):
+ async def prepare_context_window(self) -> None:
+ raise RuntimeError("server gone")
+
+ class _Slow(_FakeBrain):
+ async def prepare_context_window(self) -> None:
+ await asyncio.sleep(5)
+
+ monkeypatch.setattr(manager, "_CONTEXT_SETTLE_TIMEOUT_S", 0.01)
+ for brain in (_Broken(32_768), _Slow(32_768)):
+ await manager._settle_context_window(brain)
+ assert brain.context_window == 32_768
+
+
class TestToolCountCap:
"""Live 2026-09-29: xAI refused 378 tools ("the maximum is 350")."""
diff --git a/tests/unit/brain/test_local_context.py b/tests/unit/brain/test_local_context.py
new file mode 100644
index 0000000000..0b0ee9d720
--- /dev/null
+++ b/tests/unit/brain/test_local_context.py
@@ -0,0 +1,378 @@
+"""Local servers must never shorten a prompt without anyone noticing.
+
+Reported from testing: a 9B model never called the save tool and a larger one
+only ever listed. Local servers run a small default context, and with the
+system prompt plus every tool schema the start of the prompt was cut off with
+no error, so the model never saw some of its tools.
+
+The server is a fake behind ``httpx.MockTransport`` (a real httpx feature, no
+``unittest.mock``).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import httpx
+import pytest
+
+from jarvis.brain import local_context
+from jarvis.brain.local_context import (
+ LOCAL_CONTEXT_MARKER,
+ LocalContextError,
+ certain_tokens,
+ ensure_fits,
+ fix_hint,
+ is_overflow_refusal,
+ known_window,
+ known_window_for_model,
+ probe_server_window,
+ recommended_window,
+ remember_window,
+ reported_prompt_tokens,
+ truncation_suspected,
+)
+from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ROOT = "http://fake:1234"
+
+
[email protected](autouse=True)
+def _clean_registry():
+ local_context.reset_registry()
+ yield
+ local_context.reset_registry()
+
+
+def _req(chars: int, *, tools: int = 0) -> BrainRequest:
+ return BrainRequest(
+ messages=(BrainMessage(role="user", content="x" * chars),),
+ tools=tuple({"name": f"t{i}", "description": "d" * 80} for i in range(tools)),
+ system="s" * 400,
+ )
+
+
+def _server(routes: dict[str, Any]) -> httpx.MockTransport:
+ def handler(request: httpx.Request) -> httpx.Response:
+ payload = routes.get(request.url.path)
+ if payload is None:
+ return httpx.Response(404, json={"error": "not found"})
+ return httpx.Response(200, json=payload)
+
+ return httpx.MockTransport(handler)
+
+
+# ── Refusing before sending ──────────────────────────────────────────────
+
+
+def test_a_request_that_fits_is_left_alone() -> None:
+ ensure_fits(_req(4_000), 8_192, provider="local-openai", model="m", kind="lm-studio")
+
+
+def test_an_unknown_window_never_refuses() -> None:
+ ensure_fits(_req(4_000_000), 0, provider="local-openai", model="m", kind="unknown")
+
+
+def test_an_oversized_request_names_the_size_and_the_setting() -> None:
+ req = _req(80_000)
+ with pytest.raises(LocalContextError) as err:
+ ensure_fits(req, 4_096, provider="local-openai", model="qwen", kind="lm-studio")
+ msg = str(err.value)
+ assert LOCAL_CONTEXT_MARKER in msg.lower()
+ assert "4096" in msg
+ assert f"{certain_tokens(req)}" in msg
+ # The remedy is concrete: which program, which setting, how large.
+ assert "LM Studio" in msg and "Context Length" in msg
+ assert f"{recommended_window(certain_tokens(req))}" in msg
+ assert "was not sent" in msg
+ assert err.value.window_tokens == 4_096
+
+
+def test_the_recommendation_leaves_room_for_an_answer() -> None:
+ assert recommended_window(6_000) == 8_192
+ # 7,000 tokens fit 8,192 only without headroom for the reply.
+ assert recommended_window(7_000) == 16_384
+ assert recommended_window(10_000_000) == 262_144
+
+
+ ("kind", "needle"),
+ [
+ ("ollama", "Local Models"),
+ ("lm-studio", "Context Length"),
+ ("llama.cpp", "--ctx-size 16384"),
+ ("vllm", "--max-model-len 16384"),
+ ("tgi", "--max-total-tokens 16384"),
+ ("something-else", "LM Studio"),
+ ],
+)
+def test_every_server_kind_gets_its_own_instruction(kind: str, needle: str) -> None:
+ assert needle in fix_hint(kind, 10_000)
+
+
+def test_server_refusals_are_recognised() -> None:
+ assert is_overflow_refusal(
+ "Error code: 400 - the request exceeds the available context size"
+ )
+ assert is_overflow_refusal("This model's maximum context length is 4096 tokens")
+ assert not is_overflow_refusal("Connection refused")
+
+
+# ── Judging a server that states nothing ─────────────────────────────────
+
+
+def test_cached_tokens_count_towards_what_the_server_read() -> None:
+ assert reported_prompt_tokens({"input_tokens": 100, "cache_hit_tokens": 900}) == 1_000
+ assert reported_prompt_tokens({}) is None
+ assert reported_prompt_tokens(None) is None
+
+
+def test_a_prompt_read_in_full_is_not_suspected() -> None:
+ req = _req(60_000) # about 20,000 by the upper estimate
+ assert not truncation_suspected(req, 15_000)
+
+
+def test_a_prompt_cut_to_a_small_window_is_suspected() -> None:
+ req = _req(60_000)
+ assert truncation_suspected(req, 4_096)
+
+
+def test_a_cache_hit_reporting_only_new_tokens_is_not_suspected() -> None:
+ """Some servers report the tokens they newly evaluated. A handful of
+ tokens after a cache hit is not a truncated prompt."""
+ req = _req(60_000)
+ assert not truncation_suspected(req, 120)
+
+
+def test_small_prompts_are_never_judged() -> None:
+ assert not truncation_suspected(_req(3_000), 400)
+
+
+# ── Asking the server ────────────────────────────────────────────────────
+
+
+async def test_lm_studio_reports_the_loaded_context() -> None:
+ transport = _server(
+ {
+ "/v1/models": {"data": [{"id": "qwen"}]},
+ "/api/v0/models": {
+ "data": [
+ {
+ "id": "qwen",
+ "state": "loaded",
+ "loaded_context_length": 4_096,
+ "max_context_length": 131_072,
+ }
+ ]
+ },
+ }
+ )
+ window = await probe_server_window(ROOT, "qwen", transport=transport)
+ assert window is not None
+ # The LOADED figure, never the maximum the model could be given.
+ assert (window.tokens, window.kind) == (4_096, "lm-studio")
+ assert known_window("local-openai", ROOT, "qwen") == (4_096, "server", "lm-studio")
+ assert known_window_for_model("local-openai", "qwen") == 4_096
+
+
+async def test_lm_studio_model_not_loaded_yet_is_unknown() -> None:
+ transport = _server(
+ {
+ "/api/v0/models": {
+ "data": [{"id": "qwen", "state": "not-loaded", "max_context_length": 131_072}]
+ }
+ }
+ )
+ assert await probe_server_window(ROOT, "qwen", transport=transport) is None
+
+
+async def test_llama_cpp_reports_the_slot_context() -> None:
+ transport = _server({"/props": {"default_generation_settings": {"n_ctx": 8_192}}})
+ window = await probe_server_window(ROOT, "any", transport=transport)
+ assert window is not None and (window.tokens, window.kind) == (8_192, "llama.cpp")
+
+
+async def test_vllm_reports_max_model_len() -> None:
+ transport = _server({"/v1/models": {"data": [{"id": "qwen", "max_model_len": 32_768}]}})
+ window = await probe_server_window(ROOT, "qwen", transport=transport)
+ assert window is not None and (window.tokens, window.kind) == (32_768, "vllm")
+
+
+async def test_a_server_that_says_nothing_is_unknown_and_never_raises() -> None:
+ assert await probe_server_window(ROOT, "qwen", transport=_server({})) is None
+
+ def boom(request: httpx.Request) -> httpx.Response:
+ raise httpx.ConnectError("refused")
+
+ assert await probe_server_window(ROOT, "qwen", transport=httpx.MockTransport(boom)) is None
+
+
+async def test_the_answer_is_cached_and_a_fresh_ask_goes_out_again() -> None:
+ calls: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls.append(request.url.path)
+ if request.url.path == "/props":
+ return httpx.Response(200, json={"default_generation_settings": {"n_ctx": 4_096}})
+ return httpx.Response(404)
+
+ transport = httpx.MockTransport(handler)
+ await probe_server_window(ROOT, "m", transport=transport)
+ first = len(calls)
+ await probe_server_window(ROOT, "m", transport=transport)
+ assert len(calls) == first
+ # After a reload with a larger context the person asks again right away.
+ await probe_server_window(ROOT, "m", transport=transport, fresh=True)
+ assert len(calls) > first
+
+
+async def test_a_silent_server_is_not_asked_on_every_request() -> None:
+ calls: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls.append(request.url.path)
+ return httpx.Response(404)
+
+ transport = httpx.MockTransport(handler)
+ # Asked while the model is demonstrably loaded: this server does not tell.
+ await probe_server_window(ROOT, "m", transport=transport, fresh=True)
+ asked = len(calls)
+ await probe_server_window(ROOT, "m", transport=transport)
+ assert len(calls) == asked
+
+
+def test_the_newest_record_wins_across_server_roots() -> None:
+ remember_window("local-openai", "http://a:1", "m", 4_096, source="server")
+ remember_window("local-openai", "http://b:2", "m", 16_384, source="server")
+ assert known_window_for_model("local-openai", "m") == 16_384
+ assert known_window_for_model("ollama", "m") is None
+
+
+def test_a_suspected_window_lapses_but_a_stated_one_stays(monkeypatch) -> None:
+ """A window inferred from usage is a suspicion: it must not tighten the
+ budget forever on the strength of one odd response."""
+ remember_window("local-openai", ROOT, "guessed", 4_096, source="observed")
+ remember_window("local-openai", ROOT, "stated", 4_096, source="server")
+ later = local_context.time.monotonic() + local_context._OBSERVED_TTL_S + 1
+ monkeypatch.setattr(local_context.time, "monotonic", lambda: later)
+ assert known_window_for_model("local-openai", "guessed") is None
+ assert known_window("local-openai", ROOT, "guessed") is None
+ assert known_window_for_model("local-openai", "stated") == 4_096
+
+
+def test_one_odd_response_changes_nothing_and_two_tighten() -> None:
+ from jarvis.brain.local_context import judge_reported_prompt
+
+ req = _req(60_000)
+ assert judge_reported_prompt("local-openai", ROOT, "m", req, 4_096) == ("keep", 0)
+ assert known_window("local-openai", ROOT, "m") is None
+ assert judge_reported_prompt("local-openai", ROOT, "m", req, 4_096) == ("tighten", 4_096)
+ assert known_window("local-openai", ROOT, "m") == (4_096, "observed", "unknown")
+
+
+def test_an_honest_response_in_between_resets_the_count() -> None:
+ from jarvis.brain.local_context import judge_reported_prompt
+
+ req = _req(60_000)
+ judge_reported_prompt("local-openai", ROOT, "m", req, 4_096)
+ assert judge_reported_prompt("local-openai", ROOT, "m", req, 15_000) == ("keep", 0)
+ assert judge_reported_prompt("local-openai", ROOT, "m", req, 4_096) == ("keep", 0)
+
+
+def test_a_response_above_the_suspected_window_restores_the_budget() -> None:
+ from jarvis.brain.local_context import judge_reported_prompt
+
+ req = _req(60_000)
+ judge_reported_prompt("local-openai", ROOT, "m", req, 4_096)
+ judge_reported_prompt("local-openai", ROOT, "m", req, 4_096)
+ assert judge_reported_prompt("local-openai", ROOT, "m", req, 12_000) == ("restore", 0)
+ assert known_window("local-openai", ROOT, "m") is None
+
+
+def test_a_model_that_cannot_hold_the_request_is_told_to_change_model() -> None:
+ hint = fix_hint("ollama", 10_000, ceiling=8_192)
+ assert "8192" in hint and "larger context window" in hint
+ assert "16384" not in hint
+
+
+def test_an_encoded_image_in_a_block_is_not_counted_as_text() -> None:
+ """A screenshot rides in a content block as base64. Counted as prose it
+ would refuse every image turn."""
+ blob = "A" * 400_000
+ with_image = BrainRequest(
+ messages=(
+ BrainMessage(
+ role="user",
+ content=[
+ {"type": "text", "text": "what is this"},
+ {"type": "image", "source": {"type": "base64", "data": blob}},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64," + blob}},
+ ],
+ ),
+ ),
+ )
+ assert certain_tokens(with_image) < 50
+ ensure_fits(with_image, 4_096, provider="ollama", model="m", kind="ollama")
+
+
+def test_a_refusal_never_claims_a_prompt_larger_than_the_window() -> None:
+ from jarvis.brain.local_context import refusal_error
+
+ err = refusal_error(
+ _req(8_000), provider="local-openai", model="qwen", kind="vllm", window_tokens=8_192
+ )
+ msg = str(err)
+ assert LOCAL_CONTEXT_MARKER in msg.lower()
+ assert "refused this request as too large" in msg
+ # The next window up from the one that was too small, not the same one.
+ assert "--max-model-len 16384" in msg
+
+
+def test_a_brain_without_a_model_gets_no_other_models_window() -> None:
+ remember_window("ollama", ROOT, "big", 65_536, source="server")
+ assert known_window_for_model("ollama", "") is None
+
+
+async def test_a_silent_server_is_left_alone_even_for_a_fresh_ask() -> None:
+ """Four status requests before the first token of every turn would be a
+ standing delay for a server that will never answer them."""
+ calls: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ calls.append(request.url.path)
+ return httpx.Response(404)
+
+ transport = httpx.MockTransport(handler)
+ await probe_server_window(ROOT, "m", transport=transport, fresh=True)
+ asked = len(calls)
+ assert asked > 0
+ await probe_server_window(ROOT, "m", transport=transport, fresh=True)
+ assert len(calls) == asked
+
+
+async def test_a_malformed_root_never_raises() -> None:
+ assert await probe_server_window("not a url", "m") is None
+
+
[email protected]("needed", [12_404, 18_401, 9_402, 20_429, 6_500, 65_536])
[email protected]("window", [4_096, 8_192, 65_536])
[email protected]("kind", ["ollama", "lm-studio", "llama.cpp", "vllm", "tgi", "unknown"])
+def test_no_token_count_reads_as_an_http_status(needed: int, window: int, kind: str) -> None:
+ """Classifiers across the app take a free-standing three-digit group for
+ an HTTP status. Written "18,401 tokens", a too-small window was recorded as
+ a rejected key, and "65,536" as an unreachable server."""
+ from jarvis.brain.provider_test import ERROR, classify_provider_error
+
+ for refused in (False, True):
+ message = str(
+ LocalContextError(
+ provider="local-openai",
+ model="qwen",
+ needed_tokens=needed,
+ window_tokens=window,
+ how_to_fix=fix_hint(kind, needed, ceiling=None),
+ refused=refused,
+ )
+ )
+ assert classify_provider_error(message) == ERROR, message
+ assert classify_provider_error(fix_hint(kind, needed, ceiling=window)) == ERROR
diff --git a/tests/unit/brain/test_ollama_profiles.py b/tests/unit/brain/test_ollama_profiles.py
index c5425ce216..351be6226e 100644
--- a/tests/unit/brain/test_ollama_profiles.py
+++ b/tests/unit/brain/test_ollama_profiles.py
@@ -275,3 +275,36 @@ def test_every_knob_has_one_sentence() -> None:
set_keys = [k for k in ("num_ctx", "num_gpu", "keep_alive") if getattr(opts, k) is not None]
assert len(reasons) == 1 + 3 # the budget sentence + one per knob (placement always speaks)
assert set_keys == ["num_ctx", "num_gpu", "keep_alive"]
+
+
+# ── automatic_context (a model the person set no context for) ────────────
+def test_the_automatic_window_never_drops_below_the_floor() -> None:
+ """Memory decides how far above the floor the window goes, never whether
+ the prompt fits at all: below it the app has no room for its tools."""
+ tokens, reason = profiles.automatic_context(
+ size_gb=6.0, native_context=262_144, accelerator_gb=0.0, ram_gb=8.0
+ )
+ assert tokens == profiles.AUTOMATIC_CONTEXT_FLOOR
+ assert "floor" in reason
+
+
+def test_the_automatic_window_stops_at_the_ceiling() -> None:
+ tokens, _ = profiles.automatic_context(
+ size_gb=2.0, native_context=262_144, accelerator_gb=48.0, ram_gb=64.0
+ )
+ assert tokens == profiles.AUTOMATIC_CONTEXT_CEILING
+
+
+def test_the_automatic_window_respects_a_small_native_window() -> None:
+ tokens, _ = profiles.automatic_context(
+ size_gb=4.0, native_context=8_192, accelerator_gb=24.0, ram_gb=64.0
+ )
+ assert tokens == 8_192
+
+
+def test_unreadable_size_and_memory_still_give_the_floor() -> None:
+ tokens, reason = profiles.automatic_context(
+ size_gb=None, native_context=None, accelerator_gb=0.0, ram_gb=None
+ )
+ assert tokens == profiles.AUTOMATIC_CONTEXT_FLOOR
+ assert "unreadable memory" in reason
diff --git a/tests/unit/plugins/brain/test_local_openai.py b/tests/unit/plugins/brain/test_local_openai.py
index 6af92b979a..78e7b16ace 100644
--- a/tests/unit/plugins/brain/test_local_openai.py
+++ b/tests/unit/plugins/brain/test_local_openai.py
@@ -219,3 +219,175 @@ def test_wizard_whitelists_the_optional_secret() -> None:
# App-only: local servers usually need no key — it must not lengthen
# first-run onboarding.
assert spec.prompt is False
+
+
+# ── Context window: ask the server, refuse what cannot fit ───────────────
+class _Stream:
+ """Stands in for the shared streamer; records whether it was reached."""
+
+ calls: list[str] = []
+ usage: dict[str, int] | None = None
+ error: Exception | None = None
+
+ @classmethod
+ async def stream(cls, client: Any, model: str, req: Any, **kwargs: Any):
+ from jarvis.core.protocols import BrainDelta
+
+ cls.calls.append(model)
+ if cls.error is not None:
+ raise cls.error
+ yield BrainDelta(content="ok", finish_reason="stop")
+ if cls.usage is not None:
+ yield BrainDelta(usage=cls.usage)
+
+
+def served(monkeypatch):
+ """A brain wired to a fake stream and a server whose window the test sets."""
+ import openai
+
+ from jarvis.brain import local_context
+ from jarvis.plugins.brain import local_openai as plugin
+
+ local_context.reset_registry()
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ monkeypatch.setattr(plugin, "stream_complete", _Stream.stream)
+ _with_base_url("http://localhost:1234", monkeypatch)
+ _Stream.calls = []
+ _Stream.usage = None
+ _Stream.error = None
+ state: dict[str, Any] = {"before": None, "after": None, "asked": []}
+
+ async def probe(root: str, model: str, *, headers=None, transport=None, fresh=False):
+ state["asked"].append(fresh)
+ window = state["after"] if fresh else state["before"]
+ if window is not None:
+ local_context.remember_window(
+ "local-openai", root, model, window.tokens, source="server", kind=window.kind
+ )
+ return window
+
+ monkeypatch.setattr(local_context, "probe_server_window", probe)
+ yield state
+ local_context.reset_registry()
+
+
+def _request(chars: int = 20):
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ return BrainRequest(messages=(BrainMessage(role="user", content="x" * chars),))
+
+
+async def _drain(brain: LocalOpenAIBrain, req: Any) -> list[Any]:
+ return [delta async for delta in brain.complete(req)]
+
+
+async def test_the_servers_own_window_becomes_the_budget(served) -> None:
+ from jarvis.brain.local_context import ServerWindow
+
+ served["before"] = ServerWindow(8_192, "llama.cpp")
+ brain = LocalOpenAIBrain(model="qwen")
+ assert brain.context_window == LocalOpenAIBrain.context_window
+ await _drain(brain, _request())
+ assert brain.context_window == 8_192
+ # A brain built for the next turn budgets its tools for the real window.
+ assert LocalOpenAIBrain(model="qwen").context_window == 8_192
+
+
+async def test_a_request_the_loaded_window_cannot_hold_is_never_sent(served) -> None:
+ from jarvis.brain.local_context import LocalContextError, ServerWindow
+
+ served["before"] = ServerWindow(4_096, "lm-studio")
+ with pytest.raises(LocalContextError) as err:
+ await _drain(LocalOpenAIBrain(model="qwen"), _request(80_000))
+ assert _Stream.calls == []
+ msg = str(err.value)
+ assert "4096" in msg and "LM Studio" in msg and "Context Length" in msg
+
+
+async def test_a_model_loaded_by_the_request_is_checked_before_the_answer(served) -> None:
+ """LM Studio loads on demand: before the request the window is unknown,
+ after the first token the server states it. A prompt it cut short must not
+ reach the caller as an answer."""
+ from jarvis.brain.local_context import LocalContextError, ServerWindow
+
+ served["after"] = ServerWindow(4_096, "lm-studio")
+ handed_on: list[Any] = []
+ with pytest.raises(LocalContextError):
+ async for delta in LocalOpenAIBrain(model="qwen").complete(_request(80_000)):
+ handed_on.append(delta)
+ assert handed_on == []
+ assert served["asked"] == [False, True]
+
+
+async def test_a_server_refusal_names_the_setting(served) -> None:
+ from jarvis.brain.local_context import LocalContextError
+
+ _Stream.error = RuntimeError(
+ "Error code: 400 - the request exceeds the available context size"
+ )
+ with pytest.raises(LocalContextError) as err:
+ await _drain(LocalOpenAIBrain(model="qwen"), _request(80_000))
+ assert "--ctx-size" in str(err.value) and "Context Length" in str(err.value)
+
+
+async def test_other_server_errors_pass_through_unchanged(served) -> None:
+ _Stream.error = RuntimeError("Error code: 500 - model crashed")
+ with pytest.raises(RuntimeError) as err:
+ await _drain(LocalOpenAIBrain(model="qwen"), _request())
+ assert "model crashed" in str(err.value)
+
+
+async def test_a_silent_server_that_read_far_less_tightens_the_next_budget(served) -> None:
+ """No way to ask and no refusal: the only evidence is how many prompt
+ tokens the server says it read. That is a suspicion, so the turn is not
+ failed; the next one is planned for what the server demonstrably holds."""
+ _Stream.usage = {"input_tokens": 4_096, "output_tokens": 5}
+ brain = LocalOpenAIBrain(model="qwen")
+ deltas = await _drain(brain, _request(80_000))
+ assert deltas[0].content == "ok"
+ # One odd response changes nothing.
+ assert brain.context_window == LocalOpenAIBrain.context_window
+ await _drain(brain, _request(80_000))
+ assert brain.context_window == 4_096
+ assert LocalOpenAIBrain(model="qwen").context_window == 4_096
+
+
+async def test_a_later_full_read_clears_the_suspicion(served) -> None:
+ _Stream.usage = {"input_tokens": 4_096, "output_tokens": 5}
+ brain = LocalOpenAIBrain(model="qwen")
+ await _drain(brain, _request(80_000))
+ await _drain(brain, _request(80_000))
+ assert brain.context_window == 4_096
+ # The server now reports more than the suspected window, so it was wrong.
+ _Stream.usage = {"input_tokens": 12_000, "output_tokens": 5}
+ await _drain(brain, _request(40_000))
+ assert brain.context_window == LocalOpenAIBrain.context_window
+ assert LocalOpenAIBrain(model="qwen").context_window == LocalOpenAIBrain.context_window
+
+
+async def test_the_window_is_settled_before_the_first_turn_is_budgeted(served) -> None:
+ """Tools are fitted before complete(). A brain that only learned its
+ window there would have its first turn refused whole, not trimmed."""
+ from jarvis.brain.local_context import ServerWindow
+
+ served["before"] = ServerWindow(8_192, "llama.cpp")
+ brain = LocalOpenAIBrain(model="qwen")
+ await brain.prepare_context_window()
+ assert brain.context_window == 8_192
+ assert _Stream.calls == []
+
+
+async def test_a_refusal_does_not_claim_a_prompt_larger_than_the_window(served) -> None:
+ """vLLM counts prompt plus reply. The sentence must not say the prompt
+ needs less than the window and then call the window too small."""
+ from jarvis.brain.local_context import LocalContextError, ServerWindow
+
+ served["before"] = ServerWindow(8_192, "vllm")
+ _Stream.error = RuntimeError("This model's maximum context length is 8192 tokens")
+ with pytest.raises(LocalContextError) as err:
+ await _drain(LocalOpenAIBrain(model="qwen"), _request(8_000))
+ msg = str(err.value)
+ assert err.value.refused is True
+ assert "refused this request as too large" in msg
+ assert "--max-model-len 16384" in msg
diff --git a/tests/unit/plugins/brain/test_ollama.py b/tests/unit/plugins/brain/test_ollama.py
index 30b022ee17..b39f6ad2ef 100644
--- a/tests/unit/plugins/brain/test_ollama.py
+++ b/tests/unit/plugins/brain/test_ollama.py
@@ -33,6 +33,19 @@ class _FakeOpenAI:
_FakeOpenAI.last_kwargs = kwargs
[email protected](autouse=True)
+def _forget_context_windows():
+ """Sized and verified windows live per process; no test may inherit one."""
+ from jarvis.brain import local_context
+ from jarvis.plugins.brain import ollama as plugin
+
+ plugin.reset_context_memo()
+ local_context.reset_registry()
+ yield
+ plugin.reset_context_memo()
+ local_context.reset_registry()
+
+
def _no_override(monkeypatch) -> None:
install_provider_config(monkeypatch, JarvisConfig())
monkeypatch.delenv("OLLAMA_HOST", raising=False)
@@ -449,6 +462,10 @@ def test_tags_payload_shape_matches_documented_api() -> None:
# ── Per-model options (profile alias, warm ping, request overrides) ──────
+#: What the stubbed sizing answers in the ``wired`` tests.
+AUTOMATIC = 16_384
+
+
class _FakeStreamer:
"""Records what ``complete`` hands to the shared streamer."""
@@ -493,6 +510,17 @@ def wired(monkeypatch):
monkeypatch.setattr(plugin, "stream_complete", _FakeStreamer.stream)
monkeypatch.setattr(ollama_profiles, "ensure_profile", _FakeProfiles.ensure_profile)
monkeypatch.setattr(ollama_profiles, "warm", _FakeProfiles.warm)
+
+ async def _sized(self: OllamaBrain, model: str) -> int:
+ return AUTOMATIC
+
+ async def _unreported(self: OllamaBrain, *args: Any) -> None:
+ return None
+
+ # The sizing and the /api/ps check have their own tests below; here they
+ # must not reach a real server on the machine running the suite.
+ monkeypatch.setattr(OllamaBrain, "_automatic_context", _sized)
+ monkeypatch.setattr(OllamaBrain, "_verify_running_context", _unreported)
monkeypatch.delenv("OLLAMA_HOST", raising=False)
_FakeStreamer.calls = []
_FakeProfiles.ensured = []
@@ -517,15 +545,29 @@ async def _run(brain: OllamaBrain, req: Any) -> None:
pass
-async def test_no_options_means_no_profile_no_warm_no_override(monkeypatch, wired) -> None:
+async def test_no_options_still_get_an_explicit_context(monkeypatch, wired) -> None:
+ """Without a setting the server default applies, which is small and
+ shortens a longer prompt without an error. So a window is always sent."""
_config_with_options(monkeypatch, {})
brain = OllamaBrain(model="qwen3.5:9b")
await _run(brain, _req())
model, req = _FakeStreamer.calls[0]
- assert model == "qwen3.5:9b"
+ assert model == "qwen3.5-9b-jarvis-deadbeef"
+ assert [(b, o.num_ctx) for _, b, o in wired.ensured] == [("qwen3.5:9b", AUTOMATIC)]
assert req.temperature == 0.7 and req.reasoning_effort is None
- assert wired.ensured == [] and wired.warmed == []
- assert brain.context_window == OllamaBrain.context_window
+ assert wired.warmed == []
+ assert brain.context_window == AUTOMATIC
+
+
+def test_a_fresh_brain_budgets_for_the_floor_not_the_class_figure(monkeypatch) -> None:
+ """Tools are fitted before the first call. Until the window is sized the
+ budget is the floor every automatic window starts from, so the first turn
+ can never be planned larger than what the server is then asked to run."""
+ from jarvis.brain.ollama_profiles import AUTOMATIC_CONTEXT_FLOOR
+
+ _config_with_options(monkeypatch, {})
+ assert OllamaBrain(model="qwen3.5:9b").context_window == AUTOMATIC_CONTEXT_FLOOR
+ assert OllamaBrain().context_window == AUTOMATIC_CONTEXT_FLOOR
async def test_bakeable_options_stream_through_the_profile_alias(monkeypatch, wired) -> None:
@@ -544,13 +586,16 @@ async def test_bakeable_options_stream_through_the_profile_alias(monkeypatch, wi
assert req.reasoning_effort == "none"
-async def test_request_only_options_never_create_a_profile(monkeypatch, wired) -> None:
+async def test_request_only_options_ride_the_request(monkeypatch, wired) -> None:
_config_with_options(monkeypatch, {"qwen3.5:9b": {"temperature": 0.1, "num_predict": 300}})
brain = OllamaBrain(model="qwen3.5:9b")
await _run(brain, _req())
model, req = _FakeStreamer.calls[0]
- assert model == "qwen3.5:9b"
- assert wired.ensured == [] and wired.warmed == []
+ # The only baked knob is the automatic context; the knobs set on the
+ # model card still ride the request.
+ assert model == "qwen3.5-9b-jarvis-deadbeef"
+ assert [o.num_ctx for _, _, o in wired.ensured] == [AUTOMATIC]
+ assert wired.warmed == []
assert req.temperature == 0.1 and req.max_tokens == 300
@@ -570,7 +615,170 @@ async def test_profile_failure_degrades_to_the_base_model(monkeypatch, wired) ->
await _run(brain, _req())
model, _ = _FakeStreamer.calls[0]
assert model == "qwen3.5:9b"
- assert brain.context_window == 8192
+ call = await brain._prepare_call("qwen3.5:9b", _req())
+ # The plan stands, but nothing confirms the server runs it.
+ assert (call.planned, call.confirmed) == (8192, False)
+
+
+async def test_a_request_the_prepared_window_cannot_hold_is_never_sent(monkeypatch, wired) -> None:
+ from jarvis.brain.local_context import LocalContextError
+
+ _config_with_options(monkeypatch, {"qwen3.5:9b": {"num_ctx": 4096}})
+ brain = OllamaBrain(model="qwen3.5:9b")
+ with pytest.raises(LocalContextError) as err:
+ await _run(brain, _req(system="s" * 80_000))
+ assert _FakeStreamer.calls == []
+ msg = str(err.value)
+ assert "4096" in msg and "Local Models" in msg and "Tune" in msg
+
+
+# ── Automatic sizing and the check against what the server runs ──────────
+class _RoutedClient:
+ """A fake ``httpx.AsyncClient`` that answers by path."""
+
+ tags: dict[str, Any] | None = {}
+ show: dict[str, Any] = {}
+ ps: dict[str, Any] | None = {}
+ seen: list[str] = []
+
+ def __init__(self, **kwargs: Any) -> None:
+ pass
+
+ async def __aenter__(self) -> _RoutedClient:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+ async def get(self, url: str) -> _FakeResponse:
+ _RoutedClient.seen.append(url)
+ if url.endswith("/api/ps"):
+ if _RoutedClient.ps is None:
+ raise httpx.ConnectError("connection refused")
+ return _FakeResponse(_RoutedClient.ps)
+ if _RoutedClient.tags is None:
+ raise httpx.ConnectError("connection refused")
+ return _FakeResponse(_RoutedClient.tags)
+
+ async def post(self, url: str, json: dict[str, Any] | None = None) -> _FakeResponse:
+ return _FakeResponse(_RoutedClient.show)
+
+
+def routed(monkeypatch):
+ import openai
+
+ from jarvis.brain import ollama_profiles, ollama_pull
+ from jarvis.plugins.brain import ollama as plugin
+
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ monkeypatch.setattr(httpx, "AsyncClient", _RoutedClient)
+ monkeypatch.setattr(plugin, "stream_complete", _FakeStreamer.stream)
+ monkeypatch.setattr(ollama_profiles, "ensure_profile", _FakeProfiles.ensure_profile)
+ monkeypatch.setattr(ollama_profiles, "warm", _FakeProfiles.warm)
+ monkeypatch.setattr(ollama_pull, "accelerator_gb", lambda: (0.0, "none"))
+ monkeypatch.setattr(ollama_pull, "total_memory_gb", lambda: 16.0)
+ monkeypatch.delenv("OLLAMA_HOST", raising=False)
+ _config_with_options(monkeypatch, {})
+ _FakeStreamer.calls = []
+ _FakeProfiles.ensured = []
+ _FakeProfiles.warmed = []
+ _FakeProfiles.fail = False
+ _RoutedClient.tags = {"models": [{"name": "qwen3.5:9b", "size": 6 * 1024**3}]}
+ _RoutedClient.show = {
+ "capabilities": ["completion", "tools"],
+ "model_info": {"general.architecture": "qwen3", "qwen3.context_length": 262_144},
+ }
+ _RoutedClient.ps = {"models": []}
+ _RoutedClient.seen = []
+ return _RoutedClient
+
+
+async def test_sixteen_gb_of_ram_gets_the_floor_not_the_server_default(routed) -> None:
+ """6 GB of weights on a 16 GB machine without a readable accelerator:
+ 8k is what fits comfortably, but the prompt of this app does not fit 8k."""
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ assert [o.num_ctx for _, _, o in _FakeProfiles.ensured] == [16_384]
+ assert brain.context_window == 16_384
+
+
+async def test_a_large_card_gets_the_ceiling_not_the_native_window(routed, monkeypatch) -> None:
+ from jarvis.brain import ollama_pull
+
+ monkeypatch.setattr(ollama_pull, "accelerator_gb", lambda: (24.0, "nvidia"))
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ # The whole cache is allocated up front: 262k is never the default.
+ assert [o.num_ctx for _, _, o in _FakeProfiles.ensured] == [32_768]
+
+
+async def test_a_small_native_window_caps_the_automatic_one(routed) -> None:
+ routed.show = {
+ "capabilities": ["completion", "tools"],
+ "model_info": {"general.architecture": "old", "old.context_length": 8_192},
+ }
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ assert [o.num_ctx for _, _, o in _FakeProfiles.ensured] == [8_192]
+
+
+async def test_the_window_is_sized_once_per_model(routed) -> None:
+ """A changed num_ctx makes Ollama reload the weights."""
+ await _run(OllamaBrain(model="qwen3.5:9b"), _req())
+ tag_calls = sum(1 for url in routed.seen if url.endswith("/api/tags"))
+ await _run(OllamaBrain(model="qwen3.5:9b"), _req())
+ assert sum(1 for url in routed.seen if url.endswith("/api/tags")) == tag_calls
+
+
+async def test_a_server_that_runs_a_smaller_window_is_believed(routed) -> None:
+ """The profile could not be created, so the base model loads with the
+ server default. /api/ps says which, and that becomes the budget."""
+ _FakeProfiles.fail = True
+ routed.ps = {"models": [{"name": "qwen3.5:9b", "context_length": 4_096}]}
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ assert _FakeStreamer.calls[0][0] == "qwen3.5:9b"
+ assert brain.context_window == 4_096
+ # The next brain for this model plans with the real figure straight away.
+ assert OllamaBrain(model="qwen3.5:9b").context_window == 4_096
+
+
+async def test_a_prompt_the_server_cut_short_never_becomes_an_answer(routed) -> None:
+ from jarvis.brain.local_context import LocalContextError
+
+ _FakeProfiles.fail = True
+ routed.ps = {"models": [{"name": "qwen3.5:9b", "context_length": 4_096}]}
+ brain = OllamaBrain(model="qwen3.5:9b")
+ handed_on: list[Any] = []
+ with pytest.raises(LocalContextError) as err:
+ async for delta in brain.complete(_req(system="s" * 80_000)):
+ handed_on.append(delta)
+ # Refused before the first token reached the caller.
+ assert handed_on == []
+ assert err.value.truncated is True
+ assert "cut this request short" in str(err.value)
+
+
+async def test_an_unanswered_check_leaves_the_plan_standing(routed) -> None:
+ routed.ps = None
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ assert brain.context_window == 16_384
+
+
+async def test_a_server_refusal_names_the_setting(routed, monkeypatch) -> None:
+ from jarvis.brain.local_context import LocalContextError
+ from jarvis.plugins.brain import ollama as plugin
+
+ async def refusing(client: Any, model: str, req: Any, **kwargs: Any):
+ raise RuntimeError("Error code: 400 - the request exceeds the available context size")
+ yield # pragma: no cover
+
+ monkeypatch.setattr(plugin, "stream_complete", refusing)
+ with pytest.raises(LocalContextError) as err:
+ await _run(OllamaBrain(model="qwen3.5:9b"), _req())
+ assert "Local Models" in str(err.value)
async def test_discovered_model_is_tuned_like_a_pinned_one(monkeypatch, wired, fake_tags) -> None:
@@ -580,3 +788,107 @@ async def test_discovered_model_is_tuned_like_a_pinned_one(monkeypatch, wired, f
await _run(brain, _req())
model, _ = _FakeStreamer.calls[0]
assert model == "qwen3.5-4b-jarvis-deadbeef"
+
+
+async def test_the_smaller_window_is_enforced_on_every_later_turn(routed) -> None:
+ """The first turn learned that the server runs 4,096. A later, larger
+ request must be held to that too, not only the turn that asked."""
+ from jarvis.brain.local_context import LocalContextError
+
+ _FakeProfiles.fail = True
+ routed.ps = {"models": [{"name": "qwen3.5:9b", "context_length": 4_096}]}
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ assert len(_FakeStreamer.calls) == 1
+ with pytest.raises(LocalContextError) as err:
+ await _run(brain, _req(system="s" * 80_000))
+ # Refused before sending this time: the window is already known.
+ assert len(_FakeStreamer.calls) == 1
+ assert "was not sent" in str(err.value)
+ assert brain.context_window == 4_096
+
+
+async def test_a_model_that_declares_a_larger_window_is_not_shrunk(routed) -> None:
+ """A Modelfile that sets num_ctx 65536 works today. The automatic window
+ must not put a smaller one in front of it."""
+ routed.show = {
+ "capabilities": ["completion", "tools"],
+ "model_info": {"general.architecture": "qwen3", "qwen3.context_length": 262_144},
+ "parameters": "temperature 0.6\nnum_ctx 65536\nstop <|im_end|>",
+ }
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ assert _FakeProfiles.ensured == []
+ assert _FakeStreamer.calls[0][0] == "qwen3.5:9b"
+ assert brain.context_window == 65_536
+
+
+async def test_a_model_that_declares_a_tiny_window_still_gets_the_floor(routed) -> None:
+ routed.show = {
+ "capabilities": ["completion", "tools"],
+ "model_info": {"general.architecture": "qwen3", "qwen3.context_length": 262_144},
+ "parameters": "num_ctx 2048",
+ }
+ await _run(OllamaBrain(model="qwen3.5:9b"), _req())
+ assert [o.num_ctx for _, _, o in _FakeProfiles.ensured] == [16_384]
+
+
+async def test_a_server_still_starting_does_not_fix_the_size_for_good(routed, monkeypatch) -> None:
+ from jarvis.brain import ollama_pull
+
+ monkeypatch.setattr(ollama_pull, "accelerator_gb", lambda: (24.0, "nvidia"))
+ routed.tags = None # /api/tags does not answer yet
+ brain = OllamaBrain(model="qwen3.5:9b")
+ assert await brain._automatic_context("qwen3.5:9b") == 16_384
+ routed.tags = {"models": [{"name": "qwen3.5:9b", "size": 6 * 1024**3}]}
+ assert await brain._automatic_context("qwen3.5:9b") == 32_768
+
+
+async def test_a_remote_server_is_not_sized_from_this_machine(routed, monkeypatch) -> None:
+ from jarvis.brain import ollama_pull
+
+ monkeypatch.setattr(ollama_pull, "accelerator_gb", lambda: (24.0, "nvidia"))
+ _override("http://otherbox:11434", monkeypatch)
+ brain = OllamaBrain(model="qwen3.5:9b")
+ # 24 GB here says nothing about the machine that holds the weights.
+ assert await brain._automatic_context("qwen3.5:9b") == 16_384
+
+
+async def test_a_refused_profile_is_not_requested_again_on_every_turn(routed, monkeypatch) -> None:
+ from jarvis.brain import ollama_profiles
+
+ attempts: list[str] = []
+
+ async def refusing(root: str, base: str, opts: Any, **kwargs: Any) -> str:
+ attempts.append(base)
+ raise RuntimeError("server said no")
+
+ monkeypatch.setattr(ollama_profiles, "ensure_profile", refusing)
+ brain = OllamaBrain(model="qwen3.5:9b")
+ await _run(brain, _req())
+ await _run(brain, _req())
+ assert attempts == ["qwen3.5:9b"]
+ assert [m for m, _ in _FakeStreamer.calls] == ["qwen3.5:9b", "qwen3.5:9b"]
+
+
+async def test_the_window_is_settled_before_the_first_turn_is_budgeted(routed, monkeypatch) -> None:
+ from jarvis.brain import ollama_pull
+
+ monkeypatch.setattr(ollama_pull, "accelerator_gb", lambda: (24.0, "nvidia"))
+ brain = OllamaBrain(model="qwen3.5:9b")
+ assert brain.context_window == 16_384
+ await brain.prepare_context_window()
+ assert brain.context_window == 32_768
+ assert _FakeStreamer.calls == []
+ # The next brain for this model starts from the sized window.
+ assert OllamaBrain(model="qwen3.5:9b").context_window == 32_768
+
+
+async def test_concurrent_calls_do_not_share_their_plan(routed) -> None:
+ """One brain serves several calls. What a call was prepared with is
+ returned to it, never parked on the instance for the next one to overwrite."""
+ brain = OllamaBrain(model="qwen3.5:9b")
+ first = await brain._prepare_call("qwen3.5:9b", _req())
+ brain.set_context_window(65_536)
+ second = await brain._prepare_call("qwen3.5:9b", _req())
+ assert (first.planned, second.planned) == (16_384, 65_536)