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): engine worker core - protocol, conversation loop, client
rubenluetke10-beepf2de84607fe3
diff --git a/jarvis/voice_engine/bench/__main__.py b/jarvis/voice_engine/bench/__main__.pyindex d816c688e0..5143569356 100644--- a/jarvis/voice_engine/bench/__main__.py+++ b/jarvis/voice_engine/bench/__main__.py@@ -71,6 +71,14 @@ def build_parser() -> argparse.ArgumentParser:e2e.add_argument("--opt", action="append", default=[], help="TTS option key=value")common(memory := sub.add_parser("memory", help="resident memory per component"))memory.add_argument("--tts", type=_list, default=["piper", "pocket"])+ common(worker := sub.add_parser("worker", help="P1: real-time talk through the worker"),+ llm=True)+ worker.add_argument("--tts", default="pocket", choices=["piper", "pocket", "qwen3"])+ worker.add_argument("--voice", default="piper", choices=["piper", "pocket"])+ worker.add_argument("--opt", action="append", default=[], help="TTS option key=value")+ worker.add_argument("--barge-trials", type=int, default=3)+ drill = sub.add_parser("drill", help="P1: kill the worker's parent, measure the orphan")+ drill.add_argument("--trials", type=int, default=3)sub.add_parser("summary", help="print the latest result of every suite")return parser@@ -116,6 +124,15 @@ def main(argv: list[str] | None = None) -> int:tts_options=_options(args.opt))elif args.command == "memory":payload = suites.run_memory(args.languages, args.tts)+ elif args.command == "worker":+ from jarvis.voice_engine.bench.worker_suite import run_worker # noqa: PLC0415++ payload = run_worker(args.model, args.tts, args.languages, voice_kind=args.voice,+ tts_options=_options(args.opt), barge_trials=args.barge_trials)+ elif args.command == "drill":+ from jarvis.voice_engine.bench.worker_suite import run_drill # noqa: PLC0415++ payload = run_drill(args.trials)else: # pragma: no cover - argparse enforces the choicesraise SystemExit(f"unknown command {args.command}")path = suites.write_report(args.command, payload, before)diff --git a/jarvis/voice_engine/bench/worker_suite.py b/jarvis/voice_engine/bench/worker_suite.pynew file mode 100644index 0000000000..70c9f23e1d--- /dev/null+++ b/jarvis/voice_engine/bench/worker_suite.py@@ -0,0 +1,290 @@+"""P1 gate measurements through the real worker process.++``run_worker`` starts the engine worker the way the app will (child process,+stdin/stdout frames), configures it, runs its self-test, then talks to it in+real time: synthetic user speech is streamed in 20 ms chunks at wall-clock+pace, the bench plays the app's part (requests the answer after the final+transcript, answers tool calls) and measures speech end -> first audio frame+on the receiving side, plus barge-in latency. ``run_drill`` kills the worker's+parent and measures how long the worker survives it.+"""++from __future__ import annotations++import asyncio+import json+import subprocess+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np++from jarvis.voice_engine import protocol as p+from jarvis.voice_engine.audio import STT_RATE, silence, to_pcm16+from jarvis.voice_engine.bench import corpus+from jarvis.voice_engine.bench.speech import Components, UserVoice+from jarvis.voice_engine.bench.stats import summary+from jarvis.voice_engine.bench.suites import _FAKE_RESULTS+from jarvis.voice_engine.client import EngineClient, worker_env+from jarvis.voice_engine.paths import results_dir++CHUNK_SAMPLES = 320 # 20 ms, the browser's usual capture quantum+_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0+_BARGE = {"de": "Stopp, warte mal kurz.", "en": "Stop, wait a moment."} # i18n-allow: fixture+_LONG = {"de": "Erklär mir ausführlich, wie ein Schwarzes Loch entsteht.", # i18n-allow: fixture+ "en": "Explain in detail how a black hole forms."}+++def package_root() -> Path:+ return Path(__file__).resolve().parents[3]+++def _declarations() -> list[dict[str, Any]]:+ return [{"name": t["function"]["name"], "description": t["function"]["description"],+ "parameters": t["function"]["parameters"]} for t in corpus.tools()]+++class _Conversation:+ """Plays the app's side of one session and timestamps what comes back."""++ def __init__(self, client: EngineClient, session: str, slot: int, language: str) -> None:+ self.client, self.session, self.slot, self.language = client, session, slot, language+ self.seq = 0+ self.events: list[tuple[float, dict[str, Any]]] = []+ self.first_audio_at: float | None = None+ self.last_audio_at: float | None = None+ self.audio_frames = 0+ self.done = asyncio.Event()+ self.interrupted_at: float | None = None+ self.metrics: dict[str, Any] = {}++ def reset(self) -> None:+ self.events.clear()+ self.first_audio_at = None+ self.last_audio_at = None+ self.audio_frames = 0+ self.done = asyncio.Event()+ self.interrupted_at = None+ self.metrics = {}++ async def pump(self) -> None:+ async def messages() -> None:+ while True:+ message = await self.client.messages.get()+ if message.get("type") == "_exited":+ self.done.set()+ return+ now = time.monotonic()+ self.events.append((now, message))+ kind = message.get("type")+ if kind == p.TRANSCRIPT_INPUT and message.get("final"):+ await self.client.send({"type": p.RESPONSE_REQUEST, "session": self.session,+ "language": self.language})+ elif kind == p.TOOL_CALL:+ result = _FAKE_RESULTS.get(message.get("name"), {"success": True})+ await self.client.send({"type": p.TOOL_RESULT, "session": self.session,+ "call_id": message["call_id"], "result": result})+ elif kind == p.INTERRUPTED and self.interrupted_at is None:+ self.interrupted_at = now+ elif kind == p.METRICS:+ self.metrics = message.get("turn", {})+ elif kind == p.RESPONSE_DONE:+ self.done.set()++ async def audio() -> None:+ while True:+ await self.client.audio_frames.get()+ now = time.monotonic()+ self.audio_frames += 1+ if self.first_audio_at is None:+ self.first_audio_at = now+ self.last_audio_at = now++ await asyncio.gather(messages(), audio())++ async def stream(self, samples: np.ndarray, *, until_done_s: float = 0.0) -> float:+ """Send audio at wall-clock pace; returns the monotonic start time."""+ start = time.monotonic()+ for index in range(0, samples.size, CHUNK_SAMPLES):+ chunk = samples[index : index + CHUNK_SAMPLES]+ self.seq += 1+ await self.client.send_audio(self.slot, self.seq, to_pcm16(chunk))+ target = start + (index + CHUNK_SAMPLES) / STT_RATE+ await asyncio.sleep(max(0.0, target - time.monotonic()))+ if until_done_s > 0:+ quiet = silence(CHUNK_SAMPLES / STT_RATE, STT_RATE)+ tail_start = time.monotonic()+ while not self.done.is_set() and time.monotonic() - tail_start < until_done_s:+ self.seq += 1+ await self.client.send_audio(self.slot, self.seq, to_pcm16(quiet))+ await asyncio.sleep(CHUNK_SAMPLES / STT_RATE)+ return start+++def _speech_end(samples: np.ndarray, threshold: float = 0.01) -> float:+ voiced = np.flatnonzero(np.abs(samples) > threshold)+ return (voiced[-1] + 1) / STT_RATE if voiced.size else 0.0+++async def _run(model: str, tts: str, languages: list[str], voice_kind: str,+ tts_options: dict[str, Any], barge_trials: int) -> dict[str, Any]:+ client = EngineClient(sys.executable, env=worker_env(package_root=package_root()),+ stderr_path=results_dir() / "worker-stderr.log")+ started = time.monotonic()+ hello = await client.start()+ await client.send({"type": p.CONFIGURE, "languages": languages, "tts": tts,+ "tts_options": tts_options, "llm": {"model": model}})+ state = await client.wait_for(+ lambda m: m["type"] == p.STATE and m.get("phase") in ("ready", "failed"), 600+ )+ ready_s = round(time.monotonic() - started, 2)+ report: dict[str, Any] = {"model": model, "tts": tts, "tts_options": tts_options,+ "voice": voice_kind, "hello": hello, "ready_s": ready_s,+ "state": state}+ if state.get("phase") != "ready":+ await client.close()+ return report+ await client.send({"type": p.SELFTEST})+ report["selftest"] = await client.wait_for(lambda m: m["type"] == p.SELFTEST_RESULT, 300)++ voice = UserVoice(Components(), voice_kind)+ items: list[dict[str, Any]] = []+ barges: list[dict[str, Any]] = []+ for slot, language in enumerate(languages, start=1):+ session = f"bench-{language}"+ await client.send({"type": p.SESSION_OPEN, "session": session, "slot": slot,+ "language": language, "tools": _declarations(),+ "instructions": corpus.load(language)["system_prompt"]})+ await client.wait_for(lambda m, s=session: m["type"] == p.SESSION_READY+ and m.get("session") == s, 30)+ convo = _Conversation(client, session, slot, language)+ pump = asyncio.get_running_loop().create_task(convo.pump())+ texts = [(t, "dialog") for t in corpus.load(language)["dialog"]]+ seen: set[str] = set()+ for case in corpus.tool_cases(language):+ if case.tool and case.tool not in seen and case.tool != "end_call":+ seen.add(case.tool)+ texts.append((case.utterance, "tool"))+ for text, kind in texts:+ convo.reset()+ samples = voice.render(text, language)+ start = await convo.stream(samples, until_done_s=20.0)+ speech_end = start + _speech_end(samples)+ first = convo.first_audio_at+ items.append({+ "language": language, "kind": kind, "text": text,+ "e2e_ms": round((first - speech_end) * 1000.0, 1) if first else None,+ "done": convo.done.is_set(), "audio_frames": convo.audio_frames,+ "worker": convo.metrics,+ "transcript": next((m.get("text") for _, m in convo.events+ if m.get("type") == p.TRANSCRIPT_INPUT), None),+ "tools": [m.get("name") for _, m in convo.events if m.get("type") == p.TOOL_CALL],+ })+ await convo.stream(silence(0.5, STT_RATE))+ for _ in range(barge_trials):+ convo.reset()+ await convo.stream(voice.render(_LONG[language], language), until_done_s=0.0)+ waited = time.monotonic()+ while convo.first_audio_at is None and time.monotonic() - waited < 15:+ await convo.stream(silence(0.1, STT_RATE))+ if convo.first_audio_at is None:+ barges.append({"language": language, "error": "no answer audio"})+ continue+ await convo.stream(silence(0.4, STT_RATE))+ barge = voice.render(_BARGE[language], language, pad_s=0.0)+ barge_start = time.monotonic()+ await convo.stream(np.concatenate([barge, silence(0.6, STT_RATE)]))+ interrupted = convo.interrupted_at+ leak = 0.0+ if interrupted is not None and convo.last_audio_at is not None:+ leak = max(0.0, convo.last_audio_at - interrupted)+ barges.append({+ "language": language,+ "interrupt_ms": round((interrupted - barge_start) * 1000.0, 1)+ if interrupted else None,+ "audio_after_interrupt_ms": round(leak * 1000.0, 1),+ })+ convo.done = asyncio.Event()+ await convo.stream(silence(0.3, STT_RATE), until_done_s=10.0)+ await client.send({"type": p.SESSION_CLOSE, "session": session})+ pump.cancel()+ exit_code = await client.close()+ answered = [i for i in items if i["e2e_ms"] is not None]+ report.update({+ "exit_code": exit_code,+ "summary": {+ "e2e_ms_dialog": summary(i["e2e_ms"] for i in answered if i["kind"] == "dialog"),+ "e2e_ms_tool": summary(i["e2e_ms"] for i in answered if i["kind"] == "tool"),+ "worker_speech_end_to_first_audio_ms": summary(+ i["worker"].get("speech_end_to_first_audio_ms") for i in answered),+ "stt_ms": summary(i["worker"].get("stt_ms") for i in answered),+ "turn_ms": summary(i["worker"].get("turn_ms") for i in answered),+ "llm_first_clause_ms": summary(i["worker"].get("llm_first_clause_ms")+ for i in answered),+ "unanswered": len(items) - len(answered),+ "barge_interrupt_ms": summary(b.get("interrupt_ms") for b in barges),+ "barge_audio_after_interrupt_ms": summary(+ b.get("audio_after_interrupt_ms") for b in barges),+ },+ "items": items, "barges": barges,+ })+ return report+++def run_worker(model: str, tts: str, languages: list[str], *, voice_kind: str,+ tts_options: dict[str, Any], barge_trials: int = 3) -> dict[str, Any]:+ return asyncio.run(_run(model, tts, languages, voice_kind, tts_options, barge_trials))+++_PARENT = r"""+import subprocess, sys, time+child = subprocess.Popen([sys.executable, "-m", "jarvis.voice_engine.worker"],+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL, creationflags=CREATIONFLAGS)+print(child.pid, flush=True)+time.sleep(600)+"""+++def run_drill(trials: int = 3) -> dict[str, Any]:+ """Kill the worker's parent the hard way; the worker must exit on its own."""+ import psutil # noqa: PLC0415 - bench-only dependency++ env = worker_env(package_root=package_root())+ results = []+ for _ in range(trials):+ script = _PARENT.replace("CREATIONFLAGS", str(_NO_WINDOW))+ parent = subprocess.Popen( # noqa: S603 - fixed argv+ [sys.executable, "-c", script], stdout=subprocess.PIPE, text=True, env=env,+ creationflags=_NO_WINDOW,+ )+ assert parent.stdout is not None+ worker_pid = int(parent.stdout.readline().strip())+ time.sleep(3.0) # let the worker reach its read loop+ parent.kill()+ parent.wait()+ killed_at = time.monotonic()+ gone_after = None+ while time.monotonic() - killed_at < 10:+ if not psutil.pid_exists(worker_pid):+ gone_after = round(time.monotonic() - killed_at, 2)+ break+ try:+ if psutil.Process(worker_pid).status() == psutil.STATUS_ZOMBIE:+ gone_after = round(time.monotonic() - killed_at, 2)+ break+ except psutil.NoSuchProcess:+ gone_after = round(time.monotonic() - killed_at, 2)+ break+ time.sleep(0.05)+ if gone_after is None:+ psutil.Process(worker_pid).kill()+ results.append({"worker_pid": worker_pid, "exited_after_s": gone_after})+ return {"trials": results,+ "orphans": sum(r["exited_after_s"] is None for r in results)}+++def dump(payload: dict[str, Any]) -> str:+ return json.dumps(payload, indent=2, ensure_ascii=False)diff --git a/jarvis/voice_engine/client.py b/jarvis/voice_engine/client.pynew file mode 100644index 0000000000..15812ae01a--- /dev/null+++ b/jarvis/voice_engine/client.py@@ -0,0 +1,132 @@+"""Start the engine worker as a child process and exchange protocol frames.++Used by the app's provider adapter and by the bench. The worker reads its+stdin and exits when it closes, so closing this client (or the app dying)+ends the worker — the property that replaces pidfiles and port probes.+"""++from __future__ import annotations++import asyncio+import contextlib+import os+import sys+from collections.abc import Callable+from pathlib import Path+from typing import Any++from jarvis.voice_engine import protocol as p++# Same flag as jarvis.core.process_utils.NO_WINDOW_CREATIONFLAGS (AP-1).+_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0+EXITED = "_exited"+++def worker_env(*, package_root: Path | None = None, home: Path | None = None,+ extra: dict[str, str] | None = None) -> dict[str, str]:+ env = dict(os.environ)+ env.update({+ "PYTHONUTF8": "1",+ "PYTHONIOENCODING": "utf-8",+ "PYTHONUNBUFFERED": "1",+ "HF_HUB_DISABLE_SYMLINKS_WARNING": "1",+ "HF_HUB_DISABLE_PROGRESS_BARS": "1",+ })+ if package_root is not None:+ env["PYTHONPATH"] = str(package_root)+ if home is not None:+ env["JARVIS_VOICE_ENGINE_HOME"] = str(home)+ env.update(extra or {})+ return env+++class EngineClient:+ def __init__(self, python: str, *, env: dict[str, str] | None = None,+ stderr_path: Path | None = None) -> None:+ self._python = python+ self._env = env or worker_env()+ self._stderr_path = stderr_path+ self._process: asyncio.subprocess.Process | None = None+ self._reader_task: asyncio.Task[None] | None = None+ self.messages: asyncio.Queue[dict[str, Any]] = asyncio.Queue()+ self.audio_frames: asyncio.Queue[p.AudioFrame] = asyncio.Queue()+ self._stderr_handle: Any = None+ self._write_lock = asyncio.Lock()++ @property+ def pid(self) -> int | None:+ return self._process.pid if self._process is not None else None++ async def start(self, timeout_s: float = 30.0) -> dict[str, Any]:+ if self._stderr_path is not None:+ self._stderr_path.parent.mkdir(parents=True, exist_ok=True)+ self._stderr_handle = self._stderr_path.open("ab")+ self._process = await asyncio.create_subprocess_exec(+ self._python, "-m", "jarvis.voice_engine.worker",+ stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,+ stderr=self._stderr_handle or asyncio.subprocess.DEVNULL,+ env=self._env, creationflags=_NO_WINDOW,+ )+ self._reader_task = asyncio.get_running_loop().create_task(self._read())+ return await self.wait_for(lambda m: m["type"] == p.HELLO, timeout_s)++ async def _read(self) -> None:+ assert self._process is not None and self._process.stdout is not None+ reader = p.FrameReader()+ try:+ while True:+ data = await self._process.stdout.read(65536)+ if not data:+ break+ for frame in reader.feed(data):+ if isinstance(frame, p.AudioFrame):+ self.audio_frames.put_nowait(frame)+ else:+ self.messages.put_nowait(frame)+ finally:+ self.messages.put_nowait({"type": EXITED})++ async def send(self, message: dict[str, Any]) -> None:+ await self._write(p.encode_json(message))++ async def send_audio(self, slot: int, seq: int, pcm16: bytes) -> None:+ await self._write(p.encode_audio(slot, seq, pcm16))++ async def _write(self, data: bytes) -> None:+ if self._process is None or self._process.stdin is None:+ raise RuntimeError("the voice engine is not running")+ async with self._write_lock:+ self._process.stdin.write(data)+ await self._process.stdin.drain()++ async def wait_for(self, predicate: Callable[[dict[str, Any]], bool],+ timeout_s: float) -> dict[str, Any]:+ """Next message matching ``predicate``; other messages are dropped."""+ async with asyncio.timeout(timeout_s):+ while True:+ message = await self.messages.get()+ if message["type"] == EXITED:+ raise RuntimeError("the voice engine exited")+ if predicate(message):+ return message++ async def close(self, timeout_s: float = 5.0) -> int | None:+ process = self._process+ if process is None:+ return None+ with contextlib.suppress(RuntimeError, ConnectionError, OSError):+ await self.send({"type": p.SHUTDOWN})+ if process.stdin is not None:+ with contextlib.suppress(ConnectionError, OSError):+ process.stdin.close()+ try:+ code = await asyncio.wait_for(process.wait(), timeout_s)+ except TimeoutError:+ process.kill()+ code = await process.wait()+ if self._reader_task is not None:+ self._reader_task.cancel()+ if self._stderr_handle is not None:+ self._stderr_handle.close()+ self._process = None+ return codediff --git a/jarvis/voice_engine/engine.py b/jarvis/voice_engine/engine.pynew file mode 100644index 0000000000..165d2a56d6--- /dev/null+++ b/jarvis/voice_engine/engine.py@@ -0,0 +1,574 @@+"""One live conversation inside the engine worker.++Listens to 16 kHz audio, decides when the user finished (Silero VAD + Smart+Turn, with the transcription started speculatively at the first pause), hands+the final transcript to the app, answers with a streaming LLM when the app+requests a response, speaks clause by clause, routes tool calls to the app+and stops the moment the user talks over it+(``docs/local-live-voice-rebuild.md`` section 4.3).++All session state lives on the worker's asyncio loop. Model inference runs in+threads, one caller per model at a time (AP-24): the turn model, the+recogniser and each voice are guarded by their own lock.+"""++from __future__ import annotations++import asyncio+import json+import logging+import threading+import time+import uuid+from collections import deque+from collections.abc import Callable, Iterator+from dataclasses import dataclass, field+from typing import Any, Protocol++import numpy as np++from jarvis.voice_engine import protocol as p+from jarvis.voice_engine.audio import resample, to_float32, to_pcm16+from jarvis.voice_engine.chunker import ClauseChunker+from jarvis.voice_engine.vad import FRAME_MS, FRAME_SAMPLES, Endpointer++log = logging.getLogger("jarvis.voice_engine.engine")++INPUT_RATE = p.INPUT_RATE+OUTPUT_RATE = p.OUTPUT_RATE+LANGUAGE_NAMES = {"de": "German", "en": "English", "es": "Spanish", "fr": "French",+ "it": "Italian", "pt": "Portuguese", "nl": "Dutch"}+++class VadModel(Protocol):+ def __call__(self, frame: np.ndarray) -> float: ...+ def reset(self) -> None: ...+++class TurnModel(Protocol):+ def probability(self, audio16k: np.ndarray) -> float: ...+++class SttModel(Protocol):+ def transcribe(self, audio: np.ndarray, rate: int = INPUT_RATE) -> str: ...+++class TtsModel(Protocol):+ name: str+ sample_rate: int++ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:+ ...+++class ChatModel(Protocol):+ def chat(self, messages: list[dict[str, Any]], **kwargs: Any) -> Any: ...+++class Emit(Protocol):+ def json(self, message: dict[str, Any]) -> None: ...+ def audio(self, slot: int, seq: int, pcm16: bytes) -> None: ...+++@dataclass+class EngineModels:+ """Models shared by every session of one worker."""++ vad_factory: Callable[[], VadModel]+ turn: TurnModel+ stt: SttModel+ tts_for: Callable[[str], TtsModel]+ llm: ChatModel+ _locks: dict[str, threading.Lock] = field(default_factory=dict)+ _guard: threading.Lock = field(default_factory=threading.Lock)++ def lock(self, name: str) -> threading.Lock:+ with self._guard:+ return self._locks.setdefault(name, threading.Lock())+++@dataclass+class EngineConfig:+ silence_ms: int = 200+ min_speech_ms: int = 160+ barge_in_ms: int = 250+ preroll_ms: int = 300+ turn_threshold: float = 0.5+ incomplete_wait_ms: int = 1000+ max_utterance_s: float = 30.0+ output_frame_ms: int = 40+ max_history_messages: int = 24+ max_tool_rounds: int = 4+ tool_timeout_s: float = 30.0+++@dataclass+class _Clause:+ text: str+ start_ms: float = 0.0+ end_ms: float = 0.0+++@dataclass+class _Response:+ cancel: threading.Event = field(default_factory=threading.Event)+ task: asyncio.Task[None] | None = None+ clauses: list[_Clause] = field(default_factory=list)+ audio_ms: float = 0.0+ first_audio_at: float | None = None+ requested_at: float = 0.0+ tool_rounds: int = 0+ self_initiated_cancel: bool = False+++class ConversationSession:+ def __init__(+ self,+ *,+ slot: int,+ session_id: str,+ models: EngineModels,+ emit: Emit,+ loop: asyncio.AbstractEventLoop,+ config: EngineConfig | None = None,+ instructions: str = "",+ language: str = "en",+ tools: list[dict[str, Any]] | None = None,+ history: list[dict[str, str]] | None = None,+ turn_pause_ms: int | None = None,+ ) -> None:+ self.slot = slot+ self.session_id = session_id+ self._models = models+ self._emit = emit+ self._loop = loop+ self._config = config or EngineConfig()+ self._instructions = instructions+ self._language = language+ self._tools = _ollama_tools(tools or [])+ self._turn_pause_ms = turn_pause_ms or None+ self._vad = models.vad_factory()+ silence = self._turn_pause_ms or self._config.silence_ms+ self._endpointer = Endpointer(min_speech_ms=self._config.min_speech_ms, silence_ms=silence)+ self._barge = Endpointer(min_speech_ms=self._config.barge_in_ms, silence_ms=silence)+ preroll_frames = max(1, self._config.preroll_ms // FRAME_MS)+ self._preroll: deque[np.ndarray] = deque(maxlen=preroll_frames)+ self._tail = np.zeros(0, dtype=np.float32)+ self._utterance: list[np.ndarray] = []+ self._last_voiced_at = 0.0+ self._decision: asyncio.Task[None] | None = None+ self._decision_epoch = 0+ self._awaiting_request = False+ self._pending_user_text = ""+ self._merge_prefix = ""+ self._response: _Response | None = None+ self._tool_waiters: dict[str, asyncio.Future[dict[str, Any]]] = {}+ self._seq = 0+ self._turn_index = 0+ self._turn_metrics: dict[str, Any] = {}+ self._closed = False+ self._messages: list[dict[str, Any]] = [{"role": "system", "content": self._system_text()}]+ for item in history or []:+ role = item.get("role")+ if role in ("user", "assistant") and item.get("text"):+ self._messages.append({"role": role, "content": str(item["text"])})++ # ── inputs from the adapter ─────────────────────────────────────────────++ def on_audio(self, pcm16: bytes) -> None:+ if self._closed:+ return+ samples = to_float32(pcm16)+ self._tail = np.concatenate([self._tail, samples]) if self._tail.size else samples+ while self._tail.size >= FRAME_SAMPLES:+ frame, self._tail = self._tail[:FRAME_SAMPLES], self._tail[FRAME_SAMPLES:]+ self._on_frame(frame)++ def on_response_request(self, language: str | None = None) -> None:+ if language:+ self._set_language(language)+ if not self._awaiting_request:+ # A request for a turn the user has since continued; the merged+ # transcript brings its own request.+ return+ self._awaiting_request = False+ self._start_response(self._pending_user_text)++ def on_text(self, text: str) -> None:+ """Typed input or an announcement prompt: answer it right away."""+ text = text.strip()+ if not text or self._closed:+ return+ self._cancel_response(self_initiated=True)+ self._start_response(text)++ def on_tool_result(self, call_id: str, result: dict[str, Any]) -> None:+ waiter = self._tool_waiters.pop(call_id, None)+ if waiter is not None and not waiter.done():+ waiter.set_result(result)++ def on_interrupt(self) -> None:+ self._cancel_response(self_initiated=True)++ def on_truncate(self, audio_end_ms: float) -> None:+ """Keep only what the listener actually heard of the last answer."""+ for index in range(len(self._messages) - 1, 0, -1):+ message = self._messages[index]+ if message.get("role") == "assistant" and message.get("_clauses"):+ heard = [c for c in message["_clauses"] if c.start_ms < audio_end_ms]+ message["content"] = " ".join(c.text for c in heard)+ message["_clauses"] = heard+ return++ def on_update(+ self,+ *,+ instructions: str | None = None,+ tools: list[dict[str, Any]] | None = None,+ language: str | None = None,+ ) -> None:+ if instructions is not None:+ self._instructions = instructions+ if tools is not None:+ self._tools = _ollama_tools(tools)+ if language:+ self._set_language(language)+ self._messages[0] = {"role": "system", "content": self._system_text()}++ def close(self) -> None:+ self._closed = True+ self._cancel_response(self_initiated=True)+ if self._decision is not None:+ self._decision.cancel()+ for waiter in self._tool_waiters.values():+ if not waiter.done():+ waiter.cancel()+ self._tool_waiters.clear()++ # ── listening ──────────────────────────────────────────────────────────++ def _on_frame(self, frame: np.ndarray) -> None:+ probability = self._vad(frame)+ now = time.monotonic()+ response = self._response+ if response is not None and not response.cancel.is_set():+ event = self._barge.feed(probability)+ self._preroll.append(frame)+ if event is not None and event.kind == "speech_start":+ self._barge_in(response)+ self._begin_utterance(now, carry_preroll=True)+ return+ self._barge.reset()+ if probability >= self._endpointer.on_threshold:+ self._last_voiced_at = now+ event = self._endpointer.feed(probability)+ if event is not None and event.kind == "speech_start":+ # The frames that proved speech are in the pre-roll; the utterance+ # starts with them, then this frame.+ self._begin_utterance(now, carry_preroll=True)+ if self._endpointer.in_speech:+ self._utterance.append(frame)+ else:+ self._preroll.append(frame)+ if event is None:+ too_long = self._utterance_seconds() > self._config.max_utterance_s+ if self._endpointer.in_speech and too_long:+ self._start_decision(force=True)+ return+ if event.kind == "silence_start":+ self._start_decision(force=False)+ elif event.kind == "silence_end":+ # The user resumed before the turn was taken: the pending decision+ # describes a sentence that is still growing.+ self._decision_epoch += 1++ def _begin_utterance(self, now: float, *, carry_preroll: bool) -> None:+ if self._awaiting_request:+ # The user continued after the transcript left but before the app+ # asked for an answer: one turn, not two.+ self._awaiting_request = False+ self._merge_prefix = self._pending_user_text+ if carry_preroll:+ self._utterance = list(self._preroll)+ self._preroll.clear()+ self._endpointer.start_speech()+ self._turn_metrics = {"speech_start": now}+ self._emit.json({"type": p.SPEECH_STARTED, "session": self.session_id})++ def _utterance_seconds(self) -> float:+ return sum(f.size for f in self._utterance) / INPUT_RATE++ def _start_decision(self, *, force: bool) -> None:+ self._decision_epoch += 1+ epoch = self._decision_epoch+ audio = np.concatenate(self._utterance) if self._utterance else np.zeros(0, np.float32)+ speech_end = self._last_voiced_at+ if self._decision is not None and not self._decision.done():+ self._decision.cancel()+ self._decision = self._loop.create_task(self._decide(epoch, audio, speech_end, force))++ async def _decide(self, epoch: int, audio: np.ndarray, speech_end: float, force: bool) -> None:+ started = time.monotonic()+ stt_job = asyncio.to_thread(self._locked, "stt", self._models.stt.transcribe, audio)+ turn_job = (+ asyncio.to_thread(self._locked, "turn", self._models.turn.probability, audio)+ if not force+ else _ready(1.0)+ )+ try:+ (text, stt_ms), (probability, turn_ms) = await asyncio.gather(stt_job, turn_job)+ except Exception:+ log.exception("transcription or turn decision failed")+ self._emit.json({"type": p.ERROR, "session": self.session_id, "code": "stt_failed",+ "message": "Speech recognition failed for this turn.",+ "recoverable": True})+ return+ if epoch != self._decision_epoch:+ return+ self._turn_metrics.update({+ "speech_end": speech_end, "stt_ms": round(stt_ms, 1), "turn_ms": round(turn_ms, 1),+ "p_complete": round(float(probability), 3),+ "decision_ms": round((time.monotonic() - started) * 1000.0, 1),+ })+ if probability < self._config.turn_threshold and not force:+ await asyncio.sleep(self._config.incomplete_wait_ms / 1000.0)+ if epoch != self._decision_epoch:+ return+ self._turn_metrics["waited_incomplete_ms"] = self._config.incomplete_wait_ms+ self._finalize(text)++ def _finalize(self, text: str) -> None:+ text = " ".join(part for part in (self._merge_prefix, text.strip()) if part).strip()+ self._merge_prefix = ""+ self._utterance = []+ self._endpointer.reset()+ self._vad.reset()+ if not text:+ return+ self._turn_index += 1+ voiced_ms = int(1000 * (self._turn_metrics.get("speech_end", 0) -+ self._turn_metrics.get("speech_start", 0)))+ self._turn_metrics["final_at"] = time.monotonic()+ self._pending_user_text = text+ self._awaiting_request = True+ self._emit.json({"type": p.TRANSCRIPT_INPUT, "session": self.session_id, "text": text,+ "final": True, "voiced_ms": max(0, voiced_ms)})++ # ── answering ──────────────────────────────────────────────────────────++ def _start_response(self, user_text: str) -> None:+ self._cancel_response(self_initiated=True)+ response = _Response(requested_at=time.monotonic())+ self._response = response+ self._barge.reset()+ response.task = self._loop.create_task(self._respond(response, user_text))++ async def _respond(self, response: _Response, user_text: str) -> None:+ messages = self._bounded_messages() + [{"role": "user", "content": user_text}]+ self._messages.append({"role": "user", "content": user_text})+ speech: asyncio.Queue[str | None] = asyncio.Queue()+ speaker = self._loop.create_task(self._speak(response, speech))+ status = "completed"+ try:+ for _round in range(self._config.max_tool_rounds + 1):+ result = await asyncio.to_thread(self._chat_round, response, messages, speech)+ if response.cancel.is_set():+ status = "cancelled"+ break+ if result.error:+ raise RuntimeError(result.error)+ if not result.tool_calls:+ break+ response.tool_rounds += 1+ calls = [+ {"id": f"call_{uuid.uuid4().hex[:12]}", **call} for call in result.tool_calls+ ]+ messages.append({"role": "assistant", "content": result.text,+ "tool_calls": [{"function": {"name": c["name"],+ "arguments": c["arguments"]}}+ for c in calls]})+ outcomes = await asyncio.gather(*(self._run_tool(c) for c in calls))+ for call, outcome in zip(calls, outcomes, strict=True):+ messages.append({"role": "tool", "tool_name": call["name"],+ "content": json.dumps(outcome, ensure_ascii=False)})+ if response.cancel.is_set():+ status = "cancelled"+ break+ await speech.put(None)+ await speaker+ except asyncio.CancelledError:+ status = "cancelled"+ speaker.cancel()+ raise+ except Exception as exc:+ log.exception("response failed")+ status = "failed"+ speaker.cancel()+ self._emit.json({"type": p.ERROR, "session": self.session_id, "code": "llm_failed",+ "message": f"The local language model failed: {exc}",+ "recoverable": True})+ finally:+ spoken = [c for c in response.clauses if c.start_ms <= response.audio_ms]+ if spoken:+ message = {"role": "assistant", "content": " ".join(c.text for c in spoken)}+ message["_clauses"] = spoken+ self._messages.append(message)+ if self._response is response:+ self._response = None+ final_status = "cancelled" if response.cancel.is_set() else status+ self._emit_metrics(response, final_status)+ self._emit.json({"type": p.RESPONSE_DONE, "session": self.session_id,+ "status": final_status})++ def _chat_round(self, response: _Response, messages: list[dict[str, Any]],+ speech: asyncio.Queue[str | None]) -> Any:+ def on_clause(clause: str, _at: float) -> None:+ self._loop.call_soon_threadsafe(speech.put_nowait, clause)++ result = self._models.llm.chat(+ messages, tools=self._tools or None, chunker=ClauseChunker(), on_clause=on_clause,+ stop=response.cancel,+ )+ first = getattr(result, "t_first_clause", None)+ if first is not None and "llm_first_clause_ms" not in self._turn_metrics:+ self._turn_metrics["llm_first_clause_ms"] = round(first * 1000.0, 1)+ return result++ async def _run_tool(self, call: dict[str, Any]) -> dict[str, Any]:+ waiter: asyncio.Future[dict[str, Any]] = self._loop.create_future()+ self._tool_waiters[call["id"]] = waiter+ self._emit.json({"type": p.TOOL_CALL, "session": self.session_id, "call_id": call["id"],+ "name": call["name"], "arguments": call["arguments"]})+ try:+ return await asyncio.wait_for(waiter, self._config.tool_timeout_s)+ except TimeoutError:+ self._tool_waiters.pop(call["id"], None)+ return {"success": False, "error": "The tool did not answer in time."}++ async def _speak(self, response: _Response, speech: asyncio.Queue[str | None]) -> None:+ tts = self._models.tts_for(self._language)+ while True:+ clause = await speech.get()+ if clause is None or response.cancel.is_set():+ return+ entry = _Clause(text=clause, start_ms=response.audio_ms)+ response.clauses.append(entry)+ self._emit.json({"type": p.TRANSCRIPT_OUTPUT, "session": self.session_id,+ "delta": clause + " "})+ await asyncio.to_thread(self._synthesize, tts, clause, response)+ entry.end_ms = response.audio_ms++ def _synthesize(self, tts: TtsModel, text: str, response: _Response) -> None:+ frame = OUTPUT_RATE * self._config.output_frame_ms // 1000+ with self._models.lock(f"tts:{getattr(tts, 'name', 'tts')}:{self._language}"):+ pending = np.zeros(0, dtype=np.float32)+ for chunk in tts.stream(text, stop=response.cancel):+ if response.cancel.is_set():+ return+ audio = resample(np.asarray(chunk, dtype=np.float32), tts.sample_rate, OUTPUT_RATE)+ pending = np.concatenate([pending, audio])+ while pending.size >= frame:+ piece, pending = pending[:frame], pending[frame:]+ self._loop.call_soon_threadsafe(self._send_audio, response, piece)+ if pending.size and not response.cancel.is_set():+ self._loop.call_soon_threadsafe(self._send_audio, response, pending)++ def _send_audio(self, response: _Response, samples: np.ndarray) -> None:+ if response.cancel.is_set() or self._closed:+ return+ if response.first_audio_at is None:+ response.first_audio_at = time.monotonic()+ response.audio_ms += 1000.0 * samples.size / OUTPUT_RATE+ self._seq += 1+ self._emit.audio(self.slot, self._seq, to_pcm16(samples))++ # ── interruption ───────────────────────────────────────────────────────++ def _barge_in(self, response: _Response) -> None:+ before_audio = response.first_audio_at is None+ if before_audio and self._pending_user_text:+ # Nothing was heard yet: the user is still finishing the request.+ self._merge_prefix = self._pending_user_text+ if self._messages and self._messages[-1].get("role") == "user":+ self._messages.pop()+ self._cancel_response(self_initiated=False)++ def _cancel_response(self, *, self_initiated: bool) -> None:+ response = self._response+ if response is None or response.cancel.is_set():+ return+ response.cancel.set()+ response.self_initiated_cancel = self_initiated+ for waiter in self._tool_waiters.values():+ if not waiter.done():+ waiter.set_result({"success": False, "error": "cancelled"})+ self._tool_waiters.clear()+ self._emit.json({"type": p.INTERRUPTED, "session": self.session_id,+ "self_initiated": self_initiated, "audio_ms": round(response.audio_ms)})++ # ── helpers ────────────────────────────────────────────────────────────++ def _locked(self, name: str, fn: Callable[..., Any], *args: Any) -> tuple[Any, float]:+ with self._models.lock(name):+ started = time.perf_counter()+ value = fn(*args)+ return value, (time.perf_counter() - started) * 1000.0++ def _set_language(self, language: str) -> None:+ language = language.split("-")[0].lower()+ if language and language != self._language:+ self._language = language+ self._messages[0] = {"role": "system", "content": self._system_text()}++ def _system_text(self) -> str:+ name = LANGUAGE_NAMES.get(self._language, self._language)+ rule = f"Reply in {name}. Keep spoken answers short: one to three sentences."+ return f"{self._instructions.strip()}\n\n{rule}".strip()++ def _bounded_messages(self) -> list[dict[str, Any]]:+ history = [+ {k: v for k, v in m.items() if not k.startswith("_")} for m in self._messages[1:]+ ][-self._config.max_history_messages :]+ return [self._messages[0], *history]++ def _emit_metrics(self, response: _Response, status: str) -> None:+ metrics = dict(self._turn_metrics)+ speech_end = metrics.pop("speech_end", None)+ metrics.pop("speech_start", None)+ final_at = metrics.pop("final_at", None)+ if response.first_audio_at is not None and speech_end:+ metrics["speech_end_to_first_audio_ms"] = round(+ (response.first_audio_at - speech_end) * 1000.0, 1+ )+ if final_at is not None:+ metrics["final_to_request_ms"] = round((response.requested_at - final_at) * 1000.0, 1)+ if response.first_audio_at is not None:+ metrics["request_to_first_audio_ms"] = round(+ (response.first_audio_at - response.requested_at) * 1000.0, 1+ )+ metrics.update({"turn": self._turn_index, "status": status,+ "tool_rounds": response.tool_rounds,+ "audio_ms": round(response.audio_ms)})+ self._turn_metrics = {}+ self._emit.json({"type": p.METRICS, "session": self.session_id, "turn": metrics})+++async def _ready(value: float) -> tuple[float, float]:+ return value, 0.0+++def _ollama_tools(declarations: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Realtime-style declarations ({name, description, parameters}) to Ollama's shape."""+ tools = []+ for item in declarations:+ if item.get("type") == "function" and "function" in item:+ tools.append(item)+ continue+ name = item.get("name")+ if not name:+ continue+ tools.append({"type": "function", "function": {+ "name": name, "description": item.get("description", ""),+ "parameters": item.get("parameters") or {"type": "object", "properties": {}},+ }})+ return toolsdiff --git a/jarvis/voice_engine/protocol.py b/jarvis/voice_engine/protocol.pynew file mode 100644index 0000000000..6305832425--- /dev/null+++ b/jarvis/voice_engine/protocol.py@@ -0,0 +1,139 @@+"""Wire protocol v1 between the app's provider adapter and the engine worker.++The worker is a child process; the adapter writes frames to its stdin and+reads frames from its stdout (``docs/local-live-voice-rebuild.md`` 4.5).+Every frame is::++ length: uint32 big-endian (bytes after this field)+ kind: 1 byte b"J" = UTF-8 JSON object, b"A" = audio+ payload++An audio payload starts with an 8-byte header — ``slot: uint16`` (the session+the audio belongs to, assigned by the adapter in ``session.open``) and+``seq: uint32`` plus two reserved bytes — followed by mono PCM16+little-endian samples: 16 kHz towards the worker, 24 kHz back.++The format does not depend on the transport; a socket can carry the same+frames later.+"""++from __future__ import annotations++import json+import struct+from dataclasses import dataclass+from typing import Any++PROTOCOL_VERSION = 1+KIND_JSON = b"J"+KIND_AUDIO = b"A"+MAX_FRAME_BYTES = 1 << 20 # 1 MiB: far above any audio chunk or tool payload+_LENGTH = struct.Struct(">I")+_AUDIO_HEADER = struct.Struct(">HIH")++INPUT_RATE = 16_000+OUTPUT_RATE = 24_000++# Adapter -> worker+HELLO = "hello"+CONFIGURE = "configure"+SESSION_OPEN = "session.open"+SESSION_UPDATE = "session.update"+SESSION_CLOSE = "session.close"+RESPONSE_REQUEST = "response.request"+TOOL_RESULT = "tool.result"+TEXT = "text"+INTERRUPT = "interrupt"+TRUNCATE = "truncate"+SELFTEST = "selftest"+SHUTDOWN = "shutdown"++# Worker -> adapter+STATE = "state"+SESSION_READY = "session.ready"+SPEECH_STARTED = "speech_started"+TRANSCRIPT_INPUT = "transcript.input"+TRANSCRIPT_OUTPUT = "transcript.output"+TOOL_CALL = "tool.call"+RESPONSE_DONE = "response.done"+INTERRUPTED = "interrupted"+USAGE = "usage"+METRICS = "metrics"+ERROR = "error"+SELFTEST_RESULT = "selftest.result"+++class ProtocolError(ValueError):+ """A frame that cannot be valid: wrong kind, oversized or malformed."""+++@dataclass(frozen=True, slots=True)+class AudioFrame:+ slot: int+ seq: int+ pcm: bytes+++Frame = dict[str, Any] | AudioFrame+++def encode_json(message: dict[str, Any]) -> bytes:+ payload = KIND_JSON + json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode(+ "utf-8"+ )+ if len(payload) > MAX_FRAME_BYTES:+ raise ProtocolError(f"message of {len(payload)} bytes exceeds the frame limit")+ return _LENGTH.pack(len(payload)) + payload+++def encode_audio(slot: int, seq: int, pcm: bytes) -> bytes:+ payload = KIND_AUDIO + _AUDIO_HEADER.pack(slot, seq & 0xFFFFFFFF, 0) + pcm+ if len(payload) > MAX_FRAME_BYTES:+ raise ProtocolError(f"audio frame of {len(payload)} bytes exceeds the frame limit")+ return _LENGTH.pack(len(payload)) + payload+++def decode_payload(payload: bytes) -> Frame:+ if not payload:+ raise ProtocolError("empty frame")+ kind, body = payload[:1], payload[1:]+ if kind == KIND_JSON:+ try:+ message = json.loads(body.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise ProtocolError(f"invalid JSON frame: {exc}") from exc+ if not isinstance(message, dict) or not isinstance(message.get("type"), str):+ raise ProtocolError("a JSON frame must be an object with a string 'type'")+ return message+ if kind == KIND_AUDIO:+ if len(body) < _AUDIO_HEADER.size:+ raise ProtocolError("audio frame shorter than its header")+ slot, seq, _reserved = _AUDIO_HEADER.unpack_from(body)+ return AudioFrame(slot=slot, seq=seq, pcm=bytes(body[_AUDIO_HEADER.size :]))+ raise ProtocolError(f"unknown frame kind {kind!r}")+++class FrameReader:+ """Incremental decoder: feed raw bytes, receive whole frames."""++ def __init__(self) -> None:+ self._buffer = bytearray()++ def feed(self, data: bytes) -> list[Frame]:+ self._buffer.extend(data)+ frames: list[Frame] = []+ while len(self._buffer) >= _LENGTH.size:+ (length,) = _LENGTH.unpack_from(self._buffer)+ if length > MAX_FRAME_BYTES or length == 0:+ raise ProtocolError(f"frame length {length} is outside 1..{MAX_FRAME_BYTES}")+ end = _LENGTH.size + length+ if len(self._buffer) < end:+ break+ payload = bytes(self._buffer[_LENGTH.size : end])+ del self._buffer[:end]+ frames.append(decode_payload(payload))+ return frames++ @property+ def pending_bytes(self) -> int:+ return len(self._buffer)diff --git a/jarvis/voice_engine/runtime.py b/jarvis/voice_engine/runtime.pynew file mode 100644index 0000000000..84c2db7a9a--- /dev/null+++ b/jarvis/voice_engine/runtime.py@@ -0,0 +1,155 @@+"""Load the engine's models from a ``configure`` message and prove they work.++``build_models`` turns the configuration into :class:`EngineModels`;+``selftest`` is the readiness proof — every selected voice speaks a phrase,+the recogniser transcribes it back and the LLM answers one prompt — so+"ready" always means a real inference in this process, never files on disk+(``docs/local-live-voice-rebuild.md`` section 4.9).+"""++from __future__ import annotations++import time+from collections.abc import Callable+from dataclasses import dataclass, field+from typing import Any++import numpy as np++from jarvis.voice_engine import models as store+from jarvis.voice_engine.audio import STT_RATE, resample, silence+from jarvis.voice_engine.bench.stats import error_rates+from jarvis.voice_engine.engine import EngineConfig, EngineModels++Progress = Callable[[str, float], None]++SELFTEST_PHRASES = {+ "de": "Hallo, ich bin bereit.", # i18n-allow: German readiness phrase+ "en": "Hello, I am ready.",+}+++@dataclass+class RuntimeConfig:+ 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_base_url: str = "http://127.0.0.1:11434"+ llm_num_ctx: int = 8192+ llm_keep_alive: str = "30m"+ llm_temperature: float = 0.3+ engine: EngineConfig = field(default_factory=EngineConfig)++ @classmethod+ def from_message(cls, message: dict[str, Any]) -> RuntimeConfig:+ llm = message.get("llm") or {}+ turn = message.get("turn") or {}+ engine = EngineConfig(**{k: v for k, v in turn.items() if hasattr(EngineConfig, k)})+ return cls(+ languages=[str(x) for x in message.get("languages") or ["de", "en"]],+ tts=str(message.get("tts") or "pocket"),+ tts_options=dict(message.get("tts_options") or {}),+ llm_model=str(llm.get("model") or cls.llm_model),+ llm_base_url=str(llm.get("base_url") or cls.llm_base_url),+ llm_num_ctx=int(llm.get("num_ctx") or cls.llm_num_ctx),+ llm_keep_alive=str(llm.get("keep_alive") or cls.llm_keep_alive),+ llm_temperature=float(llm.get("temperature", cls.llm_temperature)),+ engine=engine,+ )+++def build_models(config: RuntimeConfig, progress: Progress) -> tuple[EngineModels, dict[str, Any]]:+ """Load every component; returns the models and a description of what loaded."""+ from jarvis.voice_engine.llm import OllamaChat # noqa: PLC0415+ from jarvis.voice_engine.stt import ParakeetStt # noqa: PLC0415+ from jarvis.voice_engine.tts import load_tts # noqa: PLC0415+ from jarvis.voice_engine.turn import SmartTurn # noqa: PLC0415+ from jarvis.voice_engine.vad import SileroVad # noqa: PLC0415++ timings: dict[str, float] = {}+ errors: dict[str, str] = {}+ missing = [n for n in ("silero-vad-v6", "smart-turn-v3.2", "parakeet-tdt-0.6b-v3-int8")+ if not store.is_present(n)]+ if missing:+ raise RuntimeError(f"models not installed: {', '.join(missing)}")++ def timed(name: str, fn: Callable[[], Any]) -> Any:+ started = time.perf_counter()+ value = fn()+ timings[name] = round(time.perf_counter() - started, 2)+ return value++ progress("vad", 0.05)+ vad_path = store.model_path("silero-vad-v6")+ timed("vad", lambda: SileroVad(vad_path))+ progress("turn", 0.1)+ turn = timed("turn", lambda: SmartTurn(store.model_path("smart-turn-v3.2")))+ progress("stt", 0.2)+ stt = timed("stt", lambda: ParakeetStt(store.model_path("parakeet-tdt-0.6b-v3-int8")))++ voices: dict[str, Any] = {}+ voice_kind: dict[str, str] = {}+ for index, language in enumerate(config.languages):+ progress(f"tts:{language}", 0.35 + 0.35 * index / max(1, len(config.languages)))+ try:+ voices[language] = timed(f"tts:{config.tts}:{language}",+ lambda lang=language: load_tts(config.tts, lang,+ **config.tts_options))+ voice_kind[language] = config.tts+ except Exception as exc: # noqa: BLE001 - the floor voice takes over+ if config.tts == "piper":+ raise+ errors[f"tts:{config.tts}:{language}"] = str(exc)[:200]+ voices[language] = timed(f"tts:piper:{language}",+ lambda lang=language: load_tts("piper", lang))+ voice_kind[language] = "piper"++ def tts_for(language: str) -> Any:+ if language in voices:+ return voices[language]+ return voices[config.languages[0]]++ progress("llm", 0.8)+ llm = OllamaChat(config.llm_model, base_url=config.llm_base_url, num_ctx=config.llm_num_ctx,+ keep_alive=config.llm_keep_alive, temperature=config.llm_temperature)+ timings["llm_load"] = round(llm.warm(), 2)+ models = EngineModels(+ vad_factory=lambda: SileroVad(vad_path), turn=turn, stt=stt, tts_for=tts_for, llm=llm+ )+ progress("ready", 1.0)+ return models, {"load_s": timings, "voices": voice_kind, "llm": config.llm_model,+ "errors": errors}+++def selftest(models: EngineModels, languages: list[str]) -> dict[str, Any]:+ """Speak, hear and answer once per language. ``ok`` is the readiness verdict."""+ report: dict[str, Any] = {"ok": True, "languages": {}}+ pad = silence(0.2, STT_RATE)+ for language in languages:+ phrase = SELFTEST_PHRASES.get(language, SELFTEST_PHRASES["en"])+ tts = models.tts_for(language)+ started = time.perf_counter()+ with models.lock(f"tts:{getattr(tts, 'name', 'tts')}:{language}"):+ audio = np.concatenate([np.asarray(c, dtype=np.float32) for c in tts.stream(phrase)])+ synth_ms = (time.perf_counter() - started) * 1000.0+ heard_started = time.perf_counter()+ with models.lock("stt"):+ heard = models.stt.transcribe(+ np.concatenate([pad, resample(audio, tts.sample_rate, STT_RATE), pad])+ )+ cer, _ = error_rates(phrase, heard)+ passed = cer <= 0.25+ report["languages"][language] = {+ "voice": getattr(tts, "name", "?"), "heard": heard, "cer": round(cer, 3),+ "synth_ms": round(synth_ms),+ "stt_ms": round((time.perf_counter() - heard_started) * 1000),+ "ok": passed,+ }+ report["ok"] = report["ok"] and passed+ started = time.perf_counter()+ answer = models.llm.chat([{"role": "user", "content": "Reply with the single word: ready."}])+ report["llm"] = {"ok": not answer.error and bool(answer.text.strip()),+ "error": answer.error, "ms": round((time.perf_counter() - started) * 1000)}+ report["ok"] = report["ok"] and report["llm"]["ok"]+ return reportdiff --git a/jarvis/voice_engine/vad.py b/jarvis/voice_engine/vad.pyindex 9cc40e759b..62c08c012d 100644--- a/jarvis/voice_engine/vad.py+++ b/jarvis/voice_engine/vad.py@@ -84,6 +84,13 @@ class Endpointer:self._unvoiced = 0self._frame = 0+ def start_speech(self) -> None:+ """Enter speech now (e.g. after a barge-in detected elsewhere), with clean counters."""+ self.in_speech = True+ self.in_silence = False+ self._voiced = self.min_speech_frames+ self._unvoiced = 0+def feed(self, probability: float) -> VadEvent | None:self._frame += 1now = self._frame * FRAME_MSdiff --git a/jarvis/voice_engine/worker.py b/jarvis/voice_engine/worker.pynew file mode 100644index 0000000000..b66bd16b64--- /dev/null+++ b/jarvis/voice_engine/worker.py@@ -0,0 +1,251 @@+"""The engine worker process: ``python -m jarvis.voice_engine.worker``.++Reads protocol frames from stdin and writes frames to stdout; logs go to+stderr. The process ends when stdin closes, so it never outlives the app that+started it — no pidfile, no port, no orphan (``docs/local-live-voice-rebuild.md``+section 4.2).+"""++from __future__ import annotations++import asyncio+import logging+import os+import queue+import sys+import threading+from typing import Any, BinaryIO++from jarvis.voice_engine import ENGINE_VERSION+from jarvis.voice_engine import protocol as p+from jarvis.voice_engine.engine import ConversationSession, EngineModels++log = logging.getLogger("jarvis.voice_engine.worker")+++class StdioTransport:+ """Frames over a pair of byte streams, with I/O on dedicated threads.++ A slow reader on the app side must never block the asyncio loop, so writes+ go through a queue to a writer thread; reads come from a reader thread+ that hands whole frames to the loop.+ """++ def __init__(self, source: BinaryIO, sink: BinaryIO) -> None:+ self._source = source+ self._sink = sink+ self._outbox: queue.SimpleQueue[bytes | None] = queue.SimpleQueue()++ def start(self, loop: asyncio.AbstractEventLoop, inbox: asyncio.Queue[Any]) -> None:+ threading.Thread(target=self._read, args=(loop, inbox), name="engine-stdin",+ daemon=True).start()+ threading.Thread(target=self._write, name="engine-stdout", daemon=True).start()++ def _read(self, loop: asyncio.AbstractEventLoop, inbox: asyncio.Queue[Any]) -> None:+ reader = p.FrameReader()+ try:+ while True:+ data = self._source.read1(65536) if hasattr(self._source, "read1") else (+ self._source.read(65536)+ )+ if not data:+ break+ for frame in reader.feed(data):+ loop.call_soon_threadsafe(inbox.put_nowait, frame)+ except (OSError, ValueError, p.ProtocolError) as exc:+ log.error("input stream failed: %s", exc)+ finally:+ loop.call_soon_threadsafe(inbox.put_nowait, None)++ def _write(self) -> None:+ while True:+ data = self._outbox.get()+ if data is None:+ return+ try:+ self._sink.write(data)+ self._sink.flush()+ except (OSError, ValueError) as exc:+ log.error("output stream failed: %s", exc)+ return++ def send(self, data: bytes) -> None:+ self._outbox.put(data)++ def close(self) -> None:+ self._outbox.put(None)+++class _Emitter:+ def __init__(self, transport: StdioTransport) -> None:+ self._transport = transport++ def json(self, message: dict[str, Any]) -> None:+ self._transport.send(p.encode_json(message))++ def audio(self, slot: int, seq: int, pcm16: bytes) -> None:+ self._transport.send(p.encode_audio(slot, seq, pcm16))+++class Worker:+ def __init__(self, transport: StdioTransport) -> None:+ self._transport = transport+ self._emit = _Emitter(transport)+ self._models: EngineModels | None = None+ self._runtime: Any = None+ self._phase = "starting"+ self._sessions: dict[str, ConversationSession] = {}+ self._slots: dict[int, ConversationSession] = {}+ self._loading: asyncio.Task[None] | None = None++ async def run(self) -> int:+ loop = asyncio.get_running_loop()+ inbox: asyncio.Queue[Any] = asyncio.Queue()+ self._transport.start(loop, inbox)+ self._emit.json({"type": p.HELLO, "protocol": p.PROTOCOL_VERSION,+ "engine_version": ENGINE_VERSION, "pid": os.getpid(),+ "utf8_mode": bool(sys.flags.utf8_mode)})+ self._state("idle")+ while True:+ frame = await inbox.get()+ if frame is None:+ break+ try:+ if isinstance(frame, p.AudioFrame):+ session = self._slots.get(frame.slot)+ if session is not None:+ session.on_audio(frame.pcm)+ continue+ if not await self._dispatch(frame):+ break+ except Exception:+ kind = frame.get("type") if isinstance(frame, dict) else "audio"+ log.exception("failed to handle %s", kind)+ self._emit.json({"type": p.ERROR, "code": "worker_error",+ "message": "The voice engine could not handle a request.",+ "recoverable": True})+ for session in list(self._sessions.values()):+ session.close()+ self._transport.close()+ return 0++ async def _dispatch(self, message: dict[str, Any]) -> bool:+ kind = message["type"]+ if kind == p.SHUTDOWN:+ return False+ if kind == p.HELLO:+ return True+ if kind == p.CONFIGURE:+ if self._loading is None or self._loading.done():+ self._loading = asyncio.get_running_loop().create_task(self._configure(message))+ return True+ if kind == p.SELFTEST:+ await self._selftest()+ return True+ if kind == p.SESSION_OPEN:+ self._open(message)+ return True+ session = self._sessions.get(str(message.get("session", "")))+ if session is None:+ self._emit.json({"type": p.ERROR, "code": "unknown_session",+ "message": f"No open session for {kind}.", "recoverable": True})+ return True+ if kind == p.SESSION_CLOSE:+ session.close()+ self._sessions.pop(session.session_id, None)+ self._slots.pop(session.slot, None)+ elif kind == p.RESPONSE_REQUEST:+ session.on_response_request(message.get("language"))+ elif kind == p.TOOL_RESULT:+ session.on_tool_result(str(message.get("call_id", "")), message.get("result") or {})+ elif kind == p.TEXT:+ session.on_text(str(message.get("content", "")))+ elif kind == p.INTERRUPT:+ session.on_interrupt()+ elif kind == p.TRUNCATE:+ session.on_truncate(float(message.get("audio_end_ms", 0)))+ elif kind == p.SESSION_UPDATE:+ session.on_update(instructions=message.get("instructions"),+ tools=message.get("tools"), language=message.get("language"))+ else:+ self._emit.json({"type": p.ERROR, "code": "unknown_message",+ "message": f"Unknown message type {kind!r}.", "recoverable": True})+ return True++ async def _configure(self, message: dict[str, Any]) -> None:+ from jarvis.voice_engine.runtime import RuntimeConfig, build_models # noqa: PLC0415++ loop = asyncio.get_running_loop()+ config = RuntimeConfig.from_message(message)++ def progress(stage: str, fraction: float) -> None:+ loop.call_soon_threadsafe(self._state, "loading", stage, fraction)++ self._state("loading", "start", 0.0)+ try:+ models, described = await asyncio.to_thread(build_models, config, progress)+ except Exception as exc:+ log.exception("loading the voice engine failed")+ self._state("failed", reason=f"The local voice could not load: {exc}")+ return+ self._models = models+ self._runtime = config+ self._state("ready", detail=described)++ async def _selftest(self) -> None:+ from jarvis.voice_engine.runtime import selftest # noqa: PLC0415++ if self._models is None or self._runtime is None:+ self._emit.json({"type": p.SELFTEST_RESULT, "ok": False,+ "reason": "The engine is not configured yet."})+ return+ result = await asyncio.to_thread(selftest, self._models, self._runtime.languages)+ self._emit.json({"type": p.SELFTEST_RESULT, **result})++ def _open(self, message: dict[str, Any]) -> None:+ if self._models is None or self._runtime is None:+ self._emit.json({"type": p.ERROR, "code": "not_ready", "recoverable": True,+ "message": "The local voice is still loading."})+ return+ session_id = str(message.get("session") or "")+ slot = int(message.get("slot", 0))+ session = ConversationSession(+ slot=slot, session_id=session_id, models=self._models, emit=self._emit,+ loop=asyncio.get_running_loop(), config=self._runtime.engine,+ instructions=str(message.get("instructions") or ""),+ language=str(message.get("language") or self._runtime.languages[0]),+ tools=list(message.get("tools") or []), history=list(message.get("history") or []),+ turn_pause_ms=message.get("turn_pause_ms"),+ )+ self._sessions[session_id] = session+ self._slots[slot] = session+ self._emit.json({"type": p.SESSION_READY, "session": session_id, "slot": slot,+ "input_rate": p.INPUT_RATE, "output_rate": p.OUTPUT_RATE})++ def _state(self, phase: str, stage: str = "", progress: float | None = None, *,+ reason: str = "", detail: dict[str, Any] | None = None) -> None:+ self._phase = phase+ message: dict[str, Any] = {"type": p.STATE, "phase": phase}+ if stage:+ message["stage"] = stage+ if progress is not None:+ message["progress"] = round(progress, 3)+ if reason:+ message["reason"] = reason+ if detail:+ message["detail"] = detail+ self._emit.json(message)+++def main() -> int:+ logging.basicConfig(level=os.environ.get("JARVIS_VOICE_ENGINE_LOG", "INFO"),+ stream=sys.stderr, format="%(asctime)s %(levelname)s %(name)s: %(message)s")+ if not sys.flags.utf8_mode:+ log.warning("Python UTF-8 mode is off; start the worker with PYTHONUTF8=1 "+ "(some voice packages read their configs in the locale encoding)")+ transport = StdioTransport(sys.stdin.buffer, sys.stdout.buffer)+ return asyncio.run(Worker(transport).run())+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/unit/voice_engine/test_engine_session.py b/tests/unit/voice_engine/test_engine_session.pynew file mode 100644index 0000000000..eea3253694--- /dev/null+++ b/tests/unit/voice_engine/test_engine_session.py@@ -0,0 +1,238 @@+"""The conversation loop with fake models: turns, answers, tools, barge-in."""++from __future__ import annotations++import asyncio+import threading+import time+from collections.abc import Callable, Iterator+from dataclasses import dataclass, field+from typing import Any++import numpy as np+import pytest++from jarvis.voice_engine import protocol as p+from jarvis.voice_engine.audio import to_pcm16+from jarvis.voice_engine.engine import ConversationSession, EngineConfig, EngineModels++RATE = 16_000+++class FakeVad:+ def __call__(self, frame: np.ndarray) -> float:+ return 0.9 if float(np.sqrt(np.mean(frame**2))) > 0.05 else 0.02++ def reset(self) -> None:+ """Stateless fake."""+++@dataclass+class FakeTurn:+ value: float = 0.95++ def probability(self, audio16k: np.ndarray) -> float:+ return self.value+++@dataclass+class FakeStt:+ texts: list[str] = field(default_factory=lambda: ["what time is it"])+ calls: int = 0++ def transcribe(self, audio: np.ndarray, rate: int = RATE) -> str:+ self.calls += 1+ return self.texts[min(self.calls - 1, len(self.texts) - 1)]+++class FakeTts:+ name = "fake"+ sample_rate = 24_000++ def __init__(self, chunks: int = 2, chunk_s: float = 0.1, pause_s: float = 0.0) -> None:+ self.chunks, self.chunk_s, self.pause_s = chunks, chunk_s, pause_s++ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:+ for _ in range(self.chunks):+ if stop is not None and stop.is_set():+ return+ if self.pause_s:+ time.sleep(self.pause_s)+ yield np.full(int(self.sample_rate * self.chunk_s), 0.1, dtype=np.float32)+++@dataclass+class FakeResult:+ text: str = ""+ tool_calls: list[dict[str, Any]] = field(default_factory=list)+ t_first_clause: float | None = 0.05+ error: str = ""+++class FakeLlm:+ """Each chat() call plays the next scripted reply: (clauses, tool_calls)."""++ def __init__(self, script: list[tuple[list[str], list[dict[str, Any]]]]) -> None:+ self.script = script+ self.calls: list[list[dict[str, Any]]] = []++ def chat(self, messages: list[dict[str, Any]], *, on_clause: Callable[[str, float], None]+ | None = None, stop: threading.Event | None = None, **_: Any) -> FakeResult:+ self.calls.append([dict(m) for m in messages])+ clauses, calls = self.script[min(len(self.calls) - 1, len(self.script) - 1)]+ for clause in clauses:+ if stop is not None and stop.is_set():+ break+ if on_clause is not None:+ on_clause(clause, 0.05)+ return FakeResult(text=" ".join(clauses), tool_calls=calls)+++class Collector:+ def __init__(self) -> None:+ self.messages: list[dict[str, Any]] = []+ self.audio_frames = 0+ self.heard_audio = asyncio.Event()++ def json(self, message: dict[str, Any]) -> None:+ self.messages.append(message)++ def audio(self, slot: int, seq: int, pcm16: bytes) -> None:+ self.audio_frames += 1+ self.heard_audio.set()++ def types(self) -> list[str]:+ return [m["type"] for m in self.messages]++ async def wait(self, kind: str, count: int = 1, within: float = 5.0) -> dict[str, Any]:+ deadline = time.monotonic() + within+ while time.monotonic() < deadline:+ matches = [m for m in self.messages if m["type"] == kind]+ if len(matches) >= count:+ return matches[count - 1]+ await asyncio.sleep(0.01)+ raise AssertionError(f"no {kind} #{count}; got {self.types()}")+++def _speech(seconds: float) -> bytes:+ t = np.arange(int(seconds * RATE)) / RATE+ return to_pcm16(0.3 * np.sin(2 * np.pi * 220 * t).astype(np.float32))+++def _silence(seconds: float) -> bytes:+ return to_pcm16(np.zeros(int(seconds * RATE), dtype=np.float32))+++def _session(llm: FakeLlm, *, stt: FakeStt | None = None, tts: FakeTts | None = None,+ turn: float = 0.95) -> tuple[ConversationSession, Collector, FakeStt]:+ stt = stt or FakeStt()+ tts = tts or FakeTts()+ models = EngineModels(vad_factory=FakeVad, turn=FakeTurn(turn), stt=stt,+ tts_for=lambda _lang: tts, llm=llm)+ collector = Collector()+ session = ConversationSession(+ slot=1, session_id="s1", models=models, emit=collector, loop=asyncio.get_running_loop(),+ config=EngineConfig(incomplete_wait_ms=200), instructions="You are Jarvis.",+ language="en", tools=[{"name": "set_timer", "description": "Start a timer.",+ "parameters": {"type": "object", "properties": {}}}],+ )+ return session, collector, stt+++async def _say(session: ConversationSession, seconds: float = 0.8, tail: float = 0.4) -> None:+ session.on_audio(_speech(seconds))+ session.on_audio(_silence(tail))+++async def test_a_finished_turn_is_transcribed_and_answered() -> None:+ llm = FakeLlm([(["It is noon.", "Anything else?"], [])])+ session, out, _ = _session(llm)+ await _say(session)+ final = await out.wait(p.TRANSCRIPT_INPUT)+ assert final["text"] == "what time is it" and final["final"] is True+ assert out.types()[0] == p.SPEECH_STARTED+ session.on_response_request("en")+ done = await out.wait(p.RESPONSE_DONE)+ assert done["status"] == "completed"+ spoken = [m["delta"].strip() for m in out.messages if m["type"] == p.TRANSCRIPT_OUTPUT]+ assert spoken == ["It is noon.", "Anything else?"]+ assert out.audio_frames > 0+ metrics = (await out.wait(p.METRICS))["turn"]+ assert metrics["status"] == "completed" and metrics["turn"] == 1+ assert "speech_end_to_first_audio_ms" in metrics+ system = llm.calls[0][0]["content"]+ assert "Reply in English" in system+++async def test_tool_calls_round_trip_through_the_app() -> None:+ llm = FakeLlm([+ ([], [{"name": "set_timer", "arguments": {"minutes": 10}}]),+ (["Your timer is running."], []),+ ])+ session, out, _ = _session(llm)+ await _say(session)+ await out.wait(p.TRANSCRIPT_INPUT)+ session.on_response_request("en")+ call = await out.wait(p.TOOL_CALL)+ assert call["name"] == "set_timer" and call["arguments"] == {"minutes": 10}+ session.on_tool_result(call["call_id"], {"success": True, "output": "Timer started."})+ done = await out.wait(p.RESPONSE_DONE)+ assert done["status"] == "completed"+ second = llm.calls[1]+ assert second[-1]["role"] == "tool" and "Timer started." in second[-1]["content"]+ assert second[-2]["tool_calls"][0]["function"]["name"] == "set_timer"+++async def test_speaking_over_the_answer_stops_it() -> None:+ llm = FakeLlm([(["One.", "Two.", "Three.", "Four."], [])])+ session, out, _ = _session(llm, tts=FakeTts(chunks=10, chunk_s=0.05, pause_s=0.05))+ await _say(session)+ await out.wait(p.TRANSCRIPT_INPUT)+ session.on_response_request("en")+ await out.wait(p.TRANSCRIPT_OUTPUT)+ await asyncio.wait_for(out.heard_audio.wait(), 5.0)+ session.on_audio(_speech(0.5))+ interrupted = await out.wait(p.INTERRUPTED)+ assert interrupted["self_initiated"] is False+ done = await out.wait(p.RESPONSE_DONE)+ assert done["status"] == "cancelled"+ assert out.types().count(p.SPEECH_STARTED) == 2+++async def test_a_user_who_keeps_talking_gets_one_merged_turn() -> None:+ llm = FakeLlm([(["Done."], [])])+ stt = FakeStt(texts=["remind me", "to call mum"])+ session, out, _ = _session(llm, stt=stt)+ await _say(session)+ first = await out.wait(p.TRANSCRIPT_INPUT)+ assert first["text"] == "remind me"+ await _say(session) # resumes before the app asked for an answer+ second = await out.wait(p.TRANSCRIPT_INPUT, count=2)+ assert second["text"] == "remind me to call mum"+ session.on_response_request("en")+ await out.wait(p.RESPONSE_DONE)+ assert llm.calls[0][-1] == {"role": "user", "content": "remind me to call mum"}+++async def test_an_incomplete_verdict_waits_before_finalising() -> None:+ llm = FakeLlm([(["Sure."], [])])+ session, out, _ = _session(llm, turn=0.1)+ started = time.monotonic()+ await _say(session)+ await out.wait(p.TRANSCRIPT_INPUT)+ assert time.monotonic() - started >= 0.2+++async def test_a_request_without_a_pending_turn_is_ignored() -> None:+ llm = FakeLlm([(["Hi."], [])])+ session, out, _ = _session(llm)+ session.on_response_request("en")+ await asyncio.sleep(0.1)+ assert llm.calls == [] and p.RESPONSE_DONE not in out.types()+ session.close()diff --git a/tests/unit/voice_engine/test_protocol.py b/tests/unit/voice_engine/test_protocol.pynew file mode 100644index 0000000000..56c1117ff5--- /dev/null+++ b/tests/unit/voice_engine/test_protocol.py@@ -0,0 +1,46 @@+"""Wire protocol v1: framing round trips and malformed input."""++from __future__ import annotations++import struct++import pytest++from jarvis.voice_engine import protocol as p+++def test_json_and_audio_frames_round_trip_across_arbitrary_splits() -> None:+ message = {"type": p.TRANSCRIPT_INPUT, "text": "Grüße", "final": True} # i18n-allow+ pcm = bytes(range(256)) * 4+ stream = p.encode_json(message) + p.encode_audio(3, 7, pcm) + p.encode_json({"type": "x"})+ reader = p.FrameReader()+ frames = []+ for i in range(0, len(stream), 5):+ frames.extend(reader.feed(stream[i : i + 5]))+ assert frames[0] == message+ assert frames[1] == p.AudioFrame(slot=3, seq=7, pcm=pcm)+ assert frames[2] == {"type": "x"}+ assert reader.pending_bytes == 0+++def test_partial_frames_wait_for_the_rest() -> None:+ data = p.encode_json({"type": "hello"})+ reader = p.FrameReader()+ assert reader.feed(data[:-1]) == []+ assert reader.feed(data[-1:]) == [{"type": "hello"}]+++ "payload",+ [b"Jnot json", b"J[1, 2]", b'J{"no_type": 1}', b"Xabc", b"A\x00"],+)+def test_malformed_payloads_are_rejected(payload: bytes) -> None:+ with pytest.raises(p.ProtocolError):+ p.FrameReader().feed(struct.pack(">I", len(payload)) + payload)+++def test_oversized_length_is_rejected_before_buffering() -> None:+ with pytest.raises(p.ProtocolError):+ p.FrameReader().feed(struct.pack(">I", p.MAX_FRAME_BYTES + 1) + b"J")+ with pytest.raises(p.ProtocolError):+ p.encode_audio(0, 0, b"\x00" * (p.MAX_FRAME_BYTES + 1))