Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice-engine): register the local-voice provider with a [voice_engine] config
rubenluetke10-beep0a2464057b9e
diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex b971188e59..27793b046e 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -560,6 +560,9 @@ REALTIME_MODELS: dict[str, list[ModelInfo]] = {# through /v1/models at connect time (same as the local brain card), and a# user who wants a specific one pins it on the card."local-realtime": _curated([("auto", "Chosen by your server")]),+ # local-voice: the language model is picked on the card itself (installed+ # Ollama models first), stored in [voice_engine].llm_model.+ "local-voice": _curated([("auto", "Chosen on the Local voice card")]),"openai-live": _curated([("gpt-live-1", "GPT-Live 1")]),"openai-realtime": _curated([@@ -621,6 +624,8 @@ REALTIME_VOICES: dict[str, list[ModelInfo]] = {# honest entry: the adapter sends no voice override and the server uses its# own default."local-realtime": _curated([("auto", "Your server's own voice")]),+ # local-voice: Pocket or Piper, chosen on the card ([voice_engine].tts).+ "local-voice": _curated([("auto", "Chosen on the Local voice card")]),"openai-realtime": _ids(["alloy",diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 74e42b741c..82858ecba8 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -4453,6 +4453,51 @@ class GoogleAuthConfig(BaseModel):service_account_path: str | None = None+#: Voices the local voice engine can load today (ADR-0037). Pocket TTS is the+#: natural default; Piper is the floor every machine can run. Qwen3-TTS stays+#: out of the switchable set until its premium phase (plan section 6, P4).+VOICE_ENGINE_VOICES: tuple[str, ...] = ("pocket", "piper")+++class VoiceEngineConfig(BaseModel):+ """``[voice_engine]`` — the Jarvis-owned local voice engine (``local-voice``).++ Read by ``jarvis/plugins/realtime/local_voice.py`` (``EngineSettings``) and+ shown on the Local voice card. Written only through+ ``config_writer.set_voice_engine_settings``. ``extra="allow"`` so a newer+ key written by a later build never breaks validation here (AP-16).+ """++ model_config = ConfigDict(extra="allow")++ #: Voice backend: ``pocket`` (natural, CPU) or ``piper`` (floor). An+ #: unknown value falls back to ``pocket`` instead of failing the config.+ tts: str = "pocket"+ #: Ollama tag the engine answers with. Empty = automatic: the model setup+ #: picked (installed models first), else the machine-class default.+ llm_model: str = ""+ #: Languages the engine loads a voice for; the first is the fallback voice.+ languages: list[str] = Field(default_factory=lambda: ["de", "en"])++ @field_validator("tts", mode="before")+ @classmethod+ def _known_voice(cls, value: object) -> str:+ text = str(value or "").strip().lower()+ return text if text in VOICE_ENGINE_VOICES else "pocket"++ @field_validator("llm_model", mode="before")+ @classmethod+ def _strip_model(cls, value: object) -> str:+ return str(value or "").strip()++ @field_validator("languages", mode="before")+ @classmethod+ def _clean_languages(cls, value: object) -> list[str]:+ items = value if isinstance(value, list | tuple) else []+ cleaned = [str(x).strip().lower() for x in items if str(x).strip()]+ return cleaned or ["de", "en"]++class JarvisConfig(BaseModel):"""Root config model."""@@ -4467,6 +4512,8 @@ class JarvisConfig(BaseModel):tts: TTSConfig = Field(default_factory=TTSConfig)brain: BrainConfig = Field(default_factory=BrainConfig)live: LiveConfig = Field(default_factory=LiveConfig)+ # [voice_engine] — the Jarvis-owned local voice engine (ADR-0037).+ voice_engine: VoiceEngineConfig = Field(default_factory=VoiceEngineConfig)# Google key routing (AI Studio vs Vertex express) — see GoogleAuthConfig.google: GoogleAuthConfig = Field(default_factory=GoogleAuthConfig)memory: MemoryConfig = Field(default_factory=MemoryConfig)diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 5fbb9d9abd..df7547b86b 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -34,6 +34,7 @@ from .config import (DEFAULT_CONFIG_FILE,OLLAMA_MODEL_OPTION_KEYS,PROJECT_ROOT,+ VOICE_ENGINE_VOICES,OllamaModelOptions,clear_config_cache,)@@ -1386,6 +1387,42 @@ def set_realtime_fallback_provider(provider: str, *, path: Path = DEFAULT_CONFIG_patch_realtime_provider_toml(path, provider, key="fallback_provider")+def set_voice_engine_settings(+ *,+ tts: str | None = None,+ llm_model: str | None = None,+ path: Path = DEFAULT_CONFIG_FILE,+) -> None:+ """Persist the Local voice card's choices to ``[voice_engine]``.++ ``tts`` must be one of ``config.VOICE_ENGINE_VOICES``; ``llm_model`` is an+ Ollama tag, and an empty string means "automatic". Both land in ONE atomic+ write. Read by ``jarvis/plugins/realtime/local_voice.py``; the running+ engine picks them up on its next start.+ """+ values: dict[str, str | bool | int | float | list[str]] = {}+ if tts is not None:+ voice = tts.strip().lower()+ if voice not in VOICE_ENGINE_VOICES:+ raise ValueError(f"unknown local voice {tts!r}; expected one of {VOICE_ENGINE_VOICES}")+ values["tts"] = voice+ if llm_model is not None:+ model = llm_model.strip()+ if any(ch.isspace() for ch in model) or len(model) > 200:+ raise ValueError(f"not an Ollama model tag: {llm_model!r}")+ values["llm_model"] = model+ if not values:+ return+ first_key, *rest = values+ _patch_table(+ path,+ "voice_engine",+ first_key,+ values[first_key],+ extra={key: values[key] for key in rest},+ )++def set_silence_window_ms(ms: int, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist the voice silence window to ``[speech] vad_silence_ms`` in jarvis.toml.diff --git a/jarvis/costs/model.py b/jarvis/costs/model.pyindex b16fd79744..333e10a576 100644--- a/jarvis/costs/model.py+++ b/jarvis/costs/model.py@@ -106,6 +106,7 @@ LOCAL_PROVIDERS: frozenset[str] = frozenset({"local","local-realtime",+ "local-voice","ollama","llamacpp","llama-cpp",diff --git a/jarvis/plugins/realtime/local_voice.py b/jarvis/plugins/realtime/local_voice.pyindex 47d1ceacdb..ada4c20c21 100644--- a/jarvis/plugins/realtime/local_voice.py+++ b/jarvis/plugins/realtime/local_voice.py@@ -15,6 +15,7 @@ import asyncioimport contextlibimport loggingimport os+import sysimport timefrom collections.abc import AsyncIteratorfrom dataclasses import dataclass, field@@ -26,7 +27,74 @@ log = logging.getLogger(__name__)_INPUT_RATE = 16_000_OUTPUT_RATE = 24_000_READY_TIMEOUT_S = 180.0+_SELFTEST_TIMEOUT_S = 120.0_RESTART_BACKOFF_S = (1.0, 5.0, 30.0)+#: Core load from a warm disk (plan section 7: core ready <= 15 s); scales the+#: "about N s" a refused call hears while the engine loads.+_WARM_LOAD_S = 15.0+#: Measured default for every machine class with an accelerator (plan 12.3).+DEFAULT_LLM = "qwen3.5:4b"+#: Core models the engine cannot start without (``jarvis.voice_engine.models``).+CORE_MODELS = ("silero-vad-v6", "smart-turn-v3.2", "parakeet-tdt-0.6b-v3-int8")+#: What a refused call hears and sees, per output language. ``native.py``+#: speaks ``duplex_unavailable_reason`` verbatim, so it must already be in the+#: caller's language; the card keeps the engine's own detailed reason.+_REFUSALS: dict[str, dict[str, str]] = {+ "not_set_up": {+ "en": "Local voice is not set up on this machine yet. Run its setup on the "+ "Local voice card in Settings.",+ "de": "Die lokale Stimme ist auf diesem Gerät noch nicht " # i18n-allow+ "eingerichtet. Starte die Einrichtung in den Einstellungen " # i18n-allow+ "auf der Karte Lokale Stimme.", # i18n-allow+ "es": "La voz local aún no está configurada en este equipo. " # i18n-allow+ "Inicia la configuración en la tarjeta Voz local de los " # i18n-allow+ "Ajustes.", # i18n-allow+ },+ "loading": {+ "en": "Local voice is still loading ({percent} %). Please try again in about "+ "{eta} seconds.",+ "de": "Die lokale Stimme lädt noch ({percent} %). Versuch es in " # i18n-allow+ "etwa {eta} Sekunden noch einmal.", # i18n-allow+ "es": "La voz local aún se está cargando ({percent} %). Vuelve a " # i18n-allow+ "intentarlo en unos {eta} segundos.", # i18n-allow+ },+ "failed": {+ "en": "Local voice could not start. The Local voice card in Settings shows why.",+ "de": "Die lokale Stimme konnte nicht starten. Die Karte Lokale " # i18n-allow+ "Stimme in den Einstellungen zeigt den Grund.", # i18n-allow+ "es": "La voz local no pudo arrancar. La tarjeta Voz local de los " # i18n-allow+ "Ajustes muestra el motivo.", # i18n-allow+ },+}+NOT_SET_UP_REASON = _REFUSALS["not_set_up"]["en"]+++def refusal(kind: str, language: str, **values: object) -> str:+ """One refusal sentence in ``language`` (de/en/es; anything else is English)."""+ table = _REFUSALS[kind]+ return table.get(language, table["en"]).format(**values)+++def _call_language(cfg: Any) -> str:+ """The language a call starts in, from the one authority (``turn_language``).++ A reply-language pin wins; else a pinned recognition language; else the+ app's interface language. Mirrors how the live session picks its first+ language, so a refusal is spoken in the language the call would have used.+ """+ try:+ from jarvis.core.turn_language import resolve_output_language # noqa: PLC0415++ ui_language = str(getattr(getattr(cfg, "ui", None), "language", "") or "en")+ return resolve_output_language(+ getattr(getattr(cfg, "brain", None), "reply_language", "auto"),+ getattr(getattr(cfg, "stt", None), "language", "auto"),+ "",+ default=ui_language if ui_language in _REFUSALS["failed"] else "en",+ )+ except Exception: # noqa: BLE001 - a refusal in English beats no refusal+ log.debug("local voice: call language unresolved; refusing in English", exc_info=True)+ return "en"@dataclass(frozen=True, slots=True)@@ -70,28 +138,38 @@ class EngineSettings:languages: list[str] = field(default_factory=lambda: ["de", "en"])tts: str = "pocket"tts_options: dict[str, Any] = field(default_factory=dict)- llm_model: str = "qwen3.5:4b-voice-8k"+ llm_model: str = DEFAULT_LLMllm_base_url: str = "http://127.0.0.1:11434"@classmethoddef from_config(cls, cfg: Any) -> EngineSettings:+ """Settings from ``[voice_engine]``, the last setup's record and defaults.++ ``cfg`` may be ``None`` (a provider built without a config): then the+ app's current configuration is read. The model is the card's explicit+ pick, else what setup chose (installed models first), else the measured+ default. No network call happens here; this runs on the call path.+ """+ if cfg is None:+ cfg = _current_config()section = getattr(cfg, "voice_engine", None)def pick(name: str, default: Any) -> Any:value = getattr(section, name, None) if section is not None else None- return default if value in (None, "") else value+ return default if value in (None, "", [], {}) else valuehome = pick("home", os.environ.get("JARVIS_VOICE_ENGINE_HOME") or None)+ recorded = _setup_record(home)return cls(python=str(pick("python", os.environ.get("JARVIS_VOICE_ENGINE_PYTHON")or _default_python(home))),- package_root=pick("package_root", _package_root()),+ package_root=pick("package_root", _package_root(home)),home=home,languages=list(pick("languages", ["de", "en"])),tts=str(pick("tts", "pocket")),tts_options=dict(pick("tts_options", {})),- llm_model=str(pick("llm_model", "qwen3.5:4b-voice-8k")),- llm_base_url=str(pick("llm_base_url", "http://127.0.0.1:11434")),+ llm_model=str(pick("llm_model", recorded.get("llm_model") or DEFAULT_LLM)),+ llm_base_url=str(pick("llm_base_url", _ollama_root())),)def configure_message(self) -> dict[str, Any]:@@ -100,24 +178,83 @@ class EngineSettings:"llm": {"model": self.llm_model, "base_url": self.llm_base_url}}-def _package_root() -> str | None:- """Directory that holds the ``jarvis`` package, for a source checkout."""+def _engine_home(home: str | None) -> Path:+ from jarvis.voice_engine.paths import engine_home # noqa: PLC0415 - plugin rule++ return Path(home) if home else engine_home()+++def _package_root(home: str | None = None) -> str | None:+ """Directory the worker imports ``jarvis.voice_engine`` from.++ A source checkout runs the live source, so an edit needs no re-setup.+ A frozen build has no importable source tree; it runs the copy that+ setup placed under the engine home (plan section 4.10).+ """+ if not getattr(sys, "frozen", False):+ try:+ import jarvis # noqa: PLC0415 - lazily, plugin rule++ root = Path(jarvis.__file__).resolve().parent.parent+ if (root / "jarvis" / "voice_engine" / "worker.py").is_file():+ return str(root)+ except (ImportError, AttributeError, TypeError):+ log.debug("local voice: no importable source tree", exc_info=True)+ copy = _engine_home(home) / "app"+ return str(copy) if (copy / "jarvis" / "voice_engine" / "worker.py").is_file() else None+++def _default_python(home: str | None) -> str:+ from jarvis.voice_engine.paths import venv_python # noqa: PLC0415 - plugin rule++ return str(venv_python(_engine_home(home)))+++def _setup_record(home: str | None) -> dict[str, Any]:+ from jarvis.voice_engine.paths import read_setup_state # noqa: PLC0415 - plugin rule++ return read_setup_state(_engine_home(home))+++def _ollama_root() -> str:+ """The configured Ollama server, the one Jarvis itself starts and stops."""try:- import jarvis # noqa: PLC0415 - lazily, plugin rule+ from jarvis.brain.ollama_pull import server_root # noqa: PLC0415 - plugin rule- return str(Path(jarvis.__file__).resolve().parent.parent)- except (ImportError, AttributeError, TypeError):- # Frozen builds install the engine package into the engine's own- # environment instead (plan section 4.10).+ return server_root()+ except Exception: # noqa: BLE001 - an unreadable config keeps the vendor default+ log.debug("local voice: Ollama root unresolved; using the default", exc_info=True)+ return "http://127.0.0.1:11434"+++def _current_config() -> Any:+ try:+ from jarvis.core.config import load_config # noqa: PLC0415 - plugin rule++ return load_config()+ except Exception: # noqa: BLE001 - defaults still describe a usable engine+ log.debug("local voice: config unreadable; using defaults", exc_info=True)return None-def _default_python(home: str | None) -> str:- from jarvis.voice_engine.paths import engine_home # noqa: PLC0415+def engine_installed(settings: EngineSettings) -> bool:+ """The engine's Python exists and its core models are on disk."""+ if not Path(settings.python).is_file():+ return False+ try:+ from jarvis.voice_engine import models # noqa: PLC0415 - plugin rule++ root = _engine_home(settings.home) / "models"+ return all(models.is_present(name, root) for name in CORE_MODELS)+ except (ImportError, OSError):+ # An unreadable model store is "not installed", never "ready".+ return False+- root = Path(home) if home else engine_home()- venv = root / "venv"- return str(venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python"))+def _worker_extra_env(home: Path) -> dict[str, str]:+ """Point the worker at the model cache setup filled (Pocket TTS weights)."""+ cache = home / "hf"+ return {"HF_HOME": str(cache)} if cache.is_dir() else {}class _Engine:@@ -139,6 +276,8 @@ class _Engine:self._slots: dict[int, LocalVoiceSession] = {}self._next_slot = 1self._failures = 0+ self._starting: asyncio.Task[None] | None = None+ self._selftests: list[asyncio.Future[dict[str, Any]]] = []async def ensure_started(self) -> None:async with self._start_lock:@@ -147,11 +286,13 @@ class _Engine:from jarvis.voice_engine.client import EngineClient, worker_env # noqa: PLC0415settings = self.settings+ home = _engine_home(settings.home)env = worker_env(package_root=Path(settings.package_root) if settings.package_root else None,- home=Path(settings.home) if settings.home else None,+ home=home,+ extra=_worker_extra_env(home),)- stderr = Path(settings.home) / "worker.log" if settings.home else None+ stderr = home / "worker.log"client = EngineClient(settings.python, env=env, stderr_path=stderr)self.phase, self.stage, self.reason = "starting", "process", ""self._ready.clear()@@ -161,6 +302,40 @@ class _Engine:self._audio_router = asyncio.get_running_loop().create_task(self._route_audio(client))await client.send(settings.configure_message())+ def start_soon(self) -> None:+ """Start the worker in the background; a caller never waits for it."""+ if self._client is not None or (self._starting and not self._starting.done()):+ return+ self._starting = asyncio.get_running_loop().create_task(self._start_logged())++ async def _start_logged(self) -> None:+ try:+ await self.ensure_started()+ except (OSError, RuntimeError, TimeoutError) as exc:+ log.warning("local voice engine did not start: %s", exc)+ self.phase = "failed"+ self.reason = f"The local voice engine did not start: {exc}"+ self._ready.set()++ def reset_failures(self) -> None:+ """A user-started retry (setup, self-test) clears the crash budget."""+ self._failures = 0+ if self.phase == "failed" and self._client is None:+ self.phase, self.reason = "stopped", ""++ async def selftest(self, timeout_s: float = _SELFTEST_TIMEOUT_S) -> dict[str, Any]:+ """Run the worker's self-test: speak, hear and answer once per language."""+ if self._client is None or self.phase != "ready":+ raise RuntimeError(self.reason or "The local voice is not ready.")+ waiter: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()+ self._selftests.append(waiter)+ try:+ await self._client.send({"type": "selftest"})+ return await asyncio.wait_for(waiter, timeout_s)+ finally:+ with contextlib.suppress(ValueError):+ self._selftests.remove(waiter)+async def wait_ready(self, timeout_s: float) -> bool:try:await asyncio.wait_for(self._ready.wait(), timeout_s)@@ -175,6 +350,11 @@ class _Engine:if kind == "_exited":await self._on_exit()return+ if kind == "selftest.result":+ for waiter in list(self._selftests):+ if not waiter.done():+ waiter.set_result(dict(message))+ continueif kind == "state":self.phase = str(message.get("phase", self.phase))self.stage = str(message.get("stage", ""))@@ -209,6 +389,9 @@ class _Engine:self._failures += 1self.phase = "failed" if self._failures >= len(_RESTART_BACKOFF_S) else "stopped"self.reason = self.reason or "The local voice engine stopped."+ for waiter in self._selftests:+ if not waiter.done():+ waiter.set_exception(RuntimeError(self.reason))self._ready.set()async def open(self, provider: LocalVoiceProvider, cfg: Any) -> LocalVoiceSession:@@ -388,35 +571,41 @@ class LocalVoiceProvider:_engine: ClassVar[_Engine | None] = None- def __init__(self, settings: EngineSettings | None = None) -> None:+ def __init__(self, settings: EngineSettings | None = None, *, language: str = "en") -> None:self._settings = settingsself.duplex_unavailable_reason = ""+ #: Language of the refusal sentences (de/en/es); see ``_call_language``.+ self.language = language@classmethoddef from_runtime_config(cls, cfg: Any) -> LocalVoiceProvider:- return cls(EngineSettings.from_config(cfg))+ return cls(EngineSettings.from_config(cfg), language=_call_language(cfg))@classmethoddef external_login_ready(cls, cfg: Any = None) -> bool:"""Installed means: the engine's Python exists and the core models are on disk."""- settings = EngineSettings.from_config(cfg)- if not Path(settings.python).is_file():- return False- try:- from jarvis.voice_engine import models # noqa: PLC0415-- return all(models.is_present(n) for n in- ("silero-vad-v6", "smart-turn-v3.2", "parakeet-tdt-0.6b-v3-int8"))- except (ImportError, OSError):- # An unreadable model store is "not installed", never "ready".- return False+ return engine_installed(EngineSettings.from_config(cfg))@classmethoddef _shared(cls, settings: EngineSettings) -> _Engine:- if cls._engine is None or cls._engine.settings != settings:+ previous = cls._engine+ if previous is None or previous.settings != settings:cls._engine = _Engine(settings)+ if previous is not None and previous._client is not None:+ # Changed settings (a new voice or model) start a new worker;+ # the old one must not linger with its models loaded.+ try:+ asyncio.get_running_loop().create_task(previous.stop())+ except RuntimeError:+ log.warning("local voice: a replaced engine could not be stopped "+ "outside an event loop; it exits with the app")return cls._engine+ @classmethod+ def shared_engine(cls, cfg: Any = None) -> _Engine:+ """The engine this app's calls use, for the card's status and self-test."""+ return cls._shared(EngineSettings.from_config(cfg))+@classmethodasync def prespawn_transport(cls, cfg: Any) -> bool:if not cls.external_login_ready(cfg):@@ -433,20 +622,29 @@ class LocalVoiceProvider:return await engine.wait_ready(_READY_TIMEOUT_S)async def can_open_duplex_session(self) -> bool:+ """Answer at once from the worker's state; never wait for it to load.++ A call during warm-up hears why and roughly how long within a second+ (plan section 4.9); the start itself runs in the background.+ """settings = self._settings or EngineSettings.from_config(None)engine = self._shared(settings)- if engine.phase == "ready":+ if engine.phase == "ready" and engine._client is not None:self.duplex_unavailable_reason = ""return True- if engine.phase in ("stopped", "failed") and engine._client is None:- with contextlib.suppress(OSError, RuntimeError):- await engine.ensure_started()+ if engine._client is None:+ if not engine_installed(settings):+ self.duplex_unavailable_reason = refusal("not_set_up", self.language)+ return False+ if engine.phase != "failed":+ engine.start_soon()if engine.phase == "failed":- self.duplex_unavailable_reason = engine.reason or "The local voice could not start."+ log.warning("local voice refused a call: %s", engine.reason or "engine failed")+ self.duplex_unavailable_reason = refusal("failed", self.language)else:- percent = int(engine.progress * 100)- self.duplex_unavailable_reason = (- f"The local voice is still loading ({engine.stage or 'starting'}, {percent} %)."+ eta_s = max(1, round((1.0 - engine.progress) * _WARM_LOAD_S))+ self.duplex_unavailable_reason = refusal(+ "loading", self.language, percent=int(engine.progress * 100), eta=eta_s)return Falsediff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 1051f0669d..94f8d8e1b8 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -946,6 +946,29 @@ PROVIDERS: tuple[ProviderSpec, ...] = (),alt_credential=_VERTEX_PROJECT_PATH,),+ # The Jarvis-owned local voice engine (ADR-0037): one child process per+ # app, speech on the CPU, answers from the local Ollama server. Keyless and+ # on-device; the card carries its own setup, self-test and status+ # (``voice_engine`` in the provider payload). Experimental until the P2+ # gate in docs/local-live-voice-rebuild.md passes.+ ProviderSpec(+ id="local-voice",+ label="Local voice (on this machine)",+ tier="realtime",+ auth_mode="none",+ secret_keys=(),+ dashboard_url=None,+ signup_url=None,+ credential_help=(+ "Voice calls that run entirely on this machine: no API key, no "+ "cloud account, no audio leaving the device. Setup downloads a "+ "speech engine and its models (about 1.5 GB) plus a language model "+ "for the local Ollama server, then proves the whole chain with a "+ "short self-test. A graphics card makes answers faster; without "+ "one it still works, just slower."+ ),+ experimental=True,+ ),# The local option this tier lacked entirely: every other realtime card# bills a hosted account, so an install running brain, recognizer and voice# on its own hardware still had to leave the machine for the low-latencydiff --git a/jarvis/voice_engine/paths.py b/jarvis/voice_engine/paths.pyindex e76062a451..cdc930f26d 100644--- a/jarvis/voice_engine/paths.py+++ b/jarvis/voice_engine/paths.py@@ -8,11 +8,14 @@ model stores must not be uploaded. The app passes its own location throughfrom __future__ import annotations+import jsonimport osimport sysfrom pathlib import Path+from typing import AnyENV_HOME = "JARVIS_VOICE_ENGINE_HOME"+SETUP_STATE_FILE = "setup.json"def engine_home() -> Path:@@ -36,3 +39,23 @@ def models_dir() -> Path:def results_dir() -> Path:return engine_home() / "bench-results"+++def venv_python(home: Path | None = None) -> Path:+ """The interpreter of the engine's own environment (created by the app's setup)."""+ venv = (home or engine_home()) / "venv"+ return venv / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+++def read_setup_state(home: Path | None = None) -> dict[str, Any]:+ """What the last finished setup recorded (chosen model, voice, versions).++ An absent or unreadable file is an empty record: "never set up", never an+ error, because a status read must not fail on a half-written home.+ """+ path = (home or engine_home()) / SETUP_STATE_FILE+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ return data if isinstance(data, dict) else {}diff --git a/pyproject.toml b/pyproject.tomlindex 55d1694c36..f44aeba2bd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -613,6 +613,10 @@ vertex-live = "jarvis.plugins.realtime.gemini_live:VertexLiveProvider"# this tier lacked entirely. Keyless; only ever used when explicitly selected# with a server URL configured.local-realtime = "jarvis.plugins.realtime.openai_realtime:LocalRealtimeProvider"+# The Jarvis-owned local voice engine (ADR-0037): a child worker in its own+# environment, set up from the Local voice card. Keyless, never an ambient+# fallback; replaces local-realtime at cutover (P5).+local-voice = "jarvis.plugins.realtime.local_voice:LocalVoiceProvider"[project.entry-points."jarvis.tool"]live-screen-snapshot = "jarvis.plugins.tool.live_screen:LiveScreenTool"@@ -890,6 +894,9 @@ jarvis = [# install.py read them via Path(__file__))."realtime/local_server/patches/*.patch","realtime/local_server/pins/*.txt",+ # Pinned package set of the local voice engine's own environment+ # (realtime/local_voice_setup.py reads it via Path(__file__)).+ "voice_engine/requirements-engine.txt",][tool.setuptools.data-files]diff --git a/tests/unit/voice_engine/test_local_voice_adapter.py b/tests/unit/voice_engine/test_local_voice_adapter.pyindex 28d7a16a69..b180c433ec 100644--- a/tests/unit/voice_engine/test_local_voice_adapter.py+++ b/tests/unit/voice_engine/test_local_voice_adapter.py@@ -3,18 +3,23 @@from __future__ import annotationsimport asyncio+import jsonfrom dataclasses import dataclass, field+from pathlib import Pathfrom types import SimpleNamespacefrom typing import Anyimport pytest+from jarvis.core.config import JarvisConfig, VoiceEngineConfigfrom jarvis.plugins.realtime.local_voice import (EngineSettings,LocalVoiceProvider,_Engine,)from jarvis.realtime.protocol import RealtimeProvider+from jarvis.voice_engine import models+from jarvis.voice_engine.paths import venv_pythonfrom jarvis.voice_engine.protocol import AudioFrame@@ -137,14 +142,162 @@ async def test_an_engine_exit_ends_the_call_with_an_error() -> None:@pytest.mark.asyncio-async def test_a_loading_engine_refuses_fast_with_its_stage() -> None:+async def test_a_loading_engine_refuses_fast_with_its_progress() -> None:provider = LocalVoiceProvider(_settings())engine = LocalVoiceProvider._shared(_settings())engine._client = FakeClient()engine.phase, engine.stage, engine.progress = "loading", "stt", 0.2try:assert await provider.can_open_duplex_session() is False- assert "stt" in provider.duplex_unavailable_reasonassert "20 %" in provider.duplex_unavailable_reason+ assert "about 12 seconds" in provider.duplex_unavailable_reasonfinally:LocalVoiceProvider._engine = None+++def _installed_home(home: Path) -> EngineSettings:+ """A fake engine home that passes the installed check (no real engine inside)."""+ python = venv_python(home)+ python.parent.mkdir(parents=True, exist_ok=True)+ python.write_text("", encoding="utf-8")+ for name in ("silero-vad-v6", "smart-turn-v3.2", "parakeet-tdt-0.6b-v3-int8"):+ path = models.model_path(name, home / "models")+ if models.REGISTRY[name].is_archive:+ path.mkdir(parents=True, exist_ok=True)+ (path / "model.onnx").write_bytes(b"x")+ else:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"x")+ return EngineSettings(python=str(python), package_root=None, home=str(home))+++def test_the_tool_declaration_budget_is_declared() -> None:+ assert LocalVoiceProvider.tool_declaration_budget_tokens == 2000+++async def test_an_engine_that_was_never_set_up_refuses_with_the_next_step(+ tmp_path: Path,+) -> None:+ provider = LocalVoiceProvider(EngineSettings(python=str(tmp_path / "none"),+ package_root=None, home=str(tmp_path)))+ try:+ assert await provider.can_open_duplex_session() is False+ assert "not set up" in provider.duplex_unavailable_reason+ assert LocalVoiceProvider._engine._client is None+ assert LocalVoiceProvider._engine._starting is None+ finally:+ LocalVoiceProvider._engine = None+++async def test_an_installed_engine_starts_in_the_background_and_answers_at_once(+ tmp_path: Path,+) -> None:+ settings = _installed_home(tmp_path)+ provider = LocalVoiceProvider(settings)+ engine = LocalVoiceProvider._shared(settings)+ starts: list[int] = []+ gate = asyncio.Event()++ async def slow_start() -> None:+ starts.append(1)+ engine.phase, engine.stage, engine.progress = "loading", "tts:de", 0.4+ await gate.wait()++ engine.ensure_started = slow_start+ try:+ async with asyncio.timeout(0.5):+ assert await provider.can_open_duplex_session() is False+ await asyncio.sleep(0)+ assert starts == [1]+ assert await provider.can_open_duplex_session() is False+ assert starts == [1] # joined, not started twice+ assert "40 %" in provider.duplex_unavailable_reason+ assert "about 9 seconds" in provider.duplex_unavailable_reason+ finally:+ gate.set()+ LocalVoiceProvider._engine = None+++async def test_a_selftest_result_is_routed_to_its_caller() -> None:+ engine, client = await _running_engine()+ task = asyncio.get_running_loop().create_task(engine.selftest(timeout_s=2))+ await asyncio.sleep(0)+ assert client.sent[-1] == {"type": "selftest"}+ client.messages.put_nowait({"type": "selftest.result", "ok": True, "llm": {"ms": 390}})+ result = await task+ assert result["ok"] is True and result["llm"]["ms"] == 390+ await engine.stop()+++async def test_new_settings_replace_and_stop_the_running_worker() -> None:+ engine, _client = await _running_engine()+ LocalVoiceProvider._engine = engine+ stopped: list[int] = []++ async def stop() -> None:+ stopped.append(1)++ engine.stop = stop+ try:+ other = EngineSettings(python="python", package_root=None, tts="piper")+ replacement = LocalVoiceProvider._shared(other)+ await asyncio.sleep(0)+ assert replacement is not engine and stopped == [1]+ finally:+ LocalVoiceProvider._engine = None+ engine._router.cancel()+ engine._audio_router.cancel()+++async def test_a_refusal_is_spoken_in_the_language_the_call_starts_in(tmp_path: Path) -> None:+ german = SimpleNamespace(+ brain=SimpleNamespace(reply_language="de"), stt=SimpleNamespace(language="auto"),+ ui=SimpleNamespace(language="en"),+ voice_engine=SimpleNamespace(home=str(tmp_path), python=str(tmp_path / "none")),+ )+ provider = LocalVoiceProvider.from_runtime_config(german)+ try:+ assert provider.language == "de"+ assert await provider.can_open_duplex_session() is False+ assert "noch nicht eingerichtet" in provider.duplex_unavailable_reason # i18n-allow+ finally:+ LocalVoiceProvider._engine = None+ auto_ui_es = SimpleNamespace(brain=SimpleNamespace(reply_language="auto"),+ stt=SimpleNamespace(language="auto"),+ ui=SimpleNamespace(language="es"))+ assert LocalVoiceProvider.from_runtime_config(auto_ui_es).language == "es"+ assert LocalVoiceProvider.from_runtime_config(SimpleNamespace()).language == "en"+++async def test_a_failed_engine_refuses_in_words_not_a_traceback() -> None:+ provider = LocalVoiceProvider(_settings(), language="de")+ engine = LocalVoiceProvider._shared(_settings())+ engine._client = FakeClient()+ engine.phase, engine.reason = "failed", "The local voice could not load: CUDA error 700"+ try:+ assert await provider.can_open_duplex_session() is False+ assert "CUDA" not in provider.duplex_unavailable_reason+ assert "konnte nicht starten" in provider.duplex_unavailable_reason # i18n-allow+ finally:+ LocalVoiceProvider._engine = None+++def test_the_model_comes_from_the_card_then_setup_then_the_default(tmp_path: Path) -> None:+ home = tmp_path / "engine"+ cfg = SimpleNamespace(voice_engine=SimpleNamespace(home=str(home), llm_model="",+ tts="pocket", languages=["de", "en"]))+ assert EngineSettings.from_config(cfg).llm_model == "qwen3.5:4b"+ home.mkdir()+ (home / "setup.json").write_text(json.dumps({"llm_model": "granite4.2:8b"}),+ encoding="utf-8")+ assert EngineSettings.from_config(cfg).llm_model == "granite4.2:8b"+ cfg.voice_engine.llm_model = "qwen3.5:2b"+ assert EngineSettings.from_config(cfg).llm_model == "qwen3.5:2b"+ typed = JarvisConfig(voice_engine=VoiceEngineConfig(tts="nonsense", languages=[]))+ assert (typed.voice_engine.tts, typed.voice_engine.languages) == ("pocket", ["de", "en"])