import { Worker } from 'node:worker_threads'; import { AUDIO_FORMAT } from '@hermeven/contracts'; import { SttError, type SttAdapter, type TranscribeRequest } from './adapter.ts'; import type { ModelManifest } from './modelStore.mjs'; /** * Built-in speech-to-text: OpenAI's Whisper model run on the bridge host's CPU * (ONNX Runtime via @huggingface/transformers). No audio leaves the bridge host * and no provider account is needed. * * The model lives in a worker thread (whisperWorker.mjs), so loading it and * transcribing never block the bridge's HTTP server or its Hermes polling. * * The bridge never downloads anything at run time. Model files are fetched ahead of * time (`bridge:cli fetch-model`) at a pinned commit, and every file is checked against * its pinned SHA-256 each time the model is loaded. */ export interface BuiltinWhisperOptions { /** What exactly to load: hub id, immutable revision, precision, and each file's hash. */ manifest: ModelManifest; /** Model store directory. Read-only at run time. */ modelDir: string; /** Test seam: replaces the worker thread with an in-process recogniser. */ load?: () => Promise; } export type Recognizer = (audio: Float32Array, options: Record) => Promise<{ text?: unknown } | Array<{ text?: unknown }>>; /** * Below this RMS level the capture is treated as silence and not transcribed. * Whisper invents short phrases ("Thank you.") for silent input, which would * otherwise be sent to the agent as if the user had said them. -55 dBFS. */ export const SILENCE_RMS = 0.0018; export function pcmToFloat32(pcm: Buffer): Float32Array { const samples = new Float32Array(Math.floor(pcm.length / 2)); for (let i = 0; i < samples.length; i++) samples[i] = pcm.readInt16LE(i * 2) / 32768; return samples; } export function rms(samples: Float32Array): number { if (samples.length === 0) return 0; let sum = 0; for (let i = 0; i < samples.length; i++) sum += samples[i]! * samples[i]!; return Math.sqrt(sum / samples.length); } /** Whisper marks non-speech with bracketed or parenthesised tags; those are not words. */ export function cleanTranscript(text: string): string { return text .replace(/\[[^\]]*\]|\([^)]*\)/g, ' ') .replace(/\s+/g, ' ') .trim(); } export class BuiltinWhisperStt implements SttAdapter { readonly configured = true; private recognizer: Promise | null = null; private worker: Worker | null = null; private closed = false; /** Why the last load failed: `missing`, `mismatch` (files differ from the pin) or `load`. */ lastLoadFailure: 'missing' | 'mismatch' | 'load' | null = null; /** One transcription at a time: the model is CPU-bound and this is a single-user bridge. */ private queue: Promise = Promise.resolve(); constructor(private readonly opts: BuiltinWhisperOptions) {} /** Load the model now (downloading it on first use) so the first question is not slow. */ async warm(): Promise { await this.load(); } private load(): Promise { if (!this.recognizer) { const loading = (this.opts.load ?? (() => this.startWorker()))(); this.recognizer = loading; // A failed load (no network on first start) must be retried on the next request. loading.catch(() => { if (this.recognizer === loading) this.recognizer = null; }); } return this.recognizer; } /** Start the worker, load the model in it, and return a function that runs one clip there. */ private startWorker(): Promise { return new Promise((resolve, reject) => { if (this.closed) return reject(new Error('closed')); const worker = new Worker(new URL('./whisperWorker.mjs', import.meta.url)); this.worker = worker; // The model must never keep a stopping bridge alive. worker.unref(); const waiting = new Map void; reject: (err: Error) => void }>(); let nextId = 1; let loaded = false; const fail = (reason: string) => { // Worker died or was terminated: forget it so the next request starts a fresh one. if (this.worker === worker) this.worker = null; if (this.recognizer && loaded) this.recognizer = null; for (const pending of waiting.values()) pending.reject(new Error(reason)); waiting.clear(); if (!loaded) reject(new Error(reason)); }; worker.on('error', () => fail('worker error')); worker.on('exit', () => fail('worker exited')); worker.on('message', (message: { type: string; id?: number; text?: string; reason?: 'missing' | 'mismatch' | 'load' }) => { if (message.type === 'loaded') { loaded = true; this.lastLoadFailure = null; resolve( (audio, options) => new Promise((res, rej) => { const id = nextId++; waiting.set(id, { resolve: (text) => res({ text }), reject: rej }); // Transfer, not copy: the samples are not needed on this side again. worker.postMessage({ type: 'run', id, samples: audio, options }, [audio.buffer as ArrayBuffer]); }), ); } else if (message.type === 'load_failed') { this.lastLoadFailure = message.reason ?? 'load'; void worker.terminate(); } else if (message.id !== undefined) { const pending = waiting.get(message.id); waiting.delete(message.id); if (message.type === 'result') pending?.resolve(message.text ?? ''); else pending?.reject(new Error('recognition failed')); } }); worker.postMessage({ type: 'load', dir: this.opts.modelDir, manifest: this.opts.manifest }); }); } /** Stop the worker thread and free the model. Safe to call more than once. */ async close(): Promise { this.closed = true; const worker = this.worker; this.worker = null; this.recognizer = null; if (worker) await worker.terminate(); } async transcribe(request: TranscribeRequest): Promise { const samples = pcmToFloat32(request.pcm); if (samples.length < AUDIO_FORMAT.sampleRate / 10 || rms(samples) < SILENCE_RMS) return ''; const run = this.queue.then(async () => { if (request.signal.aborted) throw new DOMException('Aborted', 'AbortError'); let recognizer: Recognizer; try { recognizer = await this.load(); } catch { throw new SttError('unavailable', 'The speech model could not be loaded'); } // English-only models take no language argument; multilingual ones are told the // language from the device locale rather than left to guess it from a short clip. const options: Record = this.opts.manifest.model.endsWith('.en') ? {} : { language: request.locale.split('-')[0]!.toLowerCase(), task: 'transcribe' }; try { const out = await recognizer(samples, options); const text = Array.isArray(out) ? out.map((o) => String(o.text ?? '')).join(' ') : String(out.text ?? ''); return cleanTranscript(text); } catch { throw new SttError('failed', 'The speech model failed on this recording'); } }); this.queue = run.catch(() => undefined); // A clip already in the model is left to finish. On cancel or deadline the caller stops // waiting; the result is discarded when it arrives and the queue keeps later requests in order. return new Promise((resolve, reject) => { const onAbort = () => reject(new DOMException('Aborted', 'AbortError')); if (request.signal.aborted) return onAbort(); request.signal.addEventListener('abort', onAbort, { once: true }); run.then(resolve, reject).finally(() => request.signal.removeEventListener('abort', onAbort)); }); } }