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(realtime): one-click install engine for the managed local server

rubenluetke10-beep9cef536e2d5b
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index df3a5e9174..a0ed48beee 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -2010,6 +2010,50 @@ def set_provider_base_url(
)
+def set_local_realtime_launch_command(
+ launch_command: str, *, path: Path = DEFAULT_CONFIG_FILE
+) -> None:
+ """Persist the managed server's derived launch command (AD-4).
+
+ Written by the one-click install engine
+ (``jarvis/realtime/local_server/install.py``) after a successful smoke
+ boot; the realtime adapter reads it to start/revive the server. The
+ command is DERIVED from probed hardware + resolved brain and never
+ carries a secret. Also pins ``base_url`` to the served port so a fresh
+ install activates without a manual URL paste.
+ """
+ path = _ensure_writable_config_path(path)
+ cleaned = (launch_command or "").strip()
+
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM) :]
+ doc: TOMLDocument = tomlkit.parse(raw)
+
+ brain = doc.get("brain")
+ if brain is None:
+ brain = tomlkit.table()
+ doc["brain"] = brain
+ providers = brain.get("providers")
+ if providers is None:
+ providers = tomlkit.table(True)
+ brain["providers"] = providers
+ block = providers.get("local-realtime")
+ if block is None:
+ block = tomlkit.table()
+ providers["local-realtime"] = block
+ block["launch_command"] = cleaned
+ if not str(block.get("base_url", "") or "").strip():
+ block["base_url"] = "http://localhost:8765"
+
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+
+
def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Patch ``[integrations.twilio]`` with the given non-secret fields.
diff --git a/jarvis/realtime/local_server/__init__.py b/jarvis/realtime/local_server/__init__.py
index 93f8fc1c55..0808589030 100644
--- a/jarvis/realtime/local_server/__init__.py
+++ b/jarvis/realtime/local_server/__init__.py
@@ -19,3 +19,7 @@ __all__ = [
"apply_create_response_patch",
"patch_state",
]
+
+# The heavier surfaces (preflight, install engine, tier ladder, brain
+# resolution) are imported from their own modules on purpose — routes and
+# CLI import them lazily so nothing here rides the boot critical path.
diff --git a/jarvis/realtime/local_server/brain_link.py b/jarvis/realtime/local_server/brain_link.py
new file mode 100644
index 0000000000..2843abbee3
--- /dev/null
+++ b/jarvis/realtime/local_server/brain_link.py
@@ -0,0 +1,145 @@
+"""Brain endpoint resolution for the managed local realtime server (AD-7).
+
+The speech-to-speech server does not think; it forwards each turn to an
+OpenAI-Responses-compatible endpoint. Resolution order, capability-gated and
+never provider-pinned (AP-21/22):
+
+1. A local Ollama that is actually running and holds a usable model —
+ the fully-local path.
+2. A configured OpenAI key — honest partial locality ("audio stays on this
+ machine, reasoning uses your OpenAI key"). Other cloud families are not
+ offered here because the server speaks the Responses API; they join once
+ the server (or a proxy) supports their protocols.
+3. Neither → a blocker naming the exact fixing actions.
+
+Every probe is short-timeout and read-only; nothing here downloads models.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import urllib.error
+import urllib.request
+from dataclasses import dataclass, field
+
+log = logging.getLogger(__name__)
+
+#: Models preferred as the server brain, best first. Only ever chosen from
+#: what is ALREADY present in Ollama — the resolver never pulls.
+_PREFERRED_MODELS: tuple[str, ...] = ("qwen2.5:7b", "qwen3-coder:30b", "llama3.1:8b")
+
+#: Tag substrings that mark non-chat models a voice brain must never use.
+_UNUSABLE_MARKERS: tuple[str, ...] = ("embed", "whisper", "rerank")
+
+_OLLAMA_DEFAULT = "http://127.0.0.1:11434"
+
+
+@dataclass(frozen=True, slots=True)
+class BrainResolution:
+ kind: str # "ollama" | "cloud-openai" | "blocked"
+ base_url: str = ""
+ api_key: str = ""
+ model: str = ""
+ #: One honest sentence for the card / preflight summary.
+ note: str = ""
+ #: For "blocked": the concrete actions that would fix it, best first.
+ actions: tuple[str, ...] = field(default_factory=tuple)
+
+ @property
+ def ok(self) -> bool:
+ return self.kind != "blocked"
+
+
+def _ollama_base() -> str:
+ host = (os.environ.get("OLLAMA_HOST") or "").strip()
+ if not host:
+ return _OLLAMA_DEFAULT
+ if not host.startswith(("http://", "https://")):
+ host = f"http://{host}"
+ return host.rstrip("/")
+
+
+def _ollama_tags(base: str, timeout: float) -> list[str] | None:
+ """Model tags of a running Ollama, or ``None`` when it is unreachable."""
+ url = f"{base}/api/tags"
+ if not url.startswith(("http://", "https://")): # scheme is normalized above
+ return None
+ try:
+ with urllib.request.urlopen(url, timeout=timeout) as resp: # noqa: S310 — http(s) only
+ payload = json.load(resp)
+ except (urllib.error.URLError, OSError, ValueError):
+ return None
+ models = payload.get("models") or []
+ return [str(m.get("name", "")) for m in models if m.get("name")]
+
+
+def _pick_model(tags: list[str]) -> str:
+ for preferred in _PREFERRED_MODELS:
+ if preferred in tags:
+ return preferred
+ for tag in tags:
+ lowered = tag.lower()
+ if not any(marker in lowered for marker in _UNUSABLE_MARKERS):
+ return tag
+ return ""
+
+
+def _openai_key() -> str:
+ try:
+ from jarvis.core.config import get_secret
+
+ return (get_secret("openai_api_key", env_fallback="OPENAI_API_KEY") or "").strip()
+ except Exception: # pragma: no cover — config not importable in odd contexts
+ log.debug("brain resolution: secret lookup failed", exc_info=True)
+ return ""
+
+
+def resolve_brain(*, timeout: float = 2.5) -> BrainResolution:
+ """Resolve the best brain endpoint available on THIS machine right now."""
+ base = _ollama_base()
+ tags = _ollama_tags(base, timeout)
+ if tags is not None:
+ model = _pick_model(tags)
+ if model:
+ return BrainResolution(
+ kind="ollama",
+ base_url=f"{base}/v1",
+ api_key="ollama",
+ model=model,
+ note=f"Fully local: reasoning runs on your Ollama ({model}).",
+ )
+ return BrainResolution(
+ kind="blocked",
+ note=(
+ "Ollama is running but holds no usable chat model, so the "
+ "local server would have no brain."
+ ),
+ actions=(
+ f"Run: ollama pull {_PREFERRED_MODELS[0]}",
+ "Or add an OpenAI API key in Settings for cloud reasoning.",
+ ),
+ )
+ key = _openai_key()
+ if key:
+ return BrainResolution(
+ kind="cloud-openai",
+ # base_url stays empty on purpose: the server's OpenAI client
+ # defaults to api.openai.com and reads OPENAI_API_KEY from its
+ # spawn environment, so no secret ever enters a command line.
+ api_key=key,
+ model="gpt-5.4-mini",
+ note=(
+ "Audio stays on this machine; reasoning uses your OpenAI "
+ "key (no local brain found)."
+ ),
+ )
+ return BrainResolution(
+ kind="blocked",
+ note="No brain available: neither a running Ollama nor an OpenAI key.",
+ actions=(
+ f"Install Ollama (ollama.com) and run: ollama pull {_PREFERRED_MODELS[0]}",
+ "Or add an OpenAI API key in Settings.",
+ ),
+ )
diff --git a/jarvis/realtime/local_server/install.py b/jarvis/realtime/local_server/install.py
new file mode 100644
index 0000000000..fad356b6f2
--- /dev/null
+++ b/jarvis/realtime/local_server/install.py
@@ -0,0 +1,407 @@
+"""The one-click install engine for the managed local realtime server.
+
+Turns the hand-built dev-box procedure into a supervised pipeline:
+preflight → venv → pinned dependencies → vendored patch → smoke boot →
+persist the launch command. Runs in a daemon thread so the REST route
+returns immediately; progress is poll-shaped (:func:`snapshot`) and every
+failure leaves a resumable state plus a one-sentence reason — never a
+half-installed "ready" (readiness itself is :func:`server_status`,
+fail-closed).
+
+The smoke boot doubles as the model-download step: the server fetches its
+STT/TTS checkpoints into the shared HF cache on first start, so the first
+real call never pays that multi-gigabyte surprise.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import shlex
+import socket
+import subprocess
+import sys
+import threading
+import time
+from collections import deque
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.realtime.local_server.brain_link import BrainResolution
+from jarvis.realtime.local_server.patching import (
+ PATCH_TARGET_VERSION,
+ apply_create_response_patch,
+ patch_state,
+)
+from jarvis.realtime.local_server.preflight import (
+ PreflightReport,
+ report_payload,
+ run_preflight,
+)
+
+log = logging.getLogger(__name__)
+
+_PINS_FILE = Path(__file__).parent / "pins" / f"core-{PATCH_TARGET_VERSION}.txt"
+
+#: torch flavor per probed hardware. The CUDA build ships from the PyTorch
+#: index; everything else takes the default wheels (macOS arm64 wheels carry
+#: MPS support out of the box).
+_TORCH_PINS_CUDA = ("torch==2.13.0+cu130", "torchaudio==2.11.0+cu130")
+_TORCH_INDEX_CUDA = "https://download.pytorch.org/whl/cu130"
+_TORCH_PINS_DEFAULT = ("torch==2.13.0", "torchaudio==2.11.0")
+
+#: The port the managed server serves on (matches the provider default) and
+#: the throwaway port the smoke boot binds so it never fights a live server.
+SERVE_PORT = 8765
+_SMOKE_PORT = 8876
+
+_PIP_TIMEOUT_S = 3600
+_SMOKE_TIMEOUT_S = 1800 # first boot downloads the TTS/STT checkpoints
+
+_PHASES = ("idle", "preflight", "venv", "deps", "patch", "smoke", "configure", "done", "error")
+
+
+def install_root() -> Path:
+ """Permanent home of the managed server, under the Jarvis data dir."""
+ return Path(os.environ.get("JARVIS_DATA_DIR") or "data") / "local_realtime"
+
+
+def _venv_dir() -> Path:
+ return install_root() / "venv"
+
+
+def _venv_bindir() -> Path:
+ return _venv_dir() / ("Scripts" if os.name == "nt" else "bin")
+
+
+def _venv_python() -> Path:
+ return _venv_bindir() / ("python.exe" if os.name == "nt" else "python")
+
+
+def _server_entrypoint() -> Path:
+ return _venv_bindir() / ("speech-to-speech.exe" if os.name == "nt" else "speech-to-speech")
+
+
+def _site_packages() -> Path:
+ if os.name == "nt":
+ return _venv_dir() / "Lib" / "site-packages"
+ version = f"python{sys.version_info.major}.{sys.version_info.minor}"
+ return _venv_dir() / "lib" / version / "site-packages"
+
+
+def _smoke_marker() -> Path:
+ return install_root() / "smoke_ok.json"
+
+
+@dataclass
+class _State:
+ phase: str = "idle"
+ percent: int = 0
+ detail: str = ""
+ error: str = ""
+ started_at: float = 0.0
+ finished_at: float = 0.0
+ log_tail: deque[str] = field(default_factory=lambda: deque(maxlen=30))
+ thread: threading.Thread | None = None
+
+
+_STATE = _State()
+_LOCK = threading.Lock()
+
+
+def _set(phase: str, percent: int, detail: str = "") -> None:
+ with _LOCK:
+ _STATE.phase = phase
+ _STATE.percent = percent
+ if detail:
+ _STATE.detail = detail
+ _STATE.log_tail.append(detail)
+
+
+def _fail(message: str) -> None:
+ log.error("local-realtime install: %s", message)
+ with _LOCK:
+ _STATE.phase = "error"
+ _STATE.error = message
+ _STATE.finished_at = time.time()
+
+
+def snapshot() -> dict[str, object]:
+ """Poll-shaped view of the running (or last) install."""
+ with _LOCK:
+ return {
+ "phase": _STATE.phase,
+ "percent": _STATE.percent,
+ "detail": _STATE.detail,
+ "error": _STATE.error,
+ "running": _STATE.thread is not None and _STATE.thread.is_alive(),
+ "log_tail": list(_STATE.log_tail),
+ }
+
+
+def server_status() -> dict[str, object]:
+ """Fail-closed readiness of the managed install (read-only, no network).
+
+ Ready means ALL of: venv python present, server entry point present,
+ vendored patch applied, and a recorded successful smoke boot. Each
+ component is reported separately so the card can say exactly what is
+ missing, in the server's words.
+ """
+ components = {
+ "venv": _venv_python().exists(),
+ "entrypoint": _server_entrypoint().exists(),
+ "patch": patch_state(_site_packages()) == "patched",
+ "smoke_boot": _smoke_marker().exists(),
+ }
+ ready = all(components.values())
+ if ready:
+ sentence = (
+ f"Managed server installed (speech-to-speech {PATCH_TARGET_VERSION}, "
+ "patched) and smoke-booted."
+ )
+ elif not components["venv"] and not components["entrypoint"]:
+ sentence = "Managed server not installed."
+ else:
+ missing = ", ".join(name for name, present in components.items() if not present)
+ sentence = f"Managed server incomplete: {missing} missing — reinstall to repair."
+ return {"ready": ready, "components": components, "sentence": sentence}
+
+
+def derive_launch_command(brain: BrainResolution, *, memory_source: str) -> str:
+ """The exact command Jarvis uses to start/revive the managed server (AD-4).
+
+ Derived, never hand-authored: flags follow the probed hardware and the
+ resolved brain. The TTS device maps NVIDIA → cuda and Apple unified
+ memory → mps; a machine with neither never passes preflight.
+
+ Secrets never enter the command (they would land in jarvis.toml): the
+ Ollama path uses the literal placeholder token Ollama expects, and the
+ cloud path omits base/key entirely — the server's OpenAI client then
+ reads ``OPENAI_API_KEY`` from the spawn environment.
+ """
+ tts_device = "cuda" if memory_source == "nvidia-smi" else "mps"
+ parts = [
+ f'"{_server_entrypoint()}"',
+ "--mode realtime",
+ "--tts qwen3",
+ f"--qwen3_tts_device {tts_device}",
+ "--qwen3_tts_dtype bfloat16",
+ "--qwen3_tts_backend torch",
+ "--qwen3_tts_speaker Aiden",
+ "--parakeet_tdt_device cpu",
+ "--num_pipelines 1",
+ f"--model_name {brain.model}",
+ ]
+ if brain.kind == "ollama":
+ parts += [
+ f"--responses_api_base_url {brain.base_url}",
+ "--responses_api_api_key ollama",
+ ]
+ return " ".join(parts)
+
+
+def _run(cmd: list[str], *, timeout: int, cwd: Path | None = None) -> None:
+ """Run a build step, streaming its output into the progress tail."""
+ env = dict(os.environ)
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ proc = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ cwd=str(cwd) if cwd else None,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ deadline = time.monotonic() + timeout
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ line = line.rstrip()
+ if line:
+ with _LOCK:
+ _STATE.detail = line[:200]
+ _STATE.log_tail.append(line[:200])
+ if time.monotonic() > deadline:
+ _kill_tree(proc)
+ raise TimeoutError(f"step timed out after {timeout}s: {' '.join(cmd[:3])}…")
+ code = proc.wait(timeout=60)
+ if code != 0:
+ raise RuntimeError(f"step failed (exit {code}): {' '.join(cmd[:3])}…")
+
+
+def _kill_tree(proc: subprocess.Popen) -> None:
+ """Terminate a step's whole process tree, not just the launcher."""
+ try:
+ if os.name == "nt":
+ subprocess.run(
+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],
+ capture_output=True,
+ timeout=30,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ else:
+ proc.terminate()
+ proc.wait(timeout=10)
+ except Exception: # pragma: no cover — best-effort teardown
+ log.warning("local-realtime install: process-tree teardown incomplete", exc_info=True)
+
+
+def _port_open(port: int, timeout: float = 1.0) -> bool:
+ try:
+ with socket.create_connection(("127.0.0.1", port), timeout=timeout):
+ return True
+ except OSError:
+ return False
+
+
+def _smoke_boot(launch_command: str, brain: BrainResolution) -> None:
+ """Boot the freshly installed server once on a throwaway port.
+
+ Proves the whole stack (imports, patched service, model downloads into
+ the HF cache, port bind) before the install may call itself ready.
+ Mirrors the adapter's revive spawn exactly: raw string on Windows,
+ shlex on POSIX, and the same hardening environment.
+ """
+ with_port = f"{launch_command} --ws_port {_SMOKE_PORT}"
+ cmd: str | list[str] = with_port if os.name == "nt" else shlex.split(with_port)
+ smoke_log = install_root() / "smoke_boot.log"
+ env = dict(os.environ)
+ env.setdefault("PYTHONIOENCODING", "utf-8")
+ env.setdefault("PYTHONFAULTHANDLER", "1")
+ env.setdefault("PYTHONUNBUFFERED", "1")
+ # Windows without the symlink privilege: huggingface_hub's symlinked
+ # snapshot layout dies with WinError 1314 mid-download (live 2026-08-07).
+ env.setdefault("HF_HUB_DISABLE_SYMLINKS", "1")
+ if brain.kind == "cloud-openai" and brain.api_key:
+ env.setdefault("OPENAI_API_KEY", brain.api_key)
+ with open(smoke_log, "ab") as sink:
+ proc = subprocess.Popen(
+ cmd,
+ stdin=subprocess.DEVNULL,
+ stdout=sink,
+ stderr=sink,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ try:
+ deadline = time.monotonic() + _SMOKE_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if proc.poll() is not None:
+ raise RuntimeError(
+ f"server exited during smoke boot (code {proc.returncode}); see {smoke_log}"
+ )
+ if _port_open(_SMOKE_PORT):
+ return
+ elapsed = int(time.monotonic() - (deadline - _SMOKE_TIMEOUT_S))
+ _set("smoke", 70 + min(25, elapsed // 30), "waiting for first boot (downloads models)")
+ time.sleep(5)
+ raise TimeoutError(f"server did not come up within {_SMOKE_TIMEOUT_S}s; see {smoke_log}")
+ finally:
+ _kill_tree(proc)
+
+
+def start_install() -> tuple[bool, str]:
+ """Kick off (or resume) the managed install. Returns immediately."""
+ with _LOCK:
+ if _STATE.thread is not None and _STATE.thread.is_alive():
+ return False, "an install is already running"
+ _STATE.phase = "preflight"
+ _STATE.percent = 0
+ _STATE.error = ""
+ _STATE.detail = ""
+ _STATE.started_at = time.time()
+ _STATE.finished_at = 0.0
+ thread = threading.Thread(target=_run_install, name="local-realtime-install", daemon=True)
+ _STATE.thread = thread
+ thread.start()
+ return True, "install started"
+
+
+def _run_install() -> None:
+ try:
+ _set("preflight", 2, "checking hardware, disk, and brain")
+ report: PreflightReport = run_preflight(install_root())
+ if not report.ok:
+ _fail(report.blocker)
+ return
+ assert report.brain is not None and report.tier is not None
+ install_root().mkdir(parents=True, exist_ok=True)
+
+ if not _venv_python().exists():
+ _set("venv", 8, "creating the server's Python environment")
+ _run([sys.executable, "-m", "venv", str(_venv_dir())], timeout=300)
+ else:
+ _set("venv", 8, "reusing the existing environment")
+
+ _set("deps", 15, "installing pinned packages (resumable)")
+ pip = [str(_venv_python()), "-m", "pip", "install"]
+ torch_pins: tuple[str, ...]
+ if report.memory_source == "nvidia-smi":
+ torch_pins = _TORCH_PINS_CUDA
+ pip_torch = pip + ["--extra-index-url", _TORCH_INDEX_CUDA, *torch_pins]
+ else:
+ torch_pins = _TORCH_PINS_DEFAULT
+ pip_torch = pip + [*torch_pins]
+ _run(pip_torch, timeout=_PIP_TIMEOUT_S)
+ _set("deps", 45, "installing the server package set")
+ _run(pip + ["-r", str(_PINS_FILE)], timeout=_PIP_TIMEOUT_S)
+
+ _set("patch", 60, "applying the vendored create_response patch")
+ outcome = apply_create_response_patch(_site_packages())
+ _set("patch", 62, f"patch {outcome}")
+
+ _set("smoke", 70, "first boot (downloads voice/hearing models once)")
+ launch_command = derive_launch_command(report.brain, memory_source=report.memory_source)
+ _smoke_boot(launch_command, report.brain)
+
+ _set("configure", 96, "writing the launch configuration")
+ _smoke_marker().write_text(
+ json.dumps(
+ {
+ "at": time.time(),
+ "tier": report.tier.key,
+ "brain": report.brain.kind,
+ "preflight": report_payload(report),
+ },
+ indent=2,
+ ),
+ encoding="utf-8",
+ )
+ from jarvis.core.config_writer import set_local_realtime_launch_command
+
+ set_local_realtime_launch_command(launch_command)
+
+ with _LOCK:
+ _STATE.phase = "done"
+ _STATE.percent = 100
+ _STATE.detail = "installed, patched, smoke-booted, configured"
+ _STATE.finished_at = time.time()
+ log.info("local-realtime: managed install completed")
+ except Exception as exc: # noqa: BLE001 — every failure must land in the state
+ _fail(str(exc))
+
+
+def uninstall() -> tuple[bool, str]:
+ """Delete the managed install tree and its readiness marker."""
+ with _LOCK:
+ if _STATE.thread is not None and _STATE.thread.is_alive():
+ return False, "an install is running; wait for it to finish first"
+ import shutil
+
+ root = install_root()
+ if not root.exists():
+ return True, "nothing installed"
+ try:
+ shutil.rmtree(root)
+ except OSError as exc:
+ return False, f"could not remove {root}: {exc}"
+ with _LOCK:
+ _STATE.phase = "idle"
+ _STATE.percent = 0
+ _STATE.detail = ""
+ _STATE.error = ""
+ return True, f"removed {root}"
diff --git a/jarvis/realtime/local_server/pins/core-0.2.12.txt b/jarvis/realtime/local_server/pins/core-0.2.12.txt
new file mode 100644
index 0000000000..643c151eeb
--- /dev/null
+++ b/jarvis/realtime/local_server/pins/core-0.2.12.txt
@@ -0,0 +1,9 @@
+# Managed local-realtime server: the tested, version-pinned core set
+# (AD-2 of docs/plans/local-realtime-one-click-install-plan.md).
+# torch/torchaudio are installed separately by the engine because their
+# flavor (CUDA index vs default) depends on the probed hardware.
+speech-to-speech==0.2.12
+faster-qwen3-tts==0.3.2
+nano_parakeet==0.2.1
+qwen-tts==0.1.1
+onnxruntime==1.28.0
diff --git a/jarvis/realtime/local_server/preflight.py b/jarvis/realtime/local_server/preflight.py
new file mode 100644
index 0000000000..a810a3c6ca
--- /dev/null
+++ b/jarvis/realtime/local_server/preflight.py
@@ -0,0 +1,179 @@
+"""Honest hardware preflight for the managed local realtime install (AD-5).
+
+Runs BEFORE the first byte downloads and reports, for THIS machine: usable
+accelerator memory (dedicated VRAM via the existing hardware detection, or
+unified memory on Apple Silicon), free disk against the tier's stated
+download volume, the picked tier, and the resolved brain endpoint. Below
+the 12 GB floor (AD-10) the report carries the honest blocker and a pointer
+to the cloud realtime cards — never a degraded install.
+
+Read-only and side-effect free: probing must not download, create, or start
+anything (the same doctrine as ``jarvis/speech/local_models.py``).
+"""
+
+from __future__ import annotations
+
+import logging
+import platform
+import shutil
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from jarvis.realtime.local_server.brain_link import BrainResolution, resolve_brain
+from jarvis.realtime.local_server.tiers import FLOOR_GB, Tier, describe_stack, pick_tier
+
+log = logging.getLogger(__name__)
+
+#: Headroom demanded beyond the tier's stated download volume, in GiB, so an
+#: install can never land a machine on a full disk.
+_DISK_HEADROOM_GB = 5.0
+
+
+@dataclass(frozen=True, slots=True)
+class PreflightReport:
+ ok: bool
+ #: Set when ``ok`` is False: one honest sentence on why.
+ blocker: str = ""
+ #: Concrete fixing actions when blocked, best first.
+ actions: tuple[str, ...] = field(default_factory=tuple)
+ usable_gb: float = 0.0
+ #: Where the memory figure came from: "nvidia-smi" | "apple-unified" | "none".
+ memory_source: str = "none"
+ disk_free_gb: float = 0.0
+ tier: Tier | None = None
+ #: What this install would actually set up, in one sentence.
+ stack_sentence: str = ""
+ brain: BrainResolution | None = None
+
+
+def _usable_accelerator_gb() -> tuple[float, str]:
+ """Usable accelerator memory in GiB and the source of that figure.
+
+ Dedicated NVIDIA VRAM counts as-is. On Apple Silicon the GPU shares the
+ unified memory, so total RAM is the honest figure (the probe measures
+ what is THERE; whether the OS grants it is the smoke boot's job).
+ Anything else reports 0 — and 0 is below the floor, which is exactly
+ the honest outcome for a GPU-less host.
+ """
+ try:
+ from jarvis.hardware.detection import _detect_nvidia_gpus # read-only probe
+
+ gpus = _detect_nvidia_gpus()
+ except Exception: # pragma: no cover — nvidia-smi quirks must not crash preflight
+ log.debug("preflight: NVIDIA probe failed", exc_info=True)
+ gpus = []
+ vram_mb = sum(g.vram_mb for g in gpus)
+ if vram_mb > 0:
+ return vram_mb / 1024.0, "nvidia-smi"
+ if sys.platform == "darwin" and platform.machine() == "arm64":
+ try:
+ from jarvis.hardware.detection import _detect_ram
+
+ total_mb, _available = _detect_ram()
+ except Exception: # pragma: no cover
+ log.debug("preflight: RAM probe failed", exc_info=True)
+ total_mb = 0
+ if total_mb > 0:
+ return total_mb / 1024.0, "apple-unified"
+ return 0.0, "none"
+
+
+def _disk_free_gb(root: Path) -> float:
+ probe = root
+ while not probe.exists() and probe.parent != probe:
+ probe = probe.parent
+ try:
+ return shutil.disk_usage(probe).free / (1024**3)
+ except OSError:
+ return 0.0
+
+
+def run_preflight(install_root: Path) -> PreflightReport:
+ """The full go/no-go report for a managed install under ``install_root``."""
+ usable_gb, source = _usable_accelerator_gb()
+ disk_free = _disk_free_gb(install_root)
+ tier = pick_tier(usable_gb)
+ if tier is None:
+ return PreflightReport(
+ ok=False,
+ blocker=(
+ f"This machine has {usable_gb:.0f} GB of usable accelerator "
+ f"memory — under the {FLOOR_GB:.0f} GB minimum for a good "
+ "local realtime experience, so the managed install is not "
+ "offered here."
+ ),
+ actions=(
+ "Use a cloud realtime provider on this machine (same card list).",
+ "Or point this card at a self-hosted server on a stronger machine.",
+ ),
+ usable_gb=usable_gb,
+ memory_source=source,
+ disk_free_gb=disk_free,
+ )
+ needed = tier.download_gb + _DISK_HEADROOM_GB
+ if disk_free < needed:
+ return PreflightReport(
+ ok=False,
+ blocker=(
+ f"Not enough free disk: the {tier.label} stack needs about "
+ f"{needed:.0f} GB free, this disk has {disk_free:.0f} GB."
+ ),
+ actions=(f"Free up at least {needed - disk_free:.0f} GB and retry.",),
+ usable_gb=usable_gb,
+ memory_source=source,
+ disk_free_gb=disk_free,
+ tier=tier,
+ )
+ brain = resolve_brain()
+ if not brain.ok:
+ return PreflightReport(
+ ok=False,
+ blocker=brain.note,
+ actions=brain.actions,
+ usable_gb=usable_gb,
+ memory_source=source,
+ disk_free_gb=disk_free,
+ tier=tier,
+ brain=brain,
+ )
+ return PreflightReport(
+ ok=True,
+ usable_gb=usable_gb,
+ memory_source=source,
+ disk_free_gb=disk_free,
+ tier=tier,
+ stack_sentence=describe_stack(tier),
+ brain=brain,
+ )
+
+
+def report_payload(report: PreflightReport) -> dict[str, object]:
+ """JSON-shaped view of a report for the REST route / CLI."""
+ tier = report.tier
+ return {
+ "ok": report.ok,
+ "blocker": report.blocker,
+ "actions": list(report.actions),
+ "usable_gb": round(report.usable_gb, 1),
+ "memory_source": report.memory_source,
+ "disk_free_gb": round(report.disk_free_gb, 1),
+ "tier": None
+ if tier is None
+ else {
+ "key": tier.key,
+ "label": tier.label,
+ "measured": tier.measured,
+ "target_class": tier.target_class,
+ "download_gb": tier.download_gb,
+ "expected_latency": tier.expected_latency,
+ },
+ "stack_sentence": report.stack_sentence,
+ "brain": None
+ if report.brain is None
+ else {
+ "kind": report.brain.kind,
+ "model": report.brain.model,
+ "note": report.brain.note,
+ },
+ }
diff --git a/jarvis/realtime/local_server/tiers.py b/jarvis/realtime/local_server/tiers.py
new file mode 100644
index 0000000000..83db358c4c
--- /dev/null
+++ b/jarvis/realtime/local_server/tiers.py
@@ -0,0 +1,124 @@
+"""The hardware tier ladder for the managed local realtime server (AD-10).
+
+Five tiers spanning ~12 GB to 128 GB+ of usable accelerator memory, with a
+HARD floor at 12 GB: below it the managed install is refused with an honest
+blocker instead of shipping a degraded experience (maintainer mandate
+2026-08-07).
+
+Bake-off honesty: a tier may only pin a model stack that has been MEASURED
+(recorded audio + numbers), never datasheet-picked. Today only the bottom
+stack is measured (the dev-box configuration: Parakeet TDT CPU STT +
+qwen2.5:7b via Ollama + Qwen3-TTS CustomVoice on GPU, speech-end → first
+audio ~2.4 s warm). Higher tiers therefore install the SAME measured stack
+and say so; their target classes are documented here and flip to pinned
+only when the Chunk-6 bake-off records a winner.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+#: Managed installs are refused below this much usable accelerator memory.
+FLOOR_GB = 12.0
+
+
+@dataclass(frozen=True, slots=True)
+class Tier:
+ key: str
+ label: str
+ #: Minimum usable accelerator memory (dedicated VRAM, or unified memory
+ #: on Apple Silicon) in GiB.
+ min_usable_gb: float
+ #: The brain model the managed install configures today.
+ brain_model: str
+ #: The class of model this tier is MEANT to run once the bake-off has
+ #: measured a winner. Documentation, never something the installer acts on.
+ target_class: str
+ #: Whether the installed stack for this tier is bake-off measured.
+ measured: bool
+ #: Approximate one-time download volume for the managed stack, in GiB
+ #: (venv wheels + first-boot model fetches), stated in the preflight.
+ download_gb: float
+ #: Expected speech-end → first-audio answer latency, warm.
+ expected_latency: str
+
+
+#: Ordered bottom-up; :func:`pick_tier` returns the highest fitting tier.
+TIERS: tuple[Tier, ...] = (
+ Tier(
+ key="t0-12gb",
+ label="12 GB — baseline",
+ min_usable_gb=12.0,
+ brain_model="qwen2.5:7b",
+ target_class="measured dev-box stack (the only recorded configuration)",
+ measured=True,
+ download_gb=14.0,
+ expected_latency="~2-3 s",
+ ),
+ Tier(
+ key="t1-16gb",
+ label="16 GB",
+ min_usable_gb=16.0,
+ brain_model="qwen2.5:7b",
+ target_class="~30B-class brain (pending bake-off)",
+ measured=False,
+ download_gb=14.0,
+ expected_latency="~2-3 s",
+ ),
+ Tier(
+ key="t2-32gb",
+ label="32 GB",
+ min_usable_gb=32.0,
+ brain_model="qwen2.5:7b",
+ target_class="~70B-class brain, quantized (pending bake-off)",
+ measured=False,
+ download_gb=14.0,
+ expected_latency="~2-3 s",
+ ),
+ Tier(
+ key="t3-64gb",
+ label="64 GB",
+ min_usable_gb=64.0,
+ brain_model="qwen2.5:7b",
+ target_class="~70B-class brain, full precision / large MoE (pending bake-off)",
+ measured=False,
+ download_gb=14.0,
+ expected_latency="~2-3 s",
+ ),
+ Tier(
+ key="t4-128gb",
+ label="128 GB+",
+ min_usable_gb=128.0,
+ brain_model="qwen2.5:7b",
+ target_class="frontier open-weights class, ~120B+ MoE (pending bake-off)",
+ measured=False,
+ download_gb=14.0,
+ expected_latency="~2-3 s",
+ ),
+)
+
+
+def pick_tier(usable_gb: float) -> Tier | None:
+ """The highest tier this much usable memory supports, or ``None``.
+
+ ``None`` means the machine is under the hard floor — the caller must
+ surface the honest blocker, never a degraded install.
+ """
+ best: Tier | None = None
+ for tier in TIERS:
+ if usable_gb >= tier.min_usable_gb:
+ best = tier
+ return best
+
+
+def describe_stack(tier: Tier) -> str:
+ """One honest sentence about what this tier actually installs today."""
+ if tier.measured:
+ return (
+ f"Installs the measured baseline stack (brain {tier.brain_model}, local STT + GPU TTS)."
+ )
+ return (
+ f"Installs the measured baseline stack (brain {tier.brain_model}) for "
+ f"now; this tier targets a {tier.target_class} and upgrades once the "
+ "bake-off has recorded a winner."
+ )
diff --git a/tests/unit/realtime/local_server/test_engine.py b/tests/unit/realtime/local_server/test_engine.py
new file mode 100644
index 0000000000..93437c3479
--- /dev/null
+++ b/tests/unit/realtime/local_server/test_engine.py
@@ -0,0 +1,186 @@
+"""Install engine, tier ladder, preflight, and brain resolution contracts."""
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.realtime.local_server import brain_link, install, preflight, tiers
+
+
+class TestTierLadder:
+ def test_below_floor_returns_none(self) -> None:
+ assert tiers.pick_tier(0.0) is None
+ assert tiers.pick_tier(11.9) is None
+
+ def test_floor_and_boundaries(self) -> None:
+ assert tiers.pick_tier(12.0) is not None
+ assert tiers.pick_tier(12.0).key == "t0-12gb"
+ assert tiers.pick_tier(16.0).key == "t1-16gb"
+ assert tiers.pick_tier(31.9).key == "t1-16gb"
+ assert tiers.pick_tier(700.0).key == "t4-128gb"
+
+ def test_only_measured_tiers_may_claim_measured(self) -> None:
+ # Mandate: a tier flips to measured only with a recorded bake-off.
+ measured = [t for t in tiers.TIERS if t.measured]
+ assert [t.key for t in measured] == ["t0-12gb"]
+ for tier in tiers.TIERS:
+ if not tier.measured:
+ assert "pending bake-off" in tier.target_class
+
+ def test_unmeasured_tiers_say_so_in_their_stack_sentence(self) -> None:
+ sentence = tiers.describe_stack(tiers.TIERS[-1])
+ assert "bake-off" in sentence
+
+
+class TestBrainResolution:
+ def test_prefers_the_pinned_model(self) -> None:
+ assert brain_link._pick_model(["llama3.1:8b", "qwen2.5:7b"]) == "qwen2.5:7b"
+
+ def test_skips_non_chat_models(self) -> None:
+ assert brain_link._pick_model(["nomic-embed-text:latest"]) == ""
+ assert brain_link._pick_model(["nomic-embed-text:latest", "mistral:7b"]) == "mistral:7b"
+
+ def test_running_ollama_with_model_is_fully_local(self, monkeypatch) -> None:
+ monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: ["qwen2.5:7b"])
+ resolution = brain_link.resolve_brain()
+ assert resolution.kind == "ollama"
+ assert resolution.ok
+ assert resolution.base_url.endswith("/v1")
+ assert resolution.model == "qwen2.5:7b"
+
+ def test_empty_ollama_blocks_with_pull_action(self, monkeypatch) -> None:
+ monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: [])
+ resolution = brain_link.resolve_brain()
+ assert resolution.kind == "blocked"
+ assert any("ollama pull" in action for action in resolution.actions)
+
+ def test_no_ollama_with_key_goes_cloud_with_honest_note(self, monkeypatch) -> None:
+ monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: None)
+ monkeypatch.setattr(brain_link, "_openai_key", lambda: "sk-test")
+ resolution = brain_link.resolve_brain()
+ assert resolution.kind == "cloud-openai"
+ assert "OpenAI key" in resolution.note
+ assert resolution.base_url == "" # server default; key stays out of commands
+
+ def test_nothing_available_blocks_with_actions(self, monkeypatch) -> None:
+ monkeypatch.setattr(brain_link, "_ollama_tags", lambda base, timeout: None)
+ monkeypatch.setattr(brain_link, "_openai_key", lambda: "")
+ resolution = brain_link.resolve_brain()
+ assert resolution.kind == "blocked"
+ assert len(resolution.actions) == 2
+
+
+class TestPreflight:
+ def test_below_floor_blocks_with_cloud_pointer(self, monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (4.0, "nvidia-smi"))
+ report = preflight.run_preflight(tmp_path)
+ assert not report.ok
+ assert "minimum" in report.blocker
+ assert any("cloud" in a.lower() for a in report.actions)
+ assert report.tier is None
+
+ def test_full_disk_blocks_before_downloading(self, monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))
+ monkeypatch.setattr(preflight, "_disk_free_gb", lambda root: 1.0)
+ report = preflight.run_preflight(tmp_path)
+ assert not report.ok
+ assert "disk" in report.blocker.lower()
+
+ def test_ok_report_carries_tier_stack_and_brain(self, monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))
+ monkeypatch.setattr(preflight, "_disk_free_gb", lambda root: 100.0)
+ monkeypatch.setattr(
+ preflight,
+ "resolve_brain",
+ lambda: brain_link.BrainResolution(
+ kind="ollama", base_url="http://127.0.0.1:11434/v1", model="qwen2.5:7b"
+ ),
+ )
+ report = preflight.run_preflight(tmp_path)
+ assert report.ok
+ assert report.tier is not None and report.tier.key == "t1-16gb"
+ assert report.stack_sentence
+ payload = preflight.report_payload(report)
+ assert payload["tier"]["key"] == "t1-16gb" # type: ignore[index]
+
+ def test_blocked_brain_blocks_the_preflight(self, monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(preflight, "_usable_accelerator_gb", lambda: (16.0, "nvidia-smi"))
+ monkeypatch.setattr(preflight, "_disk_free_gb", lambda root: 100.0)
+ monkeypatch.setattr(
+ preflight,
+ "resolve_brain",
+ lambda: brain_link.BrainResolution(kind="blocked", note="no brain", actions=("x",)),
+ )
+ report = preflight.run_preflight(tmp_path)
+ assert not report.ok
+ assert report.blocker == "no brain"
+
+
+class TestDeriveLaunchCommand:
+ def _brain(self) -> brain_link.BrainResolution:
+ return brain_link.BrainResolution(
+ kind="ollama",
+ base_url="http://127.0.0.1:11434/v1",
+ api_key="ollama",
+ model="qwen2.5:7b",
+ )
+
+ def test_ollama_command_carries_endpoint_and_placeholder_key(self) -> None:
+ cmd = install.derive_launch_command(self._brain(), memory_source="nvidia-smi")
+ assert "--responses_api_base_url http://127.0.0.1:11434/v1" in cmd
+ assert "--responses_api_api_key ollama" in cmd
+ assert "--qwen3_tts_device cuda" in cmd
+ assert "--model_name qwen2.5:7b" in cmd
+
+ def test_cloud_command_never_carries_the_secret(self) -> None:
+ brain = brain_link.BrainResolution(
+ kind="cloud-openai", api_key="sk-secret", model="gpt-5.4-mini"
+ )
+ cmd = install.derive_launch_command(brain, memory_source="nvidia-smi")
+ assert "sk-secret" not in cmd
+ assert "--responses_api_api_key" not in cmd
+
+ def test_apple_unified_memory_maps_to_mps(self) -> None:
+ cmd = install.derive_launch_command(self._brain(), memory_source="apple-unified")
+ assert "--qwen3_tts_device mps" in cmd
+
+
+class TestServerStatusFailClosed:
+ def test_nothing_installed_reports_not_ready(self, monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ status = install.server_status()
+ assert status["ready"] is False
+ assert status["sentence"] == "Managed server not installed."
+
+ def test_partial_install_names_whats_missing(self, monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ python = install._venv_python()
+ python.parent.mkdir(parents=True)
+ python.write_bytes(b"")
+ status = install.server_status()
+ assert status["ready"] is False
+ assert "missing" in str(status["sentence"])
+ components = status["components"]
+ assert components["venv"] is True # type: ignore[index]
+ assert components["patch"] is False # type: ignore[index]
+
+ def test_uninstall_refuses_while_running(self, monkeypatch) -> None:
+ class _Alive:
+ @staticmethod
+ def is_alive() -> bool:
+ return True
+
+ monkeypatch.setattr(install._STATE, "thread", _Alive())
+ ok, message = install.uninstall()
+ assert not ok
+ assert "running" in message
+
+
+class TestSnapshot:
+ def test_snapshot_shape(self) -> None:
+ snap = install.snapshot()
+ assert set(snap) == {"phase", "percent", "detail", "error", "running", "log_tail"}
+
+
+if __name__ == "__main__": # pragma: no cover
+ raise SystemExit(pytest.main([__file__, "-q"]))