Skip to content

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

feat(local-models): the setup assistant is connected — its own chat surface, its own hands

rubenluetke10-beepcf7893d56d61
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index b99bb8a562..29706a080b 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -72,8 +72,10 @@ _PREVIEW_MAX_CHARS = 120
#: is ``AgentChatSurface`` in ``src/lib/agentChatApi.ts`` and the Pydantic one
#: ``CreateSessionBody.surface`` in ``jarvis/ui/web/agent_chat_routes.py`` —
#: ``tests/unit/agent_chat/test_agent_chat_surface_parity.py`` keeps the three
-#: in step (AP-4).
-SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent")
+#: in step (AP-4). ``"local-models"`` is the Local models section's setup
+#: assistant: one session per install, its own hands, never in either chat's
+#: session list.
+SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models")
DEFAULT_SURFACE: Final[str] = "agent"
diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.py
index 7e7fd711a7..dbc6568379 100644
--- a/jarvis/agent_chat/surface_kits.py
+++ b/jarvis/agent_chat/surface_kits.py
@@ -96,6 +96,39 @@ def _chat_workspace() -> Path:
return chat_workspace_dir()
+def _local_models_tools(cfg: Any, _brain: Any) -> dict[str, Tool]:
+ """The setup assistant's hands — the ``lm_*`` tools (lazy, AP-26)."""
+ from jarvis.local_models.assistant_tools import build_tools
+ from jarvis.local_models.health_monitor import server_root
+
+ return build_tools(cfg, root=server_root(cfg))
+
+
+async def _local_models_extra(cfg: Any, _brain: Any) -> str:
+ """What the assistant can already see: machine, inventory, roles, catalogue.
+
+ Read per turn rather than once per session, because the whole point of the
+ assistant is that things change while it works — a model finishes pulling,
+ the server comes up, a role gets filled.
+ """
+ from jarvis.local_models.assistant_prompt import build_system_extra
+ from jarvis.local_models.health_monitor import server_root
+
+ return await build_system_extra(cfg, root=server_root(cfg))
+
+
+def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:
+ """Its own hands and nothing else.
+
+ The assistant sets up local models; the wiki, the calendar and the folder
+ tools are foreign schemas that only make the request bigger and give a
+ provider more to refuse.
+ """
+ from jarvis.local_models.assistant_tools import TOOL_PREFIX
+
+ return {name: tool for name, tool in tools.items() if name.startswith(TOOL_PREFIX)}
+
+
# ── the table ─────────────────────────────────────────────────────────────
_KITS: Final[dict[str, SurfaceKit]] = {
@@ -118,6 +151,26 @@ _KITS: Final[dict[str, SurfaceKit]] = {
# of these chats ever see. It has to be a small one.
workspace_dir=_chat_workspace,
),
+ # The Local models section's setup assistant. It runs on Jarvis' own
+ # harness over the Agents tier (an API key, never a vendor CLI and never
+ # the voice brain) so that a person whose voice runs on Ollama still gets
+ # a capable model to set Ollama UP. Session policy — one chat per install,
+ # re-created when the tier moves — lives in
+ # ``jarvis/local_models/assistant_session.py``.
+ "local-models": SurfaceKit(
+ surface="local-models",
+ brain_runner=True,
+ cli_seats=False,
+ ladder=_JARVIS_LADDER,
+ uses_stance=True,
+ tools=_local_models_tools,
+ system_extra=_local_models_extra,
+ tool_origin="local-models-assistant",
+ tool_filter=_only_local_models,
+ # No folder: this surface never touches a checkout. Its hands talk to
+ # the local server and the config, and the composer shows no chip.
+ workspace_dir=_chat_workspace,
+ ),
}
diff --git a/jarvis/local_models/assistant_prompt.py b/jarvis/local_models/assistant_prompt.py
new file mode 100644
index 0000000000..1c001b9d2d
--- /dev/null
+++ b/jarvis/local_models/assistant_prompt.py
@@ -0,0 +1,309 @@
+"""The setup assistant's briefing: a per-turn system-prompt addendum.
+
+Rendered fresh for every turn of the ``local-models`` chat surface and
+handed to the brain through ``TurnOverride.system_extra`` — the machine's
+facts, what is installed, which role runs what (and under which config
+key), the curated shortlist with fit verdicts and proven / new labels, the
+benchmark table from the cache, the hard rules, and the output contract the
+panel parses (a fenced ``jarvis-proposal`` JSON block). Budget: about 2.5k
+tokens, so lists are capped rather than complete.
+
+The three canned openers are what the panel's buttons send as the user
+turn (D6): ``SETUP_OPENER``, ``DIAGNOSE_OPENER``, ``TEST_OPENER``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import datetime as _dt
+import logging
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "DIAGNOSE_OPENER",
+ "PROPOSAL_FENCE",
+ "SETUP_OPENER",
+ "TEST_OPENER",
+ "build_system_extra",
+]
+
+PROPOSAL_FENCE: Final[str] = "jarvis-proposal"
+
+#: Rough budget guard: characters, not tokens (≈ 4 chars per token).
+_MAX_CHARS = 10_000
+_MAX_INVENTORY_ROWS = 30
+_MAX_BENCHMARK_ROWS = 40
+
+SETUP_OPENER: Final[str] = (
+ "Help me set up local models on this machine. Check the hardware and the server, then "
+ "propose ONE complete setup for the five roles (chat, voice, tools_screen, deep, "
+ "embedding) using the best proven models that fit, as a jarvis-proposal block. "
+ "Do not execute anything until I confirm."
+)
+
+DIAGNOSE_OPENER: Final[str] = (
+ "Something is not working with my local models. Find out what is broken (server, "
+ "roles, downloads, voice server), name the cause in one or two sentences, and propose "
+ "the smallest fix as a jarvis-proposal block. Do not execute anything until I confirm."
+)
+
+TEST_OPENER: Final[str] = (
+ "Run the end-to-end test of my local setup (lm_test_plan) and report the result as a "
+ "short table: one line per role with ok / error and the reason. Propose a fix as a "
+ "jarvis-proposal block only for roles that failed."
+)
+
+_RULES: Final[str] = """\
+HARD RULES
+- Never delete a model; there is no tool for it and you must not suggest one.
+- Never change the active brain provider yourself. When Ollama should answer the voice and \
+the chat, put a `brain_switch` entry in the proposal — the person clicks it.
+- Installs, downloads, role picks, option writes and voice-stack changes happen only after \
+the person confirmed the proposal; in that run, call the tools in the proposal's order.
+- Never touch BIOS, OS, driver or firewall settings; point to the OLLAMA_* guide instead.
+- Prefer models labelled `proven` whose fit is `comfortable`; a `new_little_tested` model is \
+never a default; a `stale` label means the shortlist needs a refresh — say so.
+- When a step fails, say exactly what failed (the tool's own sentence) and what to do next.
+- Answer in the person's language; keep prose short, the proposal block carries the plan.
+- Written delivery: this is a chat panel, not a voice reply — tables and lists are fine."""
+
+_CONTRACT: Final[str] = """\
+OUTPUT CONTRACT
+When you propose or revise a setup, end the message with exactly one fenced block:
+```jarvis-proposal
+{"version": 1,
+ "steps": [
+ {"id": "s1", "kind": "install_ollama", "label": "Install Ollama"},
+ {"id": "s2", "kind": "pull", "model": "qwen3.5:4b", "size_gb": 3.4, "fit": "comfortable",
+ "proven": true, "label": "Download Qwen 3.5 4B"},
+ {"id": "s3", "kind": "set_role", "role": "chat", "model": "qwen3.5:4b", "label": "..."},
+ {"id": "s4", "kind": "set_options", "model": "qwen3.5:4b", "options": {"num_ctx": 16384},
+ "label": "..."},
+ {"id": "s5", "kind": "apply_voice_stack", "model": "qwen3.5:4b", "options":
+ {"voice_model": "..."}, "label": "..."},
+ {"id": "s6", "kind": "test", "label": "Test every role"}
+ ],
+ "brain_switch": {"provider": "ollama", "why": "one sentence"},
+ "notes": ["one sentence per caveat"]}
+```
+`kind` is one of install_ollama | pull | set_role | set_options | apply_voice_stack | test. \
+`brain_switch` and `notes` are optional; `steps` may be empty when nothing needs doing."""
+
+
+# ── data gathering ────────────────────────────────────────────────────────
+
+
+def _provider(cfg: Any, name: str) -> Any:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ return providers.get(name) if isinstance(providers, dict) else None
+
+
+async def _machine(cfg: Any) -> dict[str, Any]:
+ import platform
+
+ from jarvis.brain.ollama_pull import accelerator_gb, total_memory_gb
+
+ (accel, source), ram = await asyncio.gather(
+ asyncio.to_thread(accelerator_gb), asyncio.to_thread(total_memory_gb)
+ )
+ brain = getattr(cfg, "brain", None)
+ worker = getattr(brain, "worker", None)
+ return {
+ "os": f"{platform.system()} {platform.release()} ({platform.machine()})",
+ "ram_gb": ram,
+ "accelerator_gb": round(accel, 1),
+ "accelerator_source": source,
+ "active_brain": str(getattr(brain, "primary", "") or ""),
+ "assistant_tier": (
+ f"{getattr(worker, 'provider', '') or ''} / {getattr(worker, 'model', '') or ''}"
+ ).strip(" /"),
+ }
+
+
+async def _inventory(root: str, transport: Any) -> tuple[list[Any], str | None]:
+ from jarvis.brain import ollama_inventory as inventory
+
+ try:
+ return await inventory.list_models(root, transport=transport), None
+ except inventory.OllamaServerError as exc:
+ return [], str(exc)
+
+
+def _roles(cfg: Any, installed_names: list[str]) -> list[dict[str, Any]]:
+ from jarvis.brain.ollama_inventory import same_model
+ from jarvis.brain.ollama_roles import ROLES, current_pick
+
+ rows: list[dict[str, Any]] = []
+ for spec in ROLES:
+ if not spec.writable:
+ continue
+ current, note = current_pick(cfg, spec.id)
+ rows.append(
+ {
+ "role": spec.id,
+ "config_key": spec.config_key,
+ "required": list(spec.required),
+ "current": current,
+ "installed": bool(current) and any(same_model(n, current) for n in installed_names),
+ "note": note,
+ }
+ )
+ return rows
+
+
+def _curated(
+ machine: dict[str, Any], installed_names: list[str], table: Any, today: _dt.date
+) -> list[dict[str, Any]]:
+ from jarvis.brain.ollama_inventory import same_model
+ from jarvis.brain.ollama_pull import RECOMMENDED_MODELS, fit_verdict
+ from jarvis.local_models.benchmarks import label_for
+
+ rows: list[dict[str, Any]] = []
+ for entry in RECOMMENDED_MODELS:
+ verdict, _note = fit_verdict(
+ entry.size_gb, machine.get("ram_gb"), float(machine.get("accelerator_gb") or 0.0)
+ )
+ rows.append(
+ {
+ "id": entry.id,
+ "role": entry.role,
+ "size_gb": entry.size_gb,
+ "tools": entry.tools,
+ "vision": entry.vision,
+ "fit": verdict,
+ "installed": any(same_model(n, entry.id) for n in installed_names),
+ "label": label_for(entry, table, today),
+ "purpose": entry.purpose,
+ }
+ )
+ return rows
+
+
+# ── rendering ─────────────────────────────────────────────────────────────
+
+
+def _yn(value: bool) -> str:
+ return "yes" if value else "no"
+
+
+def _render_machine(machine: dict[str, Any], server: dict[str, Any], root: str) -> str:
+ ram = machine.get("ram_gb")
+ lines = [
+ "MACHINE",
+ f"- OS: {machine['os']}",
+ f"- RAM: {ram:g} GB" if ram is not None else "- RAM: unknown",
+ f"- Graphics memory usable for models: {machine['accelerator_gb']:g} GB "
+ f"(source: {machine['accelerator_source']})",
+ f"- Ollama server: {root} — "
+ + (
+ f"running, version {server.get('version')}"
+ if server.get("ok")
+ else f"not answering ({server.get('detail')})"
+ ),
+ f"- Active brain provider: {machine['active_brain'] or 'unset'} "
+ "(only the person may change it)",
+ "- You run on the Tool Model (billed through its key): "
+ f"{machine['assistant_tier'] or 'unknown'}",
+ ]
+ return "\n".join(lines)
+
+
+def _render_inventory(models: list[Any], error: str | None) -> str:
+ if error:
+ return f"INSTALLED MODELS\n- unavailable: {error}"
+ if not models:
+ return "INSTALLED MODELS\n- none"
+ lines = ["INSTALLED MODELS (name · size · capabilities · context)"]
+ for m in models[:_MAX_INVENTORY_ROWS]:
+ caps = ",".join(m.capabilities) or "unknown"
+ ctx = f"{m.context_length}" if m.context_length else "?"
+ lines.append(f"- {m.name} · {m.size_bytes / (1024**3):.1f} GB · {caps} · ctx {ctx}")
+ if len(models) > _MAX_INVENTORY_ROWS:
+ lines.append(f"- … and {len(models) - _MAX_INVENTORY_ROWS} more (lm_inventory)")
+ return "\n".join(lines)
+
+
+def _render_roles(rows: list[dict[str, Any]], voice_command: str) -> str:
+ lines = ["ROLES (role · needs · current pick · installed · config key)"]
+ for r in rows:
+ pick = r["current"] or "not set"
+ extra = f" — {r['note']}" if r["note"] else ""
+ lines.append(
+ f"- {r['role']} · {'+'.join(r['required'])} · {pick} · "
+ f"{_yn(r['installed']) if r['current'] else '-'} · {r['config_key']}{extra}"
+ )
+ managed = "--model_name" in voice_command
+ lines.append(
+ "- managed voice server: "
+ + ("installed (apply_voice_stack may change its models)" if managed else "not installed")
+ )
+ return "\n".join(lines)
+
+
+def _render_curated(rows: list[dict[str, Any]], reviewed_on: _dt.date) -> str:
+ lines = [
+ f"CURATED SHORTLIST (reviewed {reviewed_on.isoformat()}; id · role · GB · fit · "
+ "label · installed)"
+ ]
+ for r in rows:
+ caps = "tools" if r["tools"] else "-"
+ if r["vision"]:
+ caps += "+vision"
+ lines.append(
+ f"- {r['id']} · {r['role']} · {r['size_gb']:g} · {r['fit']} · {r['label']} · "
+ f"{_yn(r['installed'])} · {caps} — {r['purpose']}"
+ )
+ return "\n".join(lines)
+
+
+def _render_benchmarks(table: Any) -> str:
+ if table is None:
+ return "BENCHMARKS\n- no cached table (lm_benchmarks refresh=true inside a guided run)"
+ lines = [f"BENCHMARKS (source: {table.source}; fetched {table.fetched_at or 'n/a'})"]
+ if table.note:
+ lines.append(f"- note: {table.note}")
+ for row in table.rows[:_MAX_BENCHMARK_ROWS]:
+ lines.append(f"- {row.family} · {row.source} · {row.metric} = {row.value:g}")
+ for family, facts in list(table.library.items())[:_MAX_BENCHMARK_ROWS]:
+ upd = f"{facts.updated_days} d ago" if facts.updated_days is not None else "?"
+ lines.append(f"- {family} · library · pulls {facts.pulls:,} · updated {upd}")
+ if len(lines) == 1:
+ lines.append("- no rows")
+ return "\n".join(lines)
+
+
+async def build_system_extra(cfg: Any, *, root: str, transport: Any = None) -> str:
+ """The addendum for one turn of the local-models assistant (≈ 2.5k tokens)."""
+ from jarvis.brain.ollama_pull import CURATED_REVIEWED_ON
+ from jarvis.brain.ollama_runtime import probe_host
+ from jarvis.local_models.benchmarks import load_cached
+
+ machine, server, (models, inv_error) = await asyncio.gather(
+ _machine(cfg), probe_host(root, transport=transport), _inventory(root, transport)
+ )
+ installed_names = [m.name for m in models]
+ table = load_cached()
+ today = _dt.datetime.now(_dt.UTC).date()
+ voice_command = str(getattr(_provider(cfg, "local-realtime"), "launch_command", "") or "")
+
+ sections = [
+ "LOCAL MODELS SETUP ASSISTANT\n"
+ "You help this person set up, test and repair local models (Ollama) on THIS machine, "
+ "inside the Local models section. Read with the lm_* tools before you propose; "
+ "act only through them, and only after confirmation.",
+ _render_machine(machine, server, root),
+ _render_inventory(models, inv_error),
+ _render_roles(_roles(cfg, installed_names), voice_command),
+ _render_curated(_curated(machine, installed_names, table, today), CURATED_REVIEWED_ON),
+ _render_benchmarks(table),
+ _RULES,
+ _CONTRACT,
+ ]
+ text = "\n\n".join(sections)
+ if len(text) > _MAX_CHARS:
+ log.info("local-models prompt: %d chars, trimming the benchmark section", len(text))
+ sections[5] = "BENCHMARKS\n- table too long for the briefing; use lm_benchmarks"
+ text = "\n\n".join(sections)
+ return text
diff --git a/jarvis/local_models/assistant_session.py b/jarvis/local_models/assistant_session.py
new file mode 100644
index 0000000000..587b9ef8d4
--- /dev/null
+++ b/jarvis/local_models/assistant_session.py
@@ -0,0 +1,352 @@
+"""Session policy of the setup assistant: one chat per install, on the Agents tier.
+
+The assistant is a ``local-models`` agent-chat session. It runs on the
+Jarvis-Agents tier (``[brain.worker]`` provider / model, the fallback pair
+when the primary is unknown to the chat) — never on the voice brain, so a
+person whose voice runs on Ollama still gets a capable cloud model to set
+Ollama up. There is ONE session per install: the routes reuse the newest
+``local-models`` session and re-create it only when the worker tier moved.
+
+No usable Agents-tier credential → an honest refusal (:data:`NOT_READY`),
+never a silent fallback onto another tier.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from typing import Any, Final
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "NOT_READY",
+ "SURFACE",
+ "AgentsTier",
+ "agents_tier",
+ "ensure_session",
+ "session_state",
+]
+
+SURFACE: Final[str] = "local-models"
+NOT_READY: Final[str] = (
+ "Pick a Tool Model with an API key first (API Keys → Tool Model) — the setup "
+ "assistant runs on it, billed through that key."
+)
+#: The tier is connected but every provider in its chain drives a vendor CLI
+#: on a flat prompt (Antigravity, for one) and cannot call the assistant's
+#: tools; a fallback with an API key fixes it.
+NO_TOOLS: Final[str] = (
+ "The picked Tool Model cannot call tools here (a CLI-only provider such as "
+ "Antigravity). Pick an API provider — Gemini, OpenAI, Vertex or OpenRouter — "
+ "under API Keys → Tool Model and try again."
+)
+
+
+@dataclass(frozen=True, slots=True)
+class AgentsTier:
+ provider: str
+ model: str
+ ready: bool
+ reason: str
+
+
+def _known(provider: str) -> bool:
+ from jarvis.agent_chat.catalog import provider_row
+ from jarvis.agent_chat.runner_api import supports_api_runner
+
+ return provider_row(provider) is not None or supports_api_runner(provider)
+
+
+def _tool_capable(provider: str) -> bool:
+ """Whether ``provider``'s brain plugin can call tools inside the brain loop.
+
+ Read from the plugin itself (``can_call_tools`` / ``supports_tools``) via
+ the ``jarvis.brain`` entry point, never from the name (AP-21). A plugin
+ that cannot be loaded here answers True: the turn then fails honestly
+ instead of a healthy provider being skipped by a probe glitch.
+ """
+ from importlib.metadata import entry_points
+
+ try:
+ eps = [ep for ep in entry_points(group="jarvis.brain") if ep.name == provider]
+ if not eps:
+ return True
+ cls = eps[0].load()
+ try:
+ brain = cls()
+ except TypeError:
+ brain = cls(model=None)
+ probe = getattr(brain, "can_call_tools", None)
+ if callable(probe):
+ return bool(probe())
+ return bool(getattr(brain, "supports_tools", True))
+ except Exception: # noqa: BLE001 — a probe glitch must not hide a working provider
+ log.debug("agents tier: tool-capability probe for %s failed", provider, exc_info=True)
+ return True
+
+
+def _default_usable(provider: str) -> bool:
+ """A credential exists: the provider's own key (the Tool Model bills
+ through it) or the Agents-tier secret for the fallback chain."""
+ from jarvis.core.config import get_jarvis_agent_secret
+
+ try:
+ if get_jarvis_agent_secret(provider):
+ return True
+ except Exception: # noqa: BLE001 — no credential readable counts as none
+ log.debug("agents tier: credential lookup for %s failed", provider, exc_info=True)
+ try:
+ from jarvis.brain.app_control import is_credential_present
+ from jarvis.ui.web.provider_spec import get_spec
+
+ spec = get_spec(provider)
+ return spec is not None and bool(is_credential_present(spec))
+ except Exception: # noqa: BLE001 — same: unreadable is "none"
+ log.debug("agents tier: main credential lookup for %s failed", provider, exc_info=True)
+ return False
+
+
+def _tool_model_pair(cfg: Any) -> tuple[str, str] | None:
+ """The user's Tool Model pick, ``None`` when it is ``auto``.
+
+ The same reader the Tool Model tab and the IDE's prompt writer use
+ (``resolver._tool_model_selection``), so the assistant runs on exactly the
+ model the user pointed that tab at — and is billed through that key.
+ """
+ from jarvis.brain.resolver import _tool_model_selection
+
+ try:
+ provider, model = _tool_model_selection(cfg)
+ except Exception: # noqa: BLE001 — a malformed section reads as unset, logged
+ log.debug("agents tier: tool-model selection unreadable", exc_info=True)
+ return None
+ if not provider or provider == "auto":
+ return None
+ return provider, str(model or "").strip()
+
+
+def _chain(cfg: Any) -> list[tuple[str, str]]:
+ """The Tool Model first; the Agents-tier chain only as a fallback."""
+ out: list[tuple[str, str]] = []
+ pinned = _tool_model_pair(cfg)
+ if pinned is not None:
+ out.append(pinned)
+ brain = getattr(cfg, "brain", None)
+ worker = getattr(brain, "worker", None)
+ if worker is None:
+ return out
+ pairs = [
+ ("provider", "model"),
+ ("fallback_provider", "fallback_model"),
+ ("fallback_provider_2", "fallback_model_2"),
+ ]
+ for p_key, m_key in pairs:
+ provider = str(getattr(worker, p_key, "") or "").strip()
+ model = str(getattr(worker, m_key, "") or "").strip()
+ if provider and (provider, model) not in out:
+ out.append((provider, model))
+ return out
+
+
+def chain_candidates(
+ cfg: Any,
+ *,
+ usable: Callable[[str], bool] | None = None,
+ tool_capable: Callable[[str], bool] | None = None,
+) -> list[tuple[str, str]]:
+ """The worker pairs worth a live probe: known, tool-capable, credentialed."""
+ can_tools = tool_capable or _tool_capable
+ probe = usable or _default_usable
+ out: list[tuple[str, str]] = []
+ for provider, model in _chain(cfg):
+ if not _known(provider) or not can_tools(provider):
+ continue
+ try:
+ if probe(provider):
+ out.append((provider, model))
+ except Exception: # noqa: BLE001 — a failing probe is "not ready", with the reason logged
+ log.info("agents tier: usability probe for %s failed", provider, exc_info=True)
+ return out
+
+
+#: (provider, model) -> (ok, reason, monotonic) — one real call per pair per
+#: ten minutes; a run and the session read share it.
+_LIVE_CACHE: dict[tuple[str, str], tuple[bool, str, float]] = {}
+_LIVE_TTL_S: Final[float] = 600.0
+
+
+def _reset_for_tests() -> None:
+ _LIVE_CACHE.clear()
+
+
+async def probe_live(
+ cfg: Any,
+ pairs: list[tuple[str, str]],
+ *,
+ timeout_s: float = 20.0,
+ tester: Callable[..., Awaitable[Any]] | None = None,
+) -> dict[tuple[str, str], tuple[bool, str]]:
+ """One real one-token generation per pair, classified like the API-keys
+ page's "Test" (``provider_test``): a key that authenticates but is refused
+ for quota or billing is NOT usable here, and the sentence says so."""
+ import time
+
+ from jarvis.brain import provider_test
+ from jarvis.ui.web.provider_spec import get_spec
+
+ out: dict[tuple[str, str], tuple[bool, str]] = {}
+ now = time.monotonic()
+ for provider, model in pairs:
+ hit = _LIVE_CACHE.get((provider, model))
+ if hit is not None and now - hit[2] < _LIVE_TTL_S:
+ out[(provider, model)] = (hit[0], hit[1])
+ continue
+ spec = get_spec(provider)
+ if spec is None:
+ out[(provider, model)] = (False, f"{provider} is not a provider this build knows.")
+ continue
+ run = tester or provider_test.run_provider_test
+ try:
+ result = await run(spec, cfg, model=model or None, timeout_s=timeout_s)
+ ok = result.status == provider_test.OK
+ reason = "" if ok else _plain_reason(provider, model, result)
+ except Exception as exc: # noqa: BLE001 — a probe crash is "not usable", logged
+ log.warning("agents tier: live probe of %s/%s crashed: %s", provider, model, exc)
+ ok, reason = False, f"{provider} ({model}): probe failed — {exc}"
+ _LIVE_CACHE[(provider, model)] = (ok, reason, time.monotonic())
+ out[(provider, model)] = (ok, reason)
+ return out
+
+
+_PLAIN_BY_STATUS: Final[dict[str, str]] = {
+ "no_credits": "the account has no credit or quota left for this model",
+ "rate_limited": "the provider is rate-limiting this key right now",
+ "bad_key": "the key was refused",
+ "model_unavailable": "the provider no longer offers this model",
+ "unreachable": "the provider could not be reached",
+ "not_configured": "no key is stored for it",
+}
+
+
+def _plain_reason(provider: str, model: str, result: Any) -> str:
+ """One readable sentence, never a dumped error body.
+
+ The status vocabulary is the API-keys page's; the provider's own text is
+ kept only when it is short and free of JSON braces (a 404 body is not
+ something a person should have to read in a status line).
+ """
+ status = str(getattr(result, "status", "") or "error")
+ head = f"{provider} ({model or 'default model'}): "
+ plain = _PLAIN_BY_STATUS.get(status)
+ detail = str(getattr(result, "detail", "") or "").strip()
+ if plain:
+ return head + plain + "."
+ if detail and "{" not in detail and len(detail) <= 140:
+ return head + detail
+ return head + status.replace("_", " ") + "."
+
+
+def agents_tier(
+ cfg: Any,
+ *,
+ usable: Callable[[str], bool] | None = None,
+ tool_capable: Callable[[str], bool] | None = None,
+ live: dict[tuple[str, str], tuple[bool, str]] | None = None,
+) -> AgentsTier:
+ """The pair the assistant runs on and whether it can run right now.
+
+ Walks the worker chain (primary, fallback, fallback 2) and takes the first
+ provider that is known, can call tools, has a credential and — when a
+ ``live`` map from :func:`probe_live` is given — answered a real call.
+ ``usable`` is the credential / login probe (the routes pass the
+ provider-agnostic worker check the API-keys page uses; the default reads
+ the Agents-tier secret); ``tool_capable`` defaults to asking the plugin.
+ """
+ chain = _chain(cfg)
+ if not chain:
+ return AgentsTier("", "", False, NOT_READY)
+ known = [(p, m) for p, m in chain if _known(p)]
+ if not known:
+ return AgentsTier(chain[0][0], "", False, NOT_READY)
+ can_tools = tool_capable or _tool_capable
+ handy = [(p, m) for p, m in known if can_tools(p)]
+ if not handy:
+ return AgentsTier(known[0][0], known[0][1], False, NO_TOOLS)
+ probe = usable or _default_usable
+ last_reason = NOT_READY
+ for provider, model in handy:
+ try:
+ ok = bool(probe(provider))
+ except Exception: # noqa: BLE001 — a failing probe is "not ready", with the reason logged
+ log.info("agents tier: usability probe for %s failed", provider, exc_info=True)
+ ok = False
+ if not ok:
+ continue
+ if live is not None and (provider, model) in live:
+ alive, reason = live[(provider, model)]
+ if not alive:
+ last_reason = reason or NOT_READY
+ continue
+ return AgentsTier(provider, model, True, "")
+ return AgentsTier(handy[0][0], handy[0][1], False, last_reason)
+
+
+def _current(svc: Any) -> Any | None:
+ sessions = svc.store.list_sessions(limit=1, surface=SURFACE)
+ return sessions[0] if sessions else None
+
+
+def session_state(
+ svc: Any,
+ cfg: Any,
+ *,
+ usable: Callable[[str], bool] | None = None,
+ live: dict[tuple[str, str], tuple[bool, str]] | None = None,
+) -> dict:
+ """``GET /session``: the session id (or null), the pair, readiness, reason."""
+ tier = agents_tier(cfg, usable=usable, live=live)
+ current = _current(svc)
+ matches = (
+ current is not None
+ and current.provider == tier.provider
+ and (not tier.model or current.model == tier.model)
+ )
+ return {
+ "session_id": current.session_id if matches and current is not None else None,
+ "surface": SURFACE,
+ "provider": tier.provider,
+ "model": tier.model,
+ "ready": tier.ready,
+ "reason": tier.reason,
+ }
+
+
+def ensure_session(
+ svc: Any,
+ cfg: Any,
+ *,
+ usable: Callable[[str], bool] | None = None,
+ live: dict[tuple[str, str], tuple[bool, str]] | None = None,
+) -> Any:
+ """The one ``local-models`` session, created or re-created for the current pair.
+
+ Raises ``PermissionError(reason)`` when the Agents tier cannot run.
+ """
+ tier = agents_tier(cfg, usable=usable, live=live)
+ if not tier.ready:
+ raise PermissionError(tier.reason or NOT_READY)
+ current = _current(svc)
+ if (
+ current is not None
+ and current.provider == tier.provider
+ and (not tier.model or current.model == tier.model)
+ ):
+ return current
+ return svc.create_session(
+ provider=tier.provider,
+ model=tier.model,
+ title="Local models setup",
+ surface=SURFACE,
+ )
diff --git a/jarvis/local_models/assistant_test.py b/jarvis/local_models/assistant_test.py
new file mode 100644
index 0000000000..c43ffbf238
--- /dev/null
+++ b/jarvis/local_models/assistant_test.py
@@ -0,0 +1,399 @@
+"""The end-to-end test of a local setup: does every configured role actually answer?
+
+A role that is *configured* proves nothing — the model may have been deleted,
+the server may be down, a "tools + vision" pick may declare neither. So this
+runner asks the server (``probe_host``), then makes one REAL call per
+configured role: a 1-token generation for the chat / deep / tools_screen
+roles (through :func:`jarvis.brain.provider_test.run_provider_test`, so the
+status vocabulary is the one the API-keys cards already speak), a
+capability assertion on top for ``tools_screen``, an embedding round trip
+for the embedding role, and — only when the managed voice server is
+configured — the voice smoke probe. The report is persisted to
+``DATA_DIR/state/local_models_health.json`` so the section badge and the
+health monitor read the same file.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import datetime as _dt
+import json
+import logging
+import os
+import uuid
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "HEALTH_FILE_NAME",
+ "NOT_SET",
+ "OVERALL_STATUSES",
+ "RoleCheck",
+ "TestReport",
+ "health_path",
+ "load_last_report",
+ "run_setup_test",
+]
+
+#: Status of a role nobody configured — it is not an error, there is simply
+#: nothing to test. Alongside :data:`PROVIDER_TEST_STATUSES` in ``status``.
+NOT_SET = "not_set"
+
+#: ``overall`` vocabulary — the same the health monitor (D7) writes.
+OVERALL_STATUSES: tuple[str, ...] = ("ok", "error", "needs_setup", "unknown")
+
+HEALTH_FILE_NAME = "local_models_health.json"
+
+#: The generation-tested roles and the role whose pick embeds.
+_GENERATION_ROLES: tuple[str, ...] = ("chat", "tools_screen", "deep")
+_EMBEDDING_ROLE = "embedding"
+_VOICE_ROLE = "voice"
+
+_DEFAULT_TIMEOUT_S = 90.0
+_VOICE_DEFAULT_URL = "http://127.0.0.1:8765"
+
+
+@dataclass(frozen=True, slots=True)
+class _OllamaSpec:
+ """The three fields :func:`run_provider_test` reads from a provider spec."""
+
+ id: str = "ollama"
+ tier: str = "brain"
+ auth_mode: str = "none"
+
+
+@dataclass(frozen=True, slots=True)
+class RoleCheck:
+ """One role's verdict."""
+
+ model: str
+ #: :data:`PROVIDER_TEST_STATUSES` value or :data:`NOT_SET`.
+ status: str
+ latency_ms: float
+ detail: str
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "model": self.model,
+ "status": self.status,
+ "latency_ms": round(self.latency_ms, 1),
+ "detail": self.detail,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class TestReport:
+ """The whole run, as the panel's table and the health file show it."""
+
+ #: Not a pytest class, whatever the name suggests.
+ __test__ = False
+
+ checked_at: str
+ server: dict[str, Any]
+ roles: dict[str, RoleCheck]
+ #: The voice smoke probe's payload, ``None`` when no managed voice server exists.
+ voice: dict[str, Any] | None
+ #: One of :data:`OVERALL_STATUSES`.
+ overall: str
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "checked_at": self.checked_at,
+ "server": dict(self.server),
+ "roles": {role: check.to_payload() for role, check in self.roles.items()},
+ "voice": dict(self.voice) if self.voice is not None else None,
+ "overall": self.overall,
+ # The badge keys the health monitor writes as well (D7), so one
+ # reader serves both writers.
+ "status": self.overall,
+ "reason": self.reason(),
+ }
+
+ def reason(self) -> str:
+ """One sentence naming the first failure, or ``""`` when all is well."""
+ if not self.server.get("ok"):
+ return str(self.server.get("detail") or "Ollama did not answer.")
+ for role, check in self.roles.items():
+ if check.status not in ("ok", NOT_SET):
+ return f"{role}: {check.detail or check.status}"
+ if self.voice is not None and not self.voice.get("ok", False):
+ return f"voice: {self.voice.get('detail') or 'the voice probe failed'}"
+ return ""
+
+
+def health_path() -> Path:
+ """``DATA_DIR/state/local_models_health.json`` — resolved at call time."""
+ from jarvis.core import config as cfg_mod # lazy: DATA_DIR is monkeypatched by tests
+
+ return Path(cfg_mod.DATA_DIR) / "state" / HEALTH_FILE_NAME
+
+
+def _atomic_write_json(path: Path, payload: dict[str, Any]) -> bool:
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ os.replace(temporary, path)
+ return True
+ except OSError:
+ log.warning("local-models: health file %s not written", path, exc_info=True)
+ return False
+ finally:
+ try:
+ temporary.unlink(missing_ok=True)
+ except OSError:
+ log.debug("local-models: temporary health file cleanup failed", exc_info=True)
+
+
+def load_last_report() -> dict[str, Any] | None:
+ """The persisted payload of the last run, or ``None`` when none / unreadable."""
+ path = health_path()
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return None
+ except (OSError, ValueError):
+ log.info("local-models: health file %s unreadable", path, exc_info=True)
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+# ── Reading the config ────────────────────────────────────────────────────
+
+
+def _voice_launch_command(cfg: Any) -> str:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ voice = providers.get("local-realtime") if isinstance(providers, dict) else None
+ return str(getattr(voice, "launch_command", "") or "")
+
+
+def _voice_base_url(cfg: Any) -> str:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ voice = providers.get("local-realtime") if isinstance(providers, dict) else None
+ return str(getattr(voice, "base_url", "") or "") or _VOICE_DEFAULT_URL
+
+
+def _server_root(cfg: Any) -> str:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ ollama = providers.get("ollama") if isinstance(providers, dict) else None
+ override = str(getattr(ollama, "base_url", "") or "")
+ if override:
+ from jarvis.plugins.brain.ollama import normalize_server_root
+
+ return normalize_server_root(override)
+ from jarvis.brain.ollama_pull import server_root
+
+ return server_root()
+
+
+# ── The checks ────────────────────────────────────────────────────────────
+
+
+async def _generation_check(
+ cfg: Any,
+ model: str,
+ *,
+ timeout_s: float,
+ brain_probe: Callable[[str, str], Awaitable[Any]] | None,
+) -> RoleCheck:
+ from jarvis.brain import provider_test
+
+ result = await provider_test.run_provider_test(
+ _OllamaSpec(), cfg, model=model, timeout_s=timeout_s, brain_probe=brain_probe
+ )
+ return RoleCheck(
+ model=model,
+ status=result.status,
+ latency_ms=float(result.latency_ms),
+ detail=result.detail or ("Answered." if result.status == "ok" else ""),
+ )
+
+
+async def _capability_check(root: str, check: RoleCheck, *, transport: Any) -> RoleCheck:
+ """``tools_screen`` must DECLARE tools + vision, not only answer a prompt."""
+ from jarvis.brain import ollama_inventory as inventory
+ from jarvis.brain.provider_test import ERROR, MODEL_UNAVAILABLE
+
+ if check.status != "ok":
+ return check
+ try:
+ info = await inventory.get_model(root, check.model, transport=transport)
+ except inventory.OllamaModelNotFound as exc:
+ return RoleCheck(check.model, MODEL_UNAVAILABLE, check.latency_ms, str(exc))
+ except inventory.OllamaServerError as exc:
+ return RoleCheck(check.model, ERROR, check.latency_ms, str(exc))
+ missing = [c for c in ("tools", "vision") if c not in info.capabilities]
+ if missing:
+ return RoleCheck(
+ check.model,
+ ERROR,
+ check.latency_ms,
+ f"{check.model} answers, but does not declare {' + '.join(missing)} — "
+ "it cannot read the screen or call tools for Jarvis.",
+ )
+ return RoleCheck(check.model, "ok", check.latency_ms, "Answered; declares tools + vision.")
+
+
+async def _embedding_check(root: str, model: str, *, transport: Any) -> RoleCheck:
+ import time
+
+ from jarvis.brain import ollama_inventory as inventory
+ from jarvis.brain.provider_test import ERROR, MODEL_UNAVAILABLE, UNREACHABLE
+
+ started = time.perf_counter()
+ try:
+ dim = await inventory.embed_probe(root, model, transport=transport)
+ except inventory.OllamaModelNotFound as exc:
+ return RoleCheck(model, MODEL_UNAVAILABLE, _ms(started), str(exc))
+ except inventory.OllamaServerError as exc:
+ text = str(exc)
+ status = UNREACHABLE if "No Ollama" in text or "unreachable" in text.lower() else ERROR
+ return RoleCheck(model, status, _ms(started), text)
+ if dim <= 0:
+ return RoleCheck(model, ERROR, _ms(started), f"{model} returned no embedding vector.")
+ return RoleCheck(model, "ok", _ms(started), f"Embeds ({dim} dimensions).")
+
+
+async def _voice_check(
+ cfg: Any,
+ *,
+ timeout_s: float,
+ voice_probe: Callable[[str], Awaitable[dict[str, Any]]] | None,
+) -> dict[str, Any] | None:
+ """The voice smoke probe — only for the Jarvis-managed server (``--model_name``)."""
+ command = _voice_launch_command(cfg)
+ if "--model_name" not in command:
+ return None
+ base_url = _voice_base_url(cfg)
+ try:
+ if voice_probe is not None:
+ payload = await asyncio.wait_for(voice_probe(base_url), timeout=timeout_s)
+ else:
+ from jarvis.realtime.local_server.smoke import probe_voice_roundtrip
+
+ payload = await probe_voice_roundtrip(base_url, timeout_s=timeout_s)
+ except TimeoutError:
+ return {"ok": False, "detail": f"The voice probe timed out after {timeout_s:.0f} s."}
+ except Exception as exc: # noqa: BLE001 — the report names the failure, never raises
+ log.info("local-models: voice probe failed", exc_info=True)
+ return {"ok": False, "detail": f"{type(exc).__name__}: {exc}"}
+ out = dict(payload or {})
+ out.setdefault("ok", True)
+ out.setdefault("detail", "Voice round trip answered with audio.")
+ return out
+
+
+def _ms(started: float) -> float:
+ import time
+
+ return (time.perf_counter() - started) * 1000.0
+
+
+def _overall(server: dict[str, Any], roles: dict[str, RoleCheck], voice: Any) -> str:
+ configured = [c for c in roles.values() if c.status != NOT_SET]
+ if not server.get("ok"):
+ return "needs_setup" if not configured else "error"
+ if not configured and voice is None:
+ return "needs_setup"
+ if any(c.status != "ok" for c in configured):
+ return "error"
+ if voice is not None and not voice.get("ok", False):
+ return "error"
+ return "ok"
+
+
+# ── The runner ────────────────────────────────────────────────────────────
+
+
+async def run_setup_test(
+ cfg: Any,
+ roles: tuple[str, ...] | None = None,
+ *,
+ transport: Any = None,
+ brain_probe: Callable[[str, str], Awaitable[Any]] | None = None,
+ voice_probe: Callable[[str], Awaitable[dict[str, Any]]] | None = None,
+ timeout_s: float = _DEFAULT_TIMEOUT_S,
+ persist: bool = True,
+) -> TestReport:
+ """Test the configured local setup end to end and persist the report.
+
+ ``roles`` restricts the run to those writable role ids (default: all of
+ them). ``transport`` is the httpx test seam for the Ollama calls;
+ ``brain_probe`` / ``voice_probe`` are the seams for the generation and
+ voice probes (production wiring when ``None``). Never raises for a
+ failing check — every failure is a row in the report.
+ """
+ from jarvis.brain.ollama_roles import WRITABLE_ROLE_IDS, current_pick
+ from jarvis.brain.ollama_runtime import probe_host
+ from jarvis.brain.provider_test import UNREACHABLE
+
+ wanted = tuple(roles) if roles else WRITABLE_ROLE_IDS
+ unknown = [r for r in wanted if r not in WRITABLE_ROLE_IDS]
+ if unknown:
+ raise ValueError(f"Unknown role(s): {', '.join(unknown)}")
+
+ root = _server_root(cfg)
+ server = await probe_host(root, transport=transport)
+ server["base_url"] = root
+
+ checks: dict[str, RoleCheck] = {}
+ for role in wanted:
+ if role == _VOICE_ROLE:
+ continue # the voice role is judged by the smoke probe below
+ model, note = current_pick(cfg, role)
+ if not model:
+ checks[role] = RoleCheck("", NOT_SET, 0.0, note or "No model set.")
+ continue
+ if not server.get("ok"):
+ checks[role] = RoleCheck(model, UNREACHABLE, 0.0, str(server.get("detail") or ""))
+ continue
+ if role == _EMBEDDING_ROLE:
+ checks[role] = await _embedding_check(root, model, transport=transport)
+ elif role in _GENERATION_ROLES:
+ check = await _generation_check(
+ cfg, model, timeout_s=timeout_s, brain_probe=brain_probe
+ )
+ if role == "tools_screen":
+ check = await _capability_check(root, check, transport=transport)
+ checks[role] = check
+
+ voice: dict[str, Any] | None = None
+ if _VOICE_ROLE in wanted:
+ voice = await _voice_check(cfg, timeout_s=timeout_s, voice_probe=voice_probe)
+ voice_model, voice_note = current_pick(cfg, _VOICE_ROLE)
+ if voice is None:
+ checks[_VOICE_ROLE] = RoleCheck(
+ voice_model, NOT_SET, 0.0, voice_note or "No managed voice server."
+ )
+ else:
+ checks[_VOICE_ROLE] = RoleCheck(
+ voice_model,
+ "ok" if voice.get("ok") else "error",
+ float(voice.get("first_audio_ms") or voice.get("latency_ms") or 0.0),
+ str(voice.get("detail") or ""),
+ )
+
+ report = TestReport(
+ checked_at=_dt.datetime.now(_dt.UTC).isoformat(timespec="seconds"),
+ server=server,
+ roles=checks,
+ voice=voice,
+ overall=_overall(server, checks, voice),
+ )
+ if persist:
+ payload = report.to_payload()
+ previous = load_last_report() or {}
+ payload["since"] = (
+ previous.get("since")
+ if previous.get("status") == report.overall and previous.get("since")
+ else report.checked_at
+ )
+ payload["last_ok"] = (
+ report.checked_at if report.overall == "ok" else previous.get("last_ok")
+ )
+ _atomic_write_json(health_path(), payload)
+ return report
diff --git a/jarvis/local_models/assistant_tools.py b/jarvis/local_models/assistant_tools.py
new file mode 100644
index 0000000000..d8eb17b73b
--- /dev/null
+++ b/jarvis/local_models/assistant_tools.py
@@ -0,0 +1,785 @@
+"""The setup assistant's hands: Jarvis tools over the local-models functions.
+
+Every tool here wraps a function the Local models section already calls
+(``ollama_runtime``, ``ollama_inventory``, ``ollama_roles``, ``ollama_pull``,
+``ollama_library``, the managed voice server) as a
+:class:`jarvis.core.protocols.Tool`, the way :mod:`jarvis.agent_chat.folder_tools`
+wraps the chat's folder tools — so every call goes through ``ToolExecutor``
+with its risk tiers, blacklist, audit log and approval card (AP-3), on the
+``local-models`` chat surface exactly as on the voice path.
+
+Tiers: reads are ``safe``; everything that installs, starts, stops, downloads
+or writes config is ``ask`` (the panel auto-answers the cards of a confirmed
+proposal, the executor still asks); ``lm_unload`` is ``monitor``. There is
+deliberately **no delete tool** and nothing that writes ``brain.primary`` —
+the provider lock stays with the user's click.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import platform
+import time
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from typing import Any, Final
+
+from jarvis.core.protocols import ExecutionContext, RiskTier, Tool, ToolResult
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "ACTION_TOOLS",
+ "ALLOWED_TIERS",
+ "LocalModelsTool",
+ "READ_TOOLS",
+ "TOOL_PREFIX",
+ "build_tools",
+ "tool_specs",
+]
+
+TOOL_PREFIX: Final[str] = "lm_"
+
+#: Every tier a local-models tool may carry. ``block`` is not on the list on
+#: purpose: a tool that must never run is a tool that must not exist here.
+ALLOWED_TIERS: Final[tuple[RiskTier, ...]] = ("safe", "monitor", "ask")
+
+Handler = Callable[[dict[str, Any], "_Env"], Awaitable[Any]]
+
+#: How long ``lm_pull`` follows a download before handing back a "still
+#: running" answer (the panel keeps polling ``lm_pull_status``).
+PULL_FOLLOW_MAX_S = 1800.0
+PULL_POLL_S = 1.0
+
+
+@dataclass(frozen=True, slots=True)
+class _Env:
+ """What every handler needs: the live config, the server root, the seams."""
+
+ cfg: Any
+ root: str
+ transport: Any = None
+ search_fn: Callable[[str], Any] | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class ToolSpec:
+ name: str
+ description: str
+ schema: dict[str, Any]
+ risk_tier: RiskTier
+ handler: Handler
+ summary: Callable[[dict[str, Any]], str] | None = None
+
+
+class LocalModelsTool:
+ """One spec as a Jarvis ``Tool`` bound to a config + server root."""
+
+ def __init__(self, spec: ToolSpec, env: _Env) -> None:
+ self.name: str = spec.name
+ self.description: str = spec.description
+ self.schema: dict[str, Any] = dict(spec.schema)
+ self.risk_tier: RiskTier = spec.risk_tier
+ self._spec = spec
+ self._env = env
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ try:
+ output = await self._spec.handler(dict(args or {}), self._env)
+ except Exception as exc: # noqa: BLE001 — the model reads the failure, the log keeps it
+ log.info("local-models tool %s failed: %s", self.name, exc, exc_info=True)
+ return ToolResult(success=False, output=str(exc), error=f"{type(exc).__name__}: {exc}")
+ return ToolResult(success=True, output=output)
+
+ def describe_args(self, args: dict[str, Any]) -> dict[str, str]:
+ """The one-line summary the approval card shows."""
+ if self._spec.summary is None:
+ return {}
+ try:
+ text = self._spec.summary(dict(args or {}))
+ except Exception: # noqa: BLE001 — a summary must never break the card
+ log.debug("local-models tool %s: summary failed", self.name, exc_info=True)
+ return {}
+ return {"summary": text} if text else {}
+
+ def __repr__(self) -> str: # pragma: no cover — debugging aid
+ return f"LocalModelsTool({self.name!r}, tier={self.risk_tier!r})"
+
+
+# ── schema helpers ────────────────────────────────────────────────────────
+
+
+def _obj(props: dict[str, Any] | None = None, required: tuple[str, ...] = ()) -> dict[str, Any]:
+ schema: dict[str, Any] = {"type": "object", "properties": dict(props or {})}
+ if required:
+ schema["required"] = list(required)
+ return schema
+
+
+_MODEL = {"type": "string", "description": "An Ollama model tag, e.g. qwen3.5:4b."}
+_ROLE = {
+ "type": "string",
+ "description": "A writable role id: chat, voice, tools_screen, deep or embedding.",
+}
+
+
+def _str(args: dict[str, Any], key: str) -> str:
+ return str(args.get(key) or "").strip()
+
+
+# ── read handlers (safe) ──────────────────────────────────────────────────
+
+
+async def _hardware(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_pull import accelerator_gb, total_memory_gb
+
+ (accel, source), ram = await asyncio.gather(
+ asyncio.to_thread(accelerator_gb), asyncio.to_thread(total_memory_gb)
+ )
+ import os
+
+ return {
+ "os": platform.system(),
+ "os_version": platform.release(),
+ "machine": platform.machine(),
+ "cpu_threads": os.cpu_count() or 0,
+ "ram_gb": ram,
+ "accelerator_gb": round(accel, 1),
+ "accelerator_source": source,
+ }
+
+
+async def _server_status(_args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.brain import ollama_runtime
+
+ status, probe = await asyncio.gather(
+ asyncio.to_thread(ollama_runtime.runtime_status),
+ ollama_runtime.probe_host(env.root, transport=env.transport),
+ )
+ out: dict[str, Any] = {
+ "runtime": status,
+ "probe": probe,
+ "install": ollama_runtime.install_snapshot(),
+ "base_url": env.root,
+ }
+ command = _voice_command(env.cfg)
+ if "--model_name" in command:
+ from jarvis.realtime.local_server import install as voice_install
+ from jarvis.realtime.local_server.preflight import report_payload, run_preflight
+
+ voice_status = await asyncio.to_thread(voice_install.server_status)
+ preflight = await asyncio.to_thread(run_preflight, voice_install.install_root())
+ out["voice"] = {
+ "launch_command": command,
+ "status": voice_status,
+ "preflight": report_payload(preflight),
+ }
+ else:
+ out["voice"] = {"launch_command": command, "status": None, "preflight": None}
+ return out
+
+
+async def _inventory(_args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.brain import ollama_inventory as inventory
+
+ models, running = await asyncio.gather(
+ inventory.list_models(env.root, transport=env.transport),
+ inventory.running_models(env.root, transport=env.transport),
+ )
+ return {
+ "models": [
+ {
+ "name": m.name,
+ "size_gb": round(m.size_bytes / (1024**3), 2),
+ "family": m.family,
+ "parameter_size": m.parameter_size,
+ "quantization": m.quantization_level,
+ "context_length": m.context_length,
+ "capabilities": list(m.capabilities),
+ "modified_at": m.modified_at,
+ }
+ for m in models
+ ],
+ "running": [
+ {
+ "name": r.name,
+ "size_vram_gb": round(r.size_vram_bytes / (1024**3), 2),
+ "context_length": r.context_length,
+ "expires_at": r.expires_at,
+ }
+ for r in running
+ ],
+ "disk_gb": round(sum(m.size_bytes for m in models) / (1024**3), 1),
+ }
+
+
+def _role_row(state: Any) -> dict[str, Any]:
+ spec = state.spec
+ return {
+ "role": spec.id,
+ "config_key": spec.config_key,
+ "writable": spec.writable,
+ "required_capabilities": list(spec.required),
+ "current": state.current,
+ "installed": state.installed,
+ "qualifying": list(state.qualifying),
+ "recommended": state.recommended,
+ "note": state.note,
+ "context_tokens": state.context_tokens,
+ }
+
+
+async def _roles(_args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_roles import list_roles
+
+ states, error = await list_roles(env.root, env.cfg, transport=env.transport)
+ return {"roles": [_role_row(s) for s in states], "error": error}
+
+
+async def _recommendations(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ import datetime as _dt
+
+ from jarvis.brain.ollama_pull import recommendations
+ from jarvis.local_models import benchmarks
+
+ payload = await recommendations()
+ table = benchmarks.load_cached()
+ today = _dt.datetime.now(_dt.UTC).date()
+ for row in payload.get("models") or []:
+ row["label"] = benchmarks.label_for(str(row.get("id") or ""), table, today)
+ payload["benchmark_source"] = table.source if table is not None else "curated"
+ return payload
+
+
+async def _catalog_search(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_library import search_library
+
+ return await search_library(
+ _str(args, "query"),
+ sort=_str(args, "sort") or "popular",
+ capability=_str(args, "capability") or None,
+ limit=int(args.get("limit") or 20),
+ )
+
+
+async def _catalog_tags(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_library import library_tags
+
+ return await library_tags(_str(args, "model"))
+
+
+async def _hf_search(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain import hf_gguf # lazy: only an install that switched HF on imports it
+
+ return await hf_gguf.search(
+ _str(args, "query"),
+ sort=_str(args, "sort") or "downloads",
+ limit=int(args.get("limit") or 20),
+ )
+
+
+async def _benchmarks(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.local_models import benchmarks
+
+ table: benchmarks.BenchmarkTable | None
+ if bool(args.get("refresh")) and env.search_fn is not None:
+ table = await benchmarks.refresh_benchmarks(env.search_fn)
+ else:
+ table = benchmarks.load_cached()
+ if table is None:
+ note = (
+ "No benchmark cache yet; pass refresh=true to build one."
+ if env.search_fn is not None
+ else "No benchmark cache and no web search on this surface; curated list only."
+ )
+ table = benchmarks.curated_only(note)
+ return table.to_payload()
+
+
+async def _pull_status(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_pull import pull_status
+
+ return await pull_status(_str(args, "model"))
+
+
+async def _server_log(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_runtime import tail_log
+
+ lines = max(1, min(int(args.get("lines") or 40), 200))
+ return {"lines": await asyncio.to_thread(tail_log, lines)}
+
+
+async def _env_guide(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_runtime import env_guide
+
+ return {"entries": env_guide()}
+
+
+async def _suggest(model: str, env: _Env) -> tuple[dict[str, Any], list[str], dict[str, Any]]:
+ from jarvis.brain import ollama_inventory as inventory
+ from jarvis.brain import ollama_profiles
+ from jarvis.brain.ollama_pull import accelerator_gb, total_memory_gb
+
+ info = await inventory.get_model(env.root, model, transport=env.transport)
+ (accel, source), ram = await asyncio.gather(
+ asyncio.to_thread(accelerator_gb), asyncio.to_thread(total_memory_gb)
+ )
+ size_gb = round(info.size_bytes / (1024**3), 2)
+ opts, reasons = ollama_profiles.suggest_options(
+ size_gb=size_gb,
+ native_context=info.context_length,
+ accelerator_gb=accel,
+ source=source,
+ ram_gb=ram,
+ )
+ facts = {
+ "model": info.name,
+ "size_gb": size_gb,
+ "native_context": info.context_length,
+ "accelerator_gb": round(accel, 1),
+ "ram_gb": ram,
+ }
+ return opts.model_dump(exclude_none=True), reasons, facts
+
+
+async def _suggested_options(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ options, reasons, facts = await _suggest(_str(args, "model"), env)
+ return {**facts, "options": options, "reasons": reasons}
+
+
+async def _test_plan(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.local_models.assistant_test import run_setup_test
+
+ raw = args.get("roles")
+ roles = tuple(str(r) for r in raw) if isinstance(raw, list) and raw else None
+ report = await run_setup_test(env.cfg, roles, transport=env.transport)
+ return report.to_payload()
+
+
+# ── action handlers (ask / monitor) ───────────────────────────────────────
+
+
+async def _install_ollama(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain import ollama_runtime
+
+ ok, detail = await asyncio.to_thread(ollama_runtime.start_install)
+ return {"started": ok, "detail": detail, "install": ollama_runtime.install_snapshot()}
+
+
+async def _start_server(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_runtime import start_server
+
+ ok, detail = await asyncio.to_thread(start_server)
+ return {"ok": ok, "detail": detail}
+
+
+async def _stop_server(_args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_runtime import stop_server
+
+ ok, detail = await asyncio.to_thread(stop_server)
+ return {"ok": ok, "detail": detail}
+
+
+async def _pull(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ """Start (or join) a download and follow it, reporting progress lines."""
+ from jarvis.brain.ollama_pull import pull_status, start_pull
+
+ model = _str(args, "model")
+ state = await start_pull(model)
+ lines: list[str] = [str(state.get("message") or "")]
+ if state.get("state") != "running":
+ return {**state, "progress": lines}
+ max_wait = float(args.get("max_wait_s") or PULL_FOLLOW_MAX_S)
+ started = time.monotonic()
+ last_pct = -1
+ while time.monotonic() - started < max_wait:
+ await asyncio.sleep(PULL_POLL_S)
+ state = await pull_status(model)
+ total = int(state.get("total") or 0)
+ done = int(state.get("completed") or 0)
+ pct = int(done * 100 / total) if total else -1
+ if pct >= 0 and pct // 10 > last_pct // 10:
+ last_pct = pct
+ lines.append(f"{model}: {pct}% ({done / 1e9:.1f} of {total / 1e9:.1f} GB)")
+ if state.get("state") != "running":
+ lines.append(str(state.get("message") or ""))
+ return {**state, "progress": lines}
+ lines.append(f"{model}: still downloading — check lm_pull_status for progress.")
+ return {**state, "progress": lines}
+
+
+async def _set_role(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.brain.ollama_roles import set_role
+
+ result = dict(set_role(_str(args, "role"), _str(args, "model"), cfg=env.cfg))
+ if result.get("drift_guarded") is False:
+ result["warning"] = (
+ "The pick was written, but the drift baseline could not be updated — "
+ "the drift guard may revert it within minutes. Check the config baseline."
+ )
+ return result
+
+
+async def _set_model_options(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ """Write ONLY keys the suggestion for this model returned — nothing else."""
+ from jarvis.core import config_writer
+
+ model = _str(args, "model")
+ wanted = args.get("options")
+ if not isinstance(wanted, dict) or not wanted:
+ raise ValueError("options must be a non-empty object.")
+ suggested, _reasons, _facts = await _suggest(model, env)
+ allowed = set(suggested)
+ rejected = sorted(k for k in wanted if k not in allowed)
+ if rejected:
+ raise ValueError(
+ f"Only the suggested keys may be set for {model} ({', '.join(sorted(allowed))}); "
+ f"refused: {', '.join(rejected)}."
+ )
+ written = await asyncio.to_thread(
+ config_writer.set_ollama_model_options, model, {k: wanted[k] for k in wanted}
+ )
+ provider = _ollama_provider(env.cfg)
+ models = getattr(provider, "models", None)
+ if isinstance(models, dict):
+ from jarvis.core.config import OllamaModelOptions
+
+ try:
+ models[model] = OllamaModelOptions.model_validate(written)
+ except (TypeError, ValueError):
+ log.info("local-models: in-memory options for %s not updated", model, exc_info=True)
+ return {"model": model, "written": written}
+
+
+async def _install_voice_server(args: dict[str, Any], _env: _Env) -> dict[str, Any]:
+ from jarvis.realtime.local_server import install as voice_install
+
+ ok, detail = await asyncio.to_thread(
+ lambda: voice_install.start_install(
+ confirmed_brain="ollama",
+ brain_model=_str(args, "brain_model"),
+ voice_model=_str(args, "voice_model"),
+ )
+ )
+ return {"started": ok, "detail": detail, "install": voice_install.snapshot()}
+
+
+async def _apply_voice_stack(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.realtime.local_server.configure import ManagedSetupError, apply_and_test_stack
+
+ command = _voice_command(env.cfg)
+ if "--model_name" not in command:
+ raise ValueError("Install the managed voice server first (lm_install_voice_server).")
+ try:
+ result = await apply_and_test_stack(
+ base_url=_voice_base_url(env.cfg),
+ current_command=command,
+ brain_model=_str(args, "brain_model"),
+ voice_model=_str(args, "voice_model"),
+ language=_str(args, "language") or "en",
+ )
+ except ManagedSetupError as exc:
+ # The function rolled back (or says it could not) — report, never hide.
+ return {"ok": False, "rolled_back": "restored" in str(exc), "detail": str(exc)}
+ voice = _voice_provider(env.cfg)
+ if voice is not None and result.get("launch_command"):
+ voice.launch_command = str(result["launch_command"])
+ return dict(result)
+
+
+async def _unload(args: dict[str, Any], env: _Env) -> dict[str, Any]:
+ from jarvis.brain import ollama_inventory as inventory
+
+ model = _str(args, "model")
+ await inventory.unload_model(env.root, model, transport=env.transport)
+ return {"model": model, "unloaded": True}
+
+
+# ── config readers ────────────────────────────────────────────────────────
+
+
+def _ollama_provider(cfg: Any) -> Any:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ return providers.get("ollama") if isinstance(providers, dict) else None
+
+
+def _voice_provider(cfg: Any) -> Any:
+ providers = getattr(getattr(cfg, "brain", None), "providers", None) or {}
+ return providers.get("local-realtime") if isinstance(providers, dict) else None
+
+
+def _voice_command(cfg: Any) -> str:
+ return str(getattr(_voice_provider(cfg), "launch_command", "") or "")
+
+
+def _voice_base_url(cfg: Any) -> str:
+ return str(getattr(_voice_provider(cfg), "base_url", "") or "") or "http://127.0.0.1:8765"
+
+
+# ── the specs ─────────────────────────────────────────────────────────────
+
+
+def _s(
+ name: str,
+ description: str,
+ schema: dict[str, Any],
+ tier: RiskTier,
+ handler: Handler,
+ summary: Callable[[dict[str, Any]], str] | None = None,
+) -> ToolSpec:
+ return ToolSpec(name, description, schema, tier, handler, summary)
+
+
+READ_TOOLS: Final[tuple[ToolSpec, ...]] = (
+ _s(
+ "lm_hardware",
+ "This machine's memory: RAM, usable graphics memory and where that figure comes from.",
+ _obj(),
+ "safe",
+ _hardware,
+ ),
+ _s(
+ "lm_server_status",
+ "Is Ollama installed and running, which version, and the state of the managed voice "
+ "server (status + preflight) when one exists.",
+ _obj(),
+ "safe",
+ _server_status,
+ ),
+ _s(
+ "lm_inventory",
+ "Every downloaded model with size, capabilities and context length, plus what is "
+ "loaded in memory right now.",
+ _obj(),
+ "safe",
+ _inventory,
+ ),
+ _s(
+ "lm_roles",
+ "The five roles (chat, voice, tools_screen, deep, embedding): current pick, its config "
+ "key, whether it is installed, which downloads qualify and the recommendation.",
+ _obj(),
+ "safe",
+ _roles,
+ ),
+ _s(
+ "lm_recommendations",
+ "The curated shortlist ranked for this machine with fit verdicts and the "
+ "proven / new_little_tested / stale label per entry.",
+ _obj(),
+ "safe",
+ _recommendations,
+ ),
+ _s(
+ "lm_catalog_search",
+ "Search the public Ollama library (ollama.com).",
+ _obj(
+ {
+ "query": {"type": "string"},
+ "sort": {"type": "string", "enum": ["popular", "newest"]},
+ "capability": {
+ "type": "string",
+ "enum": ["tools", "vision", "embedding", "thinking"],
+ },
+ "limit": {"type": "integer", "minimum": 1, "maximum": 50},
+ }
+ ),
+ "safe",
+ _catalog_search,
+ ),
+ _s(
+ "lm_catalog_tags",
+ "Every tag of one library model with its size and fit verdict for this machine.",
+ _obj({"model": _MODEL}, ("model",)),
+ "safe",
+ _catalog_tags,
+ ),
+ _s(
+ "lm_hf_search",
+ "Search GGUF repositories on Hugging Face (only when the user enabled it).",
+ _obj(
+ {
+ "query": {"type": "string"},
+ "sort": {"type": "string", "enum": ["downloads", "lastModified", "trendingScore"]},
+ "limit": {"type": "integer", "minimum": 1, "maximum": 100},
+ }
+ ),
+ "safe",
+ _hf_search,
+ ),
+ _s(
+ "lm_benchmarks",
+ "The benchmark table behind the proven / new labels (cached seven days). "
+ "refresh=true rebuilds it from the web inside a guided run.",
+ _obj({"refresh": {"type": "boolean"}}),
+ "safe",
+ _benchmarks,
+ ),
+ _s(
+ "lm_pull_status",
+ "Progress of one download.",
+ _obj({"model": _MODEL}, ("model",)),
+ "safe",
+ _pull_status,
+ ),
+ _s(
+ "lm_server_log",
+ "The last lines of the Ollama server log Jarvis writes.",
+ _obj({"lines": {"type": "integer", "minimum": 1, "maximum": 200}}),
+ "safe",
+ _server_log,
+ ),
+ _s(
+ "lm_env_guide",
+ "The OLLAMA_* environment variables that matter (models dir, host, keep-alive) and how "
+ "to set each on this OS — advice only, nothing is applied.",
+ _obj(),
+ "safe",
+ _env_guide,
+ ),
+ _s(
+ "lm_suggested_options",
+ "An advisory option profile (num_ctx, num_gpu, …) for one installed model on this "
+ "machine, with one reason per knob. Only these keys may be set with "
+ "lm_set_model_options.",
+ _obj({"model": _MODEL}, ("model",)),
+ "safe",
+ _suggested_options,
+ ),
+ _s(
+ "lm_test_plan",
+ "Run the end-to-end test: server probe, one real generation per configured role, an "
+ "embedding round trip, the voice probe when a managed voice server exists. Returns a "
+ "per-role table with ok / error statuses.",
+ _obj(
+ {
+ "roles": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Subset of chat, voice, tools_screen, deep, embedding.",
+ }
+ }
+ ),
+ "safe",
+ _test_plan,
+ ),
+)
+
+ACTION_TOOLS: Final[tuple[ToolSpec, ...]] = (
+ _s(
+ "lm_install_ollama",
+ "Install Ollama on this machine (winget / installer / install.sh). Starts in the "
+ "background; follow it with lm_server_status.",
+ _obj(),
+ "ask",
+ _install_ollama,
+ lambda _a: "Install Ollama",
+ ),
+ _s(
+ "lm_start_server",
+ "Start the Ollama server.",
+ _obj(),
+ "ask",
+ _start_server,
+ lambda _a: "Start the Ollama server",
+ ),
+ _s(
+ "lm_stop_server",
+ "Stop the Ollama server Jarvis started (never one started elsewhere).",
+ _obj(),
+ "ask",
+ _stop_server,
+ lambda _a: "Stop the Ollama server",
+ ),
+ _s(
+ "lm_pull",
+ "Download a model and follow the download, returning progress lines. Long downloads "
+ "hand back 'still downloading'; poll lm_pull_status then.",
+ _obj({"model": _MODEL, "max_wait_s": {"type": "number"}}, ("model",)),
+ "ask",
+ _pull,
+ lambda a: f"Download {a.get('model', '')}",
+ ),
+ _s(
+ "lm_set_role",
+ "Persist which installed model serves a role. Reports drift_guarded=false when the "
+ "config baseline could not be updated (the pick may then be reverted).",
+ _obj({"role": _ROLE, "model": _MODEL}, ("role", "model")),
+ "ask",
+ _set_role,
+ lambda a: f"Use {a.get('model', '')} for {a.get('role', '')}",
+ ),
+ _s(
+ "lm_set_model_options",
+ "Persist per-model options — only keys lm_suggested_options returned for that model.",
+ _obj(
+ {
+ "model": _MODEL,
+ "options": {"type": "object", "description": "num_ctx, num_gpu, … values."},
+ },
+ ("model", "options"),
+ ),
+ "ask",
+ _set_model_options,
+ lambda a: f"Tune {a.get('model', '')}",
+ ),
+ _s(
+ "lm_install_voice_server",
+ "Install the Jarvis-managed local voice server (background; follow with lm_server_status).",
+ _obj({"brain_model": _MODEL, "voice_model": {"type": "string"}}),
+ "ask",
+ _install_voice_server,
+ lambda _a: "Install the local voice server",
+ ),
+ _s(
+ "lm_apply_voice_stack",
+ "Switch the managed voice server to a brain + voice model pair, run the voice test and "
+ "persist only on success; reports a rollback otherwise.",
+ _obj(
+ {
+ "brain_model": _MODEL,
+ "voice_model": {"type": "string", "description": "A voice profile id."},
+ "language": {"type": "string"},
+ },
+ ("brain_model", "voice_model"),
+ ),
+ "ask",
+ _apply_voice_stack,
+ lambda a: f"Voice stack: {a.get('brain_model', '')} + {a.get('voice_model', '')}",
+ ),
+ _s(
+ "lm_unload",
+ "Free the memory a loaded model holds (it reloads on the next request).",
+ _obj({"model": _MODEL}, ("model",)),
+ "monitor",
+ _unload,
+ lambda a: f"Unload {a.get('model', '')}",
+ ),
+)
+
+
+def tool_specs(cfg: Any) -> tuple[ToolSpec, ...]:
+ """The specs offered for ``cfg`` — HF search only when the user enabled it."""
+ from jarvis.core.config import ollama_hf_enabled
+
+ hf = ollama_hf_enabled(cfg) if cfg is not None else False
+ reads = tuple(s for s in READ_TOOLS if hf or s.name != "lm_hf_search")
+ return reads + ACTION_TOOLS
+
+
+def build_tools(
+ cfg: Any,
+ *,
+ root: str,
+ transport: Any = None,
+ search_fn: Callable[[str], Any] | None = None,
+) -> dict[str, Tool]:
+ """The assistant's tools for one turn, keyed by name.
+
+ ``root`` is the Ollama server root the section talks to; ``transport``
+ the httpx test seam; ``search_fn`` (the ``search_web`` call) lets
+ ``lm_benchmarks`` refresh the table — without it the table is read-only.
+ """
+ env = _Env(cfg=cfg, root=root, transport=transport, search_fn=search_fn)
+ return {spec.name: LocalModelsTool(spec, env) for spec in tool_specs(cfg)}
diff --git a/jarvis/local_models/benchmarks.py b/jarvis/local_models/benchmarks.py
new file mode 100644
index 0000000000..4570030f7b
--- /dev/null
+++ b/jarvis/local_models/benchmarks.py
@@ -0,0 +1,511 @@
+"""Benchmarks and freshness for the curated shortlist: proven, new, or stale?
+
+The setup assistant must prefer the best *proven* local models and never
+pick a brand-new one as a default. "Proven" is decided here from two
+sources, both tolerant of being unreachable:
+
+* public benchmark pages (Artificial Analysis, LMArena, the Open LLM
+ Leaderboard) reached through a caller-supplied ``search_fn`` (the
+ key-free ``search_web`` tool in production) — the snippets are mined with
+ tolerant regexes into ``{family, source, metric, value, url, seen_at}``
+ rows;
+* the Ollama library (``ollama_library.search_library``) for pulls and the
+ last update of each family.
+
+The result is cached at ``DATA_DIR/state/local_models_benchmarks.json`` for
+seven days; the assistant refreshes it only inside a guided run or on an
+explicit "Refresh shortlist". Offline, the cache or a curated-only table
+(with a note saying so) is the answer — never an error.
+
+:func:`label_for` is the pure labelling rule the proposal card renders and
+the tests pin.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import datetime as _dt
+import inspect
+import json
+import logging
+import os
+import re
+import uuid
+from collections.abc import Awaitable, Callable, Iterable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "BENCHMARK_FILE_NAME",
+ "CACHE_TTL_DAYS",
+ "LABELS",
+ "BenchmarkRow",
+ "BenchmarkTable",
+ "LibraryFacts",
+ "extract_rows",
+ "family_of",
+ "label_for",
+ "load_cached",
+ "parse_pulls",
+ "parse_updated_days",
+ "refresh_benchmarks",
+]
+
+BENCHMARK_FILE_NAME = "local_models_benchmarks.json"
+CACHE_TTL_DAYS = 7
+
+#: The three labels, in the order the card explains them.
+LABELS: tuple[str, ...] = ("proven", "new_little_tested", "stale")
+
+#: Library facts that make a family "proven" without a benchmark row.
+PROVEN_MIN_PULLS = 100_000
+#: A family updated more recently than this is "new" whatever the numbers say.
+NEW_MAX_AGE_DAYS = 60
+
+#: Query templates, one per source; ``{family}`` is the curated family name.
+QUERY_TEMPLATES: tuple[tuple[str, str], ...] = (
+ ("artificial_analysis", "{family} Artificial Analysis intelligence index"),
+ ("lmarena", "{family} LMArena text arena score"),
+ ("open_llm_leaderboard", "{family} Open LLM Leaderboard average score"),
+)
+
+#: Result host → source id, so a snippet from LMArena found via the
+#: Artificial-Analysis query is still filed under LMArena.
+_SOURCE_HOSTS: tuple[tuple[str, str], ...] = (
+ ("artificialanalysis.ai", "artificial_analysis"),
+ ("lmarena.ai", "lmarena"),
+ ("lmsys.org", "lmarena"),
+ ("huggingface.co", "open_llm_leaderboard"),
+)
+
+#: (metric id, tolerant pattern). Values are the first capture group.
+_METRIC_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
+ (
+ "intelligence_index",
+ re.compile(r"intelligence\s+index(?:\s+of)?\s*[:=]?\s*(\d{1,3}(?:\.\d+)?)", re.I),
+ ),
+ (
+ "arena_score",
+ re.compile(r"(?:arena|elo)\s*(?:score|rating)?\s*(?:of|[:=])?\s*(\d{3,4})\b", re.I),
+ ),
+ (
+ "leaderboard_average",
+ re.compile(
+ r"(?:average|avg\.?)\s*(?:score)?\s*(?:of|[:=])?\s*(\d{1,3}(?:\.\d+)?)\s*%?", re.I
+ ),
+ ),
+ (
+ "mmlu",
+ re.compile(r"MMLU(?:-Pro)?\s*(?:score)?\s*(?:of|[:=])?\s*(\d{1,3}(?:\.\d+)?)\s*%?", re.I),
+ ),
+ (
+ "gpqa",
+ re.compile(r"GPQA(?:\s+Diamond)?\s*(?:score)?\s*(?:of|[:=])?\s*(\d{1,3}(?:\.\d+)?)", re.I),
+ ),
+)
+
+SearchFn = Callable[[str], Any]
+
+
+@dataclass(frozen=True, slots=True)
+class BenchmarkRow:
+ family: str
+ source: str
+ metric: str
+ value: float
+ url: str
+ seen_at: str
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "family": self.family,
+ "source": self.source,
+ "metric": self.metric,
+ "value": self.value,
+ "url": self.url,
+ "seen_at": self.seen_at,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class LibraryFacts:
+ family: str
+ pulls: int
+ #: Days since the library's "Updated … ago"; ``None`` when unknown.
+ updated_days: int | None
+
+ def to_payload(self) -> dict[str, Any]:
+ return {"family": self.family, "pulls": self.pulls, "updated_days": self.updated_days}
+
+
+@dataclass(frozen=True, slots=True)
+class BenchmarkTable:
+ fetched_at: str
+ rows: tuple[BenchmarkRow, ...]
+ library: dict[str, LibraryFacts]
+ #: ``live`` | ``cache`` | ``curated`` — where the numbers came from.
+ source: str
+ #: One sentence when the table is not live ("" otherwise).
+ note: str = ""
+
+ def rows_for(self, family: str) -> tuple[BenchmarkRow, ...]:
+ return tuple(r for r in self.rows if r.family == family)
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "fetched_at": self.fetched_at,
+ "source": self.source,
+ "note": self.note,
+ "rows": [r.to_payload() for r in self.rows],
+ "library": {f: facts.to_payload() for f, facts in self.library.items()},
+ }
+
+ @classmethod
+ def from_payload(cls, payload: dict[str, Any], *, source: str | None = None) -> BenchmarkTable:
+ rows: list[BenchmarkRow] = []
+ for raw in payload.get("rows") or []:
+ try:
+ rows.append(
+ BenchmarkRow(
+ family=str(raw["family"]),
+ source=str(raw.get("source") or ""),
+ metric=str(raw.get("metric") or ""),
+ value=float(raw.get("value") or 0.0),
+ url=str(raw.get("url") or ""),
+ seen_at=str(raw.get("seen_at") or ""),
+ )
+ )
+ except (KeyError, TypeError, ValueError):
+ log.debug("benchmarks: dropping malformed row %r", raw)
+ library: dict[str, LibraryFacts] = {}
+ for family, raw in (payload.get("library") or {}).items():
+ try:
+ updated = raw.get("updated_days")
+ library[str(family)] = LibraryFacts(
+ family=str(family),
+ pulls=int(raw.get("pulls") or 0),
+ updated_days=None if updated is None else int(updated),
+ )
+ except (AttributeError, TypeError, ValueError):
+ log.debug("benchmarks: dropping malformed library facts %r", raw)
+ return cls(
+ fetched_at=str(payload.get("fetched_at") or ""),
+ rows=tuple(rows),
+ library=library,
+ source=source or str(payload.get("source") or "cache"),
+ note=str(payload.get("note") or ""),
+ )
+
+
+# ── Small pure helpers ────────────────────────────────────────────────────
+
+
+def family_of(model_id: str) -> str:
+ """``qwen3.5:4b`` → ``qwen3.5``; ``hf.co/u/r:Q4`` keeps its path."""
+ return (model_id or "").strip().partition(":")[0]
+
+
+def _entry_id(entry: Any) -> str:
+ """The model id of a curated entry or a bare id string."""
+ return str(getattr(entry, "id", None) or entry or "")
+
+
+def curated_families(entries: Iterable[Any] | None = None) -> tuple[str, ...]:
+ """The distinct families of the curated shortlist, in list order."""
+ if entries is None:
+ from jarvis.brain.ollama_pull import RECOMMENDED_MODELS
+
+ entries = tuple(RECOMMENDED_MODELS)
+ seen: list[str] = []
+ for entry in entries:
+ family = family_of(_entry_id(entry))
+ if family and family not in seen:
+ seen.append(family)
+ return tuple(seen)
+
+
+_PULLS_FACTOR = {"": 1, "K": 1_000, "M": 1_000_000, "B": 1_000_000_000}
+
+
+def parse_pulls(text: str) -> int:
+ """``"17.2M"`` → ``17200000``; anything unreadable → ``0``."""
+ match = re.fullmatch(r"\s*([\d.,]+)\s*([KMB]?)\s*", (text or "").upper())
+ if not match:
+ return 0
+ try:
+ return int(float(match.group(1).replace(",", "")) * _PULLS_FACTOR[match.group(2)])
+ except ValueError:
+ return 0
+
+
+_UNIT_DAYS = {
+ "second": 0,
+ "minute": 0,
+ "hour": 0,
+ "day": 1,
+ "week": 7,
+ "month": 30,
+ "year": 365,
+}
+
+
+def parse_updated_days(text: str) -> int | None:
+ """``"2 weeks ago"`` → ``14``, ``"yesterday"`` → ``1``; unknown → ``None``."""
+ t = (text or "").strip().lower()
+ if not t:
+ return None
+ if t in ("yesterday",):
+ return 1
+ if t in ("today", "just now"):
+ return 0
+ match = re.match(r"(a|an|\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago", t)
+ if not match:
+ return None
+ count = 1 if match.group(1) in ("a", "an") else int(match.group(1))
+ return count * _UNIT_DAYS[match.group(2)]
+
+
+def _source_for(url: str, fallback: str) -> str:
+ low = (url or "").lower()
+ for host, source in _SOURCE_HOSTS:
+ if host in low:
+ return source
+ return fallback
+
+
+def extract_rows(
+ family: str, results: Iterable[dict[str, Any]], *, source: str, seen_at: str
+) -> list[BenchmarkRow]:
+ """Mine benchmark numbers out of search snippets — tolerant, never raising.
+
+ A snippet counts only when it names the family (case-insensitive,
+ ``qwen3.5`` also matches ``Qwen 3.5``) AND carries a number one of the
+ metric patterns understands. One row per (source, metric) per family.
+ """
+ needle = re.escape(family.lower()).replace(r"\.", r"\.?").replace(r"\-", r"[\s-]?")
+ needle = re.sub(r"([a-z])(\d)", r"\1\\s?\2", needle)
+ family_re = re.compile(needle, re.I)
+ rows: dict[tuple[str, str], BenchmarkRow] = {}
+ for result in results:
+ if not isinstance(result, dict):
+ continue
+ text = f"{result.get('title') or ''} {result.get('snippet') or ''}"
+ if not family_re.search(text):
+ continue
+ url = str(result.get("url") or "")
+ row_source = _source_for(url, source)
+ for metric, pattern in _METRIC_PATTERNS:
+ match = pattern.search(text)
+ if not match:
+ continue
+ try:
+ value = float(match.group(1))
+ except ValueError:
+ continue
+ key = (row_source, metric)
+ if key not in rows:
+ rows[key] = BenchmarkRow(family, row_source, metric, value, url, seen_at)
+ return list(rows.values())
+
+
+# ── The labelling rule ────────────────────────────────────────────────────
+
+
+def label_for(entry: Any, table: BenchmarkTable | None, today: _dt.date) -> str:
+ """``proven`` | ``new_little_tested`` | ``stale`` for one curated entry.
+
+ In order:
+
+ 1. ``stale`` — the curated list was last reviewed more than a year before
+ ``today`` (nothing on it may be called proven any more).
+ 2. ``new_little_tested`` — the library updated the family less than
+ :data:`NEW_MAX_AGE_DAYS` ago (a brand-new build is never a default,
+ whatever last month's numbers said).
+ 3. ``proven`` — at least one benchmark row, or :data:`PROVEN_MIN_PULLS`
+ pulls in the library.
+ 4. Otherwise ``new_little_tested`` (no row, no pull count to speak of).
+
+ ``entry`` is a curated :class:`~jarvis.brain.ollama_pull.RecommendedModel`
+ or a model id string; ``table`` may be ``None`` (curated-only mode).
+ """
+ from jarvis.brain.ollama_pull import CURATED_MAX_AGE_DAYS, CURATED_REVIEWED_ON
+
+ if (today - CURATED_REVIEWED_ON).days > CURATED_MAX_AGE_DAYS:
+ return "stale"
+ family = family_of(_entry_id(entry))
+ facts = table.library.get(family) if table is not None else None
+ updated_days = facts.updated_days if facts is not None else None
+ if updated_days is not None and updated_days < NEW_MAX_AGE_DAYS:
+ return "new_little_tested"
+ if table is not None and table.rows_for(family):
+ return "proven"
+ if facts is not None and facts.pulls >= PROVEN_MIN_PULLS:
+ return "proven"
+ return "new_little_tested"
+
+
+# ── Cache ─────────────────────────────────────────────────────────────────
+
+
+def cache_path() -> Path:
+ from jarvis.core import config as cfg_mod # lazy: DATA_DIR is monkeypatched by tests
+
+ return Path(cfg_mod.DATA_DIR) / "state" / BENCHMARK_FILE_NAME
+
+
+def _atomic_write_json(path: Path, payload: dict[str, Any]) -> bool:
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ os.replace(temporary, path)
+ return True
+ except OSError:
+ log.warning("benchmarks: cache %s not written", path, exc_info=True)
+ return False
+ finally:
+ try:
+ temporary.unlink(missing_ok=True)
+ except OSError:
+ log.debug("benchmarks: temporary cache cleanup failed", exc_info=True)
+
+
+def load_cached(
+ *, max_age_days: int | None = CACHE_TTL_DAYS, now: _dt.datetime | None = None
+) -> BenchmarkTable | None:
+ """The cached table when it exists and is younger than ``max_age_days``.
+
+ ``max_age_days=None`` returns whatever is on disk, however old — the
+ offline fallback prefers a stale table over none.
+ """
+ path = cache_path()
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return None
+ except (OSError, ValueError):
+ log.info("benchmarks: cache %s unreadable", path, exc_info=True)
+ return None
+ if not isinstance(payload, dict):
+ return None
+ table = BenchmarkTable.from_payload(payload, source="cache")
+ if max_age_days is not None:
+ fetched = _parse_iso(table.fetched_at)
+ current = now or _dt.datetime.now(_dt.UTC)
+ if fetched is None or (current - fetched).days >= max_age_days:
+ return None
+ return table
+
+
+def _parse_iso(text: str) -> _dt.datetime | None:
+ try:
+ value = _dt.datetime.fromisoformat(text)
+ except (TypeError, ValueError):
+ return None
+ return value if value.tzinfo is not None else value.replace(tzinfo=_dt.UTC)
+
+
+def curated_only(note: str = "") -> BenchmarkTable:
+ """An empty table that says so — the honest offline answer."""
+ return BenchmarkTable(
+ fetched_at="",
+ rows=(),
+ library={},
+ source="curated",
+ note=note or "No benchmark data reachable; showing the curated shortlist only.",
+ )
+
+
+# ── Refresh ───────────────────────────────────────────────────────────────
+
+
+async def _call(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
+ """Call a sync or async seam uniformly."""
+ result = fn(*args, **kwargs)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+
+
+async def _library_facts(
+ family: str, library_fn: Callable[[str], Awaitable[dict[str, Any]]]
+) -> LibraryFacts | None:
+ try:
+ payload = await library_fn(family)
+ except Exception: # noqa: BLE001 — the library is advisory; log and go on
+ log.info("benchmarks: library lookup for %s failed", family, exc_info=True)
+ return None
+ if not isinstance(payload, dict) or payload.get("error"):
+ return None
+ for entry in payload.get("models") or []:
+ if isinstance(entry, dict) and str(entry.get("name") or "") == family:
+ return LibraryFacts(
+ family=family,
+ pulls=parse_pulls(str(entry.get("pulls") or "")),
+ updated_days=parse_updated_days(str(entry.get("updated") or "")),
+ )
+ return None
+
+
+async def _default_library_fn(family: str) -> dict[str, Any]:
+ from jarvis.brain.ollama_library import search_library
+
+ return await search_library(family, limit=10)
+
+
+async def refresh_benchmarks(
+ search_fn: SearchFn,
+ *,
+ families: Iterable[str] | None = None,
+ library_fn: Callable[[str], Awaitable[dict[str, Any]]] | None = None,
+ now: _dt.datetime | None = None,
+ persist: bool = True,
+) -> BenchmarkTable:
+ """Rebuild the table: three concurrent searches per family plus the library.
+
+ ``search_fn(query)`` returns (or resolves to) a list of
+ ``{title, url, snippet}`` dicts; one failing query loses only its rows.
+ When EVERY query failed or answered nothing and the library is silent too,
+ the cached table (any age) or a curated-only table is returned with a
+ note — the shortlist must render offline.
+ """
+ fams = tuple(families) if families is not None else curated_families()
+ stamp = (now or _dt.datetime.now(_dt.UTC)).isoformat(timespec="seconds")
+ lib_fn = library_fn or _default_library_fn
+
+ async def _search(family: str, source: str, template: str) -> list[BenchmarkRow]:
+ query = template.format(family=family)
+ try:
+ results = await _call(search_fn, query)
+ except Exception: # noqa: BLE001 — one failed query loses only its rows
+ log.info("benchmarks: search %r failed", query, exc_info=True)
+ return []
+ if not isinstance(results, list):
+ return []
+ return extract_rows(family, results, source=source, seen_at=stamp)
+
+ searches = [
+ _search(family, source, template) for family in fams for source, template in QUERY_TEMPLATES
+ ]
+ lookups = [_library_facts(family, lib_fn) for family in fams]
+ search_results, library_results = await asyncio.gather(
+ asyncio.gather(*searches), asyncio.gather(*lookups)
+ )
+
+ rows: list[BenchmarkRow] = [row for batch in search_results for row in batch]
+ library = {facts.family: facts for facts in library_results if facts is not None}
+
+ if not rows and not library:
+ cached = load_cached(max_age_days=None)
+ if cached is not None:
+ note = "Benchmark sources unreachable; showing the cached table."
+ return BenchmarkTable(cached.fetched_at, cached.rows, cached.library, "cache", note)
+ return curated_only()
+
+ table = BenchmarkTable(fetched_at=stamp, rows=tuple(rows), library=library, source="live")
+ if persist:
+ _atomic_write_json(cache_path(), table.to_payload())
+ return table
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 16f6a37084..d622130d7c 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -46,6 +46,7 @@ from fastapi import (
from pydantic import BaseModel, Field
from jarvis.agent_chat import attachments as chat_attachments
+from jarvis.agent_chat import typeahead
from jarvis.agent_chat.catalog import CLAUDE_CODE_MODELS, offers, rows_for
from jarvis.agent_chat.effort import normalize_effort
from jarvis.agent_chat.events import make_event
@@ -70,12 +71,12 @@ log = logging.getLogger(__name__)
#: The Pydantic twin of ``jarvis.agent_chat.store.SURFACES`` (AP-4; the parity
#: test in tests/unit/agent_chat/test_agent_chat_surface_parity.py pins it).
-SurfaceName = Literal["jarvis", "agent"]
+SurfaceName = Literal["jarvis", "agent", "local-models"]
#: The same names, as data — a multipart form field cannot be typed by a
#: ``Literal`` without turning an unknown surface into a 422 on a file the
#: person just dropped.
-SURFACE_NAMES: frozenset[str] = frozenset({"jarvis", "agent"})
+SURFACE_NAMES: frozenset[str] = frozenset({"jarvis", "agent", "local-models"})
router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
@@ -93,8 +94,9 @@ class CreateSessionBody(BaseModel):
#: "" = the runner's default mode (jarvis/agent_chat/permissions.py).
permission_mode: str = ""
title: str = ""
- #: Which chat the session belongs to — the front page ("jarvis") or the
- #: Agentic IDE's chat mode ("agent"). Fixed for the session's life.
+ #: Which chat the session belongs to — the front page ("jarvis"), the
+ #: Agentic IDE's chat mode ("agent"), or the Local models section's setup
+ #: assistant ("local-models"). Fixed for the session's life.
surface: SurfaceName = "agent"
@@ -254,6 +256,10 @@ async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[
ladder = ladder_key(surface, runner)
d["permission_modes"] = [m.to_dict() for m in permission_modes(ladder)]
d["default_permission_mode"] = default_permission(ladder)
+ # Which characters open the composer's typeahead on this seat —
+ # decided here, from the runner, so the box never offers a "/" list
+ # to a seat that would read it as plain text.
+ d["typeahead"] = list(typeahead.triggers_for(runner))
rows.append(d)
return {
"providers": rows,
@@ -262,6 +268,40 @@ async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[
}
+# ----------------------------------------------------------- typeahead
+
+
[email protected]("/typeahead", openapi_extra={"x-jarvis-readonly": True})
+async def get_typeahead(
+ request: Request,
+ trigger: str = Query(..., min_length=1, max_length=1),
+ surface: SurfaceName = "agent",
+ provider: str = "",
+ cwd: str | None = None,
+ q: str = Query("", max_length=200),
+ limit: int = Query(40, ge=1, le=200),
+) -> dict[str, Any]:
+ """What the composer lists after ``/``, ``@`` or ``$`` on one seat.
+
+ The seat is (surface, provider) resolved to its runner exactly as a turn
+ would be; the folder is the chat's. Rows are read from the disk that
+ runner reads (``jarvis.agent_chat.typeahead``) — the account's skills,
+ commands and plugins, the folder's own, or the files under it — and a
+ trigger the seat does not honour answers with an empty list.
+ """
+ svc = _service(request)
+ runner = resolve_runner(provider, surface=surface) if provider else "api"
+ folder = _validate_cwd(cwd) or svc.default_cwd(surface)
+ return await asyncio.to_thread(
+ typeahead.suggest,
+ runner=runner,
+ cwd=folder,
+ trigger=trigger,
+ query=q,
+ limit=limit,
+ )
+
+
# ------------------------------------------------------------- health
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 1ffcdb1e5a..be93e9525e 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -42,6 +42,12 @@ export interface AgentChatProvider {
default_permission_mode: string;
/** null for the API runner; else whether the vendor binary is on PATH. */
cli_installed: boolean | null;
+ /**
+ * The characters that open the composer's typeahead on this seat — a
+ * subset of "/", "@", "$" decided by the runner (jarvis/agent_chat/typeahead.py).
+ * Absent on an older backend: then nothing opens.
+ */
+ typeahead?: string[];
}
export interface AgentChatCatalog {
@@ -57,7 +63,13 @@ export interface AgentChatCatalog {
* and catalog, so they never mix in a sidebar. Mirrors `SURFACES` in
* `jarvis/agent_chat/store.py` (a parity test reads this union).
*/
-export type AgentChatSurface = "jarvis" | "agent";
+/**
+ * Where a person is typing. Each surface is its own session list, socket
+ * and draft, and the backend keeps one turn recipe per name
+ * (``jarvis/agent_chat/surface_kits.py``): the front page, the coding
+ * agents, and the Local models section's setup assistant.
+ */
+export type AgentChatSurface = "jarvis" | "agent" | "local-models";
export interface AgentChatSession {
session_id: string;
@@ -151,6 +163,43 @@ export async function fetchAgentChatCatalog(surface?: AgentChatSurface): Promise
return json(await fetch(`/api/agent-chat/catalog${query}`), "catalog-failed");
}
+export interface TypeaheadRow {
+ value: string;
+ label: string;
+ hint: string;
+ kind: string;
+ group: string;
+}
+
+/**
+ * What the composer lists after a trigger character on one seat — read from
+ * the disk that seat's runner reads (`GET /api/agent-chat/typeahead`).
+ */
+export async function fetchTypeahead(
+ input: {
+ surface: AgentChatSurface;
+ provider: string;
+ cwd: string;
+ trigger: string;
+ q: string;
+ limit?: number;
+ },
+ signal?: AbortSignal,
+): Promise<{ trigger: string; items: TypeaheadRow[]; truncated: boolean }> {
+ const params = new URLSearchParams({
+ surface: input.surface,
+ provider: input.provider,
+ trigger: input.trigger,
+ q: input.q,
+ limit: String(input.limit ?? 40),
+ });
+ if (input.cwd) params.set("cwd", input.cwd);
+ return json(
+ await fetch(`/api/agent-chat/typeahead?${params.toString()}`, { signal }),
+ "typeahead-failed",
+ );
+}
+
/**
* Which seats actually answer. Slow by nature — it makes one real request per
* provider — so callers fire it beside the catalog and never await it before
diff --git a/jarvis/ui/web/local_models_assistant_routes.py b/jarvis/ui/web/local_models_assistant_routes.py
new file mode 100644
index 0000000000..9ab78481f4
--- /dev/null
+++ b/jarvis/ui/web/local_models_assistant_routes.py
@@ -0,0 +1,202 @@
+"""REST for the Local models setup assistant.
+
+ POST /api/providers/{provider_id}/local-models/assistant/run start a guided turn
+ GET /api/providers/{provider_id}/local-models/assistant/session the one session + tier
+ POST /api/providers/{provider_id}/local-models/assistant/test end-to-end setup test
+ GET /api/providers/{provider_id}/local-models/assistant/benchmarks the proven/new table
+ GET /api/providers/{provider_id}/local-models/assistant/health the badge record
+
+The assistant is a ``local-models`` agent-chat session (the timeline, the
+WebSocket stream and the approval cards are the agent chat's — see
+``agent_chat_routes.py``); these routes only start it with the canned opener
+of a mode and expose the runner, the benchmark table and the health file.
+Every handler sits behind the pull-capability gate the section uses
+(``provider_routes._require_pull_capable``). ``/run`` answers 409 with one
+English sentence when the Jarvis-Agents tier cannot run — never a silent
+fallback.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel, Field
+
+from jarvis.ui.web.agent_chat_routes import _service_from_state
+from jarvis.ui.web.provider_routes import (
+ _require_pull_capable,
+ _resolve_cfg,
+ _worker_flagged_dead,
+ _worker_usable,
+)
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(
+ prefix="/api/providers/{provider_id}/local-models/assistant",
+ tags=["local-models-assistant"],
+)
+
+Mode = Literal["setup", "diagnose", "test"]
+
+
+class RunBody(BaseModel):
+ mode: Mode = "setup"
+
+
+class RunResponse(BaseModel):
+ session_id: str
+ turn_id: str
+ surface: str = "local-models"
+
+
+class SessionResponse(BaseModel):
+ session_id: str | None
+ surface: str = "local-models"
+ provider: str
+ model: str
+ ready: bool
+ reason: str
+
+
+class TestBody(BaseModel):
+ roles: list[str] | None = Field(default=None, description="Subset of the writable roles.")
+
+
+class HealthResponse(BaseModel):
+ status: str
+ reason: str
+ since: str | None = None
+ last_ok: str | None = None
+ checked_at: str | None = None
+
+
+def _opener(mode: str) -> str:
+ from jarvis.local_models.assistant_prompt import (
+ DIAGNOSE_OPENER,
+ SETUP_OPENER,
+ TEST_OPENER,
+ )
+
+ return {"setup": SETUP_OPENER, "diagnose": DIAGNOSE_OPENER, "test": TEST_OPENER}[mode]
+
+
+def _usable(provider: str) -> bool:
+ """The provider-agnostic worker check the API-keys page uses."""
+ from jarvis.local_models.assistant_session import _default_usable
+
+ return (_worker_usable(provider) or _default_usable(provider)) and not _worker_flagged_dead(
+ provider
+ )
+
+
+async def _live(cfg: Any) -> dict[tuple[str, str], tuple[bool, str]]:
+ """One real call per candidate pair (cached ten minutes): a key that
+ authenticates but is refused for quota is not a working assistant."""
+ from jarvis.local_models.assistant_session import chain_candidates, probe_live
+
+ return await probe_live(cfg, chain_candidates(cfg, usable=_usable))
+
+
+def _svc(request: Request) -> Any:
+ svc = _service_from_state(request.app.state)
+ if svc is None:
+ raise HTTPException(status_code=503, detail="agent-chat-unavailable")
+ return svc
+
+
+def _cfg(request: Request) -> Any:
+ cfg = _resolve_cfg(request)
+ if cfg is None:
+ raise HTTPException(status_code=503, detail="Configuration is unavailable (headless mode?)")
+ return cfg
+
+
[email protected]("/run", response_model=RunResponse)
+async def post_run(provider_id: str, body: RunBody, request: Request) -> RunResponse:
+ """Start a guided turn: ensure the one session, send the mode's opener."""
+ from jarvis.agent_chat.service import SessionBusy
+ from jarvis.local_models.assistant_session import ensure_session
+
+ _require_pull_capable(provider_id)
+ cfg = _cfg(request)
+ svc = _svc(request)
+ live = await _live(cfg)
+ try:
+ session = ensure_session(svc, cfg, usable=_usable, live=live)
+ except PermissionError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ try:
+ turn_id = await svc.send(session.session_id, _opener(body.mode))
+ except SessionBusy as exc:
+ raise HTTPException(
+ status_code=409, detail="The assistant is still answering; wait for that turn."
+ ) from exc
+ return RunResponse(session_id=session.session_id, turn_id=turn_id)
+
+
[email protected]("/session", response_model=SessionResponse)
+async def get_session(provider_id: str, request: Request) -> SessionResponse:
+ """The one ``local-models`` session (or null) and whether the tier can run."""
+ from jarvis.local_models.assistant_session import session_state
+
+ _require_pull_capable(provider_id)
+ cfg = _cfg(request)
+ svc = _svc(request)
+ live = await _live(cfg)
+ return SessionResponse(**session_state(svc, cfg, usable=_usable, live=live))
+
+
+async def post_test(provider_id: str, request: Request, body: TestBody | None = None) -> dict:
+ """Run the end-to-end setup test and persist the report."""
+ from jarvis.local_models.assistant_test import run_setup_test
+
+ _require_pull_capable(provider_id)
+ cfg = _cfg(request)
+ roles = tuple(body.roles) if body is not None and body.roles else None
+ try:
+ report = await run_setup_test(cfg, roles)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return report.to_payload()
+
+
[email protected]("/benchmarks")
+async def get_benchmarks(provider_id: str, request: Request, refresh: bool = False) -> dict:
+ """The benchmark table; ``refresh=1`` rebuilds it through the brain's web search."""
+ from jarvis.local_models import benchmarks
+
+ _require_pull_capable(provider_id)
+ table: benchmarks.BenchmarkTable | None
+ if refresh:
+ from jarvis.agent_chat.runner_brain import brain_manager
+ from jarvis.agent_chat.surface_kits import local_models_search_fn
+
+ search_fn = local_models_search_fn(brain_manager())
+ if search_fn is None:
+ raise HTTPException(
+ status_code=503, detail="Web search is not available yet; try again shortly."
+ )
+ table = await benchmarks.refresh_benchmarks(search_fn)
+ else:
+ table = benchmarks.load_cached() or benchmarks.curated_only(
+ "No benchmark cache yet; refresh=1 builds one."
+ )
+ return table.to_payload()
+
+
[email protected]("/health", response_model=HealthResponse)
+async def get_health(provider_id: str) -> HealthResponse:
+ """The persisted badge record — a file read, no live call."""
+ from jarvis.local_models.health_monitor import read_health_record
+
+ _require_pull_capable(provider_id)
+ return HealthResponse(**read_health_record())
+
+
+__all__ = ["router"]
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 2574222d5a..4171d6ae94 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -367,6 +367,9 @@ class WebServer:
from .friends_routes import router as friends_router
from .frontier_routes import router as frontier_router
from .grok_build_routes import router as grok_build_router
+ from .local_models_assistant_routes import (
+ router as local_models_assistant_router,
+ )
from .local_models_routes import router as local_models_router
from .marketplace_publish_routes import router as marketplace_publish_router
from .marketplace_routes import router as marketplace_router
@@ -436,6 +439,9 @@ class WebServer:
# Local models section: inventory / unload / delete behind the
# pull-capable card (same capability gate as the pull routes).
app.include_router(local_models_router)
+ # The section's setup assistant — same capability gate, its own chat
+ # surface on the Agents tier.
+ app.include_router(local_models_assistant_router)
app.include_router(antigravity_router)
app.include_router(claude_router)
app.include_router(grok_build_router)
diff --git a/tests/unit/local_models/test_assistant_session.py b/tests/unit/local_models/test_assistant_session.py
new file mode 100644
index 0000000000..f4fbffad37
--- /dev/null
+++ b/tests/unit/local_models/test_assistant_session.py
@@ -0,0 +1,149 @@
+"""Session policy: the Agents-tier pair, one session per install, an honest refusal."""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig
+from jarvis.local_models import assistant_session as policy
+
+
+def _cfg(provider: str = "openai", model: str = "gpt-x", **fallback: str) -> JarvisConfig:
+ cfg = JarvisConfig()
+ cfg.brain.worker = BrainTierConfig(provider=provider, model=model, **fallback)
+ return cfg
+
+
+def _svc() -> AgentChatService:
+ return AgentChatService(AgentChatStore(":memory:"))
+
+
+def test_tier_is_the_worker_pair_and_ready_only_with_a_credential() -> None:
+ ready = policy.agents_tier(_cfg(), usable=lambda p: p == "openai")
+ assert (ready.provider, ready.model, ready.ready, ready.reason) == ("openai", "gpt-x", True, "")
+ blocked = policy.agents_tier(_cfg(), usable=lambda _p: False)
+ assert blocked.ready is False and blocked.reason == policy.NOT_READY
+
+
+def test_unknown_primary_falls_back_to_the_fallback_pair() -> None:
+ cfg = _cfg("some-cli-only-thing", "m", fallback_provider="gemini", fallback_model="g-2")
+ tier = policy.agents_tier(cfg, usable=lambda _p: True)
+ assert (tier.provider, tier.model) == ("gemini", "g-2")
+
+
+def test_a_cli_only_primary_yields_to_the_tool_capable_fallback() -> None:
+ """Antigravity drives a CLI on a flat prompt and drops every tool; the
+ assistant needs its lm_* tools, so the chain moves on to a fallback that
+ can call them — and says why when none can."""
+ cfg = _cfg("antigravity", "gemini-3.5-flash", fallback_provider="gemini", fallback_model="g-2")
+ tier = policy.agents_tier(
+ cfg, usable=lambda _p: True, tool_capable=lambda p: p != "antigravity"
+ )
+ assert (tier.provider, tier.model, tier.ready) == ("gemini", "g-2", True)
+ stuck = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: False)
+ assert stuck.ready is False and stuck.reason == policy.NO_TOOLS
+
+
+def test_the_real_antigravity_plugin_reports_no_tools() -> None:
+ assert policy._tool_capable("antigravity") is False
+ assert policy._tool_capable("gemini") is True
+
+
+def test_no_worker_tier_is_not_ready() -> None:
+ cfg = JarvisConfig()
+ cfg.brain.worker = None
+ tier = policy.agents_tier(cfg, usable=lambda _p: True)
+ assert tier.ready is False and tier.reason == policy.NOT_READY
+
+
+def test_ensure_session_creates_once_and_recreates_when_the_tier_moves() -> None:
+ svc = _svc()
+ cfg = _cfg()
+ first = policy.ensure_session(svc, cfg, usable=lambda _p: True)
+ again = policy.ensure_session(svc, cfg, usable=lambda _p: True)
+ assert first.session_id == again.session_id
+ assert first.surface == "local-models" and first.provider == "openai"
+ assert first.permission_mode == "ask"
+
+ moved = policy.ensure_session(svc, _cfg(model="gpt-y"), usable=lambda _p: True)
+ assert moved.session_id != first.session_id and moved.model == "gpt-y"
+ assert len(svc.store.list_sessions(surface="local-models")) == 2
+
+
+def test_ensure_session_refuses_without_the_tier() -> None:
+ svc = _svc()
+ with pytest.raises(PermissionError, match="Pick a Tool Model with an API key first"):
+ policy.ensure_session(svc, _cfg(), usable=lambda _p: False)
+ assert svc.store.list_sessions(surface="local-models") == []
+
+
+def test_session_state_shape() -> None:
+ svc = _svc()
+ cfg = _cfg()
+ assert policy.session_state(svc, cfg, usable=lambda _p: True) == {
+ "session_id": None,
+ "surface": "local-models",
+ "provider": "openai",
+ "model": "gpt-x",
+ "ready": True,
+ "reason": "",
+ }
+ session = policy.ensure_session(svc, cfg, usable=lambda _p: True)
+ state = policy.session_state(svc, cfg, usable=lambda _p: False)
+ assert state["session_id"] == session.session_id
+ assert state["ready"] is False and state["reason"] == policy.NOT_READY
+
+
+def test_a_pair_the_live_probe_refuses_yields_to_the_next_and_names_the_reason() -> None:
+ cfg = _cfg("gemini", "g-pro", fallback_provider="openai", fallback_model="o-1")
+ live = {
+ ("gemini", "g-pro"): (False, "gemini (g-pro): no credits — quota 0"),
+ ("openai", "o-1"): (True, ""),
+ }
+ tier = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: True, live=live)
+ assert (tier.provider, tier.model, tier.ready) == ("openai", "o-1", True)
+ live[("openai", "o-1")] = (False, "openai (o-1): bad key")
+ stuck = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: True, live=live)
+ assert stuck.ready is False and stuck.reason == "openai (o-1): bad key"
+
+
+async def test_probe_live_classifies_with_the_provider_test_and_caches() -> None:
+ from jarvis.brain.provider_test import ProviderTestResult
+
+ policy._reset_for_tests()
+ calls: list[tuple[str, str | None]] = []
+
+ async def _tester(spec, cfg, *, model=None, timeout_s=20.0):
+ calls.append((spec.id, model))
+ status = "no_credits" if spec.id == "gemini" else "ok"
+ return ProviderTestResult(provider=spec.id, status=status, detail="quota 0")
+
+ cfg = _cfg("gemini", "g-pro", fallback_provider="openai", fallback_model="o-1")
+ pairs = policy.chain_candidates(cfg, usable=lambda _p: True, tool_capable=lambda _p: True)
+ out = await policy.probe_live(cfg, pairs, tester=_tester)
+ assert out[("gemini", "g-pro")] == (
+ False,
+ "gemini (g-pro): the account has no credit or quota left for this model.",
+ )
+ assert out[("openai", "o-1")] == (True, "")
+ again = await policy.probe_live(cfg, pairs, tester=_tester)
+ assert again == out and len(calls) == 2 # cached, no second real call
+
+
+def test_the_tool_model_comes_first_and_the_agents_chain_is_the_fallback() -> None:
+ """The user answers "which model does my own work" once, in the Tool
+ Model tab; the assistant honours that pick and bills through its key."""
+ cfg = _cfg("openai", "gpt-x")
+ cfg.brain.tool_model = BrainTierConfig(provider="vertex")
+ cfg.brain.providers["vertex"] = BrainProviderConfig(tool_model="gemini-3.6-flash")
+ assert policy._chain(cfg)[0] == ("vertex", "gemini-3.6-flash")
+ tier = policy.agents_tier(cfg, usable=lambda _p: True, tool_capable=lambda _p: True)
+ assert (tier.provider, tier.model) == ("vertex", "gemini-3.6-flash")
+ # An unusable Tool Model falls back to the Agents chain, honestly.
+ tier = policy.agents_tier(cfg, usable=lambda p: p != "vertex", tool_capable=lambda _p: True)
+ assert (tier.provider, tier.model) == ("openai", "gpt-x")
+ cfg.brain.tool_model = BrainTierConfig(provider="auto")
+ assert policy._chain(cfg)[0] == ("openai", "gpt-x")
diff --git a/tests/unit/local_models/test_assistant_test.py b/tests/unit/local_models/test_assistant_test.py
new file mode 100644
index 0000000000..44f4b8924f
--- /dev/null
+++ b/tests/unit/local_models/test_assistant_test.py
@@ -0,0 +1,202 @@
+"""The setup test runner: one real call per configured role, an honest table.
+
+Fakes only: the Ollama server is :class:`tests.fakes.fake_ollama_server.FakeOllamaServer`
+over ``httpx.MockTransport``; the 1-token generation and the voice probe go
+through the runner's injectable seams.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.brain import ollama_inventory as inventory
+from jarvis.core import config as cfg_mod
+from jarvis.core.config import BrainProviderConfig, JarvisConfig
+from jarvis.local_models import assistant_test
+from jarvis.local_models.assistant_test import NOT_SET, run_setup_test
+from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+
+class _HealthResult:
+ def __init__(self, ok: bool, error: str | None) -> None:
+ self.ok = ok
+ self.error = error
+ self.duration_ms = 12.0
+
+
+class _Probe:
+ """Records the generation probes and answers ok unless told otherwise."""
+
+ def __init__(self, failing: dict[str, str] | None = None) -> None:
+ self.calls: list[tuple[str, str]] = []
+ self.failing = failing or {}
+
+ async def __call__(self, provider: str, model: str) -> Any:
+ self.calls.append((provider, model))
+ return _HealthResult(model not in self.failing, self.failing.get(model))
+
+
+def _cfg(**picks: str) -> JarvisConfig:
+ cfg = JarvisConfig()
+ cfg.brain.providers["ollama"] = BrainProviderConfig(
+ model=picks.get("chat", ""),
+ tool_model=picks.get("tools_screen", ""),
+ deep_model=picks.get("deep", ""),
+ base_url="http://fake-ollama:11434",
+ )
+ cfg.ultrawiki.embedding_provider = "ollama"
+ cfg.ultrawiki.embedding_model = picks.get("embedding", "")
+ return cfg
+
+
+def _server() -> FakeOllamaServer:
+ fake = FakeOllamaServer()
+ fake.add("qwen3.5:4b", capabilities=("completion", "tools", "vision"))
+ fake.add("chatonly:7b", capabilities=("completion",))
+ fake.add("embeddinggemma", capabilities=("embedding",), embed_dim=768)
+ return fake
+
+
[email protected](autouse=True)
+def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)
+ return tmp_path
+
+
+async def test_embed_probe_returns_the_vector_length() -> None:
+ fake = _server()
+ dim = await inventory.embed_probe("http://x", "embeddinggemma", transport=fake.transport())
+ assert dim == 768
+ assert ("POST", "/api/embed", {"model": "embeddinggemma", "input": "ping"}) in fake.calls
+ with pytest.raises(inventory.OllamaModelNotFound):
+ await inventory.embed_probe("http://x", "nope", transport=fake.transport())
+
+
+async def test_full_setup_answers_ok_per_role_and_persists(tmp_path: Path) -> None:
+ fake = _server()
+ probe = _Probe()
+ cfg = _cfg(
+ chat="qwen3.5:4b", tools_screen="qwen3.5:4b", deep="qwen3.5:4b", embedding="embeddinggemma"
+ )
+ report = await run_setup_test(cfg, transport=fake.transport(), brain_probe=probe)
+
+ assert isinstance(report, assistant_test.TestReport)
+ assert report.server["ok"] is True and report.server["version"] == "0.32.15"
+ assert {r: c.status for r, c in report.roles.items()} == {
+ "chat": "ok",
+ "tools_screen": "ok",
+ "deep": "ok",
+ "embedding": "ok",
+ "voice": NOT_SET,
+ }
+ assert report.voice is None
+ assert report.overall == "ok"
+ # Exactly one real generation per generation role, on the Ollama provider.
+ assert probe.calls == [("ollama", "qwen3.5:4b")] * 3
+ # Persisted to the state file with the badge keys the monitor also writes.
+ written = json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))
+ assert written["status"] == "ok" and written["overall"] == "ok"
+ assert written["roles"]["embedding"]["detail"] == "Embeds (768 dimensions)."
+ assert written["last_ok"] == written["checked_at"] == report.checked_at
+ assert report.to_payload()["roles"]["chat"]["model"] == "qwen3.5:4b"
+
+
+async def test_tools_screen_needs_declared_tools_and_vision() -> None:
+ fake = _server()
+ cfg = _cfg(tools_screen="chatonly:7b")
+ report = await run_setup_test(
+ cfg, ("tools_screen",), transport=fake.transport(), brain_probe=_Probe()
+ )
+ check = report.roles["tools_screen"]
+ assert check.status == "error"
+ assert "tools + vision" in check.detail
+ assert report.overall == "error"
+ assert report.reason().startswith("tools_screen:")
+
+
+async def test_nothing_configured_is_needs_setup_not_error() -> None:
+ fake = _server()
+ report = await run_setup_test(_cfg(), transport=fake.transport(), brain_probe=_Probe())
+ assert all(c.status == NOT_SET for c in report.roles.values())
+ assert report.overall == "needs_setup"
+ assert report.reason() == ""
+
+
+async def test_server_down_marks_every_configured_role_unreachable() -> None:
+ fake = _server()
+ fake.offline = True
+ probe = _Probe()
+ cfg = _cfg(chat="qwen3.5:4b", embedding="embeddinggemma")
+ report = await run_setup_test(cfg, transport=fake.transport(), brain_probe=probe)
+ assert report.server["ok"] is False
+ assert report.roles["chat"].status == "unreachable"
+ assert report.roles["embedding"].status == "unreachable"
+ assert probe.calls == [], "no generation is attempted against a dead server"
+ assert report.overall == "error"
+
+
+async def test_generation_failure_is_classified_with_the_provider_vocabulary() -> None:
+ fake = _server()
+ cfg = _cfg(chat="qwen3.5:4b")
+ probe = _Probe(failing={"qwen3.5:4b": "model 'qwen3.5:4b' not found (404)"})
+ report = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=probe)
+ assert report.roles["chat"].status == "model_unavailable"
+
+
+async def test_voice_probe_runs_only_for_the_managed_server() -> None:
+ fake = _server()
+ seen: list[str] = []
+
+ async def voice_probe(base_url: str) -> dict[str, Any]:
+ seen.append(base_url)
+ return {"ok": True, "first_audio_ms": 640}
+
+ cfg = _cfg(chat="qwen3.5:4b")
+ cfg.brain.providers["local-realtime"] = BrainProviderConfig(
+ launch_command="python server.py --model_name qwen3.5:4b --port 8765",
+ base_url="http://127.0.0.1:8765",
+ )
+ report = await run_setup_test(
+ cfg,
+ ("chat", "voice"),
+ transport=fake.transport(),
+ brain_probe=_Probe(),
+ voice_probe=voice_probe,
+ )
+ assert seen == ["http://127.0.0.1:8765"]
+ assert report.voice == {
+ "ok": True,
+ "first_audio_ms": 640,
+ "detail": "Voice round trip answered with audio.",
+ }
+ assert report.roles["voice"].status == "ok"
+ assert report.roles["voice"].latency_ms == 640
+ assert report.overall == "ok"
+
+ # A bring-your-own command (no --model_name) is never probed.
+ cfg.brain.providers["local-realtime"].launch_command = "my-own-server --port 8765"
+ report = await run_setup_test(
+ cfg, ("voice",), transport=fake.transport(), brain_probe=_Probe(), voice_probe=voice_probe
+ )
+ assert seen == ["http://127.0.0.1:8765"]
+ assert report.voice is None and report.roles["voice"].status == NOT_SET
+
+
+async def test_unknown_role_is_refused() -> None:
+ with pytest.raises(ValueError, match="Unknown role"):
+ await run_setup_test(_cfg(), ("chat", "ack"), transport=_server().transport())
+
+
+async def test_since_is_kept_while_the_status_holds() -> None:
+ fake = _server()
+ cfg = _cfg(chat="qwen3.5:4b")
+ first = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=_Probe())
+ second = await run_setup_test(cfg, ("chat",), transport=fake.transport(), brain_probe=_Probe())
+ written = assistant_test.load_last_report()
+ assert written is not None
+ assert written["since"] == first.checked_at
+ assert written["checked_at"] == second.checked_at
diff --git a/tests/unit/local_models/test_assistant_tools.py b/tests/unit/local_models/test_assistant_tools.py
new file mode 100644
index 0000000000..4529a6197f
--- /dev/null
+++ b/tests/unit/local_models/test_assistant_tools.py
@@ -0,0 +1,284 @@
+"""The assistant's tools: allowed tiers only, no delete, ask-tier through the executor.
+
+Every action tool is exercised through a REAL ``ToolExecutor`` (bus, tier
+evaluator, approval workflow — no mocks) on the ``interactive`` surface, so
+the approval card the panel auto-answers is a genuine ticket, not a
+convention.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+from pathlib import Path
+from uuid import uuid4
+
+import pytest
+
+from jarvis.core import config as cfg_mod
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, JarvisConfig, SafetyConfig
+from jarvis.core.events import ActionApprovalRequired, ActionDenied, ActionExecuted
+from jarvis.core.protocols import ExecutionContext
+from jarvis.local_models import assistant_prompt, assistant_tools
+from jarvis.local_models.assistant_tools import ALLOWED_TIERS, TOOL_PREFIX, build_tools
+from jarvis.safety.approval import ApprovalWorkflow
+from jarvis.safety.approval_surface import INTERACTIVE
+from jarvis.safety.risk_tier import RiskTierEvaluator
+from jarvis.safety.tool_executor import APPROVAL_DENIED_PREFIX, ToolExecutor
+from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+ROOT = "http://fake-ollama:11434"
+
+ASK_TOOLS = {
+ "lm_install_ollama",
+ "lm_start_server",
+ "lm_stop_server",
+ "lm_pull",
+ "lm_set_role",
+ "lm_set_model_options",
+ "lm_install_voice_server",
+ "lm_apply_voice_stack",
+}
+
+
+def _cfg(*, hf: bool = False, **picks: str) -> JarvisConfig:
+ cfg = JarvisConfig()
+ cfg.brain.providers["ollama"] = BrainProviderConfig(
+ model=picks.get("chat", ""),
+ tool_model=picks.get("tools_screen", ""),
+ deep_model=picks.get("deep", ""),
+ base_url=ROOT,
+ hf_enabled=hf,
+ )
+ cfg.ultrawiki.embedding_provider = "ollama"
+ cfg.ultrawiki.embedding_model = picks.get("embedding", "")
+ return cfg
+
+
+def _server() -> FakeOllamaServer:
+ fake = FakeOllamaServer()
+ fake.add("qwen3.5:4b", size=3_400_000_000, capabilities=("completion", "tools", "vision"))
+ fake.add("embeddinggemma", size=600_000_000, capabilities=("embedding",), embed_dim=768)
+ fake.load("qwen3.5:4b")
+ return fake
+
+
+def _ctx() -> ExecutionContext:
+ return ExecutionContext(trace_id=uuid4(), user_utterance="", config={}, memory_read=None)
+
+
+def _executor(timeout_s: float = 5.0) -> tuple[ToolExecutor, EventBus]:
+ bus = EventBus()
+ executor = ToolExecutor(
+ bus,
+ RiskTierEvaluator(SafetyConfig()),
+ ApprovalWorkflow(bus, timeout_s=timeout_s),
+ default_timeout_s=timeout_s,
+ )
+ return executor, bus
+
+
[email protected](autouse=True)
+def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)
+ return tmp_path
+
+
+# ------------------------------------------------------------ the tool set
+
+
+def test_every_tool_has_an_allowed_tier_and_the_prefix() -> None:
+ tools = build_tools(_cfg(hf=True), root=ROOT)
+ assert tools, "no tools built"
+ for name, tool in tools.items():
+ assert name == tool.name
+ assert name.startswith(TOOL_PREFIX), name
+ assert tool.risk_tier in ALLOWED_TIERS, (name, tool.risk_tier)
+ assert tool.schema.get("type") == "object"
+ assert tool.description
+ assert {n for n, t in tools.items() if t.risk_tier == "ask"} == ASK_TOOLS
+ assert {n for n, t in tools.items() if t.risk_tier == "monitor"} == {"lm_unload"}
+ assert "lm_test_plan" in tools and tools["lm_test_plan"].risk_tier == "safe"
+
+
+def test_no_delete_tool_and_nothing_writes_the_brain_primary() -> None:
+ tools = build_tools(_cfg(hf=True), root=ROOT)
+ for name in tools:
+ assert not any(word in name for word in ("delete", "remove", "rm_", "uninstall")), name
+ source = inspect.getsource(assistant_tools)
+ assert "set_brain_primary" not in source
+ assert "delete_model" not in source
+ assert "switch_provider" not in source
+
+
+def test_hf_search_is_offered_only_when_enabled() -> None:
+ assert "lm_hf_search" not in build_tools(_cfg(hf=False), root=ROOT)
+ assert "lm_hf_search" in build_tools(_cfg(hf=True), root=ROOT)
+
+
+def test_describe_args_is_the_card_summary() -> None:
+ tools = build_tools(_cfg(), root=ROOT)
+ assert tools["lm_pull"].describe_args({"model": "qwen3.5:4b"}) == { # type: ignore[attr-defined]
+ "summary": "Download qwen3.5:4b"
+ }
+ assert tools["lm_set_role"].describe_args({"role": "chat", "model": "x"}) == { # type: ignore[attr-defined]
+ "summary": "Use x for chat"
+ }
+ assert tools["lm_inventory"].describe_args({}) == {} # type: ignore[attr-defined]
+
+
+# ------------------------------------------------------------ reads through the executor
+
+
+async def test_safe_reads_run_through_the_executor_on_the_fake_server() -> None:
+ fake = _server()
+ tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())
+ executor, _bus = _executor()
+
+ inventory = await executor.execute(
+ tools["lm_inventory"], args={}, config_snapshot={"approval_surface": INTERACTIVE}
+ )
+ assert inventory.success, inventory.error
+ names = {row["name"] for row in inventory.output["models"]}
+ assert names == {"qwen3.5:4b", "embeddinggemma"}
+ assert [r["name"] for r in inventory.output["running"]] == ["qwen3.5:4b"]
+
+ status = await executor.execute(tools["lm_server_status"], args={})
+ assert status.success, status.error
+ assert status.output["probe"]["ok"] is True
+ assert status.output["voice"]["status"] is None
+
+
+async def test_test_plan_tool_reports_per_role() -> None:
+ fake = _server()
+ tools = build_tools(_cfg(embedding="embeddinggemma"), root=ROOT, transport=fake.transport())
+ executor, _bus = _executor()
+ result = await executor.execute(tools["lm_test_plan"], args={"roles": ["embedding"]})
+ assert result.success, result.error
+ assert result.output["roles"]["embedding"]["status"] == "ok"
+ assert result.output["overall"] == "ok"
+
+
+async def test_a_failing_handler_is_an_honest_tool_error_not_an_exception() -> None:
+ fake = _server()
+ fake.offline = True
+ tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())
+ result = await tools["lm_inventory"].execute({}, _ctx())
+ assert result.success is False
+ assert result.error and "OllamaServerError" in result.error
+
+
+# ------------------------------------------------------------ ask tier = a real ticket
+
+
[email protected]("name", sorted(ASK_TOOLS))
+async def test_ask_tools_raise_an_interactive_ticket_and_stop_on_denial(name: str) -> None:
+ fake = _server()
+ tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())
+ executor, bus = _executor(timeout_s=5.0)
+ cards: list[ActionApprovalRequired] = []
+ executed: list[ActionExecuted] = []
+
+ async def _on_card(event: ActionApprovalRequired) -> None:
+ cards.append(event)
+ await bus.publish(ActionDenied(trace_id=event.trace_id, reason="user_vetoed"))
+
+ async def _on_executed(event: ActionExecuted) -> None:
+ executed.append(event)
+
+ bus.subscribe(ActionApprovalRequired, _on_card)
+ bus.subscribe(ActionExecuted, _on_executed)
+
+ args = {
+ "model": "qwen3.5:4b",
+ "role": "chat",
+ "options": {"num_ctx": 4096},
+ "brain_model": "qwen3.5:4b",
+ "voice_model": "kokoro",
+ }
+ result = await asyncio.wait_for(
+ executor.execute(tools[name], args=args, config_snapshot={"approval_surface": INTERACTIVE}),
+ timeout=4.0,
+ )
+
+ assert len(cards) == 1, "exactly one approval card"
+ card = cards[0]
+ assert card.tool_name == name and card.risk_tier == "ask" and card.reason == "risk_tier"
+ assert card.expires_at_ns > 0, "an interactive card has a real window"
+ assert result.success is False
+ assert result.error == f"{APPROVAL_DENIED_PREFIX} (user_vetoed)"
+ assert executed == [], "a denied action never runs"
+ # Nothing reached the server for a denied action.
+ assert not any(path in ("/api/pull", "/api/generate") for _m, path, _b in fake.calls)
+
+
+async def test_monitor_tool_runs_without_a_card() -> None:
+ fake = _server()
+ tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())
+ executor, bus = _executor()
+ cards: list[ActionApprovalRequired] = []
+
+ async def _on_card(event: ActionApprovalRequired) -> None:
+ cards.append(event)
+
+ bus.subscribe(ActionApprovalRequired, _on_card)
+ result = await executor.execute(
+ tools["lm_unload"],
+ args={"model": "qwen3.5:4b"},
+ config_snapshot={"approval_surface": INTERACTIVE},
+ )
+ assert result.success, result.error
+ assert cards == []
+ assert fake.models["qwen3.5:4b"].loaded is False
+
+
+async def test_set_model_options_refuses_keys_the_suggestion_did_not_return() -> None:
+ fake = _server()
+ tools = build_tools(_cfg(), root=ROOT, transport=fake.transport())
+ suggested = await tools["lm_suggested_options"].execute({"model": "qwen3.5:4b"}, _ctx())
+ assert suggested.success, suggested.error
+ assert set(suggested.output["options"]) <= set(cfg_mod.OLLAMA_MODEL_OPTION_KEYS)
+
+ result = await tools["lm_set_model_options"].execute(
+ {"model": "qwen3.5:4b", "options": {"not_a_knob": 1}}, _ctx()
+ )
+ assert result.success is False
+ assert "refused: not_a_knob" in (result.error or "")
+
+
+# ------------------------------------------------------------ the prompt
+
+
+async def test_prompt_renders_with_the_fake_server_and_carries_the_contract() -> None:
+ fake = _server()
+ cfg = _cfg(chat="qwen3.5:4b", embedding="embeddinggemma")
+ text = await assistant_prompt.build_system_extra(cfg, root=ROOT, transport=fake.transport())
+
+ assert len(text) < 10_000, len(text)
+ assert "Ollama server: http://fake-ollama:11434 — running, version 0.32.15" in text
+ assert "- qwen3.5:4b · 3.2 GB · completion,tools,vision · ctx 262144" in text
+ assert "chat · completion · qwen3.5:4b · yes · brain.providers.ollama.model" in text
+ assert "embedding · embedding · embeddinggemma · yes · ultrawiki.embedding_model" in text
+ assert "tools_screen · tools+vision · not set" in text
+ assert "CURATED SHORTLIST (reviewed " in text
+ assert "qwen3.5:4b · chat · 3.4 · " in text and "· yes · tools+vision" in text
+ assert "new_little_tested" in text or "proven" in text
+ assert "```jarvis-proposal" in text
+ assert "Never delete a model" in text
+ assert "brain_switch" in text
+
+
+async def test_prompt_is_honest_when_the_server_is_down() -> None:
+ fake = _server()
+ fake.offline = True
+ text = await assistant_prompt.build_system_extra(_cfg(), root=ROOT, transport=fake.transport())
+ assert "not answering" in text
+ assert "INSTALLED MODELS\n- unavailable:" in text
+
+
+def test_openers_name_the_contract_and_never_execute_unasked() -> None:
+ for opener in (assistant_prompt.SETUP_OPENER, assistant_prompt.DIAGNOSE_OPENER):
+ assert "jarvis-proposal" in opener
+ assert "until I confirm" in opener
+ assert "lm_test_plan" in assistant_prompt.TEST_OPENER
diff --git a/tests/unit/local_models/test_benchmarks.py b/tests/unit/local_models/test_benchmarks.py
new file mode 100644
index 0000000000..e97a3066cb
--- /dev/null
+++ b/tests/unit/local_models/test_benchmarks.py
@@ -0,0 +1,240 @@
+"""Benchmarks + freshness: canned snippets in, honest labels out, offline safe."""
+
+from __future__ import annotations
+
+import datetime as _dt
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.brain.ollama_pull import CURATED_REVIEWED_ON, RECOMMENDED_MODELS
+from jarvis.core import config as cfg_mod
+from jarvis.local_models import benchmarks as bm
+
+pytestmark = pytest.mark.asyncio
+
+TODAY = CURATED_REVIEWED_ON + _dt.timedelta(days=1)
+NOW = _dt.datetime(TODAY.year, TODAY.month, TODAY.day, 12, 0, tzinfo=_dt.UTC)
+
+SNIPPETS: dict[str, list[dict[str, Any]]] = {
+ "qwen3.5 Artificial Analysis intelligence index": [
+ {
+ "title": "Qwen 3.5 27B — Artificial Analysis",
+ "url": "https://artificialanalysis.ai/models/qwen3-5-27b",
+ "snippet": "Qwen3.5 27B scores an Intelligence Index of 48 across our evaluations.",
+ },
+ {
+ "title": "Unrelated blog",
+ "url": "https://example.com/blog",
+ "snippet": "Gemma 4 has an intelligence index of 99 (this is not about qwen).",
+ },
+ ],
+ "qwen3.5 LMArena text arena score": [
+ {
+ "title": "LMArena leaderboard",
+ "url": "https://lmarena.ai/leaderboard/text",
+ "snippet": "qwen3.5-27b-instruct: Arena score 1312, rank 18.",
+ }
+ ],
+ "qwen3.5 Open LLM Leaderboard average score": [],
+ "gemma4 Artificial Analysis intelligence index": [
+ {
+ "title": "Gemma 4 — page without numbers",
+ "url": "https://artificialanalysis.ai/models/gemma-4",
+ "snippet": "Gemma 4 is Google's open model family.",
+ }
+ ],
+ "gemma4 LMArena text arena score": [],
+ "gemma4 Open LLM Leaderboard average score": [],
+}
+
+
+class _Search:
+ def __init__(self, table: dict[str, list[dict[str, Any]]] | None = None, *, fail: bool = False):
+ self.table = table if table is not None else SNIPPETS
+ self.fail = fail
+ self.queries: list[str] = []
+
+ async def __call__(self, query: str) -> list[dict[str, Any]]:
+ self.queries.append(query)
+ if self.fail:
+ raise ConnectionError("offline")
+ return self.table.get(query, [])
+
+
+def _library(entries: dict[str, dict[str, str]], *, fail: bool = False):
+ async def _fn(family: str) -> dict[str, Any]:
+ if fail:
+ raise ConnectionError("offline")
+ entry = entries.get(family)
+ return {"models": [dict(name=family, **entry)] if entry else [], "error": None}
+
+ return _fn
+
+
[email protected](autouse=True)
+def _data_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)
+ return tmp_path
+
+
+# ------------------------------------------------------------ pure helpers
+
+
+def test_family_and_pulls_and_updated_parsers() -> None:
+ assert bm.family_of("qwen3.5:4b") == "qwen3.5"
+ assert bm.family_of("gemma4:26b-a4b-it-qat") == "gemma4"
+ assert bm.family_of("embeddinggemma") == "embeddinggemma"
+ assert bm.parse_pulls("17.2M") == 17_200_000
+ assert bm.parse_pulls("845.3K") == 845_300
+ assert bm.parse_pulls("1,204") == 1204
+ assert bm.parse_pulls("") == 0 and bm.parse_pulls("lots") == 0
+ assert bm.parse_updated_days("2 weeks ago") == 14
+ assert bm.parse_updated_days("a month ago") == 30
+ assert bm.parse_updated_days("yesterday") == 1
+ assert bm.parse_updated_days("3 hours ago") == 0
+ assert bm.parse_updated_days("") is None and bm.parse_updated_days("soon") is None
+
+
+def test_extract_rows_is_tolerant_and_keyed_by_source_and_metric() -> None:
+ results = (
+ SNIPPETS["qwen3.5 Artificial Analysis intelligence index"]
+ + SNIPPETS["qwen3.5 LMArena text arena score"]
+ )
+ rows = bm.extract_rows("qwen3.5", results, source="artificial_analysis", seen_at="t")
+ by_key = {(r.source, r.metric): r for r in rows}
+ assert by_key[("artificial_analysis", "intelligence_index")].value == 48.0
+ # The LMArena snippet is filed under LMArena by its host, whatever query found it.
+ assert by_key[("lmarena", "arena_score")].value == 1312.0
+ assert by_key[("lmarena", "arena_score")].url == "https://lmarena.ai/leaderboard/text"
+ # The unrelated snippet (no family mention) contributed nothing.
+ assert all(r.value != 99.0 for r in rows)
+ assert bm.extract_rows("qwen3.5", [None, "junk", {}], source="x", seen_at="t") == [] # type: ignore[list-item]
+
+
+def test_curated_families_come_from_the_shortlist() -> None:
+ families = bm.curated_families()
+ assert families[0] == bm.family_of(RECOMMENDED_MODELS[0].id)
+ assert len(families) == len(set(families))
+ assert bm.curated_families(("qwen3.5:4b", "qwen3.5:27b")) == ("qwen3.5",)
+
+
+# ------------------------------------------------------------ labelling
+
+
+def _table(
+ rows: tuple[bm.BenchmarkRow, ...] = (), library: dict[str, bm.LibraryFacts] | None = None
+) -> bm.BenchmarkTable:
+ return bm.BenchmarkTable(
+ fetched_at=NOW.isoformat(), rows=rows, library=library or {}, source="live"
+ )
+
+
+def test_label_proven_needs_a_row_or_100k_pulls() -> None:
+ row = bm.BenchmarkRow("qwen3.5", "lmarena", "arena_score", 1312.0, "u", "t")
+ assert bm.label_for("qwen3.5:4b", _table((row,)), TODAY) == "proven"
+ popular = {"gemma4": bm.LibraryFacts("gemma4", pulls=2_000_000, updated_days=120)}
+ assert bm.label_for("gemma4:12b-it-qat", _table((), popular), TODAY) == "proven"
+ quiet = {"gemma4": bm.LibraryFacts("gemma4", pulls=5_000, updated_days=120)}
+ assert bm.label_for("gemma4:12b-it-qat", _table((), quiet), TODAY) == "new_little_tested"
+ assert bm.label_for("gemma4:12b-it-qat", None, TODAY) == "new_little_tested"
+
+
+def test_label_new_when_the_library_updated_it_recently_even_with_rows() -> None:
+ row = bm.BenchmarkRow("qwen3.5", "lmarena", "arena_score", 1312.0, "u", "t")
+ fresh = {"qwen3.5": bm.LibraryFacts("qwen3.5", pulls=9_000_000, updated_days=3)}
+ assert bm.label_for("qwen3.5:4b", _table((row,), fresh), TODAY) == "new_little_tested"
+ settled = {"qwen3.5": bm.LibraryFacts("qwen3.5", pulls=9_000_000, updated_days=60)}
+ assert bm.label_for("qwen3.5:4b", _table((row,), settled), TODAY) == "proven"
+
+
+def test_label_stale_when_the_review_is_older_than_a_year() -> None:
+ row = bm.BenchmarkRow("qwen3.5", "lmarena", "arena_score", 1312.0, "u", "t")
+ a_year_later = CURATED_REVIEWED_ON + _dt.timedelta(days=366)
+ assert bm.label_for(RECOMMENDED_MODELS[0], _table((row,)), a_year_later) == "stale"
+ assert bm.label_for(RECOMMENDED_MODELS[0], _table((row,)), TODAY) in bm.LABELS
+
+
+# ------------------------------------------------------------ refresh + cache
+
+
+async def test_refresh_runs_three_queries_per_family_and_caches(tmp_path: Path) -> None:
+ search = _Search()
+ library = _library({"qwen3.5": {"pulls": "17.2M", "updated": "3 months ago"}})
+ table = await bm.refresh_benchmarks(
+ search, families=("qwen3.5", "gemma4"), library_fn=library, now=NOW
+ )
+ assert table.source == "live" and table.note == ""
+ assert sorted(search.queries) == sorted(SNIPPETS)
+ assert {(r.source, r.metric, r.value) for r in table.rows_for("qwen3.5")} == {
+ ("artificial_analysis", "intelligence_index", 48.0),
+ ("lmarena", "arena_score", 1312.0),
+ }
+ assert table.rows_for("gemma4") == ()
+ assert table.library["qwen3.5"] == bm.LibraryFacts("qwen3.5", 17_200_000, 90)
+ assert "gemma4" not in table.library
+
+ written = json.loads((tmp_path / "state" / "local_models_benchmarks.json").read_text("utf-8"))
+ assert written["fetched_at"] == NOW.isoformat(timespec="seconds")
+ assert len(written["rows"]) == 2
+
+ cached = bm.load_cached(now=NOW + _dt.timedelta(days=6))
+ assert cached is not None and cached.source == "cache"
+ assert cached.rows == table.rows and cached.library == table.library
+ assert bm.load_cached(now=NOW + _dt.timedelta(days=7)) is None, "TTL is seven days"
+ assert bm.load_cached(max_age_days=None, now=NOW + _dt.timedelta(days=400)) is not None
+
+
+async def test_one_failing_query_loses_only_its_rows() -> None:
+ class _Flaky(_Search):
+ async def __call__(self, query: str) -> list[dict[str, Any]]:
+ if "LMArena" in query:
+ raise TimeoutError("slow")
+ return await super().__call__(query)
+
+ table = await bm.refresh_benchmarks(
+ _Flaky(), families=("qwen3.5",), library_fn=_library({}), now=NOW, persist=False
+ )
+ assert [r.metric for r in table.rows] == ["intelligence_index"]
+
+
+async def test_offline_prefers_the_cache_then_the_curated_note(tmp_path: Path) -> None:
+ # No cache at all → curated-only, with the note.
+ table = await bm.refresh_benchmarks(
+ _Search(fail=True), families=("qwen3.5",), library_fn=_library({}, fail=True), now=NOW
+ )
+ assert table.source == "curated" and table.rows == () and "curated" in table.note
+ assert not (tmp_path / "state" / "local_models_benchmarks.json").exists()
+
+ # A cache (however old) beats curated-only.
+ await bm.refresh_benchmarks(
+ _Search(), families=("qwen3.5",), library_fn=_library({}), now=NOW - _dt.timedelta(days=30)
+ )
+ table = await bm.refresh_benchmarks(
+ _Search(fail=True), families=("qwen3.5",), library_fn=_library({}, fail=True), now=NOW
+ )
+ assert table.source == "cache" and len(table.rows) == 2 and "cached" in table.note
+
+
+async def test_sync_search_fn_is_accepted() -> None:
+ def search(query: str) -> list[dict[str, Any]]:
+ return SNIPPETS.get(query, [])
+
+ table = await bm.refresh_benchmarks(
+ search, families=("qwen3.5",), library_fn=_library({}), now=NOW, persist=False
+ )
+ assert len(table.rows) == 2
+
+
+def test_from_payload_drops_malformed_entries() -> None:
+ table = bm.BenchmarkTable.from_payload(
+ {
+ "fetched_at": "2026-08-25T12:00:00+00:00",
+ "rows": [{"family": "a", "value": "x"}, {"family": "b", "value": 1}],
+ "library": {"a": {"pulls": "nope"}, "b": {"pulls": 5, "updated_days": None}},
+ }
+ )
+ assert [r.family for r in table.rows] == ["b"]
+ assert table.library == {"b": bm.LibraryFacts("b", 5, None)}
diff --git a/tests/unit/ui/web/test_local_models_assistant_routes.py b/tests/unit/ui/web/test_local_models_assistant_routes.py
new file mode 100644
index 0000000000..25536b1478
--- /dev/null
+++ b/tests/unit/ui/web/test_local_models_assistant_routes.py
@@ -0,0 +1,204 @@
+"""The assistant routes: run / session / test / benchmarks / health behind the pull gate.
+
+The agent-chat service is real (in-memory store); the brain turn is not run
+— ``send`` is observed through the service's own store events. The Ollama
+server is the fake; the Agents-tier check is injected by patching the routes'
+``_usable`` seam (a plain function, not a mock library).
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.brain import ollama_inventory, ollama_runtime
+from jarvis.core import config as cfg_mod
+from jarvis.core.bus import EventBus
+from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig
+from jarvis.local_models.assistant_prompt import DIAGNOSE_OPENER, SETUP_OPENER
+from jarvis.local_models.assistant_session import NOT_READY
+from jarvis.ui.web import local_models_assistant_routes as routes
+from jarvis.ui.web.server import WebServer
+from tests.fakes.fake_ollama_server import FakeOllamaServer
+
+BASE = "/api/providers/ollama/local-models/assistant"
+
+
+def fake(monkeypatch: pytest.MonkeyPatch) -> FakeOllamaServer:
+ server = FakeOllamaServer()
+ server.add("embeddinggemma", capabilities=("embedding",), embed_dim=768)
+
+ def _client(transport: httpx.AsyncBaseTransport | None = None) -> httpx.AsyncClient:
+ return httpx.AsyncClient(transport=server.transport(), timeout=5.0)
+
+ monkeypatch.setattr(ollama_inventory, "_make_client", _client)
+
+ real_probe = ollama_runtime.probe_host
+
+ async def _probe(base_url: str, *, transport=None) -> dict:
+ return await real_probe(base_url, transport=server.transport())
+
+ monkeypatch.setattr(ollama_runtime, "probe_host", _probe)
+ return server
+
+
[email protected](autouse=True)
+def live_probe_is_a_fake(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The routes ask every candidate pair for one real generation; a unit
+ test answers "alive" for all of them instead of calling a vendor."""
+ from jarvis.local_models import assistant_session
+
+ async def _alive(cfg, pairs, *, timeout_s=20.0, tester=None):
+ return {pair: (True, "") for pair in pairs}
+
+ assistant_session._reset_for_tests()
+ monkeypatch.setattr(assistant_session, "probe_live", _alive)
+
+
+def server(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> WebServer:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ monkeypatch.setattr(cfg_mod, "DATA_DIR", tmp_path)
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ cfg.brain.providers["ollama"] = BrainProviderConfig(base_url="http://fake:11434")
+ cfg.brain.worker = BrainTierConfig(provider="openai", model="gpt-x")
+ cfg.ultrawiki.embedding_provider = "ollama"
+ cfg.ultrawiki.embedding_model = "embeddinggemma"
+ srv = WebServer(cfg, bus=EventBus())
+ srv.app.state.config = cfg
+ srv.app.state.agent_chat = AgentChatService(AgentChatStore(":memory:"))
+ return srv
+
+
+def ready(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(routes, "_usable", lambda _p: True)
+
+
+def test_routes_sit_behind_the_pull_gate(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ assert client.get("/api/providers/openai/local-models/assistant/health").status_code == 400
+ assert client.get("/api/providers/nope/local-models/assistant/session").status_code == 404
+
+
+def test_session_is_null_until_a_run_and_names_the_tier(server: WebServer, ready: None) -> None:
+ with TestClient(server.app) as client:
+ body = client.get(f"{BASE}/session").json()
+ assert body == {
+ "session_id": None,
+ "surface": "local-models",
+ "provider": "openai",
+ "model": "gpt-x",
+ "ready": True,
+ "reason": "",
+ }
+
+
+def test_run_refuses_honestly_without_the_agents_tier(
+ server: WebServer, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(routes, "_usable", lambda _p: False)
+ with TestClient(server.app) as client:
+ resp = client.post(f"{BASE}/run", json={"mode": "setup"})
+ assert resp.status_code == 409
+ assert resp.json()["detail"] == NOT_READY
+ assert client.get(f"{BASE}/session").json()["ready"] is False
+ assert server.app.state.agent_chat.store.list_sessions(surface="local-models") == []
+
+
+def test_run_creates_one_session_and_sends_the_mode_opener(
+ server: WebServer, ready: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ svc: AgentChatService = server.app.state.agent_chat
+ sent: list[tuple[str, str]] = []
+
+ async def fake_send(session_id: str, text: str) -> str:
+ sent.append((session_id, text))
+ return "turn-1"
+
+ monkeypatch.setattr(svc, "send", fake_send)
+ with TestClient(server.app) as client:
+ first = client.post(f"{BASE}/run", json={"mode": "setup"})
+ assert first.status_code == 200, first.text
+ assert first.json() == {
+ "session_id": first.json()["session_id"],
+ "turn_id": "turn-1",
+ "surface": "local-models",
+ }
+ second = client.post(f"{BASE}/run", json={"mode": "diagnose"})
+ assert second.json()["session_id"] == first.json()["session_id"]
+ state = client.get(f"{BASE}/session").json()
+ assert state["session_id"] == first.json()["session_id"]
+ assert client.post(f"{BASE}/run", json={"mode": "bogus"}).status_code == 422
+ assert [text for _sid, text in sent] == [SETUP_OPENER, DIAGNOSE_OPENER]
+ sessions = svc.store.list_sessions(surface="local-models")
+ assert len(sessions) == 1 and sessions[0].provider == "openai"
+
+
+def test_run_answers_409_while_a_turn_is_running(
+ server: WebServer, ready: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.agent_chat.service import SessionBusy
+
+ svc: AgentChatService = server.app.state.agent_chat
+
+ async def busy(session_id: str, text: str) -> str:
+ raise SessionBusy(session_id)
+
+ monkeypatch.setattr(svc, "send", busy)
+ with TestClient(server.app) as client:
+ resp = client.post(f"{BASE}/run", json={"mode": "test"})
+ assert resp.status_code == 409 and "still answering" in resp.json()["detail"]
+
+
+def test_test_route_runs_the_setup_test_and_health_reads_the_file(
+ server: WebServer, fake: FakeOllamaServer, tmp_path: Path
+) -> None:
+ with TestClient(server.app) as client:
+ before = client.get(f"{BASE}/health").json()
+ assert before == {
+ "status": "unknown",
+ "reason": "",
+ "since": None,
+ "last_ok": None,
+ "checked_at": None,
+ }
+ resp = client.post(f"{BASE}/test", json={"roles": ["embedding"]})
+ assert resp.status_code == 200, resp.text
+ report = resp.json()
+ assert report["roles"]["embedding"]["status"] == "ok"
+ assert report["overall"] == "ok"
+ assert client.post(f"{BASE}/test", json={"roles": ["ack"]}).status_code == 400
+ after = client.get(f"{BASE}/health").json()
+ assert after["status"] == "ok" and after["checked_at"] == report["checked_at"]
+ assert after["since"] == after["last_ok"] == report["checked_at"]
+ written = json.loads((tmp_path / "state" / "local_models_health.json").read_text("utf-8"))
+ assert written["overall"] == "ok"
+
+
+def test_benchmarks_without_a_cache_is_curated_only(server: WebServer) -> None:
+ with TestClient(server.app) as client:
+ body = client.get(f"{BASE}/benchmarks").json()
+ assert body["source"] == "curated" and body["rows"] == [] and body["note"]
+
+
+def test_section_health_carries_the_local_models_badge_from_the_file(
+ server: WebServer, fake: FakeOllamaServer
+) -> None:
+ from jarvis.local_models.health_monitor import write_health_record
+
+ write_health_record("error", "chat: model not found")
+ with TestClient(server.app) as client:
+ resp = client.get("/api/providers/section-health?refresh=true")
+ assert resp.status_code == 200, resp.text
+ section = resp.json()["sections"]["local_models"]
+ assert section["status"] == "error"
+ assert section["detail"] == "chat: model not found"