Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: local voice Chief-of-Staff (STT + LLM + TTS + tool calling) (#143)

[._.]/ Adam Eivy094897b36fdc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index de2532de51..06623c361f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,11 +1,42 @@
## Added
+- **Voice CoS tool expansion — round two** — nine more hands-free tools registered in `server/services/voice/tools.js`, bringing the total to 14:
+ - `brain_list_recent` — "Read me my last five captures"; returns the newest inbox entries with date + text.
+ - `meatspace_log_weight` — "Log my weight at 180"; accepts `lb` (default) or `kg`, auto-converts to lb before persisting, defaults to today.
+ - `goal_list` — "What are my goals?"; lists active goals ordered by urgency with horizon, category, and progress percent.
+ - `goal_update_progress` — "Bump my jacket goal to 40 percent"; fuzzy-matches the title (exact → substring → per-word token score), reports previous → new percent and flags ambiguous matches.
+ - `goal_log_note` — "Add a note to my estate goal — found the property"; attaches a free-form progress entry to the matched goal without changing the percent.
+ - `pm2_status` — "Is anything crashed?"; reports online/total plus any process in an unhealthy state with its restart count.
+ - `pm2_restart` — "Restart portos-api"; restart-only by design (no kill/delete, per the shared-server CLAUDE.md rule), accepts a substring match on process name.
+ - `feeds_digest` — "What's new in my feeds?"; returns total unread plus the top 5 newest items with title + feed name.
+ - `time_now` — "What day is it?"; returns ISO + day of week + localized date/time. Included because LLMs don't know current time on their own and frequently hallucinate it.
+ All new tools reuse existing PortOS services (`getInboxLog`, `addBodyEntry`, `getGoals`/`updateGoalProgress`/`addProgressEntry`, `listProcesses`/`restartApp`, `getItems`/`getFeeds`) and stay read/write-aligned with the web UI paths — no parallel data model. Settings → Voice copy updated to reflect the broader tool surface ("brain capture, goal updates, PM2 control, feed digests, time, and more").
+- **Voice CoS tool expansion — round one** — four new hands-free tools registered in `server/services/voice/tools.js` on top of the existing `brain_capture`:
+ - `brain_search` — substring-search the brain inbox ("what did I say about that book?"); returns up to 5 hits with date + text.
+ - `meatspace_log_drink` — "I had a beer" / "log two glasses of Cabernet"; known categories (beer/wine/whiskey/shot/cocktail) auto-fill oz+ABV defaults, free-form names also work.
+ - `meatspace_log_nicotine` — "I had a cigarette" / "two pouches"; presets for cigarette/vape/pouch.
+ - `meatspace_summary_today` — "How am I doing today?" — reports today's drinks + nicotine against 7-day rolling averages.
+ All new tools reuse existing services (`captureThought`, `getInboxLog`, `logDrink`, `logNicotine`, `getAlcoholSummary`, `getNicotineSummary`) so behavior stays aligned with the UI paths.
+- **Curated Piper voice catalog** — Settings → Voice now surfaces a hand-picked set of Piper voices for comparison against Kokoro: British (Jenny Dioco, Cori-high, Southern English female), Scottish (Alba), Irish (VCTK p266 via `speakerId: 39`), and an American baseline (Amy). Picker shows accent + gender + quality note, and flags voices that aren't downloaded yet with a ⬇ marker — they fetch automatically on save via `scripts/setup-voice.sh`. New `server/services/voice/piper-voices.js` holds the catalog; `tts-piper.js` now passes `--speaker <id>` to the Piper CLI for multi-speaker models, and the health probe was swapped from a bogus HTTP check (CLI-mode piper has no server) to a real "binary + selected voice present" check. Default Piper voice flipped from `en_US-ryan-high` (male) to `en_GB-jenny_dioco-medium` (female).
+- **Kokoro voice preview button in Settings → Voice** — new ▶ button next to the voice dropdown lets you audition any Kokoro (or Piper) voice without saving. Hits `POST /api/voice/test` with an optional `voice` override that temporarily swaps the voice for the test synth call — the saved config is untouched. Per-button spinner while rendering; button self-disables when another preview is in flight.
+- **Human-readable Kokoro voice labels in Settings → Voice** — voice picker options now render as "American Female — Heart (A)" / "British Male — Fable (C)" instead of the raw `af_heart (Female) — A` form. Accent is derived from the voice's `language` field (`en-US` → American, `en-GB` → British) and the name after the underscore is title-cased. Trait icons (❤️, 🔥, 🎧) still prefix the label.
+- **STT engine picker in Settings → Voice** — surfaces the existing `stt.engine` config option in the UI. Auto-disables the Web Speech API choice on browsers that don't expose `SpeechRecognition` (Firefox, older Safari) with a "not supported here" marker. Whisper-specific fields (model, endpoint, CoreML toggle) now hide when the engine is Web Speech, keeping the form focused.
+
+## Changed
+
+- **Default STT engine flipped from Whisper to Web Speech API** — fresh installs and the sample `data.sample/settings.json` now default to `stt.engine: 'web-speech'` (browser-native, zero-latency, no server process). `reconcile()` in `server/services/voice/bootstrap.js` now short-circuits when STT is Web Speech: stops any leftover `portos-whisper` PM2 app and skips binary/model verification and download so users who stick with the default don't pay for the whisper.cpp model or process. Health probes skip the whisper HTTP check in this mode and report a synthetic `web-speech: { ok: true, state: 'browser-native' }` status so the Settings page no longer shows whisper as "down" when it's intentionally off. Existing installs keep their saved `stt.engine` value — flip it via Settings → Voice → STT Engine.
+
+- **Web Speech API STT mode for voice assistant** — new `stt.engine: 'web-speech'` config option uses the browser's native SpeechRecognition API for speech-to-text instead of whisper.cpp. Transcription runs entirely in-browser with zero network latency — final transcripts are sent via the existing `voice:text` path so no server changes needed. Hands-free toggle and VAD meter hidden in this mode (browser handles VAD natively). Interim transcripts appear live in the conversation panel. Enable via Settings → Voice → STT Engine.
+- **Local voice Chief-of-Staff with hands-free VAD and opt-in tool calling** — new voice stack under `server/services/voice/` and `client/src/{services,components}/voice/` runs entirely on-device: Whisper (STT) + Kokoro or Piper (TTS) + LM Studio (LLM). Two capture modes: push-to-talk (click once to listen, click again to send) and **hands-free continuous mode** (default) that auto-submits on a ~600ms pause and lets you barge in over the bot's own voice. Hands-free is built around an AudioWorklet streaming raw PCM to a thin energy-based VAD — thresholds auto-calibrate to the user's ambient noise floor on startup, a pre-roll ring buffer avoids clipping the first syllable, a TTS echo-tail cooldown filters speaker→mic reverb, and a runaway-speech watchdog unjams VAD if silence never registers. Whisper requests now bias the decoder with a PortOS vocabulary prompt so proper nouns ("brain inbox", "Chief of Staff", "Tailscale") don't drift to homophones.
+- **Configurable CoS personality for the voice assistant** — Settings → Voice exposes a personality editor (name, role, traits, speech style, custom prompt). The system prompt is composed live per turn from those fields plus the list of available tools. Toggle **Enable tools** (off by default; needs a tool-use-trained model like Qwen2.5-7B or Hermes-3) to let the CoS actually do things. First tool shipped: `brain_capture` — routes any "remember…", "add…", "note…" style request into the existing brain inbox via `captureThought()`. The pipeline runs up to 3 tool-call rounds per turn and streams text deltas to TTS between iterations so you hear the CoS narrate what it's doing.
+- **Voice widget on every page** — floating conversation card (bottom-right) with live mic-level meter, stage indicator (`handsfree` / `capturing` / `thinking` / `speaking`), mode toggle, interrupt button, text-entry fallback, and scrolling transcript. Hotkey (default Space) toggles listening. Settings → Voice also gets STT/TTS engine pickers, Whisper model picker, Kokoro voice picker (dozens of voices: `af_*` female, `am_*` male, `bf_*`/`bm_*` British), CoreML encoder toggle, and one-click "Test voice".
- **MortalLoom iCloud sync** — new Settings tab (Settings → MortalLoom) lets PortOS share Goals and Meatspace data with the MortalLoom iOS/macOS app by reading from and writing to the app's iCloud ubiquity container (`~/Library/Mobile Documents/iCloud~net~shadowpuppet~MeatSpaceTracker/Documents/MortalLoom.json`). When enabled, PortOS treats the iCloud file as the source of truth for alcohol drinks, nicotine entries, blood tests, body composition, epigenetic tests, eye exams, and goals — and every add/update/remove flow mirrors back to it so edits on either side stay in sync. Non-destructive one-shot "Import from MortalLoom" button for adopting the iCloud data into local PortOS stores by id-dedup. New `server/services/mortalLoomStore.js` exposes tight primitives (`readStore`, `updateStore`, `mlPush/mlPatchById/mlRemoveById/mlReplace`, `mlArrayIfEnabled`, `mlIdAtDateIndex`) used by `meatspaceHealth`, `meatspaceAlcohol`, `meatspaceNicotine`, and `identity`.
- **MortalLoom promo banner on Meatspace + Goals pages** — dismissible banner (stored in `localStorage` as `mortalloom-banner-dismissed-v1`) linking to the App Store (`id6760883701`) and to the new Settings tab for iCloud sync configuration.
## Fixed
- **Cmd prompt windows flashing on Windows** — `fetchJlist` in `pm2.js` was spawning a `node pm2.js jlist` subprocess every 400ms+ during app-status polling. Even with `windowsHide: true`, Windows briefly flashes the console for spawned Node.js processes on some configurations. Fixed by switching to the PM2 Node.js API (`pm2.list()` via IPC) for the default PM2_HOME case, eliminating subprocess spawning entirely. The CLI path is kept only for custom `pm2Home` (managed external apps).
+- **Digital Twin build errors — missing Soul-prefixed API exports** — components used `api.createSoulDocument`, `api.runSoulTests`, etc. but `apiDigitalTwin.js` only exported `DigitalTwin`-prefixed names. Added 10 Soul aliases so the build resolves all imports.
- **POST drill scoring paired every answer to the first prompt** — `llmResponseSchema` in `postValidation.js` didn't list `questionIndex`, so Zod's default strip mode dropped the field on its way to the scorer. The scorer's `r.questionIndex ?? i` fallback then resolved to the response-array index — always 0 for the single-response submits the trainer makes — and every answer was evaluated against the FIRST prompt of the drill. Affected bridge-word, idiom-twist, double-meaning, and every other LLM-scored POST drill (the v1.43.0 client-side fix wired up `questionIndex` on the request but it never reached the scorer). Schema now declares `questionIndex` and a regression test in `postValidation.test.js` covers the round-trip.
- **Compound chain rejected the natural shorthand** — typing just the *other half* of a compound (e.g., `hose`, `pit`, `work` for the root `fire`) was scored as invalid because the local scorer required the user's input to literally include the root word. Players had to type `firehose` / `firepit` / `firework` in full, which slowed them down and produced misleading "0 valid compounds" scores. Scorer now accepts both the full compound and the half — bare root word still rejected, and the "you could also have said" suggestions correctly suppress examples the user already covered via either form. UI placeholder updated to "Type the full compound or just the other half...".
diff --git a/PLAN.md b/PLAN.md
index 32c682cd13..6e09f10a06 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -10,6 +10,12 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Backlog
+- [ ] **Voice CoS tool expansion** — 14 tools registered in `server/services/voice/tools.js`: `brain_capture`, `brain_search`, `brain_list_recent`, `meatspace_log_drink`, `meatspace_log_nicotine`, `meatspace_log_weight`, `meatspace_summary_today`, `goal_list`, `goal_update_progress`, `goal_log_note`, `pm2_status`, `pm2_restart`, `feeds_digest`, `time_now`. Remaining candidates:
+ - `calendar_today` / `calendar_next` — surface today's Google Calendar events through the existing Google MCP integration
+ - `meatspace_log_workout` — wrap `meatspaceHealth.js` workout/activity exports
+ - `weather_now` — needs an external API choice (OpenWeather / Apple WeatherKit / NWS)
+ - `timer_set` — set a voice-triggered reminder; likely reuses `agentActionExecutor.js` scheduled actions
+ - `feeds_mark_read` — pair with `feeds_digest` for "mark that one read"
- [x] **Test coverage** — cosRunnerClient.js ✅ (37 tests), agentActionExecutor.js ✅ (27 tests), CoS routes ✅ (170 tests across 6 test files, 83-100% route coverage). Remaining gap: cos.js service (~4% coverage)
- [ ] **CyberCity v2** — Transform from decorative scene to living systems dashboard. See [cybercity-v2.md](./docs/features/cybercity-v2.md) for full plan. Top priorities: system health atmosphere, richer billboards, brain inbox pulse, agent activity visualization, chronotype energy overlay.
- [ ] **M50 P9**: CoS Automation & Rules — Automated email classification, rule-based pre-filtering, email-to-task pipeline
diff --git a/README.md b/README.md
index 2c23790255..0ba5592731 100644
--- a/README.md
+++ b/README.md
@@ -111,6 +111,19 @@ Everything you need to manage your dev environment without leaving the browser.
- **Browser Control** — Remote Chrome DevTools Protocol integration for headless browser management ([Browser docs](./docs/features/browser.md))
- **Code Runner** — In-app code execution with syntax highlighting
+### Voice Mode (Local)
+
+Push-to-talk and hands-free voice assistant with no PortOS-hosted server dependencies. TTS and LLM run locally; STT is fully offline with whisper.cpp.
+
+- **STT** — browser Web Speech API by default (zero-latency, no PortOS server process needed). **Note:** the Web Speech API in Chrome and most Chromium browsers forwards audio to a vendor cloud speech service (Google); for fully-offline STT with no data leaving the machine, select local [whisper.cpp](https://github.com/ggerganov/whisper.cpp) under *Settings → Voice → STT engine*. Optional CoreML encoder gives 2–3× speedup on Apple Silicon
+- **Local TTS** — [Kokoro-82M](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX) running in-process via ONNX Runtime (default, cross-platform), or [Piper](https://github.com/rhasspy/piper) CLI as a lightweight alternative
+- **Local LLM** — routed through your existing LM Studio installation
+- **Push-to-talk** — click and hold the mic widget or hold `Space` to speak; release to send
+- **Barge-in** — start a new turn while the assistant is speaking to interrupt and redirect
+- **Configurable** — STT engine, TTS engine, voice, Whisper model size, CoreML, speech rate, system prompt all editable from Settings
+
+Enable under *Settings → Voice*; PortOS provisions required voice components as needed on first enable — `whisper-cpp` via Homebrew (when STT is whisper), Piper + phonemize libs pulled from [rhasspy/piper](https://github.com/rhasspy/piper) GitHub Releases (when TTS is Piper), and selected Whisper/Piper models downloaded into `~/.portos/voice/`. Full setup in [Voice Mode docs](./docs/features/voice.md).
+
### Meatspace (Physical Health)
Track your biological self alongside your digital one.
@@ -230,6 +243,8 @@ Configure AI providers for the runner and Chief of Staff:
- [Troubleshooting](./docs/TROUBLESHOOTING.md) — Common issues and solutions
### Feature Deep Dives
+
+- [Voice Mode](./docs/features/voice.md) — local STT/TTS/LLM voice assistant setup
- [Chief of Staff](./docs/features/chief-of-staff.md) — Autonomous agent orchestrator
- [Agent Skills](./docs/features/agent-skills.md) — Task-type-specific agent prompts
- [CoS Agent Runner](./docs/features/cos-agent-runner.md) — Isolated agent process architecture
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 4480afe0b9..a893c75cb4 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -72,7 +72,8 @@ import {
HardDrive,
MessagesSquare,
BookOpen,
- Search
+ Search,
+ Mic
} from 'lucide-react';
/* global __APP_VERSION__ */
import Logo from './Logo';
@@ -84,6 +85,7 @@ import NotificationDropdown from './NotificationDropdown';
import ThemeSwitcher from './ThemeSwitcher';
import CmdKSearch from './CmdKSearch';
import KeyboardHelp from './KeyboardHelp';
+import VoiceWidget from './voice/VoiceWidget';
import * as api from '../services/api';
import socket from '../services/socket';
@@ -231,6 +233,7 @@ const navItems = [
{ to: '/settings/backup', label: 'Backup', icon: Download },
{ to: '/settings/database', label: 'Database', icon: Database },
{ to: '/settings/image-gen', label: 'Image Gen', icon: ImageIcon },
+ { to: '/settings/voice', label: 'Voice', icon: Mic },
{ to: '/prompts', label: 'Prompts', icon: FileText },
{ to: '/ai', label: 'Providers', icon: Bot },
{ to: '/security', label: 'Security', icon: Camera },
@@ -724,6 +727,8 @@ export default function Layout() {
<CmdKSearch />
{/* Keyboard shortcuts help — press ? to toggle */}
<KeyboardHelp />
+ {/* Push-to-talk voice widget — self-hides when voice.enabled is false */}
+ <VoiceWidget />
</div>
);
}
diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsx
new file mode 100644
index 0000000000..7777eda79c
--- /dev/null
+++ b/client/src/components/settings/VoiceTab.jsx
@@ -0,0 +1,519 @@
+import { useState, useEffect, useCallback } from 'react';
+import { Save, Mic, Play, Zap } from 'lucide-react';
+import toast from '../ui/Toast';
+import BrailleSpinner from '../BrailleSpinner';
+import {
+ getVoiceStatus, getVoiceConfig, updateVoiceConfig, listVoices, testTts, fetchPiperVoice,
+} from '../../services/apiVoice';
+import { playWav, webSpeechSupported } from '../../services/voiceClient';
+
+const SERVICE_LABELS = {
+ whisper: 'Whisper (STT)',
+ 'web-speech': 'Web Speech API (STT)',
+ piper: 'Piper (TTS)',
+ kokoro: 'Kokoro (TTS)',
+ lmstudio: 'LM Studio (LLM)',
+};
+
+const STT_ENGINES = [
+ { value: 'whisper', label: 'Whisper (local, accurate, works offline)' },
+ { value: 'web-speech', label: 'Web Speech API (browser-native, zero latency)' },
+];
+
+const TTS_ENGINES = [
+ { value: 'kokoro', label: 'Kokoro (in-process, high quality)' },
+ { value: 'piper', label: 'Piper (CLI binary, lightweight)' },
+];
+
+const KOKORO_DTYPES = [
+ { value: 'q8', label: 'q8 (recommended — ~80MB, fast)' },
+ { value: 'q4', label: 'q4 (smallest)' },
+ { value: 'fp16', label: 'fp16 (higher quality)' },
+ { value: 'fp32', label: 'fp32 (best quality, slowest)' },
+];
+
+const ACCENT_LABELS = { 'en-US': 'American', 'en-GB': 'British' };
+
+const formatVoiceLabel = (v, engine) => {
+ if (engine === 'piper') {
+ // Always lead with the voice ID so entries are distinguishable even if the
+ // catalog metadata (accent/gender/note) is stripped or missing.
+ const meta = [v.accent, v.gender].filter(Boolean).join(' — ');
+ const dl = v.downloaded ? '' : ' ⬇';
+ const note = v.note ? ` · ${v.note}` : '';
+ return meta ? `${v.name} — ${meta}${note}${dl}` : `${v.name}${note}${dl}`;
+ }
+ const accent = ACCENT_LABELS[v.language] || v.language || '';
+ const [, ...rest] = v.name.split('_');
+ const raw = rest.join(' ') || v.name;
+ const display = raw.charAt(0).toUpperCase() + raw.slice(1);
+ const who = [accent, v.gender].filter(Boolean).join(' ');
+ const traits = v.traits ? `${v.traits} ` : '';
+ const grade = v.grade ? ` (${v.grade})` : '';
+ return `${traits}${who ? `${who} — ${display}` : display}${grade}`;
+};
+
+const WHISPER_MODELS = [
+ { value: 'tiny.en', file: 'ggml-tiny.en.bin', label: 'tiny.en — 75 MB, fastest' },
+ { value: 'base.en', file: 'ggml-base.en.bin', label: 'base.en — 142 MB, balanced (default)' },
+ { value: 'small.en', file: 'ggml-small.en.bin', label: 'small.en — 466 MB, more accurate' },
+ { value: 'medium.en', file: 'ggml-medium.en.bin', label: 'medium.en — 1.5 GB, very accurate' },
+ { value: 'large-v3', file: 'ggml-large-v3.bin', label: 'large-v3 — 3 GB, multilingual, best' },
+];
+
+const ServiceBadge = ({ label, probe }) => {
+ if (!probe) return null;
+ const ok = probe.ok;
+ return (
+ <div className={`flex items-center gap-2 text-sm ${ok ? 'text-port-success' : 'text-port-error'}`}>
+ <span className={`w-2 h-2 rounded-full ${ok ? 'bg-port-success' : 'bg-port-error'}`} />
+ <span className="font-medium">{label}</span>
+ <span className="text-xs text-gray-500">
+ {ok ? `${probe.latencyMs ?? probe.state ?? '—'}` : probe.state || probe.error || 'down'}
+ {ok && typeof probe.latencyMs === 'number' ? 'ms' : ''}
+ </span>
+ </div>
+ );
+};
+
+const Field = ({ label, hint, children, className = '' }) => (
+ <div className={`space-y-1 ${className}`}>
+ <label className="block text-sm text-gray-400">{label}</label>
+ {hint && <p className="text-xs text-gray-500">{hint}</p>}
+ {children}
+ </div>
+);
+
+const inputCls = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';
+
+export function VoiceTab() {
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [cfg, setCfg] = useState(null);
+ const [status, setStatus] = useState(null);
+ const [voiceList, setVoiceList] = useState({ engine: null, voices: [] });
+ const [testing, setTesting] = useState(false);
+ const [previewingVoice, setPreviewingVoice] = useState(null);
+ const [downloadingVoice, setDownloadingVoice] = useState(null);
+
+ const currentEngine = cfg?.tts?.engine;
+
+ const refreshStatus = useCallback(() => {
+ return Promise.all([
+ getVoiceStatus(),
+ listVoices(currentEngine).catch(() => ({ engine: null, voices: [] })),
+ ])
+ .then(([s, v]) => { setStatus(s); setVoiceList(v); })
+ .catch(() => setStatus(null));
+ }, [currentEngine]);
+
+ useEffect(() => {
+ Promise.all([getVoiceConfig(), getVoiceStatus()])
+ .then(([config, s]) => { setCfg(config); setStatus(s); })
+ .catch(() => toast.error('Failed to load voice settings'))
+ .finally(() => setLoading(false));
+ }, []);
+
+ // Refetch the voice catalog whenever the user flips TTS engine so the picker
+ // reflects the selected engine's voices (without requiring a save first).
+ useEffect(() => {
+ if (!currentEngine) return;
+ listVoices(currentEngine)
+ .then((v) => setVoiceList(v))
+ .catch(() => setVoiceList({ engine: currentEngine, voices: [] }));
+ }, [currentEngine]);
+
+ // Functional setState form so sequential patch() calls in one event handler
+ // compose correctly — each one sees the prior's result instead of cloning
+ // the pre-event `cfg` and silently overwriting earlier changes.
+ const patch = (path, value) => {
+ setCfg((prev) => {
+ const next = JSON.parse(JSON.stringify(prev));
+ let cur = next;
+ const keys = path.split('.');
+ for (let i = 0; i < keys.length - 1; i++) cur = cur[keys[i]] ??= {};
+ cur[keys[keys.length - 1]] = value;
+ return next;
+ });
+ };
+
+ const handleSave = async () => {
+ setSaving(true);
+ await updateVoiceConfig(cfg)
+ .then((r) => {
+ setCfg(r.config);
+ const rec = r.reconciliation || {};
+ if (rec.error) {
+ toast.error(`Saved, but reconcile failed: ${rec.error}`, { duration: 12000 });
+ } else if (rec.skipped === 'web-speech') {
+ toast.success('Voice settings saved — using Web Speech API for STT');
+ } else if (rec.skipped === true) {
+ toast.success('Voice settings saved (disabled)');
+ } else if (rec.stopped) {
+ toast.success('Voice settings saved — whisper stopped');
+ } else if (rec.host) {
+ toast.success(`Voice settings saved — whisper up on ${rec.host}:${rec.port}`);
+ } else {
+ toast.success('Voice settings saved');
+ }
+ })
+ .catch((err) => toast.error(`Failed to save voice settings: ${err.message}`))
+ .finally(() => setSaving(false));
+ await refreshStatus();
+ };
+
+ const handleTest = async () => {
+ setTesting(true);
+ await testTts('Voice mode is online. I am ready to help.', undefined, currentEngine)
+ .then((buf) => playWav(buf))
+ .catch((err) => toast.error(`TTS test failed: ${err.message}`))
+ .finally(() => setTesting(false));
+ await refreshStatus();
+ };
+
+ const handlePreviewVoice = async (voiceName) => {
+ if (!voiceName || previewingVoice) return;
+ setPreviewingVoice(voiceName);
+ await testTts("Hi, I'm your voice. This is how I sound.", voiceName, currentEngine)
+ .then((buf) => playWav(buf))
+ .catch((err) => toast.error(`Preview failed: ${err.message}`))
+ .finally(() => setPreviewingVoice(null));
+ };
+
+ const handleWhisperModel = (value) => {
+ const m = WHISPER_MODELS.find((x) => x.value === value);
+ if (!m) return;
+ patch('stt.model', m.value);
+ patch('stt.modelPath', `~/.portos/voice/models/${m.file}`);
+ };
+
+ if (loading || !cfg) return <BrailleSpinner text="Loading voice settings" />;
+
+ const engine = cfg.tts.engine || 'kokoro';
+ const sttEngine = cfg.stt.engine || 'whisper';
+ const activeVoice = engine === 'kokoro' ? cfg.tts.kokoro?.voice : cfg.tts.piper?.voice;
+ const voices = voiceList.voices || [];
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-6">
+ <div className="flex items-center gap-2 text-white">
+ <Mic size={18} />
+ <h2 className="text-lg font-semibold">Local Voice Chief-of-Staff</h2>
+ </div>
+ <p className="text-xs text-gray-500 -mt-4">
+ Hands-free or push-to-talk voice. Whisper (STT) + Kokoro/Piper (TTS) + LM Studio (LLM)
+ with tool calling for real actions (brain capture, goal updates, PM2 control, feed
+ digests, time, and more). Everything runs on this machine — no external API calls.
+ </p>
+
+ <label className="flex items-center gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={cfg.enabled}
+ onChange={(e) => patch('enabled', e.target.checked)}
+ className="w-4 h-4"
+ />
+ <span className="text-sm text-white">Enable voice mode</span>
+ <span className="text-xs text-gray-500">
+ (toggling on installs missing binaries + downloads selected models)
+ </span>
+ </label>
+
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
+ {status?.services && Object.entries(status.services).map(([k, probe]) => (
+ <ServiceBadge key={k} label={SERVICE_LABELS[k] || k} probe={probe} />
+ ))}
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <Field label="Hotkey" hint="Hold to talk (keyboard).">
+ <input
+ type="text"
+ value={cfg.hotkey}
+ onChange={(e) => patch('hotkey', e.target.value)}
+ className={inputCls}
+ />
+ </Field>
+
+ <Field label="TTS engine" hint="Kokoro is higher quality and runs in-process. Piper is a small CLI binary.">
+ <select
+ value={engine}
+ onChange={(e) => patch('tts.engine', e.target.value)}
+ className={inputCls}
+ >
+ {TTS_ENGINES.map((opt) => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ </Field>
+
+ <Field label={`${engine === 'kokoro' ? 'Kokoro' : 'Piper'} voice`} hint={
+ engine === 'kokoro'
+ ? 'Grade letter = Kokoro author\'s quality rating. ❤️ 🔥 🎧 mark the best-sounding voices. Click ▶ to preview without saving.'
+ : 'Curated Piper catalog — selecting a ⬇ voice fetches it immediately so you can preview. Click ▶ to audition.'
+ }>
+ <div className="flex items-center gap-2">
+ <select
+ value={activeVoice || ''}
+ onChange={(e) => {
+ const val = e.target.value;
+ if (engine === 'kokoro') { patch('tts.kokoro.voice', val); return; }
+ const v = voices.find((x) => x.name === val);
+ patch('tts.piper.voice', val);
+ if (v?.path) patch('tts.piper.voicePath', v.path);
+ patch('tts.piper.speakerId', null);
+ // Fetch voice on select so ▶ preview works without a save.
+ // Safe to kick off fire-and-forget — the UI disables the
+ // preview button while a download is in flight.
+ if (v && v.downloaded === false) {
+ setDownloadingVoice(val);
+ fetchPiperVoice(val)
+ .then(() => listVoices('piper'))
+ .then((fresh) => setVoiceList(fresh))
+ .catch((err) => toast.error(`Voice download failed: ${err.message}`))
+ .finally(() => setDownloadingVoice(null));
+ }
+ }}
+ className={`${inputCls} flex-1`}
+ >
+ {activeVoice && !voices.some((v) => v.name === activeVoice) && (
+ <option value={activeVoice}>{activeVoice} (current)</option>
+ )}
+ {voices.map((v) => (
+ <option key={v.name} value={v.name}>{formatVoiceLabel(v, engine)}</option>
+ ))}
+ </select>
+ <button
+ type="button"
+ onClick={() => handlePreviewVoice(activeVoice)}
+ disabled={!activeVoice || !!previewingVoice || !!downloadingVoice}
+ title={downloadingVoice ? `Downloading ${downloadingVoice}…` : 'Preview this voice'}
+ className="shrink-0 p-2 rounded-lg bg-port-border hover:bg-port-border/70 text-white disabled:opacity-50"
+ >
+ {previewingVoice === activeVoice || downloadingVoice === activeVoice
+ ? <BrailleSpinner />
+ : <Play size={14} />}
+ </button>
+ </div>
+ </Field>
+
+ {engine === 'kokoro' && (
+ <Field label="Kokoro precision" hint="Lower precision = smaller download + faster, slight quality cost.">
+ <select
+ value={cfg.tts.kokoro?.dtype || 'q8'}
+ onChange={(e) => patch('tts.kokoro.dtype', e.target.value)}
+ className={inputCls}
+ >
+ {KOKORO_DTYPES.map((opt) => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ </Field>
+ )}
+
+ <Field label="Speech rate" hint="0.5 = slow, 1.0 = normal, 2.0 = fast">
+ <input
+ type="number" min="0.5" max="2" step="0.1"
+ value={cfg.tts.rate ?? 1.0}
+ onChange={(e) => patch('tts.rate', parseFloat(e.target.value) || 1.0)}
+ className={inputCls}
+ />
+ </Field>
+
+ <Field label="STT engine" hint={webSpeechSupported
+ ? 'Web Speech = browser-native, zero-latency, but quality varies by browser and only works in Chrome/Edge. Whisper = local, consistent, offline.'
+ : 'Web Speech unavailable in this browser (Chrome/Edge only). Whisper it is.'}>
+ <select
+ value={sttEngine}
+ onChange={(e) => patch('stt.engine', e.target.value)}
+ className={inputCls}
+ >
+ {STT_ENGINES.map((opt) => (
+ <option key={opt.value} value={opt.value} disabled={opt.value === 'web-speech' && !webSpeechSupported}>
+ {opt.label}{opt.value === 'web-speech' && !webSpeechSupported ? ' — not supported here' : ''}
+ </option>
+ ))}
+ </select>
+ </Field>
+
+ {sttEngine === 'whisper' && (
+ <>
+ <Field label="Whisper model" hint="Bigger = more accurate, slower, larger download.">
+ <select
+ value={cfg.stt.model || 'base.en'}
+ onChange={(e) => handleWhisperModel(e.target.value)}
+ className={inputCls}
+ >
+ {WHISPER_MODELS.map((m) => (
+ <option key={m.value} value={m.value}>{m.label}</option>
+ ))}
+ </select>
+ </Field>
+
+ <Field label="Whisper endpoint">
+ <input
+ type="text"
+ value={cfg.stt.endpoint}
+ onChange={(e) => patch('stt.endpoint', e.target.value)}
+ className={inputCls}
+ />
+ </Field>
+ </>
+ )}
+
+ <Field label="LLM model" hint="'auto' picks the first loaded LM Studio model">
+ <input
+ type="text"
+ value={cfg.llm.model}
+ onChange={(e) => patch('llm.model', e.target.value)}
+ className={inputCls}
+ />
+ </Field>
+
+ <label className="flex items-center gap-3 cursor-pointer md:col-span-2">
+ <input
+ type="checkbox"
+ checked={cfg.llm.usePersonality !== false}
+ onChange={(e) => patch('llm.usePersonality', e.target.checked)}
+ className="w-4 h-4"
+ />
+ <span className="text-sm text-white">Use Chief-of-Staff personality (recommended)</span>
+ <span className="text-xs text-gray-500">
+ Composes the system prompt from the fields below. Turn off to use the raw prompt.
+ </span>
+ </label>
+
+ {cfg.llm.usePersonality !== false ? (
+ <>
+ <Field label="Name" hint="What the assistant calls itself.">
+ <input
+ type="text"
+ value={cfg.llm.personality?.name ?? ''}
+ onChange={(e) => patch('llm.personality.name', e.target.value)}
+ className={inputCls}
+ />
+ </Field>
+ <Field label="Role" hint="The role it plays for you.">
+ <input
+ type="text"
+ value={cfg.llm.personality?.role ?? ''}
+ onChange={(e) => patch('llm.personality.role', e.target.value)}
+ className={inputCls}
+ />
+ </Field>
+ <Field label="Speech style" hint="e.g. 'casual and brief', 'formal and precise'.">
+ <input
+ type="text"
+ value={cfg.llm.personality?.speechStyle ?? ''}
+ onChange={(e) => patch('llm.personality.speechStyle', e.target.value)}
+ className={inputCls}
+ />
+ </Field>
+ <Field label="Traits (comma-separated)" hint="e.g. 'concise, warm, proactive'.">
+ <input
+ type="text"
+ value={(cfg.llm.personality?.traits || []).join(', ')}
+ onChange={(e) => patch('llm.personality.traits',
+ e.target.value.split(',').map((s) => s.trim()).filter(Boolean))}
+ className={inputCls}
+ />
+ </Field>
+ <Field label="Custom prompt (optional)" className="md:col-span-2" hint="Any extra context or instructions appended to the system prompt.">
+ <textarea
+ value={cfg.llm.personality?.customPrompt ?? ''}
+ onChange={(e) => patch('llm.personality.customPrompt', e.target.value)}
+ rows={2}
+ className={`${inputCls} font-mono text-xs`}
+ />
+ </Field>
+ </>
+ ) : (
+ <Field label="System prompt" className="md:col-span-2">
+ <textarea
+ value={cfg.llm.systemPrompt}
+ onChange={(e) => patch('llm.systemPrompt', e.target.value)}
+ rows={2}
+ className={`${inputCls} font-mono text-xs`}
+ />
+ </Field>
+ )}
+
+ <label className="flex items-center gap-3 cursor-pointer md:col-span-2">
+ <input
+ type="checkbox"
+ checked={cfg.llm.tools?.enabled === true}
+ onChange={(e) => patch('llm.tools.enabled', e.target.checked)}
+ className="w-4 h-4"
+ />
+ <span className="text-sm text-white">Enable tools (brain, goals, PM2, feeds, time…)</span>
+ <span className="text-xs text-gray-500">
+ Needs a tool-use-capable model (Qwen2.5, Hermes-3, etc.).
+ </span>
+ </label>
+
+ {sttEngine === 'whisper' && (
+ <label className="flex items-center gap-3 cursor-pointer md:col-span-2">
+ <input
+ type="checkbox"
+ checked={!!cfg.stt.coreml}
+ onChange={(e) => patch('stt.coreml', e.target.checked)}
+ className="w-4 h-4"
+ />
+ <span className="text-sm text-white">Use CoreML encoder for Whisper (macOS only)</span>
+ <span className="text-xs text-gray-500">2–3× faster STT on Apple Silicon.</span>
+ </label>
+ )}
+ </div>
+
+ <div className="flex items-center gap-3 pt-2">
+ <button
+ onClick={handleSave}
+ disabled={saving}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white text-sm rounded-lg transition-colors disabled:opacity-50"
+ >
+ {saving ? <BrailleSpinner /> : <Save size={14} />}
+ Save & Reconcile
+ </button>
+ <button
+ onClick={handleTest}
+ disabled={testing}
+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors disabled:opacity-50"
+ title="Synthesize a test phrase with the active TTS engine"
+ >
+ {testing ? <BrailleSpinner /> : <Play size={14} />}
+ Test voice
+ </button>
+ <button
+ onClick={refreshStatus}
+ className="flex items-center gap-2 px-4 py-2 bg-port-border hover:bg-port-border/70 text-white text-sm rounded-lg transition-colors"
+ >
+ <Zap size={14} />
+ Refresh
+ </button>
+ </div>
+
+ <details className="text-xs text-gray-500">
+ <summary className="cursor-pointer">Binary + model paths</summary>
+ <dl className="mt-2 space-y-1 font-mono">
+ {sttEngine === 'whisper' ? (
+ <>
+ <div>whisper-server: {status?.binaries?.whisper || <em className="text-port-error">not found</em>}</div>
+ <div>STT model: {status?.models?.sttModel || <em className="text-port-error">missing</em>}</div>
+ {cfg.stt.coreml && (
+ <div>CoreML encoder: {status?.models?.coreml || <em className="text-port-error">missing</em>}</div>
+ )}
+ </>
+ ) : (
+ <div>STT: <em>Web Speech API (browser-native — no server binaries required)</em></div>
+ )}
+ {engine === 'piper' && (
+ <div>piper: {status?.binaries?.piper || <em className="text-port-error">not found</em>}</div>
+ )}
+ <div>TTS voice: {status?.models?.ttsVoice || <em className="text-port-error">missing</em>}</div>
+ </dl>
+ </details>
+ </div>
+ );
+}
+
+export default VoiceTab;
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
new file mode 100644
index 0000000000..26b15fb58b
--- /dev/null
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -0,0 +1,410 @@
+import { useState, useEffect, useRef, useCallback } from 'react';
+import { Mic, MicOff, Brain, Volume2, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon } from 'lucide-react';
+import {
+ startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,
+ startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,
+ webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,
+} from '../../services/voiceClient';
+import { getVoiceConfig } from '../../services/apiVoice';
+import toast from '../ui/Toast';
+
+// Peak below this (0..1) is usually whisper's [BLANK_AUDIO] territory.
+const QUIET_MIC_THRESHOLD = 0.02;
+
+const HANDS_FREE_KEY = 'portos.voice.handsFree';
+
+const STAGE = {
+ idle: { icon: Mic, label: '', tone: 'text-gray-300' },
+ listening: { icon: MicOff, label: 'Listening… (click to send)', tone: 'text-port-accent' },
+ handsfree: { icon: MicOff, label: 'Hands-free — speak anytime', tone: 'text-port-accent' },
+ capturing: { icon: MicOff, label: 'Capturing your voice…', tone: 'text-port-accent animate-pulse' },
+ thinking: { icon: Brain, label: 'Thinking…', tone: 'text-yellow-400' },
+ speaking: { icon: Volume2, label: 'Speaking (talk to interrupt)', tone: 'text-port-success' },
+};
+
+// Stages where the mic is live and/or the user is mid-utterance — do not
+// overwrite these when a server event would otherwise demote them.
+const ACTIVE_STAGES = new Set(['listening', 'capturing', 'handsfree']);
+
+const MAX_HISTORY = 50;
+
+const warnIfQuiet = (peak) => {
+ if (typeof peak === 'number' && peak < QUIET_MIC_THRESHOLD) {
+ toast(`Mic very quiet (peak ${peak.toFixed(3)}). Check input device / volume.`, { icon: '🎤' });
+ }
+};
+
+export default function VoiceWidget() {
+ const [enabled, setEnabled] = useState(false);
+ const [hotkey, setHotkey] = useState('Space');
+ const [sttEngine, setSttEngine] = useState('whisper');
+ const [sttLanguage, setSttLanguage] = useState('en');
+ const [stage, setStage] = useState('idle');
+ const [history, setHistory] = useState([]);
+ const [collapsed, setCollapsed] = useState(false);
+ const [draft, setDraft] = useState('');
+ const [interimTranscript, setInterimTranscript] = useState('');
+ const [handsFree, setHandsFree] = useState(() => {
+ if (typeof window === 'undefined') return true;
+ const stored = window.localStorage.getItem(HANDS_FREE_KEY);
+ return stored === null ? true : stored === '1';
+ });
+ const [level, setLevel] = useState(0);
+ const scrollRef = useRef(null);
+ const useWebSpeech = sttEngine === 'web-speech' && webSpeechSupported;
+
+ // Disabling voice mode (via Settings or the socket broadcast) must release
+ // every mic path — MediaRecorder, AudioWorklet VAD, and Web Speech — plus
+ // drop any queued TTS. Without this, a user who turns voice off while
+ // hands-free is listening leaves the mic active in the background.
+ useEffect(() => {
+ if (enabled) return;
+ if (isWebSpeechCapturing()) stopWebSpeechCapture();
+ if (isContinuous()) stopContinuous();
+ if (isCapturing()) stopCapture({ submit: false });
+ interrupt();
+ setStage('idle');
+ }, [enabled]);
+
+ useEffect(() => {
+ getVoiceConfig()
+ .then((cfg) => {
+ setEnabled(!!cfg?.enabled);
+ setHotkey(cfg?.hotkey || 'Space');
+ if (cfg?.stt?.engine) setSttEngine(cfg.stt.engine);
+ if (cfg?.stt?.language) setSttLanguage(cfg.stt.language);
+ })
+ .catch(() => {});
+ // Settings → Voice writes via PUT /api/voice/config and the route broadcasts
+ // voice:config:changed — keep the widget's enabled/engine/hotkey in sync so
+ // toggling voice mode mid-session takes effect without a reload.
+ const off = onVoiceEvent('voice:config:changed', (cfg) => {
+ if (typeof cfg?.enabled === 'boolean') setEnabled(cfg.enabled);
+ if (cfg?.hotkey) setHotkey(cfg.hotkey);
+ if (cfg?.sttEngine) setSttEngine(cfg.sttEngine);
+ if (cfg?.sttLanguage) setSttLanguage(cfg.sttLanguage);
+ });
+ return off;
+ }, []);
+
+ useEffect(() => {
+ if (!enabled) return;
+ const appendUser = (text) => setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));
+ const appendAssistantDelta = (delta) => setHistory((h) => {
+ const last = h[h.length - 1];
+ if (last?.role === 'assistant') {
+ return [...h.slice(0, -1), { role: 'assistant', text: last.text + delta }];
+ }
+ return [...h, { role: 'assistant', text: delta }].slice(-MAX_HISTORY);
+ });
+
+ const restState = () => {
+ if (isWebSpeechCapturing()) return 'listening';
+ if (isContinuous()) return 'handsfree';
+ return 'idle';
+ };
+
+ const offs = [
+ onVoiceEvent('voice:transcript', (d) => {
+ // In web-speech mode, user text is already appended client-side
+ // when onFinal fires. Server echoes it back with source='text' —
+ // skip the duplicate append but still advance the stage.
+ if (d.text && d.source !== 'text') appendUser(d.text);
+ setStage('thinking');
+ }),
+ onVoiceEvent('voice:llm:delta', (d) => {
+ if (d.delta) appendAssistantDelta(d.delta);
+ }),
+ onVoiceEvent('voice:tts:audio', () => {
+ // 'handsfree' is intentionally NOT preserved here — the arrival of
+ // TTS audio means the bot is speaking, so stage must advance.
+ setStage((current) => (
+ current === 'listening' || current === 'capturing' ? current : 'speaking'
+ ));
+ }),
+ onVoiceEvent('voice:idle', (d) => {
+ // voice:idle fires when the server finishes *sending* TTS; local
+ // playback may still be running. Wait for drain so stage doesn't
+ // flip off 'speaking' while audio is still playing.
+ if (d?.reason === 'reset') setHistory([]);
+ whenPlaybackDrained().then(() => {
+ setStage((current) => (ACTIVE_STAGES.has(current) ? current : restState()));
+ });
+ }),
+ onVoiceEvent('voice:error', (d) => {
+ toast.error(`Voice: ${d.message}`);
+ setStage(restState());
+ }),
+ ];
+ return () => offs.forEach((off) => off());
+ }, [enabled]);
+
+ // Auto-scroll to bottom on new content
+ useEffect(() => {
+ if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ }, [history]);
+
+ const handleStart = useCallback(async () => {
+ if (!enabled) return;
+
+ // Web Speech API mode — browser handles STT, sends text directly
+ if (useWebSpeech) {
+ if (isWebSpeechCapturing()) return;
+ setStage('listening');
+ setInterimTranscript('');
+ startWebSpeechCapture({
+ language: sttLanguage,
+ onInterim: (text) => setInterimTranscript(text),
+ onFinal: (text) => {
+ setInterimTranscript('');
+ setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));
+ setStage('thinking');
+ },
+ onError: (err) => {
+ toast.error(`Mic: ${err}`);
+ setStage('idle');
+ },
+ });
+ return;
+ }
+
+ if (handsFree) {
+ if (isContinuous()) return;
+ setStage('handsfree');
+ await startContinuous({
+ onSpeechStart: () => setStage('capturing'),
+ onSpeechEnd: () => setStage('thinking'),
+ onSubmit: ({ submitted, peak }) => {
+ if (!submitted) {
+ setStage('handsfree');
+ return;
+ }
+ warnIfQuiet(peak);
+ },
+ }).catch((err) => {
+ toast.error(`Mic: ${err.message}`);
+ setStage('idle');
+ });
+ return;
+ }
+ if (isCapturing()) return;
+ setStage('listening');
+ await startCapture().catch((err) => {
+ toast.error(`Mic: ${err.message}`);
+ setStage('idle');
+ });
+ }, [enabled, handsFree, useWebSpeech, sttLanguage]);
+
+ const handleStop = useCallback(async () => {
+ if (useWebSpeech) {
+ stopWebSpeechCapture();
+ setInterimTranscript('');
+ setStage('idle');
+ return;
+ }
+ if (handsFree && isContinuous()) {
+ await stopContinuous();
+ setStage('idle');
+ return;
+ }
+ if (!isCapturing()) return;
+ setStage('thinking');
+ const r = await stopCapture().catch((err) => {
+ toast.error(`Mic: ${err.message}`);
+ setStage('idle');
+ return null;
+ });
+ if (!r) {
+ setStage('idle');
+ return;
+ }
+ warnIfQuiet(r.peak);
+ }, [handsFree, useWebSpeech]);
+
+ const handleClear = () => {
+ resetConversation();
+ setHistory([]);
+ };
+
+ const handleSend = useCallback(() => {
+ const text = draft.trim();
+ if (!text) return;
+ setHistory((h) => [...h, { role: 'user', text }].slice(-MAX_HISTORY));
+ sendText(text);
+ setDraft('');
+ setStage('thinking');
+ }, [draft]);
+
+ const toggleCapture = useCallback(() => {
+ if (isWebSpeechCapturing() || isCapturing() || isContinuous()) handleStop();
+ else handleStart();
+ }, [handleStart, handleStop]);
+
+ const toggleHandsFree = useCallback(() => {
+ setHandsFree((prev) => {
+ const next = !prev;
+ window.localStorage.setItem(HANDS_FREE_KEY, next ? '1' : '0');
+ // Discard any in-flight PTT recording — toggling modes mid-utterance
+ // shouldn't send a partial turn to the server.
+ if (isCapturing()) stopCapture({ submit: false });
+ if (isContinuous()) stopContinuous();
+ interrupt();
+ setStage('idle');
+ return next;
+ });
+ }, []);
+
+ // Poll the VAD's current RMS reading while the hands-free mic is live.
+ // Gated on stage !== 'idle' so the interval doesn't tick when the mic is off,
+ // and the setLevel updater is guarded so jitter below ~0.002 doesn't re-render.
+ const pollLevel = handsFree && stage !== 'idle';
+ useEffect(() => {
+ if (!pollLevel) return undefined;
+ const id = setInterval(() => {
+ const v = getVadLevel();
+ setLevel((prev) => (Math.abs(prev - v) > 0.002 ? v : prev));
+ }, 100);
+ return () => clearInterval(id);
+ }, [pollLevel]);
+
+ // Hotkey toggles listening (press once to start, press again to send).
+ // Ignored while focus is on an input/textarea so typing isn't hijacked.
+ useEffect(() => {
+ if (!enabled) return;
+ const isTypingTarget = (el) => {
+ if (!el) return false;
+ const tag = el.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || el.isContentEditable;
+ };
+ const onKey = (e) => {
+ if (e.code !== hotkey || e.repeat) return;
+ if (isTypingTarget(document.activeElement)) return;
+ e.preventDefault();
+ toggleCapture();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [enabled, hotkey, toggleCapture]);
+
+ if (!enabled) return null;
+
+ const { icon: Icon, label, tone } = STAGE[stage] || STAGE.idle;
+ const capturing = ACTIVE_STAGES.has(stage) || isWebSpeechCapturing();
+
+ return (
+ <div className="fixed bottom-4 right-4 z-50 flex flex-col items-end gap-2 w-96 max-w-[calc(100vw-2rem)]">
+ {!collapsed && history.length > 0 && (
+ <div className="bg-port-card/95 backdrop-blur border border-port-border rounded-xl shadow-lg w-full flex flex-col">
+ <div className="flex items-center justify-between px-3 py-1.5 border-b border-port-border/50">
+ <span className="text-xs text-gray-400">Conversation</span>
+ <button
+ onClick={handleClear}
+ title="Clear conversation"
+ className="p-1 rounded text-gray-400 hover:text-port-error hover:bg-port-error/10"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ <div ref={scrollRef} className="text-xs p-3 space-y-2 overflow-y-auto max-h-80">
+ {history.map((turn, i) => (
+ <div key={i} className={turn.role === 'user' ? 'text-gray-400' : 'text-white'}>
+ <span className="text-[10px] uppercase tracking-wide opacity-60 mr-2">
+ {turn.role === 'user' ? 'you' : 'assistant'}
+ </span>
+ {turn.text}
+ </div>
+ ))}
+ {interimTranscript && (
+ <div className="text-gray-500 italic">
+ <span className="text-[10px] uppercase tracking-wide opacity-60 mr-2">you</span>
+ {interimTranscript}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ <form
+ onSubmit={(e) => { e.preventDefault(); handleSend(); }}
+ className="flex items-center gap-1 bg-port-card/95 backdrop-blur border border-port-border rounded-full pl-4 pr-1 py-1 shadow-lg w-full"
+ >
+ <input
+ type="text"
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ placeholder="Type a message…"
+ className="flex-1 bg-transparent text-sm text-white placeholder-gray-500 focus:outline-none"
+ />
+ <button
+ type="submit"
+ disabled={!draft.trim()}
+ title="Send text (Enter)"
+ className="p-2 rounded-full text-gray-400 hover:text-white hover:bg-port-border/70 disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-gray-400"
+ >
+ <Send size={14} />
+ </button>
+ </form>
+ <div className="flex items-center gap-2 bg-port-card/95 backdrop-blur border border-port-border rounded-full pl-3 pr-1 py-1 shadow-lg">
+ <span className={`text-xs ${tone}`}>{label}</span>
+ {!useWebSpeech && handsFree && isContinuous() && (
+ <span
+ className="w-1.5 rounded-full bg-port-accent transition-all"
+ style={{ height: `${Math.min(20, 4 + level * 120)}px` }}
+ title={`mic level ${level.toFixed(3)}`}
+ />
+ )}
+ {!useWebSpeech && (
+ <button
+ onClick={toggleHandsFree}
+ title={handsFree
+ ? 'Hands-free ON — mic stays open, auto-submits on pause, talk over the bot to interrupt. Click to switch to push-to-talk.'
+ : 'Push-to-talk ON — click mic to start, click again to send. Click to switch to hands-free.'}
+ className={`flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-medium ${handsFree
+ ? 'text-port-accent bg-port-accent/10 hover:bg-port-accent/20'
+ : 'text-gray-400 hover:text-white hover:bg-port-border/70'}`}
+ >
+ <InfinityIcon size={12} />
+ {handsFree ? 'hands-free' : 'push-to-talk'}
+ </button>
+ )}
+ {history.length > 0 && (
+ <button
+ onClick={() => setCollapsed((c) => !c)}
+ title={collapsed ? 'Show conversation' : 'Hide conversation'}
+ className="p-1.5 rounded-full text-gray-400 hover:text-white hover:bg-port-border/70"
+ >
+ {collapsed ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
+ </button>
+ )}
+ {stage === 'speaking' && (
+ <button
+ onClick={interrupt}
+ title="Interrupt"
+ className="p-2 rounded-full text-port-error hover:bg-port-error/10"
+ >
+ <Square size={14} />
+ </button>
+ )}
+ <button
+ onClick={toggleCapture}
+ className={`p-3 rounded-full transition-colors ${
+ capturing
+ ? 'bg-port-accent text-white animate-pulse'
+ : 'bg-port-border hover:bg-port-border/70 text-white'
+ }`}
+ title={(() => {
+ if (handsFree) {
+ return capturing
+ ? `Click or press ${hotkey} to stop hands-free listening`
+ : `Click or press ${hotkey} to start hands-free listening`;
+ }
+ return capturing
+ ? `Click or press ${hotkey} to send`
+ : `Click or press ${hotkey} to listen`;
+ })()}
+ >
+ <Icon size={16} />
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index 3bcf970c73..7f1af5b158 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -5,12 +5,14 @@ import { TelegramTab } from '../components/settings/TelegramTab';
import { GeneralTab } from '../components/settings/GeneralTab';
import { ImageGenTab } from '../components/settings/ImageGenTab';
import { MortalLoomTab } from '../components/settings/MortalLoomTab';
+import { VoiceTab } from '../components/settings/VoiceTab';
const TABS = [
{ id: 'general', label: 'General' },
{ id: 'backup', label: 'Backup' },
{ id: 'database', label: 'Database' },
{ id: 'image-gen', label: 'Image Gen' },
+ { id: 'voice', label: 'Voice' },
{ id: 'telegram', label: 'Telegram' },
{ id: 'mortalloom', label: 'MortalLoom' }
];
@@ -30,6 +32,7 @@ export default function Settings() {
case 'backup': return <BackupTab />;
case 'database': return <DatabaseTab />;
case 'image-gen': return <ImageGenTab />;
+ case 'voice': return <VoiceTab />;
case 'telegram': return <TelegramTab />;
case 'mortalloom': return <MortalLoomTab />;
default: return <GeneralTab />;
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index 74b0b564ce..c4d19e3176 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -227,3 +227,15 @@ export const compareTimeCapsuleSnapshots = (id1, id2) => request('/digital-twin/
method: 'POST',
body: JSON.stringify({ id1, id2 })
});
+
+// Soul aliases (used by digital-twin UI components)
+export const createSoulDocument = createDigitalTwinDocument;
+export const updateSoulDocument = updateDigitalTwinDocument;
+export const deleteSoulDocument = deleteDigitalTwinDocument;
+export const updateSoulSettings = updateDigitalTwinSettings;
+export const detectSoulContradictions = detectDigitalTwinContradictions;
+export const submitSoulEnrichAnswer = submitDigitalTwinEnrichAnswer;
+export const runSoulTests = runDigitalTwinTests;
+export const runSoulMultiTests = runDigitalTwinMultiTests;
+export const generateSoulTests = generateDigitalTwinTests;
+export const exportSoul = exportDigitalTwin;
diff --git a/client/src/services/apiVoice.js b/client/src/services/apiVoice.js
new file mode 100644
index 0000000000..668b768b00
--- /dev/null
+++ b/client/src/services/apiVoice.js
@@ -0,0 +1,26 @@
+import api from './apiCore';
+
+export const getVoiceStatus = () => api.get('/voice/status');
+export const getVoiceConfig = () => api.get('/voice/config');
+export const updateVoiceConfig = (patch) => api.put('/voice/config', patch);
+export const listVoices = (engine) => api.get(`/voice/voices${engine ? `?engine=${engine}` : ''}`);
+export const fetchPiperVoice = (voice) => api.post('/voice/piper/fetch', { voice });
+
+// Returns the raw WAV bytes of the test utterance. Optional `voice` and
+// `engine` overrides let the voice-picker preview audition a voice from a
+// different engine than the saved one — without forcing a save first.
+export const testTts = async (text, voice, engine) => {
+ const body = { text };
+ if (voice) body.voice = voice;
+ if (engine) body.engine = engine;
+ const res = await fetch('/api/voice/test', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
+ throw new Error(err.error || 'TTS test failed');
+ }
+ return res.arrayBuffer();
+};
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
new file mode 100644
index 0000000000..4b92c4ffa6
--- /dev/null
+++ b/client/src/services/voiceClient.js
@@ -0,0 +1,675 @@
+// Browser-side voice capture + playback. Supports two modes:
+// - Push-to-talk: MediaRecorder, manual start/stop.
+// - Continuous: AudioWorklet + energy VAD auto-submits on silence,
+// and fires barge-in (voice:interrupt + stopPlayback) when
+// the user starts talking over the bot.
+// Both emit 'voice:turn' over Socket.IO and play incoming TTS via Web Audio.
+
+import socket from './socket';
+
+let stream = null;
+let recorder = null;
+let chunks = [];
+let audioCtx = null;
+let playQueue = Promise.resolve();
+let currentSource = null;
+let ttsQueueDepth = 0;
+// Timestamp after which the post-TTS echo-tail window ends. See VAD.ttsTailMs.
+let ttsCooldownUntil = 0;
+// Raised when a turn is cancelled (barge-in, explicit interrupt, reset, new
+// text turn); cleared when the server emits voice:transcript for the next
+// turn. While raised, incoming voice:tts:audio is dropped — prevents
+// in-flight chunks from the old turn overlaying the new turn's audio.
+let rejectingTts = false;
+
+const pickMime = () => {
+ const candidates = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
+ for (const m of candidates) {
+ if (window.MediaRecorder && window.MediaRecorder.isTypeSupported?.(m)) return m;
+ }
+ return 'audio/webm';
+};
+
+const ensureCtx = () => {
+ if (!audioCtx) {
+ const Ctor = window.AudioContext || window.webkitAudioContext;
+ audioCtx = new Ctor();
+ }
+ if (audioCtx.state === 'suspended') audioCtx.resume();
+ return audioCtx;
+};
+
+const stopPlayback = () => {
+ if (currentSource) {
+ try { currentSource.stop(); } catch { /* already stopped */ }
+ currentSource = null;
+ }
+ playQueue = Promise.resolve();
+ ttsQueueDepth = 0;
+ ttsCooldownUntil = 0;
+ // Any chunks still in-flight from the cancelled turn must not be played —
+ // they'll arrive asynchronously after we've torn down local playback.
+ rejectingTts = true;
+};
+
+// whisper.cpp only accepts 16-bit PCM WAV — it has no built-in audio decoder.
+// Decode whatever MediaRecorder produced, downmix to mono, resample to 16 kHz,
+// and hand-encode a minimal WAV header.
+const TARGET_SAMPLE_RATE = 16000;
+
+const encodePcmToWav = (float32, sampleRate) => {
+ const n = float32.length;
+ const buffer = new ArrayBuffer(44 + n * 2);
+ const view = new DataView(buffer);
+ const writeStr = (off, s) => { for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i)); };
+
+ writeStr(0, 'RIFF');
+ view.setUint32(4, 36 + n * 2, true);
+ writeStr(8, 'WAVE');
+ writeStr(12, 'fmt ');
+ view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true);
+ view.setUint16(22, 1, true);
+ view.setUint32(24, sampleRate, true);
+ view.setUint32(28, sampleRate * 2, true);
+ view.setUint16(32, 2, true);
+ view.setUint16(34, 16, true);
+ writeStr(36, 'data');
+ view.setUint32(40, n * 2, true);
+
+ let off = 44;
+ for (let i = 0; i < n; i++) {
+ const s = Math.max(-1, Math.min(1, float32[i]));
+ view.setInt16(off, s < 0 ? s * 0x8000 : s * 0x7fff, true);
+ off += 2;
+ }
+ return buffer;
+};
+
+const blobToWav16k = async (blob) => {
+ const bytes = await blob.arrayBuffer();
+ const decodeCtx = new (window.AudioContext || window.webkitAudioContext)();
+ // Chain .finally() so a decode failure (unsupported codec, corrupt blob)
+ // still releases the AudioContext — otherwise repeated failures leak a
+ // context per retry.
+ const decoded = await decodeCtx.decodeAudioData(bytes).finally(() => {
+ decodeCtx.close().catch(() => {});
+ });
+
+ // OfflineAudioContext handles resampling natively when we render at the target rate.
+ const frames = Math.ceil(decoded.duration * TARGET_SAMPLE_RATE);
+ const offline = new OfflineAudioContext(1, frames, TARGET_SAMPLE_RATE);
+ const src = offline.createBufferSource();
+ src.buffer = decoded;
+ src.connect(offline.destination);
+ src.start();
+ const rendered = await offline.startRendering();
+ const pcm = rendered.getChannelData(0);
+
+ // Peak amplitude surfaces dead-mic / too-quiet situations that whisper would
+ // otherwise silently transcribe as [BLANK_AUDIO].
+ let peak = 0;
+ for (let i = 0; i < pcm.length; i++) {
+ const a = Math.abs(pcm[i]);
+ if (a > peak) peak = a;
+ }
+
+ return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
+};
+
+const enqueuePlay = async (bytes) => {
+ const ctx = ensureCtx();
+ // decodeAudioData consumes its buffer — clone so we don't mutate the socket frame
+ const copy = bytes.slice(0);
+ const buffer = await ctx.decodeAudioData(copy);
+ ttsQueueDepth += 1;
+ playQueue = playQueue.then(() => new Promise((resolve) => {
+ const src = ctx.createBufferSource();
+ src.buffer = buffer;
+ src.connect(ctx.destination);
+ src.onended = () => {
+ if (currentSource === src) currentSource = null;
+ ttsQueueDepth = Math.max(0, ttsQueueDepth - 1);
+ // Skip the tail when we're rejecting (playback was torn down) —
+ // there's no real audio left for a room echo to trail off from.
+ if (ttsQueueDepth === 0 && !rejectingTts) {
+ ttsCooldownUntil = performance.now() + VAD.ttsTailMs;
+ }
+ resolve();
+ };
+ currentSource = src;
+ src.start();
+ }));
+};
+
+const isTtsActive = () => ttsQueueDepth > 0 || currentSource !== null;
+const isInTtsEchoWindow = () => isTtsActive() || performance.now() < ttsCooldownUntil;
+
+// socket.io may deliver a plain ArrayBuffer, a sliced TypedArray/DataView,
+// or a serialized Buffer-like { type: 'Buffer', data: [...] }. Using the raw
+// `wav.buffer` for a sliced view would pass extra bytes to decodeAudioData,
+// causing intermittent decode failures; always hand off an exact slice.
+const toExactArrayBuffer = (wav) => {
+ if (wav instanceof ArrayBuffer) return wav;
+ if (ArrayBuffer.isView(wav)) {
+ return wav.buffer.slice(wav.byteOffset, wav.byteOffset + wav.byteLength);
+ }
+ if (wav?.type === 'Buffer' && Array.isArray(wav.data)) {
+ return new Uint8Array(wav.data).buffer;
+ }
+ return null;
+};
+
+socket.on('voice:tts:audio', ({ wav }) => {
+ if (rejectingTts) return; // stale chunk from a cancelled turn — drop it
+ const ab = toExactArrayBuffer(wav);
+ if (!ab) return;
+ enqueuePlay(ab).catch((err) => console.warn('[voice] playback failed:', err));
+});
+
+// voice:transcript marks the start of a new turn's outputs — any pending
+// rejection from a previous cancellation should be lifted now so this turn's
+// TTS chunks actually play.
+socket.on('voice:transcript', () => { rejectingTts = false; });
+
+export const startCapture = async () => {
+ if (recorder) return;
+ // Barge-in: abort any in-flight turn and silence current playback
+ socket.emit('voice:interrupt');
+ stopPlayback();
+
+ // autoGainControl is critical — without it, quiet mics record near-silent audio
+ // that whisper transcribes as [BLANK_AUDIO].
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ },
+ });
+ const mimeType = pickMime();
+ chunks = [];
+ recorder = new MediaRecorder(stream, { mimeType });
+ recorder.addEventListener('dataavailable', (e) => { if (e.data.size > 0) chunks.push(e.data); });
+ recorder.start(250);
+ return { mimeType };
+};
+
+export const stopCapture = async ({ submit = true } = {}) => {
+ if (!recorder) return null;
+ const rec = recorder;
+ recorder = null;
+
+ await new Promise((resolve) => {
+ rec.addEventListener('stop', resolve, { once: true });
+ rec.stop();
+ });
+ stream?.getTracks().forEach((t) => t.stop());
+ stream = null;
+
+ const blob = new Blob(chunks, { type: rec.mimeType });
+ chunks = [];
+ // Mode-switch cancellation (e.g. user toggled hands-free mid-utterance):
+ // drop the buffered audio instead of submitting a partial sentence.
+ if (!submit) return null;
+ if (blob.size < 800) return null; // discard sub-25ms empty recordings
+
+ const { wav, peak } = await blobToWav16k(blob);
+ socket.emit('voice:turn', { audio: wav, mimeType: 'audio/wav' });
+ return { mimeType: 'audio/wav', size: wav.byteLength, sourceSize: blob.size, peak };
+};
+
+export const sendText = (text) => {
+ const trimmed = (text || '').trim();
+ if (!trimmed) return;
+ stopPlayback();
+ socket.emit('voice:text', { text: trimmed });
+};
+
+export const interrupt = () => {
+ socket.emit('voice:interrupt');
+ stopPlayback();
+};
+
+export const resetConversation = () => {
+ socket.emit('voice:reset');
+ stopPlayback();
+};
+
+export const isCapturing = () => recorder !== null;
+
+/**
+ * Subscribe to voice events. Returns an unsubscribe function.
+ * Events: voice:transcript, voice:llm:delta, voice:llm:done, voice:error, voice:idle
+ */
+export const onVoiceEvent = (event, handler) => {
+ socket.on(event, handler);
+ return () => socket.off(event, handler);
+};
+
+export const playWav = (arrayBuffer) => enqueuePlay(arrayBuffer);
+
+// Resolves once every currently-queued TTS chunk has finished playing locally.
+// Used by continuous mode to know when to return from 'speaking' → listening.
+export const whenPlaybackDrained = () => playQueue.then(() => !isTtsActive());
+
+// ─── Continuous mode (hands-free VAD) ─────────────────────────────────────
+// AudioWorklet streams PCM, RMS-based VAD auto-submits on silence, and
+// barge-in (voice:interrupt + stopPlayback) fires when the user talks over
+// the bot. Thresholds are auto-calibrated from ambient noise at startup.
+
+const VAD = {
+ minOnRms: 0.010,
+ minOffRms: 0.005,
+ maxOnRms: 0.060,
+ silenceMs: 600, // silence duration that ends a turn
+ minSpeechMs: 250, // ignore utterances shorter than this (noise blips)
+ preRollMs: 250, // audio kept before detected speech start
+ onsetConfirmMs: 80, // frames required above onRms before firing speech-start
+ calibrationMs: 600, // ambient-noise sampling window at startup
+ bargeInMul: 1.15, // small bump over onRms during TTS to dampen echo
+ // bleed. Higher blocks real speech with calibrated
+ // thresholds; lower trusts echoCancellation alone.
+ ttsTailMs: 300, // echo-tail window: keep bargeInMul active for this
+ // long after the last TTS chunk ends to ignore reverb.
+ maxSpeechMs: 15000, // runaway-speech watchdog: if silence never registers
+ // (noisy env, stuck state), force submit/discard.
+ debug: false, // window.__portosVadDebug = true to enable logging
+};
+
+// Live thresholds (set by calibration, then static for the session).
+let onRms = VAD.minOnRms;
+let offRms = VAD.minOffRms;
+let calibrating = false;
+let calibrationSamples = [];
+let calibrationUntil = 0;
+
+let lastRmsValue = 0;
+let lastDebugLogAt = 0;
+
+let continuousCtx = null;
+let continuousStream = null;
+let continuousWorkletNode = null;
+let continuousSource = null;
+let continuousCallbacks = null;
+let vadState = 'idle';
+let speechChunks = [];
+// Fixed-size ring buffer of the last `preRollLimit` frames; avoids the
+// O(n) Array.shift() that would otherwise run ~375 times/second.
+let preRoll = null;
+let preRollLimit = 0;
+let preRollIdx = 0;
+let preRollFilled = 0;
+let silenceStartedAt = 0;
+let speechStartedAt = 0;
+let onsetFrames = 0;
+
+const WORKLET_SOURCE = `
+class VADProcessor extends AudioWorkletProcessor {
+ process(inputs) {
+ const ch = inputs[0] && inputs[0][0];
+ if (ch && ch.length) this.port.postMessage(ch.slice(0));
+ return true;
+ }
+}
+registerProcessor('vad-processor', VADProcessor);
+`;
+
+const float32ToWav16k = async (samples, sourceRate) => {
+ if (!samples.length) return { wav: null, peak: 0 };
+ const frames = Math.ceil(samples.length * TARGET_SAMPLE_RATE / sourceRate);
+ const offline = new OfflineAudioContext(1, frames, TARGET_SAMPLE_RATE);
+ const buf = offline.createBuffer(1, samples.length, sourceRate);
+ buf.getChannelData(0).set(samples);
+ const src = offline.createBufferSource();
+ src.buffer = buf;
+ src.connect(offline.destination);
+ src.start();
+ const rendered = await offline.startRendering();
+ const pcm = rendered.getChannelData(0);
+
+ let peak = 0;
+ for (let i = 0; i < pcm.length; i++) {
+ const a = Math.abs(pcm[i]);
+ if (a > peak) peak = a;
+ }
+ return { wav: encodePcmToWav(pcm, TARGET_SAMPLE_RATE), peak };
+};
+
+const submitUtterance = async () => {
+ if (!speechChunks.length) return;
+ const chunksToSubmit = speechChunks;
+ speechChunks = [];
+
+ const total = chunksToSubmit.reduce((n, c) => n + c.length, 0);
+ const samples = new Float32Array(total);
+ let off = 0;
+ for (const c of chunksToSubmit) { samples.set(c, off); off += c.length; }
+
+ const rate = continuousCtx?.sampleRate || 48000;
+ const { wav, peak } = await float32ToWav16k(samples, rate);
+ if (!wav || wav.byteLength < 800) {
+ continuousCallbacks?.onSubmit?.({ submitted: false, peak });
+ return;
+ }
+ socket.emit('voice:turn', { audio: wav, mimeType: 'audio/wav' });
+ continuousCallbacks?.onSubmit?.({ submitted: true, peak, size: wav.byteLength });
+};
+
+const finishCalibration = () => {
+ calibrating = false;
+ const samples = calibrationSamples;
+ calibrationSamples = [];
+ if (!samples.length) return;
+ samples.sort((a, b) => a - b);
+ // Median is robust if the user accidentally speaks during calibration —
+ // up to ~50% of frames can be speech without poisoning the floor estimate.
+ const floor = samples[Math.floor(samples.length * 0.5)] ?? samples[samples.length - 1];
+ offRms = Math.max(VAD.minOffRms, floor * 2.0);
+ onRms = Math.min(VAD.maxOnRms, Math.max(VAD.minOnRms, floor * 4.0, offRms * 2));
+ // eslint-disable-next-line no-console
+ console.log(`🎙️ [vad] calibrated floor=${floor.toFixed(4)} → on=${onRms.toFixed(4)} off=${offRms.toFixed(4)}`);
+};
+
+const snapshotPreRoll = () => {
+ if (!preRollFilled) return [];
+ const out = new Array(preRollFilled);
+ const start = preRollFilled < preRollLimit ? 0 : preRollIdx;
+ for (let i = 0; i < preRollFilled; i++) out[i] = preRoll[(start + i) % preRollLimit];
+ return out;
+};
+
+const handleFrame = (frame) => {
+ let sum = 0;
+ for (let i = 0; i < frame.length; i++) sum += frame[i] * frame[i];
+ const rms = Math.sqrt(sum / frame.length);
+ lastRmsValue = rms;
+
+ preRoll[preRollIdx] = frame;
+ preRollIdx = (preRollIdx + 1) % preRollLimit;
+ if (preRollFilled < preRollLimit) preRollFilled += 1;
+
+ const now = performance.now();
+
+ if (calibrating) {
+ calibrationSamples.push(rms);
+ if (now >= calibrationUntil) finishCalibration();
+ else return;
+ }
+
+ if (VAD.debug && now - lastDebugLogAt > 250) {
+ lastDebugLogAt = now;
+ // eslint-disable-next-line no-console
+ console.log(`[vad] state=${vadState} rms=${rms.toFixed(4)} on=${onRms.toFixed(4)} off=${offRms.toFixed(4)} tts=${isTtsActive()}`);
+ }
+
+ if (vadState === 'idle') {
+ // Raise the bar while TTS plays AND during the echo tail so neither the
+ // bot's live audio nor reverb through the mic trigger a false barge-in.
+ const effectiveOnRms = isInTtsEchoWindow() ? onRms * VAD.bargeInMul : onRms;
+ if (rms > effectiveOnRms) {
+ onsetFrames += 1;
+ const frameMs = (frame.length / (continuousCtx?.sampleRate || 48000)) * 1000;
+ if (onsetFrames * frameMs >= VAD.onsetConfirmMs) {
+ // Confirmed speech onset — barge-in + start capturing
+ vadState = 'speaking';
+ speechStartedAt = now;
+ silenceStartedAt = 0;
+ onsetFrames = 0;
+ if (isTtsActive()) {
+ socket.emit('voice:interrupt');
+ stopPlayback();
+ }
+ speechChunks = snapshotPreRoll();
+ continuousCallbacks?.onSpeechStart?.();
+ }
+ } else {
+ onsetFrames = 0;
+ }
+ return;
+ }
+
+ // state === 'speaking'
+ speechChunks.push(frame);
+
+ // Watchdog: if silence never crosses offRms (e.g. noisy env, echo tail,
+ // stuck mic), force the turn to end so VAD doesn't jam here forever.
+ if (now - speechStartedAt >= VAD.maxSpeechMs) {
+ vadState = 'idle';
+ silenceStartedAt = 0;
+ onsetFrames = 0;
+ continuousCallbacks?.onSpeechEnd?.();
+ if (speechChunks.length) {
+ submitUtterance().catch((err) => console.warn('[voice] watchdog submit failed:', err));
+ } else {
+ continuousCallbacks?.onSubmit?.({ submitted: false, peak: 0, discarded: true });
+ }
+ return;
+ }
+
+ if (rms < offRms) {
+ if (!silenceStartedAt) silenceStartedAt = now;
+ if (now - silenceStartedAt >= VAD.silenceMs) {
+ const speechMs = silenceStartedAt - speechStartedAt;
+ vadState = 'idle';
+ silenceStartedAt = 0;
+ onsetFrames = 0;
+ continuousCallbacks?.onSpeechEnd?.();
+ if (speechMs >= VAD.minSpeechMs) {
+ submitUtterance().catch((err) => console.warn('[voice] submit failed:', err));
+ } else {
+ // Too short to submit — notify the widget so it leaves 'thinking'
+ // instead of waiting for a server response that won't arrive.
+ speechChunks = [];
+ continuousCallbacks?.onSubmit?.({ submitted: false, peak: 0, discarded: true });
+ }
+ }
+ } else {
+ silenceStartedAt = 0;
+ }
+};
+
+export const startContinuous = async (callbacks = {}) => {
+ if (continuousCtx) return;
+ continuousCallbacks = callbacks;
+
+ // AGC is intentionally OFF here — it boosts silence to maintain a target
+ // output level, which destroys the energy-difference signal the VAD needs.
+ continuousStream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: false,
+ },
+ });
+
+ const Ctor = window.AudioContext || window.webkitAudioContext;
+ continuousCtx = new Ctor();
+ if (continuousCtx.state === 'suspended') await continuousCtx.resume();
+
+ // Inline worklet module so we don't need a separate file in the build
+ const blobUrl = URL.createObjectURL(new Blob([WORKLET_SOURCE], { type: 'application/javascript' }));
+ await continuousCtx.audioWorklet.addModule(blobUrl);
+ URL.revokeObjectURL(blobUrl);
+
+ continuousSource = continuousCtx.createMediaStreamSource(continuousStream);
+ continuousWorkletNode = new AudioWorkletNode(continuousCtx, 'vad-processor');
+
+ const sampleRate = continuousCtx.sampleRate;
+ preRollLimit = Math.max(1, Math.ceil((VAD.preRollMs / 1000) * sampleRate / 128));
+ preRoll = new Array(preRollLimit);
+ preRollIdx = 0;
+ preRollFilled = 0;
+ speechChunks = [];
+ vadState = 'idle';
+ silenceStartedAt = 0;
+ speechStartedAt = 0;
+ onsetFrames = 0;
+ calibrating = true;
+ calibrationSamples = [];
+ calibrationUntil = performance.now() + VAD.calibrationMs;
+ onRms = VAD.minOnRms;
+ offRms = VAD.minOffRms;
+
+ continuousWorkletNode.port.onmessage = (e) => handleFrame(e.data);
+ continuousSource.connect(continuousWorkletNode);
+ // Worklet output must be pulled by the graph or process() stops running;
+ // sinking through a zero-gain node keeps it alive without echoing the mic.
+ const sink = continuousCtx.createGain();
+ sink.gain.value = 0;
+ continuousWorkletNode.connect(sink).connect(continuousCtx.destination);
+};
+
+export const stopContinuous = async () => {
+ if (!continuousCtx) return;
+ try {
+ continuousSource?.disconnect();
+ continuousWorkletNode?.disconnect();
+ continuousWorkletNode && (continuousWorkletNode.port.onmessage = null);
+ } catch { /* ignore teardown errors */ }
+ continuousStream?.getTracks().forEach((t) => t.stop());
+ await continuousCtx.close().catch(() => {});
+ continuousCtx = null;
+ continuousStream = null;
+ continuousWorkletNode = null;
+ continuousSource = null;
+ speechChunks = [];
+ preRoll = null;
+ preRollIdx = 0;
+ preRollFilled = 0;
+ vadState = 'idle';
+ onsetFrames = 0;
+ calibrating = false;
+ calibrationSamples = [];
+ continuousCallbacks = null;
+};
+
+export const isContinuous = () => continuousCtx !== null;
+
+export const getVadLevel = () => lastRmsValue;
+
+// Toggle verbose VAD logging at runtime: window.__portosVadDebug = true
+if (typeof window !== 'undefined') {
+ Object.defineProperty(window, '__portosVadDebug', {
+ configurable: true,
+ get: () => VAD.debug,
+ set: (v) => { VAD.debug = !!v; },
+ });
+}
+
+// ─── Web Speech API mode ─────────────────────────────────────────────────
+// Browser-native STT via SpeechRecognition. Transcription happens entirely
+// in the browser — no whisper.cpp server needed. Final transcripts are sent
+// as voice:text (reusing the existing text-input path on the server).
+
+const SpeechRecognition = typeof window !== 'undefined'
+ && (window.SpeechRecognition || window.webkitSpeechRecognition);
+
+let webSpeechRecognition = null;
+let webSpeechShouldListen = false;
+let webSpeechCallbacks = null;
+// Chrome fires onend immediately when a mic error, OS permission flicker, or
+// driver glitch prevents recognition from ever binding. Blindly calling
+// start() from onend in that state hot-loops the CPU. Count consecutive
+// restarts that never produced a result and back off.
+let webSpeechRestartFailures = 0;
+let webSpeechRestartTimer = null;
+const WEB_SPEECH_MAX_RESTART_FAILURES = 5;
+
+export const webSpeechSupported = !!SpeechRecognition;
+
+// BCP-47 tag that SpeechRecognition expects. Short codes like 'en' → 'en-US',
+// 'es' → 'es-ES', 'fr' → 'fr-FR'. Anything already region-tagged or unknown
+// passes through; finally fall back to navigator.language then en-US.
+const SHORT_LANG_TO_BCP47 = { en: 'en-US', es: 'es-ES', fr: 'fr-FR', de: 'de-DE', it: 'it-IT', pt: 'pt-BR', ja: 'ja-JP', ko: 'ko-KR', zh: 'zh-CN' };
+const resolveRecognitionLang = (configured) => {
+ const raw = (configured || '').trim();
+ if (raw.includes('-')) return raw;
+ if (raw && SHORT_LANG_TO_BCP47[raw.toLowerCase()]) return SHORT_LANG_TO_BCP47[raw.toLowerCase()];
+ if (typeof navigator !== 'undefined' && navigator.language) return navigator.language;
+ return 'en-US';
+};
+
+export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {
+ if (!SpeechRecognition) return;
+ stopWebSpeechCapture();
+
+ // Barge-in: abort any in-flight turn and silence current playback
+ socket.emit('voice:interrupt');
+ stopPlayback();
+
+ const recognition = new SpeechRecognition();
+ recognition.continuous = true;
+ recognition.interimResults = true;
+ // Honor cfg.stt.language (threaded in by VoiceWidget) so a user on a
+ // non-English locale doesn't silently get US English STT.
+ recognition.lang = resolveRecognitionLang(language);
+
+ recognition.onresult = (event) => {
+ let interim = '';
+ let final = '';
+ for (let i = event.resultIndex; i < event.results.length; i++) {
+ const transcript = event.results[i][0].transcript;
+ if (event.results[i].isFinal) {
+ final += transcript;
+ } else {
+ interim += transcript;
+ }
+ }
+ if (interim) callbacks.onInterim?.(interim);
+ if (final) {
+ callbacks.onInterim?.('');
+ callbacks.onFinal?.(final);
+ // Any successful result resets the restart-failure counter.
+ webSpeechRestartFailures = 0;
+ // Send as text — server pipeline skips STT and goes straight to LLM
+ sendText(final);
+ }
+ };
+
+ recognition.onend = () => {
+ if (!webSpeechShouldListen) return;
+ webSpeechRestartFailures += 1;
+ if (webSpeechRestartFailures >= WEB_SPEECH_MAX_RESTART_FAILURES) {
+ webSpeechShouldListen = false;
+ callbacks.onError?.('restart-loop');
+ return;
+ }
+ // Exponential backoff (50ms → 800ms) so a broken driver doesn't pin the CPU.
+ const delay = Math.min(50 * 2 ** (webSpeechRestartFailures - 1), 800);
+ clearTimeout(webSpeechRestartTimer);
+ webSpeechRestartTimer = setTimeout(() => {
+ if (webSpeechShouldListen && webSpeechRecognition === recognition) {
+ recognition.start();
+ }
+ }, delay);
+ };
+
+ recognition.onerror = (event) => {
+ if (event.error === 'not-allowed' || event.error === 'service-not-allowed') {
+ webSpeechShouldListen = false;
+ callbacks.onError?.(event.error);
+ }
+ // "no-speech" and "aborted" are expected, ignore them
+ };
+
+ webSpeechRecognition = recognition;
+ webSpeechShouldListen = true;
+ webSpeechCallbacks = callbacks;
+ webSpeechRestartFailures = 0;
+ recognition.start();
+};
+
+export const stopWebSpeechCapture = () => {
+ webSpeechShouldListen = false;
+ clearTimeout(webSpeechRestartTimer);
+ webSpeechRestartTimer = null;
+ webSpeechRestartFailures = 0;
+ if (webSpeechRecognition) {
+ webSpeechRecognition.stop();
+ webSpeechRecognition = null;
+ }
+ webSpeechCallbacks = null;
+};
+
+export const isWebSpeechCapturing = () => webSpeechShouldListen;
diff --git a/data.sample/settings.json b/data.sample/settings.json
index 196af5e23d..886b4de05a 100644
--- a/data.sample/settings.json
+++ b/data.sample/settings.json
@@ -1,3 +1,49 @@
{
- "timezone": "America/Los_Angeles"
+ "timezone": "America/Los_Angeles",
+ "voice": {
+ "enabled": false,
+ "trigger": "push-to-talk",
+ "hotkey": "Space",
+ "stt": {
+ "engine": "web-speech",
+ "endpoint": "http://127.0.0.1:5562",
+ "model": "base.en",
+ "modelPath": "~/.portos/voice/models/ggml-base.en.bin",
+ "language": "en",
+ "coreml": false,
+ "vocabularyPrompt": ""
+ },
+ "tts": {
+ "engine": "kokoro",
+ "rate": 1.0,
+ "kokoro": {
+ "modelId": "onnx-community/Kokoro-82M-v1.0-ONNX",
+ "dtype": "q8",
+ "voice": "af_heart"
+ },
+ "piper": {
+ "voice": "en_GB-jenny_dioco-medium",
+ "voicePath": "~/.portos/voice/voices/en_GB-jenny_dioco-medium.onnx",
+ "speakerId": null
+ }
+ },
+ "llm": {
+ "provider": "lmstudio",
+ "model": "auto",
+ "systemPrompt": "You are the PortOS assistant. Your replies are spoken aloud — keep them short and use plain prose (no markdown or lists).",
+ "usePersonality": true,
+ "personality": {
+ "name": "Alfred",
+ "role": "Chief of Staff",
+ "traits": ["concise", "warm", "proactive"],
+ "speechStyle": "casual and brief",
+ "customPrompt": ""
+ },
+ "tools": {
+ "enabled": false,
+ "maxIterations": 3
+ }
+ },
+ "vad": { "endOfSpeechMs": 700, "minUtteranceMs": 250 }
+ }
}
\ No newline at end of file
diff --git a/docs/features/voice.md b/docs/features/voice.md
new file mode 100644
index 0000000000..7e798fa1d0
--- /dev/null
+++ b/docs/features/voice.md
@@ -0,0 +1,131 @@
+# Voice Mode
+
+PortOS includes an optional voice assistant with support for fully local operation. Supports push-to-talk and hands-free continuous mode with barge-in (start speaking over a reply to interrupt it).
+
+**Privacy note:** LLM, TTS, and pipeline orchestration always run locally. For speech-to-text, the default **Web Speech API** uses your browser's built-in recognition service — in Chrome/Chromium this forwards audio to a Google cloud endpoint. Switch `stt.engine` to **`whisper`** (whisper.cpp, local HTTP server) under *Settings → Voice* for fully-offline STT with no audio leaving the machine.
+
+## Stack
+
+| Stage | Default engine | Alternatives | Local? |
+|-------|----------------|--------------|--------|
+| Speech-to-text | Browser [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API) (default — **note**: Chromium browsers forward audio to a vendor cloud speech service) or [whisper.cpp](https://github.com/ggerganov/whisper.cpp) via `whisper-server` (HTTP :5562, fully local) | — | ✅ (whisper) / ⚠️ (web-speech) |
+| LLM | LM Studio (`/v1/chat/completions`) | OpenAI-compatible local server | ✅ |
+| Text-to-speech | [Kokoro-82M](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX) via `kokoro-js` (in-process) | [Piper](https://github.com/rhasspy/piper) (CLI) | ✅ |
+| Voice activity | AudioWorklet + RMS VAD (hands-free) or `MediaRecorder` (push-to-talk) — Web Speech mode bypasses server audio and posts final text via `voice:text` | — | ✅ |
+
+The TTS engine is selectable in **Settings → Voice → TTS engine**.
+
+### Why Kokoro is the default
+
+Kokoro is a 82M-parameter frontier TTS model that runs in-process via ONNX Runtime + transformers.js — **no Python, no extra binaries, cross-platform**. Quality is significantly higher than Piper (more natural prosody, expressive pacing). First synthesis after server start has a 2–3 s cold start as the model loads; warm calls are 200–500 ms per sentence on CPU.
+
+Use **Piper** instead if you need lower latency per call (~100 ms cold start), are on a memory-constrained machine, or want a particular pre-trained voice from rhasspy's catalogue.
+
+## First-time setup
+
+1. Open PortOS → **Settings → Voice**.
+2. Pick your TTS engine (default: Kokoro), Whisper model size, and CoreML toggle (macOS).
+3. Toggle **Enable voice mode** and click **Save & Reconcile**.
+
+PortOS will:
+- Install `whisper-cpp` via Homebrew if missing (the whisper.cpp binary + its base models)
+- Download the selected Whisper ggml `.bin` model into `~/.portos/voice/models/`
+- On macOS with CoreML enabled, download the matching `<model>-encoder.mlmodelc` (2–3× faster STT on Apple Silicon, requires a custom whisper.cpp build)
+- If Piper is selected, download the pre-built Piper binary + phonemize libs from [rhasspy/piper](https://github.com/rhasspy/piper) and [rhasspy/piper-phonemize](https://github.com/rhasspy/piper-phonemize) GitHub Releases (Piper is not on Homebrew), then fetch the selected voice `.onnx` into `~/.portos/voice/voices/`
+- Start `portos-whisper` under PM2
+
+Kokoro models live under `~/.cache/huggingface/hub/` and download lazily on first synthesis.
+
+You can also run the bootstrap script directly:
+
+```bash
+TTS_ENGINE=kokoro INSTALL_COREML=1 bash scripts/setup-voice.sh
+TTS_ENGINE=piper VOICE_NAME=en_US-ryan-high bash scripts/setup-voice.sh
+MODEL_NAME=ggml-small.en.bin bash scripts/setup-voice.sh
+```
+
+## Configuration options
+
+All options live in `data/settings.json` under `voice` (Settings UI patches this file).
+
+| Option | Default | Notes |
+|--------|---------|-------|
+| `enabled` | `false` | Master toggle. Triggers reconcile on change. |
+| `hotkey` | `Space` | Held to talk. Ignored while typing in inputs. |
+| `stt.model` | `base.en` | `tiny.en` · `base.en` · `small.en` · `medium.en` · `large-v3` |
+| `stt.coreml` | `false` | Optional on macOS. Enable to use the CoreML encoder companion (requires a custom whisper.cpp build with `-DWHISPER_COREML=1`). |
+| `stt.endpoint` | `http://127.0.0.1:5562` | whisper-server listen address (whisper engine only). |
+| `tts.engine` | `kokoro` | `kokoro` or `piper` |
+| `tts.rate` | `1.0` | Speech rate, 0.5–2.0 |
+| `tts.kokoro.voice` | `af_heart` | See [Kokoro voices](https://huggingface.co/onnx-community/Kokoro-82M-v1.0-ONNX) — A-grade are `af_heart`, `af_bella`. |
+| `tts.kokoro.dtype` | `q8` | `q4` · `q8` · `fp16` · `fp32` (size/quality trade-off) |
+| `tts.kokoro.modelId` | `onnx-community/Kokoro-82M-v1.0-ONNX` | HuggingFace repo id |
+| `tts.piper.voice` | `en_GB-jenny_dioco-medium` | Piper voice id (path-encoded) |
+| `tts.piper.voicePath` | `~/.portos/voice/voices/<voice>.onnx` | ONNX file location |
+| `llm.model` | `auto` | `auto` picks first loaded LM Studio model |
+| `llm.systemPrompt` | (concise voice prompt) | Edit to change personality |
+
+## Using voice mode
+
+Two modes, toggle with the headset icon in the voice widget:
+
+- **Push-to-talk**: click/hold the mic or hold the configured hotkey. Release to send. The hotkey ignores keypresses while an input/textarea is focused.
+- **Hands-free**: the mic stays live; an AudioWorklet computes an RMS envelope and auto-submits once you've been silent for `vad.endOfSpeechMs` (default 700 ms). Ambient noise is calibrated at session start.
+
+Either mode: start speaking while the assistant is replying to interrupt it (barge-in). Click the square button to stop current TTS playback without sending a new turn.
+
+With `stt.engine = 'web-speech'` the browser's SpeechRecognition handles STT entirely client-side; PortOS sends the final transcript as `voice:text` instead of shipping audio, which skips whisper.cpp and avoids a 250–800 ms server-side round-trip.
+
+## Architecture
+
+```
+browser mic → MediaRecorder (PTT) OR AudioWorklet + RMS VAD (hands-free)
+ → Socket.IO 'voice:turn' (audio) OR 'voice:text' (Web Speech final)
+ → whisper.cpp /inference (STT for audio path)
+ → LM Studio /v1/chat (streaming) (LLM)
+ → sentence-boundary TTS dispatch (Kokoro in-process | Piper CLI)
+ → Socket.IO 'voice:tts:audio' → Web Audio playback queue
+```
+
+Pipeline orchestration: `server/services/voice/pipeline.js`. The pipeline emits events as it runs:
+
+- `voice:transcript` — STT result
+- `voice:llm:delta` — each token delta from LM Studio
+- `voice:llm:done` — full assistant reply
+- `voice:tts:audio` — one WAV per sentence as soon as TTS finishes it
+- `voice:idle` — turn complete (or interrupted)
+
+Barge-in works by aborting the shared `AbortController` tied to the current turn — the LLM stream is torn down and any queued TTS is discarded.
+
+## Endpoints
+
+| Method | Path | Purpose |
+|--------|------|---------|
+| GET | `/api/voice/status` | Health probes + active engines + binary/model presence |
+| GET | `/api/voice/config` | Current merged voice config |
+| PUT | `/api/voice/config` | Deep-merge patch; triggers PM2 + setup reconcile |
+| GET | `/api/voice/voices` | Voices for the active TTS engine |
+| POST | `/api/voice/test` | Body `{ text }`, returns WAV bytes — verifies TTS |
+
+Socket events are documented in `server/sockets/voice.js`.
+
+## Troubleshooting
+
+- **Whisper badge red** — `brew install whisper-cpp`, then `which whisper-server`.
+- **CoreML missing** — re-run `INSTALL_COREML=1 bash scripts/setup-voice.sh` (or toggle voice off/on after enabling CoreML).
+- **Kokoro shows `lazy`** — model loads on first synthesis. Hit "Test voice" to warm it up.
+- **Kokoro slow on first call** — first call after server start downloads model (~80 MB for q8) and initializes the runtime. Subsequent calls are 200–500 ms.
+- **Piper spawn fails** — `which piper` and check voice file at `~/.portos/voice/voices/<name>.onnx`.
+- **LM Studio red** — start LM Studio and load a chat model; the voice pipeline uses `/v1/chat/completions`.
+- **No audio playback** — browsers require a user gesture before AudioContext can play. Click the page once or press the mic button.
+
+## Performance notes
+
+| Engine | Cold start | Warm latency (per sentence) | Quality |
+|--------|------------|------------------------------|---------|
+| Kokoro q8 (CPU) | 2–3 s | 200–500 ms | High |
+| Kokoro fp32 (CPU) | 3–5 s | 400–900 ms | Highest |
+| Piper | ~100 ms (CLI spawn) | ~100 ms | Mid |
+| Whisper base.en (no CoreML) | 0 (server resident) | 400–800 ms / 2 s of audio | Good |
+| Whisper base.en + CoreML | 0 | 150–300 ms / 2 s of audio | Good |
+| Whisper small.en + CoreML | 0 | 300–600 ms / 2 s of audio | Better |
diff --git a/scripts/setup-voice.sh b/scripts/setup-voice.sh
new file mode 100755
index 0000000000..e1c050233d
--- /dev/null
+++ b/scripts/setup-voice.sh
@@ -0,0 +1,149 @@
+#!/usr/bin/env bash
+# Bootstrap local voice stack: whisper.cpp (STT) + active TTS backend.
+# Safe to re-run: installs only what's missing, downloads only what's missing.
+#
+# Env overrides:
+# STT_ENGINE 'whisper' (default) | 'web-speech' — browser-native STT
+# skips whisper-cpp install + model download entirely
+# MODEL_NAME Whisper GGUF to fetch (default: ggml-base.en.bin)
+# VOICE_NAME Piper voice name (default: en_GB-jenny_dioco-medium) — only used when TTS_ENGINE=piper
+# TTS_ENGINE 'kokoro' (default) | 'piper'
+# INSTALL_COREML '1' to download CoreML encoder for Whisper on macOS (default: 0)
+#
+# Models live under ~/.portos/voice/{models,voices}/. Kokoro models are managed
+# automatically by transformers.js under ~/.cache/huggingface/.
+
+set -euo pipefail
+
+VOICE_HOME="${HOME}/.portos/voice"
+MODELS_DIR="${VOICE_HOME}/models"
+VOICES_DIR="${VOICE_HOME}/voices"
+MODEL_NAME="${MODEL_NAME:-ggml-base.en.bin}"
+VOICE_NAME="${VOICE_NAME:-en_GB-jenny_dioco-medium}"
+TTS_ENGINE="${TTS_ENGINE:-kokoro}"
+STT_ENGINE="${STT_ENGINE:-whisper}"
+INSTALL_COREML="${INSTALL_COREML:-0}"
+
+mkdir -p "$MODELS_DIR" "$VOICES_DIR"
+
+have() { command -v "$1" >/dev/null 2>&1; }
+is_macos() { [[ "$(uname -s)" == "Darwin" ]]; }
+
+install_brew_pkg() {
+ local pkg="$1"
+ if ! have brew; then
+ echo "❌ Homebrew not found. Install from https://brew.sh then re-run." >&2
+ exit 1
+ fi
+ echo "📦 brew install $pkg"
+ brew install "$pkg"
+}
+
+# whisper.cpp provides whisper-cli + whisper-server binaries. Skip entirely
+# when STT runs in the browser via Web Speech — no server-side STT needed.
+if [[ "$STT_ENGINE" == "whisper" ]]; then
+ if ! have whisper-server; then
+ install_brew_pkg whisper-cpp
+ fi
+else
+ echo "ℹ️ STT_ENGINE=${STT_ENGINE} — skipping whisper-cpp install and model download"
+fi
+
+# piper TTS binary (only when active engine uses it)
+# Not available via Homebrew — download pre-built binary + phonemize libs from
+# GitHub releases. The piper binary links against libespeak-ng, libpiper_phonemize,
+# and libonnxruntime at specific versions bundled in the piper-phonemize release.
+PIPER_DIR="${VOICE_HOME}/piper"
+PIPER_LIB="${PIPER_DIR}/lib"
+if [[ "$TTS_ENGINE" == "piper" ]]; then
+ OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
+ ARCH="$(uname -m)"
+ [[ "$OS" == "darwin" ]] && OS="macos"
+ [[ "$ARCH" == "arm64" ]] && ARCH="aarch64"
+ [[ "$ARCH" == "x86_64" ]] && ARCH="x64"
+
+ if [[ ! -x "${PIPER_DIR}/piper" ]]; then
+ PIPER_VERSION="2023.11.14-2"
+ TAR="piper_${OS}_${ARCH}.tar.gz"
+ URL="https://github.com/rhasspy/piper/releases/download/${PIPER_VERSION}/${TAR}"
+ echo "⬇️ Piper TTS → ${PIPER_DIR}/"
+ mkdir -p "${PIPER_DIR}"
+ curl --fail --location --progress-bar "$URL" | tar xz -C "${VOICE_HOME}"
+ chmod +x "${PIPER_DIR}/piper" 2>/dev/null || true
+ fi
+
+ # Companion dylibs (espeak-ng, piper_phonemize, onnxruntime) from piper-phonemize
+ if [[ ! -f "${PIPER_LIB}/libpiper_phonemize.1.dylib" ]] && [[ ! -f "${PIPER_LIB}/libpiper_phonemize.so.1" ]]; then
+ PHONEMIZE_VERSION="2023.11.14-4"
+ PTTAR="piper-phonemize_${OS}_${ARCH}.tar.gz"
+ PTURL="https://github.com/rhasspy/piper-phonemize/releases/download/${PHONEMIZE_VERSION}/${PTTAR}"
+ echo "⬇️ Piper libs → ${PIPER_LIB}/"
+ TMPDIR_PT="$(mktemp -d)"
+ curl --fail --location --progress-bar "$PTURL" | tar xz -C "$TMPDIR_PT"
+ mkdir -p "${PIPER_LIB}"
+ # Copy whichever extension is present; let one pattern miss without aborting.
+ cp "$TMPDIR_PT"/piper-phonemize/lib/*.dylib "${PIPER_LIB}/" 2>/dev/null || true
+ cp "$TMPDIR_PT"/piper-phonemize/lib/*.so "${PIPER_LIB}/" 2>/dev/null || true
+ rm -rf "$TMPDIR_PT"
+ fi
+fi
+
+# Whisper model (GGUF) — only when whisper engine is active.
+if [[ "$STT_ENGINE" == "whisper" && ! -f "${MODELS_DIR}/${MODEL_NAME}" ]]; then
+ echo "⬇️ Whisper model → ${MODELS_DIR}/${MODEL_NAME}"
+ curl --fail --location --progress-bar \
+ "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${MODEL_NAME}" \
+ -o "${MODELS_DIR}/${MODEL_NAME}"
+fi
+
+# CoreML encoder companion (macOS only) — 2–3× faster STT on Apple Silicon.
+# Pairs with `<base>.bin` as `<base>-encoder.mlmodelc/`. whisper.cpp loads it
+# automatically when present.
+if [[ "$STT_ENGINE" == "whisper" && "$INSTALL_COREML" == "1" ]] && is_macos; then
+ ENCODER_BASE="${MODEL_NAME%.bin}"
+ ENCODER_DIR="${MODELS_DIR}/${ENCODER_BASE}-encoder.mlmodelc"
+ ENCODER_ZIP="${MODELS_DIR}/${ENCODER_BASE}-encoder.mlmodelc.zip"
+ if [[ ! -d "${ENCODER_DIR}" ]]; then
+ echo "⬇️ CoreML encoder → ${ENCODER_DIR}"
+ curl --fail --location --progress-bar \
+ "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${ENCODER_BASE}-encoder.mlmodelc.zip" \
+ -o "${ENCODER_ZIP}"
+ (cd "${MODELS_DIR}" && unzip -q -o "${ENCODER_ZIP}" && rm -f "${ENCODER_ZIP}")
+ fi
+fi
+
+# Piper voice (ONNX + JSON sidecar). Only when active engine uses it.
+# Voice names encode path: en_US-ryan-high → en/en_US/ryan/high/
+if [[ "$TTS_ENGINE" == "piper" ]]; then
+ ONNX_PATH="${VOICES_DIR}/${VOICE_NAME}.onnx"
+ JSON_PATH="${VOICES_DIR}/${VOICE_NAME}.onnx.json"
+ if [[ ! -f "${ONNX_PATH}" ]]; then
+ LOCALE="${VOICE_NAME%%-*}" # en_US
+ LANG_="${LOCALE%%_*}" # en
+ REST="${VOICE_NAME#*-}" # ryan-high
+ SPEAKER="${REST%-*}" # ryan
+ QUALITY="${REST##*-}" # high
+ BASE="https://huggingface.co/rhasspy/piper-voices/resolve/main/${LANG_}/${LOCALE}/${SPEAKER}/${QUALITY}"
+ echo "⬇️ Piper voice → ${ONNX_PATH}"
+ curl --fail --location --progress-bar "${BASE}/${VOICE_NAME}.onnx" -o "${ONNX_PATH}"
+ curl --fail --location --progress-bar "${BASE}/${VOICE_NAME}.onnx.json" -o "${JSON_PATH}"
+ fi
+fi
+
+echo "✅ Voice stack ready"
+if [[ "$STT_ENGINE" == "whisper" ]]; then
+ echo " whisper-server: $(command -v whisper-server || echo '<not installed>')"
+ echo " stt model: ${MODELS_DIR}/${MODEL_NAME}"
+ if [[ "$INSTALL_COREML" == "1" ]] && is_macos; then
+ echo " coreml encoder: ${MODELS_DIR}/${MODEL_NAME%.bin}-encoder.mlmodelc/"
+ fi
+else
+ echo " stt engine: ${STT_ENGINE} (browser-native, no server provisioning)"
+fi
+echo " tts engine: ${TTS_ENGINE}"
+if [[ "$TTS_ENGINE" == "piper" ]]; then
+ echo " piper: ${PIPER_DIR}/piper"
+ echo " piper voice: ${VOICES_DIR}/${VOICE_NAME}.onnx"
+else
+ echo " kokoro models: managed by transformers.js (~/.cache/huggingface/)"
+fi
diff --git a/server/index.js b/server/index.js
index 04db66418b..3f122d0298 100644
--- a/server/index.js
+++ b/server/index.js
@@ -44,6 +44,9 @@ import genomeRoutes from './routes/genome.js';
import digitalTwinRoutes from './routes/digital-twin.js';
import socialAccountsRoutes from './routes/socialAccounts.js';
import lmstudioRoutes from './routes/lmstudio.js';
+import voiceRoutes from './routes/voice.js';
+import { getVoiceConfig } from './services/voice/config.js';
+import { reconcile as reconcileVoice } from './services/voice/bootstrap.js';
import browserRoutes from './routes/browser.js';
import moltworldToolsRoutes from './routes/moltworldTools.js';
import moltworldWsRoutes from './routes/moltworldWs.js';
@@ -264,6 +267,7 @@ app.use('/api/digital-twin/identity', identityRoutes);
app.use('/api/digital-twin/autobiography', autobiographyRoutes);
app.use('/api/digital-twin', digitalTwinRoutes);
app.use('/api/lmstudio', lmstudioRoutes);
+app.use('/api/voice', voiceRoutes);
app.use('/api/browser', browserRoutes);
app.use('/api/data', dataManagerRoutes);
app.use('/api/datadog', datadogRoutes);
@@ -307,6 +311,8 @@ getInitSettings().then(s => {
telegram.init().catch(err => console.error(`❌ Telegram init failed: ${err.message}`));
}
}).catch(err => console.error(`❌ Telegram settings read failed: ${err.message}`));
+// Reconcile voice stack (start portos-whisper if voice.enabled)
+getVoiceConfig().then(reconcileVoice).catch(err => console.error(`❌ Voice reconcile failed: ${err.message}`));
// Check for update completion marker from a previous update cycle
const updateMarkerPath = join(PATHS.data, 'update-complete.json');
const removeMarker = () => unlink(updateMarkerPath).catch(e => {
diff --git a/server/package.json b/server/package.json
index 25f590207c..9033662fae 100644
--- a/server/package.json
+++ b/server/package.json
@@ -13,6 +13,7 @@
"dependencies": {
"express": "5.2.1",
"googleapis": "171.4.0",
+ "kokoro-js": "^1.2.1",
"node-pty": "1.2.0-beta.10",
"pg": "8.19.0",
"pm2": "5.4.3",
diff --git a/server/routes/voice.js b/server/routes/voice.js
new file mode 100644
index 0000000000..05caaf4464
--- /dev/null
+++ b/server/routes/voice.js
@@ -0,0 +1,170 @@
+/**
+ * Voice Routes
+ *
+ * REST endpoints for voice configuration and local voice-stack health.
+ * Actual audio streaming happens over Socket.IO (see server/sockets/voice.js).
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { getVoiceConfig, updateVoiceConfig } from '../services/voice/config.js';
+import { checkAll, invalidateHealthCache } from '../services/voice/health.js';
+import { reconcile, verifyBinaries, verifyModels, downloadPiperVoice } from '../services/voice/bootstrap.js';
+import { synthesize, listVoices } from '../services/voice/tts.js';
+import { findPiperVoice } from '../services/voice/piper-voices.js';
+
+const router = Router();
+
+const VALID_TTS_ENGINES = new Set(['kokoro', 'piper']);
+const validEngine = (v) => VALID_TTS_ENGINES.has(v) ? v : undefined;
+
+// Match the Socket.IO-side cap so /test can't be used to bypass it with a
+// multi-megabyte string that would then take minutes to synthesize.
+const MAX_TEST_TEXT_LEN = 4000;
+
+// Partial schema — deepMerge fills in anything omitted, so every field is
+// optional. The point here is to reject unknown engine values and obvious
+// type mistakes, not to exhaustively re-spec the full config tree.
+const voiceConfigPatchSchema = z.object({
+ enabled: z.boolean().optional(),
+ trigger: z.enum(['push-to-talk', 'hotword', 'vad']).optional(),
+ hotkey: z.string().max(32).optional(),
+ stt: z.object({
+ engine: z.enum(['whisper', 'web-speech']).optional(),
+ endpoint: z.string().url().optional(),
+ model: z.string().max(64).optional(),
+ modelPath: z.string().max(512).optional(),
+ language: z.string().max(16).optional(),
+ coreml: z.boolean().optional(),
+ vocabularyPrompt: z.string().max(4000).optional(),
+ }).partial().optional(),
+ tts: z.object({
+ engine: z.enum(['kokoro', 'piper']).optional(),
+ rate: z.number().min(0.25).max(4).optional(),
+ kokoro: z.object({
+ modelId: z.string().max(128).optional(),
+ dtype: z.enum(['fp32', 'fp16', 'q8', 'q4', 'q4f16']).optional(),
+ voice: z.string().max(64).optional(),
+ }).partial().optional(),
+ piper: z.object({
+ voice: z.string().max(128).optional(),
+ voicePath: z.string().max(512).optional(),
+ speakerId: z.number().int().nullable().optional(),
+ }).partial().optional(),
+ }).partial().optional(),
+ llm: z.object({
+ provider: z.string().max(32).optional(),
+ model: z.string().max(128).optional(),
+ systemPrompt: z.string().max(4000).optional(),
+ usePersonality: z.boolean().optional(),
+ personality: z.object({
+ name: z.string().max(64).optional(),
+ role: z.string().max(128).optional(),
+ traits: z.array(z.string().max(64)).max(20).optional(),
+ speechStyle: z.string().max(256).optional(),
+ customPrompt: z.string().max(2000).optional(),
+ }).partial().optional(),
+ tools: z.object({
+ enabled: z.boolean().optional(),
+ maxIterations: z.number().int().min(1).max(10).optional(),
+ }).partial().optional(),
+ }).partial().optional(),
+ vad: z.object({
+ endOfSpeechMs: z.number().int().min(100).max(5000).optional(),
+ minUtteranceMs: z.number().int().min(50).max(5000).optional(),
+ }).partial().optional(),
+}).strict();
+
+// GET /api/voice/config — current merged voice settings
+router.get('/config', asyncHandler(async (_req, res) => {
+ res.json(await getVoiceConfig());
+}));
+
+// PUT /api/voice/config — deep-merge patch, save, and reconcile PM2 state
+router.put('/config', asyncHandler(async (req, res) => {
+ const parsed = voiceConfigPatchSchema.safeParse(req.body || {});
+ if (!parsed.success) {
+ throw new ServerError(
+ `Invalid voice config: ${parsed.error.issues.map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`,
+ { status: 400, code: 'VALIDATION_ERROR' },
+ );
+ }
+ const next = await updateVoiceConfig(parsed.data);
+ invalidateHealthCache();
+ const reconciliation = await reconcile(next).catch((err) => ({ error: err.message }));
+ // Notify connected clients (VoiceWidget, etc.) so they can refresh the
+ // enabled flag / STT engine without a page reload when Settings saves.
+ req.app.get('io')?.emit('voice:config:changed', {
+ enabled: next.enabled,
+ sttEngine: next.stt?.engine,
+ sttLanguage: next.stt?.language,
+ ttsEngine: next.tts?.engine,
+ hotkey: next.hotkey,
+ });
+ res.json({ config: next, reconciliation });
+}));
+
+// GET /api/voice/status — reachability + enabled flag + binary/model presence
+router.get('/status', asyncHandler(async (_req, res) => {
+ const cfg = await getVoiceConfig();
+ const [services, bins] = await Promise.all([checkAll(cfg), verifyBinaries(cfg)]);
+ const models = verifyModels(cfg);
+ res.json({
+ enabled: cfg.enabled,
+ sttEngine: cfg.stt.engine,
+ ttsEngine: cfg.tts.engine,
+ services,
+ binaries: bins,
+ models,
+ });
+}));
+
+// GET /api/voice/voices?engine=kokoro|piper — enumerate voices for the given
+// engine (or the active one when unspecified). Query param lets the Settings
+// page preview a different engine's voices without saving first.
+router.get('/voices', asyncHandler(async (req, res) => {
+ res.json(await listVoices(validEngine(req.query?.engine)));
+}));
+
+// POST /api/voice/piper/fetch — download a single Piper voice on demand.
+// Validates against the curated catalog to keep shell interpolation safe.
+router.post('/piper/fetch', asyncHandler(async (req, res) => {
+ const voice = (req.body?.voice || '').toString();
+ if (!findPiperVoice(voice)) {
+ return res.status(400).json({ error: `unknown piper voice: ${voice}` });
+ }
+ const cfg = await getVoiceConfig();
+ const result = await downloadPiperVoice(voice, cfg);
+ res.json({ voice, ...result });
+}));
+
+// POST /api/voice/test — synthesize {text, voice?, engine?} and return WAV.
+// `engine` override lets the Settings page preview a different engine's voice
+// without saving first (e.g. flip to Piper, hit ▶, before clicking Save).
+router.post('/test', asyncHandler(async (req, res) => {
+ const text = (req.body?.text || '').toString().trim();
+ if (!text) return res.status(400).json({ error: 'text is required' });
+ if (text.length > MAX_TEST_TEXT_LEN) {
+ return res.status(400).json({ error: `text too long (${text.length} > ${MAX_TEST_TEXT_LEN} chars)` });
+ }
+ const voice = (req.body?.voice || '').toString().trim() || undefined;
+ const engine = validEngine((req.body?.engine || '').toString().trim());
+ // synthesize() throws "unknown piper voice: X" when a client supplies a
+ // voice id that isn't in the curated catalog — that's user input, not a
+ // server failure, so map to 400 instead of asyncHandler's default 500.
+ let wav; let latencyMs;
+ try {
+ ({ wav, latencyMs } = await synthesize(text, { voice, engine }));
+ } catch (err) {
+ if (err?.message?.startsWith('unknown piper voice:')) {
+ return res.status(400).json({ error: err.message });
+ }
+ throw err;
+ }
+ res.setHeader('Content-Type', 'audio/wav');
+ res.setHeader('X-TTS-Latency-Ms', String(latencyMs));
+ res.send(wav);
+}));
+
+export default router;
diff --git a/server/routes/voice.test.js b/server/routes/voice.test.js
new file mode 100644
index 0000000000..cfe8bd0192
--- /dev/null
+++ b/server/routes/voice.test.js
@@ -0,0 +1,193 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+// Mock all voice service modules before importing the router so the route
+// file's top-level imports resolve to the mocks.
+vi.mock('../services/voice/config.js', () => ({
+ getVoiceConfig: vi.fn(),
+ updateVoiceConfig: vi.fn(),
+}));
+vi.mock('../services/voice/health.js', () => ({
+ checkAll: vi.fn(),
+ invalidateHealthCache: vi.fn(),
+}));
+vi.mock('../services/voice/bootstrap.js', () => ({
+ reconcile: vi.fn(),
+ verifyBinaries: vi.fn(),
+ verifyModels: vi.fn(),
+ downloadPiperVoice: vi.fn(),
+}));
+vi.mock('../services/voice/tts.js', () => ({
+ synthesize: vi.fn(),
+ listVoices: vi.fn(),
+}));
+vi.mock('../services/voice/piper-voices.js', () => ({
+ findPiperVoice: vi.fn(),
+}));
+
+import * as config from '../services/voice/config.js';
+import * as health from '../services/voice/health.js';
+import * as bootstrap from '../services/voice/bootstrap.js';
+import * as tts from '../services/voice/tts.js';
+import * as piperVoices from '../services/voice/piper-voices.js';
+import voiceRoutes from './voice.js';
+
+const DEFAULT_CFG = {
+ enabled: false,
+ stt: { engine: 'web-speech', endpoint: 'http://127.0.0.1:5562' },
+ tts: { engine: 'kokoro' },
+};
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/voice', voiceRoutes);
+ return app;
+};
+
+describe('Voice Routes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ config.getVoiceConfig.mockResolvedValue(DEFAULT_CFG);
+ });
+
+ describe('GET /api/voice/config', () => {
+ it('returns the merged voice config', async () => {
+ const res = await request(buildApp()).get('/api/voice/config');
+ expect(res.status).toBe(200);
+ expect(res.body.stt.engine).toBe('web-speech');
+ });
+ });
+
+ describe('PUT /api/voice/config', () => {
+ it('rejects unknown top-level keys via the Zod strict schema', async () => {
+ const res = await request(buildApp()).put('/api/voice/config').send({ bogus: true });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(res.body.error).toMatch(/Invalid voice config/);
+ expect(config.updateVoiceConfig).not.toHaveBeenCalled();
+ });
+
+ it('rejects an invalid stt engine value', async () => {
+ const res = await request(buildApp())
+ .put('/api/voice/config')
+ .send({ stt: { engine: 'cloud-api' } });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(config.updateVoiceConfig).not.toHaveBeenCalled();
+ });
+
+ it('rejects an invalid tts engine value', async () => {
+ const res = await request(buildApp())
+ .put('/api/voice/config')
+ .send({ tts: { engine: 'elevenlabs' } });
+ expect(res.status).toBe(400);
+ expect(config.updateVoiceConfig).not.toHaveBeenCalled();
+ });
+
+ it('saves a valid patch and runs reconcile', async () => {
+ const next = { ...DEFAULT_CFG, enabled: true };
+ config.updateVoiceConfig.mockResolvedValue(next);
+ bootstrap.reconcile.mockResolvedValue({ skipped: 'web-speech', piperProvisioned: false });
+
+ const res = await request(buildApp())
+ .put('/api/voice/config')
+ .send({ enabled: true });
+ expect(res.status).toBe(200);
+ expect(res.body.config.enabled).toBe(true);
+ expect(res.body.reconciliation).toEqual({ skipped: 'web-speech', piperProvisioned: false });
+ expect(config.updateVoiceConfig).toHaveBeenCalledWith({ enabled: true });
+ expect(health.invalidateHealthCache).toHaveBeenCalled();
+ });
+
+ it('reports reconcile failures without 500-ing the route', async () => {
+ config.updateVoiceConfig.mockResolvedValue({ ...DEFAULT_CFG, enabled: true });
+ bootstrap.reconcile.mockRejectedValue(new Error('whisper-server not on PATH'));
+
+ const res = await request(buildApp())
+ .put('/api/voice/config')
+ .send({ enabled: true });
+ expect(res.status).toBe(200);
+ expect(res.body.reconciliation).toEqual({ error: 'whisper-server not on PATH' });
+ });
+ });
+
+ describe('GET /api/voice/status', () => {
+ it('returns the expected shape', async () => {
+ health.checkAll.mockResolvedValue({ whisper: { ok: true } });
+ bootstrap.verifyBinaries.mockResolvedValue({ whisper: '/usr/bin/whisper-server', piper: null, piperRequired: false });
+ bootstrap.verifyModels.mockReturnValue({ sttModel: '/p/model.bin', ttsVoice: 'kokoro:x' });
+
+ const res = await request(buildApp()).get('/api/voice/status');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ enabled: false,
+ sttEngine: 'web-speech',
+ ttsEngine: 'kokoro',
+ services: { whisper: { ok: true } },
+ binaries: { whisper: '/usr/bin/whisper-server' },
+ models: { sttModel: '/p/model.bin' },
+ });
+ });
+ });
+
+ describe('GET /api/voice/voices', () => {
+ it('delegates to listVoices with the requested engine and returns { engine, voices } shape', async () => {
+ tts.listVoices.mockResolvedValue({ engine: 'kokoro', voices: [{ id: 'af_heart' }] });
+ const res = await request(buildApp()).get('/api/voice/voices?engine=kokoro');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ engine: 'kokoro', voices: [{ id: 'af_heart' }] });
+ expect(tts.listVoices).toHaveBeenCalledWith('kokoro');
+ });
+
+ it('ignores unknown engine query values', async () => {
+ tts.listVoices.mockResolvedValue({ engine: 'kokoro', voices: [] });
+ await request(buildApp()).get('/api/voice/voices?engine=elevenlabs');
+ expect(tts.listVoices).toHaveBeenCalledWith(undefined);
+ });
+ });
+
+ describe('POST /api/voice/piper/fetch', () => {
+ it('rejects unknown piper voice ids with 400', async () => {
+ piperVoices.findPiperVoice.mockReturnValue(null);
+ const res = await request(buildApp())
+ .post('/api/voice/piper/fetch')
+ .send({ voice: 'en_US-fake-high' });
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/unknown piper voice/);
+ expect(bootstrap.downloadPiperVoice).not.toHaveBeenCalled();
+ });
+
+ it('downloads a valid voice and returns the result', async () => {
+ piperVoices.findPiperVoice.mockReturnValue({ id: 'en_GB-jenny_dioco-medium' });
+ bootstrap.downloadPiperVoice.mockResolvedValue({ skipped: true, voicePath: '~/.portos/voice/voices/en_GB-jenny_dioco-medium.onnx' });
+
+ const res = await request(buildApp())
+ .post('/api/voice/piper/fetch')
+ .send({ voice: 'en_GB-jenny_dioco-medium' });
+ expect(res.status).toBe(200);
+ expect(res.body.voice).toBe('en_GB-jenny_dioco-medium');
+ expect(res.body.skipped).toBe(true);
+ expect(bootstrap.downloadPiperVoice).toHaveBeenCalled();
+ });
+ });
+
+ describe('POST /api/voice/test', () => {
+ it('requires text', async () => {
+ const res = await request(buildApp()).post('/api/voice/test').send({});
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/text is required/);
+ });
+
+ it('returns WAV bytes on success', async () => {
+ tts.synthesize.mockResolvedValue({ wav: Buffer.from([0x52, 0x49, 0x46, 0x46]), latencyMs: 123 });
+ const res = await request(buildApp())
+ .post('/api/voice/test')
+ .send({ text: 'hello', voice: 'af_heart', engine: 'kokoro' });
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/audio\/wav/);
+ expect(res.headers['x-tts-latency-ms']).toBe('123');
+ });
+ });
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index 04853054d5..c641cb8d6d 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -37,6 +37,7 @@ import {
import * as appsService from './apps.js';
import * as appUpdater from './appUpdater.js';
import * as appDeployer from './appDeployer.js';
+import { registerVoiceHandlers } from '../sockets/voice.js';
// Store active log streams per socket
const activeStreams = new Map();
@@ -58,6 +59,7 @@ let ioInstance = null;
export function initSocket(io) {
io.on('connection', (socket) => {
console.log(`🔌 Client connected: ${socket.id}`);
+ registerVoiceHandlers(socket);
// Handle streaming app detection
socket.on('detect:start', async (rawData) => {
diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.js
new file mode 100644
index 0000000000..575b0735e9
--- /dev/null
+++ b/server/services/voice/bootstrap.js
@@ -0,0 +1,223 @@
+// Voice stack lifecycle — owns the whisper-server PM2 app and model/binary
+// provisioning. Piper (TTS) is spawned per-request in services/voice/tts.js.
+
+import { existsSync } from 'fs';
+import { execFile } from 'child_process';
+import { promisify } from 'util';
+import { basename, join } from 'path';
+import { createServer } from 'net';
+import { PATHS } from '../../lib/fileUtils.js';
+import { execPm2, getAppStatus } from '../pm2.js';
+import { expandPath, piperVoiceTildePath } from './config.js';
+
+export const pexec = promisify(execFile);
+
+export const WHISPER_APP = 'portos-whisper';
+
+export const which = async (bin) => {
+ const res = await pexec('which', [bin]).catch(() => null);
+ return res?.stdout.trim() || null;
+};
+
+export const verifyBinaries = async (cfg) => {
+ const [whisper, piper] = await Promise.all([which('whisper-server'), which('piper')]);
+ // Only require piper when active engine actually uses it.
+ const piperRequired = cfg?.tts?.engine === 'piper';
+ return { whisper, piper, piperRequired };
+};
+
+export const verifyModels = (cfg) => {
+ const modelPath = expandPath(cfg.stt.modelPath);
+ const out = { sttModel: existsSync(modelPath) ? modelPath : null };
+
+ if (cfg.tts.engine === 'piper') {
+ const voicePath = expandPath(cfg.tts.piper.voicePath);
+ out.ttsVoice = existsSync(voicePath) ? voicePath : null;
+ } else {
+ // Kokoro models are managed by transformers.js cache — assume present.
+ out.ttsVoice = `kokoro:${cfg.tts.kokoro?.modelId}`;
+ }
+
+ if (cfg.stt.coreml) {
+ const mlPath = modelPath.replace(/\.bin$/, '-encoder.mlmodelc');
+ out.coreml = existsSync(mlPath) ? mlPath : null;
+ }
+ return out;
+};
+
+const parseVoiceName = (voicePath) => basename(voicePath).replace(/\.onnx$/, '');
+
+export const runSetupScript = async (cfg) => {
+ const scriptPath = join(PATHS.root, 'scripts', 'setup-voice.sh');
+ const modelName = basename(expandPath(cfg.stt.modelPath));
+ const voiceName = cfg.tts.engine === 'piper' ? parseVoiceName(expandPath(cfg.tts.piper.voicePath)) : '';
+ const sttEngine = cfg.stt?.engine || 'whisper';
+ const env = {
+ ...process.env,
+ MODEL_NAME: modelName,
+ VOICE_NAME: voiceName,
+ // Pass STT_ENGINE so the script can skip whisper install + model download
+ // when the user picked Web Speech (browser-native) — they'd otherwise pay
+ // the Homebrew + GGUF model cost for a feature they don't use.
+ STT_ENGINE: sttEngine,
+ TTS_ENGINE: cfg.tts.engine || 'kokoro',
+ INSTALL_COREML: cfg.stt.coreml ? '1' : '0',
+ };
+ console.log(`🔧 voice: setup-voice.sh (stt=${sttEngine}/${modelName}, tts=${cfg.tts.engine}, coreml=${env.INSTALL_COREML})`);
+ // 10-minute cap — large models + slow network can legitimately take several
+ // minutes, but a hung curl must not pin the HTTP request that triggered us.
+ const { stdout, stderr } = await pexec('bash', [scriptPath], {
+ env,
+ maxBuffer: 64 * 1024 * 1024,
+ timeout: 10 * 60 * 1000,
+ });
+ return { stdout, stderr };
+};
+
+/**
+ * Download a single Piper voice without touching whisper/STT state. Used by
+ * the Settings voice-picker so users can audition voices as they browse the
+ * catalog rather than waiting for Save & Reconcile.
+ */
+export const downloadPiperVoice = async (voiceId, currentCfg) => {
+ if (!voiceId || typeof voiceId !== 'string') throw new Error('voiceId required');
+ const voicePath = piperVoiceTildePath(voiceId);
+ if (existsSync(expandPath(voicePath))) return { skipped: true, voicePath };
+ // Re-use the existing setup script but force it into Piper-only mode. The
+ // script already short-circuits whisper steps when the model/binary are
+ // present, so this is cheap on repeat invocations.
+ await runSetupScript({
+ ...currentCfg,
+ tts: { engine: 'piper', piper: { voicePath } },
+ });
+ return { downloaded: true, voicePath };
+};
+
+const isWhisperRunning = async () => {
+ const status = await getAppStatus(WHISPER_APP).catch(() => null);
+ return status?.status === 'online';
+};
+
+// Returns null if the port is free, else a short description of who's there.
+// `port` MUST be coerced to a number — `net.Server.listen(stringPort)` is
+// interpreted as a pipe path and silently misses real TCP port collisions.
+// Any listen() error other than EADDRINUSE (EACCES, EADDRNOTAVAIL, EINVAL…)
+// indicates endpoint misconfiguration — surface it instead of silently
+// proceeding to a more confusing PM2 failure downstream.
+const probePortInUse = (host, port) => new Promise((resolve) => {
+ const portNum = Number(port);
+ const s = createServer();
+ s.once('error', (err) => {
+ s.close();
+ if (err.code === 'EADDRINUSE') {
+ resolve(`port ${portNum} in use (${err.code})`);
+ } else {
+ resolve(`cannot bind ${host}:${portNum} (${err.code || err.message})`);
+ }
+ });
+ s.once('listening', () => s.close(() => resolve(null)));
+ s.listen(portNum, host);
+});
+
+// Poll until whisper's /inference endpoint answers (any HTTP status = bound),
+// or give up after `timeoutMs`. Distinguishes "bound but slow" from "crashed".
+// Each probe has its own abort-based timeout so a hung connect (firewall,
+// half-open socket) can't stall the loop past the overall deadline.
+const waitForWhisper = async (host, port, timeoutMs = 8000) => {
+ const deadline = Date.now() + timeoutMs;
+ const url = `http://${host}:${port}/`;
+ while (Date.now() < deadline) {
+ const remaining = deadline - Date.now();
+ const probeTimeout = Math.max(1, Math.min(1000, remaining));
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), probeTimeout);
+ const ok = await fetch(url, { method: 'GET', signal: ctrl.signal })
+ .then(() => true)
+ .catch(() => false)
+ .finally(() => clearTimeout(t));
+ if (ok) return true;
+ const sleep = Math.min(250, Math.max(0, deadline - Date.now()));
+ if (sleep > 0) await new Promise((r) => setTimeout(r, sleep));
+ }
+ return false;
+};
+
+export const startWhisper = async (cfg) => {
+ const whisperBin = await which('whisper-server');
+ if (!whisperBin) throw new Error('whisper-server not on PATH — run scripts/setup-voice.sh');
+ const modelPath = expandPath(cfg.stt.modelPath);
+ if (!existsSync(modelPath)) throw new Error(`whisper model missing: ${modelPath}`);
+
+ const url = new URL(cfg.stt.endpoint);
+ const host = url.hostname;
+ const port = url.port || '5562';
+
+ // Delete stale PM2 entry so our own previous instance doesn't count as a collision.
+ await execPm2(['delete', WHISPER_APP]).catch(() => {});
+
+ // Pre-flight: refuse to start if something ELSE is already on the port —
+ // whisper-server crashes on bind failure and takes the model with it.
+ // Distinguish "port collision" (use a different port) from "bind error"
+ // (EACCES / EINVAL / EADDRNOTAVAIL → host/IP itself is wrong).
+ const occupied = await probePortInUse(host, port);
+ if (occupied) {
+ if (/EADDRINUSE|in use/i.test(occupied)) {
+ throw new Error(`${occupied} — another service is bound to ${host}:${port}. Change voice.stt.endpoint (e.g. http://127.0.0.1:5563) under Settings → Voice.`);
+ }
+ throw new Error(`${occupied} — voice.stt.endpoint is misconfigured for ${host}:${port}. Check Settings → Voice and ensure the host/IP is valid and bindable on this machine.`);
+ }
+
+ await execPm2([
+ 'start', whisperBin,
+ '--name', WHISPER_APP,
+ '--interpreter', 'none',
+ '--no-autorestart',
+ '--',
+ '--host', host, '--port', port, '--model', modelPath,
+ ]);
+
+ // Verify the server actually bound. whisper-server returns 0 to PM2 even
+ // when it aborts on bind failure, so we can't trust pm2 exit status alone.
+ const bound = await waitForWhisper(host, port);
+ if (!bound) {
+ await execPm2(['delete', WHISPER_APP]).catch(() => {});
+ throw new Error(`whisper-server failed to bind on ${host}:${port} within 8s — check pm2 logs ${WHISPER_APP}`);
+ }
+
+ console.log(`🎙️ voice: ${WHISPER_APP} up on ${host}:${port} (model=${modelPath})`);
+ return { name: WHISPER_APP, host, port, modelPath };
+};
+
+export const stopWhisper = async () => {
+ if (!(await isWhisperRunning())) return { skipped: true };
+ await execPm2(['delete', WHISPER_APP]).catch(() => {});
+ console.log(`🛑 voice: ${WHISPER_APP} stopped`);
+ return { stopped: true };
+};
+
+/**
+ * Reconcile PM2 state with desired voice.enabled. Called from
+ * PUT /api/voice/config and at server boot.
+ */
+export const reconcile = async (cfg) => {
+ if (!cfg.enabled) return stopWhisper();
+
+ const bins = await verifyBinaries(cfg);
+ const models = verifyModels(cfg);
+ const piperMissing = bins.piperRequired && (!bins.piper || !models.ttsVoice);
+ const webSpeech = cfg.stt?.engine === 'web-speech';
+
+ // Web Speech STT runs entirely in the browser — stop any leftover whisper
+ // instance and skip STT provisioning. Piper voice provisioning still runs.
+ if (webSpeech) {
+ if (piperMissing) await runSetupScript(cfg);
+ await stopWhisper().catch(() => null);
+ return { skipped: 'web-speech', piperProvisioned: piperMissing };
+ }
+
+ const coremlMissing = cfg.stt.coreml && !models.coreml;
+ const sttMissing = !bins.whisper || !models.sttModel || coremlMissing;
+ if (piperMissing || sttMissing) await runSetupScript(cfg);
+
+ return startWhisper(cfg);
+};
diff --git a/server/services/voice/config.js b/server/services/voice/config.js
new file mode 100644
index 0000000000..befc0084de
--- /dev/null
+++ b/server/services/voice/config.js
@@ -0,0 +1,124 @@
+// Voice config — defaults merged with data/settings.json#voice. Engine-dispatched:
+// stt.<engine> / tts.<engine> hold backend-specific options. Stored paths use `~/`
+// for portability and are expanded by `expandPath` at consumption time.
+
+import { homedir } from 'os';
+import { join } from 'path';
+import { getSettings, updateSettings } from '../settings.js';
+
+const VOICE_HOME = join(homedir(), '.portos', 'voice');
+
+export const VOICE_DEFAULTS = Object.freeze({
+ enabled: false,
+ trigger: 'push-to-talk',
+ hotkey: 'Space',
+
+ stt: {
+ // 'web-speech' (browser-native, zero-latency, no server process needed) is the
+ // default. Falls back to 'whisper' (local whisper.cpp) for browsers without
+ // SpeechRecognition support (Firefox, older Safari) or when the user wants
+ // consistent offline STT across clients.
+ engine: 'web-speech', // 'whisper' | 'web-speech'
+ // 5562 keeps whisper inside PortOS's own 55xx port band. Avoid 8080 —
+ // IPFS, Supabase Studio, Tomcat, etc. commonly squat on it.
+ endpoint: 'http://127.0.0.1:5562',
+ model: 'base.en',
+ modelPath: '~/.portos/voice/models/ggml-base.en.bin',
+ language: 'en',
+ // CoreML (Apple Neural Engine) is NOT enabled by default because Homebrew's
+ // whisper-cpp formula ships without WHISPER_COREML — the `.mlmodelc` encoder
+ // companion is ignored even if downloaded. Turn on only if you've built
+ // whisper.cpp from source with `cmake -DWHISPER_COREML=1`. Metal backend
+ // (GPU) is always used and is fast enough for most utterances.
+ coreml: false,
+ // Whisper prompt bias — seeds the decoder with context so PortOS-specific
+ // terms don't get mapped to common English homophones. Empty = defaults.
+ vocabularyPrompt: '',
+ },
+
+ tts: {
+ engine: 'kokoro', // 'kokoro' | 'piper'
+ rate: 1.0,
+ kokoro: {
+ modelId: 'onnx-community/Kokoro-82M-v1.0-ONNX',
+ dtype: 'q8', // 'fp32' | 'fp16' | 'q8' | 'q4' | 'q4f16'
+ voice: 'af_heart',
+ },
+ piper: {
+ voice: 'en_GB-jenny_dioco-medium',
+ voicePath: '~/.portos/voice/voices/en_GB-jenny_dioco-medium.onnx',
+ // Null = use the catalog default (set per-voice in piper-voices.js).
+ // Override here when experimenting with other VCTK speaker indices.
+ speakerId: null,
+ },
+ },
+
+ llm: {
+ provider: 'lmstudio',
+ model: 'auto',
+ // Legacy free-form system prompt. Overridden by `personality` + tool
+ // descriptions when `usePersonality` is true (default).
+ systemPrompt: 'You are the PortOS assistant. Your replies are spoken aloud — keep them short and use plain prose (no markdown or lists).',
+ usePersonality: true,
+ personality: {
+ name: 'Alfred',
+ role: 'Chief of Staff',
+ traits: ['concise', 'warm', 'proactive'],
+ speechStyle: 'casual and brief',
+ customPrompt: '',
+ },
+ // Tool-calling is OFF by default — it adds 1–2 LLM roundtrips per turn
+ // (slower) and needs a tool-use-trained model (Qwen2.5, Hermes-3, etc.)
+ // to avoid producing JSON-like gibberish in the spoken reply.
+ tools: {
+ enabled: false,
+ maxIterations: 3,
+ },
+ },
+
+ vad: { endOfSpeechMs: 700, minUtteranceMs: 250 },
+});
+
+const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
+
+const deepMerge = (base, patch) => {
+ if (!isObj(patch)) return patch === undefined ? base : patch;
+ const out = { ...base };
+ for (const [k, v] of Object.entries(patch)) {
+ out[k] = isObj(base[k]) && isObj(v) ? deepMerge(base[k], v) : v;
+ }
+ return out;
+};
+
+export const expandPath = (p) => {
+ if (typeof p !== 'string') return p;
+ if (p.startsWith('~/')) return join(homedir(), p.slice(2));
+ if (p === '~') return homedir();
+ return p;
+};
+
+// Tiny in-memory cache so hot paths (per-turn enabled check in voice sockets)
+// don't hit disk on every dispatch. Invalidated on updateVoiceConfig and
+// manually via invalidateVoiceConfigCache() from the reconcile flow.
+let cachedConfig = null;
+
+export const getVoiceConfig = async () => {
+ if (cachedConfig) return cachedConfig;
+ const settings = await getSettings();
+ cachedConfig = deepMerge(VOICE_DEFAULTS, settings.voice || {});
+ return cachedConfig;
+};
+
+export const invalidateVoiceConfigCache = () => { cachedConfig = null; };
+
+export const updateVoiceConfig = async (patch) => {
+ const settings = await getSettings();
+ const current = deepMerge(VOICE_DEFAULTS, settings.voice || {});
+ const next = deepMerge(current, patch || {});
+ await updateSettings({ voice: next });
+ cachedConfig = next;
+ return next;
+};
+
+export const voiceHome = () => VOICE_HOME;
+export const piperVoiceTildePath = (id) => `~/.portos/voice/voices/${id}.onnx`;
diff --git a/server/services/voice/health.js b/server/services/voice/health.js
new file mode 100644
index 0000000000..e15f8db47c
--- /dev/null
+++ b/server/services/voice/health.js
@@ -0,0 +1,82 @@
+// Voice stack health checks — whisper.cpp + LM Studio + (when active) Piper.
+// Kokoro runs in-process; readiness is reported via the in-memory model flag.
+
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { getVoiceConfig, expandPath, voiceHome } from './config.js';
+import { readyState as kokoroReadyState } from './tts-kokoro.js';
+import { which } from './bootstrap.js';
+
+const PROBE_TIMEOUT_MS = 1500;
+const CACHE_TTL_MS = 3000;
+let cache = null;
+
+const probe = async (url) => {
+ const started = Date.now();
+ const controller = new AbortController();
+ const t = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, { method: 'GET', signal: controller.signal });
+ return { ok: true, status: res.status, latencyMs: Date.now() - started };
+ } catch (err) {
+ const name = err?.name || '';
+ const code = err?.cause?.code || err?.code || '';
+ if (name === 'AbortError') return { ok: false, state: 'timeout', latencyMs: Date.now() - started };
+ if (code === 'ECONNREFUSED') return { ok: false, state: 'down', error: code };
+ return { ok: false, state: 'error', error: err?.message || String(err) };
+ } finally {
+ clearTimeout(t);
+ }
+};
+
+const lmStudioBaseUrl = () => (process.env.LM_STUDIO_URL || 'http://localhost:1234').replace(/\/+$/, '').replace(/\/v1$/, '');
+
+export const checkAll = async (cfg) => {
+ const voice = cfg || await getVoiceConfig();
+ const sttEngine = voice.stt?.engine || 'whisper';
+ const cacheKey = `${sttEngine}|${voice.tts.engine}|${voice.stt.endpoint}`;
+ if (cache && cache.key === cacheKey && Date.now() - cache.ts < CACHE_TTL_MS) {
+ // Refresh kokoro readiness on every call — it's a cheap in-memory check
+ // and flips from lazy → loading → loaded mid-cache-window after first synthesis.
+ if (voice.tts.engine === 'kokoro') {
+ const state = kokoroReadyState();
+ cache.value.kokoro = { ok: state === 'loaded', state };
+ }
+ return cache.value;
+ }
+
+ // STT probes: whisper.cpp needs an HTTP health check; web-speech runs in
+ // the browser so just report it as available.
+ const probes = [probe(`${lmStudioBaseUrl()}/v1/models`)];
+ const labels = ['lmstudio'];
+ if (sttEngine === 'whisper') {
+ probes.unshift(probe(voice.stt.endpoint));
+ labels.unshift('whisper');
+ }
+
+ const results = await Promise.all(probes);
+ const out = Object.fromEntries(labels.map((k, i) => [k, results[i]]));
+
+ if (voice.tts.engine === 'piper') {
+ // CLI-mode piper has no server to probe — check binary + selected voice.
+ const localPiper = join(voiceHome(), 'piper', 'piper');
+ const [hasBin, voicePath] = [existsSync(localPiper) || !!(await which('piper')), expandPath(voice.tts.piper?.voicePath || '')];
+ const hasVoice = voicePath && existsSync(voicePath);
+ out.piper = hasBin && hasVoice
+ ? { ok: true, state: 'ready' }
+ : { ok: false, state: !hasBin ? 'no binary' : 'voice missing' };
+ }
+
+ if (sttEngine === 'web-speech') {
+ out['web-speech'] = { ok: true, state: 'browser-native' };
+ }
+ if (voice.tts.engine === 'kokoro') {
+ const state = kokoroReadyState();
+ out.kokoro = { ok: state === 'loaded', state };
+ }
+
+ cache = { key: cacheKey, ts: Date.now(), value: out };
+ return out;
+};
+
+export const invalidateHealthCache = () => { cache = null; };
diff --git a/server/services/voice/kokoro-voices.js b/server/services/voice/kokoro-voices.js
new file mode 100644
index 0000000000..a487cfa88a
--- /dev/null
+++ b/server/services/voice/kokoro-voices.js
@@ -0,0 +1,36 @@
+// Static Kokoro voice catalogue — mirrors the frozen `$` table inside
+// kokoro-js's bundled dist (kokoro-js@^1.2.x), which the package does not
+// export at the top level. We use this for `listVoices()` so the UI can
+// populate a picker without paying the 80MB model load.
+// Refresh from node_modules/kokoro-js/dist/kokoro.js when bumping the dep.
+
+export const KOKORO_VOICES = Object.freeze({
+ af_heart: { gender: 'Female', language: 'en-US', traits: '❤️', grade: 'A' },
+ af_alloy: { gender: 'Female', language: 'en-US', grade: 'C' },
+ af_aoede: { gender: 'Female', language: 'en-US', grade: 'C+' },
+ af_bella: { gender: 'Female', language: 'en-US', traits: '🔥', grade: 'A-' },
+ af_jessica: { gender: 'Female', language: 'en-US', grade: 'D' },
+ af_kore: { gender: 'Female', language: 'en-US', grade: 'C+' },
+ af_nicole: { gender: 'Female', language: 'en-US', traits: '🎧', grade: 'B-' },
+ af_nova: { gender: 'Female', language: 'en-US', grade: 'C' },
+ af_river: { gender: 'Female', language: 'en-US', grade: 'D' },
+ af_sarah: { gender: 'Female', language: 'en-US', grade: 'C+' },
+ af_sky: { gender: 'Female', language: 'en-US', grade: 'C-' },
+ am_adam: { gender: 'Male', language: 'en-US', grade: 'F+' },
+ am_echo: { gender: 'Male', language: 'en-US', grade: 'D' },
+ am_eric: { gender: 'Male', language: 'en-US', grade: 'D' },
+ am_fenrir: { gender: 'Male', language: 'en-US', grade: 'C+' },
+ am_liam: { gender: 'Male', language: 'en-US', grade: 'D' },
+ am_michael: { gender: 'Male', language: 'en-US', grade: 'C+' },
+ am_onyx: { gender: 'Male', language: 'en-US', grade: 'D' },
+ am_puck: { gender: 'Male', language: 'en-US', grade: 'C+' },
+ am_santa: { gender: 'Male', language: 'en-US', grade: 'D-' },
+ bf_alice: { gender: 'Female', language: 'en-GB', grade: 'D' },
+ bf_emma: { gender: 'Female', language: 'en-GB', grade: 'B-' },
+ bf_isabella: { gender: 'Female', language: 'en-GB', grade: 'C' },
+ bf_lily: { gender: 'Female', language: 'en-GB', grade: 'D' },
+ bm_daniel: { gender: 'Male', language: 'en-GB', grade: 'D' },
+ bm_fable: { gender: 'Male', language: 'en-GB', grade: 'C' },
+ bm_george: { gender: 'Male', language: 'en-GB', grade: 'C' },
+ bm_lewis: { gender: 'Male', language: 'en-GB', grade: 'D+' },
+});
diff --git a/server/services/voice/llm.js b/server/services/voice/llm.js
new file mode 100644
index 0000000000..2f9f3f05c6
--- /dev/null
+++ b/server/services/voice/llm.js
@@ -0,0 +1,133 @@
+// LM Studio streaming chat — SSE parser yielding token deltas via onDelta callback.
+
+const LM_STUDIO_BASE = () => (process.env.LM_STUDIO_URL || 'http://localhost:1234')
+ .replace(/\/+$/, '').replace(/\/v1$/, '');
+
+// Approximate parameter count from LM Studio model id so 'auto' avoids a 70B
+// when smaller, faster models are available. Returns Infinity for non-matches
+// and utility models so they sort last rather than silently winning ties.
+// Accepts "7B", "7 B", "7b", "1.5B" plus MoE ids like "8x7B" (ranked by total
+// experts × per-expert size; checked first so the naive `\d+\s*b\b` match
+// doesn't silently rank "8x7B" as 7B). Utility-model filter runs first and is
+// case-insensitive so "BAAI/bge-embed" / "Cohere/rerank" are excluded even
+// when they happen to contain a size token.
+const sizeRank = (id) => {
+ const normalized = String(id).toLowerCase();
+ if (/embed|rerank/.test(normalized)) return Infinity;
+ const moe = normalized.match(/(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*b\b/);
+ if (moe) return parseFloat(moe[1]) * parseFloat(moe[2]);
+ const m = normalized.match(/(\d+(?:\.\d+)?)\s*b\b/);
+ if (m) return parseFloat(m[1]);
+ return Infinity;
+};
+
+const resolveModel = async (requested) => {
+ const res = await fetch(`${LM_STUDIO_BASE()}/v1/models`).catch(() => null);
+ if (!res || !res.ok) return requested && requested !== 'auto' ? requested : null;
+ const body = await res.json();
+ const ids = (body?.data || []).map((m) => m.id);
+ if (requested && requested !== 'auto') {
+ return ids.includes(requested) ? requested : ids[0] || null;
+ }
+ // 'auto' → smallest non-utility model, or first if no size info
+ const sorted = ids.slice().sort((a, b) => sizeRank(a) - sizeRank(b));
+ return sorted[0] || null;
+};
+
+/**
+ * Stream an LM Studio chat completion. Text deltas are forwarded via onDelta
+ * for TTS; tool_call fragments are buffered per-index and returned at the end
+ * so the pipeline can execute them and loop.
+ *
+ * @param {Array<object>} messages
+ * @param {object} opts
+ * @param {string} [opts.model='auto']
+ * @param {AbortSignal} [opts.signal]
+ * @param {(delta: string) => void} [opts.onDelta]
+ * @param {Array<object>} [opts.tools] OpenAI-format tool specs (optional)
+ * @returns {Promise<{ text: string, toolCalls: Array<object>, model: string|null, ttfbMs: number|null, totalMs: number, finishReason: string|null }>}
+ */
+export const streamChat = async (messages, opts = {}) => {
+ const model = await resolveModel(opts.model);
+ if (!model) throw new Error('No LM Studio model available');
+
+ const started = Date.now();
+ const body = {
+ model,
+ messages,
+ stream: true,
+ temperature: 0.5,
+ max_tokens: opts.maxTokens ?? 250,
+ };
+ if (opts.tools?.length) {
+ body.tools = opts.tools;
+ body.tool_choice = opts.toolChoice ?? 'auto';
+ }
+
+ const res = await fetch(`${LM_STUDIO_BASE()}/v1/chat/completions`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ signal: opts.signal,
+ });
+ if (!res.ok || !res.body) {
+ const errBody = await res.text().catch(() => '');
+ throw new Error(`LM Studio chat failed: ${res.status} ${errBody.slice(0, 200)}`);
+ }
+
+ const decoder = new TextDecoder();
+ const reader = res.body.getReader();
+ let buffer = '';
+ let text = '';
+ let ttfbMs = null;
+ let finishReason = null;
+ // Tool calls stream as fragments keyed by index; accumulate until [DONE].
+ const toolCallFrags = new Map();
+
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+
+ let idx;
+ while ((idx = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, idx).trim();
+ buffer = buffer.slice(idx + 1);
+ if (!line.startsWith('data:')) continue;
+ const payload = line.slice(5).trim();
+ if (payload === '[DONE]') {
+ const toolCalls = [...toolCallFrags.values()].sort((a, b) => a.index - b.index);
+ return { text, toolCalls, model, ttfbMs, totalMs: Date.now() - started, finishReason };
+ }
+ // Malformed SSE frames (proxy keep-alive, truncated write) would otherwise
+ // abort the whole turn; skip the line and keep streaming.
+ let obj;
+ try { obj = JSON.parse(payload); } catch { continue; }
+ const choice = obj?.choices?.[0];
+ if (choice?.finish_reason) finishReason = choice.finish_reason;
+ const delta = choice?.delta || {};
+ if (delta.content) {
+ if (ttfbMs === null) ttfbMs = Date.now() - started;
+ text += delta.content;
+ opts.onDelta?.(delta.content);
+ }
+ for (const tc of delta.tool_calls || []) {
+ const frag = toolCallFrags.get(tc.index) || {
+ index: tc.index,
+ id: '',
+ type: 'function',
+ function: { name: '', arguments: '' },
+ };
+ if (tc.id) frag.id = tc.id;
+ if (tc.type) frag.type = tc.type;
+ // `name` is sent once per tool call per the OpenAI spec; set-once
+ // rather than concatenate so a split fragment can't produce garbage.
+ if (tc.function?.name && !frag.function.name) frag.function.name = tc.function.name;
+ if (tc.function?.arguments) frag.function.arguments += tc.function.arguments;
+ toolCallFrags.set(tc.index, frag);
+ }
+ }
+ }
+ const toolCalls = [...toolCallFrags.values()].sort((a, b) => a.index - b.index);
+ return { text, toolCalls, model, ttfbMs, totalMs: Date.now() - started, finishReason };
+};
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
new file mode 100644
index 0000000000..52ee21d6fb
--- /dev/null
+++ b/server/services/voice/pipeline.js
@@ -0,0 +1,223 @@
+// One conversational turn: audio → STT → streaming LLM (with tool-calling
+// loop) → sentence-boundary TTS. If the model emits tool_calls, each is
+// executed server-side, the result is appended to the message list, and the
+// LLM is called again — up to cfg.llm.tools.maxIterations rounds.
+// Caller supplies an `emit` callback (sockets/voice.js passes socket.emit)
+// and an AbortSignal; aborting tears down the LLM stream and skips pending
+// sentences.
+
+import { transcribe } from './stt.js';
+import { synthesize } from './tts.js';
+import { streamChat } from './llm.js';
+import { getVoiceConfig } from './config.js';
+import { getToolSpecs, dispatchTool } from './tools.js';
+
+const buildSystemPrompt = (cfg) => {
+ if (!cfg.llm.usePersonality) return cfg.llm.systemPrompt;
+ const p = cfg.llm.personality || {};
+ const name = p.name || 'your Chief of Staff';
+ const role = p.role || 'Chief of Staff';
+ const lines = [
+ `You are ${name}, ${role} for the user.`,
+ 'Your replies are spoken aloud — keep them short and use plain prose. No markdown, no lists, no headings, no code fences.',
+ ];
+ if (p.speechStyle) lines.push(`Speech style: ${p.speechStyle}.`);
+ if (Array.isArray(p.traits) && p.traits.length) lines.push(`Personality: ${p.traits.join(', ')}.`);
+ if (cfg.llm.tools?.enabled) {
+ // Critical: with tools on, the model must ACTUALLY call them, not just
+ // speak as if it did. Confirm only *after* a tool call succeeds.
+ lines.push('You have tools for acting on the user\'s behalf (for example, saving to the brain inbox). When the user asks you to save, capture, add, remember, note, or file something, you MUST call the matching tool — do not just reply in words. After the tool runs, confirm briefly in one short sentence using the exact words the user said. If you reference the brain inbox, call it "brain inbox" (not "green inbox" or any other near-homophone).');
+ } else {
+ // Prevent hallucinated actions when tools are disabled.
+ lines.push('You cannot take actions right now — no tools are enabled. If the user asks you to save, add, or remember something, acknowledge the request and honestly say you can\'t file it yourself yet. Do not claim to have done anything.');
+ }
+ if (p.customPrompt) lines.push(p.customPrompt);
+ return lines.join(' ');
+};
+
+const SENTENCE_RE = /[.!?\n](?:\s+|$)/;
+
+// Exported for unit testing — the sentence-boundary logic is too central to
+// leave untested.
+export const splitSentences = (buffer) => {
+ const out = [];
+ let rest = buffer;
+ while (true) {
+ const m = rest.match(SENTENCE_RE);
+ if (!m || m.index === undefined) break;
+ const end = m.index + m[0].length;
+ const sentence = rest.slice(0, end).trim();
+ if (sentence) out.push(sentence);
+ rest = rest.slice(end);
+ }
+ return { sentences: out, remainder: rest };
+};
+
+/**
+ * Run one turn.
+ *
+ * @param {object} args
+ * @param {Buffer} args.audio — utterance audio bytes
+ * @param {string} args.mimeType — e.g. 'audio/webm', 'audio/wav'
+ * @param {Array} args.history — prior conversation messages
+ * @param {(event:string, payload:any) => void} args.emit
+ * @param {AbortSignal} [args.signal]
+ * @returns {Promise<{ transcript: string, reply: string }>}
+ */
+// Whisper tags non-speech as bracketed markers like [BLANK_AUDIO], [MUSIC],
+// [LAUGHTER], [INAUDIBLE]. Treat those as empty so we don't waste an LLM turn.
+export const isNonSpeechMarker = (text) => /^\s*\[[A-Z_ ]+\]\s*$/i.test(text);
+
+export const runTurn = async ({ audio, text, mimeType, history = [], emit, signal }) => {
+ const cfg = await getVoiceConfig();
+ if (signal?.aborted) return { transcript: '', reply: '' };
+
+ const turnStart = Date.now();
+
+ let userText = text;
+ let sttLatencyMs = 0;
+ if (!userText) {
+ const stt = await transcribe(audio, { mimeType, signal });
+ sttLatencyMs = stt.latencyMs;
+ userText = isNonSpeechMarker(stt.text) ? '' : stt.text;
+ emit('voice:transcript', { text: userText, latencyMs: stt.latencyMs });
+ } else {
+ emit('voice:transcript', { text: userText, latencyMs: 0, source: 'text' });
+ }
+
+ if (!userText) {
+ console.log(`🎙️ voice: empty input (stt=${sttLatencyMs}ms)`);
+ emit('voice:idle', { reason: 'empty-transcript' });
+ return { transcript: '', reply: '' };
+ }
+ if (signal?.aborted) return { transcript: userText, reply: '' };
+
+ const messages = [
+ { role: 'system', content: buildSystemPrompt(cfg) },
+ ...history,
+ { role: 'user', content: userText },
+ ];
+
+ const toolsEnabled = !!cfg.llm.tools?.enabled;
+ const toolSpecs = toolsEnabled ? getToolSpecs() : undefined;
+ const maxIterations = Math.max(1, cfg.llm.tools?.maxIterations ?? 3);
+
+ let pending = '';
+ const ttsTimings = [];
+ const speak = async (sentence) => {
+ if (signal?.aborted || !sentence) return;
+ const { wav, latencyMs } = await synthesize(sentence, { signal });
+ if (signal?.aborted) return;
+ ttsTimings.push(latencyMs);
+ emit('voice:tts:audio', { sentence, wav, latencyMs });
+ };
+
+ let synthQueue = Promise.resolve();
+ const flushSentence = (delta) => {
+ pending += delta;
+ const { sentences, remainder } = splitSentences(pending);
+ pending = remainder;
+ for (const s of sentences) {
+ synthQueue = synthQueue.then(() => speak(s)).catch((err) => {
+ // Barge-in aborts the turn mid-synthesis — Kokoro throws Error('aborted')
+ // and Piper rejects 'piper synthesis aborted'. That's expected, not a
+ // real failure, so don't surface it as voice:error.
+ if (signal?.aborted || /aborted/i.test(err?.message || '')) return;
+ emit('voice:error', { stage: 'tts', message: err.message });
+ });
+ }
+ };
+
+ let firstLlm = null;
+ let lastLlm = null;
+ let finalText = '';
+ const toolRuns = []; // [{ name, ok, ms, error }]
+
+ for (let iter = 0; iter < maxIterations; iter++) {
+ if (signal?.aborted) break;
+
+ const llm = await streamChat(messages, {
+ model: cfg.llm.model,
+ signal,
+ tools: toolSpecs,
+ onDelta: (delta) => {
+ emit('voice:llm:delta', { delta });
+ flushSentence(delta);
+ },
+ });
+ if (!firstLlm) firstLlm = llm;
+ lastLlm = llm;
+ // Accumulate spoken text across tool-calling iterations. The old single-
+ // assignment version dropped every earlier segment, so the persisted
+ // `reply` (and next turn's history) diverged from what the user actually
+ // heard when the model spoke before/between tool calls.
+ if (llm.text) finalText += (finalText ? ' ' : '') + llm.text;
+
+ if (!llm.toolCalls?.length) break;
+
+ // Assign stable IDs up-front so the assistant's tool_calls[].id and each
+ // tool response's tool_call_id are guaranteed to match, even when the
+ // upstream stream omitted tc.id. Previously the fallback `call_<index>`
+ // was computed only at the tool-response side, so the assistant entry
+ // could carry a different id and the next LLM iteration wouldn't pair
+ // the result with the call.
+ const callsWithIds = llm.toolCalls.map((tc, i) => ({
+ ...tc,
+ resolvedId: tc.id || `call_${iter}_${tc.index ?? i}`,
+ }));
+
+ // Persist the assistant's tool-call turn, then execute each call and
+ // feed the result back as a 'tool' message for the next iteration.
+ messages.push({
+ role: 'assistant',
+ content: llm.text || null,
+ tool_calls: callsWithIds.map((tc) => ({
+ id: tc.resolvedId,
+ type: tc.type,
+ function: { name: tc.function.name, arguments: tc.function.arguments },
+ })),
+ });
+
+ for (const tc of callsWithIds) {
+ if (signal?.aborted) break;
+ const t0 = Date.now();
+ let result;
+ let args = {};
+ try {
+ args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
+ result = await dispatchTool(tc.function.name, args);
+ toolRuns.push({ name: tc.function.name, ok: true, ms: Date.now() - t0 });
+ } catch (err) {
+ result = { ok: false, error: err.message };
+ toolRuns.push({ name: tc.function.name, ok: false, ms: Date.now() - t0, error: err.message });
+ }
+ emit('voice:tool', { name: tc.function.name, args, result });
+ messages.push({
+ role: 'tool',
+ tool_call_id: tc.resolvedId,
+ content: JSON.stringify(result),
+ });
+ }
+ }
+
+ if (pending.trim()) synthQueue = synthQueue.then(() => speak(pending.trim()));
+ await synthQueue;
+
+ const totalMs = Date.now() - turnStart;
+ const ttsTotal = ttsTimings.reduce((a, b) => a + b, 0);
+ const source = text ? 'text' : 'voice';
+ const toolSummary = toolRuns.length
+ ? ` · tools=${toolRuns.map((r) => `${r.name}(${r.ok ? `${r.ms}ms` : 'err'})`).join(',')}`
+ : '';
+ console.log(
+ `🎙️ ${source} turn ${totalMs}ms — ` +
+ `stt=${sttLatencyMs}ms · ` +
+ `llm[${lastLlm?.model}] ttft=${firstLlm?.ttfbMs ?? '—'}ms total=${lastLlm?.totalMs}ms · ` +
+ `tts=${ttsTotal}ms (${ttsTimings.length} sentences)` +
+ toolSummary
+ );
+
+ emit('voice:llm:done', { text: finalText, model: lastLlm?.model, ttfbMs: firstLlm?.ttfbMs });
+ emit('voice:idle', { reason: 'turn-complete' });
+ return { transcript: userText, reply: finalText };
+};
diff --git a/server/services/voice/pipeline.test.js b/server/services/voice/pipeline.test.js
new file mode 100644
index 0000000000..0c98955151
--- /dev/null
+++ b/server/services/voice/pipeline.test.js
@@ -0,0 +1,75 @@
+import { describe, it, expect } from 'vitest';
+import { splitSentences, isNonSpeechMarker } from './pipeline.js';
+
+describe('splitSentences', () => {
+ it('returns empty when no terminator is present', () => {
+ const { sentences, remainder } = splitSentences('hello world no terminator');
+ expect(sentences).toEqual([]);
+ expect(remainder).toBe('hello world no terminator');
+ });
+
+ it('splits on period + whitespace, preserving terminator', () => {
+ // Terminator followed by end-of-string also matches, so the trailing
+ // "Second sentence." gets flushed too.
+ const { sentences, remainder } = splitSentences('First sentence. Second sentence.');
+ expect(sentences).toEqual(['First sentence.', 'Second sentence.']);
+ expect(remainder).toBe('');
+ });
+
+ it('drains multiple complete sentences in a single call', () => {
+ const { sentences, remainder } = splitSentences('One. Two. Three. ');
+ expect(sentences).toEqual(['One.', 'Two.', 'Three.']);
+ expect(remainder).toBe('');
+ });
+
+ it('handles ! and ? as sentence terminators', () => {
+ const { sentences, remainder } = splitSentences('Wait! Really? Yes.');
+ expect(sentences).toEqual(['Wait!', 'Really?', 'Yes.']);
+ expect(remainder).toBe('');
+ });
+
+ it('splits on newline followed by whitespace', () => {
+ // Regex needs more whitespace after the terminator (or EOS); bare `\n`
+ // followed by a non-space char does NOT split — keeps paragraphs intact
+ // until the LLM writes a real paragraph break.
+ const kept = splitSentences('line one\nline two');
+ expect(kept.sentences).toEqual([]);
+ expect(kept.remainder).toBe('line one\nline two');
+
+ const split = splitSentences('line one\n line two');
+ expect(split.sentences).toEqual(['line one']);
+ expect(split.remainder).toBe('line two');
+ });
+
+ it('keeps incomplete trailing text as remainder', () => {
+ const { sentences, remainder } = splitSentences('Done. Still typin');
+ expect(sentences).toEqual(['Done.']);
+ expect(remainder).toBe('Still typin');
+ });
+
+ it('is idempotent when called with the remainder repeatedly', () => {
+ // Simulate streaming deltas: first chunk has no terminator, second adds it.
+ const first = splitSentences('partial');
+ expect(first.sentences).toEqual([]);
+ const second = splitSentences(first.remainder + ' sentence.');
+ expect(second.sentences).toEqual(['partial sentence.']);
+ expect(second.remainder).toBe('');
+ });
+});
+
+describe('isNonSpeechMarker', () => {
+ it('detects whisper non-speech markers', () => {
+ expect(isNonSpeechMarker('[BLANK_AUDIO]')).toBe(true);
+ expect(isNonSpeechMarker('[MUSIC]')).toBe(true);
+ expect(isNonSpeechMarker('[LAUGHTER]')).toBe(true);
+ expect(isNonSpeechMarker('[INAUDIBLE]')).toBe(true);
+ expect(isNonSpeechMarker(' [BLANK_AUDIO] ')).toBe(true);
+ });
+
+ it('does not match real speech', () => {
+ expect(isNonSpeechMarker('hello world')).toBe(false);
+ expect(isNonSpeechMarker('[BLANK] plus words')).toBe(false);
+ expect(isNonSpeechMarker('')).toBe(false);
+ expect(isNonSpeechMarker('note: [TODO]')).toBe(false);
+ });
+});
diff --git a/server/services/voice/piper-voices.js b/server/services/voice/piper-voices.js
new file mode 100644
index 0000000000..ce75e848f7
--- /dev/null
+++ b/server/services/voice/piper-voices.js
@@ -0,0 +1,56 @@
+// Curated Piper voice catalog — small, hand-picked set for comparison against
+// Kokoro. These are ONNX voices from https://huggingface.co/rhasspy/piper-voices.
+// Each entry maps to `<lang>/<locale>/<speaker>/<quality>/<id>.onnx` on HF.
+//
+// `speakerId` is used with multi-speaker models (VCTK). Piper accepts it via
+// `--speaker <id>`. Indices follow the VCTK speaker-sorted order baked into
+// the rhasspy Piper VCTK checkpoint (p225=0 … p376=108), so 39 ≈ p266, a known
+// Irish female. Changing this index lets you audition other VCTK speakers.
+
+export const PIPER_VOICES = Object.freeze([
+ {
+ id: 'en_GB-jenny_dioco-medium',
+ gender: 'Female',
+ accent: 'British (Jenny Dioco)',
+ note: 'Clean, neutral British female',
+ sizeMB: 63,
+ },
+ {
+ id: 'en_GB-southern_english_female-low',
+ gender: 'Female',
+ accent: 'Southern English',
+ note: 'Low-quality model, small + fast',
+ sizeMB: 28,
+ },
+ {
+ id: 'en_GB-cori-high',
+ gender: 'Female',
+ accent: 'British (Cori, high)',
+ note: 'Highest-quality Piper English female',
+ sizeMB: 115,
+ },
+ {
+ id: 'en_GB-alba-medium',
+ gender: 'Female',
+ accent: 'Scottish (Alba)',
+ note: 'Closest Piper has to a non-English UK regional',
+ sizeMB: 63,
+ },
+ {
+ id: 'en_GB-vctk-medium',
+ gender: 'Female',
+ accent: 'Irish (VCTK p266)',
+ note: 'Multi-speaker VCTK; speakerId picks the accent',
+ speakerId: 39,
+ sizeMB: 75,
+ },
+ {
+ id: 'en_US-amy-medium',
+ gender: 'Female',
+ accent: 'American (Amy)',
+ note: 'US comparison baseline',
+ sizeMB: 63,
+ },
+]);
+
+export const findPiperVoice = (id) => PIPER_VOICES.find((v) => v.id === id) || null;
diff --git a/server/services/voice/stt.js b/server/services/voice/stt.js
new file mode 100644
index 0000000000..78ac2ce49d
--- /dev/null
+++ b/server/services/voice/stt.js
@@ -0,0 +1,67 @@
+// Speech-to-text via whisper.cpp's built-in HTTP server (POST /inference).
+// Docs: https://github.com/ggerganov/whisper.cpp/tree/master/examples/server
+
+import { getVoiceConfig } from './config.js';
+
+const STT_TIMEOUT_MS = 30_000;
+
+// Vocabulary bias: whisper.cpp's `prompt` field seeds the decoder with context
+// so proper nouns and PortOS-specific terms are transcribed correctly instead
+// of being mapped to common English homophones ("brain inbox" → "green inbox").
+const DEFAULT_STT_PROMPT = 'PortOS, Chief of Staff, brain inbox, brain capture, task, agent, TASKS.md, Tailscale, Socket.IO, LM Studio, Whisper, Kokoro, Piper.';
+
+/**
+ * Transcribe a Buffer/Uint8Array of audio bytes.
+ * @param {Buffer|Uint8Array} audio - audio payload (wav/webm/mp3)
+ * @param {object} [opts]
+ * @param {string} [opts.language='en']
+ * @param {string} [opts.mimeType='audio/wav']
+ * @param {string} [opts.endpoint] override default endpoint
+ * @param {AbortSignal} [opts.signal] upstream abort (barge-in) — cancels STT mid-flight
+ * @returns {Promise<{ text: string, latencyMs: number }>}
+ */
+export const transcribe = async (audio, opts = {}) => {
+ const cfg = await getVoiceConfig();
+ const endpoint = opts.endpoint || cfg.stt.endpoint;
+ // Honor the configured STT language (opts override > settings > 'en').
+ // Without this, changing voice.stt.language in Settings had no effect because
+ // the pipeline calls transcribe(audio, { mimeType }) with no language arg.
+ const language = opts.language || cfg.stt.language || 'en';
+ const mimeType = opts.mimeType || 'audio/wav';
+ const filename = opts.filename || 'audio.wav';
+
+ const blob = new Blob([audio], { type: mimeType });
+ const form = new FormData();
+ form.append('file', blob, filename);
+ form.append('response_format', 'json');
+ form.append('language', language);
+ form.append('temperature', '0');
+ form.append('prompt', cfg.stt.vocabularyPrompt || DEFAULT_STT_PROMPT);
+
+ const started = Date.now();
+ // Combine the internal timeout with the caller's abort signal so barge-in
+ // can tear down an in-flight whisper request. If the caller's signal is
+ // already aborted, short-circuit without hitting the network.
+ if (opts.signal?.aborted) throw new Error('transcribe aborted');
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), STT_TIMEOUT_MS);
+ const onCallerAbort = () => controller.abort();
+ opts.signal?.addEventListener?.('abort', onCallerAbort, { once: true });
+
+ const res = await fetch(`${endpoint}/inference`, {
+ method: 'POST',
+ body: form,
+ signal: controller.signal,
+ }).finally(() => {
+ clearTimeout(timer);
+ opts.signal?.removeEventListener?.('abort', onCallerAbort);
+ });
+
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ throw new Error(`whisper inference failed: ${res.status} ${res.statusText} ${body.slice(0, 200)}`);
+ }
+
+ const data = await res.json();
+ return { text: (data.text || '').trim(), latencyMs: Date.now() - started };
+};
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
new file mode 100644
index 0000000000..cab6189949
--- /dev/null
+++ b/server/services/voice/tools.js
@@ -0,0 +1,534 @@
+// Tool registry for the voice Chief-of-Staff. Each tool has an OpenAI-format
+// function schema (fed to the LLM) plus an execute() that runs the action.
+// Add a new tool by pushing another entry onto TOOLS.
+
+import { captureThought, getInboxLog } from '../brain.js';
+import { logDrink, getAlcoholSummary } from '../meatspaceAlcohol.js';
+import { logNicotine, getNicotineSummary } from '../meatspaceNicotine.js';
+import { addBodyEntry } from '../meatspaceHealth.js';
+import { getGoals, updateGoalProgress, addProgressEntry } from '../identity.js';
+import { listProcesses, restartApp } from '../pm2.js';
+import { getItems, getFeeds } from '../feeds.js';
+import { getUserTimezone, todayInTimezone, getLocalParts } from '../../lib/timezone.js';
+
+// Shorthand presets for voice logging. A user saying "I had a beer" should
+// not need to recite oz + ABV — these defaults match typical US servings.
+const DRINK_PRESETS = {
+ beer: { oz: 12, abv: 5 },
+ wine: { oz: 5, abv: 13 },
+ whiskey: { oz: 1.5, abv: 40 },
+ shot: { oz: 1.5, abv: 40 },
+ cocktail:{ oz: 3, abv: 20 },
+};
+
+const NICOTINE_PRESETS = {
+ cigarette: { mgPerUnit: 1 },
+ vape: { mgPerUnit: 1 },
+ pouch: { mgPerUnit: 6 },
+};
+
+const resolveDrinkPreset = (name) => {
+ const key = Object.keys(DRINK_PRESETS).find((k) => name.toLowerCase().includes(k));
+ return key ? DRINK_PRESETS[key] : DRINK_PRESETS.beer;
+};
+
+const resolveNicotinePreset = (product) => {
+ const key = Object.keys(NICOTINE_PRESETS).find((k) => product.toLowerCase().includes(k));
+ return key ? NICOTINE_PRESETS[key] : NICOTINE_PRESETS.cigarette;
+};
+
+// Score goals against a voice query. Users say "my jacket goal", "the estate
+// property one" — we need forgiving substring matching on title + any token.
+const scoreGoalMatch = (goal, query) => {
+ const title = (goal.title || '').toLowerCase();
+ const q = query.toLowerCase().trim();
+ if (!title || !q) return 0;
+ if (title === q) return 100;
+ if (title.includes(q)) return 80;
+ const qTokens = q.split(/\s+/).filter((t) => t.length >= 3);
+ if (!qTokens.length) return 0;
+ const hits = qTokens.filter((t) => title.includes(t)).length;
+ return hits ? (hits / qTokens.length) * 60 : 0;
+};
+
+const findGoalByQuery = (goals, query) => {
+ const active = goals.filter((g) => g.status === 'active' || !g.status);
+ const scored = active
+ .map((g) => ({ goal: g, score: scoreGoalMatch(g, query) }))
+ .filter((s) => s.score > 0)
+ .sort((a, b) => b.score - a.score);
+ if (!scored.length) return { match: null, candidates: [] };
+ return { match: scored[0].goal, candidates: scored.slice(0, 4).map((s) => s.goal) };
+};
+
+const TOOLS = [
+ {
+ name: 'brain_capture',
+ description:
+ 'Capture a thought, note, idea, todo, reminder, or any free-form information to the user\'s brain inbox for later classification. Use whenever the user asks you to remember, add, save, note, or jot something down. The text should be in the user\'s own words with enough detail that it\'s useful later.',
+ parameters: {
+ type: 'object',
+ properties: {
+ text: {
+ type: 'string',
+ description: 'The content to capture, phrased naturally. Include who/what/when/why details if the user mentioned them.',
+ },
+ },
+ required: ['text'],
+ },
+ execute: async ({ text }) => {
+ if (!text || typeof text !== 'string') throw new Error('text is required');
+ const trimmed = text.trim();
+ if (!trimmed) throw new Error('text must not be empty');
+ // captureThought returns { inboxLog, message } — the inbox record id
+ // lives inside inboxLog; returning `entry.id` was `undefined`.
+ const { inboxLog } = await captureThought(trimmed);
+ return {
+ ok: true,
+ id: inboxLog?.id,
+ summary: `Captured "${trimmed.slice(0, 60)}${trimmed.length > 60 ? '…' : ''}"`,
+ };
+ },
+ },
+
+ {
+ name: 'brain_search',
+ description:
+ 'Search the user\'s brain inbox for previously captured thoughts, notes, or ideas. Use when the user asks "what did I say about X?", "do I have any notes on Y?", or wants to recall something they captured earlier. Returns up to 5 matching entries with their capture text and date.',
+ parameters: {
+ type: 'object',
+ properties: {
+ query: {
+ type: 'string',
+ description: 'Substring to search for in captured text (case-insensitive). Use the most distinctive keyword the user mentioned.',
+ },
+ limit: {
+ type: 'integer',
+ description: 'Max results to return (default 5, max 10).',
+ },
+ },
+ required: ['query'],
+ },
+ execute: async ({ query, limit = 5 }) => {
+ if (!query || typeof query !== 'string') throw new Error('query is required');
+ const q = query.trim().toLowerCase();
+ // `String.includes('')` matches everything, so an all-whitespace query
+ // would return unrelated entries — reject instead of surprising the user.
+ if (!q) throw new Error('query must not be empty');
+ const max = Math.max(1, Math.min(10, limit || 5));
+ // Load a reasonable window — the brain inbox is small enough that an
+ // in-memory filter is fine and avoids a second storage pass for ranking.
+ const records = await getInboxLog({ limit: 200 });
+ const hits = records
+ .filter((r) => (r.capturedText || '').toLowerCase().includes(q))
+ .slice(0, max)
+ .map((r) => ({
+ id: r.id,
+ date: (r.capturedAt || '').slice(0, 10),
+ text: r.capturedText,
+ }));
+ return {
+ ok: true,
+ count: hits.length,
+ hits,
+ summary: hits.length
+ ? `Found ${hits.length} match${hits.length === 1 ? '' : 'es'} for "${query}"`
+ : `No captures matched "${query}"`,
+ };
+ },
+ },
+
+ {
+ name: 'meatspace_log_drink',
+ description:
+ 'Log an alcoholic drink to MortalLoom / Meatspace tracking. Use when the user says things like "I had a beer", "log a glass of wine", "I just had two whiskeys". The "name" field takes free-form ("IPA", "Cabernet", "Old Fashioned") — known categories (beer/wine/whiskey/shot/cocktail) get sensible oz+ABV defaults, otherwise the user should specify oz+abv explicitly.',
+ parameters: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Drink name or category (e.g. "beer", "IPA", "Cabernet", "whiskey").' },
+ count: { type: 'number', description: 'How many (default 1).' },
+ oz: { type: 'number', description: 'Serving size in ounces. Omit to use category default.' },
+ abv: { type: 'number', description: 'Alcohol by volume percent (e.g. 5 for 5%). Omit to use category default.' },
+ },
+ required: ['name'],
+ },
+ execute: async ({ name, count = 1, oz, abv }) => {
+ if (!name || typeof name !== 'string') throw new Error('name is required');
+ const trimmedName = name.trim();
+ if (!trimmedName) throw new Error('name must not be empty');
+ // Tool args come from an LLM — guard against negative/NaN counts, absurd
+ // serving sizes (gallons), and impossible ABV (>100%) before persistence.
+ if (!Number.isFinite(count) || count <= 0 || count > 50) {
+ throw new Error('count must be a positive number (≤50)');
+ }
+ const preset = resolveDrinkPreset(trimmedName);
+ const resolvedOz = oz ?? preset.oz;
+ const resolvedAbv = abv ?? preset.abv;
+ if (!Number.isFinite(resolvedOz) || resolvedOz <= 0 || resolvedOz > 128) {
+ throw new Error('oz must be a positive number (≤128)');
+ }
+ if (!Number.isFinite(resolvedAbv) || resolvedAbv < 0 || resolvedAbv > 100) {
+ throw new Error('abv must be between 0 and 100');
+ }
+ const result = await logDrink({
+ name: trimmedName,
+ oz: resolvedOz,
+ abv: resolvedAbv,
+ count,
+ });
+ return {
+ ok: true,
+ summary: `Logged ${count} ${trimmedName} (${result.standardDrinks.toFixed(1)} std drinks). Day total: ${result.dayTotal.toFixed(1)} std drinks.`,
+ };
+ },
+ },
+
+ {
+ name: 'meatspace_log_nicotine',
+ description:
+ 'Log nicotine use (cigarette, vape puff, pouch) to MortalLoom / Meatspace tracking. Use when the user says "I had a cigarette", "two pouches", "just vaped". Known categories (cigarette/vape/pouch) get sensible mgPerUnit defaults; otherwise specify mgPerUnit explicitly.',
+ parameters: {
+ type: 'object',
+ properties: {
+ product: { type: 'string', description: 'Product type (e.g. "cigarette", "vape", "Zyn pouch", "cigar").' },
+ count: { type: 'number', description: 'How many units (default 1).' },
+ mgPerUnit: { type: 'number', description: 'Nicotine milligrams per unit. Omit to use category default.' },
+ },
+ required: ['product'],
+ },
+ execute: async ({ product, count = 1, mgPerUnit }) => {
+ if (!product || typeof product !== 'string') throw new Error('product is required');
+ const trimmedProduct = product.trim();
+ if (!trimmedProduct) throw new Error('product must not be empty');
+ if (!Number.isFinite(count) || count <= 0 || count > 100) {
+ throw new Error('count must be a positive number (≤100)');
+ }
+ const preset = resolveNicotinePreset(trimmedProduct);
+ const resolvedMg = mgPerUnit ?? preset.mgPerUnit;
+ if (!Number.isFinite(resolvedMg) || resolvedMg < 0 || resolvedMg > 200) {
+ throw new Error('mgPerUnit must be between 0 and 200');
+ }
+ const result = await logNicotine({
+ product: trimmedProduct,
+ mgPerUnit: resolvedMg,
+ count,
+ });
+ return {
+ ok: true,
+ summary: `Logged ${count} ${trimmedProduct} (${result.totalMg}mg). Day total: ${result.dayTotal.toFixed(1)}mg nicotine.`,
+ };
+ },
+ },
+
+ {
+ name: 'meatspace_summary_today',
+ description:
+ 'Report today\'s alcohol and nicotine totals against rolling averages. Use when the user asks "how am I doing today?", "what\'s my drink count?", "have I had any cigarettes today?".',
+ parameters: { type: 'object', properties: {} },
+ execute: async () => {
+ const [alcohol, nicotine] = await Promise.all([getAlcoholSummary(), getNicotineSummary()]);
+ const parts = [
+ alcohol.today > 0
+ ? `${alcohol.today.toFixed(1)} standard drinks today`
+ : 'No drinks logged today',
+ nicotine.today > 0
+ ? `${nicotine.today.toFixed(1)}mg nicotine today`
+ : 'No nicotine logged today',
+ ];
+ if (alcohol.avg7day) parts.push(`7-day avg ${alcohol.avg7day.toFixed(1)} drinks/day`);
+ if (nicotine.avg7day) parts.push(`${nicotine.avg7day.toFixed(1)}mg/day nicotine avg`);
+ return { ok: true, summary: parts.join('. ') + '.' };
+ },
+ },
+
+ {
+ name: 'brain_list_recent',
+ description:
+ 'Read back the user\'s most recently captured brain-inbox entries. Use when they ask "what are my last notes?", "read me my recent captures", "what did I jot down today?".',
+ parameters: {
+ type: 'object',
+ properties: {
+ limit: {
+ type: 'integer',
+ description: 'How many entries to return (default 5, max 10).',
+ },
+ },
+ },
+ execute: async ({ limit = 5 } = {}) => {
+ const max = Math.max(1, Math.min(10, limit || 5));
+ const records = await getInboxLog({ limit: max });
+ const items = records.map((r) => ({
+ date: (r.capturedAt || '').slice(0, 10),
+ text: r.capturedText,
+ }));
+ return {
+ ok: true,
+ count: items.length,
+ items,
+ summary: items.length
+ ? `Last ${items.length} capture${items.length === 1 ? '' : 's'}.`
+ : 'Brain inbox is empty.',
+ };
+ },
+ },
+
+ {
+ name: 'meatspace_log_weight',
+ description:
+ 'Log a body weight entry to MortalLoom / Meatspace tracking. Use when the user says "log my weight at 180", "I weigh 175 today", "weigh-in at eighty kilos". Defaults to today. Unit is lb unless the user explicitly mentions kg.',
+ parameters: {
+ type: 'object',
+ properties: {
+ weight: { type: 'number', description: 'Body weight value.' },
+ unit: { type: 'string', enum: ['lb', 'kg'], description: 'Unit (lb or kg). Default lb.' },
+ date: { type: 'string', description: 'ISO date (YYYY-MM-DD). Omit for today.' },
+ },
+ required: ['weight'],
+ },
+ execute: async ({ weight, unit = 'lb', date }) => {
+ if (typeof weight !== 'number' || !Number.isFinite(weight) || weight <= 0) {
+ throw new Error('weight must be a positive number');
+ }
+ // Validate unit explicitly — tool args come from an LLM, so "kgs"
+ // or "pounds" would otherwise silently be treated as lb and corrupt
+ // the body-weight log.
+ if (unit !== 'lb' && unit !== 'kg') {
+ throw new Error('unit must be either "lb" or "kg"');
+ }
+ const weightLb = unit === 'kg' ? weight * 2.2046226218 : weight;
+ // Upper guard catches STT mis-transcriptions ("eighty" → "1800") before
+ // they silently corrupt body-weight history.
+ if (weightLb > 800) throw new Error(`weight ${weight}${unit} is out of realistic range`);
+ const entry = await addBodyEntry({ date, weight: weightLb });
+ return {
+ ok: true,
+ summary: `Logged ${weight}${unit} on ${entry.date}.`,
+ };
+ },
+ },
+
+ {
+ name: 'goal_list',
+ description:
+ 'List the user\'s active goals with their current progress percent. Use when they ask "what are my goals?", "how am I doing on my goals?", "what am I working on?". Returns up to 10 goals ordered by urgency.',
+ parameters: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', description: 'Max goals to return (default 10).' },
+ },
+ },
+ execute: async ({ limit = 10 } = {}) => {
+ const max = Math.max(1, Math.min(20, limit || 10));
+ const data = await getGoals();
+ const active = (data.goals || []).filter((g) => g.status === 'active' || !g.status);
+ active.sort((a, b) => (b.urgency ?? 0) - (a.urgency ?? 0));
+ const goals = active.slice(0, max).map((g) => ({
+ title: g.title,
+ horizon: g.horizon,
+ category: g.category,
+ progress: Math.round(g.progress ?? 0),
+ }));
+ return {
+ ok: true,
+ count: goals.length,
+ goals,
+ summary: goals.length
+ ? `${goals.length} active goal${goals.length === 1 ? '' : 's'}.`
+ : 'No active goals.',
+ };
+ },
+ },
+
+ {
+ name: 'goal_update_progress',
+ description:
+ 'Update the progress percent on an active goal. Use when the user says "bump my jacket goal to 40 percent", "set my estate goal to 25", "I\'m halfway done with X". Matches the goal by fuzzy title match — if multiple match, the most relevant wins but the alternatives are reported back.',
+ parameters: {
+ type: 'object',
+ properties: {
+ goalQuery: { type: 'string', description: 'A distinctive word or phrase from the goal title ("jacket", "estate property").' },
+ progress: { type: 'number', description: 'New progress percentage, 0 to 100.' },
+ },
+ required: ['goalQuery', 'progress'],
+ },
+ execute: async ({ goalQuery, progress }) => {
+ if (typeof goalQuery !== 'string' || !goalQuery.trim()) {
+ throw new Error('goalQuery is required');
+ }
+ if (typeof progress !== 'number' || !Number.isFinite(progress) || progress < 0 || progress > 100) {
+ throw new Error('progress must be a number between 0 and 100');
+ }
+ const query = goalQuery.trim();
+ const data = await getGoals();
+ const { match, candidates } = findGoalByQuery(data.goals || [], query);
+ if (!match) {
+ return { ok: false, summary: `No active goal matched "${query}".` };
+ }
+ const prev = Math.round(match.progress ?? 0);
+ const next = Math.round(progress);
+ await updateGoalProgress(match.id, next);
+ const alts = candidates.filter((g) => g.id !== match.id).map((g) => g.title);
+ return {
+ ok: true,
+ title: match.title,
+ previous: prev,
+ current: next,
+ alternatives: alts,
+ summary: `"${match.title}" progress ${prev}% → ${next}%.`,
+ };
+ },
+ },
+
+ {
+ name: 'goal_log_note',
+ description:
+ 'Attach a free-form progress note to an active goal (without changing the percent). Use when the user says "log on my X goal that I talked to Y", "add a note to my jacket goal — found the pattern". Matches the goal by fuzzy title match.',
+ parameters: {
+ type: 'object',
+ properties: {
+ goalQuery: { type: 'string', description: 'A distinctive word or phrase from the goal title.' },
+ note: { type: 'string', description: 'The progress note in the user\'s words.' },
+ durationMinutes: { type: 'number', description: 'Optional time spent on this activity (minutes).' },
+ },
+ required: ['goalQuery', 'note'],
+ },
+ execute: async ({ goalQuery, note, durationMinutes }) => {
+ if (typeof goalQuery !== 'string' || !goalQuery.trim()) {
+ throw new Error('goalQuery is required');
+ }
+ if (typeof note !== 'string' || !note.trim()) throw new Error('note is required');
+ const query = goalQuery.trim();
+ const data = await getGoals();
+ const { match } = findGoalByQuery(data.goals || [], query);
+ if (!match) {
+ return { ok: false, summary: `No active goal matched "${query}".` };
+ }
+ // Server runs TZ=UTC; "today" must be the user's local date, not UTC.
+ const today = todayInTimezone(await getUserTimezone());
+ await addProgressEntry(match.id, { date: today, note: note.trim(), durationMinutes });
+ return {
+ ok: true,
+ title: match.title,
+ summary: `Logged a note on "${match.title}".`,
+ };
+ },
+ },
+
+ {
+ name: 'pm2_status',
+ description:
+ 'Report the status of PortOS PM2 processes. Use when the user asks "is anything crashed?", "is everything running?", "any errors?". Reports total, healthy, and any processes in errored/stopped states.',
+ parameters: { type: 'object', properties: {} },
+ execute: async () => {
+ const procs = await listProcesses();
+ const unhealthy = procs.filter((p) => p.status !== 'online');
+ const online = procs.length - unhealthy.length;
+ const parts = [`${online} of ${procs.length} processes online`];
+ if (unhealthy.length) {
+ parts.push(
+ `issues: ${unhealthy.map((p) => `${p.name} (${p.status})`).join(', ')}`,
+ );
+ }
+ return {
+ ok: true,
+ total: procs.length,
+ online,
+ unhealthy: unhealthy.map((p) => ({ name: p.name, status: p.status, restarts: p.restarts })),
+ summary: parts.join('. ') + '.',
+ };
+ },
+ },
+
+ {
+ name: 'pm2_restart',
+ description:
+ 'Restart a PortOS PM2 process by name. Use when the user says "restart the whisper server", "restart portos-api", "bounce the cos runner". Only restart — never kill or delete.',
+ parameters: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'PM2 process name (or a distinctive substring).' },
+ },
+ required: ['name'],
+ },
+ execute: async ({ name }) => {
+ if (typeof name !== 'string' || !name.trim()) throw new Error('name is required');
+ const trimmed = name.trim();
+ const lower = trimmed.toLowerCase();
+ const procs = await listProcesses();
+ const exact = procs.find((p) => p.name === trimmed);
+ const match = exact
+ || procs.find((p) => p.name?.toLowerCase() === lower)
+ || procs.find((p) => p.name?.toLowerCase().includes(lower));
+ if (!match) {
+ return { ok: false, summary: `No PM2 process matched "${trimmed}".` };
+ }
+ await restartApp(match.name);
+ return { ok: true, name: match.name, summary: `Restarted ${match.name}.` };
+ },
+ },
+
+ {
+ name: 'feeds_digest',
+ description:
+ 'Summarize the user\'s unread RSS feed items. Use when the user asks "what\'s new in my feeds?", "any news?", "read me my headlines". Returns up to 5 of the newest unread items with title and feed name.',
+ parameters: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', description: 'Max items (default 5, max 10).' },
+ },
+ },
+ execute: async ({ limit = 5 } = {}) => {
+ const max = Math.max(1, Math.min(10, limit || 5));
+ const [items, feeds] = await Promise.all([getItems({ unreadOnly: true }), getFeeds()]);
+ const feedName = (id) => feeds.find((f) => f.id === id)?.title || 'feed';
+ const picks = items.slice(0, max).map((i) => ({
+ title: i.title,
+ feed: feedName(i.feedId),
+ date: (i.pubDate || i.fetchedAt || '').slice(0, 10),
+ }));
+ return {
+ ok: true,
+ totalUnread: items.length,
+ count: picks.length,
+ items: picks,
+ summary: picks.length
+ ? `${items.length} unread. Top ${picks.length}: ${picks.map((p) => `"${p.title}" (${p.feed})`).join('; ')}.`
+ : 'No unread feed items.',
+ };
+ },
+ },
+
+ {
+ name: 'time_now',
+ description:
+ 'Report the current local date, time, and day of week. Use when the user asks "what time is it?", "what day is today?", "what\'s the date?". LLMs don\'t know the current time on their own — always call this tool rather than guessing.',
+ parameters: { type: 'object', properties: {} },
+ execute: async () => {
+ // Server runs TZ=UTC, so formatting must be scoped to the user's TZ.
+ const tz = await getUserTimezone();
+ const now = new Date();
+ const fmt = (opts) => new Intl.DateTimeFormat('en-US', { timeZone: tz, ...opts }).format(now);
+ const parts = getLocalParts(now, tz);
+ return {
+ ok: true,
+ iso: now.toISOString(),
+ timezone: tz,
+ date: `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`,
+ dayOfWeek: fmt({ weekday: 'long' }),
+ time: fmt({ hour: 'numeric', minute: '2-digit' }),
+ summary: `${fmt({ weekday: 'long' })}, ${fmt({ month: 'long', day: 'numeric', year: 'numeric' })} at ${fmt({ hour: 'numeric', minute: '2-digit' })}.`,
+ };
+ },
+ },
+];
+
+export const getToolSpecs = () => TOOLS.map((t) => ({
+ type: 'function',
+ function: { name: t.name, description: t.description, parameters: t.parameters },
+}));
+
+export const dispatchTool = async (name, args) => {
+ const tool = TOOLS.find((t) => t.name === name);
+ if (!tool) throw new Error(`Unknown tool: ${name}`);
+ return tool.execute(args || {});
+};
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
new file mode 100644
index 0000000000..739d168d46
--- /dev/null
+++ b/server/services/voice/tools.test.js
@@ -0,0 +1,139 @@
+import { describe, it, expect, vi } from 'vitest';
+
+// Stub every external side-effect before importing tools.js so the unit test
+// exercises pure validation/dispatch logic without hitting the filesystem.
+vi.mock('../brain.js', () => ({
+ captureThought: vi.fn(async () => ({ inboxLog: { id: 'inbox-1' }, message: 'ok' })),
+ getInboxLog: vi.fn(async () => []),
+}));
+vi.mock('../meatspaceAlcohol.js', () => ({
+ logDrink: vi.fn(async () => ({ standardDrinks: 1, dayTotal: 1 })),
+ getAlcoholSummary: vi.fn(async () => ({ today: 0 })),
+}));
+vi.mock('../meatspaceNicotine.js', () => ({
+ logNicotine: vi.fn(async () => ({ totalMg: 1, dayTotal: 1 })),
+ getNicotineSummary: vi.fn(async () => ({ today: 0 })),
+}));
+vi.mock('../meatspaceHealth.js', () => ({
+ addBodyEntry: vi.fn(async () => ({ date: '2026-04-17' })),
+}));
+vi.mock('../identity.js', () => ({
+ getGoals: vi.fn(async () => ({ goals: [] })),
+ updateGoalProgress: vi.fn(async () => {}),
+ addProgressEntry: vi.fn(async () => {}),
+}));
+vi.mock('../pm2.js', () => ({
+ listProcesses: vi.fn(async () => []),
+ restartApp: vi.fn(async () => {}),
+}));
+vi.mock('../feeds.js', () => ({
+ getItems: vi.fn(async () => []),
+ getFeeds: vi.fn(async () => []),
+}));
+
+const { dispatchTool, getToolSpecs } = await import('./tools.js');
+
+describe('getToolSpecs', () => {
+ it('returns OpenAI-format function specs', () => {
+ const specs = getToolSpecs();
+ expect(specs.length).toBeGreaterThan(0);
+ for (const s of specs) {
+ expect(s.type).toBe('function');
+ expect(typeof s.function.name).toBe('string');
+ expect(s.function.parameters?.type).toBe('object');
+ }
+ });
+});
+
+describe('dispatchTool unknown tool', () => {
+ it('throws when tool name is unknown', async () => {
+ await expect(dispatchTool('nope_tool', {})).rejects.toThrow(/Unknown tool/);
+ });
+});
+
+describe('brain_capture validation', () => {
+ it('rejects missing text', async () => {
+ await expect(dispatchTool('brain_capture', {})).rejects.toThrow(/text is required/);
+ });
+ it('rejects whitespace-only text', async () => {
+ await expect(dispatchTool('brain_capture', { text: ' ' })).rejects.toThrow(/text must not be empty/);
+ });
+ it('returns inboxLog id on success', async () => {
+ const r = await dispatchTool('brain_capture', { text: 'remember milk' });
+ expect(r.ok).toBe(true);
+ expect(r.id).toBe('inbox-1');
+ });
+});
+
+describe('brain_search validation', () => {
+ it('rejects missing query', async () => {
+ await expect(dispatchTool('brain_search', {})).rejects.toThrow(/query is required/);
+ });
+ it('rejects whitespace-only query (would match everything)', async () => {
+ await expect(dispatchTool('brain_search', { query: ' ' })).rejects.toThrow(/query must not be empty/);
+ });
+});
+
+describe('meatspace_log_drink validation', () => {
+ it('rejects missing name', async () => {
+ await expect(dispatchTool('meatspace_log_drink', {})).rejects.toThrow(/name is required/);
+ });
+ it('rejects negative count', async () => {
+ await expect(dispatchTool('meatspace_log_drink', { name: 'beer', count: -1 }))
+ .rejects.toThrow(/count must be a positive number/);
+ });
+ it('rejects abv over 100', async () => {
+ await expect(dispatchTool('meatspace_log_drink', { name: 'beer', abv: 500 }))
+ .rejects.toThrow(/abv must be between 0 and 100/);
+ });
+ it('rejects oz over 128', async () => {
+ await expect(dispatchTool('meatspace_log_drink', { name: 'beer', oz: 999 }))
+ .rejects.toThrow(/oz must be a positive number/);
+ });
+});
+
+describe('meatspace_log_nicotine validation', () => {
+ it('rejects empty product', async () => {
+ await expect(dispatchTool('meatspace_log_nicotine', { product: ' ' }))
+ .rejects.toThrow(/product must not be empty/);
+ });
+ it('rejects negative count', async () => {
+ await expect(dispatchTool('meatspace_log_nicotine', { product: 'cigarette', count: -2 }))
+ .rejects.toThrow(/count must be a positive number/);
+ });
+ it('rejects mgPerUnit over 200', async () => {
+ await expect(dispatchTool('meatspace_log_nicotine', { product: 'cigarette', mgPerUnit: 9999 }))
+ .rejects.toThrow(/mgPerUnit must be between 0 and 200/);
+ });
+});
+
+describe('goal_update_progress type guard', () => {
+ it('rejects non-string goalQuery', async () => {
+ await expect(dispatchTool('goal_update_progress', { goalQuery: 42, progress: 50 }))
+ .rejects.toThrow(/goalQuery is required/);
+ });
+ it('rejects out-of-range progress', async () => {
+ await expect(dispatchTool('goal_update_progress', { goalQuery: 'jacket', progress: 150 }))
+ .rejects.toThrow(/progress must be a number between 0 and 100/);
+ });
+});
+
+describe('goal_log_note type guard', () => {
+ it('rejects non-string goalQuery', async () => {
+ await expect(dispatchTool('goal_log_note', { goalQuery: {}, note: 'hi' }))
+ .rejects.toThrow(/goalQuery is required/);
+ });
+ it('rejects missing note', async () => {
+ await expect(dispatchTool('goal_log_note', { goalQuery: 'jacket' }))
+ .rejects.toThrow(/note is required/);
+ });
+});
+
+describe('pm2_restart type guard', () => {
+ it('rejects non-string name', async () => {
+ await expect(dispatchTool('pm2_restart', { name: 12345 })).rejects.toThrow(/name is required/);
+ });
+ it('rejects empty string name', async () => {
+ await expect(dispatchTool('pm2_restart', { name: ' ' })).rejects.toThrow(/name is required/);
+ });
+});
diff --git a/server/services/voice/tts-kokoro.js b/server/services/voice/tts-kokoro.js
new file mode 100644
index 0000000000..b53895e543
--- /dev/null
+++ b/server/services/voice/tts-kokoro.js
@@ -0,0 +1,74 @@
+// Kokoro TTS backend — in-process ONNX inference via kokoro-js + transformers.js.
+// Model loads lazily on first synthesis (~2–3s) and stays resident.
+
+import { KokoroTTS } from 'kokoro-js';
+import { KOKORO_VOICES } from './kokoro-voices.js';
+
+let modelPromise = null;
+let loadedKey = null;
+// `loaded` only flips once from_pretrained() resolves, so health reporting
+// can distinguish "loading" (2-3s cold start in progress) from "loaded".
+let loaded = false;
+
+const ensureModel = async ({ modelId, dtype }) => {
+ const key = `${modelId}|${dtype}`;
+ if (modelPromise && loadedKey === key) return modelPromise;
+ loadedKey = key;
+ loaded = false;
+ console.log(`🗣 kokoro: loading ${modelId} (dtype=${dtype})`);
+ const started = Date.now();
+ // Capture the in-flight promise so the then/catch handlers only mutate
+ // shared state when they're still the active load. Without this, a second
+ // load (different modelId/dtype) could race the first to completion and
+ // corrupt `loaded`/`modelPromise`.
+ const current = KokoroTTS.from_pretrained(modelId, { dtype, device: 'cpu' })
+ .then((tts) => {
+ if (modelPromise === current && loadedKey === key) {
+ loaded = true;
+ console.log(`🗣 kokoro: ready in ${Date.now() - started}ms`);
+ }
+ return tts;
+ })
+ .catch((err) => {
+ if (modelPromise === current && loadedKey === key) {
+ modelPromise = null;
+ loadedKey = null;
+ loaded = false;
+ }
+ throw err;
+ });
+ modelPromise = current;
+ return modelPromise;
+};
+
+/**
+ * @param {string} text
+ * @param {object} cfg — full voice.tts config
+ * @param {AbortSignal} [signal]
+ * @returns {Promise<{ wav: Buffer, latencyMs: number }>}
+ */
+export const synthesizeKokoro = async (text, cfg, signal) => {
+ if (signal?.aborted) throw new Error('aborted');
+ const { modelId, dtype, voice } = cfg.kokoro;
+ const tts = await ensureModel({ modelId, dtype });
+ if (signal?.aborted) throw new Error('aborted');
+
+ const started = Date.now();
+ const speed = Math.max(0.5, Math.min(2.0, cfg.rate ?? 1.0));
+ const audio = await tts.generate(text, { voice, speed });
+ if (signal?.aborted) throw new Error('aborted');
+
+ return { wav: Buffer.from(audio.toWav()), latencyMs: Date.now() - started };
+};
+
+export const listKokoroVoices = async () =>
+ Object.entries(KOKORO_VOICES)
+ .map(([name, meta]) => ({ name, ...meta }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+// 'lazy' = never touched; 'loading' = from_pretrained in flight; 'loaded' = usable.
+export const readyState = () => {
+ if (!modelPromise) return 'lazy';
+ return loaded ? 'loaded' : 'loading';
+};
+export const isReady = () => loaded;
diff --git a/server/services/voice/tts-piper.js b/server/services/voice/tts-piper.js
new file mode 100644
index 0000000000..a060389d4d
--- /dev/null
+++ b/server/services/voice/tts-piper.js
@@ -0,0 +1,115 @@
+// Piper TTS backend — spawn-per-request CLI: text on stdin, WAV on stdout.
+
+import { spawn } from 'child_process';
+import { existsSync } from 'fs';
+import { delimiter, join } from 'path';
+import { expandPath, piperVoiceTildePath, voiceHome } from './config.js';
+import { PIPER_VOICES, findPiperVoice } from './piper-voices.js';
+
+const PIPER_TIMEOUT_MS = 30_000;
+const VOICES_DIR = join(voiceHome(), 'voices');
+const PIPER_BIN = join(voiceHome(), 'piper', 'piper');
+
+const voicePathFor = (id) => join(VOICES_DIR, `${id}.onnx`);
+
+export const synthesizePiper = (text, cfg, signal) => {
+ const voiceId = cfg.piper.voice;
+ const voicePath = expandPath(cfg.piper.voicePath || voicePathFor(voiceId));
+ if (!existsSync(voicePath)) {
+ return Promise.reject(new Error(`piper voice missing: ${voicePath}`));
+ }
+
+ const rate = Math.max(0.25, Math.min(4, cfg.rate ?? 1.0));
+ const lengthScale = String(1 / rate);
+ const args = ['--model', voicePath, '--length_scale', lengthScale, '--output_file', '-'];
+
+ // Multi-speaker voices (VCTK) need a speaker index. Prefer the per-session
+ // override from config, fall back to the catalog default.
+ const catalog = findPiperVoice(voiceId);
+ const speakerId = cfg.piper.speakerId ?? catalog?.speakerId;
+ if (speakerId != null) args.push('--speaker', String(speakerId));
+
+ const started = Date.now();
+
+ return new Promise((resolve, reject) => {
+ const piperBin = existsSync(PIPER_BIN) ? PIPER_BIN : 'piper';
+ const piperLib = join(voiceHome(), 'piper', 'lib');
+ // Prepend piperLib onto existing DYLD_/LD_LIBRARY_PATH so users who rely
+ // on other libraries (MKL, Metal plugins, locally-built deps) don't have
+ // their paths clobbered. Piper's dylibs win first-match without erasing
+ // the caller's environment.
+ const env = { ...process.env };
+ if (existsSync(piperLib)) {
+ env.DYLD_LIBRARY_PATH = process.env.DYLD_LIBRARY_PATH
+ ? `${piperLib}${delimiter}${process.env.DYLD_LIBRARY_PATH}`
+ : piperLib;
+ env.LD_LIBRARY_PATH = process.env.LD_LIBRARY_PATH
+ ? `${piperLib}${delimiter}${process.env.LD_LIBRARY_PATH}`
+ : piperLib;
+ }
+ const child = spawn(piperBin, args, { stdio: ['pipe', 'pipe', 'pipe'], env });
+ const chunks = [];
+ let errBuf = '';
+ let killed = false;
+ let settled = false;
+
+ const settle = (fn) => (arg) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(killTimer);
+ fn(arg);
+ };
+ const doResolve = settle(resolve);
+ const doReject = settle(reject);
+
+ const killTimer = setTimeout(() => {
+ killed = true;
+ child.kill('SIGKILL');
+ doReject(new Error(`piper timed out after ${PIPER_TIMEOUT_MS}ms`));
+ }, PIPER_TIMEOUT_MS);
+
+ if (signal) {
+ if (signal.aborted) {
+ killed = true;
+ try { child.kill('SIGTERM'); } catch { /* already gone */ }
+ return doReject(new Error('piper synthesis aborted'));
+ }
+ signal.addEventListener('abort', () => {
+ killed = true;
+ try { child.kill('SIGTERM'); } catch { /* already gone */ }
+ doReject(new Error('piper synthesis aborted'));
+ }, { once: true });
+ }
+
+ child.stdout.on('data', (c) => chunks.push(c));
+ child.stderr.on('data', (c) => { errBuf += c.toString(); });
+ child.on('error', (err) => { doReject(err); });
+ child.on('close', (code) => {
+ if (killed) return doReject(new Error('piper synthesis aborted'));
+ if (code !== 0) return doReject(new Error(`piper exited ${code}: ${errBuf.slice(0, 400)}`));
+ doResolve({ wav: Buffer.concat(chunks), latencyMs: Date.now() - started });
+ });
+
+ child.stdin.end(text);
+ });
+};
+
+// Return the curated catalog, annotated with `downloaded` plus both tilde
+// and resolved paths. Storing `path` in tilde form keeps voice.tts.piper.voicePath
+// portable across machines/users (the rest of the voice config uses `~/` too),
+// while `resolvedPath` is available for UI display or diagnostics.
+export const listPiperVoices = async () => PIPER_VOICES.map((v) => {
+ const tildePath = piperVoiceTildePath(v.id);
+ const resolvedPath = voicePathFor(v.id);
+ return {
+ name: v.id,
+ path: tildePath,
+ resolvedPath,
+ downloaded: existsSync(resolvedPath),
+ gender: v.gender,
+ accent: v.accent,
+ note: v.note,
+ sizeMB: v.sizeMB,
+ speakerId: v.speakerId,
+ };
+});
diff --git a/server/services/voice/tts.js b/server/services/voice/tts.js
new file mode 100644
index 0000000000..2442c1758a
--- /dev/null
+++ b/server/services/voice/tts.js
@@ -0,0 +1,70 @@
+// TTS façade — dispatches on cfg.tts.engine ('kokoro' default | 'piper').
+
+import { getVoiceConfig, piperVoiceTildePath } from './config.js';
+import { synthesizeKokoro, listKokoroVoices } from './tts-kokoro.js';
+import { synthesizePiper, listPiperVoices } from './tts-piper.js';
+import { findPiperVoice } from './piper-voices.js';
+
+const VALID_ENGINES = new Set(['kokoro', 'piper']);
+
+// Normalize `engine` against the allowlist so an invalid value can't silently
+// produce Kokoro audio while the response reports `engine: 'elevenlabs'`.
+const resolveEngine = (engine) => VALID_ENGINES.has(engine) ? engine : 'kokoro';
+
+const backend = (engine) => {
+ if (engine === 'piper') return { synth: synthesizePiper, list: listPiperVoices };
+ return { synth: synthesizeKokoro, list: listKokoroVoices };
+};
+
+/**
+ * Synthesize text with the active TTS engine. `opts.voice` and `opts.engine`
+ * override the configured voice/engine just for this call — used by the
+ * voice-picker preview so users can audition before saving.
+ * @param {string} text
+ * @param {object} [opts]
+ * @param {AbortSignal} [opts.signal]
+ * @param {string} [opts.voice] transient voice override
+ * @param {string} [opts.engine] transient engine override ('kokoro'|'piper')
+ * @returns {Promise<{ wav: Buffer, latencyMs: number, engine: string }>}
+ */
+export const synthesize = async (text, opts = {}) => {
+ const cfg = await getVoiceConfig();
+ const engine = resolveEngine(opts.engine || cfg.tts.engine);
+ const { synth } = backend(engine);
+ let ttsCfg = cfg.tts;
+ if (opts.voice) {
+ if (engine === 'kokoro') {
+ ttsCfg = { ...cfg.tts, kokoro: { ...cfg.tts.kokoro, voice: opts.voice } };
+ } else {
+ // Reject Piper voice overrides that aren't in the curated catalog —
+ // otherwise `voice` would change but `voicePath` would remain the
+ // previous config value, silently synthesizing the wrong voice.
+ const catalog = findPiperVoice(opts.voice);
+ if (!catalog) throw new Error(`unknown piper voice: ${opts.voice}`);
+ ttsCfg = {
+ ...cfg.tts,
+ piper: {
+ ...cfg.tts.piper,
+ voice: opts.voice,
+ voicePath: piperVoiceTildePath(opts.voice),
+ speakerId: null,
+ },
+ };
+ }
+ }
+ const result = await synth(text, ttsCfg, opts.signal);
+ return { ...result, engine };
+};
+
+/**
+ * Enumerate voices available for the given engine (or the configured one).
+ * @param {string} [engineOverride] 'kokoro' | 'piper' to preview voices for
+ * an engine without saving it as active.
+ * @returns {Promise<{ engine: string, voices: Array }>}
+ */
+export const listVoices = async (engineOverride) => {
+ const cfg = await getVoiceConfig();
+ const engine = resolveEngine(engineOverride || cfg.tts.engine);
+ const { list } = backend(engine);
+ return { engine, voices: await list() };
+};
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
new file mode 100644
index 0000000000..160a033b03
--- /dev/null
+++ b/server/sockets/voice.js
@@ -0,0 +1,140 @@
+// Per-socket voice handlers.
+// Inbound: voice:turn | voice:text | voice:interrupt | voice:reset
+// Outbound: voice:transcript | voice:llm:delta | voice:llm:done | voice:tts:audio
+// | voice:tool | voice:error | voice:idle
+
+import { runTurn } from '../services/voice/pipeline.js';
+import { getVoiceConfig } from '../services/voice/config.js';
+
+// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.
+const HISTORY_MESSAGES = 24;
+// Payload size caps. Voice audio is typically 16 kHz mono PCM/WebM (~32 KB/s),
+// so 8 MB leaves headroom for ~4 min of audio even in WAV. Text utterances are
+// short; 4 KB covers any realistic spoken turn and rejects prompt-stuffing.
+const MAX_AUDIO_BYTES = 8 * 1024 * 1024;
+const MAX_TEXT_LEN = 4000;
+
+const audioByteLength = (audio) => {
+ if (Buffer.isBuffer(audio)) return audio.byteLength;
+ if (audio instanceof ArrayBuffer) return audio.byteLength;
+ if (ArrayBuffer.isView(audio)) return audio.byteLength;
+ return 0;
+};
+
+export const registerVoiceHandlers = (socket) => {
+ const state = {
+ history: [],
+ ctrl: null,
+ };
+
+ const pushHistory = (role, content) => {
+ if (!content) return;
+ state.history.push({ role, content });
+ if (state.history.length > HISTORY_MESSAGES) {
+ state.history = state.history.slice(-HISTORY_MESSAGES);
+ }
+ };
+
+ const runTurnWithState = async ({ audio, mimeType, text, errorStage }) => {
+ state.ctrl?.abort();
+ state.ctrl = new AbortController();
+ const { signal } = state.ctrl;
+
+ const emit = (event, data) => {
+ if (signal.aborted) return;
+ socket.emit(event, data);
+ };
+
+ try {
+ const { transcript, reply } = await runTurn({
+ audio, mimeType, text, history: state.history, emit, signal,
+ });
+ // Don't persist transcript/reply when the turn was aborted or superseded
+ // by a newer turn — the user interrupted, and that output shouldn't
+ // re-enter context on the next turn.
+ if (signal.aborted || state.ctrl?.signal !== signal) return;
+ pushHistory('user', transcript);
+ pushHistory('assistant', reply);
+ } catch (err) {
+ if (signal.aborted) return;
+ console.error(`🎙️ ${errorStage} failed: ${err.message}`);
+ socket.emit('voice:error', { stage: errorStage, message: err.message });
+ socket.emit('voice:idle', { reason: 'error' });
+ }
+ };
+
+ // Gate voice:turn / voice:text on the Settings voice.enabled toggle so the
+ // disabled state isn't merely "don't provision PM2" — disabled clients can't
+ // run the LLM/TTS pipeline either. Small race (config change mid-turn) is
+ // acceptable: the per-turn check runs at event dispatch, not inside the
+ // streaming loop.
+ const ensureEnabled = async (stage) => {
+ const cfg = await getVoiceConfig();
+ if (cfg.enabled) return true;
+ socket.emit('voice:error', { stage, message: 'voice mode disabled' });
+ return false;
+ };
+
+ socket.on('voice:turn', async (payload = {}) => {
+ if (!(await ensureEnabled('turn'))) return;
+ const { audio, mimeType: rawMime } = payload;
+ if (!audio) {
+ socket.emit('voice:error', { stage: 'turn', message: 'audio is required' });
+ return;
+ }
+ const size = audioByteLength(audio);
+ if (!size) {
+ socket.emit('voice:error', { stage: 'turn', message: 'audio is empty or unrecognized' });
+ return;
+ }
+ if (size > MAX_AUDIO_BYTES) {
+ socket.emit('voice:error', { stage: 'turn', message: `audio too large (${size} > ${MAX_AUDIO_BYTES} bytes)` });
+ return;
+ }
+ // Normalize mimeType — reject anything that isn't a plain string to keep
+ // downstream HTTP multipart stable.
+ const mimeType = typeof rawMime === 'string' && rawMime.length <= 64 ? rawMime : 'audio/wav';
+ // Preserve TypedArray byteOffset/byteLength so a sliced Uint8Array view
+ // doesn't drag unrelated bytes from its underlying ArrayBuffer.
+ let buffer;
+ if (Buffer.isBuffer(audio)) buffer = audio;
+ else if (audio instanceof ArrayBuffer) buffer = Buffer.from(audio);
+ else if (ArrayBuffer.isView(audio)) buffer = Buffer.from(audio.buffer, audio.byteOffset, audio.byteLength);
+ else buffer = Buffer.from(audio);
+ await runTurnWithState({ audio: buffer, mimeType, errorStage: 'turn' });
+ });
+
+ socket.on('voice:text', async (payload = {}) => {
+ if (!(await ensureEnabled('text'))) return;
+ const raw = payload.text;
+ if (typeof raw !== 'string' && typeof raw !== 'number') {
+ socket.emit('voice:error', { stage: 'text', message: 'text is required' });
+ return;
+ }
+ const text = String(raw).trim();
+ if (!text) {
+ socket.emit('voice:error', { stage: 'text', message: 'text is required' });
+ return;
+ }
+ if (text.length > MAX_TEXT_LEN) {
+ socket.emit('voice:error', { stage: 'text', message: `text too long (${text.length} > ${MAX_TEXT_LEN} chars)` });
+ return;
+ }
+ await runTurnWithState({ text, errorStage: 'text' });
+ });
+
+ socket.on('voice:interrupt', () => {
+ state.ctrl?.abort();
+ socket.emit('voice:idle', { reason: 'interrupted' });
+ });
+
+ socket.on('voice:reset', () => {
+ state.ctrl?.abort();
+ state.history = [];
+ socket.emit('voice:idle', { reason: 'reset' });
+ });
+
+ socket.on('disconnect', () => {
+ state.ctrl?.abort();
+ });
+};