Answers read aloud: Voice on the menu, ElevenLabs voices per agent via the bridge (0.5.0)

- bridge: GET /v1/speech (which agents have a voice) and GET /v1/turns/{id}/speech (MP3 of the
  caller's own finished answer, markup removed, first 900 characters). ElevenLabs adapter; key
  and voice ids from the environment; per-device budget; last three clips kept in memory.
  speech.done / speech.failed log ids, lengths and durations only.
- bridge: forceCloseConnections. A request the client had abandoned kept shutdown waiting for
  ever (also true of /v1/transcribe as deployed). Regression test for both routes.
- client: 'Voice: off/on' on the opening menu when the bridge offers it and the page can play
  sound; off at every launch. With it on, a finished answer is fetched and played; it stops
  when the answer leaves the screen; the app does not leave the glasses while it plays.
- tests: fake provider, fake loudspeaker (tests/integration/voice.test.ts).
- docs: 0006, security 3g-3i, device plan E, 0.4.1 rollout and Dan's sound check report.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Dan
2026-11-29 12:11:38 -08:00
co-authored by Claude Fable 5.2
parent d65beeab77
commit 9874e1bb5b
25 changed files with 1199 additions and 17 deletions
+6 -2
View File
@@ -9,6 +9,7 @@ import { buildServer } from './server.ts';
import { NoSttAdapter, type SttAdapter } from './stt/adapter.ts';
import { BuiltinWhisperStt } from './stt/builtinWhisper.ts';
import { OpenAiCompatibleStt } from './stt/openaiCompatible.ts';
import { ElevenLabsTts, NoTtsAdapter, type TtsAdapter } from './tts.ts';
import { TurnEngine, type EngineLog, type EngineTiming } from './turns.ts';
export interface Bridge {
@@ -45,7 +46,7 @@ export function sttFromConfig(config: BridgeConfig): SttAdapter {
export async function createBridge(
config: BridgeConfig,
overrides: { hermes?: HermesAdapter; stt?: SttAdapter; timing?: EngineTiming; logger?: object | boolean; cancelSweepMs?: number } = {},
overrides: { hermes?: HermesAdapter; stt?: SttAdapter; tts?: TtsAdapter; timing?: EngineTiming; logger?: object | boolean; cancelSweepMs?: number } = {},
): Promise<Bridge> {
const db = openDb(config.dbPath);
const hermes =
@@ -73,7 +74,10 @@ export async function createBridge(
: pino(given as object)
: pino({ level: 'silent' });
const engine = new TurnEngine({ db, config, devices, hermes, agents, stt, log: logger as unknown as EngineLog, timing: overrides.timing });
const app = await buildServer({ config, devices, hermes, stt, engine, logger });
const tts: TtsAdapter =
overrides.tts ??
(config.tts.apiKey ? new ElevenLabsTts({ baseUrl: config.tts.baseUrl, apiKey: config.tts.apiKey, model: config.tts.model }) : new NoTtsAdapter());
const app = await buildServer({ config, devices, hermes, stt, tts, engine, logger });
engine.recover();
engine.purgeExpired();
+31 -1
View File
@@ -16,6 +16,8 @@ export interface AgentConfig {
* any aliases, lower-case. Empty = it cannot be called by voice. Never sent to a client.
*/
wakeWords: string[];
/** The provider's voice for reading this agent's answers aloud. Empty = it is not read aloud. */
voiceId: string;
}
export const DEFAULT_AGENT_ID = 'default';
@@ -62,6 +64,8 @@ export interface BridgeConfig {
manifest: ModelManifest | null;
modelDir: string;
};
/** Reading answers aloud. `apiKey` empty = off. The key never leaves the bridge. */
tts: { baseUrl: string; apiKey: string; model: string; timeoutSeconds: number };
limits: {
captureMaxSeconds: number;
transcribeDeadlineSeconds: number;
@@ -73,6 +77,10 @@ export interface BridgeConfig {
turnsPerMinute: number;
/** Wake checks (speech heard while the app is open, tested for a leading agent name). */
wakeChecksPerMinute: number;
/** Answers read aloud per device per minute (each one is paid for). */
speechPerMinute: number;
/** The most characters of one answer that are read aloud. */
speechMaxChars: number;
/** Live previews of a recording in progress. */
previewsPerMinute: number;
pairingAttemptsPerMinute: number;
@@ -189,6 +197,13 @@ function wakeWords(key: string, raw: string | undefined, name: string): string[]
return wakeWordsFor(name, aliases);
}
/** HERMEVEN_AGENT_<ID>_VOICE (for the default agent, HERMEVEN_AGENT_VOICE): the provider's voice id. */
function voiceId(key: string, raw: string | undefined): string {
const id = (raw ?? '').trim();
if (id && !/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new ConfigError(`${key} is not a voice id (letters, digits, - and _)`);
return id;
}
function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: string): AgentConfig[] {
const defaultName = agentName('HERMEVEN_AGENT_NAME', env.HERMEVEN_AGENT_NAME, 'Agent');
const agents: AgentConfig[] = [
@@ -200,6 +215,7 @@ function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: stri
// The placeholder name "Agent" is not something to listen for: the default agent answers
// to a name only once the owner has given it one (or an alias).
wakeWords: wakeWords('HERMEVEN_AGENT_WAKE', env.HERMEVEN_AGENT_WAKE, env.HERMEVEN_AGENT_NAME ? defaultName : ''),
voiceId: voiceId('HERMEVEN_AGENT_VOICE', env.HERMEVEN_AGENT_VOICE),
},
];
const ids = (env.HERMEVEN_AGENTS ?? '')
@@ -215,7 +231,7 @@ function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: stri
const profile = env[`${prefix}_PROFILE`] || id;
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(profile)) throw new ConfigError(`${prefix}_PROFILE is not a valid profile name`);
const name = agentName(`${prefix}_NAME`, env[`${prefix}_NAME`], id.charAt(0).toUpperCase() + id.slice(1));
agents.push({ id, name, baseUrl: `${baseUrl}/p/${profile}`, apiKey, wakeWords: wakeWords(`${prefix}_WAKE`, env[`${prefix}_WAKE`], name) });
agents.push({ id, name, baseUrl: `${baseUrl}/p/${profile}`, apiKey, wakeWords: wakeWords(`${prefix}_WAKE`, env[`${prefix}_WAKE`], name), voiceId: voiceId(`${prefix}_VOICE`, env[`${prefix}_VOICE`]) });
}
const claimed = new Map<string, string>();
for (const agent of agents) {
@@ -229,6 +245,12 @@ function agentsFromEnv(env: NodeJS.ProcessEnv, baseUrl: string, defaultKey: stri
return agents;
}
function ttsModel(raw: string | undefined): string {
const model = (raw ?? '').trim() || 'eleven_flash_v2_5';
if (!/^[A-Za-z0-9_.-]{1,64}$/.test(model)) throw new ConfigError('HERMEVEN_ELEVENLABS_MODEL is not a model id');
return model;
}
export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
const host = env.HERMEVEN_HOST || '127.0.0.1';
const allowNonLoopback = bool(env, 'HERMEVEN_ALLOW_NON_LOOPBACK');
@@ -318,6 +340,12 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
manifest: sttManifest,
modelDir: env.STT_MODEL_DIR || './data/models',
},
tts: {
baseUrl: httpUrl('HERMEVEN_ELEVENLABS_BASE_URL', env.HERMEVEN_ELEVENLABS_BASE_URL || 'https://api.elevenlabs.io').replace(/\/+$/, ''),
apiKey: env.HERMEVEN_ELEVENLABS_API_KEY || '',
model: ttsModel(env.HERMEVEN_ELEVENLABS_MODEL),
timeoutSeconds: int(env, 'HERMEVEN_SPEECH_TIMEOUT_SECONDS', 20, 1, 120),
},
limits: {
captureMaxSeconds,
transcribeDeadlineSeconds: int(env, 'HERMEVEN_TRANSCRIBE_DEADLINE_SECONDS', DEFAULT_LIMITS.transcribeDeadlineSeconds, 1, 300),
@@ -329,6 +357,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): BridgeConfig {
audioMaxBytes: (captureMaxSeconds + 1) * AUDIO_FORMAT.bytesPerSecond,
turnsPerMinute: int(env, 'HERMEVEN_TURNS_PER_MINUTE', 20, 1, 600),
wakeChecksPerMinute: int(env, 'HERMEVEN_WAKE_CHECKS_PER_MINUTE', 30, 1, 600),
speechPerMinute: int(env, 'HERMEVEN_SPEECH_PER_MINUTE', 6, 1, 60),
speechMaxChars: int(env, 'HERMEVEN_SPEECH_MAX_CHARS', 900, 50, 5000),
previewsPerMinute: int(env, 'HERMEVEN_PREVIEWS_PER_MINUTE', 60, 1, 600),
pairingAttemptsPerMinute: int(env, 'HERMEVEN_PAIRING_ATTEMPTS_PER_MINUTE', 5, 1, 60),
},
+89
View File
@@ -18,6 +18,7 @@ import {
type ErrorCode,
type ErrorResponse,
type Limits,
type SpeechInfoResponse,
type TranscribeResponse,
type WakeResponse,
} from '@hermeven/contracts';
@@ -26,6 +27,7 @@ import type { DeviceRow, Devices } from './devices.ts';
import type { HermesAdapter } from './hermes/adapter.ts';
import { RateLimiter } from './ratelimit.ts';
import type { SttAdapter } from './stt/adapter.ts';
import { speechText, TtsError, type TtsAdapter } from './tts.ts';
import type { TurnEngine } from './turns.ts';
import { matchWake } from './wake.ts';
@@ -35,6 +37,7 @@ export interface ServerDeps {
engine: TurnEngine;
hermes: HermesAdapter;
stt: SttAdapter;
tts: TtsAdapter;
/** Request bodies, queries and auth headers are never passed to it. */
logger: FastifyBaseLogger;
}
@@ -92,6 +95,11 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
const app = Fastify({
loggerInstance: deps.logger,
trustProxy: config.trustProxy,
// On shutdown, close every connection, not only idle ones. A request the client gave up on
// (a preview or speech it no longer wants) can leave its connection open after the handler
// has finished, and waiting for that one never ends. Anything cut off here is something the
// app already retries: turns are created with a request id and found again by polling.
forceCloseConnections: true,
// JSON bodies are tiny; the audio parser below sets its own, larger limit.
bodyLimit: 32 * 1024,
// Per-request access logs are off: routes log ids and outcomes themselves, and a URL
@@ -427,6 +435,87 @@ export async function buildServer(deps: ServerDeps): Promise<FastifyInstance> {
return engine.toResult(turn);
});
// ------------------------------------------------------------------ speech
const speechLimiter = new RateLimiter(config.limits.speechPerMinute, 60_000);
/** One request to the provider per turn at a time, shared by anyone asking meanwhile. */
const speechInFlight = new Map<string, Promise<Buffer>>();
/** The last few answers spoken, so a repeated request is not paid for twice. In memory only. */
const speechCache = new Map<string, Buffer>();
const voiced = () => (deps.tts.configured ? config.agents.filter((a) => a.voiceId) : []);
app.get('/v1/speech', async (req): Promise<SpeechInfoResponse> => {
authenticate(req);
const agents = voiced();
return {
schema_version: SCHEMA_VERSION,
available: agents.length > 0,
agent_ids: agents.map((a) => a.id),
max_chars: agents.length > 0 ? config.limits.speechMaxChars : 0,
};
});
/**
* The answer of one of this device's own finished turns, read aloud in its agent's voice.
* There is no way to have arbitrary text spoken. The text (cut to the configured length) is
* sent to the speech provider; neither it nor the audio is logged or stored.
*/
app.get('/v1/turns/:requestId/speech', async (req, reply) => {
const device = authenticate(req);
const { requestId } = req.params as { requestId: string };
const turn = engine.get(device.id, requireUuid(requestId));
const agentId = turn ? engine.agentIdOf(turn) : undefined;
const agent = voiced().find((a) => a.id === agentId);
const answer = turn && (turn.outcome === 'succeeded' || turn.outcome === 'incomplete') ? (turn.answer_text ?? '') : '';
const spoken = speechText(answer, config.limits.speechMaxChars);
// No such turn, not this device's, not finished, nothing to say, or no voice: all the same.
if (!turn || !agent || !spoken.text) throw new ApiError('not_found', 'Not found.');
let audio = speechCache.get(turn.request_id);
if (!audio) {
let pending = speechInFlight.get(turn.request_id);
if (!pending) {
if (!speechLimiter.take(device.id)) throw new ApiError('rate_limited', 'Too many requests. Wait a moment.');
const startedAt = Date.now();
pending = deps.tts
.synthesize({ text: spoken.text, voiceId: agent.voiceId, signal: AbortSignal.timeout(config.tts.timeoutSeconds * 1000) })
.then(
(result) => {
req.log.info(
{
device_id: device.id,
request_id: turn.request_id,
agent_id: agent.id,
chars: spoken.text.length,
truncated: spoken.truncated,
audio_bytes: result.length,
speech_ms: Date.now() - startedAt,
},
'speech.done',
);
speechCache.set(turn.request_id, result);
while (speechCache.size > 3) speechCache.delete(speechCache.keys().next().value as string);
return result;
},
(err) => {
req.log.warn(
{ device_id: device.id, request_id: turn.request_id, agent_id: agent.id, provider_status: err instanceof TtsError ? err.status : null, speech_ms: Date.now() - startedAt },
'speech.failed',
);
throw err;
},
)
.finally(() => speechInFlight.delete(turn.request_id));
speechInFlight.set(turn.request_id, pending);
}
try {
audio = await pending;
} catch {
throw new ApiError('internal', 'Speech could not be generated.');
}
}
return reply.header('Content-Type', 'audio/mpeg').send(audio);
});
app.post('/v1/turns/:requestId/cancel', async (req) => {
const device = authenticate(req);
const { requestId } = req.params as { requestId: string };
+95
View File
@@ -0,0 +1,95 @@
/**
* Text to speech: turning an agent's answer into audio the app can play.
*
* Unlike speech-to-text this is NOT done on the bridge host: the text of the answer is sent to
* a provider (ElevenLabs). It happens only when a client asks for the speech of one of its own
* finished turns, and only up to a fixed length.
*/
export interface SynthesizeRequest {
text: string;
voiceId: string;
signal: AbortSignal;
}
export class TtsError extends Error {
override name = 'TtsError';
constructor(
/** HTTP status from the provider, or 0 when there was no answer. Never the provider's text. */
readonly status: number,
) {
super(`speech provider failed (${status || 'no answer'})`);
}
}
export interface TtsAdapter {
readonly configured: boolean;
/** MP3 audio. */
synthesize(request: SynthesizeRequest): Promise<Buffer>;
}
export class NoTtsAdapter implements TtsAdapter {
readonly configured = false;
async synthesize(): Promise<Buffer> {
throw new TtsError(0);
}
}
/** The most audio the bridge will pass on: far more than the text cap can produce. */
const MAX_AUDIO_BYTES = 4 * 1024 * 1024;
export class ElevenLabsTts implements TtsAdapter {
readonly configured = true;
constructor(private readonly options: { baseUrl: string; apiKey: string; model: string; fetchImpl?: typeof fetch }) {}
async synthesize({ text, voiceId, signal }: SynthesizeRequest): Promise<Buffer> {
const url = `${this.options.baseUrl}/v1/text-to-speech/${encodeURIComponent(voiceId)}?output_format=mp3_44100_64`;
let res: Response;
try {
res = await (this.options.fetchImpl ?? fetch)(url, {
method: 'POST',
headers: { 'xi-api-key': this.options.apiKey, 'Content-Type': 'application/json', Accept: 'audio/mpeg' },
body: JSON.stringify({ text, model_id: this.options.model }),
signal,
});
} catch {
throw new TtsError(0);
}
if (!res.ok) {
// The provider's error body can quote the text back; it is read and thrown away.
await res.arrayBuffer().catch(() => undefined);
throw new TtsError(res.status);
}
let audio: Buffer;
try {
audio = Buffer.from(await res.arrayBuffer());
} catch {
throw new TtsError(0);
}
if (audio.length === 0 || audio.length > MAX_AUDIO_BYTES) throw new TtsError(res.status);
return audio;
}
}
/**
* What is read aloud for an answer: plain sentences, no markup, no code, no web addresses, and
* no more than `maxChars`, ending at a sentence where one is near.
*/
export function speechText(answer: string, maxChars: number): { text: string; truncated: boolean } {
let text = answer.replace(/\r\n?/g, '\n').normalize('NFC');
text = text.replace(/^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?^[ \t]*\1[^\n]*$/gm, ' ');
text = text.replace(/<\/?[a-zA-Z][^<>\n]*>/g, ' ');
text = text.replace(/!?\[([^\]]*)\]\([^)\s]+(?:\s+"[^"]*")?\)/g, '$1');
text = text.replace(/\bhttps?:\/\/\S+/g, 'link');
text = text
.split('\n')
.map((line) => line.replace(/^\s{0,3}(#{1,6}\s+|>\s?|[-*+]\s+)/, '').replace(/^\s*\|?[\s:|-]{3,}\|?\s*$/, ''))
.join('\n');
text = text.replace(/[*_`~|]+/g, ' ');
// A line break is a pause when the line did not already end one.
text = text.replace(/([^\s.!?:;,])\s*\n+/g, '$1. ').replace(/\s+/g, ' ').trim();
if (text.length <= maxChars) return { text, truncated: false };
const head = text.slice(0, maxChars);
const sentence = Math.max(head.lastIndexOf('. '), head.lastIndexOf('! '), head.lastIndexOf('? '));
const cut = sentence >= maxChars / 2 ? sentence + 1 : head.lastIndexOf(' ') > 0 ? head.lastIndexOf(' ') : maxChars;
return { text: head.slice(0, cut).trim(), truncated: true };
}
+8
View File
@@ -276,6 +276,14 @@ export class TurnEngine {
return decision;
}
/** The id of the agent a turn was put to (`default` for the main one), or undefined if unknown. */
agentIdOf(row: TurnRow): string | undefined {
const conversation = this.deps.db.prepare('SELECT agent_id FROM conversations WHERE id = ?').get(row.conversation_id) as
| { agent_id: string | null }
| undefined;
return conversation ? (conversation.agent_id ?? DEFAULT_AGENT_ID) : undefined;
}
get(deviceId: string, requestId: string): TurnRow | undefined {
const row = this.row(requestId);
return row && row.device_id === deviceId ? row : undefined;