diff --git a/README.md b/README.md index cb77c11..713ddfe 100644 --- a/README.md +++ b/README.md @@ -17,13 +17,13 @@ the implementer read from the server's log, and what Cody reproduced independent | Path | State | |---|---| -| **What is where today** | Server (bridge and static page): `e4c102a5391464cec6f540f5a41f5557a3f61e0b`, since 2026-11-28 21:44 UTC. Even account, beta channel: client 0.4.0, built from that commit. This repository's client is **0.4.1, a candidate: not deployed, not uploaded, not on the device.** | +| **What is where today** | Server (bridge and static page): `d65beeab77288049b801e4969ac9b68821833b23`, since 2026-11-29 19:50 UTC. Even account, beta channel: client 0.4.1, built from that commit. Both deployed and checked by the implementer, not reproduced by Cody. This repository's client is **0.5.0, a candidate: not deployed, not uploaded, not on the device.** | | Client, bridge and contract | Implemented. | -| Automated tests with fakes (357) | Passing. | +| Automated tests with fakes (375) | Passing. | | Client in Even's official simulator | 9 scenarios, run by the implementer, simulator only. Eight run with the menu, hands free and live preview switched off (the tap path and idle exit); the ninth launches the app as shipped and covers the menu and the microphone opening and closing for hands free, with a silent microphone, so no name is ever heard. Live preview is not exercised in the simulator. One unexplained failure of the idle-exit scenario in the Round 19 runs; see `docs/test-evidence.md`. | | Bridge against a real Hermes gateway | Passing (9 scenarios) with a **stub model**. | | Built-in speech-to-text (Whisper, in the bridge) | Passing (11 scenarios) on a real speech recording, including with no network. Not yet on audio from the glasses. | -| Running on a droplet | Since 2026-11-28 21:44 UTC the server runs commit `e4c102a5391464cec6f540f5a41f5557a3f61e0b` (bridge and static page), which holds Cody's SHIP FOR TRIAL (Round 20). Deployed and checked by the implementer; not reproduced by Cody. Checks performed: `docs/evidence/device/2026-11-28.md`, second half. Earlier: `44ea1148c34a271f4fdc565ef71a145adf459b42` (0.3.0, same file, first half) and `docs/evidence/droplet/2026-11-21.md`. | +| Running on a droplet | Since 2026-11-29 19:50 UTC the server runs commit `d65beeab77288049b801e4969ac9b68821833b23` (bridge and static page), which holds Cody's SHIP FOR TRIAL (Round 23). Deployed and checked by the implementer; not reproduced by Cody. Checks performed: `docs/evidence/device/2026-11-29.md`. Earlier: `e4c102a` (0.4.0) and `44ea114` (0.3.0), both in `docs/evidence/device/2026-11-28.md`; `docs/evidence/droplet/2026-11-21.md`. | | Phone page in an ordinary phone browser | Paired and answered one typed question (Chrome on Android, reported by Dan). This is **not** the Even app: a browser cannot reach the glasses. | | Phone page inside the Even app, physical G2 | First runs on 2026-11-21, QR-sideloaded, phone unlocked: paired, four spoken questions answered on the glasses. See `docs/evidence/device/2026-11-21.md` for exactly which builds and what was and was not observed. | | Installed as an Even Hub private build ("Pepper", `xylo.hermeven` 0.1.0) | Runs from the Even app with no QR code: paired, and four spoken questions answered on the glasses, including hold-to-talk and one that had the agent send a Telegram message (Dan's report plus the bridge log, 2026-11-21). Needs `HERMEVEN_ALLOWED_ORIGINS=http://127.0.0.1:*` on the bridge. | @@ -31,9 +31,10 @@ the implementer read from the server's log, and what Cody reproduced independent | Locked phone | First success on 2026-11-21 with the beta build: launched by voice ("Hey Even, open Pepper") and a spoken question answered with the phone locked (Dan's report). The specification's ten-cycle acceptance run has **not** been done. | | Leaving the glasses when idle | 0.1.1 on the device (2026-11-21, Dan's report): after one gesture the app left by itself and Telegram notifications returned to the lenses; after a voice launch with nothing touched it did **not** leave. 0.1.2 starts the countdown however the app was opened; tested with fakes and the simulator, **not installed on the device.** | | More than one agent (swipe at Ready to choose) | 0.2.0. Deployed on 2026-11-22 with three agents; a question sent through the bridge was answered by a second Hermes profile (`docs/evidence/droplet/2026-11-21.md`). Installed on the device and tried by Dan, who reported "All tests check out" without detail (`docs/evidence/device/2026-11-21.md`, sixth session). The agent screens have not been run in the simulator. | -| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | Introduced in 0.3.0 (`44ea114`, no longer deployed); part of what is deployed and on beta now (0.4.0, `e4c102a`). Fakes: passing. Simulator: menu and microphone open/close only (scenario 9). Device: tried by Dan on 2026-11-28, "pretty cool"; a name reached an agent and a different name switched agent. No item-by-item report; section D of the device plan has not been run. `docs/decisions/0004-always-listening.md`, `docs/evidence/device/2026-11-28.md`. | -| Words shown while recording (Agents only); "Heard: ..." while the agent works | 0.4.0, deployed and on beta (`e4c102a`). Fakes: passing. Not in the simulator. Device, Dan, 2026-11-28: "Heard" appears; **live words did not appear**, cause unknown; and Dan wants them in hands free, not Agents (open, not built). `docs/decisions/0005-live-preview.md`, `docs/evidence/device/2026-11-28.md`. | -| Sound check on the phone page (can the page play sound, untouched, in the background; which outputs it sees) | 0.4.1 candidate. A probe for issue #1 (spoken answers), not a feature. Tested with a fake sound engine in a fake browser (`apps/even-client/test/soundCheck.test.ts`). **Never run in a real browser, the simulator, the Even app or on the device; not deployed, not uploaded.** | +| Opening menu (Hands free, Agents); hands-free mode: calling an agent by name ("Wendy, ...") | Introduced in 0.3.0 (`44ea114`, no longer deployed); part of what is deployed and on beta now (0.4.1, `d65beea`). Fakes: passing. Simulator: menu and microphone open/close only (scenario 9). Device: tried by Dan on 2026-11-28, "pretty cool"; a name reached an agent and a different name switched agent. No item-by-item report; section D of the device plan has not been run. `docs/decisions/0004-always-listening.md`, `docs/evidence/device/2026-11-28.md`. | +| Words shown while recording (Agents only); "Heard: ..." while the agent works | Introduced in 0.4.0; part of what is deployed and on beta now (0.4.1, `d65beea`). Fakes: passing. Not in the simulator. Device, Dan, 2026-11-28: "Heard" appears; **live words did not appear**, cause unknown; and Dan wants them in hands free, not Agents (open, not built). `docs/decisions/0005-live-preview.md`, `docs/evidence/device/2026-11-28.md`. | +| Sound check on the phone page (can the page play sound, untouched, later; which outputs it sees) | 0.4.1, deployed and on beta (`d65beea`). A probe for issue #1, not a feature. Fake sound engine: passing. Device, Dan, 2026-11-29, earbuds connected: tone heard in the earbuds, allowed without a touch, played 20 s after a press, no phone voice, one unnamed output (`docs/evidence/device/2026-11-29.md`). Not in the simulator. | +| Answers read aloud ("Voice" on the opening menu; ElevenLabs voices per agent, called by the bridge; first 900 characters) | 0.5.0 candidate. Fakes only: a fake provider and a fake loudspeaker. **The real provider has never been called; MP3 playback has never run in a browser, the simulator, the Even app or on the device; not deployed, not uploaded.** `docs/decisions/0006-spoken-answers.md`. | | Real tools and approval flow | One tool use seen (a Telegram message, reported by Dan). The approval path has **not** been exercised against a real agent. | | Sustained load, backups, monitoring, upgrades on the server | **Not verified.** | | Clean-host install (`deploy/install.sh`) | Proven on a disposable Ubuntu 24.04 container with systemd (`tests/deploy/runbook-proof.sh`), not on a second real server. | @@ -78,7 +79,7 @@ instructions, including building for the glasses, are in `docs/setup.md`. | You do | It does | |---|---| -| Open the app | From 0.3.0: a menu. Swipe to move, tap to open. **Hands free** is first, **Agents** (everything below, as before) second. | +| Open the app | From 0.3.0: a menu. Swipe to move, tap to open. **Hands free** is first, **Agents** (everything below, as before) second. From 0.5.0, when the bridge has voices set up, a third entry, **Voice: off/on**, is a switch: with it on, each answer is also read aloud on whatever sound output the phone is using. It is off at every launch. | | In Hands free: say an agent's name, then your question | The microphone is open while the app is at rest (the status line starts with `●`). "Wendy, what's on my calendar" goes to Wendy. A name alone starts a recording that is sent when you stop speaking. Tap and swipe still work. The app stays on the glasses. | | Tap | Start recording. The display shows `● REC` and a timer the whole time. From 0.4.0, in Agents, the words appear as you speak, a second or two behind; "Heard: ..." shows what was sent while the agent works. | | Tap again | Stop and send. Recording also stops by itself after 30 seconds. | diff --git a/apps/even-client/app.template.json b/apps/even-client/app.template.json index ab9652a..b894ce5 100644 --- a/apps/even-client/app.template.json +++ b/apps/even-client/app.template.json @@ -2,7 +2,7 @@ "package_id": "xylo.hermeven", "edition": "202601", "name": "Pepper", - "version": "0.4.1", + "version": "0.5.0", "min_sdk_version": "0.0.16", "entrypoint": "index.html", "permissions": [ diff --git a/apps/even-client/src/boot.ts b/apps/even-client/src/boot.ts index 4736ccf..5fd6686 100644 --- a/apps/even-client/src/boot.ts +++ b/apps/even-client/src/boot.ts @@ -6,6 +6,7 @@ import { waitForEvenHost, watchForLateHost, type HostWindow } from './device/hos import { BrowserPreviewDevice } from './device/previewDevice.ts'; import type { DevicePort } from './device/port.ts'; import { mountPhoneUi } from './ui/phone.ts'; +import { createSpeaker } from './ui/speaker.ts'; /** * Page start-up, kept out of main.ts so it can be exercised against a real DOM in tests. @@ -37,6 +38,8 @@ export interface BootOptions { menu?: boolean; /** `false`: no words shown while recording. For automated simulator runs. */ livePreview?: boolean; + /** `false`: answers are never read aloud and the menu has no Voice entry. */ + voice?: boolean; /** Reload hook, replaceable in tests. */ reload?: () => void; } @@ -102,6 +105,8 @@ export async function boot(doc: Document, win: Window, options: BootOptions = {} wake: mode === 'even' && options.wake !== false ? {} : null, menu: options.menu !== false, livePreview: mode === 'even' && options.livePreview !== false, + // Spoken answers: only in the Even app (the menu entry is on the glasses). + speaker: mode === 'even' && options.voice !== false ? createSpeaker(win) : null, ...(options.idleExit === false ? { idleExit: null } : typeof options.idleExit === 'object' ? { idleExit: options.idleExit } : {}), // Development builds mirror diagnostics to the console (visible in the simulator and the // Even dev console). Diagnostics never contain questions, answers or credentials. diff --git a/apps/even-client/src/core/controller.ts b/apps/even-client/src/core/controller.ts index 27e54c9..97091dd 100644 --- a/apps/even-client/src/core/controller.ts +++ b/apps/even-client/src/core/controller.ts @@ -94,9 +94,18 @@ export interface Snapshot { * it. `enabled`: that mode is the one in use. `listening`: the microphone is open for it now. */ wake: { available: boolean; enabled: boolean; listening: boolean }; + /** Reading answers aloud. `offered`: possible here. `on`: switched on. `speaking`: playing now. */ + voice: { offered: boolean; on: boolean; speaking: boolean }; log: DiagEntry[]; } +/** Something that can play an answer's audio. The real one is the page's sound engine. */ +export interface SpeakerPort { + /** Play MP3 audio. Resolves when it has finished or was stopped; rejects if it cannot play. */ + play(audio: Uint8Array): Promise; + stop(): void; +} + export interface WakeTiming { /** After a name alone, a pause this long ends the question that follows. */ commandEndSilenceMs: number; @@ -154,6 +163,11 @@ export interface ControllerOptions { now?: () => number; makeClient?: (baseUrl: string, token: string) => BridgeClient; onChange?: (snapshot: Snapshot) => void; + /** + * Lets answers be read aloud when the bridge can do it and the user switches Voice on (a + * menu entry, so it needs `menu`). Without it nothing is ever fetched or played. + */ + speaker?: SpeakerPort | null; /** Receives each diagnostic entry (ids, codes, timings; never content). */ onNote?: (entry: DiagEntry) => void; /** Override the poll schedule with one fixed interval (tests). */ @@ -281,6 +295,12 @@ export class Controller { /** The bridge said it cannot do previews (or is too old): stop asking for this session. */ private previewUnsupported = false; + // ---- reading answers aloud (all unused without a speaker) + /** The agents the bridge has a voice for. */ + private speechAgents: string[] = []; + /** The answer being fetched or played. `abort` stops the fetch. */ + private speaking: { requestId: string; abort: AbortController; playing: boolean } | null = null; + // ---- listening for a name (all unused when `wake` is null) private readonly wake: WakeTiming | null; private readonly segmenter = new SpeechSegmenter(); @@ -390,6 +410,7 @@ export class Controller { handsFree: this.handsFreeAvailable(), }); if (abandoned) void this.cancelTurn(abandoned); + void this.loadSpeech(); if (this.wake) this.wakeWatch = setInterval(() => this.watchWakeMic(), this.wake.watchMs); } @@ -672,6 +693,7 @@ export class Controller { if (this.wakeWatch) clearInterval(this.wakeWatch); this.wakeWatch = null; this.stopTicker(); + this.quiet(); await this.closeMic(); } @@ -693,6 +715,7 @@ export class Controller { enabled: this.wakeOn(), listening: this.state.wakeListening, }, + voice: { offered: this.state.voiceOffered, on: this.state.voice, speaking: this.speaking?.playing === true }, log: [...this.log], }; } @@ -746,6 +769,7 @@ export class Controller { menu: this.options.menu === true, handsFree: this.handsFreeAvailable(), }); + void this.loadSpeech(); } /** Disconnect: revoke the credential on the bridge, then clear everything held locally. */ @@ -810,6 +834,8 @@ export class Controller { this.state = step.state; // In the same step, before anything is drawn or another question can start. this.reconcileRemovedAgent(); + // An answer is only read while it is the one on screen: anything that moves on stops it. + if (this.speaking && (this.state.phase !== 'answer' || this.state.requestId !== this.speaking.requestId || !this.state.voice)) this.quiet(); if (before.phase !== step.state.phase) this.note('state', `${before.phase} -> ${step.state.phase}`); for (const effect of step.effects) void this.run(effect); this.afterChange(); @@ -841,6 +867,8 @@ export class Controller { if (this.stopped || this.exited || !this.idleExitMs || !this.hudReady) return; // Listening for a name is the point of staying open: the app does not leave by itself. if (this.wakeOn()) return; + // Not while an answer is being read out: the countdown starts when it ends. + if (this.speaking) return; const phase = this.state.phase; const wait = phase === 'answer' @@ -1316,6 +1344,73 @@ export class Controller { } } this.dispatch({ type: 'turn_update', generation, result, pages }); + if (result.terminal && (result.outcome === 'succeeded' || result.outcome === 'incomplete') && result.answer_text) { + void this.speak(result.request_id); + } + } + + // ------------------------------------------------------ reading answers aloud + + /** Ask the bridge whether it can read answers aloud. Quietly "no" on any failure. */ + private async loadSpeech(): Promise { + const client = this.client; + if (!this.options.speaker || !client) return; + let agents: string[] = []; + try { + const info = await client.speech(); + agents = info.available ? info.agent_ids : []; + } catch (err) { + if (!(err instanceof BridgeApiError && err.body.code === 'not_found')) this.note('voice', `not available: ${describe(err)}`); + } + if (this.stopped || this.client !== client) return; + this.speechAgents = agents; + this.dispatch({ type: 'voice_offered', offered: agents.length > 0 }); + } + + /** Read the answer on screen aloud, if Voice is on and its agent has a voice. */ + private async speak(requestId: string): Promise { + const speaker = this.options.speaker; + const client = this.client; + if (!speaker || !client || !this.state.voice) return; + if (this.state.phase !== 'answer' || this.state.requestId !== requestId) return; + if (!this.speechAgents.includes(this.state.agentId ?? 'default')) return; + this.quiet(); + const mine = { requestId, abort: new AbortController(), playing: false }; + this.speaking = mine; + this.scheduleIdleExit(); + const startedAt = this.now(); + try { + const audio = await client.turnSpeech(requestId, mine.abort.signal); + if (this.speaking !== mine) return; + this.note('voice', `audio for ${requestId}: ${audio.length} bytes in ${this.now() - startedAt} ms`); + mine.playing = true; + this.emit(); + await speaker.play(audio); + if (this.speaking === mine) this.note('voice', `finished ${requestId} after ${this.now() - startedAt} ms`); + } catch (err) { + // No speech this time. The answer is on the glasses either way. + if (this.speaking === mine) this.note('voice', `not spoken: ${describe(err)}`); + } finally { + if (this.speaking === mine) { + this.speaking = null; + this.emit(); + this.scheduleIdleExit(); + } + } + } + + /** Stop reading aloud, and stop waiting for audio that has not arrived. */ + private quiet(): void { + const was = this.speaking; + if (!was) return; + this.speaking = null; + was.abort.abort(); + try { + this.options.speaker?.stop(); + } catch { + // Nothing was playing. + } + this.note('voice', `stopped ${was.requestId}`); } private async cancelTurn(requestId: string): Promise { diff --git a/apps/even-client/src/core/hud.ts b/apps/even-client/src/core/hud.ts index 8910f62..d10129a 100644 --- a/apps/even-client/src/core/hud.ts +++ b/apps/even-client/src/core/hud.ts @@ -1,4 +1,4 @@ -import { currentAgent, menuItems, MODE_LABEL, type AppState } from './reducer.ts'; +import { currentAgent, menuItems, menuLabel, type AppState } from './reducer.ts'; /** * HUD geometry. Canvas size and line height are documented by Even @@ -86,7 +86,7 @@ function renderFrame(state: AppState, nowMs: number): HudFrame { case 'menu': { // Plain ASCII marker: the firmware font silently drops characters it does not have. - const lines = menuItems(state).map((mode, i) => `${i === state.menuIndex ? '>' : ' '} ${MODE_LABEL[mode]}`); + const lines = menuItems(state).map((item, i) => `${i === state.menuIndex ? '>' : ' '} ${menuLabel(item, state)}`); return { body: `Hermeven\n\n${lines.join('\n')}`, status: lines.length > 1 ? 'Tap: open · Swipe: move · 2×: exit' : 'Tap: open · Double-tap: exit' }; } diff --git a/apps/even-client/src/core/reducer.ts b/apps/even-client/src/core/reducer.ts index 2ac96ab..119608c 100644 --- a/apps/even-client/src/core/reducer.ts +++ b/apps/even-client/src/core/reducer.ts @@ -55,6 +55,10 @@ export interface AppState { mode: Mode; /** Hands free can be offered: this build has it, and nothing has said the bridge cannot do it. */ handsFree: boolean; + /** The bridge can read answers aloud and this page can play sound: the menu offers Voice. */ + voiceOffered: boolean; + /** Answers are read aloud. Chosen on the menu; off at every launch, never saved. */ + voice: boolean; /** * The agents the bridge offers, default first. Empty when there is only one (or the bridge * predates agent selection): nothing about agents is then shown or sent. @@ -115,6 +119,8 @@ export const initialState: AppState = { menuIndex: 0, mode: 'agents', handsFree: false, + voiceOffered: false, + voice: false, agents: [], agentId: null, generation: 0, @@ -155,6 +161,8 @@ export type AppEvent = } /** Hands free turned out not to be possible (the bridge cannot do it): fall back to Agents. */ | { type: 'handsfree_lost' } + /** Whether answers can be read aloud at all (asked of the bridge after pairing). */ + | { type: 'voice_offered'; offered: boolean } /** The user picked another agent (a swipe at Ready). `conversationId` is that agent's own, if it has one. */ | { type: 'agent_selected'; agentId: string; conversationId: string | null } /** @@ -219,8 +227,15 @@ const IDLE: ReadonlySet = new Set(['ready', 'answer', 'error', 'cancelled const IN_FLIGHT: ReadonlySet = new Set(['transcribing', 'thinking', 'approval']); /** The menu's entries, in order. Hands free comes first whenever it can be offered. */ -export function menuItems(state: Pick): Mode[] { - return state.handsFree ? ['handsfree', 'agents'] : ['agents']; +export type MenuItem = Mode | 'voice'; +export function menuItems(state: Pick): MenuItem[] { + const modes: MenuItem[] = state.handsFree ? ['handsfree', 'agents'] : ['agents']; + return state.voiceOffered ? [...modes, 'voice'] : modes; +} + +/** How a menu entry reads. Voice is a switch, so it shows its setting. */ +export function menuLabel(item: MenuItem, state: Pick): string { + return item === 'voice' ? `Voice: ${state.voice ? 'on' : 'off'}` : MODE_LABEL[item]; } /** The agent questions go to now, or undefined when the bridge offers no choice. */ @@ -313,6 +328,12 @@ export function reduce(state: AppState, event: AppEvent): Step { return same({ ...base, phase: base.menu ? 'menu' : 'ready' }); } + case 'voice_offered': { + if (event.offered === state.voiceOffered) return same(state); + const next = { ...state, voiceOffered: event.offered, voice: event.offered && state.voice }; + return same({ ...next, menuIndex: Math.min(state.menuIndex, menuItems(next).length - 1) }); + } + case 'handsfree_lost': { if (!state.handsFree) return same(state); const wasOn = state.mode === 'handsfree'; @@ -403,7 +424,10 @@ export function reduce(state: AppState, event: AppEvent): Step { case 'activate': { if (state.phase === 'menu') { - const mode = menuItems(state)[state.menuIndex] ?? 'agents'; + const item = menuItems(state)[state.menuIndex] ?? 'agents'; + // Voice is a switch: it flips and the menu stays. + if (item === 'voice') return same({ ...state, voice: !state.voice }); + const mode: Mode = item; return same({ ...clearTurn(state), phase: 'ready', mode, generation: state.generation + 1 }); } if (IDLE.has(state.phase)) { diff --git a/apps/even-client/src/main.ts b/apps/even-client/src/main.ts index 09d6e2a..118f023 100644 --- a/apps/even-client/src/main.ts +++ b/apps/even-client/src/main.ts @@ -26,6 +26,7 @@ const { controller } = await boot(document, window, { wake: !(import.meta.env.DEV && new URLSearchParams(location.search).get('wake') === 'off'), menu: !(import.meta.env.DEV && new URLSearchParams(location.search).get('menu') === 'off'), livePreview: !(import.meta.env.DEV && new URLSearchParams(location.search).get('preview') === 'off'), + voice: !(import.meta.env.DEV && new URLSearchParams(location.search).get('voice') === 'off'), }); // Development-only convenience for automated simulator runs, where nothing can type into the diff --git a/apps/even-client/src/net/bridgeClient.ts b/apps/even-client/src/net/bridgeClient.ts index 8239cfd..588358c 100644 --- a/apps/even-client/src/net/bridgeClient.ts +++ b/apps/even-client/src/net/bridgeClient.ts @@ -8,6 +8,7 @@ import { ErrorResponse, RevokeResponse, SCHEMA_VERSION, + SpeechInfoResponse, TranscribeResponse, TurnResult, WakeResponse, @@ -207,6 +208,46 @@ export class BridgeClient { return this.call(TranscribeResponse, 'POST', `/v1/transcribe?${query}`, { binary: args.pcm }); } + /** Whether answers can be read aloud, and for which agents. An older bridge answers `not_found`. */ + speech(): Promise { + return this.call(SpeechInfoResponse, 'GET', '/v1/speech'); + } + + /** A finished answer read aloud, as MP3. Not JSON, so it does not go through `call`. */ + async turnSpeech(requestId: string, signal?: AbortSignal): Promise { + let res: Response; + try { + res = await this.fetchImpl(`${this.baseUrl}/v1/turns/${requestId}/speech`, { + method: 'GET', + headers: { Accept: 'audio/mpeg', Authorization: `Bearer ${this.token}` }, + signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(this.timeoutMs * 2)]) : AbortSignal.timeout(this.timeoutMs * 2), + credentials: 'omit', + cache: 'no-store', + }); + } catch (err) { + throw new BridgeNetworkError(err instanceof Error ? err.name : 'network error'); + } + if (!res.ok) { + let payload: unknown; + try { + payload = await res.json(); + } catch { + payload = null; + } + if (check(ErrorResponse, payload)) throw new BridgeApiError(res.status, payload.error as ErrorBody); + throw new BridgeNetworkError(`unexpected HTTP ${res.status}`); + } + const type = (res.headers.get('Content-Type') ?? '').split(';')[0]!.trim().toLowerCase(); + if (type !== 'audio/mpeg') throw new BridgeNetworkError('response was not audio'); + try { + const audio = new Uint8Array(await res.arrayBuffer()); + if (audio.length === 0) throw new Error('empty'); + return audio; + } catch (err) { + throw new BridgeNetworkError(err instanceof Error ? err.name : 'network error'); + } + } + getTurn(requestId: string): Promise { return this.call(TurnResult, 'GET', `/v1/turns/${requestId}`) as Promise; } diff --git a/apps/even-client/src/ui/phone.ts b/apps/even-client/src/ui/phone.ts index 4433e77..b37f834 100644 --- a/apps/even-client/src/ui/phone.ts +++ b/apps/even-client/src/ui/phone.ts @@ -158,6 +158,14 @@ export function mountPhoneUi(root: HTMLElement, controller: Controller, defaults ['Bridge', s.bridgeUrl], ['Agent', s.status ? (s.status.agent_reachable ? 'reachable' : 'not reachable from the bridge') : 'not checked'], ['Speech-to-text', s.status ? (s.status.stt_configured ? 'configured' : 'not configured (typed questions only)') : 'not checked'], + [ + 'Spoken answers', + !s.voice.offered + ? 'not available (the bridge has no voices set up, or this page cannot play sound)' + : s.voice.on + ? `on${s.voice.speaking ? ', speaking now' : ''}: answers are sent to the speech provider and played on whatever sound output the phone is using` + : 'off. Switch on with “Voice” on the glasses’ opening menu; it is off again at every launch.', + ], ['Credential valid until', when(s.tokenExpiresAt)], ['Pairing valid until', when(s.pairingExpiresAt)], ['Stored on this phone', 'In the Even app’s app storage, which is not an encrypted vault. The credential is revocable and expires.'], diff --git a/apps/even-client/src/ui/speaker.ts b/apps/even-client/src/ui/speaker.ts new file mode 100644 index 0000000..8e94fd5 --- /dev/null +++ b/apps/even-client/src/ui/speaker.ts @@ -0,0 +1,58 @@ +import type { SpeakerPort } from '../core/controller.ts'; + +/** + * Plays an answer's audio through the page's sound engine (Web Audio). Where it is heard is + * Android's choice, not ours: whatever output is selected (earbuds, car, or the phone itself). + * The page cannot tell which, so speech is only ever played after the user switched Voice on. + * + * Device evidence (docs/evidence/device/2026-11-29.md): in the Even app on Dan's phone a page + * may play sound without a touch, and did so 20 s after a press. Playing an MP3 this way has + * NOT been tried on the device. + */ +export function createSpeaker(win: Window): SpeakerPort | null { + const w = win as unknown as { AudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext }; + const Ctor = w.AudioContext ?? w.webkitAudioContext; + if (!Ctor) return null; + let context: AudioContext | null = null; + let current: { source: AudioBufferSourceNode; done: () => void } | null = null; + + const stop = () => { + const playing = current; + current = null; + if (!playing) return; + try { + playing.source.onended = null; + playing.source.stop(); + } catch { + // Already stopped. + } + playing.done(); + }; + + return { + async play(audio: Uint8Array): Promise { + stop(); + context ??= new Ctor(); + const ctx = context; + await Promise.race([ctx.resume(), new Promise((r) => win.setTimeout(r, 800))]); + if (ctx.state !== 'running') throw new Error(`sound is blocked (${ctx.state})`); + // decodeAudioData takes ownership of the buffer it is given: hand it a copy. + const copy = audio.buffer.slice(audio.byteOffset, audio.byteOffset + audio.byteLength) as ArrayBuffer; + const buffer = await ctx.decodeAudioData(copy); + // Stopped, or replaced by a newer answer, while decoding. + if (current) stop(); + const source = ctx.createBufferSource(); + source.buffer = buffer; + source.connect(ctx.destination); + await new Promise((resolve) => { + current = { source, done: resolve }; + source.onended = () => { + if (current?.source === source) current = null; + resolve(); + }; + source.start(); + }); + }, + stop, + }; +} diff --git a/apps/even-client/test/layout.test.ts b/apps/even-client/test/layout.test.ts index 1a743a0..9d6dd7c 100644 --- a/apps/even-client/test/layout.test.ts +++ b/apps/even-client/test/layout.test.ts @@ -184,7 +184,7 @@ describe('HUD frames', () => { { id: 'cody', name: 'Cody' }, ]; const wake = { wakeListening: true }; - if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }]; + if (phase === 'menu') return [base, { ...base, handsFree: true }, { ...base, handsFree: true, menuIndex: 1 }, { ...base, handsFree: true, voiceOffered: true, menuIndex: 2 }, { ...base, voiceOffered: true, voice: true, menuIndex: 1 }]; if (phase === 'ready') { return [{ ...base, menu: true }, { ...base, menu: true, ...wake, agents: few }, base, { ...base, notice: 'New conversation' }, { ...base, ...wake }, { ...base, ...wake, agents: few }, { ...base, ...wake, agents: many }, { ...base, ...wake, agents: few, notice: 'New conversation' }]; } diff --git a/deploy/bridge.env.example b/deploy/bridge.env.example index 55202d9..0b93785 100644 --- a/deploy/bridge.env.example +++ b/deploy/bridge.env.example @@ -15,6 +15,18 @@ HERMES_PROFILE_LABEL=default # HERMEVEN_AGENT_CODY_WAKE=kody,codi # HERMEVEN_AGENT_WAKE=peper +# Optional: answers read aloud (0.5.0). Off unless a key is set here AND an agent has a voice. +# With it on, when the user has switched "Voice" on in the app, the text of each answer (cut to +# HERMEVEN_SPEECH_MAX_CHARS) is sent to ElevenLabs and is paid for there. The key stays on this +# host. Voice ids are the ids ElevenLabs shows for a voice, not its name. +# HERMEVEN_ELEVENLABS_API_KEY=replace-with-an-elevenlabs-api-key +# HERMEVEN_AGENT_VOICE=voice-id-for-the-default-agent +# HERMEVEN_AGENT_WENDY_VOICE=voice-id-for-wendy +# HERMEVEN_AGENT_CODY_VOICE=voice-id-for-cody +# HERMEVEN_ELEVENLABS_MODEL=eleven_flash_v2_5 +# HERMEVEN_SPEECH_MAX_CHARS=900 +# HERMEVEN_SPEECH_PER_MINUTE=6 + HERMEVEN_HOST=127.0.0.1 HERMEVEN_PORT=8787 # Caddy is in front, so the client address comes from its forwarded header. diff --git a/docs/bridge-api.md b/docs/bridge-api.md index d665015..f7e2bff 100644 --- a/docs/bridge-api.md +++ b/docs/bridge-api.md @@ -23,6 +23,8 @@ Every error has the shape: | `POST /v1/turns` | Create one turn (text or audio). | 202, or 200 for a duplicate | | `POST /v1/wake` | One stretch of speech heard while the app was open (raw audio body, same format as an audio turn; query: `schema_version`, `locale`, `encoding`, `sample_rate`, `channels`). Transcribed in memory and dropped. Answers `{matched, agent_id, text, near_miss}`: whether it **began** with an agent's name, which agent, and what was said after the name (empty for the name alone). When not matched `text` is always empty; `near_miss` is the first word if it was close to a name. Creates no turn and sends nothing to any agent. 404 `not_found` when speech-to-text is off or no agent has a usable name (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_WAKE_CHECKS_PER_MINUTE` (default 30) or while this device's previous check is still running. A failed transcription is answered as not matched. | 200 | | `POST /v1/transcribe` | The words in a recording that is still being made, for showing while the user speaks. Same body and query as `/v1/wake`. Answers `{text}` (empty if nothing was recognised or transcription failed). Transcribed in memory and dropped; creates no turn, sends nothing to any agent, logs no text. 404 `not_found` when speech-to-text is off (also what an older bridge answers); 429 `rate_limited` over `HERMEVEN_PREVIEWS_PER_MINUTE` (default 60) or while this device's previous preview is still running. | 200 | +| `GET /v1/speech` | Whether answers can be read aloud: `{available, agent_ids, max_chars}`. `available` is false (and the list empty) unless the bridge has a speech provider key and at least one agent has a voice. Added in 0.5.0: an older bridge answers 404 `not_found`, which a client must treat as "not available". | 200 | +| `GET /v1/turns/{request_id}/speech` | The answer of one of this device's own finished turns (`succeeded` or `incomplete`), read aloud in its agent's voice. **The response is `audio/mpeg`, not JSON.** The text is the answer with markup, code blocks and web addresses removed, cut to `HERMEVEN_SPEECH_MAX_CHARS` (default 900) at the end of a sentence where one is near; it is sent to the speech provider (ElevenLabs). Neither text nor audio is stored or logged; the last three are kept in memory so a repeat is not paid for twice. There is no way to have other text spoken. 404 `not_found` for an unknown, foreign or unfinished turn, an answer with nothing to read, an agent without a voice, or speech not configured (all indistinguishable); 429 `rate_limited` over `HERMEVEN_SPEECH_PER_MINUTE` (default 6) new syntheses per device; 500 `internal` "Speech could not be generated." when the provider fails (its message is never passed on). | 200 | | `GET /v1/turns/{request_id}` | Current state and result. | 200 | | `POST /v1/turns/{request_id}/cancel` | Request cancellation. Idempotent. | 200 | @@ -151,6 +153,8 @@ Defaults, all configurable. These are limits, not measured performance. | Agent deadline | 120 s, paused while an approval is pending | | Approval wait | 300 s | | Grace period to confirm a stop | 30 s | +| Speech provider deadline | 20 s | +| Answer read aloud | first 900 characters, 6 answers a minute per device | No latency percentiles are published because none have been measured against a real STT provider, a real model or a real device. diff --git a/docs/decisions/0006-spoken-answers.md b/docs/decisions/0006-spoken-answers.md new file mode 100644 index 0000000..0e2b236 --- /dev/null +++ b/docs/decisions/0006-spoken-answers.md @@ -0,0 +1,70 @@ +# 0006: Spoken answers through the page, switched on by hand + +Date: 2026-11-29. Status: built for trial (0.5.0), not reviewed, not on the device. + +## What Dan asked for + +> "Pivot time - I'd like to get the voice thing going for the ability to get spoken replies back +> in my galaxy pro ear buds when they're connected. Part of the scope in +> https://git.xylo.gg/Xylo-Digital/hermeven/issues/1" + +Earlier (2026-11-28) he had described the eventual shape: the phone or app detecting Android +Auto or a Bluetooth headset "so that the agents can use their elevenlab voices and return their +responses into a speaker as well as on screen." + +## What the sound check showed (0.4.1, Dan's phone, 2026-11-29) + +Reported by Dan from the Sound check section, earbuds connected; full text in +`docs/evidence/device/2026-11-29.md`. + +| Question | Result | +|---|---| +| Can the page play sound, and where is it heard? | Yes; in the earbuds | +| Without a touch on the phone? | "allowed" | +| 20 s after a press? | Played | +| The phone's own voice (`speechSynthesis`)? | "not available in this page" | +| Which outputs can the page see? | "1. without names" | + +So: the existing page can play sound and Android routes it; a voice has to be made somewhere +else; and the page cannot know whether earbuds are connected. + +## Decision + +1. **No native companion yet.** Issue #1 proposes one for route awareness. The page can already + do the playing, and Android's own routing satisfies the issue's rule of never forcing a + route. What the page cannot do is *know* the route, which is item 2. +2. **Voice is a switch on the opening menu, off at every launch.** Proposed to Dan as the + consequence of the last row above; his answer: "yes on the voice menu entry, cap it". It is + not saved, so a forgotten setting cannot speak from the loudspeaker next time. +3. **ElevenLabs, called by the bridge.** Dan named it. The key stays on the server; the app + receives audio only. One voice id per agent (`HERMEVEN_AGENT__VOICE`); an agent without + one is not read. +4. **Capped.** Asked "speak the whole thing, or cap it (say the first 60 seconds)", Dan: "cap + it". Implemented as characters, not seconds: 900 by default, cut at a sentence end. 900 + characters is roughly a minute at an ordinary speaking rate; **that equivalence is an + estimate and has not been measured with any voice.** +5. **Speech is of a turn, not of text.** `GET /v1/turns/{id}/speech` reads only the caller's + own finished answer. There is no endpoint that speaks arbitrary text, so a device credential + cannot be used as a general speech account. +6. **Stopping.** Reading stops when the answer leaves the screen (double tap, a new question by + tap, name or typing) or Voice is switched off. Turning the page does not stop it. The app + does not leave the glasses while it is reading. + +## Not done, on purpose + +- Detecting earbuds, the car, or "worn". Not possible from the page; issue #1 remains open for it. +- Audio focus (pausing music, ducking), Android Auto behaviour, phone calls. Untested. +- Streaming the audio as it is generated. The whole clip is fetched, then played. +- A marker on the glasses that Voice is on outside the menu. +- Reading questions back, or any speech not tied to an answer. + +## Risks to judge + +- **Answers now go to a third party** when Voice is on (security 3g). +- **The loudspeaker case** (security 3h). +- **Cost** is per character at ElevenLabs. Bounded per device by the cap and six syntheses a + minute; not bounded per day. +- **MP3 decoding and playback in the Even app's WebView is untested.** The sound check played a + generated tone, not a decoded file. +- **The provider's API** was written from its documentation as read on 2026-11-29 and has never + been called by this code. The tests use a fake that imitates the documented request. diff --git a/docs/device-test-plan.md b/docs/device-test-plan.md index ff82fd0..1973b11 100644 --- a/docs/device-test-plan.md +++ b/docs/device-test-plan.md @@ -94,6 +94,26 @@ If A13 fails, stop and report it. It is a product-level blocker, not a bug to wo | D9 | In Agents, tap and speak a long sentence slowly. | Do words appear while speaking? How far behind? Do they jump or flicker? | Live preview on a real G2 and the real server. | | D10 | After sending, watch the screen. | Does "Heard: ..." show what you said? Seconds from tap to "thinking" compared with 0.3.0. | Whether a running preview delays the real transcription noticeably. | +## E. Spoken answers (0.5.0; nothing here has been run) + +Needs an ElevenLabs key and a voice per agent in `/etc/hermeven/bridge.env`. Record the phone, +Android version, Even app version, earbud model, and for every row which outputs were +**connected**, which was **selected** in Android, and whether anything was **worn**: the app +cannot tell these apart and neither can this plan unless they are written down. + +| # | Do | Record | Answers | +|---|---|---|---| +| E0 | Open the app with the bridge configured. | Does the menu show a third entry, "Voice: off"? Does a tap change it to "Voice: on" and stay on the menu? | The menu entry on a real G2. | +| E1 | Voice on, earbuds in and selected. Agents, ask a short question. | Is the answer heard, in the earbuds, in the right voice? Seconds from the answer appearing to the voice starting. | MP3 playback in the Even app; routing; latency. | +| E2 | Ask each agent. | Right voice for each? An agent without a voice stays silent? | Per-agent voices. | +| E3 | While it is speaking: swipe; then double tap; then (next answer) tap. | Does a swipe leave it speaking, and the others stop it at once? | Stopping. | +| E4 | Ask for something long. | Does the voice stop at a sentence after roughly a minute while the text continues on the glasses? | The cap. | +| E5 | Voice on, hands free, phone locked in a pocket. "Wendy, ...". | Is it spoken? Does a second "Wendy, ..." during the speech work, and does the speech stop? | Unattended playback; the microphone while speaking. | +| E6 | Voice on, earbuds out. Ask. | Where is it heard? | 3h above: the loudspeaker case. | +| E7 | Earbuds in, a call or music playing. Ask. | What happens to the music? Is the answer audible? | Audio focus (not handled by the app). | +| E8 | Close and reopen the app. | Is Voice off again? | Not remembered. | +| E9 | In Agents with Voice on, ask and do nothing. | Does the app stay on the glasses until the voice ends, then leave after the usual wait? | Idle exit while speaking. | + ## Reporting Anything that fails in A13, A14, A15 or C1 is a blocker or a stated limitation of the product, to diff --git a/docs/evidence/device/2026-11-29.md b/docs/evidence/device/2026-11-29.md new file mode 100644 index 0000000..6364f77 --- /dev/null +++ b/docs/evidence/device/2026-11-29.md @@ -0,0 +1,44 @@ +# 0.4.1 on the server and the phone: the sound check, 2026-11-29 + +**Whose evidence this is.** Server facts are the implementer's (Claude's) own commands and the +bridge's replies. What happened on the phone is Dan's report, quoted. Nothing on the device was +seen or heard by the implementer. + +## Deployment and upload + +Cody, Round 23: SHIP / SHIP FOR TRIAL on `d65beeab77288049b801e4969ac9b68821833b23`. Told what a +"go" would do (deploy the bridge, then build, upload and promote 0.4.1), Dan: "go". + +| Step | Result | +|---|---| +| `git archive d65beea` to `/root/hermeven-src`, `deploy/install.sh --bridge-url https://hermeven.xylo.gg` | All seven steps. `DEPLOYED_SHA` is `d65beeab77288049b801e4969ac9b68821833b23` (was `e4c102a`). | +| `systemctl restart hermeven-bridge`, 19:50 UTC | active; `stt.ready` in 2.4 s; healthz ok at `https://hermeven.xylo.gg`. No turn had been accepted in the 90 s before. Hermes was not restarted. `/etc/hermeven/bridge.env` was not changed. | +| Smoke test with a temporary device (`smoke-0.4.1`, revoked afterwards; 401 after revocation) | The repository's 11 s archive speech clip to `/v1/wake` (200, 1.79 s) and `/v1/transcribe` (200, 2.74 s). The log gained one `wake.checked` (`audio_ms` 11001, `check_ms` 1522, `matched` false, `near_miss` false) and one `preview.done` (`audio_ms` 11001, `preview_ms` 2543, `empty` false). No word of the transcript in the log. | +| Package | `hermeven.ehpk`, 106,593 bytes, SHA-256 `8e231e8c215cdd76f956204dd6abb39ca6094f8b33d061866b901d8a3ec1c33a`, built twice from `d65beea` with a clean tree: the hash Cody recorded. | +| Even account | `evenhub upload` 0.4.1, `evenhub promote 0.4.1 --to beta`. `evenhub ls`: 0.4.1 Private, beta; 0.4.0 no longer on a channel. | + +## What Dan reported + +Asked to press the four buttons with the earbuds in and connected, to lock the phone after the +second, and to say what the lines read. His whole reply: + +> "1. yes, in buds, 2. yes, in 20s, 3. nothing happened with this button, 4. without touching +> phone: allowed, outpush this page can see 1. without names, test sound at 11:51, dleayed sound +> 11:52, phone voice: not available in this page" + +| Establishes | | +|---|---| +| A page in the Even app can play Web Audio, and it was heard in the earbuds | Yes (item 1). | +| Without a touch | The page reported "allowed": the sound engine was running when the page opened. | +| 20 s after a press | Played (item 2). **Whether the phone was locked at the time was not said.** | +| `speechSynthesis` | Not available in that WebView. | +| Output devices visible to the page | One, unnamed. The page cannot tell earbuds from the loudspeaker. | + +Not established: the phone model, Android version, Even app version, the earbud model beyond +Dan's earlier "galaxy pro ear buds", whether the earbuds were worn, what was selected in Android, +behaviour with the phone locked or the Even app in the background, behaviour with no earbuds, +with the car, or with other audio playing, and whether a decoded MP3 plays as the tone did. + +The single recording in Agents that was also asked for (to see whether the glasses request live +words) had not been made when the log was read at 19:54 UTC: no request from the glasses had +arrived since the restart. diff --git a/docs/security.md b/docs/security.md index fec1619..d13c9cb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -94,6 +94,22 @@ Stated so they are not mistaken for protections. touch) and asks the browser which media devices exist; output names, if the browser gives them, are shown on the page only. It plays a tone or the phone's own voice only when a button on the page is pressed. It sends nothing to the bridge and records nothing. +3g. **With Voice switched on (0.5.0), answers leave your infrastructure.** Until now nothing + but the agent's own model calls did. When the bridge has an ElevenLabs key and the user has + switched "Voice" on (a menu entry on the glasses, off at every launch), the app asks the + bridge for the speech of each answer and the bridge sends that answer's text, with markup + removed and cut to 900 characters, to ElevenLabs, which returns audio. What ElevenLabs keeps + is governed by its terms and the account's settings, not by this code. Questions are not + sent; only answers. The key is in `/etc/hermeven/bridge.env` and is never sent to the app. + A client can only obtain speech for its own finished turns, at most six new ones a minute, + so a stolen device credential cannot use the account to speak arbitrary text. +3h. **Where the sound comes out is not known to the app.** A page in the Even app cannot tell + which output Android is using (measured on Dan's phone, 2026-11-29: one output, no name). With + Voice on and no earbuds connected, the answer is spoken from the phone's loudspeaker, to + whoever is nearby. Voice is therefore never on by default and is not remembered. +3i. **Shutdown now closes every connection** (`forceCloseConnections`). Before, a request the + app had given up on could keep the bridge from stopping until systemd killed it after 20 s. + A request cut off by a shutdown is retried by the app as after any other network failure. 4. **In the simulator, raw audio frames are echoed to the WebView console.** Whether the phone does the same is unknown and is on the device checklist. If it does, recordings would be visible to whoever can read that console. diff --git a/packages/contracts/src/schemas.ts b/packages/contracts/src/schemas.ts index 7ff1bc8..a899875 100644 --- a/packages/contracts/src/schemas.ts +++ b/packages/contracts/src/schemas.ts @@ -248,6 +248,23 @@ export const TranscribeResponse = Type.Object( ); export type TranscribeResponse = Static; +/** + * Whether answers can be read aloud, and for which agents. The audio itself is + * `GET /v1/turns/{request_id}/speech` (MP3, not JSON). + */ +export const SpeechInfoResponse = Type.Object( + { + schema_version: SchemaVersion, + available: Type.Boolean(), + /** The agents that have a voice. Empty when not available. */ + agent_ids: Type.Array(AgentId, { maxItems: 16 }), + /** At most this many characters of an answer are read. */ + max_chars: Type.Integer({ minimum: 0, maximum: 5000 }), + }, + { additionalProperties: false }, +); +export type SpeechInfoResponse = Static; + export const TURN_STATES = [ 'accepted', 'transcribing', diff --git a/services/bridge/src/app.ts b/services/bridge/src/app.ts index 66ba2dd..98f0732 100644 --- a/services/bridge/src/app.ts +++ b/services/bridge/src/app.ts @@ -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 { 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(); diff --git a/services/bridge/src/config.ts b/services/bridge/src/config.ts index 824cde1..86ad208 100644 --- a/services/bridge/src/config.ts +++ b/services/bridge/src/config.ts @@ -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__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(); 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), }, diff --git a/services/bridge/src/server.ts b/services/bridge/src/server.ts index bd921cb..e07a1c6 100644 --- a/services/bridge/src/server.ts +++ b/services/bridge/src/server.ts @@ -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 { 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 { 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>(); + /** The last few answers spoken, so a repeated request is not paid for twice. In memory only. */ + const speechCache = new Map(); + const voiced = () => (deps.tts.configured ? config.agents.filter((a) => a.voiceId) : []); + + app.get('/v1/speech', async (req): Promise => { + 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 }; diff --git a/services/bridge/src/tts.ts b/services/bridge/src/tts.ts new file mode 100644 index 0000000..d217a75 --- /dev/null +++ b/services/bridge/src/tts.ts @@ -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; +} + +export class NoTtsAdapter implements TtsAdapter { + readonly configured = false; + async synthesize(): Promise { + 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 { + 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 }; +} diff --git a/services/bridge/src/turns.ts b/services/bridge/src/turns.ts index 63fb737..bf9dbc2 100644 --- a/services/bridge/src/turns.ts +++ b/services/bridge/src/turns.ts @@ -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; diff --git a/tests/fakes/fakeTts.ts b/tests/fakes/fakeTts.ts new file mode 100644 index 0000000..0bf8167 --- /dev/null +++ b/tests/fakes/fakeTts.ts @@ -0,0 +1,57 @@ +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +/** + * TEST FAKE. Not a speech synthesiser and not ElevenLabs. + * + * Accepts `POST /v1/text-to-speech/{voice_id}` with an `xi-api-key` header and a JSON body, as + * the provider's documentation describes it (read 2026-11-29), and returns a few bytes labelled + * audio/mpeg that are NOT playable audio. It proves what the bridge sends and how it handles + * failures, and nothing about the real service, its voices, latency, limits or cost. + */ +export class FakeTts { + readonly apiKey = 'fake-tts-key'; + requests: Array<{ voiceId: string; text: string; model: string; outputFormat: string | null }> = []; + private replies: Array<{ status?: number; delayMs?: number; body?: string }> = []; + private server: Server | null = null; + url = ''; + + async start(): Promise { + this.server = createServer(async (req, res) => { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk as Buffer); + const url = new URL(req.url ?? '/', 'http://x'); + const match = /^\/v1\/text-to-speech\/([^/]+)$/.exec(url.pathname); + if (req.method !== 'POST' || !match) { + res.writeHead(404).end(); + return; + } + if (req.headers['xi-api-key'] !== this.apiKey) { + res.writeHead(401, { 'Content-Type': 'application/json' }).end('{"detail":{"status":"invalid_api_key"}}'); + return; + } + const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { text: string; model_id: string }; + this.requests.push({ voiceId: decodeURIComponent(match[1]!), text: body.text, model: body.model_id, outputFormat: url.searchParams.get('output_format') }); + const reply = this.replies.shift() ?? {}; + if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs)); + if (reply.status && reply.status >= 400) { + // A real provider may quote the text back in an error: the bridge must not pass it on. + res.writeHead(reply.status, { 'Content-Type': 'application/json' }).end(JSON.stringify({ detail: { message: `could not speak: ${body.text}` } })); + return; + } + res.writeHead(200, { 'Content-Type': 'audio/mpeg' }).end(Buffer.from(reply.body ?? `FAKE-MP3:${match[1]}:${body.text.length}`)); + }); + await new Promise((resolve) => this.server!.listen(0, '127.0.0.1', resolve)); + this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; + } + + next(...replies: Array<{ status?: number; delayMs?: number; body?: string }>): void { + this.replies.push(...replies); + } + + async stop(): Promise { + // The bridge keeps its connection to the provider open; do not wait for it to idle out. + this.server?.closeAllConnections(); + await new Promise((resolve) => (this.server ? this.server.close(() => resolve()) : resolve())); + } +} diff --git a/tests/integration/voice.test.ts b/tests/integration/voice.test.ts new file mode 100644 index 0000000..1ccef7a --- /dev/null +++ b/tests/integration/voice.test.ts @@ -0,0 +1,483 @@ +import { measureTextWrap } from '@evenrealities/pretext'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { Controller, type Snapshot, type SpeakerPort } from '../../apps/even-client/src/core/controller.ts'; +import { BridgeClient } from '../../apps/even-client/src/net/bridgeClient.ts'; +import { loadConfig } from '../../services/bridge/src/config.ts'; +import { speechText } from '../../services/bridge/src/tts.ts'; +import { FakeDevice } from '../fakes/fakeDevice.ts'; +import { FakeTts } from '../fakes/fakeTts.ts'; +import { createHarness, type Harness } from './harness.ts'; + +/** + * Answers read aloud. The bridge is real. Hermes, the speech provider, the glasses and the + * loudspeaker are TEST FAKES: the "audio" is a few labelled bytes that no player could play. + * This proves who is asked for what, when, and what is kept out of logs; it proves nothing + * about ElevenLabs, about MP3 playback in the Even app, or about where sound is heard. + */ +const WENDY_KEY = 'wendy-profile-key-0123456789'; +const CODY_KEY = 'cody-profile-key-0123456789'; + +let h: Harness; +let tts: FakeTts; +async function harness(extra: Record = {}, voices = true): Promise { + tts = new FakeTts(); + await tts.start(); + h = await createHarness({ + env: { + HERMEVEN_AGENT_NAME: 'Pepper', + HERMEVEN_AGENTS: 'wendy,cody', + HERMEVEN_AGENT_WENDY_API_KEY: WENDY_KEY, + HERMEVEN_AGENT_CODY_API_KEY: CODY_KEY, + ...(voices + ? { + HERMEVEN_ELEVENLABS_BASE_URL: tts.url, + HERMEVEN_ELEVENLABS_API_KEY: tts.apiKey, + HERMEVEN_AGENT_VOICE: 'voicePepper01', + HERMEVEN_AGENT_WENDY_VOICE: 'voiceWendy02', + } + : {}), + ...extra, + }, + }); + h.hermes.profiles.set('wendy', WENDY_KEY); + h.hermes.profiles.set('cody', CODY_KEY); +} +afterEach(async () => { + await h?.close(); + await tts?.stop(); +}); + +async function answered(token: string, output: string, agentId?: string): Promise { + const conversation = (await h.api('POST', '/v1/conversations', { token, json: { schema_version: 1, ...(agentId ? { agent_id: agentId } : {}) } })).body.conversation_id; + h.hermes.next({ kind: 'complete', output }); + const turn = await h.textTurn(token, conversation, 'a question'); + const id = turn.body.request_id as string; + await h.waitTerminal(token, id); + return id; +} +async function speech(token: string | undefined, requestId: string): Promise<{ status: number; type: string | null; bytes: Buffer }> { + const res = await fetch(`${h.url}/v1/turns/${requestId}/speech`, { headers: token ? { Authorization: `Bearer ${token}` } : {} }); + return { status: res.status, type: res.headers.get('content-type'), bytes: Buffer.from(await res.arrayBuffer()) }; +} + +describe('what is read aloud (speechText)', () => { + it('drops markup, code and web addresses', () => { + const { text, truncated } = speechText('## Plan\n\n- **First**, open [the page](https://example.com/a?b=c)\n- Then run:\n```sh\nrm -rf /tmp/x\n```\nSee https://example.com/long/path for more.', 900); + expect(truncated).toBe(false); + expect(text).toBe('Plan. First , open the page. Then run: See link for more.'); + }); + it('cuts at the end of a sentence within the limit, or at a word', () => { + const long = 'One short sentence. Another sentence that goes on. ' + 'word '.repeat(100); + const cut = speechText(long, 60); + expect(cut.truncated).toBe(true); + expect(cut.text).toBe('One short sentence. Another sentence that goes on.'); + const noStop = speechText('word '.repeat(100), 22); + expect(noStop.text).toBe('word word word word'); + expect(speechText(' \n', 900)).toEqual({ text: '', truncated: false }); + }); +}); + +describe('bridge: configuration for speech', () => { + const base = { HERMES_API_KEY: 'k'.repeat(16) }; + it('is off without a key, and rejects ids that are not ids', () => { + expect(loadConfig(base).tts.apiKey).toBe(''); + expect(loadConfig(base).agents[0]!.voiceId).toBe(''); + expect(() => loadConfig({ ...base, HERMEVEN_AGENT_VOICE: 'a voice/../x' })).toThrow(/HERMEVEN_AGENT_VOICE/); + expect(() => loadConfig({ ...base, HERMEVEN_ELEVENLABS_MODEL: 'bad model' })).toThrow(/HERMEVEN_ELEVENLABS_MODEL/); + expect(() => loadConfig({ ...base, HERMEVEN_ELEVENLABS_BASE_URL: 'http://example.com' })).toThrow(/https/); + const on = loadConfig({ ...base, HERMEVEN_ELEVENLABS_API_KEY: 'x', HERMEVEN_AGENT_VOICE: 'abcDEF123' }); + expect(on.tts).toMatchObject({ baseUrl: 'https://api.elevenlabs.io', model: 'eleven_flash_v2_5' }); + expect(on.limits).toMatchObject({ speechMaxChars: 900, speechPerMinute: 6 }); + }); +}); + +describe('bridge: GET /v1/speech and /v1/turns/{id}/speech', () => { + it('says which agents have a voice; nothing is offered without a key or without voices', async () => { + await harness(); + const { token } = await h.pair(); + expect((await h.api('GET', '/v1/speech', { token })).body).toEqual({ schema_version: 1, available: true, agent_ids: ['default', 'wendy'], max_chars: 900 }); + expect((await h.api('GET', '/v1/speech')).status).toBe(401); + await h.close(); + await tts.stop(); + await harness({}, false); + const second = await h.pair(); + expect((await h.api('GET', '/v1/speech', { token: second.token })).body).toEqual({ schema_version: 1, available: false, agent_ids: [], max_chars: 0 }); + const id = await answered(second.token, 'An answer.'); + expect((await speech(second.token, id)).status).toBe(404); + expect(tts.requests).toEqual([]); + }); + + it('reads a finished answer in its agent\'s voice, once, and logs no word of it', async () => { + await harness(); + const { token } = await h.pair(); + const secret = 'The safe combination is four one one one.'; + const pepper = await answered(token, `**Sure.** ${secret}`); + const wendy = await answered(token, 'Wendy speaking.', 'wendy'); + const first = await speech(token, pepper); + expect(first.status).toBe(200); + expect(first.type).toBe('audio/mpeg'); + expect(first.bytes.toString()).toBe(`FAKE-MP3:voicePepper01:${`Sure. ${secret}`.length}`); + // Asked again (a retry, a second page): the provider is not paid twice. + expect((await speech(token, pepper)).bytes.equals(first.bytes)).toBe(true); + expect((await speech(token, wendy)).bytes.toString()).toMatch(/^FAKE-MP3:voiceWendy02:/); + expect(tts.requests).toEqual([ + { voiceId: 'voicePepper01', text: `Sure. ${secret}`, model: 'eleven_flash_v2_5', outputFormat: 'mp3_44100_64' }, + { voiceId: 'voiceWendy02', text: 'Wendy speaking.', model: 'eleven_flash_v2_5', outputFormat: 'mp3_44100_64' }, + ]); + const logs = h.logs.join('\n'); + for (const fragment of ['safe combination', 'four one one', 'Wendy speaking', tts.apiKey, 'FAKE-MP3']) expect(logs).not.toContain(fragment); + const done = h.logs.filter((l) => l.includes('speech.done')).map((l) => JSON.parse(l)); + expect(done.map((d) => [d.agent_id, d.chars, d.truncated])).toEqual([['default', `Sure. ${secret}`.length, false], ['wendy', 15, false]]); + }); + + it('only for this device\'s own finished answers, and only for agents with a voice', async () => { + await harness(); + const mine = await h.pair('one'); + const other = await h.pair('two'); + const id = await answered(mine.token, 'Mine.'); + expect((await speech(other.token, id)).status).toBe(404); + expect((await speech(undefined, id)).status).toBe(401); + expect((await speech(mine.token, 'not-a-uuid')).status).toBe(404); + expect((await speech(mine.token, '0b7e1c5e-3f0a-4c56-9d3b-2f6a9f1c7e11')).status).toBe(404); + // Cody has no voice. + const cody = await answered(mine.token, 'Cody here.', 'cody'); + expect((await speech(mine.token, cody)).status).toBe(404); + // Still running: nothing to read yet. + const conversation = (await h.api('POST', '/v1/conversations', { token: mine.token, json: { schema_version: 1 } })).body.conversation_id; + h.hermes.next({ kind: 'complete', afterMs: 400, output: 'Late.' }); + const running = (await h.textTurn(mine.token, conversation, 'slow one')).body.request_id as string; + expect((await speech(mine.token, running)).status).toBe(404); + await h.waitTerminal(mine.token, running); + expect(tts.requests).toEqual([]); + }); + + it('reads no more than the limit, and no more often than the budget', async () => { + await harness({ HERMEVEN_SPEECH_MAX_CHARS: '60', HERMEVEN_SPEECH_PER_MINUTE: '2' }); + const { token } = await h.pair(); + const long = await answered(token, 'One short sentence. Another sentence that goes on. ' + 'word '.repeat(200)); + expect((await speech(token, long)).status).toBe(200); + expect(tts.requests[0]!.text).toBe('One short sentence. Another sentence that goes on.'); + expect((await speech(token, await answered(token, 'Second.'))).status).toBe(200); + const third = await answered(token, 'Third.'); + expect((await speech(token, third)).status).toBe(429); + // What was already made is still served; it costs nothing. + expect((await speech(token, long)).status).toBe(200); + expect(tts.requests).toHaveLength(2); + expect(JSON.parse(h.logs.find((l) => l.includes('speech.done'))!)).toMatchObject({ chars: 50, truncated: true }); + }); + + it('a provider failure is an error without the provider\'s words, and two requests at once make one call', async () => { + await harness(); + const { token } = await h.pair(); + const id = await answered(token, 'Private answer text.'); + tts.next({ status: 401 }); + const failed = await fetch(`${h.url}/v1/turns/${id}/speech`, { headers: { Authorization: `Bearer ${token}` } }); + expect(failed.status).toBe(500); + expect(await failed.json()).toEqual({ schema_version: 1, error: { code: 'internal', message: 'Speech could not be generated.', retryable: false } }); + expect(JSON.parse(h.logs.find((l) => l.includes('speech.failed'))!)).toMatchObject({ provider_status: 401, agent_id: 'default' }); + expect(h.logs.join('\n')).not.toContain('Private answer'); + tts.next({ delayMs: 120 }); + const [a, b] = await Promise.all([speech(token, id), speech(token, id)]); + expect([a.status, b.status]).toEqual([200, 200]); + expect(tts.requests).toHaveLength(2); // the failed one and one shared one + }); +}); + +describe('bridge: shutting down after the app gave up on a request', () => { + // Found while building speech: with Fastify's default, a connection whose client had gone + // away before the handler finished was waited for at shutdown and never ended. + for (const route of ['speech', 'transcribe'] as const) { + it(`closes promptly after an abandoned ${route} request`, async () => { + await harness(); + const { token } = await h.pair(); + const id = await answered(token, 'An answer.'); + const gaveUp = new AbortController(); + let pending: Promise; + if (route === 'speech') { + tts.next({ delayMs: 150 }); + pending = fetch(`${h.url}/v1/turns/${id}/speech`, { headers: { Authorization: `Bearer ${token}` }, signal: gaveUp.signal }); + } else { + h.stt.next({ text: 'words', delayMs: 150 }); + pending = fetch(`${h.url}/v1/transcribe?schema_version=1&locale=en-US&encoding=pcm_s16le&sample_rate=16000&channels=1`, { + method: 'POST', + body: new Uint8Array(32_000), + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/octet-stream' }, + signal: gaveUp.signal, + }); + } + await new Promise((r) => setTimeout(r, 50)); + gaveUp.abort(); + await pending.catch(() => undefined); + // Let the handler finish against the connection that has gone. + await new Promise((r) => setTimeout(r, 350)); + const outcome = await Promise.race([h.bridge.close().then(() => 'closed'), new Promise((r) => setTimeout(() => r('still waiting'), 3000))]); + expect(outcome).toBe('closed'); + }); + } +}); + +// ---------------------------------------------------------------- the app + +class FakeSpeaker implements SpeakerPort { + played: string[] = []; + stops = 0; + playing = false; + fail = false; + private finish: (() => void) | null = null; + play(audio: Uint8Array): Promise { + if (this.fail) return Promise.reject(new Error('sound is blocked (suspended)')); + this.played.push(Buffer.from(audio).toString()); + this.playing = true; + return new Promise((resolve) => { + this.finish = () => { + this.playing = false; + this.finish = null; + resolve(); + }; + }); + } + stop(): void { + this.stops += 1; + this.finish?.(); + } + /** The audio reaches its end by itself. */ + end(): void { + this.finish?.(); + } +} + +let device: FakeDevice; +let controller: Controller; +let snapshot: Snapshot; +let speaker: FakeSpeaker; +let sent: string[]; + +function makeController(extras: Partial[0]> = {}): Controller { + return new Controller({ + wake: { armTimeoutMs: 250, watchMs: 40, stallMs: 150, retryMs: 120, pauseMs: 100 }, + menu: true, + idleExit: null, + speaker, + ...extras, + device, + measure: (text, width) => measureTextWrap(text, width).lineCount, + locale: 'en-US', + pollIntervalMs: 20, + submitAttempts: 3, + submitRetryMs: 30, + micStallMs: 2000, + makeClient: (baseUrl, token) => + new BridgeClient({ + baseUrl, + token, + timeoutMs: 1500, + fetchImpl: async (input, init) => { + sent.push(`${init?.method ?? 'GET'} ${new URL(String(input)).pathname.replace(/[0-9a-f-]{36}/, ':id')}`); + return fetch(input, init); + }, + }), + onChange: (s) => { + snapshot = s; + }, + }); +} +async function until(what: string, predicate: () => boolean, timeoutMs = 4000): Promise { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for: ${what}; phase=${snapshot?.state.phase} hud=${JSON.stringify(device.frame)}`); + await new Promise((r) => setTimeout(r, 10)); + } +} +const pause = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const phase = () => snapshot.state.phase; +const speechRequests = () => sent.filter((s) => s === 'GET /v1/turns/:id/speech').length; +async function atMenu(extras: Partial[0]> = {}): Promise { + device = new FakeDevice(); + controller = makeController(extras); + await controller.start(); + await controller.pair(h.url, h.bridge.devices.createPairingCode().code, 'fake-g2'); + expect(phase()).toBe('menu'); +} +const voiceOffered = () => until('Voice on the menu', () => snapshot.voice.offered); +/** Menu -> Voice on -> Agents -> Ready. */ +async function voiceOnInAgents(): Promise { + await voiceOffered(); + device.swipeDown(); + device.swipeDown(); + device.tap(); + device.swipeUp(); + device.tap(); + expect(phase()).toBe('ready'); +} + +describe('glasses: Voice on the menu, and answers read aloud', () => { + beforeEach(() => { + sent = []; + speaker = new FakeSpeaker(); + }); + afterEach(async () => { + await controller?.stop(); + }); + + it('the menu gains a Voice switch, off at first; a tap flips it and stays on the menu', async () => { + await harness(); + await atMenu(); + await voiceOffered(); + expect(device.frame.body).toBe('Hermeven\n\n> Hands free\n Agents\n Voice: off'); + device.swipeDown(); + device.swipeDown(); + device.swipeDown(); // already on the last entry + device.tap(); + expect(phase()).toBe('menu'); + expect(device.frame.body).toBe('Hermeven\n\n Hands free\n Agents\n> Voice: on'); + expect(snapshot.voice).toEqual({ offered: true, on: true, speaking: false }); + device.tap(); + expect(device.frame.body).toBe('Hermeven\n\n Hands free\n Agents\n> Voice: off'); + expect(device.micOpens).toBe(0); + expect(speaker.played).toEqual([]); + expect(tts.requests).toEqual([]); + }); + + it('no Voice entry when the bridge has no voices, when it is an older bridge, or when the page cannot play sound', async () => { + await harness({}, false); + await atMenu(); + await until('asked', () => sent.includes('GET /v1/speech')); + await pause(50); + expect(device.frame.body).toBe('Hermeven\n\n> Hands free\n Agents'); + await controller.stop(); + await h.close(); + await tts.stop(); + await harness(); + sent = []; + await atMenu({ speaker: null }); + await pause(80); + expect(sent).not.toContain('GET /v1/speech'); + expect(device.frame.body).toBe('Hermeven\n\n> Hands free\n Agents'); + }); + + it('with Voice off nothing is fetched or played', async () => { + await harness(); + await atMenu(); + await voiceOffered(); + device.swipeDown(); + device.tap(); // Agents + controller.askText('hello'); + await until('answer', () => phase() === 'answer'); + await pause(80); + expect(speechRequests()).toBe(0); + expect(speaker.played).toEqual([]); + expect(tts.requests).toEqual([]); + }); + + it('with Voice on the answer is shown and read; the next question stops it', async () => { + await harness(); + await atMenu(); + await voiceOnInAgents(); + h.hermes.next({ kind: 'complete', output: 'The first answer.' }); + controller.askText('one'); + await until('answer', () => phase() === 'answer'); + expect(device.frame.body).toContain('The first answer.'); + await until('speaking', () => speaker.playing && snapshot.voice.speaking); + expect(speaker.played).toEqual(['FAKE-MP3:voicePepper01:17']); + // Turning the page does not interrupt. + device.swipeDown(); + expect(speaker.playing).toBe(true); + // Asking again does. + h.hermes.next({ kind: 'complete', output: 'The second answer.' }); + controller.askText('two'); + expect(speaker.playing).toBe(false); + expect(speaker.stops).toBeGreaterThan(0); + await until('second spoken', () => speaker.played.length === 2 && speaker.playing); + speaker.end(); + await until('finished', () => !snapshot.voice.speaking); + expect(phase()).toBe('answer'); + expect(tts.requests.map((r) => r.text)).toEqual(['The first answer.', 'The second answer.']); + expect(h.hermes.executions).toBe(2); + }); + + it('double tap and a tap to record stop the reading; audio that arrives late is not played', async () => { + await harness(); + await atMenu(); + await voiceOnInAgents(); + controller.askText('one'); + await until('speaking', () => speaker.playing); + device.doubleTap(); // back to Ready + expect(speaker.playing).toBe(false); + expect(phase()).toBe('ready'); + + controller.askText('two'); + await until('speaking again', () => speaker.playing); + device.tap(); // starts a recording + expect(speaker.playing).toBe(false); + device.doubleTap(); // cancel the recording + await until('rest', () => phase() !== 'listening'); + + // Slow audio, and the user has moved on before it arrives. + tts.next({ delayMs: 250 }); + const before = speaker.played.length; + controller.askText('three'); + await until('answer', () => phase() === 'answer'); + device.doubleTap(); + await pause(400); + expect(speaker.played.length).toBe(before); + expect(speaker.playing).toBe(false); + }); + + it('an agent without a voice is not read, and a failure to play leaves the answer on screen', async () => { + await harness(); + await atMenu(); + await voiceOnInAgents(); + device.swipeDown(); + device.swipeDown(); + expect(device.frame.body).toContain('Cody'); + controller.askText('for cody'); + await until('answer', () => phase() === 'answer'); + await pause(80); + expect(speechRequests()).toBe(0); + device.doubleTap(); + device.swipeDown(); // back round to Pepper + expect(device.frame.body).toContain('Pepper'); + speaker.fail = true; + h.hermes.next({ kind: 'complete', output: 'Still shown.' }); + controller.askText('for pepper'); + await until('tried', () => speechRequests() === 1); + await until('gave up', () => snapshot.log.some((e) => e.kind === 'voice' && e.detail.startsWith('not spoken'))); + expect(phase()).toBe('answer'); + expect(device.frame.body).toContain('Still shown.'); + expect(snapshot.log.map((e) => e.detail).join('\n')).not.toContain('Still shown'); + }); + + it('the app does not leave the glasses while an answer is being read; the countdown starts when it ends', async () => { + await harness(); + await atMenu({ idleExit: { ready: 5000, answer: 150, message: 5000 } }); + await voiceOnInAgents(); + controller.askText('one'); + await until('speaking', () => speaker.playing); + await pause(400); + expect(device.exits).toBe(0); + speaker.end(); + await until('left', () => device.exits === 1, 2000); + }); + + it('hands free: an answer to a spoken name is read, and the microphone still listens', async () => { + await harness(); + await atMenu(); + await voiceOffered(); + device.swipeDown(); + device.swipeDown(); + device.tap(); // Voice on + device.swipeUp(); + device.swipeUp(); + device.tap(); // Hands free + await until('listening for a name', () => device.micOpen && snapshot.state.wakeListening); + h.stt.next({ text: 'Wendy, hello' }); + h.hermes.next({ kind: 'complete', output: 'Hello from Wendy.' }); + device.speak(1); + device.silence(0.8); + await until('speaking', () => speaker.playing); + expect(speaker.played).toEqual(['FAKE-MP3:voiceWendy02:17']); + await until('listening again', () => device.micOpen && snapshot.state.wakeListening); + // No preview, as before: the only audio sent for transcription was the name check. + expect(sent.filter((s) => s === 'POST /v1/transcribe')).toEqual([]); + }); +});