@skaile/forge-voice 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # @skaile/forge-voice
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b7e7fab: New entry `@skaile/forge-voice/browser`: the headless browser engine of the platform's Talk, moved without behaviour change. `PipelineVoiceLayer` (behind the `VoiceLayer` seam) captures the microphone as 16 kHz PCM (an AudioWorklet node, `createWorkletCaptureNode`, or a ScriptProcessor), decides when an utterance is finished and sends it eagerly before that, detects barge-in by voice and by words, filters its own voice out of the transcript, re-transcribes an utterance whose language it doubts, and speaks a reply as it streams (over the relay's TTS socket, else clip by clip), with time-stretch for faster or slower speech. It reaches the relay only through the `SpeechTransport` port; `createRelayTransport({ baseUrl, paths?, scope?, getToken?, fetch?, WebSocket? })` implements it for wire protocol v1. Also exported: level calibration and envelope for visuals, audio route and headphone detection, turn latency records and their report, and the diagnostic sink (`createTalkDiagSink`, lengths, ids and reasons only).
8
+ - d535c8f: First release of `@skaile/forge-voice`, the headless voice package. The root entry has the shared speech types and pure text logic: wire protocol v1 (the frames of the speech-to-text and text-to-speech sockets and the re-transcription and clip routes), spoken languages, speech terms with the Deepgram keyterm budget (`buildKeyterms`), audio tags, stop phrases, utterance-end holds and spoken sentences. `@skaile/forge-voice/server` is a framework-free relay (`createVoiceRelay`) between the browser and Deepgram (live speech to text, re-transcription) and ElevenLabs (streamed speech, clips): the host's `authorize` hook decides who may use voice and with which keys, per-principal stream caps, and privacy it enforces itself (`mip_opt_out=true` and `enable_logging=false` set last on every provider URL, keys redacted from every frame and log line, no content logged, the WebSocket Origin check fails closed). `@skaile/forge-voice/h3` serves all four routes from one h3 / Nitro handler (`defineVoiceRelayRoutes`).
9
+ - 3c95734: `createTalk` in `@skaile/forge-voice/browser`: the turn-taking Talk session on top of the browser engine, moved from the platform without behaviour change. It decides what to send for each utterance (eagerly, folded into the running turn, restarting it with the whole request, or cutting the reply), speaks the reply as it streams, marks what the user heard of a reply they cut off, plays fillers while a slow answer is on its way, and applies spoken speed and language commands. The host connects its agent through a `ConversationPort` and may plug in a `TalkInterceptor` that speaks its own questions and claims the answers. `talkPhase` folds the session's state into one phase for a UI; `withSteerFallback` wraps a port whose agent cannot take messages into a running turn. Also exported: the filler scheduler and clip cache, the speed and speak-language helpers, and optional setters on the `VoiceLayer` seam (`setVoice`, `setPlaybackRate`, `switchToLanguage`, …).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthias Ortegro
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,289 @@
1
- # Temporary Holding Version
1
+ # @skaile/forge-voice
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Headless voice for skaile apps: speech in (Deepgram) and speech out (ElevenLabs) through a relay
4
+ that holds the provider keys on the server. The package ships state, types and protocol, never UI:
5
+ each app draws its own controls.
6
+
7
+ It has the shared text logic, the wire protocol, the server relay, the browser engine (capture,
8
+ voice activity and barge-in, echo filter, streamed playback) and, on top of the engine, the
9
+ turn-taking Talk session (`createTalk`): a full-duplex voice conversation with the host's agent.
10
+
11
+ ```bash
12
+ bun add @skaile/forge-voice
13
+ bun add ws # the relay's default upstream dialer (optional peer)
14
+ bun add h3 # only for @skaile/forge-voice/h3 (optional peer)
15
+ ```
16
+
17
+ ## Entry points
18
+
19
+ | Import | Runs on | Contents |
20
+ | --- | --- | --- |
21
+ | `@skaile/forge-voice` | browser and server | Wire protocol v1 frame types and constants; spoken languages (`STT_LANGUAGES`, `parseSttLanguage`, `ttsLanguageCode`); speech terms and the keyterm budget (`buildKeyterms`, `estimateKeytermTokens`); audio tags (`stripAudioTags`, `toElevenLabsTags`, …); stop phrases, utterance-end holds, spoken sentences, spoken-language defaults |
22
+ | `@skaile/forge-voice/browser` | browser (every DOM dependency injected or read at call time) | `createTalk` → `TalkSession`, `talkPhase`, `withSteerFallback`, the ports (`ConversationPort`, `TalkInterceptor`); fillers (`AckScheduler`, `AckClipCache`, `ToolDurations`, phrases), speed and language helpers (`talkSpeedAfter`, `TALK_SPEEDS`, `parseTalkSpeakLanguages`, …); `PipelineVoiceLayer` and the `VoiceLayer` seam; `createRelayTransport` and the `SpeechTransport` port; `RealtimeTtsStream`; the capture worklet (`createWorkletCaptureNode`); PCM, VAD and barge-in, echo filter, noise gate, level calibration and envelope, time-stretch, sticky language, eager send, speakable chunker, speech aliases, audio route, turn latency (record and report), the diag sink (`createTalkDiagSink`) |
23
+ | `@skaile/forge-voice/server` | Node ≥ 22, no framework | `createVoiceRelay(config, host)`, `relayRequest(...)`, the URL builders `buildDeepgramUrl` / `buildElevenLabsUrl`, `withoutKey`, `formatAuditLine`, socket shims (`wsRelaySocket`, `wsDialer`) |
24
+ | `@skaile/forge-voice/h3` | h3 1.x / Nitro | `defineVoiceRelayRoutes(relay)`: one event handler for all four routes |
25
+
26
+ ESM only. A CommonJS host (NestJS compiled to CommonJS) loads `dist/server/index.mjs` through Node's
27
+ `require(esm)`; the package has no top-level await. For linking a checkout, each export has a
28
+ `forge-voice-source` condition pointing at the TypeScript source.
29
+
30
+ ## Ports: what the host provides
31
+
32
+ The relay decides nothing about who may speak. Everything that is policy comes in through the host:
33
+
34
+ ```ts
35
+ import { createVoiceRelay } from '@skaile/forge-voice/server'
36
+
37
+ const relay = createVoiceRelay(
38
+ { allowedOrigins: ['https://app.example'] },
39
+ {
40
+ // Once per request, before any provider is contacted. Return a grant or a refusal.
41
+ async authorize(req) {
42
+ const user = await userFromToken(req.token) // or cookies in req.headers / req.context
43
+ if (!user) return { refuse: 401 }
44
+ if (!(await voiceAllowed(user, req.scope))) return { refuse: 403, code: 'ADD_ON_DISABLED' }
45
+ return {
46
+ principalId: user.id, // caps count per principal
47
+ deepgram: { apiKey: () => keys.deepgram(user), host: 'api.eu.deepgram.com', model: 'nova-3', defaultLanguage: 'auto' },
48
+ elevenlabs: {
49
+ apiKey: process.env.ELEVENLABS_API_KEY!,
50
+ voiceId: 'JBFqnCBsd6RMkjVDRZzb',
51
+ models: { stream: 'eleven_v4_turbo', clip: 'eleven_multilingual_v2', clipFast: 'eleven_flash_v2_5' },
52
+ },
53
+ keyterms: async language => termsFor(user, language), // already filtered by your opt-in rules
54
+ }
55
+ },
56
+ limits: { stt: { maxConcurrent: 5 } }, // optional overrides
57
+ audit: line => log.warn(line), // optional; default logger.warn(formatAuditLine(line))
58
+ },
59
+ )
60
+ ```
61
+
62
+ | Port | Shape | Notes |
63
+ | --- | --- | --- |
64
+ | `authorize(req)` | `RelayRequest → VoiceGrant \| RelayRefusal` | `req` has `kind`, `origin`, `token` (`?token=` or a bearer header), `headers`, `scope` (every query parameter, or `speak` body field, the relay does not read itself: `sessionId`, `spaceId`, …), the raw `language`, and the adapter's `context` |
65
+ | `VoiceGrant.*.apiKey` | `string` or `() => Promise<string \| null>` | A function is read only after the concurrency cap passed; `null` answers 501 |
66
+ | `VoiceGrant.deepgram.host` | bare host | No default: pass your region (`api.eu.deepgram.com`). Must match `allowedHosts.deepgram` (default `*.deepgram.com`) |
67
+ | `VoiceGrant.keyterms` | `(language) => Promise<string[]>` | Gets the stream language (`multi` = every language) or `null` for a detecting re-transcription; a rejection streams without keyterms. Build the list with `buildKeyterms` to stay inside Deepgram's token budget |
68
+ | `config.dial` | `(url, headers) => UpstreamSocket` | Default: `ws`. `wsDialer(WebSocket)` makes one from an imported `ws` (bundlers that do not trace `require`) |
69
+ | `config.fetch` | `typeof fetch` | Default: the global `fetch` |
70
+ | `RelaySocket` | `send`, `close`, `onMessage`, `onClose` | The browser socket; `wsRelaySocket(ws)` wraps a `ws` socket, the h3 entry wraps crossws peers |
71
+
72
+ ### Serving the routes
73
+
74
+ **h3 / Nitro** (`experimental: { websocket: true }` in the Nitro config):
75
+
76
+ ```ts
77
+ // server/routes/voice/[...].ts
78
+ import { defineVoiceRelayRoutes } from '@skaile/forge-voice/h3'
79
+ import { relay } from '../../utils/voice-relay'
80
+
81
+ export default defineVoiceRelayRoutes(relay)
82
+ ```
83
+
84
+ `authorize` then gets `req.context = { request, event? }`: the web `Request` (cookies, headers), and on
85
+ the HTTP routes the `H3Event`.
86
+
87
+ **Any other server** calls the relay itself. For the WebSocket routes, admit before the upgrade so a
88
+ refusal is an HTTP status, then hand the socket over:
89
+
90
+ ```ts
91
+ import { createVoiceRelay, isRelayRefusal, relayRequest, wsRelaySocket } from '@skaile/forge-voice/server'
92
+
93
+ server.on('upgrade', async (req, socket, head) => {
94
+ const url = new URL(req.url ?? '', 'http://localhost')
95
+ if (url.pathname !== '/voice/transcribe-stream') return
96
+ const admitted = await relay.admit(relayRequest({ kind: 'stt', url, headers: req.headers, context: req }))
97
+ if (isRelayRefusal(admitted)) return void socket.end(`HTTP/1.1 ${admitted.refuse} Refused\r\n\r\n`)
98
+ wss.handleUpgrade(req, socket, head, ws => relay.stt(wsRelaySocket(ws), admitted))
99
+ })
100
+ ```
101
+
102
+ Give the TTS socket server `maxPayload: TTS_MAX_CLIENT_FRAME_BYTES` (64 KiB), so an oversized
103
+ client frame is refused before it is buffered; the h3 entry closes such a frame with 1009, but only
104
+ after crossws has received it (crossws has no per-route limit). Read HTTP bodies with a size cap
105
+ (`limits.retranscribe.maxBytes`) before calling the relay, as the h3 entry does.
106
+
107
+ An admission holds a slot under the principal's cap; it is freed when the stream closes, by
108
+ `admitted.release()` if the upgrade fails, or after 10 s if it is never handed over.
109
+ `relay.retranscribe(req, pcm)` and `relay.speak(req, body)` answer the HTTP routes with
110
+ `{ ok: true, value }` or `{ ok: false, status, message, code?, retryAfterS? }`.
111
+
112
+ ## Browser engine
113
+
114
+ `PipelineVoiceLayer` runs one side of a voice conversation: one 16 kHz PCM capture feeds the speech-to-text
115
+ socket, a pre-open buffer and a re-transcription ring; replies play through WebAudio, so playback end,
116
+ output latency and the output level share the clock of the user's speech. It decides when an utterance
117
+ is finished (and sends it eagerly before that), detects barge-in by voice and by words, filters its own
118
+ voice out of the transcript, and speaks a reply as it streams. It knows no URLs, scopes or credentials:
119
+ it reaches the relay through a `SpeechTransport`.
120
+
121
+ ```ts
122
+ import { createRelayTransport, createWorkletCaptureNode, PipelineVoiceLayer } from '@skaile/forge-voice/browser'
123
+
124
+ const transport = createRelayTransport({
125
+ baseUrl: 'https://api.example.com', // HTTP routes are appended; sockets go to this host
126
+ scope: () => ({ spaceId }), // opaque, on every request
127
+ getToken: async () => auth.token(), // bearer in ?token= on the sockets; omit for a cookie
128
+ fetch: (url, init) => authedFetch(url, init), // optional, default: global fetch
129
+ })
130
+
131
+ const layer = new PipelineVoiceLayer(
132
+ {
133
+ transport,
134
+ getUserMedia: c => navigator.mediaDevices.getUserMedia(c),
135
+ createAudioContext: () => new AudioContext(),
136
+ createCaptureNode: createWorkletCaptureNode, // falls back to a ScriptProcessor without it
137
+ storage: localStorage, // the device's home language; optional
138
+ diag: (event, fields) => sink.log(event, fields), // lengths, ids and reasons only
139
+ },
140
+ { voiceId, speakLanguages: ['de', 'en'], deviceLocale: navigator.language },
141
+ )
142
+
143
+ layer.on('utterance', u => u.final && !u.hush && agent.send(u.text))
144
+ layer.on('bargeIn', b => agent.noteHeard(b.turnId, b.heardChars))
145
+ await layer.start()
146
+ layer.speak(turnId, replyDeltas) // AsyncIterable<string> or a whole string
147
+ ```
148
+
149
+ | Port | Shape | Notes |
150
+ | --- | --- | --- |
151
+ | `SpeechTransport` | `socketCredential()`, `openStt(query, credential)`, `openTtsStream(query, credential)`, `retranscribe(pcm, query, signal)`, `speakClip(body, signal?)` | Sockets open synchronously after the credential is fetched; the HTTP calls return the raw `Response`. `createRelayTransport` speaks wire protocol v1; `paths` moves the routes |
152
+ | `PipelineVoiceDeps` | `getUserMedia`, `createAudioContext`, `transport`, `createCaptureNode?`, `timers?`, `createId?`, `storage?`, `storageKeys?`, `diag?`, `nowMs?` | Fakes for all of them drive the tests |
153
+ | `PipelineVoiceOptions` | `voiceId`, `pinnedLanguage`, `speakLanguages`, `audioMode`, `headphones`, `pushToTalk`, `speakerHush`, `realtimeTts`, `playbackRate`, `speechTerms`, … | Changed later through the layer's setters (`setVoice`, `setPlaybackRate`, `setSpeakLanguages`, …) |
154
+ | Storage keys | `LanguageHome` (`skaile.talk.language-*.v1`), level peaks (`skaile.talk.level-peaks.v1`), tool durations (`skaile.talk.toolDurations`, through `createTalk`'s `storage`); the host's own helpers: default speed (`skaile:talk:default-speed`), speak languages (`skaile:talk:speak-languages`), headphones toggle (host key) | The defaults keep what devices stored before the move |
155
+
156
+ The engine emits `utterance`, `partial`, `bargeIn`, `dropped`, `state`, `language` and `replyStage`.
157
+ Levels for a visual: `layer.levels.mic()` / `.output()` (raw RMS) and `TalkLevelCalibration` (0..1 per
158
+ device and voice).
159
+
160
+ ## Talk session
161
+
162
+ `createTalk` runs a voice conversation with the host's agent on top of the engine. It decides what
163
+ to send for each utterance: an eager send before the user finished, words folded into the running
164
+ turn, the whole request again when the user went on before any of the answer was heard, or a new
165
+ message that cuts the reply. It speaks the reply as it streams (holding back what looks like a note
166
+ the agent wrote to itself between tool calls), marks what the user heard of a reply they cut off,
167
+ plays a short filler while a slow answer is on its way, and applies spoken speed and language
168
+ commands ("faster", "sprich Englisch"). It ships state and events; the host draws the orb, captions
169
+ and buttons.
170
+
171
+ ```ts
172
+ import { createRelayTransport, createTalk, talkPhase, withSteerFallback } from '@skaile/forge-voice/browser'
173
+
174
+ const talk = createTalk({
175
+ conversation: withSteerFallback(myConversationPort), // drop the wrapper if your agent can steer
176
+ speech: createRelayTransport({ baseUrl: '/api', scope: () => ({ spaceId }) }),
177
+ storage: localStorage, // home language, tool durations; optional
178
+ voice: { voiceId, speakLanguages: ['de', 'en'], deviceLocale: navigator.language },
179
+ audio: { pauseInBackground: isIphone },
180
+ diag: (event, fields) => sink.log(event, fields), // lengths, ids and reasons only
181
+ })
182
+
183
+ const off = talk.subscribe(() => render(talkPhase(talk.state), talk.state.layer.speakingText))
184
+ talk.on('speed', (_command, rate) => saveSpeed(rate))
185
+ await talk.start() // rejects when the mic cannot open
186
+ // later: talk.tapInterrupt(), talk.muteMic(), talk.resume(), talk.set({ voiceId }), talk.stop(), talk.dispose()
187
+ ```
188
+
189
+ ### The conversation port
190
+
191
+ The session reaches the agent only through a `ConversationPort` the host implements:
192
+
193
+ | Member | Shape | Notes |
194
+ | --- | --- | --- |
195
+ | `send(message)` | `TalkOutgoing → Promise<string \| undefined>` | `{ text, utteranceId, final, language?, continuation?, steer? }`. Resolves with the host's prompt id, if it has one. `final: false` is an eager send; a later send with the same `utteranceId` supersedes it. `steer` is set while a turn runs: `now` replaces the turn, `fold` is read at its next step. `continuation: 'restart'` says the message repeats and replaces a cut-off start, `fold` that it goes on with the previous one. A rejection is retried once unless `describeSendError` calls it refused |
196
+ | `cancelTurn()` | `void` | Ends the running turn, keeping what streamed (a hush, a tap that is not followed by words) |
197
+ | `markInterrupted(mark)` | `TalkMarkInterrupted → Promise<{ marked }>` | What the user heard of a cut reply (`lastHeardSentence`, `heardChars`, or `replyStart` when nothing was heard), so the agent's next turn knows. `marked: false` is sent again as `phase: 'settle'` once the turn ended. A host that stores nothing resolves `{ marked: true }` |
198
+ | `describeSendError?(error)` | `→ { code, refused }` | The code goes to the diagnostic log; a refused send is not retried |
199
+ | `subscribe(listener)` | `ConversationEvent` | `turn{running}`, then the reply as `text{text}` (the text so far) or `delta{delta, segmentStart?}`, `toolStarted{name?, subagent?}`, `toolEnded{name?, subagent?}`, `turnEnded{outcome?}`. Emit synchronously, in order |
200
+
201
+ Name each tool in `toolStarted` / `toolEnded`: the fillers learn per name which tools return fast,
202
+ and an end without a name is ignored.
203
+
204
+ An agent that cannot take a message into a running turn: wrap the port in `withSteerFallback(port)`.
205
+ A `now` send then cancels the turn, waits for it to end (5 s at most) and goes out as a new message;
206
+ a `fold` send is held until the turn ends. Held words are sent once: a `now` message carries those it
207
+ does not already repeat, and `cancelTurn` (a hush, a tap) drops them with the turn.
208
+
209
+ ### Options and controls
210
+
211
+ | Option | Notes |
212
+ | --- | --- |
213
+ | `speech` | A `SpeechTransport` (the session builds a `PipelineVoiceLayer` on the browser's mic and WebAudio), or `{ layer, transport? }` for a ready `VoiceLayer` (native, tests); `transport` then only serves the filler clips |
214
+ | `interceptor` | A host extension (below) |
215
+ | `voice` | `voiceId`, `speed`, `speakLanguages`, `pinnedLanguage`, `conversationLocale`, `lastUtteranceLanguage`, `deviceLocale`, `speechTerms` |
216
+ | `audio` | `mode`, `headphones`, `pushToTalk`, `speakerHush`, `realtimeTts`, `pauseInBackground` |
217
+ | `fillers` | `{ enabled?, phrases?, clips?, durations? }`, `false`, or your own `TalkFillers`. Clips are spoken once through `transport.speakClip` and cached (`clips` shares a cache across sessions); built-in phrases in eight languages |
218
+ | `commands` | `{ speed?, language? }`, both on by default; a command is never sent |
219
+ | `storage`, `storageKeys` | The device's home language and tool durations; nothing is stored without `storage` |
220
+ | `browser` | `getUserMedia`, `createAudioContext`, `createCaptureNode`, `timers`, `createId`, `now`, `nowMs`, `random` |
221
+
222
+ `TalkSession`: `state` (`TalkSnapshot`: `active`, `layer` with `listening` / `speaking` / `speakingText`
223
+ / `error` / `micMuted` / …, `partial`, `unsupportedLanguage`, `turnRunning`, `promptIds`, `paused`),
224
+ `subscribe`, `on(event)` for `utterance`, `bargeIn`, `dropped`, `language`, `replyStage`, `speed`,
225
+ `languageCommand`, `turnLatency`; `start`, `stop`, `dispose`, `muteMic`, `resume`, `pageHidden`,
226
+ `pageVisible`, `tapInterrupt`, `pressTalk`, `releaseTalk`, `expectReplyToTypedSend(promptIdPromise)`
227
+ (a message typed while Talk runs: its reply is spoken), `set({ voiceId, speed, speakLanguages, language,
228
+ languageContext, audioMode, headphones, pushToTalk, speechTerms })`, `speed`, `levels`, `layer`.
229
+ `talkPhase(state)` folds the snapshot into `idle`, `listening`, `userSpeaking`, `thinking`, `speaking`,
230
+ `paused` or `error`.
231
+
232
+ ### Host extensions
233
+
234
+ A `TalkInterceptor` lets the host speak its own questions in the conversation and take the answers
235
+ before they reach the agent (an approval flow, an offer). It gets a `TalkInterceptorApi` on
236
+ `attach`: `ask(turnId, text)` speaks a question in one of Talk's turns (no filler follows it, and an
237
+ answer never continues the request), `say(id, text)` speaks a sentence under its own id, `turns`
238
+ (a frozen array of read-only views, read afresh each time; each view is live and stays the same
239
+ object for its turn), `state`, `spokenLanguage`, `lastSpokenAtMs`,
240
+ `interruptedTurnId`, `suspended`, `now()` and `changed()` (host state next to the snapshot changed).
241
+ As each utterance ends, `utteranceEnded(u)` may return a `TalkHostQuestion`: while one is open eager
242
+ sends wait, and its `claim(text)` takes the final words or lets them go to the agent. `ownsTurn(id)`
243
+ marks speak ids that are the host's own, so cutting them marks nothing.
244
+
245
+ ## Wire protocol v1
246
+
247
+ Frozen: a change to a frame is a `### Breaking` changeset and a new `VOICE_WIRE_PROTOCOL_VERSION`.
248
+ Optional fields are additive. The types live in the root entry, so a browser transport and the relay
249
+ share them. Default paths: `VOICE_RELAY_DEFAULT_PATHS`.
250
+
251
+ | Route | Client → relay | Relay → client |
252
+ | --- | --- | --- |
253
+ | `WS /voice/transcribe-stream` `?language&encoding=linear16&<scope>&token?` | binary audio (16 kHz PCM with `linear16`, else a container such as webm/opus); `{type:'stop'}` | `ready`, `speech_started{timestamp?}`, `transcript{transcript,is_final,speech_final,start?,duration?,wordsStart?,wordsEnd?,confidence?,language?}`, `expiring{inMs}`, `error{error}`, `closed`; close 1000 `max-duration` / `idle-timeout`, 1011 `upstream-error` |
254
+ | `WS /voice/speak-stream` `?voiceId&languageCode&<scope>&token?` | `{type:'text',text,flush?}`, `{type:'end'}` (each ≤ 64 KiB) | `ready{sampleRate}`, then per audio piece an optional `alignment{text}` followed by ONE binary PCM s16le frame, `done`, `error{error}`; close 1000 `done`, 1011, 1008 `text-limit` |
255
+ | `POST /voice/retranscribe` `?language&<scope>`, body `audio/l16; rate=16000` ≤ 960,000 B | | `{transcript, language, languageConfidence, confidence}`; 400 / 401 / 403 / 413 / 415 / 429 / 501 / 502 / 504 |
256
+ | `POST /voice/speak` JSON `{text, voiceId?, languageCode?, expressive?, lowLatency?, <scope>}` | | `audio/mpeg` |
257
+
258
+ Defaults of the caps (`DEFAULT_RELAY_LIMITS`, each overridable through `host.limits`): STT 5 streams
259
+ per principal, 10 min with an `expiring` warning 30 s before, 90 s idle; TTS 3 streams, 5 min, 2 min
260
+ idle, a provider keep-alive every 10 s, 10,000 characters; re-transcription 960,000 bytes and 15 s;
261
+ clips 10,000 characters, `expressive` up to 200. The caps are in memory, per process.
262
+
263
+ ## Privacy contract
264
+
265
+ What the package enforces itself, pinned by its tests, and no option turns off:
266
+
267
+ - **Provider retention off.** Every Deepgram URL carries `mip_opt_out=true` and every ElevenLabs URL
268
+ `enable_logging=false`, set last by the only URL builders, so a caller-supplied value never wins.
269
+ (ElevenLabs ignores the flag below its enterprise plans; purging its history is the host's job.)
270
+ - **Keys stay server-side.** Keys travel in request headers only, never in a URL; a key is redacted
271
+ (`[redacted]`) from every frame relayed and every line logged, and a dial that fails with the key in
272
+ its error answers fixed text.
273
+ - **No content in logs.** No audio, transcript, reply text or keyterm is logged; the audit lines carry
274
+ ids, sizes, counts and the privacy values read back from the URL actually sent
275
+ (`VOICE_PROVIDER_PRIVACY: Deepgram stream opened: user=… host=… model=… language=… mip_opt_out=true keyterms=3`).
276
+ Provider error bodies that may echo the request are relayed redacted (Deepgram) or not at all (ElevenLabs).
277
+ - **Closed lists for anything in a URL.** Languages come from `STT_LANGUAGES`, the encoding from
278
+ `parseSttEncoding`, voice ids match `^[A-Za-z0-9]+$`; the Deepgram host must be a bare host on the
279
+ allowlist.
280
+ - **Fail closed.** The WebSocket routes refuse a missing or unlisted `Origin`; `authorize` runs before
281
+ any provider contact and gets nothing from the relay. The relay sets no cookies.
282
+
283
+ - **HTTP routes have no Origin check** (they are meant for a bearer token). A host whose `authorize`
284
+ trusts cookies relies on the h3 entry taking `speak` as `application/json` only and `retranscribe`
285
+ as `audio/l16` only, which a cross-site form cannot send without a CORS preflight; keep that
286
+ in any other adapter.
287
+
288
+ What it leaves to the host: who may use voice (add-ons, opt-ins, data zones), which keys pay, rate
289
+ limits beyond the stream caps, and storing nothing it receives.