docs: add spec 07-voice-audio

This commit is contained in:
nocode committed 2026-11-11 20:20:49 +01:00
1 parent 3604d90fa4
commit e540375dca
1 file changed
+670
+670
View File
@@ -0,0 +1,670 @@
# 07 — Voice and audio (VOX): microphone, speech recognition, TTS, voice effects, subtitles, music detection, call audio
Source of truth: CapriCore 1.0.4 tree at `~/Capri` (read-only). All paths below are relative to that root unless stated otherwise. Capri uses a single *install root* that holds `config/`, `integrations/`, `data/`, `logs/` and `.runtime/`; the Rust port should keep that layout (the Python TTS sidecar depends on it, see §10).
Conventions: `file:line` references point at the 1.0.4 sources. "Host" = the Electron main process, "renderer" = the companion web page; in the Rust app both collapse into one process (plus sidecars). Feature IDs are stable: `VOX-xx`.
---
## 1. Purpose and scope
This spec covers everything that captures, recognizes, synthesizes, plays, transforms or classifies audio in Capri:
| Area | Capri files | Rust module (proposed, §10) |
|---|---|---|
| Microphone session, wake gate, transcript routing, echo guard | `apps/desktop/microphone-service.mjs`, `apps/desktop/wake-phrase.mjs`, `apps/desktop/voice-follow-up.mjs` (consumed), `apps/desktop/renderer/microphone.mjs`, `renderer/microphone-worklet.mjs`, `renderer/microphone-button.mjs`, `renderer/wake-feedback.mjs` (consumed), `main/companion-ipc.mjs:31-157` (wake audio, consumed) | `capri-mic`, `capri-wake` |
| Microphone device selection | `apps/desktop/audio-input-settings.mjs` | `capri-audio-io` |
| ASR worker protocol and runtime | `apps/desktop/asr-worker.mjs`, `integrations/asr_runtime/{worker,protocol,model,recognition,vocabulary,alignment,shared_encoder}.py`, `integrations/multilingual.py`, `config/{companion-asr,asr-vocabulary,asr-model-upstream,asr-vad-upstream,multilingual-candidates,multilingual-runtime}.json`, `config/asr-requirements.lock.txt` | `capri-asr` |
| Speech-pause setting | `renderer/speech-settings.mjs`, `renderer/speech-panel.mjs` | `capri-mic` |
| TTS client (sentence queue) | `apps/desktop/voice-service.mjs`, `renderer/speech-text.mjs` | `capri-tts` |
| TTS sidecar (Python, kept) | `integrations/voice_runtime/*` (+ `host.mjs`, `readiness.mjs`, `environment.mjs`, `startup-error.mjs`), `integrations/voice_training/*` (summary), `config/{companion-voice,tts-catalog,voice-runtime,voice-upstream,voice-model-download,qwen-tts-upstream,voice-training,voice-evaluation.en}.json`, `config/requirements-*.lock`, `config/voice-*-overrides.txt`, `config/voice-pytorch-*.constraints.txt` | `capri-tts::sidecar` |
| Voice catalog, residency, training, install | `apps/desktop/voice-catalog-service.mjs`, `voice-residency.mjs`, `voice-training-service.mjs`, `speech-install-service.mjs`, `packages/runtime/src/voice-settings.mjs`, `packages/runtime/src/hardware/voice-gpu.mjs`, `packages/installer/src/{speech-components,voice-catalog-prepare,voice-pack}.mjs` (followed imports), `tools/setup/*.ps1|*.py` (followed) | `capri-tts::catalog`, `capri-speech-install` |
| Playback, effects, level meter | `renderer/voice-player.mjs`, `renderer/voice-effects.mjs`, `renderer/voice-effects-settings.mjs`, `renderer/voice-effects-panel.mjs`, `renderer/voice-model-panel.mjs` | `capri-player`, `capri-fx` |
| Subtitles | `renderer/subtitles.mjs`, `renderer/subtitle-controller.mjs` | `capri-subtitles` |
| Music listening | `apps/desktop/{music-listening-service,music-listening-settings,music-audio-capture,music-detector-provision,music-artwork}.mjs`, `renderer/{system-music-capture,music-worklet,music-listening-panel}.mjs`, `integrations/music_runtime/{worker,features,tempo}.py`, `config/music-detector.json` | `capri-music` |
| System audio into ASR | `apps/desktop/system-audio-capture.mjs`, `renderer/microphone.mjs:115-210` | `capri-mic` |
| Call audio | `apps/desktop/{call-audio-setup,call-response,virtual-cable-installer}.mjs`, `main/{call-audio,call-audio-diagnostics}.mjs`, `renderer/{call-audio-route,call-audio-settings,call-microphone}.mjs`, `integrations/call-audio/CableDefaults.cs` | `capri-call` |
| Wiring | `apps/desktop/main.mjs` (lines cited per feature), `apps/desktop/preload.cjs:18-205` (IPC surface) | app crate |
Out of scope (other specs, only interfaces listed in §9): chat/turn production, avatar rendering (mouth plates `renderer/avatar-mouth.mjs`, music poses/notes `renderer/music-animation.mjs`), language-settings model, reminders, the settings-window framework, response-timing telemetry, window raising.
**Current Linux state (observed, not designed):** none of the owned files carry `FWS-LINUX-BRIDGE` patches. On the owner's machine ASR and TTS run only because of hand-made shims (`.runtime/asr-venv/Scripts/python.exe -> ../bin/python`, `.runtime/voice-training-venv/Scripts/python.exe -> ../bin/python`, `.runtime/asr-venv/Lib/site-packages -> ../lib/python3.11/site-packages`) and a manual uv setup (`.runtime/asr-setup.log`, `.runtime/voice-setup.log`, `.runtime/voice-server-test.log` show Parakeet/Silero/Whisper verified and "Capri voice ready on loopback port 8101" with torch 2.7.1+cu128 on an RTX 5070 Laptop GPU). Music listening, system audio and call audio are hard-disabled by `process.platform === 'win32'` gates (`music-listening-service.mjs:98`, `music-audio-capture.mjs:11`, `system-audio-capture.mjs:11`, `main.mjs:1337-1359`). The in-app speech installer fails (see VOX-34).
---
## 2. Feature catalog
Priority legend: **P0** core (companion broken without it), **P1** expected by a Capri user, **P2** optional/niche.
### 2.1 Microphone and speech recognition
#### VOX-01 — Microphone session lifecycle · P0
Source: `microphone-service.mjs:60-314,527-533`; `main.mjs:5942-5969,6160-6178`; `renderer/microphone.mjs:39-114,268-299`.
- Host state machine `status`: `off → starting → arming → listening → off`. Every start creates a *capture* `{id: uuidv4, generation, sequence:0, interrupted:Set, finalized:Set, waiting:0, latestUtterance:-1, discardedThrough:-1, recognitionPhase:'idle', inputGeneration:0, followUps:0, wake: WakePhraseGate}`; `generation` is a monotonically increasing integer bumped by every start/stop/close so late results/packets from a previous capture are ignored.
- `start()` is idempotent (returns the current snapshot if a capture exists). It publishes `starting`, sends worker `start {sessionId, attention: !wakeWord.enabled, trailingSilenceSeconds}` (this lazily spawns/loads the recognizer), and on ack moves to `arming` unless the generation changed (`'Microphone start cancelled'`). Failure → `recognizerFailed(error, startup=true)` then rethrow.
- `confirm(id)` (renderer calls it after its audio graph is wired, IPC `capri:microphone-ready`) requires `status==='arming'` and the same id, else throws `'Inactive microphone'`; sets `listening`.
- Host preconditions for `capri:microphone-start` (`main.mjs:5942`): speech installer not busy (`'Wait for speech installation to finish, or cancel it in Languages.'`); recognition allowed and installed for the current recognition language, not shutting down, backend phase `ready` or `asleep`, else `'The selected speech recognition model is unavailable. Run setup-multilingual.cmd.'`. Returns `{...snapshot, sessionId, deviceId, deviceLabel}`. Side effect: if companion `wakeSound==='voice'`, awake, no chat turn, voice not generating and no playback → prepare the cached wake voice in background (VOX-15).
- Renderer start order: AudioContext at 16 kHz (fallback: default rate), `resume()`, `startMicrophone`, `getUserMedia` (VOX-02 constraints), track `ended` → stop + `'The microphone disconnected. Choose an available device in Menu → Microphone input.'`, load worklet, graph `source → micGain → worklet → silence(gain 0) → destination` (worklet output always zero: the mic is never monitored), `microphoneReady(id)`, then state `listening` with `actualDeviceLabel`. Any await that finds the run replaced releases what it acquired (tracks stopped, `stopMicrophone(run.id)`).
- Renderer error mapping: `NotAllowedError` → `'Microphone access was denied. Check Windows microphone access for desktop apps.'`; `NotFoundError|NotReadableError|OverconstrainedError` → `'The selected microphone is unavailable. Choose a device in Menu → Microphone input.'`; anything else → `'Speech recognition could not start. Check the selected language and setup-multilingual.cmd.'`.
- `stop(id?)`: no-op `false` if `id` given and not current. Closes wake timers, clears capture, bumps generation, `status='off'`, new EchoGuard, publishes `microphone.settings {…, stoppedSessionId}`, and (if a worker process exists) sends `stop {sessionId}` ignoring errors.
- IPC `capri:microphone-stop` accepts `{id?, keepModelWarm?: boolean}` or a bare id (`main.mjs:6167`); if stopped and `!keepModelWarm` the recognizer process is closed (frees ~1-3 GB RAM). The composer mic button stops with `keepModelWarm=true`; the header button is the "master switch" that also unloads (`renderer/microphone.mjs:31-38`: toggle → stop if running; else if `modelLoaded` → unload; else start).
- The microphone is **off at every launch** (nothing persisted). Recognition-language change (`main.mjs:6197-6234`) stops capture, closes the worker and requires re-enabling. Device change stops capture and emits `microphone.device-changed {deviceId, deviceLabel, restart}`; the renderer restarts if `restart`.
- Sleep (`main.mjs:2343-2436`): unloading keeps an *already enabled* CPU microphone alive (so wake phrases still work); otherwise the worker is closed. On wake-up the recognizer is pre-started (startup step `recognition`) only if capture is active.
#### VOX-02 — Capture format and framing · P0
Source: `renderer/microphone.mjs:6-17`, `renderer/microphone-worklet.mjs:2-58`.
- Constraints: mono, `echoCancellation:true`, `noiseSuppression:false`, `autoGainControl:false` (recognition needs unprocessed quiet syllables), `deviceId:{exact:id}` when a specific device is saved, otherwise the system default.
- `PCMFramer(inputRate, 16000, 1600)`: box-integration resampler (each output sample = mean of the input interval of length `inputRate/16000`), non-finite → 0, clamp to [-1, 1]; emits frames of **1600 samples = 100 ms of f32 LE mono @16 kHz** with `rms = sqrt(Σx²/1600)`. Must be continuous across render-quantum boundaries (tested at 16/44.1/48 kHz).
- Level meter: `min(1, rms*10)` drives the transcript-preview and wake-feedback CSS level.
- Rust/Linux: open a PulseAudio record stream `float32le/16000/1ch` on the selected source (PipeWire/PulseAudio resamples server-side), fragment 1600 frames. Keep `PCMFramer` for backends that cannot resample (cpal/ALSA).
#### VOX-03 — Audio transport and backpressure · P0
Source: `renderer/microphone.mjs:3,211-254`; `microphone-service.mjs:336-377`.
- Renderer FIFO: max **50 frames (5 s)**; overflow → stop + `'Microphone audio could not keep up. Enable the microphone to retry.'`. Pump sends at most 2 frames concatenated (≤12 800 bytes = 200 ms) per message, never waits to fill a batch, increments `sequence` per message. `{accepted:false}` → silent stop; exception → stop + `'The speech recognizer stopped. Enable the microphone to retry.'`.
- Host validation: packets for no/other capture or not `listening` → `{accepted:false}` quietly (late packets after stop/language change must neither reach ASR nor fault a newer capture). Otherwise require `sequence === expected`, `pcm` byte array of 1..12 800 bytes, length % 4 == 0, and at most **2 packets in flight**; violation → `fail('Microphone audio could not be delivered reliably. Restart the microphone.')` and error. Transport errors record `lastFailure {at, code: error.code ?? 'ASR_TRANSPORT', message: ≤300 chars}` and fail with the worker's message (if it has a code) or `'Recognition could not keep up. Restart the microphone.'`.
- Rust: capture thread → bounded channel (50 frames) → recognizer; same overflow behavior; keep `{sessionId, sequence}` tokens on every frame.
#### VOX-04 — Microphone device selection · P1
Source: `audio-input-settings.mjs:1-114`; `main.mjs:874,3574-3605,3663-3709`.
- Persisted file `data/desktop/microphone.json` (§3). `''` means system default. A corrupt file is ignored (defaults used) and **not overwritten** until the user explicitly selects a device.
- `update(devices)`: ≤128 entries else error; keep `kind==='audioinput'`, id string ≤512 chars without control chars, non-empty. Entry `default` only provides the default label: `'System default — ' + label.replace(/^Default\s*[-–—]\s*/i,'')`. Skip `communications` and duplicates. Labels: control chars → space, trim, ≤180 chars, fallback `Microphone N`.
- `describe(id)`: `'default'`→`''`; unknown id → `'That microphone is unavailable. Reopen the menu to refresh the list.'`. `select(id)` writes only when changed.
- Menu (tray/context): radio items "System default…" + devices; a saved-but-absent device is shown checked and disabled as `Unavailable — <label>` (never silently fall back); empty list → disabled `No named microphones detected`. Tray also has `Microphone (<language name>)` checkbox (enabled when ASR installed and backend ready/asleep) and `Microphone settings…`.
- Enumeration only reads metadata, never opens a stream; 2.5 s timeout (`'Audio input list timed out'`), single in-flight refresh.
- Linux: enumerate PulseAudio sources excluding monitors (`monitor_of_sink` set or name ending `.monitor`) and Capri's own virtual sources (`capri_*`); `deviceId` = source name (stable), label = description; default = `@DEFAULT_SOURCE@`.
#### VOX-05 — ASR worker process and protocol · P0
Source: `asr-worker.mjs:1-353`; `integrations/asr_runtime/worker.py:1-119`, `protocol.py:1-12`.
Today the recognizer is an owned CPU child process speaking JSON lines over private stdio (never a network listener). Keep this as the Rust contract (recommended: a subprocess of the same Rust binary, `capri asr-worker`, see §10) so crash isolation, the one-shot safe restart and the tests survive.
Spawn (today): `<root>/.runtime/asr-venv/Scripts/python.exe -u -m integrations.asr_runtime.worker`, cwd=root, env = allowlist (`SystemRoot WINDIR PATH TEMP TMP USERPROFILE APPDATA LOCALAPPDATA`) + `PYTHONUTF8=1 PYTHONIOENCODING=utf-8 PYTHONNOUSERSITE=1 OMP_NUM_THREADS=4 HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false CAPRI_ASR_LANGUAGE=<lang>`; safe mode: `OMP_NUM_THREADS=1 CAPRI_ASR_SAFE_STARTUP=1 CAPRI_CPU_THREADS=1`. stderr is drained and discarded ("Diagnostics must never echo captured speech"). Language must be `auto`, `auto-europe` or a language-pack id, else `ASR_START_CONFIG`; missing interpreter → `ASR_START_PYTHON`.
Worker → host (stdout, one compact ASCII JSON object per line):
| type | fields / rules |
|---|---|
| `startup-stage` | exactly `{type, code}`; code ∈ `ASR_START_DEPENDENCIES, ASR_START_CONFIG, ASR_START_DETECTOR, ASR_START_MODEL`; flushed *before* each step (a native crash cannot be caught); only valid before `ready` |
| `startup-error` | `{type, code:<last stage>}` (no exception text: it may contain install paths) |
| `ready` | must equal `{protocol:1, language:<requested>, sampleRate:16000, provider:'cpu', mode:'utterance', draft:false}` (+`engine`) |
| `recognition-state` | `{sessionId, utterance≥0, phase:'speech'|'processing'}` |
| `wake-candidate` | `{sessionId, utterance, text≤4096, boundaries:[{start,end,startSample,endSample}]≤64}`; `0≤start<end≤text.length`, `0≤startSample≤endSample`, `endSample>0` |
| `transcript` | `{sessionId, utterance, final:true, text≤4096, audioSeconds, prefixRemoved, recognitionMs}` |
| `recognition-reset` | exactly `{type, sessionId(≤80), utterance, nextUtterance:utterance+1, reason:'utterance_limit'}` |
| `recognition-error` | `{sessionId, code:'recognition_failed'}` → fatal |
| `ack` / `error` | `{request}` / `{request, code:'ASR_…'}` |
Host → worker commands (`request` = increasing integer): `start {sessionId≤80, attention, trailingSilenceSeconds}`, `stop {sessionId}` (a foreign id is acked and ignored), `configure {sessionId, trailingSilenceSeconds}`, `attention {sessionId, active, utterance?, wakeEndSample?}`, `pcm {sessionId, pcm: base64 f32le, ≤12 800 bytes, %4==0}`, `finish` (same as pcm + VAD flush), `quit`.
Error codes (`protocol.py`): `ASR_INACTIVE_SESSION` (inactive capture/recognition session), `ASR_QUEUE_FULL`, `ASR_UTTERANCE_LIMIT`, `ASR_HISTORY_GAP`, `ASR_INVALID_PCM` (bad packet or >200 ms / non-finite), `ASR_WAKE_BOUNDARY`, default `ASR_PACKET_REJECTED`. Host messages: QUEUE_FULL → `'Speech recognition is busy. Wait a moment, then restart the microphone.'`; UTTERANCE_LIMIT → `'The spoken phrase is too long. Restart the microphone and use a shorter phrase.'`; INACTIVE_SESSION → `'The microphone session changed. Restart the microphone.'`; else `'Recognition rejected an audio packet'`. Codes outside `/^ASR_[A-Z_]{1,40}$/` become `ASR_PACKET_REJECTED`.
Limits and timeouts: worker stdin line ≤32 768 bytes; host stdout buffer >65 536 chars without newline, non-JSON, non-object, unknown type or any invalid field → protocol failure + kill. Startup timeout **60 s** (`ASR_START_TIMEOUT`, `'Recognition worker startup timed out'`). Every command times out after **15 s** (`'Recognition timed out'`, worker closed). At most **4 pending** commands (`'The speech recognizer cannot keep up with audio input.'`). Concurrent `start()` calls share one startup task.
Failure codes: spawn error → `ASR_START_SPAWN` / `ASR_WORKER_IO`; stdin error → `ASR_START_IO` / `ASR_WORKER_IO`; protocol → `ASR_START_PROTOCOL` / `ASR_WORKER_PROTOCOL`; exit before ready → native map of the Windows exit status (`0xC000001D`→`ASR_START_NATIVE_INSTRUCTION`, `0xC0000005`→`ASR_START_NATIVE_CRASH`, `0xC0000017`→`ASR_START_NO_MEMORY`, `0xC0000135/139/142`→`ASR_START_NATIVE_DLL`) else `ASR_START_EXIT`; exit after ready → `ASR_WORKER_EXIT`. Startup errors carry the last allowlisted `startupStage`. **Recovery**: exactly once, only for `ASR_START_NATIVE_CRASH` at stage `ASR_START_MODEL`: emit `recovery`, restart in safe mode (1 thread, greedy, 1 path); the first crash emits no `failure`.
Host mapping (`microphone-service.mjs:319-335`): code kept if it matches `/^ASR_(?:START|WORKER)_[A-Z_]{1,40}$/`, else `ASR_START_SESSION` (startup) / `ASR_WORKER_EXIT`; message `'Speech recognition could not start. Check the selected language and setup-multilingual.cmd.'` (startup) or `'The local speech recognizer stopped. Restart the microphone.'`; `lastFailure {at, code, message, startupStage?}`; then stop + `microphone.error`.
Linux mapping of native exits (recommended): `SIGILL`→`ASR_START_NATIVE_INSTRUCTION`; `SIGSEGV|SIGBUS|SIGABRT`→`ASR_START_NATIVE_CRASH`; `SIGKILL` (OOM killer) →`ASR_START_NO_MEMORY`; dynamic-loader failure (exit 127 or a dedicated exit code from the worker when a library fails to load) →`ASR_START_NATIVE_DLL`.
#### VOX-06 — VAD and utterance segmentation · P0
Source: `integrations/asr_runtime/model.py:178-200`, `recognition.py:11-274`.
- Silero VAD v5 (`data/speech/silero-vad-v5/silero_vad.onnx`): 16 kHz, window 512, threshold 0.5, min speech 0.12 s, **min silence = trailing pause** (0.5–5.0 s, default 1.0), `max_speech_duration = maxUtteranceSeconds + max(4, pause+2) + 1` s (35 s at defaults; placed beyond the session limit so Sherpa's forced endpoint can never emit a cropped command), ring buffer 75 s, 1 thread.
- Session bound `max_samples = (maxUtteranceSeconds + max(4, pause+2)) × 16000` (34 s at defaults). History keeps only chunks newer than `received − max_samples`. `accept()` accepts ≤3200 samples (200 ms), 1-D, finite; clips to [-1, 1].
- Turn start = `max(vad_offset, received − len − 6400)` when speech begins. If a turn (active or with pending segments) exceeds `max_samples` → **discard_turn** (see below).
- Speech rising edge increments `revision` (invalidates an endpoint already being decoded: the next decode contains original audio + gap + continuation). Emit `recognition-state 'speech'` on the rising edge and then at most once per 16 000 samples.
- Segment extraction: start mapped to capture clock (`segment.start + vad_offset`), audio range `[start − 6400, end + 2400]` (400 ms pre-roll, 150 ms real tail) clipped to `[vad_offset, received]`; pre-roll older than history or segment longer than `max_samples` → discard_turn. Consecutive segments merge into one utterance with the real gap zero-filled (overlap trimmed); merged size > `max_samples` → discard_turn.
- Endpoint: when ≥1 segment completed and speech is not active → `revision++`, emit `processing`, submit final job `(utterance, revision, pcm ++ 3200 zeros (200 ms pad), start)`.
- Wake probes (only while waiting for the name): speech active, no attention, no utterance pending, `probes < 3`, current segment ≥ `wakeProbeSeconds×16000` (12 800) and grown ≥12 800 since last probe and ≤ 4 s → submit `wake` job if the decoder queue is idle.
- `discard_turn()`: `utterance++`, `revision++`, attention reset to `!wakeEnabled`, pcm/history cleared, VAD reset, `vad_offset = received`, pending pause applied, emit `recognition-reset`. Capture and loaded model keep running.
- Delivery: drop if session stopped or `(utterance, revision)` changed. Wake job → `wake-candidate` only if still speaking, no attention and text non-empty (boundaries shifted to the capture clock, ≤64). Final job → drop if speech resumed; if a wake end sample is known, `remove_wake_prefix(result, wakeEndSample − audioStart)`; then `utterance++`, `revision++`, probes reset, emit `transcript` (`audioSeconds` rounded to 3 decimals, `recognitionMs` to 2).
- Decoder queue: one decode thread; a `wake` job is refused when anything is queued/running; submitting cancels queued (not running) jobs; ≥2 futures → `'Recognition queue is full'`; decode exception → `recognition-error` (fatal, **no weaker fallback**). The hotword set is chosen from the *attention* flag at decode start.
- `set_attention(active, utterance?, wakeEndSample?)`: `active` must be bool; deactivation clears the wake end; activation for the current utterance with `0 < wakeEndSample ≤ received` stores it, otherwise `ASR_WAKE_BOUNDARY`.
- `configure_pause`: the new detector is installed only when idle (no active speech, nothing pending); its sample clock is rebased (`vad_offset = received`) and `max_samples` recomputed. An utterance in progress keeps its old pause through decoding.
- Stop: session dead, history cleared, queued futures cancelled, running decode discarded.
#### VOX-07 — Recognition engines and language routing · P0 (English) / P1 (other languages)
Source: `integrations/asr_runtime/model.py:16-175`, `shared_encoder.py`, `integrations/multilingual.py`, `apps/shared/languages.json`.
- `config/companion-asr.json` validation (model.py:18-31): schemaVersion 1, engine `parakeet-tdt-0.6b-v2`, language `en`, sampleRate 16000, chunkMs 100, `cpuThreads` int 1..8 (effective `min(cpuThreads, cpu_count, CAPRI_CPU_THREADS || 8)`), `decodingMethod ∈ {greedy_search, modified_beam_search}`, `maxActivePaths` 1..8, `trailingSilenceSeconds` 0.5..5, `maxUtteranceSeconds` 10..60, booleans `autoSend`, `bargeIn`; `vad.threshold` 0.2..0.9, `vad.minSpeechSeconds` 0.06..0.5, `vad.wakeProbeSeconds` 0.5..2; both model dirs must resolve inside `data/speech`.
- Routing by recognition language (`resolveLanguages`, `renderer/language-settings.mjs:32-48`; `recognition='follow'` uses the conversation language, `custom` conversation or `autoDetect` → `auto`):
- `en` → **Parakeet TDT 0.6B v2 INT8** (sherpa-onnx export, `data/speech/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8`, files/hashes in `config/asr-model-upstream.json`), `modified_beam_search`, 4 active paths, contextual hotwords (VOX-08), `model_type='nemo_transducer'`, `modeling_unit='bpe'`.
- `auto-europe` or any language whose `recognizer` is `parakeet-v3` (24: bg hr cs da nl et fi fr de el hu it lv lt mt pl pt ro ru sk sl es sv uk) → **Parakeet TDT 0.6B v3 INT8** (`data/speech/candidates/parakeet-tdt-v3-int8`, `config/multilingual-candidates.json → asr`), forced `greedy_search` (the pinned v3 beam decoder returns empty text for clear speech), therefore no hotwords.
- every other language (75 `whisper` languages) and `auto` → **faster-whisper large-v3-turbo** (CTranslate2 INT8 CPU, `data/speech/faster-whisper-large-v3-turbo`, `multilingual-runtime.json → whisper`), language=None for `auto`; `beam_size=5, best_of=1, temperature=0, condition_on_previous_text=False, word_timestamps=True, vad_filter=False, hotwords='Capri, Spotify', hallucination_silence_threshold=1.0, max_new_tokens=440`; segments with `no_speech_prob>0.6 and avg_logprob<−1` dropped; words joined with a space unless the detected language ∈ {ja, zh, yue, th, lo, my} and the word has no leading whitespace; per-word boundaries in samples. The encoder output of the language-detection window is reused for transcription when features are byte-identical (scope: one utterance). **Wake probes in Whisper mode use the English Parakeet v2 model** (must be installed).
- All model files are checked by exact size and SHA-256 before loading; mismatch → startup error (`'Recognition model checksum mismatch'`, `MissingSpeechModel`) — never a weaker fallback.
- Safe startup (VOX-05 recovery): 1 thread, greedy, 1 active path; language and model unchanged.
- Text normalization: collapse whitespace; >4096 chars → error.
- Installed-check used by the UI (`language-models.mjs:101-131`): interpreter present + Silero files + (v3 files | v2 files [+ faster-whisper package + Whisper files]) with exact sizes (hashes are verified later by the worker).
#### VOX-08 — Contextual vocabulary (hotwords) · P1
Source: `integrations/asr_runtime/vocabulary.py:23-57`; `config/asr-vocabulary.json`.
- File ≤16 384 bytes, schemaVersion 1, `wakeScore`/`commandScore` finite in [0, 3], per-language lists ≤16 phrases, each 1..80 chars of letters/space/`'`/`-`. Wake list falls back to `en` for a missing language; commands do not.
- Hotword string: `"<phrase> :<score>"` joined with `/` (e.g. `Capri :1.5`, `clip that :0.8/clip this :0.8/…`). Per decode: wake probe → wake list; addressed final (attention on) → command list; unaddressed final → wake + commands. Only applied with `modified_beam_search`.
- BPE vocabulary for Parakeet hotwords: for each non-empty line of `tokens.txt`, `<first space-separated field>\t-1.0\n`; cached at `.runtime/asr-vocab/<sha256(tokens.txt)>.vocab`, rewritten atomically (`.<pid>.tmp` + rename) when content differs. (The Windows narrow-path workaround is not needed on Linux.)
- Rust: `SherpaOnnxCreateOfflineStreamWithHotwords(recognizer, hotwords)` per stream; recognizer config `modeling_unit="bpe"`, `bpe_vocab=<cache path>`, `decoding_method`, `max_active_paths`.
#### VOX-09 — Wake phrase gate ("Capri" / "Hey, Capri") · P0
Source: `wake-phrase.mjs:1-256`; `microphone-service.mjs:79-97,214-255`; `config/companion-asr.json → wakeWord {enabled:true, commandWindowMs:10000, ambiguityHoldMs:120}`.
Matching (pure function, port verbatim):
- Tokens: regex `[\p{L}\p{N}]+`, first 256 matches, each word NFKD-normalized, combining marks removed, lowercased; keep char offsets.
- `phonetic(word)`: map Cyrillic `к→k а→a э→a е→e п→p р→r и→i й→i ы→i ф→f`, then in order: `/ce$/→s`, `/ee|ie|ea/→i`, `/y$/→i`, `/[cq]/→k`, `/[bf]/→p`, collapse repeated letters `([a-z])\1+ → \1`.
- `nameMatch(word, relaxed)`: sound length 3..9, starts with `k`, first 4 chars contain `p`; bounded Damerau–Levenshtein distance to `kapri` (length difference >2 ⇒ 3); accept `≤1` (`≤2` when relaxed); `exact = distance==0`.
- `findWakePhrase(text, relaxed=false)`: (1) bare name: the first token, or the first two tokens concatenated, must match **strictly** (a name must *start* the address; "copy" stays a command); (2) compound greeting token starting with `hey|hay|эй|эи` followed by the name inside the same token (`heycapri`); (3) greeting token in `{hey, hay, hi, эй, хей, хэй, эи, хеи, хэи}` or weak greeting in `{a, ay, eh, he, okay, ok}` followed by 1 or 2 tokens matching the name (weak greetings require an exact match unless relaxed); `exact` only for strong greetings. Result `{start, end, exact, body}` where `body` = text after the match with leading `[\s,.!?;:—–-]+` stripped.
- `stripActivatedPrefix(text)`: relaxed `findWakePhrase`, else strip a leading 1–2-token name; otherwise unchanged.
Gate state machine (`WakePhraseGate`; constructor rejects `commandWindowMs` outside 3000..30000 or `ambiguityHoldMs` outside 0..500): states `disabled` (wake off) / `waiting` / `command`; `floor` = first utterance number still allowed.
- `observe(event)`: disabled → accept trimmed text. `utterance < floor` → reject. In `waiting`: no match → cancel candidate, reject; match that is exact, or a final transcript, or hold==0 → `activate`; otherwise keep the latest candidate for this utterance for **120 ms** (`{accepted:false, pending:true}`), then `activate(candidate, delayed=true)` which re-feeds it through `onReady` (= transcript handler). In `command`: text = `prefixRemoved ? text : (utterance === wakeUtterance ? stripActivatedPrefix(text) : text)`; non-empty text re-arms the window.
- `activate(event)`: state `command`, `wakeUtterance=lastUtterance=event.utterance`, arm window, compute `wakeEndSample` from the boundary that covers the end of the matched name, call `onWake`.
- `armTimeout(refining, budget=20000)`: window = `commandWindowMs` (10 s), or while ASR reports activity `max(commandWindowMs, min(90000, max(20000, budget)))` — the host passes 90 000 when Whisper is *processing*, else 20 000. Expiry → `rearm(lastUtterance, 'timeout')`.
- `rearm(utterance, reason)`: `floor = max(floor, utterance+1)`, state `waiting`, `onSleep(reason)`; reasons `submitted|timeout|manual|typed-input|mixed-audio|utterance-limit`.
- `continueListening(ms=12000)`: only when enabled and `waiting`; state `command`, `wakeUtterance=-1` (no prefix stripping), timeout clamped to 5000..30000 ms.
- Host callbacks: `onWake` → reset follow-ups, worker `attention {active:true, wakeEndSample?, utterance?}`, publish, emit `microphone.wake {sessionId, utterance}`, barge-in (VOX-11). `onSleep` → worker `attention {active:false}`, publish; on `timeout` also emit an empty `microphone.partial` (clears the preview).
- Snapshot `wakePhrase` label is the literal `'Capri / Hey, Capri'`.
- The final decode always hears the intact utterance; the worker removes only leading words whose `startSample < wakeEnd − 1280` (one encoder frame of margin, `alignment.py:33-45`) and marks `prefixRemoved` so the gate never strips twice. Word boundaries come from Parakeet token timestamps/durations (`alignment.py:6-30`): tokens joined must reproduce the text word-for-word, timestamps finite and ≥0, otherwise no boundaries (no stripping by time; fall back to text stripping).
#### VOX-10 — Transcript acceptance and submission · P0
Source: `microphone-service.mjs:8-24,389-526`; `main.mjs:1322-1336`.
Order of rules for each worker `transcript`/`wake-candidate` event (port exactly):
1. Ignore if no capture, other session, not `listening`, or `utterance ≤ discardedThrough`.
2. Only finals and internal wake probes (`wakeOnly`) proceed — **no provisional words ever reach the UI or the conversation**.
3. `echo = EchoGuard.matches(text)`; an echo cancels a pending wake candidate.
4. Already-finalized utterance → ignore. For finals: record timing (keep last 20 rows; accept only `0≤recognitionMs≤600000` and `0≤audioSeconds≤60`), set phase `idle`, publish.
5. `latestUtterance = max(latestUtterance, utterance)`.
6. System-audio review without wake (VOX-17): finals are finalized (set bounded to 64) and, if non-empty and not echo, emitted as `microphone.activity` + `microphone.partial {final:true, autoSend:false}`; stop.
7. Not review mode, final, not echo, and text matches *microphone off* (`/^(stop listening|microphone off|turn off (?:the )?microphone|не слушай|выключи микрофон|прекрати слушать)$/i` after trimming trailing `.!?,;:`) → stop capture + emit `microphone.stop-request` (works without the wake word).
8. Non-echo non-empty → `microphone.activity`.
9. Wake gate: observe only if not echo and (gate not `waiting` or this is the latest utterance). Not accepted → finalize finals unless a candidate is pending; stop.
10. `wakeOnly` events stop here after a possible activation.
11. Barge-in check (VOX-11).
12. Non-final or already finalized → stop. Finalize (sets bounded to 64 entries, FIFO eviction). Echo → stop.
13. Emit `microphone.partial {sessionId, text, final:true, utterance, autoSend}` (the composer shows it; with `autoSend:false` it is copied into an empty input box).
14. Empty text → stop. Review-with-wake mode → `rearm(utterance)`. Normal mode: mic-off phrase → stop; *local stop* phrase `/^(stop|stop capri|stop talking|be quiet|quiet capri|стоп|хватит|замолчи)$/i` → rearm + emit `microphone.sent {localCommand:true}` (the barge-in already stopped speech) and stop; otherwise rearm (back to waiting after every accepted command).
15. If `canAutoSend = config.autoSend && (!review || reviewWake)` → reset follow-ups, append to a serialized submission tail: re-check `current()` (same capture, same `inputGeneration`, still auto-send) → `submit({id: uuidv4, text}, current)` (host waits for the running chat task, re-checks, then `submitMessage(value, 'microphone')`) → emit `microphone.sent {utterance}`. Failure while current → `fail('The spoken phrase could not be sent. Its text is shown above the input.')`.
- Renderer: a `microphone.partial`/`microphone.sent` for an utterance older than the last previewed one is ignored (a late result cannot overwrite the live draft).
#### VOX-11 — Barge-in (interrupt Capri by voice) · P1
Source: `microphone-service.mjs:9-10,230-238,462-472`; `main.mjs:1325-1329`.
- Enabled by `companion-asr.json → bargeIn` (default true); never in system-audio review mode; at most once per utterance (bounded set of 64).
- Triggers: a wake activation, or accepted addressed final text satisfying `/[\p{L}\p{N}]{3}/` or exactly `no|go|hi|ok`.
- Action: `chat.cancel()`, cancel visual turn, `voice.cancel()`; emit `microphone.interrupt` → renderer stops playback immediately and plays the attention animation.
#### VOX-12 — Echo suppression · P0 (text guard) / P1 (acoustic AEC)
Source: `microphone-service.mjs:26-57,378-388`; `renderer/microphone.mjs:255-267`; `renderer/app.js:568-608`.
- Acoustic echo cancellation is primary on Windows (Chromium AEC3 on its own output). The text guard only rejects obvious transcripts of Capri's own speech.
- Renderer reports `{sessionId, speaking, text}` at each sentence start/end and for wake-voice playback; host validates `speaking` bool and `text` ≤1200 chars (`'Invalid playback state'`), ignores other sessions.
- `EchoGuard(tailMs = max(1100, trailingSilenceSeconds×1000 + 1500))` (2.5 s at default pause; reconfigured with the pause). `playback()`: when the current sentence changes or stops, push it to history valid until `now + tailMs`; keep at most 2 history entries still valid.
- `matches(text)`: explicit stop commands (`stop|stop capri|wait|no|be quiet|stop listening`) are never echoes. Words = lowercased `[\p{L}\p{N}]+`. Echo if the heard word sequence is a contiguous sub-sequence of (history + current) words, or if heard ≥4 words and ≥85 % of them occur in Capri's words. A new EchoGuard is created at every stop.
- Rust/Linux: there is no browser AEC. Provide AEC in-process (far-end reference = the exact PCM sent to the speakers) or via PipeWire `module-echo-cancel` (§8). Keep the text guard unchanged.
#### VOX-13 — End-of-speech pause setting · P1
Source: `renderer/speech-settings.mjs:1-19`, `renderer/speech-panel.mjs`, `microphone-service.mjs:178-197`, `main.mjs:1106-1112,3228-3281,6154-6159`.
- `trailingSilenceSeconds` number in **[0.5, 5.0], step 0.1** (must be a multiple of 0.1 within 1e-8; stored rounded to 1 decimal), default from `config/companion-asr.json` (1.0). Object must have exactly this one key. Stored in `data/desktop/speech.json`.
- Applying: persist, then `configurePause` → update config, EchoGuard tail, and send `configure` to the live worker (no capture restart, no model reload; failure → `'The pause was saved. Enable the microphone again to apply it.'`). Emits `speech.settings`. Settings-window *preview* (unsaved slider) also reconfigures live.
- UI: slider + value formatted `{value} s` with one decimal; Reset restores 1.0 before Apply; save error → `'Microphone settings could not be saved.'`.
#### VOX-14 — Follow-up listening and "listen now" · P1
Source: `voice-follow-up.mjs:3-11`, `microphone-service.mjs:534-570`, `main.mjs:2268-2316,5908-5922,6160-6166`; `renderer/app.js:321-340`.
- Follow-up: after `turn.completed`, if companion `followUp` (default true) and the turn came from the microphone with the *same* active capture and the reply ends with `?`, `?` or `؟` (optionally followed by whitespace/closing punctuation/quotes) → pending follow-up `{turnId, sessionId, generated}` (`generated` is true immediately when voice is off/muted/errored). When `voice.generated` arrives for the turn and playback reports not busy (`capri:playback-state false`) → `continueListening(followUpSeconds×1000)` (`followUpSeconds` 5..30, default 12). Cancelled by `turn.started`, `voice.error`, `voice.cancelled`, typed input (`cancelContinuation` → rearm `'typed-input'`).
- `continueListening` requires `listening`, not review mode, `followUps < 3` (max three chained follow-ups; reset on any wake or submission), gate `waiting`; sets attention, emits `microphone.wake {followUp:true}`.
- Listen now (composer mic button / `capri:microphone-listen`): refused while installer busy; returns false if shutting down or backend not ready/asleep or review mode. If the gate is in `command` → rearm `'manual'` (toggle off). Else reset follow-ups; if wake enabled, `continueListening(30000)`; set attention; emit `microphone.wake {manual:true}`.
- Composer button: if command-listening → (wake disabled ? stop keep-warm : listen-now toggle); else unlock audio output, start capture if needed, then listen-now (or stop keep-warm when wake is disabled and it was already running).
#### VOX-15 — Wake feedback and wake sound · P1
Source: `renderer/wake-feedback.mjs:2-168`, `main/companion-ipc.mjs:31-157`, `companion-settings.mjs:14-19,52-56`, `main.mjs:2216-2228`.
- Visual: badge visible while listening with gate not `waiting` (`I'M LISTENING` / `SPEAK NOW`), plus a 900 ms acknowledgement after activation (`HEARD YOU` / `REQUEST RECEIVED`); body flags `data-command-listening`, `data-wake-burst=true` for 700 ms.
- Sound by `companion.wakeSound`: `tone` (default), `file`, `voice`, `off`; `wakeVolume` 0..1 (default 0.7). Tone = two sine partials on a bus of gain `0.085×volume`: (t=0, 740 Hz, 115 ms) and (t=85 ms, 1110 Hz, 140 ms), each with frequency exponential ramp to ×1.08, envelope linear 0→1 in 8 ms then exponential to 0.001 at the end, start offset 6 ms. `file` = user-imported audio (`capri:wake-import`: wav/mp3/ogg/flac/m4a, ≤4 MiB, copied to `data/desktop/wake-audio`), refused at play time if >10 s. `voice` = TTS of `wakePhrase ∈ {'Listening.', 'Yes, choom.', 'Mhm?'}` translated to the voice language, cached as `data/desktop/wake-voice-<first 20 hex of sha256(JSON{language,phrase,text,identity})>.pcm` (f32 24 kHz, size >0, ≤960 000 bytes, %4==0, regular file, not a symlink); prepared via `POST /synthesize` with `requestId 'wake:<uuid>'` (90 s timeout), written `wx` to a temp file then renamed; emits `wake.audio-ready`. A missing voice/file sample never silently falls back to the tone (feedback reports `unavailable`).
- Voice/file wake playback reports `{speaking:true, text}` / `{speaking:false}` to the echo guard.
- `restoreFromTrayOnWake` (default true): a genuine wake (not manual, not follow-up) shows the hidden companion window (window subsystem).
#### VOX-16 — Microphone status, diagnostics and UI states · P1
Source: `microphone-service.mjs:102-142`, `renderer/microphone-button.mjs`, `renderer/app.js:1679-1695`, `main.mjs:2229-2265`.
- `microphone.settings` snapshot: `{status, enabled, modelLoaded, sessionId, language, autoSend, sampleRate:16000, trailingSilenceSeconds, recognitionPhase:'idle'|'speech'|'processing', systemAudioReview, systemAudioWake, wakeState:'disabled'|'waiting'|'command', wakePhrase, available?, stoppedSessionId?}`.
- Diagnostics (bug report): `{language, wakeState, recognitionPhase, samples, lastRecognitionMs, meanRecognitionMs, lastAudioSeconds, trailingSilenceSeconds, lastFailure}` — no text.
- Labels: listening & waiting → `SAY CAPRI`; listening & processing → `TRANSCRIBING`; listening → `LISTENING`; enabled not yet listening → `STARTING`; else `TRANSCRIPT`; ticker shows last transcript or the language code.
- Buttons: `loading` while `starting|arming`; header enabled if capture/model loaded/loading; header disabled if unavailable or (not enabled and (not ready or backend not ready/asleep)); composer disabled while loading; `aria-busy` mirrors loading.
- Speech activity (`microphone.partial` with text, `.activity`, `.wake`) sets `lastSpeechUntil = now + 5 s` (suppresses initiative/avatar reactions) and cancels click reactions. Tray tooltip lists `Microphone (<language>)` while capturing.
- Turn context exposed to the LLM: `microphone`, `speechLanguage`, `wakePhrase`, `followUp` (see §9).
#### VOX-17 — System audio mixed into recognition (call/game context) · P2
Source: `system-audio-capture.mjs:1-68`, `renderer/microphone.mjs:115-210`, `microphone-service.mjs:283-301`, `main.mjs:1346-1351,5972-5975`.
- Requires an active `listening` capture. Grant `prepare(id, frame, wake)` lives **5 s**, single use, bound to the capture id and the companion main frame; consumed by the display-media request only with a user gesture; the forced video track is discarded unread.
- Mixing: loopback gain **0.4** and mic gain **0.6** while Capri is silent; during Capri playback and 0.4 s after it ends, loopback 0 / mic 1 (prevents Capri hearing itself).
- `enableSystemAudioReview(id, wake)`: `inputGeneration++` (revokes queued submissions), review on, follow-ups reset, wake timers closed. `wake=false` → attention forced on: every utterance becomes a *draft* (`autoSend:false`), no barge-in, no local commands. `wake=true` → gate re-enabled and rearmed (`'mixed-audio'`): addressed speech may auto-send, still no barge-in or mic-off commands. A `recognition-reset` in review-without-wake re-sends attention.
- Errors: `'System audio could not start. Microphone input is still active.'`; track ended → `'System audio stopped. Enable it again to reconnect.'`.
- Linux: capture `@DEFAULT_MONITOR@` (mono, 16 kHz) and mix in-process with the same gains; see §8 for own-audio exclusion.
### 2.2 Text-to-speech, playback, effects, subtitles
#### VOX-20 — Voice enable/mute and voice language · P0
Source: `voice-service.mjs:46-169`, `main.mjs:1077-1104,2136-2147,6196-6234`, `renderer/language-settings.mjs:32-93`.
- Voice output is **opt-in per desktop session**: `enabled=false` at every launch (no persisted preference outside verification). Speaker button → `capri:voice-enabled(bool)`: disabling cancels call voice and previews, then releases the muted sidecar (VOX-27); enabling when no voice is installed throws `'English voice is not installed. Open Languages and choose Install and enable. Capri downloads and installs everything automatically.'`, otherwise starts the sidecar (VOX-24).
- Voice language = resolved `speech` setting: `'follow'` → conversation language if it is one of the 23 speech languages (en ar zh da nl fi fr de el he hi it ja ko ms no pl pt ru es sw sv tr), else `'off'`; an explicit voice language must equal the conversation language (`'Choose a voice matching the conversation language, or Use conversation language.'`).
- `setLanguage(lang)`: non-speech language → `'Unsupported voice language'`; on change cancel the current turn and abort a pending prepare; emit `voice.settings`. On language change the host restarts the sidecar if the backend family differs (Turbo ↔ Multilingual ↔ Qwen, `voiceBackendChanged`), else calls `/prepare` on the running sidecar, or starts it.
- `voice.settings` event: `{enabled, ready: ready && language!=='off', language, error}`.
#### VOX-21 — Spoken-text sanitization and sentence segmentation · P0
Source: `renderer/speech-text.mjs:1-77`.
- `masked(text)`: replace fenced code blocks ` ```…``` ` (or to end) and every backtick by NUL of equal length (offsets stay stable while streaming).
- `spokenText(text)`: masked → NUL→space; remove `[voice:…]`, `[avatar:…]`, `[pose:…]` tags (case-insensitive); markdown links `[label](http…)` → label; remove bare `https?://\S+`; remove `* # _ ~` (words inside asterisks are kept); collapse whitespace; trim. Code is never read aloud.
- Sentence end regex (streaming): `(?:[.!?;…]+["”'’)\]}]*(?=\s)|[!?;。؟؛।॥]+["”'’)\]}」』]*)`; final variant also accepts end of text. Rules: a CJK/Arabic/Indic terminator at the very end of a non-final buffer waits for one more character (a closing quote may follow); a single `.` is *not* a boundary after `mr|mrs|ms|dr|prof|st|vs|etc|no` or a single capital letter, nor after a pure number (`3.`); `..`/`…` are boundaries. Commas and colons never split.
- `SentenceBuffer.push(text, final)`: skip leading blank/masked chars; emit each complete sentence as `spokenText(sentence)` (empty ones dropped); on `final` flush the remainder.
- `MAX_SPEECH_SENTENCE = 1200` characters (also the sidecar limit).
- English-only guard `speechLanguageMismatch(text, 'en')`: letters `\p{L}`; foreign = non-Latin-script letters; mismatch if `foreign ≥ 3 && foreign×4 ≥ letters`. Same rule in Python `voice_runtime/text.py` (`unicodedata.name` contains `LATIN`).
#### VOX-22 — Voice service: turn-scoped sentence queue and synthesis client · P0
Source: `voice-service.mjs:15-376`; `main.mjs:2289-2316` (`voice.onChat(event)` for every chat event).
- Constructor refuses any URL that is not `http://127.0.0.1:<port>` (`'Voice service must use loopback'`). Headers come from a callback (bearer token read from disk on each call).
- `beginTurn(turnId, preview)`: cancels the previous turn; if the service is in error and not ready → no turn; creates a turn only if `(enabled || preview) && language!=='off'`: `{id, language, controller, buffer, queue:[], final:false, sequence:0, segments:0, started, timing}`.
- `onChat`: `turn.started` → beginTurn. Events of other turns ignored. `turn.cancelled|turn.failed` → cancel. `turn.preface` (thinking briefing, chat-service) → once per turn, non-empty string ≤240 chars, queued first. `turn.delta|turn.completed` → push text (completed = final); any sentence >1200 chars → cancel + `voice.error 'This sentence is too long to read aloud. The full text is still available.'`; >100 sentences in a turn → cancel + `'This reply is too long to read aloud.'`.
- Text replies never wait for synthesis; sentences queued while the sidecar is still starting are spoken once `ready` (pump runs on `setReady(true)`).
- `pump()` (single runner): for each sentence: English guard → error code `SPEECH_LANGUAGE_MISMATCH`; `requestId = "<turnId>:<sequence>"`; `POST /synthesize {text, language, requestId}` with `redirect:error`, abort = turn controller ∪ 90 s timeout; **409 (busy) → retry every 50 ms until 90 s elapsed**; non-2xx → `voiceHttpFailure` (reads ≤4096 bytes only if JSON, keeps `code` only if in `{CAPRI_VOICE_SPEECH_LIMIT, CAPRI_VOICE_CUDA_OOM, CAPRI_VOICE_MODEL_MISSING, CAPRI_VOICE_INFERENCE_FAILED}`, never logs server text); require `content-type: application/octet-stream` and `x-sample-rate: 24000`; body ≤ **24000×4×45 = 4 320 000 bytes (45 s)**, non-empty, length %4==0; results for a cancelled/replaced turn are dropped. Emits `voice.timing {turnId, sequence, elapsedMs, requestMs, tokenMs:X-T3-Ms, decoderMs:X-Decoder-Ms}` and `voice.audio {turnId, sequence, text, sampleRate:24000, pcm:<base64 f32le>}` (sequence increments). When the queue is empty and the turn is final → `voice.generated {turnId}`.
- Synthesis error while current: record `lastFailure {at, phase:'synthesize', name, message, stack≤12000, code?, httpStatus?}`, cancel the turn (voice stays ready), emit `voice.error` with: SPEECH_LIMIT → `'This sentence could not be spoken. Voice is still ready.'`; LANGUAGE_MISMATCH → its message; else `'Capri’s voice is unavailable. Text replies are still available.'`.
- `cancel()`: abort, drop the turn, best-effort `POST /cancel {requestId}` (2 s timeout) if a request is in flight, emit `voice.cancelled {turnId}`. Called on mute, new turn, barge-in, `capri:cancel`, `capri:voice-stop`, language change.
- `prepareLanguage()`: `POST /prepare {language, requestId:"prepare:<lang>:<epochMs>"}`, 409 → retry every 100 ms, overall 600 s; errors → `voice.error` with `'Multilingual voice files are missing or damaged. Open Languages and install multilingual speech.'` (server `error:'model_missing'`) or `'The selected voice could not start. Text replies remain available. Check setup-multilingual.cmd.'`.
- `preview(turnId, text)`: requires ready and a language (`'No spoken voice is selected for this language.'`); works while muted; feeds `delta`+`completed`.
- `generating` = runner active or a turn not final / with queued sentences (used by reminders).
- Response-timing marks (other spec): `voice_text`, `voice_queued {cold}`, `voice_synthesis {speechCharacters}`, `voice_audio {requestMs, tokenMs, decoderMs}` on the first sentence.
#### VOX-23 — Voice runtime sidecar server (kept in Python) · P0
Source: `integrations/voice_runtime/server.py:1-260`, `model.py`, `multilingual.py`, `inference.py`, `failure.py`, `catalog.py`, `text.py`.
- Launch: `<venv>/python -m integrations.voice_runtime.server --language <lang> [--validate-turbo]`, cwd = install root. If `data/run/companion-voice.stop` exists at import time it exits immediately.
- Token: `data/speech/companion-voice-token` created on first run with `secrets.token_urlsafe(32)` (43 chars); the host reads it per request. Port from `config/companion-voice.json` (8101).
- Listens on `127.0.0.1:<port>` (ThreadingHTTPServer, socket timeout 10 s, request logging disabled). **Every** request (including `/health`) requires `Host` = `127.0.0.1:<port>` or `localhost:<port>`, **no `Origin` header** (else 403), and `Authorization: Bearer <token>` compared in constant time (else 401).
- `GET /health` → 200 JSON (§5.1). `POST /synthesize | /prepare | /cancel`: `Content-Length` 1..8192, no `Transfer-Encoding`, JSON body; `requestId` string ≤100; `/cancel` needs a non-empty id → `200 {"ok":true}`, sets the running request's cancel flag and remembers the id (≤128 ids, 120 s) so a later request with that id starts cancelled. `language` must be a speech language; `text` (default `'Hello.'` for `/prepare`) 1..1200 chars after trim, no NUL; invalid → 400.
- One inference at a time on a persistent single worker thread (the warm-up thread): second request → **409**. Cancelled → **499**. `MissingSpeechModel` → **503** `{error:'model_missing', code, component, file, reason}`; other failures → **503** `{error:'Voice generation failed', code}` with code `CAPRI_VOICE_SPEECH_LIMIT | CAPRI_VOICE_CUDA_OOM | CAPRI_VOICE_MODEL_MISSING | CAPRI_VOICE_INFERENCE_FAILED`; stdout logs only code/type and up to 6 frames `file:line function` (never text).
- `/synthesize` 200: body = mono **float32 LE @24 kHz**, headers `Content-Type: application/octet-stream`, `X-Sample-Rate: 24000`, `X-T3-Ms`, `X-Decoder-Ms`, `X-Synthesis-Ms`, `Cache-Control: no-store`. `/prepare` 200: `{ready:true, ...health}` after loading/switching the backend for that language.
- Stop: a thread polls `data/run/companion-voice.stop` every 250 ms; when present it cancels all active requests, shuts the server down and deletes the stop file. Startup failure writes `data/run/voice-startup-error.json` `{schemaVersion:1, pid, at(ms), code:'CAPRI_VOICE_COMMIT_LIMIT'|'CAPRI_VOICE_STARTUP_FAILED', errorClass, memory}` (commit-limit = Windows error 1455).
- Startup: CUDA preflight unless CPU (`compatibility.py`: real arithmetic/matmul check; Blackwell needs CUDA ≥12.8), load the selected backend directly, warm up once with a per-language greeting (`ru 'Привет.' zh '你好。' ja 'こんにちは。' ko '안녕하세요.' de 'Hallo.' fr 'Bonjour.' pt 'Olá.' es 'Hola.' it 'Ciao.'`, else `'Hello.'`), empty CUDA cache, print `Capri voice ready on loopback port <port>`; the port opens only after warm-up.
#### VOX-24 — Voice sidecar lifecycle (host side) · P0
Source: `integrations/voice_runtime/host.mjs:21-152`, `readiness.mjs`, `startup-error.mjs`, `environment.mjs`; `main.mjs:2080-2135`; `packages/runtime/src/host/processes.mjs:32-189`; `packages/runtime/src/hardware/model-devices.mjs:151-170`.
- `connectVoice()` returns the in-flight start or does nothing when: residency release pending (awaited first), voice not allowed, not enabled and no preview, installer/training/catalog busy, shutting down, sleeping/asleep, language off, already starting or ready. Not installed (`speechModelsInstalled`) → `voice.fail` with the English or `'Multilingual voice is not installed. Open Languages and install multilingual speech.'` message.
- `startCompanionVoice({language, signal, modelId?})`: language must be a speech language; `modelId` may only be `chatterbox-turbo` with `en` (training validation, adds `--validate-turbo`). Expected engine: `turbo | multilingual-v3 | qwen3-tts` from the per-language selection (VOX-26). Profile dir must be inside the root; reads `voice-profile.json`; interpreter must exist (`'Install the voice environment with setup-voice-training.cmd.'`).
- Restart triggers: managed marker with a different `deviceKey`; marker from an older private-log schema; health mismatch (`protocolVersion≠2`, `activeEngine`, `profile`, `adapterSha256`).
- Port ownership: `/health` (3 s timeout) answering 401/403 → `'Voice port belongs to another installation. Close its voice service before starting this one.'`; healthy but no managed marker → `'Voice port belongs to an unmanaged process.'`.
- Launch with env = runtime env (`ROCM_SDK_TARGET_FAMILY=custom` only when `.runtime/voice-runtime.json` profile is `amd`) + device env (`CAPRI_VOICE_COMPUTE_DEVICE=auto|cpu|cuda:0`, `CAPRI_VOICE_GPU_UUID`, `CUDA_VISIBLE_DEVICES` = GPU UUID/ordinal or `-1` for CPU, `HIP/ROCR/GPU_DEVICE_ORDINAL` masks) from `data/desktop/model-devices.json → voice`; marker `data/run/companion-voice.json {pid, startedAt, executable, args, projectRoot, privateLogSchema:1, deviceKey}`; stdout/stderr go to `/dev/null`, lifecycle lines only to `logs/companion-voice.{stdout,stderr}.log`.
- `waitForVoiceReady`: poll `/health` every 1 s, check the process every 5 s (`'The local voice process stopped during startup. See logs/companion-voice.stderr.log.'`), overall **600 s** (`'Voice model loading timed out…'`; cold loads can exceed 3 min). On failure a fresh `voice-startup-error.json` (same pid, `at ≥ startedAt`, ≤ now+10 s, <4096 bytes, regular file) with `CAPRI_VOICE_COMMIT_LIMIT` produces the specific memory message. Final check: `ready, protocolVersion 2, engine 'chatterbox-turbo', profile id, adapterSha256, activeEngine` must match (`'Running voice service does not match the selected profile. Restart Capri with stop.cmd.'`).
- Start errors: `lastVoiceFailure {at, phase:'startup', name, code, memory, message, stack}`; user message `'Capri’s voice could not start. Text replies are still available.'` (or the commit-limit text).
- Stop: graceful (write `data/run/companion-voice.stop`, wait ≤60 s for exit, verify by pid+start time). `stopVoiceForChange()` = abort start, close service, `setReady(false)`, await start, stop process. Used before catalog changes, training, speech installs and backend-family switches.
#### VOX-25 — TTS backends inside the sidecar · P0 (Turbo, English) / P1 (Multilingual v3) / P2 (Qwen3-TTS CPU beta)
Source: `voice_runtime/model.py`, `inference.py`, `cuda_graph.py`, `optimize.py`, `reference_memory.py`, `multilingual.py:96-274`, `qwen.py`, `qwen_provision.py`, `config/companion-voice.json`.
- `companion-voice.json` (+ optional `config/companion-voice.local.json` overriding only `profileDir`): `engine 'chatterbox-turbo'`, `port 1024..65535`, `precision 'float32'`, `cpuThreads 1..16` (effective `min(cfg, cpu_count, CAPRI_CPU_THREADS||16)`; startup may use up to 8 threads on ≥16-core GPU hosts), `maxSpeechTokens 100..1000` (800), `seed` (417), `decoderDevice auto|cpu|cuda:0`, `mergeAdapter` (true), `cudaGraph` (true).
- **Chatterbox Turbo (English, Capri LoRA)**: verifies profile engine/language/baseModel, adapter and reference SHA-256; loads the pinned Turbo model (`data/speech/chatterbox-turbo`, receipt-verified), applies the LoRA, folds it into FP32 weights (`mergeAdapter`), TF32 disabled; reference conditioning prepared once from `references/neutral.wav` and the reference encoders released (~0.49 GiB). Sampling: `temperature 0.8, top_p 0.95, top_k 1000, repetition_penalty 1.2, max_gen_len=maxSpeechTokens`, `torch.manual_seed(seed)` per phrase; reaching the token cap → `SpeechGenerationLimit`, retried **once** with native FP32 (graph bypassed) and seed+1. Tokens ≥6561 dropped, 3 silence tokens appended, flow decoder 2 steps (CPU noise), HiFiGAN, trim-fade, Perth watermark, 24 kHz output. Optional CUDA-graph token replay (capacity 1536, requires ≥768 MiB free, validated against eager forward, NVIDIA only).
- Decoder placement (`DecoderMemoryBudget`): `auto` keeps the acoustic decoder on GPU only with ≥2.5 GiB free and moves it to CPU below 1 GiB (re-check every 5 s, hold 30 s after a move, OOM → CPU and retry the phrase once); free memory = `min(cudaMemGetInfo, nvidia-smi memory.free of the selected UUID)`.
- **Chatterbox Multilingual v3** (non-English, reference-conditioned, no LoRA): `data/speech/chatterbox-multilingual-v3` (hash-verified), T3 in FP16 on GPU (FP32 on CPU), `exaggeration 0.5, cfg_weight 0.5, temperature 0.8, repetition_penalty 1.2`, token cap → `SpeechGenerationLimit`; Chinese segmentation (pkuseg) loaded lazily and verified only when switching to `zh`; output ≤45 s.
- **Qwen3-TTS 0.6B Base** (CPU by default, beta): `data/speech/qwen3-tts-0.6b-base`, voice clone prompt from the neutral reference (≤30 s, ≤2 channels, x-vector only), `seed 42, do_sample, temperature 0.7, repetition_penalty 1.2`, frame cap `min(480, maxSpeechTokens)` (12 frames/s ⇒ 40 s) and 120 s wall clock, resampled to 24 kHz (soxr); languages en zh ja ko de fr ru pt es it.
- `VoicePool`: exactly one backend resident; switching frees the previous one (gc + CUDA cache) after verifying the new weights; English guard before generation.
#### VOX-26 — Voice catalog and per-language model selection · P1 (P2 for Qwen install)
Source: `voice-catalog-service.mjs:20-301`, `config/tts-catalog.json`, `renderer/voice-model-panel.mjs`, `main.mjs:4975-4990`.
- Catalog models: `qwen3-tts-0.6b-base` (backend `qwen3-tts`, 10 languages, CPU/CUDA/ROCm, download 2 516 100 892 B, needs 8 GiB free, experimental), `chatterbox-turbo` (en, trained Capri adapter, fine-tunable), `chatterbox-multilingual-v3` (23 languages, Capri reference voice; `installLanguage 'ru'`).
- Selection file `data/speech/voice-selections.json`; defaults `en → chatterbox-turbo`, others → `chatterbox-multilingual-v3`. A saved selection must reference a model that supports the language (else error).
- `installed(model)`: profile `voice-profile.json` and the backend interpreter exist; Turbo additionally needs `data/speech/chatterbox-turbo/model-receipt.json`; Multilingual/Qwen need every manifest file with exact size.
- `select({language, modelId})`: not busy; model supports language and is installed; stop voice; write selection atomically; emit `voice-catalog.status`; host recomputes availability and reconnects voice if enabled.
- `install({modelId, language})`: Qwen only (Chatterbox models use the speech installer, VOX-34); needs the shared installer lock and `minimumFreeBytes`; stages `dependencies → models → ready` from JSON lines `{"stage","progress"}` mapped to `20 + p×0.8` %; 2 h timeout; errors `'Voice installation could not finish. Check free disk space and the network, then retry; partial downloads are retained.'`.
- UI: language select (speech languages), model select, details (`repository · Installed/Not installed · Fine-tuning supported/Capri reference voice · devices · ≈GB · required free space`), install/cancel/use buttons, CPU alternative button shown only after a `CAPRI_VOICE_GPU_UNSUPPORTED` install error when a Qwen model supports the language.
#### VOX-27 — Muted-voice residency (free VRAM when muted) · P1
Source: `voice-residency.mjs:5-47`; `main.mjs:2068-2079,1045,2458,2136-2147,6234`.
- `release()` is a no-op when disabled (verification), when voice is needed (`enabled && language≠off` or a preview pending) or not resident. Otherwise: cancel/close the service, await a starting sidecar, re-check `needed()` (an unmute or preview that wins the race keeps it), stop the process; `releases++`; errors kept as `{name, message≤500}` and rethrown; concurrent calls share one promise; `connectVoice` waits for a pending release.
- Called on mute, when the voice language becomes `off`, before each LLM turn (`prepareModel`) and before `connectBackend` — so a muted voice never holds GPU memory needed by the LLM.
#### VOX-28 — Voice preview · P1
Source: `main.mjs:6250-6271`, `language-context.mjs:27-51` (`VOICE_PREVIEWS`), `renderer/voice-effects-panel.mjs:170-182`.
- `capri:voice-preview(effects?)`: refused while a chat task, playback, synthesis or another preview runs (`'Wait for the current reply or preview to finish.'`); wakes the backend if asleep, starts voice (allowed while muted), emits `voice.preview-started {turnId, effects}` then `voice.preview(turnId, VOICE_PREVIEWS[language] ?? en)`. The renderer applies the preview effects only to that turn and restores saved effects afterwards. `capri:voice-stop` cancels previews and call speech.
#### VOX-29 — Voice player (PCM playback, ordering, playback events, level) · P0
Source: `renderer/voice-player.mjs:16-515`; `renderer/app.js:568-608,2432-2450`.
- Packets accepted only for the current turn and the **exact next sequence** (stale/out-of-order ignored); `sampleRate===24000`, base64 ≤6 000 000 chars, decoded length >0 and %4==0, every sample finite, queue <100 chunks; otherwise stop + error (`'Audio playback failed. Try unmuting Capri again.'`, renderer also calls `stopVoice`).
- Strictly sequential: one source at a time, next chunk starts on `ended`; the first chunk of a turn triggers a strong effects glitch burst.
- `begin(turnId, {call, effects})`, `finish(turnId)` (generation complete), `stop()` (immediate: stop sources, clear queue, reset effects, emit playback `stopped`).
- Playback events to subtitles: `started {turnId, sequence, text, durationMs = samples/24, startedAt, audioStartedAt}`, `ended`, `stopped`.
- Busy state: `busy:true, text` while playing; between chunks while generation continues `busy:true, waiting:true`; after the last chunk stays busy for the effects tail; then `busy:false`. Busy is forwarded to the host (`capri:playback-state`), the microphone echo guard (`speaking`, `outputBusy = busy && !waiting`) and the music client.
- `playbackElapsedMs` from the audio clock (`currentTime − audioStartedAt`), clamped to the chunk duration.
- `level`: RMS of the analyser time-domain buffer (FFT size 256, smoothing 0.7) of the active output; 0 when nothing plays.
- Output unlock: the audio output is resumed on user gestures (mic buttons, speaker button) to satisfy autoplay policies (Rust: not needed).
- Call output path: VOX-50.
#### VOX-30 — Voice effects DSP chain · P2 (off by default)
Source: `renderer/voice-effects.mjs:3-238`, `renderer/voice-effects-settings.mjs:2-105`, `renderer/voice-effects-panel.mjs`, `main.mjs:792-796,6235-6239`.
- Settings `{enabled, preset ∈ clean|cybernetic|radio|holographic|synthetic|custom, intensity 0..200, mix 0..100, reverb 0..200, delay 0..200, filter 0..200, glitch 0..200, electronicMix 0..100, carrierHz 20..200}` (integers after rounding; missing `electronicMix`/`carrierHz` take defaults 0/60). Defaults: clean, disabled, intensity 40, mix 25, others 0, carrier 60.
- Presets: cybernetic `{145, 68, 28, 35, 58, 122, 20, 48}`, radio `{92, 94, 0, 0, 151, 26, 0, 60}`, holographic `{48, 60, 160, 125, 16, 0, 0, 60}`, synthetic `{104, 87, 0, 0, 33, 0, 68, 84}` (order: intensity, mix, reverb, delay, filter, glitch, electronicMix, carrierHz; all `enabled:true`). Saved values exactly equal to an *old* factory preset (`previousPresets`, voice-effects-settings.mjs:74-79) upgrade to the new preset values; edited/custom values are kept.
- Graph (enabled): `input → dry → sum`; `input → highpass → lowpass → drive`; `drive → normal → wet`; `drive → ringmod(carrier sine) → robot → wet`; `drive → small room convolver → roomGain → wet`; `drive → large space convolver → spaceGain → wet`; `drive → delay → echoGain → wet` with `delay → feedback → delay`; `wet → sum → safety waveshaper y = 0.96·tanh(x/0.96) → analyser → output`. Disabled: `input → output`.
- Parameters with `ext(a)=max(0, a/100−1)`, `m=mix/100`: dry `1−m`; wet `0.85·m`; drive `1 + 0.25·intensity/100 + 0.75·ext(intensity)`; normal `1−electronicMix/100`; robot `electronicMix/100`; carrier `carrierHz`; roomGain `min(reverb/100,1)·0.35·(1−0.65·ext(reverb))`; spaceGain `0.9·ext(reverb)`; echoGain `0.24·min(delay/100,1) + 0.71·ext(delay)`; delay time `0.095 + 0.125·ext(delay)` s (max 0.25); feedback `0.42·ext(delay)`; highpass `25 + 4.2·min(filter,100) + 555·ext(filter)` Hz; lowpass `min(sr/2−100, 14000 − 110·min(filter,100) − 1600·ext(filter))` Hz. Changes glide with a one-pole target (τ = 8 ms) except on the first build.
- Impulses (procedural, deterministic): LCG `seed = seed·1664525 + 1013904223 mod 2³²` starting at 417, sample `(seed/2³¹ − 1)·exp(−i/(sr·τ))·0.025`; small room 0.32 s / τ 0.055 s; space 1.6 s / τ 0.3 s.
- Glitch: interval `((first?2:3) + 0.12·max(0,100−glitch)) / (1 + 7·ext(glitch))` s; while speaking a 150 ms timer fires `burst()` when due. `burst(strong)`, `a=intensity/100`, `b=ext(glitch)`: lowpass → `max(b?600:1800, base·(strong?0.45:0.7)/(1+2b))` (τ 3 ms) and back to base at `+ (strong?0.06:0.025)·a + 0.065·b` s (τ 9 ms); drive → `1 + a·(strong?0.65:0.4) + b·a` (τ 4 ms), back at `+0.045 + 0.065·b` s (τ 8 ms). Never gates words to silence.
- Tail: `0.36 + max(1.28·ext(reverb), 1.64·ext(delay))` s when enabled with reverb or delay, else 0.
- Panel: sliders save as `custom` (debounced 100 ms, serialized saves, last revision wins); preset select applies a preset; reset → defaults; preview button (VOX-28). Effects apply to playback only; the same settings are applied to the call output.
#### VOX-31 — Subtitles (reply pagination and voice-synchronized paging) · P0
Source: `renderer/subtitles.mjs:2-127`, `renderer/subtitle-controller.mjs:153-382`, `renderer/app.js:461-482`.
- `subtitleCues(text, limit, fits)`: `limit` integer 24..240; whitespace-collapsed code points; take ≤limit chars, shrink by binary search until `fits`; when not at the end break at the last space, preferring a space that follows `.!?…` located at ≥50 % of the limit; trim; content is never dropped (long unbroken words are split).
- `sentenceSubtitleCues(text, limit, fits, final)`: pack whole sentences (VOX-21 rule) into pages while they fit; a sentence too long for a page is split with `subtitleCues` (last fragment continues the next page); while streaming *and* following the voice, stop at the first unfinished sentence once a complete one exists.
- Controller: page width limit `max(48, min(144, floor(stageWidth/10)·3))` chars; `fits` = rendered text ≤3 lines at the element's font, width `clientWidth − 10`, letter-spacing included. New message → follow voice iff voice enabled, language ≠ off and the player's turn is this message's turn. `interrupted|error` pauses auto paging.
- Following voice: on playback `started`, locate the spoken sentence (`spokenText` coordinates) at or after the cursor (repeated sentences resolve forward); plan page changes within the chunk proportionally: `atMs = (cueStart − start)/(end − start) × durationMs`; schedule the next step (≥12 ms); on `ended` move to the sentence end; on `stopped` return to reading-time paging.
- Not following voice: auto-advance after `subtitleReadingMs(cue) = clamp(2200 + 48·chars, 3600, 11000)` ms measured from when the page appeared (reset on reveal).
- Status label: streaming → `REPLYING` (cue shown) or `THINKING…`; interrupted → `STOPPED`; error → `RESPONSE INCOMPLETE`. Controls hidden below 2 pages; `i / n`; manual prev/next pauses auto paging. Hidden companion: emit the cue (or first 144 chars) to the detached reply window without measuring.
#### VOX-32 — Mouth amplitude feed · P1
Source: `renderer/app.js:1482-1503`, consumer `renderer/avatar-mouth.mjs:185-212`.
- Every animation frame: `shape = visemes.sample(now, speaking && !sleeping, player.level)`. Shapes `closed|small|round|wide`: amplitude <0.006 (or not speaking) → `closed` immediately; otherwise update at most every 90 ms with `level = 0.25·level + 0.75·amp`; `wide` if level >0.075 (>0.055 when already wide), `round` if >0.03 (>0.022 when already round), else `small`. Detached avatar receives shape changes over IPC (`api.avatarMouth(shape)`). Amplitude animation only; no phoneme alignment.
#### VOX-33 — English voice language guard · P1
Covered by VOX-21/22: non-Latin replies are refused before synthesis in English (`SPEECH_LANGUAGE_MISMATCH`), text stays visible.
#### VOX-34 — Speech component installer · P0 on Linux (nothing speaks or listens without it)
Source: `speech-install-service.mjs:22-207`, `packages/installer/src/speech-components.mjs:23-329`, `tools/setup/*.ps1`, `logs/speech-install.log`.
- Selection `{speech: 'off'|speech language, recognition: 'off'|'auto'|'auto-europe'|language}`, not both off (`'Choose a supported voice or recognition language.'`). Refused while chat/visual turns, updates, model/HF/catalog/training/Spotify operations run; disabled in verification.
- Status `.runtime/installer/speech-status.json` `{phase: idle|installing|ready|error|cancelled|interrupted, stage, selection, progress, error, errorCode, currentFile, transferState: null|connecting|retrying, failedStage}`; a file left in `installing` loads as `interrupted`. Status survives renderer reconnects; `speech-install.status` events.
- Before: stop and unload mic worker and voice sidecar. After success: recompute voice/ASR availability, emit `speech-components {speechAvailability, recognitionAvailability}`.
- Stages: `checking` (skip work already installed; voice requires `voiceGpuSupported`: any NVIDIA GPU, or Windows 11 + listed Radeon models; else error `CAPRI_VOICE_GPU_UNSUPPORTED` with the fixed message; disk space preflight) → `python` (install pinned **uv**) → `recognition` (ASR venv + models) → `voice-pack` (validate/import the Capri reference voice pack; from local candidates or the GitHub release asset `capri-en-v1.zip`, ≤200 MiB, `sha256:` digest) → `voice-runtime` (git + voice venv; English also downloads Turbo weights) → `voice-models` (non-English multilingual weights) → `verify`.
- Progress: per-line messages; `NN%` parsed as progress; voice file names parsed from `Voice model file i/n: <name>`; `Connecting:`/`Download interrupted:` set `transferState`.
- Log `logs/speech-install.log`: JSON lines from an allowlist (`privateLogRecord`: stage/event/code only, no free text), truncated to its last 64 KiB when >2 MiB.
- Known errors shown verbatim (GPU unsupported, `Voice replies currently require…`, `Not enough free space…`, `GitHub access is unavailable…`, `The included Capri voice pack is unavailable…`, `Another installation process…`); otherwise `'Voice installation failed. Retry or save a diagnostic report.'`.
- **Why it fails on Linux today** (`logs/speech-install.log`: `{"stage":"python","event":"failure","code":"ENOENT"}`; status: selection `{speech:'fr', recognition:'fr'}`, `failedStage:'python'`): the GPU check passes (NVIDIA RTX 5070), `runtime('uv', '.runtime/uv/uv.exe')` downloads the pinned **Windows** uv zip (`.runtime/installer/downloads/a38b8d19….zip`, sha256 from `config/installer.json → artifacts.uv`), then `runCommand('powershell.exe', [... 'tools/setup/owned-speech.ps1', '-Component', 'archive', ...])` → `spawn powershell.exe ENOENT`. Even with PowerShell present every later step is Windows-only: `uv.exe`, `cpython-3.11.17-windows-x86_64-none`, `Scripts/python.exe` paths, the C# `SpeechOwner` guard (`Add-Type packages/installer/windows/speech-owner.cs`), Windows-only AMD wheels and a Windows-hashed Qwen lock. The Linux procedure is in §5.6.
#### VOX-35 — Voice training (summary) · P2
Source: `voice-training-service.mjs`, `integrations/voice_training/*`, `config/voice-training.json`.
- Optional English-only LoRA fine-tuning of Chatterbox Turbo on *reviewed* recordings (NVIDIA CUDA BF16, ≥5 GiB free VRAM). Import: folder with `metadata.csv` (`id,file,text,emotion,scene,split,approved`) and lossless `raw/*.wav|flac`, 4..200 approved clips, ≤300 s → `data/voices/capri/en/imports/<uuid>/` + `import-receipt.json`; selected dataset written to `config/voice-training.local.json`. Job: `<voice venv>/python -m integrations.voice_training.job --job <uuid>` (stdout JSON lines `{"stage": checking|preparing|caching|training|previewing|review|no-improvement|failed, epoch?, epochs?}`, 4 h timeout, single-job lock `.runtime/voice-training-job.lock {pid}`), output `data/speech/training-jobs/<uuid>/{candidate.json, preview.wav}` and an exported profile `…/exports/capri-trained-<uuid>/`. The user must listen (`preview.wav` ≤12 MiB RIFF/WAVE) before `apply`, which writes `config/companion-voice.local.json` and the `en` selection, validates by starting Turbo, and rolls both files back on failure. Status persisted in `data/speech/voice-training-status.json`. Keep as-is in the Python sidecar venv; port only the orchestration if training is kept.
### 2.3 Music listening (system-audio music/BPM detection)
#### VOX-40 — Music listening session and consent · P2 (off by default)
Source: `music-listening-service.mjs:77-330`, `music-listening-settings.mjs`, `music-audio-capture.mjs`, `renderer/music-listening-panel.mjs`, `renderer/app.js:120-144`, `main.mjs:875-880,1352-1395,5976-6026`.
- Purpose: react visually (music poses, floating notes, beat-synchronized motion) when *system playback* contains music. Independent of the microphone, ASR, screen observation and conversation; audio is never transcribed, stored, logged or sent anywhere.
- Capture starts **only from an explicit owner action**: companion music button, Settings → Music listening "Start music listening", or ticking "Music animations" (which also starts capture). Saved preferences never restart capture after relaunch. Settings-originated commands require role `settings` and a visible settings window; 15 s timeout (`'Music listening could not start. Try again from Settings.'`).
- Availability (`musicAvailable`): Windows only today; not session-locked, not shutting down, power phase `awake`, companion window alive with the expected URL. Loss of availability stops the session; sleep and lock stop it.
- Host phases: `off → preparing (download/verify detector, spawn worker) → starting (worker ready, capture not yet confirmed) → listening`; `error` with `'Music listening stopped. Enable it again to retry.'`. `start()` returns `{sessionId:uuid, sampleRate:16000}` immediately; renderer confirms capture with `musicAudioReady(id)`.
- Worker spawn: `<python> -u -m integrations.music_runtime.worker --model-dir <data/models/music-detector/<id>>`, cwd root, env allowlist + `PYTHONUTF8=1 PYTHONIOENCODING=utf-8 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1`; `ready` must arrive within **20 s**; stdout buffer >16 384 chars or any invalid line (including a worker `error` line) → fail. Interpreter: `router-venv` else `asr-venv` (none → `'Music listening is unavailable. Run Capri Setup again.'`). In Rust this worker is replaced by native code (§10) but the semantics stay.
- Snapshot / `music.status`: `{phase, enabled, supported, hearingMusic, energy, musicScore, speechScore, tempo, tempoConfidence, beatAt, settings, progress?, error}`; when the "Music animations" setting is off, `hearingMusic`, `tempo`, `tempoConfidence`, `beatAt` report 0/false. The host forwards `{enabled, hearingMusic, energy, tempo, tempoConfidence, beatAt, notes, motion, autoBpm}` to the detached avatar and refreshes the seated frame when `musicAnimationReady` flips.
- Settings `data/desktop/music-listening.json`: `{enabled:false, notes:true, motion:true, autoBpm:true}` (`autoBpm` optional on read); a grant or PCM is never persisted.
- Panel label: unsupported/error → `Unavailable`; `sleeping|paused|locked` → `Paused`; preparing/loading/downloading → `Preparing music detection…`; starting/arming/connecting → `Connecting system audio…`; music → `Music detected · BPM <n|…>`; capture active with speech ≥0.6 and music <0.5 → `Speech detected`; active → `Listening`; else `Off`.
#### VOX-41 — System-playback capture for music · P2
Source: `renderer/system-music-capture.mjs:1-211`, `renderer/music-worklet.mjs:1-38`, `music-audio-capture.mjs:6-79`.
- Windows: one-shot 5 s grant bound to the session id and companion frame, consumed by `getDisplayMedia({audio:{restrictOwnAudio:true, suppressLocalAudioPlayback:false}, systemAudio:'include', video:{frameRate:{max:1}}})` with a user gesture; the video track is stopped unread; exactly one live audio track required. AudioContext 16 kHz with no output device (`sinkId {type:'none'}`), latency `playback`.
- Worklet `capri-music-pcm`: 2-channel input; picks the **channel with the highest energy** per render quantum (preserves anti-phase/one-sided stereo), resamples with `PCMFramer` to 16 kHz, emits **8000-sample (0.5 s, 32 000-byte) f32 packets** with the audio-clock capture time.
- Delivery: `capturedAt = Date.now() − clamp(context.currentTime − capturedTime, 0, 30 s)`; at most **one pending packet** (newest replaces older: no backlog replay); while Capri plays audio and for **400 ms** after it, packets are dropped (own-speech suppression); `{stop|revoked}` receipt stops capture; track end → `'System audio stopped. Enable it again to reconnect.'`.
- Host packet validation (`music-listening-service.mjs:251-307`): only keys `sessionId, sequence, pcm, capturedAt`; `sequence` strictly increasing safe integer; exactly 32 000 bytes; `capturedAt` finite ≥0. A sequence gap resets the tempo state (`tempoStartSequence`). Packets older than 5 s or >1 s in the future, or arriving before capture confirmation/worker ready, or when the worker stdin backlog exceeds **128 KiB**, are not accepted and reset tempo. Submitted capture times are tracked for ≤64 sequences.
- Linux replacement: read `@DEFAULT_MONITOR@` stereo f32 at 16 kHz (§8), same channel selection, packetization, gating and freshness rules.
#### VOX-42 — Music classifier (YAMNet) · P2
Source: `integrations/music_runtime/worker.py`, `features.py`, `config/music-detector.json`.
- Model: Qualcomm YAMNet ONNX float export v0.61.0 (`yamnet.onnx` + external weights `yamnet.data`, `labels.txt` (521 lines), `metadata.json`), input `audio` shape `[1,1,96,64]`, outputs 521 **logits** → probabilities via `1/(1+exp(−clip(x,−60,60)))`. Classes used: `music` (132), `speech` (0), `singing` (24); labels at those indices must read exactly `music`, `speech`, `singing`. CPU, 1 intra/inter-op thread.
- Front end (must match bit-for-bit within float tolerance): last 16 000 samples of the window (zero-padded at the end if shorter), clipped; reflect-pad 256 each side; frames of 512 with hop 160; window = **periodic** Hann(400) zero-padded 56 on each side to 512; `|rfft|`; 64 HTK-mel triangular filters from 125 to 7500 Hz over 257 bins (mel = 2595·log10(1+f/700), 66 edges linearly spaced in mel); `log(mel + 0.001)`; first 96 frames.
- Streaming: window keeps the last **48 000 samples (3 s)**; inference every **16 000 new samples (1 s)**; `rms` over the window (float64); if `rms < 0.0003` scores are all zero (no inference). Output = mean of the last **3** score vectors. Session/sequence change (`sessionId` regex `[A-Za-z0-9_-]{1,80}`, `sequence` must be previous+1) resets audio, scores and tempo.
- Protocol: §5.3.
#### VOX-43 — Tempo (BPM) and beat-phase tracker · P2
Source: `integrations/music_runtime/tempo.py:17-228` (port exactly; constants matter).
- Onset novelty: 16 kHz, FFT 512 with **symmetric** `np.hanning(512)`, hop 160 (10 ms), magnitude bins 1..240; positive spectral flux vs the previous frame; novelty = `0.45·mean(bins 1–8) + 0.35·mean(bins 9–64) + 0.20·mean(bins 65–240)`; onset time = `(frameStart + 256)/16000`; history 1200 frames (12 s); leftover samples carried between packets so chunk size does not change results.
- `estimate(music)`: if the classifier gate is false (`mean music ≥ 0.6` and `rms ≥ 0.0003` not met) → unknown; 3 consecutive non-music windows reset the tracker. Requires ≥300 onsets (3 s); uses the last 800 (8 s).
- Envelope: subtract a 21-tap moving average (edge-padded), clamp ≥0, smooth `[0.25, 0.5, 0.25]`; peak <0.005 → unknown; peaks = local maxima ≥18 % of max; <5 peaks → unknown.
- Candidates: normalized autocorrelation of the mean-centered envelope for lags 25..150 frames (240..40 BPM; a lag needs `3·lag < length`); keep local maxima with correlation ≥0.35; parabolic sub-frame refinement (clamped ±0.5); harmonic support `Σ max(0,corr(k·lag))·w_k / Σ w_k` with `(k,w) = (1,0.6),(2,0.25),(3,0.15)`; phase support from a 64-point phase grid with Gaussian kernels σ = 0.075 weighted by peak heights; score = `support − 0.065·lag/150 + 0.4·phaseSupport`.
- Primitive period preference: for the best candidate, any other candidate whose lag divides it (`ratio ∈ (1.8, 4.2)`, `|ratio − round(ratio)| < 0.045`) with score ≥ best − 0.08 and direct correlation ≥ 0.86·best wins. `bpm = clamp(6000/lag, 40, 240)`.
- Octave hysteresis: with a locked tempo, a new estimate at ≈2× (±0.06) or ≈0.5× (±0.025) keeps the old tempo when the old lag's correlation ≥ 0.88·new and its phase support ≥ max(0.35, 0.85·new).
- Confidence = `clamp(0.65·direct + 0.35·coherence, 0, 1)`; reject if coherence <0.35 or confidence <0.53, or if the last peak is older than 2.2 periods. Two consecutive estimates within 3.5 % are required before reporting; within 2.5 % of the locked tempo it is smoothed `0.6·locked + 0.4·new`.
- Output `{tempo (3 decimals), tempoConfidence, beatPhase ∈ [0, 0.999999]}` with phase computed at the latest packet end; unknown = all zeros.
#### VOX-44 — Music decision, hysteresis and beat clock · P2
Source: `music-listening-service.mjs:7-74,197-242`, `music-listening-settings.mjs:9-25`.
- Result acceptance: must be `classification` for the current session, after capture confirmation, with `lastResult < sequence ≤ lastSubmitted` and a known submitted sequence; anything else is fatal. Older submitted entries are pruned. A result whose capture time is >5 s old resets the decision (stale). A 5 s stale timer resets the decision if results stop.
- Validation: `music, speech, rms` finite in [0,1]; tempo 0 or 40..240; confidence/phase in range; tempo 0 ⇒ confidence 0 and phase 0.
- Hysteresis: `energy = min(1, 6·rms)`; enter counter increments when `music ≥ 0.60 && rms ≥ 0.0003` else resets; exit counter increments when `music < 0.28 || rms < 0.0003` else resets; enter music after **3** consecutive, leave after **3** consecutive.
- Beat: a tempo with confidence ≥ **0.45** (`MUSIC_TEMPO_MIN_CONFIDENCE`) yields `beatAt = capturedAt − phase·60000/tempo` (ms epoch). Before the gate opens a reliable beat is kept privately as `pendingTempo` (only while the enter counter >0) and published on the first music decision; afterwards the last reliable beat is held through uncertain windows; sequence gaps or late packets clear it.
- `musicAnimationReady(snapshot)` = enabled session, hearing music, settings enabled, tempo in [40,240], confidence in [0.45,1] (no motionless music pose while the BPM is warming up). Visual consumer (`renderer/music-animation.mjs`, avatar spec): `autoBpm:false` uses a fixed 110 BPM.
#### VOX-45 — Music detector provisioning · P2
Source: `music-detector-provision.mjs:18-134`, `integrations/music_runtime/extract.ps1`.
- Manifest checks: schemaVersion 1, id `yamnet-…`, sampleRate 16000, packetSamples 8000, exactly the 4 file names, each ≤20 MiB with SHA-256.
- Installed if all 4 files in `data/models/music-detector/<id>/` match size+hash (no symlinks). Otherwise resumable download of the zip (≤32 MiB; URL must be exactly `https://qaihub-public-assets.s3.us-west-2.amazonaws.com/qai-hub-models/models/yamnet/releases/v<ver>/yamnet-onnx-float.zip`, no credentials/query/fragment, archive SHA-256 pinned) into `.runtime/music-detector/`, extraction of only `yamnet-onnx-float/{yamnet.onnx,yamnet.data,labels.txt,metadata.json}` (each ≤20 MiB, no duplicates, all required) into a fresh `verified-*` temp dir, re-verify, copy each file to `<dest>.<uuid>.tmp` then rename, verify again. Windows extraction uses PowerShell (30 s timeout) → Rust `zip` crate.
#### VOX-46 — Music artwork pack · P2
Source: `music-artwork.mjs:1-162`; files in `assets/default/capri-music-v1/`.
- `runtime-music.json` (≤16 KiB, exact keys) lists 2 frames (`music-window` → `capri-music-window.png`, anchor `seat`, pose `music_seat`; `music-floor` → `capri-music-floor.png`, anchor `ground`, pose `music_ground`) each 1254×1254 RGBA PNG (color type 6), plus 4 notes `01-eighth-cyan, 02-beamed-lime, 03-quarter-pink, 04-sixteenth-violet` 256×256; every PNG checked by signature, IHDR size, color type and SHA-256; files must be regular, ≤20 MiB, not linked, inside the real pack directory. Optional on old installs (empty pack), required when building sources. Frames are exposed as `kind:'reviewed_music'`, `expression:'happy'`, `canPersist:false`. Consumed by the avatar spec.
### 2.4 Call audio (Capri's voice into voice calls)
#### VOX-50 — Call output (virtual microphone for call apps) · P2
Source: `renderer/voice-player.mjs:92-306,431-514`, `main/call-audio.mjs`, `main.mjs:1396-1488,6027-6075`, `renderer/settings-app.mjs:496-700`.
- Goal: route Capri's speech (and optionally the owner's physical microphone) into a call app through a virtual audio cable, while still hearing Capri locally.
- Commands (Settings → Voice calls, role `settings`, settings window visible, `callAudioAvailable`): `state`, `output-on {deviceId, mixMic}`, `output-off`, `share-replies {enabled}`, `allow-model {enabled}`, `voice-volume {volume 0..100 int}`, `system-on {wakeFromSystem}`, `system-off` (VOX-17). Strict key validation (`callAudioCommand`). `allow-model`/`voice-volume` persist to `data/desktop/call-audio.json` and emit `call-audio.policy`; disabling `allowModel` cancels pending model-chosen call speech. Other commands run in the companion renderer with a **15 s** timeout; a failed `*-on` triggers the matching `*-off`.
- Output device list: audio outputs with specific ids (not `default`/`communications`, no control chars, ≤512), label cleaned ≤180, **Steam Streaming endpoints excluded**; device groups only for the companion role; listing has a 2.5 s timeout; non-settings callers get `[]` unless an output is being enabled or is ready.
- `output-on`: host injects the saved physical mic id; `CallMicrophone.start` (VOX-51) if `mixMic`; `enableCallOutput(deviceId, micStream)`: device must still exist and not be Steam Streaming; mic must be live and not look virtual (`stereo mix|what u hear|cable output|loopback|steam streaming microphone`); if mic and sink share a hardware group → require `isVerifiedSeparateCallCable` (fresh enumeration; unique `CABLE[-X] Input` sink and `CABLE[-X] Output` source, different from the mic) else `'Use a call cable separate from your microphone.'`. Creates an output context bound to the sink at creation, mono destination; with mic: `mic → DynamicsCompressor(threshold −6 dB, knee 12, ratio 4, attack 3 ms, release 60 ms) → sink`; voice: `effects → analyser → voiceGain(callVoiceVolume/100) → mixer|sink`. Must be running. Sets `shareReplies=true` (enabling the call output starts a session of shared replies). Watches device changes / sink changes / mic `ended` → lose output.
- Playback when sharing: reply turns begin on the call output; each chunk is also **mirrored** to the local speakers (same buffer, 10 ms lead) so the owner hears Capri; previews stay local. Volume changes ramp over 20 ms. Turning sharing off stops a shared reply in progress.
- State published to host (`capri:call-audio-state`, validated by `callAudioState`): `{systemAudioActive, systemAudioPending, systemAudioReview, systemAudioWake, micListening, callOutputReady, mixingMic, shareReplies, deviceId}`; host snapshot adds `allowModel, callVoiceVolume (default 50), supported`.
- Errors surfaced: `'Choose a specific call output device.'`, `'Call audio output is unavailable.'`, `'A virtual audio cable is needed. Install VB-CABLE to continue.'`, `'The selected microphone is unavailable. Choose a device in Menu → Microphone input.'`, `'Call audio requires an open Capri window.'`, `'Call audio output is already being set up.'`.
- Reset (`call-audio.reset`) on sleep, lock, minimize/close, shutdown: stop call mic, disable output, stop system audio.
#### VOX-51 — Call microphone (physical input only) · P2
Source: `renderer/call-microphone.mjs:4-220`.
- Physical inputs: `audioinput`, specific id, non-empty label not matching `/\b(?:cable(?:[ -]?[a-d])?\s+(?:input|output)|vb[ -]?audio|voicemeeter|steam streaming|loopback|stereo mix|what u hear|wave out mix|virtual|obs[ -]?audio)\b/i`.
- Selection: saved device (must be physical and present, else `'The selected microphone is unavailable. Choose a connected physical microphone in Microphone settings.'`) → physical device in the same group as the OS default → first physical input → error `'No physical microphone is available…'`.
- Reuse the live ASR track only if it is that exact physical device, single track, sample rate ≥44 100 Hz; otherwise open a separate exact capture with `sampleRate ideal 48000`, mono, AEC on, NS off, AGC off (never retune the ASR track). Granted track must match the selected device and be physical.
- 10 s timeout, generation-based cancellation (late grants are stopped), loss on track end / device change / retargeted default → output disabled once.
#### VOX-52 — Virtual cable setup · P2
Source: `call-audio-setup.mjs:1-200`, `virtual-cable-installer.mjs:1-189`, `integrations/call-audio/CableDefaults.cs`.
- Windows: detect a VB-CABLE family (`''`, `-A`..`-D`) with exactly one matching playback `CABLE<f> Input` and recording `CABLE<f> Output`; "Set up automatically" connects it (`output-on` with mic mixing) without installing; a missing cable requires a separate explicit **consented** install: pinned `VBCABLE_Driver_Pack45.zip` (≤2 MiB, SHA-256 `b950e39f…16bfb`), UAC-elevated staging in an admin-only directory, Authenticode signer `BUREL VINCENT`, silent `-i -h`, restores the owner's default endpoints afterwards, never reboots; polls 10×500 ms for new endpoints, else phase `reboot`. Exit codes 20 (UAC cancelled) 21 (download) 22 (hash) 23 (publisher) 24 (other).
- Phases `idle|checking|missing|downloading|installing|reboot|connecting|ready|error`; diagnostics use a fixed failure vocabulary (`feedback-loop, microphone-unavailable, microphone-permission, microphone-invalid, device-list-failed, output-unavailable, cable-required, setup-unavailable, install-failed, timeout, cancelled, unknown`).
- Linux replacement (§8): no driver; create a PulseAudio/PipeWire null sink + remapped source on explicit consent, non-persistent, no root.
#### VOX-53 — Speak in call / Ask Capri in call · P2
Source: `main.mjs:6076-6143`, `call-response.mjs:1-87`, `renderer/app.js:520-552`.
- Companion buttons: *Speak in call* (input text), *Speak last reply* (last complete assistant message), *Ask Capri in call* (model decides the route; requires `allowModel` and no pending attachments). Request `{id: uuid, text, model?}` (`validateInput`: 1..MAX_INPUT chars, no NUL).
- Preconditions: model use allowed (`'Enable model-selected replies in Voice calls first.'`), call output ready (`'Enable a call output in Voice calls first.'`), voice enabled (else `voice.warning 'Enable Capri’s voice first.'` and `false`), no chat/playback/synthesis/preview (`'Wait for the current reply or preview to finish.'`), awake and backend ready (`'The local core is not ready yet.'`).
- Model route: one isolated Ollama `/api/chat` request (no history, no tools; §5.5, §6) within **20 s**, returning `{route: 'owner'|'owner-and-call', reply ≤420}`; failure → `'Capri could not determine a safe call reply.'`. Plain text route = `owner-and-call` with the typed text.
- Then start voice, emit `voice.call-started {turnId:id, route, reply?}` and `voice.preview(id, reply)`; the renderer begins the turn on the call output only for `owner-and-call` (else local only) and shows the model reply as a notice.
#### VOX-54 — Call audio diagnostics · P2
Source: `main/call-audio-diagnostics.mjs:1-98`.
- One volatile, text-free receipt for the latest speech request: booleans `requested, explicit, model, toCall, toOwner, started, audioGenerated, generationCompleted, playbackReported, playbackEnded, cancelled, failed, rejected`, updated from `voice.call-started`, `voice.audio`, `voice.generated`, `voice.cancelled` and playback busy reports (playback is a renderer report, not proof of audibility); stale ids ignored. Snapshot adds `supported, outputReady, mixingMic, allowModel, shareReplies, voiceEnabled, setup` (bounded vocabulary). Included in bug reports.
---
## 3. Data and persistence
Write rule used everywhere (`packages/runtime/src/atomic-json.mjs:13-32`): create parent dirs, write `<file>.<pid>.<uuid>.tmp` with `O_EXCL` and mode `0600`, `fsync`, `rename` over the target, delete the temp on failure. Python sidecars use `<file>.tmp` + `replace`. Path-safety rule (`noLinks`/`no_links`/`voiceDataPath`): every voice/speech/model path must resolve inside the install root and no component may be a symlink (reject, do not follow). `Preferences` files are `{schemaVersion:1, settings:{…}}`, ≤16 KiB; an invalid file falls back to defaults with a warning and is only overwritten by an explicit change.
| Path (install root) | Owner | Format / schema | Synthetic example | Rules |
|---|---|---|---|---|
| `data/desktop/speech.json` | VOX-13 | Preferences: `settings.trailingSilenceSeconds` | `{"schemaVersion":1,"settings":{"trailingSilenceSeconds":1.4}}` | atomic; validated 0.5..5 step 0.1 |
| `data/desktop/microphone.json` | VOX-04 | `{schemaVersion:1, deviceId, deviceLabel}` (no `settings` wrapper; `''` = default) | `{"schemaVersion":1,"deviceId":"alsa_input.usb-Example_Mic-00.mono-fallback","deviceLabel":"Example USB Mic"}` | atomic; written only on explicit selection; unreadable file kept untouched |
| `data/desktop/voice-effects.json` | VOX-30 | Preferences: effects object | `{"schemaVersion":1,"settings":{"enabled":true,"preset":"radio","intensity":92,"mix":94,"reverb":0,"delay":0,"filter":151,"glitch":26,"electronicMix":0,"carrierHz":60}}` | atomic |
| `data/desktop/music-listening.json` | VOX-40 | Preferences `{enabled,notes,motion,autoBpm}` | `{"schemaVersion":1,"settings":{"enabled":false,"notes":true,"motion":true,"autoBpm":true}}` | never stores grants/PCM |
| `data/desktop/call-audio.json` | VOX-50 | Preferences `{allowModel:bool, callVoiceVolume:0..100}` | `{"schemaVersion":1,"settings":{"allowModel":false,"callVoiceVolume":50}}` | default allowModel false |
| `data/desktop/companion.json` (read) | VOX-14/15 | companion Preferences; keys used here: `wakeSound`, `wakePhrase`, `wakeVolume`, `followUp`, `followUpSeconds`, `restoreFromTrayOnWake`, `wakeOnReminder` | see §4 | owned by companion spec |
| `data/desktop/languages.json` (read) | VOX-07/20 | `{interface, conversation, customConversation, recognition, speech, autoDetect}` | `{"schemaVersion":1,"settings":{"interface":"en","conversation":"fr","customConversation":"","recognition":"follow","speech":"follow","autoDetect":false}}` | owned by language spec |
| `data/desktop/model-devices.json` (read) | VOX-24 | `{schemaVersion:1, language, voice}` ids `auto|cpu|(cuda|rocm|vulkan):N:<16 hex>` | `{"schemaVersion":1,"language":"auto","voice":"auto"}` | single link, ≤4096 B |
| `data/desktop/wake-audio` | VOX-15 | user audio file (wav/mp3/ogg/flac/m4a), ≤4 MiB | — | copied on import |
| `data/desktop/wake-voice-<20 hex>.pcm` | VOX-15 | raw f32 LE mono 24 kHz, ≤960 000 B | — | `wx` temp + rename; regenerated when phrase/language/voice identity changes |
| `data/desktop/voice.json` | verification only | `{enabled}` | — | ignored in production |
| `data/speech/voice-selections.json` | VOX-26 | `{schemaVersion:1, languages:{<lang>:<modelId>}}` | `{"schemaVersion":1,"languages":{"en":"chatterbox-turbo","fr":"chatterbox-multilingual-v3"}}` | atomic; ≤64 KiB; no symlinks; every entry must support its language |
| `data/speech/companion-voice-token` | VOX-23 | 43-char URL-safe random token, UTF-8, no newline | `q4Zx…` (synthetic) | created by the sidecar; secret: never sent to UI, never logged |
| `data/speech/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8/` | VOX-07 | `encoder.int8.onnx, decoder.int8.onnx, joiner.int8.onnx, tokens.txt, ATTRIBUTION.txt` | sizes/hashes: `config/asr-model-upstream.json` | verified at load |
| `data/speech/candidates/parakeet-tdt-v3-int8/` | VOX-07 | same 4 files (v3) + attribution | `config/multilingual-candidates.json → asr` | |
| `data/speech/silero-vad-v5/` | VOX-06 | `silero_vad.onnx`, `ATTRIBUTION.txt`, `LICENSE.txt` (MIT text) | `config/asr-vad-upstream.json` | |
| `data/speech/faster-whisper-large-v3-turbo/` | VOX-07 | CTranslate2 model (`model.bin` 1.6 GB, configs, tokenizer, vocabulary) | `config/multilingual-runtime.json → whisper` | |
| `data/speech/chatterbox-turbo/` | VOX-25 | 10 Turbo files + `model-receipt.json {upstream:<voice-upstream.json>, files:{name:sha256}}` | `config/voice-upstream.json`, `config/voice-model-download.json` | receipt must deep-equal upstream |
| `data/speech/chatterbox-multilingual-v3/` | VOX-25 | `t3_mtl23ls_v3.safetensors, s3gen.pt, ve.pt, grapheme_mtl_merged_expanded_v1.json, Cangjie5_TC.json` | `config/multilingual-runtime.json → tts` (may be hard-linked from `candidates/chatterbox-multilingual-v2` when hashes match) | |
| `data/speech/pkuseg/spacy_ontonotes/` | VOX-25 (zh) | `features.msgpack, weights.npz` from a pinned zip | `config/multilingual-runtime.json → chinese` | |
| `data/speech/qwen3-tts-0.6b-base/` | VOX-25 | 11 files incl. `speech_tokenizer/` | `config/qwen-tts-upstream.json` | |
| `data/speech/hf-cache/`, `data/speech/torch-cache/` | sidecar | HF_HOME / TORCH_HOME (offline) | — | |
| `data/speech/voice-training-status.json` | VOX-35 | `{phase, stage, jobId, error, epoch, epochs}` | `{"phase":"review","stage":null,"jobId":"0f1e2d3c-…","error":null,"epoch":null,"epochs":null}` | |
| `data/speech/training-jobs/<uuid>/` | VOX-35 | `candidate.json {schemaVersion:1, jobId, modelId:'chatterbox-turbo', language:'en', profileDir, preview:'preview.wav', quality:'requires-listening'}`, `preview.wav` | — | |
| `data/voices/capri/en/exports/<id>/` | VOX-24/25 | `voice-profile.json`, `adapter.json`, `adapter.safetensors`, `references/<style>.wav` | see below | imported with `COPYFILE_EXCL`; checksums |
| `data/voices/capri/en/imports/<uuid>/` | VOX-35 | imported dataset + `import-receipt.json {schemaVersion:1, importId, reviewed:true, clips 4..200, seconds ≤300}` | — | |
| `data/run/companion-voice.json` | VOX-24 | process marker `{pid, startedAt (/proc start ticks), executable, args, projectRoot, privateLogSchema:1, deviceKey}` | — | atomic |
| `data/run/companion-voice.stop` | VOX-23/24 | presence = graceful stop request (`"stop\n"`) | — | launcher deletes stale file before spawn; sidecar deletes after stopping |
| `data/run/voice-startup-error.json` | VOX-23/24 | `{schemaVersion:1, pid, at, code, errorClass, memory}` | `{"schemaVersion":1,"pid":4242,"at":1767000000000,"code":"CAPRI_VOICE_STARTUP_FAILED","errorClass":"RuntimeError","memory":null}` | <4096 B, regular file |
| `data/models/music-detector/yamnet-qualcomm-v0.61.0/` | VOX-45 | 4 files | `config/music-detector.json` | temp+rename per file |
| `assets/default/capri-music-v1/` | VOX-46 | `runtime-music.json` + 6 PNGs | — | read-only, checksummed |
| `config/companion-voice.local.json` | VOX-35/24 | `{schemaVersion:1, profileDir}`; `profileDir` must match `^data/voices/capri/en/(?:imports/<uuid>/)?exports/capri-trained-<uuid>$` | — | exact keys; ≤64 KiB; no links |
| `config/voice-training.local.json` | VOX-35 | `{schemaVersion:1, datasetDir}` matching `^data/voices/capri/en/imports/<uuid>$` | — | forces `allowProvisionalTranscripts:false` |
| `.runtime/installer/speech-status.json` | VOX-34 | see VOX-34 | `{"phase":"error","stage":null,"selection":{"speech":"fr","recognition":"fr"},"progress":null,"error":"Voice installation failed. Retry or save a diagnostic report.","errorCode":null,"currentFile":null,"transferState":null,"failedStage":"python"}` | atomic, best effort |
| `.runtime/installer/install.lock.json` | VOX-26/34 | `{pid, id}` created `O_EXCL 0600`; stale if pid dead | — | shared by all installers |
| `.runtime/installer/downloads/<sha256>.zip` | VOX-34 | cached artifacts | — | |
| `.runtime/voice-runtime.json` | VOX-34/24 | voice wheel profile receipt `{profile:'legacy'|'blackwell'|'amd', torch, torchaudio, backend, requirements, overrides?, devices[], warning}` | — | written after a successful dependency install |
| `.runtime/asr-vocab/<sha256>.vocab` | VOX-08 | derived BPE vocab | — | rebuilt if content differs |
| `.runtime/voice-training-job.lock` | VOX-35 | `{pid}` | — | stale if pid dead |
| `.runtime/{uv,python,uv-cache,tmp,asr-venv,voice-training-venv,qwen-tts-venv,router-venv}` | VOX-34 | tool and venv dirs | — | venv repairs move broken envs to `.runtime/venv-recovery/<name>-<hex>` (never delete) |
| `logs/speech-install.log` | VOX-34 | JSON lines `{schemaVersion:1, service:'speech-install', stage, event:'stage'|'failure'…, code?, time}` | `{"schemaVersion":1,"service":"speech-install","stage":"python","event":"failure","code":"ENOENT","time":"2026-01-01T00:00:00.000Z"}` | allowlisted fields only; >2 MiB → keep last 64 KiB |
| `logs/companion-voice.stdout.log` / `.stderr.log` | VOX-24 | JSON lines lifecycle (`started`, `exited {exitCode}`, `spawn-failed {code}`) | — | reset at each launch, cleared at >1 MiB; raw child output never written |
| `logs/voice-training-doctor.json` | VOX-34 | `{python, torch, cuda, cudaCompute{available,kernelReady,…}, modelReady, …}` | — | used by setup to decide success |
`voice-profile.json` schema (export, `voice_training/audition.py:139-190`): `{schemaVersion:1, id, character, language:'en', engine:'chatterbox-turbo', baseModel:<voice-upstream.json.model>, adapter:'adapter.safetensors', adapterConfig:'adapter.json', adapterSha256, references:{neutral:{file:'references/neutral.wav', sha256}, …≤8}, capabilities:{languages:['en'], referenceStyles, nativeTags:['[laugh]','[chuckle]'], instructionControl:false, tokenStreaming:false}, sampleRate:24000, selection}`. Voice-pack validation (`packages/installer/src/voice-pack.mjs:17-88`): file names restricted to `voice-profile.json|adapter.safetensors|adapter.json|references/[a-z0-9_-]+\.wav`, each ≤200 MiB, `.wav`/`.safetensors` must carry a SHA-256, `id` `[a-z0-9-]{1,64}`, `baseModel` deep-equal to the pinned model.
Retention: no audio is ever written except the wake-voice PCM cache, training previews and user-imported wake/training files. Microphone PCM, music PCM and synthesized reply PCM live only in memory and are dropped on stop.
---
## 4. Settings
| Key (file) | Type | Default | Allowed | Effect |
|---|---|---|---|---|
| `trailingSilenceSeconds` (`data/desktop/speech.json`; default from `config/companion-asr.json`) | number | 1.0 | 0.5..5.0 step 0.1 | VAD end-of-speech pause, echo tail, ASR session bound; applied live |
| mic `deviceId` (`data/desktop/microphone.json`) | string | `''` | known input id or `''` | capture device (exact) |
| `wakeSound` (companion) | enum | `tone` | `tone|file|voice|off` | wake acknowledgement sound |
| `wakePhrase` (companion) | enum | `Listening.` | `Listening.|Yes, choom.|Mhm?` | text of the voice acknowledgement (translated) |
| `wakeVolume` (companion) | number | 0.7 | 0..1 | wake sound gain |
| `followUp` (companion) | bool | true | | follow-up listening after a question |
| `followUpSeconds` (companion) | int | 12 | 5..30 | follow-up window |
| `restoreFromTrayOnWake` (companion) | bool | true | | show hidden window on wake |
| `wakeOnReminder` (companion, read by reminders) | bool | true | | may start the voice to speak a reminder |
| voice enabled | bool, session-only | false | | speak replies; never persisted |
| `speech` / `recognition` / `conversation` / `autoDetect` (languages) | enums | `follow` / `follow` / `en` / false | §VOX-07/20 | voice and ASR languages |
| `voice` (`data/desktop/model-devices.json`) | device id | `auto` | `auto|cpu|cuda:N:<hash>|rocm:N:<hash>` | TTS compute device (restart required) |
| voice effects (`data/desktop/voice-effects.json`) | object | clean/disabled | VOX-30 | playback DSP |
| music `enabled/notes/motion/autoBpm` | bools | false/true/true/true | | music animations; enabling starts capture |
| `allowModel` (`call-audio.json`) | bool | false | | permits "Ask Capri in call" |
| `callVoiceVolume` (`call-audio.json`) | int | 50 | 0..100 | Capri's level in the call |
| per-language model (`data/speech/voice-selections.json`) | map | en→`chatterbox-turbo`, others→`chatterbox-multilingual-v3` | catalog ids supporting the language | TTS backend |
| `config/companion-asr.json` | file | see VOX-07 | validated | engine, threads (8), `decodingMethod` (`modified_beam_search`), `maxActivePaths` (4), `maxUtteranceSeconds` (30), `autoSend` (true), `bargeIn` (true), `wakeWord {enabled:true, commandWindowMs:10000, ambiguityHoldMs:120}`, `vad {threshold:0.5, minSpeechSeconds:0.12, wakeProbeSeconds:0.8}` |
| `config/asr-vocabulary.json` | file | `wakeScore 1.5`, `commandScore 0.8`, wake `en:[Capri]`, `ru:[Capri, Капри]`, commands `en:[clip that, clip this, clip it, take a screenshot, save a screenshot, Spotify]`, `ru:[Spotify]` | VOX-08 | hotwords |
| `config/companion-voice.json` (+ `.local.json` profileDir) | file | port 8101, cpuThreads 8, maxSpeechTokens 800, seed 417, decoderDevice auto, mergeAdapter true, cudaGraph true, profileDir `data/voices/capri/en/exports/capri-en-v1` | VOX-25 | sidecar |
| Env (sidecars) | | | `CAPRI_CPU_THREADS`, `CAPRI_VOICE_COMPUTE_DEVICE`, `CAPRI_VOICE_GPU_UUID`, `CUDA_VISIBLE_DEVICES`, `ROCM_SDK_TARGET_FAMILY`, `CAPRI_ASR_LANGUAGE`, `CAPRI_ASR_SAFE_STARTUP` | see VOX-05/24 |
Hidden test switches (verification mode only, do not port as user settings): `CAPRI_DESKTOP_VERIFICATION_{VOICE,ASR,WAKE,MOCK_PACKS}`.
---
## 5. External protocols
### 5.1 Voice sidecar HTTP (loopback, `127.0.0.1:8101`)
All requests: `Host: 127.0.0.1:8101`, `Authorization: Bearer <data/speech/companion-voice-token>`, no `Origin`, `redirect: error` on the client, body JSON ≤8192 bytes with `Content-Length`.
```http
POST /synthesize HTTP/1.1
Host: 127.0.0.1:8101
Authorization: Bearer <token>
Content-Type: application/json
Content-Length: 78
{"text":"Hey, I am right here.","language":"en","requestId":"6b1c…-e2f0:0"}
```
```http
HTTP/1.0 200 OK
Content-Type: application/octet-stream
Content-Length: 211200
Cache-Control: no-store
X-Sample-Rate: 24000
X-T3-Ms: 812.4
X-Decoder-Ms: 95.1
X-Synthesis-Ms: 907.5
<raw float32 little-endian mono PCM>
```
Errors: `400` (validation), `401`/`403` (auth/Host/Origin), `404`, `409` (busy: client retries every 50 ms, ≤90 s), `499` (cancelled), `503 {"error":"model_missing","code":"CAPRI_VOICE_MODEL_MISSING","component":"tts","file":"s3gen.pt","reason":"missing|corrupt"}` or `503 {"error":"Voice generation failed","code":"CAPRI_VOICE_CUDA_OOM"}`.
`POST /prepare {"language":"fr","requestId":"prepare:fr:1767000000000"}` → `200 {"ready":true, …health fields}` (409 → retry every 100 ms ≤600 s). `POST /cancel {"requestId":"6b1c…:0"}` → `200 {"ok":true}`.
`GET /health` → 200:
```json
{"ready":true,"protocolVersion":2,"multilingual":true,"engine":"chatterbox-turbo","profile":"capri-en-v1",
"tokenStreaming":false,"sampleRate":24000,"adapterSha256":"<64 hex>","gpuAllocatedMiB":3120.4,"gpuReservedMiB":3302.0,
"warm":true,"cancellation":true,"activeEngine":"turbo","language":"en","decoderDevice":"cuda:0","computeDevice":"cuda:0",
"decoderReason":"available-vram","precision":"float32","mergedProjections":96,"cudaGraph":true,"cpuThreads":8,
"graphBatchSteps":null,"graphMaxLogitError":0.0,"generationRecoveries":0,"referenceEncodersReleased":true,
"releasedReferenceEncoderMiB":503.9,"lastInferenceFailure":null,"languages":["en","ar","zh","…"]}
```
(`activeEngine ∈ turbo|multilingual-v3|qwen3-tts`; `precision` is `float16-t3/float32-decoder` for GPU multilingual; `lastInferenceFailure = {schemaVersion:1, pid, at, code, errorType}`.)
### 5.2 ASR worker stdio (JSON lines)
```text
→ {"type":"start","sessionId":"3f0c…","attention":false,"trailingSilenceSeconds":1,"request":1}
← {"type":"startup-stage","code":"ASR_START_DEPENDENCIES"} … CONFIG, DETECTOR, MODEL
← {"type":"ready","protocol":1,"language":"en","sampleRate":16000,"provider":"cpu","engine":"parakeet-tdt-0.6b-v2","mode":"utterance","draft":false}
← {"type":"ack","request":1}
→ {"type":"pcm","sessionId":"3f0c…","pcm":"AAAAAAAA…","request":2}
← {"type":"recognition-state","sessionId":"3f0c…","utterance":0,"phase":"speech"}
← {"type":"wake-candidate","sessionId":"3f0c…","utterance":0,"text":"hey capri","boundaries":[{"start":0,"end":3,"startSample":5120,"endSample":9600},{"start":4,"end":9,"startSample":9600,"endSample":16640}]}
→ {"type":"attention","sessionId":"3f0c…","active":true,"wakeEndSample":16640,"utterance":0,"request":9}
← {"type":"recognition-state","sessionId":"3f0c…","utterance":0,"phase":"processing"}
← {"type":"transcript","sessionId":"3f0c…","utterance":0,"final":true,"text":"what time is it","audioSeconds":2.84,"prefixRemoved":true,"recognitionMs":301.55}
← {"type":"error","request":12,"code":"ASR_QUEUE_FULL"}
← {"type":"recognition-reset","sessionId":"3f0c…","utterance":3,"nextUtterance":4,"reason":"utterance_limit"}
```
If the ASR moves into a Rust child process the same message set is kept; base64 PCM may be replaced by a length-prefixed binary frame, but all validation rules of VOX-05 stay.
### 5.3 Music worker stdio (JSON lines; to be reproduced in-process)
```text
← {"type":"ready","modelId":"yamnet-qualcomm-v0.61.0"}
→ {"type":"audio","sessionId":"9d2e…","sequence":17,"pcm":"<base64 of 32000 bytes>"} (line ≤128 KiB, pcm ≤44000 chars)
← {"type":"classification","sessionId":"9d2e…","sequence":17,"music":0.912345,"speech":0.010203,"singing":0.120001,"rms":0.041234,"tempo":121.873,"tempoConfidence":0.71,"beatPhase":0.412,"inferenceMs":1.85}
→ {"type":"reset"} → {"type":"stop"}
← {"type":"error","code":"MUSIC_AUDIO_PACKET_INVALID"} (also MUSIC_MODEL_UNAVAILABLE, MUSIC_RUNTIME_UNAVAILABLE)
```
A classification is emitted only every second packet (1 s hop).
### 5.4 Training/import sidecar stdio
- Job: `python -m integrations.voice_training.job --job <uuid>` (stdin ignored, stderr ignored), stdout JSON lines `{"stage":"training","epoch":3}` / `{"stage":"training","epochs":8}`; only allowlisted stages and integer `epoch 0..50`, `epochs 1..50` are used; nonzero exit = failure (fixed message). Env: `HF_HUB_OFFLINE=1 HF_HUB_DISABLE_TELEMETRY=1 PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false HF_HOME=data/speech/hf-cache TORCH_HOME=data/speech/torch-cache TEMP/TMP=.runtime/tmp` (+ ROCm receipt env).
- Import: `python -m integrations.voice_training.import_dataset --id <uuid>`, stdin = `{"source":"/abs/folder"}`, stdout/stderr ignored, 2 min timeout.
### 5.5 Ollama request for "Ask Capri in call" (`call-response.mjs:20-87`)
`POST http://127.0.0.1:<ollamaPort>/api/chat` (endpoint must be loopback `http:` without credentials), `redirect: error`, abort after 20 s:
```json
{"model":"<settings.model>","stream":false,"shift":false,"truncate":false,"keep_alive":-1,"think":false,
"options":{"…auxiliary runner params…":0,"num_predict":160},
"format":{"type":"object","properties":{"route":{"type":"string","enum":["owner","owner-and-call"]},"reply":{"type":"string","maxLength":420}},"required":["route","reply"],"additionalProperties":false},
"tools":[],
"messages":[{"role":"system","content":"<§6 call prompt>\n<conversationInstruction(languages)>"},{"role":"user","content":"<trimmed request ≤1200>"}]}
```
`think:false` only when the model advertises `thinking` or capabilities are unknown. Response body ≤16 384 bytes; reject `done_reason:"length"` or any `tool_calls`; `message.content` must parse to exactly `{route, reply}` with valid values; `reply = plainDialogueText(reply).trim()` non-empty.
### 5.6 Speech installation on Linux (replaces `tools/setup/*.ps1`)
Recommended procedure (validated pieces: the owner's manual run in `.runtime/*.log`):
1. **uv**: use a pinned Linux uv (`uv-x86_64-unknown-linux-gnu.tar.gz`, add version + SHA-256 to a Linux artifact manifest) extracted to `.runtime/uv/uv`; a system `uv` (present on the host, 0.13.7) may be accepted if its version is ≥ the pin.
2. **Python**: `UV_PYTHON_INSTALL_DIR=.runtime/python UV_PYTHON_PREFERENCE=only-managed UV_NO_CONFIG=1 UV_CACHE_DIR=.runtime/uv-cache TMPDIR=.runtime/tmp uv python install cpython-3.11.<pin>-linux-x86_64-gnu --no-bin`. Do **not** use the system `python3` (Arch ships 3.14.10: no cp314 wheels for torch 2.6/2.7.1, numpy 1.26.4, ctranslate2 4.8.4 in the locks). Python 3.12 only for a future AMD profile.
3. **venv**: `uv venv .runtime/<name> --python <managed python>`; interpreter path is `.runtime/<name>/bin/python` (never `Scripts/python.exe`; drop the shims). Repair = rename the broken env to `.runtime/venv-recovery/<name>-<hex>`.
4. **Dependencies** (clear `UV_INDEX UV_EXTRA_INDEX_URL UV_INDEX_URL UV_DEFAULT_INDEX UV_FIND_LINKS UV_NO_INDEX UV_INDEX_STRATEGY UV_TORCH_BACKEND UV_OVERRIDE UV_CONSTRAINT UV_BUILD_CONSTRAINT` first):
- Voice, NVIDIA: run `select-voice-runtime.py --profile auto` (queries `nvidia-smi --query-gpu=index,uuid,name,compute_cap --format=csv,noheader,nounits`; compute capability ≥10 or `RTX 50xx`/`Blackwell` name → `blackwell`, else `legacy`). Blackwell: `uv pip install --exact --python .runtime/voice-training-venv/bin/python --requirements config/requirements-voice-blackwell.lock --overrides config/voice-blackwell-overrides.txt --torch-backend cu128 --default-index https://pypi.org/simple --index-strategy first-index`. Legacy: `uv pip sync --python … config/requirements-voice-training.lock --torch-backend cu124 --default-index https://pypi.org/simple --index-strategy first-index`. (The locks are version pins without hashes and resolve to Linux wheels; the `voice-pytorch-cu12x.constraints.txt` transport fallbacks pin **Windows** wheel URLs and must not be used.) Only the NVIDIA driver is needed (CUDA runtime comes from `nvidia-*` wheels). Write `.runtime/voice-runtime.json`.
- Voice, AMD: no Linux lock exists (Windows lock pins `repo.radeon.com` win_amd64 wheels) → open question; until then report `CAPRI_VOICE_GPU_UNSUPPORTED` and offer Qwen CPU.
- Qwen (CPU): regenerate the hashed lock for Linux: `uv pip compile config/requirements-qwen-tts.in --python-version 3.11 --python-platform x86_64-manylinux_2_28 --torch-backend cpu --generate-hashes --output-file config/requirements-qwen-tts.linux.lock`, then `uv pip sync --python .runtime/qwen-tts-venv/bin/python config/requirements-qwen-tts.linux.lock --require-hashes --torch-backend cpu --default-index https://pypi.org/simple --index-strategy first-index --no-config`; verify `python -c "from qwen_tts import Qwen3TTSModel; import torch; assert not torch.version.cuda"`.
- ASR: none if ASR is native Rust; only for the optional faster-whisper sidecar: `uv pip sync --python .runtime/asr-venv/bin/python config/asr-requirements.lock.txt` (verified on this host).
5. **Models**: download in Rust with the `download_verified` contract (§5.7) from the manifests, or run the existing Python provisioners (`python -m integrations.voice_training init|download|doctor`, `tools/setup/provision-multilingual.py --component tts --language <lang>`, `python -m integrations.voice_runtime.qwen_provision`). `doctor` must report `cuda && cudaCompute.kernelReady && modelReady` for the GPU voice.
6. **Voice pack**: validate `profileDir`; else import `capri-en-v1` from `data/voices/capri/en/exports/capri-en-v1`, `data/speech/bundled-voice`, `.runtime/installer/bundled-voice`, `.bundled-voice`, else download the release asset `capri-en-v1.zip` (stable non-draft release ≤ current tag, `state:'uploaded'`, size ≤200 MiB, `digest:'sha256:<hex>'`), extract (≤256 MiB) into `.runtime/installer/speech-packs/pack-XXXX/`, import, write `profileDir`.
7. **Process ownership**: children in their own process group with `PR_SET_PDEATHSIG(SIGTERM)`; cancel = SIGTERM to the group, then SIGKILL after 10 s (replaces `taskkill /T /F` and the C# `SpeechOwner`). Default command timeout 1 h; Qwen install 2 h. Hold `.runtime/installer/install.lock.json` for the whole run.
### 5.7 Model downloads
- URL patterns: `https://huggingface.co/<repo>/resolve/<40-hex revision>/<file>` (Parakeet v2/v3, Whisper, Chatterbox multilingual, Turbo, Qwen); Silero: `https://raw.githubusercontent.com/snakers4/silero-vad/6478567951ae5c9979ad7b234185b5515f4be7a1/src/silero_vad/data/silero_vad.onnx`; pkuseg zip: GitHub release + API asset fallback; YAMNet: Qualcomm S3 URL (VOX-45).
- `download_verified(url, target, {bytes, sha256})` (`integrations/model_download.py:81-241`): https only; partial file `<target>.partial` kept across retries; `Range: bytes=<offset>-` resume (servers ignoring Range restart cleanly); headers `Accept-Encoding: identity`, `Cache-Control: no-cache`, `User-Agent: Capri-Installer/0.3`; 45 s socket timeout (25 s for Turbo), 6 attempts (5 for Turbo) with backoff `min(2^(n−1), 30)` s honoring `Retry-After`; publish (rename) only after exact size + SHA-256 match; progress lines `<file>: NN% | x/y MB | rate | ~eta`; errors report host + numeric errno only (never signed redirect URLs). Disk check: free ≥ file + 1 GiB.
### 5.8 Linux audio commands (subprocess fallback; native libpulse preferred, §10)
- Microphone list / default: `pactl --format=json list sources` (skip `monitor_source_of_sink`/`*.monitor`), `pactl get-default-source`.
- System playback for music/system-audio (stereo 16 kHz f32): `parec --device=@DEFAULT_MONITOR@ --format=float32le --rate=16000 --channels=2 --raw --latency-msec=100 --client-name=Capri --stream-name="Capri music listening"` (stdout = interleaved f32; 64 000 bytes per 0.5 s packet before channel selection). PipeWire alternative (verify flags on the target): `pw-record -P stream.capture.sink=true --rate 16000 --channels 2 --format f32 --raw -`.
- Call cable (on explicit consent, no root, non-persistent):
`pactl load-module module-null-sink sink_name=capri_call rate=48000 channels=1 channel_map=mono sink_properties=device.description=Capri-call-output` →
`pactl load-module module-remap-source master=capri_call.monitor source_name=capri_call_mic channels=1 channel_map=mono source_properties=device.description=Capri-call-microphone`; both commands print the module index; unload with `pactl unload-module <index>` on disable/exit. Call apps select "Capri-call-microphone".
- Optional system AEC: `pactl load-module module-echo-cancel aec_method=webrtc source_master=<mic> sink_master=<default sink> source_name=capri_ec_source sink_name=capri_ec_sink` (noise suppression/AGC should be disabled through `aec_args`; exact key names differ between PulseAudio and PipeWire — verify), capture from `capri_ec_source`, play TTS to `capri_ec_sink`.
### 5.9 Hardware inventory used by voice
- `nvidia-smi --query-gpu=index,uuid,name,compute_cap --format=csv,noheader,nounits` (fallback without `compute_cap`), 8 s timeout; `nvidia-smi --id=<uuid> --query-gpu=memory.free --format=csv,noheader,nounits` (3 s) inside the sidecar.
- `python integrations/voice_runtime/device_inventory.py` (15 s, ≤64 KiB stdout) → `{"backend":"cuda"|"rocm","devices":[{"ordinal":0,"name":"…","totalBytes":…,"uuid":"GPU-…","available":true}]}` used to resolve a saved voice device id.