@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 +9 -0
- package/LICENSE +21 -0
- package/README.md +288 -2
- package/dist/browser/index.d.mts +2102 -0
- package/dist/browser/index.mjs +5808 -0
- package/dist/browser/index.mjs.map +1 -0
- package/dist/h3/index.d.mts +26 -0
- package/dist/h3/index.mjs +234 -0
- package/dist/h3/index.mjs.map +1 -0
- package/dist/index.d.mts +138 -0
- package/dist/index.mjs +1 -0
- package/dist/relay.d.mts +345 -0
- package/dist/relay.mjs +1194 -0
- package/dist/relay.mjs.map +1 -0
- package/dist/server/index.d.mts +57 -0
- package/dist/server/index.mjs +1 -0
- package/dist/speech-terms.d.mts +237 -0
- package/dist/wire.mjs +792 -0
- package/dist/wire.mjs.map +1 -0
- package/package.json +90 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"relay.mjs","names":[],"sources":["../src/server/audit.ts","../src/server/deepgram-request.ts","../src/server/elevenlabs-request.ts","../src/server/key-redact.ts","../src/shared/audio-tags.ts","../src/shared/voice-languages.ts","../src/shared/wire.ts","../src/server/retranscribe.ts","../src/server/sockets.ts","../src/server/speak.ts","../src/server/runtime.ts","../src/server/stt.ts","../src/server/tts.ts","../src/server/relay.ts"],"sourcesContent":["import type { RelayAuditLine } from './types'\n\nconst PREFIX = 'VOICE_PROVIDER_PRIVACY:'\n\n/**\n * The audit line as one log string, e.g. `VOICE_PROVIDER_PRIVACY: Deepgram stream opened: user=u1\n * host=api.eu.deepgram.com model=nova-3 language=de mip_opt_out=true keyterms=3`. The privacy values\n * are read back from the URL actually sent. No audio, transcript, text, keyterm or key ever appears.\n */\nexport function formatAuditLine(line: RelayAuditLine): string {\n switch (line.event) {\n case 'deepgram-stream-opened':\n return `${PREFIX} Deepgram stream opened: user=${line.principalId} host=${line.host} model=${line.model} language=${line.language} mip_opt_out=${line.mipOptOut} keyterms=${line.keyterms}`\n case 'deepgram-retranscription-requested':\n return `${PREFIX} Deepgram re-transcription requested: user=${line.principalId} host=${line.host} model=${line.model} bytes=${line.bytes} mip_opt_out=${line.mipOptOut} keyterms=${line.keyterms}`\n case 'elevenlabs-stream-opened':\n return `${PREFIX} ElevenLabs stream opened: user=${line.principalId} voice=${line.voiceId} model=${line.model} enable_logging=${line.enableLogging}`\n case 'elevenlabs-stream-closed':\n return `${PREFIX} ElevenLabs stream closed: user=${line.principalId} chars=${line.chars}`\n case 'elevenlabs-speech-requested':\n return `${PREFIX} ElevenLabs speech requested: voice=${line.voiceId} model=${line.model} chars=${line.chars} enable_logging=${line.enableLogging}`\n }\n}\n","/**\n * The one place a Deepgram request URL is built. Deepgram keeps audio and transcripts in memory\n * only for requests that opt out of its Model Improvement Program (`mip_opt_out=true`), so the\n * opt-out is set here, last, and cannot be omitted or overridden by a caller.\n */\n\n/**\n * A bare Deepgram API host (`api.deepgram.com`, `api.eu.deepgram.com`): no scheme, port or path,\n * so the key in the request header goes to Deepgram and nowhere else.\n */\nexport const DEEPGRAM_HOST_PATTERN = /^([a-z0-9-]+\\.)+deepgram\\.com$/\n\nconst DEEPGRAM_MIP_OPT_OUT = 'true'\n\nexport interface DeepgramUrlOptions {\n /** The hosts a request may go to; default `DEEPGRAM_HOST_PATTERN`. Matched against the whole host. */\n hostPattern?: RegExp\n}\n\n/**\n * Whether `host` is a bare host (no scheme, port, path or fragment, which could redirect the key) that\n * the pattern matches as a whole. An unanchored or `g`-flagged pattern cannot widen this.\n */\nexport function isAllowedDeepgramHost(host: string, hostPattern: RegExp = DEEPGRAM_HOST_PATTERN): boolean {\n if (!/^[a-z0-9.-]+$/.test(host)) return false\n const match = new RegExp(hostPattern.source, hostPattern.flags.replace(/[gy]/g, '')).exec(host)\n return match !== null && match.index === 0 && match[0] === host\n}\n\n/**\n * A list value repeats the parameter (`keyterm=a&keyterm=b`), as Deepgram reads it; each value is\n * percent-encoded by `URLSearchParams`, so a term can never add a parameter of its own. Throws for a\n * host that does not match the pattern.\n */\nexport function buildDeepgramUrl(\n host: string,\n protocol: 'https' | 'wss',\n path: `/v1/${string}`,\n params: Record<string, string | readonly string[]>,\n { hostPattern = DEEPGRAM_HOST_PATTERN }: DeepgramUrlOptions = {},\n): URL {\n if (!isAllowedDeepgramHost(host, hostPattern)) {\n throw new Error(`Not a Deepgram API host: ${host}`)\n }\n const url = new URL(`${protocol}://${host}${path}`)\n for (const [key, value] of Object.entries(params)) {\n if (typeof value === 'string') {\n url.searchParams.set(key, value)\n } else {\n url.searchParams.delete(key)\n for (const item of value as readonly string[]) url.searchParams.append(key, item)\n }\n }\n // Set last so a caller-supplied `mip_opt_out` can never win.\n url.searchParams.set('mip_opt_out', DEEPGRAM_MIP_OPT_OUT)\n return url\n}\n","/**\n * The one place an ElevenLabs request URL is built. `enable_logging=false` is ElevenLabs'\n * per-request Zero Retention Mode: the text and audio of the request are not stored. It is set\n * here, last, and cannot be omitted or overridden by a caller, the same way `buildDeepgramUrl`\n * forces Deepgram's opt-out.\n */\nexport const ELEVENLABS_HOST = 'api.elevenlabs.io'\n\nconst ELEVENLABS_ENABLE_LOGGING = 'false'\n\n/** `wss` for the streaming-input sockets (the text-to-dialogue stream), else `https`. */\nexport function buildElevenLabsUrl(\n path: `/v1/${string}`,\n params: Record<string, string> = {},\n { protocol = 'https' }: { protocol?: 'https' | 'wss' } = {},\n): URL {\n const url = new URL(`${protocol}://${ELEVENLABS_HOST}${path}`)\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, value)\n }\n // Set last so a caller-supplied `enable_logging` can never win.\n url.searchParams.set('enable_logging', ELEVENLABS_ENABLE_LOGGING)\n return url\n}\n","/** A key shorter than this is not redacted: it would blank ordinary words out of a message. */\nconst MIN_REDACTED_KEY_LENGTH = 8\n\n/** A provider's text with the key it was called with removed, for a reply or a log line. */\nexport function withoutKey(text: string, key: string): string {\n return key.length >= MIN_REDACTED_KEY_LENGTH ? text.split(key).join('[redacted]') : text\n}\n","/**\n * Audio tags in a spoken reply: `[[whispers]]`, `[[laughs]]`. The reply-format contract between an\n * agent that writes tags and the speech model that performs them. The stored text keeps them; what a\n * chat shows of a voice reply, what Talk counts as heard (`heardChars`) and what a server reuses of one\n * (history, search, recaps) is the text without them. Only voice replies have tags: anywhere else\n * `[[...]]` is code or a wiki link. Browser and server import the same functions, so both count\n * offsets the same way; keep this file free of runtime-specific imports.\n */\n\n/** `[[` + letters, spaces, commas, hyphens or apostrophes (at most 40) + `]]`. */\nconst TAG_SOURCE = \"\\\\[\\\\[[\\\\p{L} ,'-]{1,40}\\\\]\\\\]\"\nconst anyDoubleBracket = /\\[\\[[^\\]\\n]*\\]\\]/gu\n// A tag still streaming in: `[[`, up to 40 tag characters and at most the first `]`.\nconst pendingTail = /\\[\\[[\\p{L} ,'-]{0,40}\\]?$/u\n\n/** The text without its audio tags. */\nexport function stripAudioTags(text: string): string {\n return text.replace(new RegExp(TAG_SOURCE, 'gu'), '')\n}\n\n/**\n * Where `rawOffset` in the stored text lands in the stripped text. An offset inside a tag lands\n * where the tag was.\n */\nexport function strippedOffset(raw: string, rawOffset: number): number {\n const end = Math.max(0, Math.min(rawOffset, raw.length))\n let removed = 0\n for (const match of raw.matchAll(new RegExp(TAG_SOURCE, 'gu'))) {\n const start = match.index ?? 0\n if (start >= end) {\n break\n }\n removed += Math.min(match[0].length, end - start)\n }\n return end - removed\n}\n\n/**\n * The text without any double-bracket tag, malformed ones too (`[[laughs!]]`): what Talk speaks\n * on the fallback model or shows as a caption, never a `[[`. Not for offsets: `stripAudioTags`.\n */\nexport function stripAnyAudioTags(text: string): string {\n return text.replace(anyDoubleBracket, '')\n}\n\n/**\n * Where a trailing, not yet closed tag starts (`[[laug`, `[[laughs]`, or a lone final `[`), so\n * Talk holds it back until it closes instead of speaking or cutting half of it; -1 otherwise.\n */\nexport function pendingTagStart(text: string): number {\n const match = pendingTail.exec(text)\n if (match) {\n return match.index\n }\n return text.endsWith('[') ? text.length - 1 : -1\n}\n\n/**\n * The ElevenLabs v4 form: `[[x]]` becomes `[x]`; a malformed double-bracket tag is dropped.\n */\nexport function toElevenLabsTags(text: string): string {\n const valid = new RegExp(`^${TAG_SOURCE}$`, 'u')\n return text.replace(anyDoubleBracket, tag => (valid.test(tag) ? tag.slice(1, -1) : ''))\n}\n\n// Fenced code (to its closing fence or the end) and inline code spans: `[[x]]` there is code, not a tag.\nconst codeSpan = /```[\\s\\S]*?(?:```|$)|`[^`\\n]+`/g\n\n/** The [start, end) ranges of fenced code blocks and inline code spans in `text`. */\nfunction codeRanges(text: string): [number, number][] {\n return [...text.matchAll(codeSpan)].map(m => [m.index, m.index + m[0].length])\n}\n\nfunction inCode(ranges: readonly [number, number][], at: number): boolean {\n return ranges.some(([start, end]) => at >= start && at < end)\n}\n\n/**\n * What Chat shows of a voice reply: its valid tags removed, except inside code (a fenced block or\n * an inline span), where `[[x]]` is the code's own (bash `[[ -d x ]]`, a wiki link).\n */\nexport function stripAudioTagsForDisplay(text: string): string {\n if (!text.includes('[[')) {\n return text\n }\n const ranges = codeRanges(text)\n return text.replace(new RegExp(TAG_SOURCE, 'gu'), (tag: string, at: number) => (inCode(ranges, at) ? tag : ''))\n}\n\n/** The [start, end) ranges of the audio tags in `raw`. */\nexport function audioTagRanges(raw: string): [number, number][] {\n return [...raw.matchAll(new RegExp(TAG_SOURCE, 'gu'))].map(m => [m.index ?? 0, (m.index ?? 0) + m[0].length])\n}\n\n/**\n * A voice reply's text for reuse as plain text (history, search, recaps, read-aloud): every\n * `[[...]]` removed, malformed ones too since Flash reads them aloud, but none inside code. Text\n * without one comes back unchanged; a removed tag takes one adjacent space, nothing else is touched.\n * Callers outside `/voice/speak` apply it to voice replies only. `inCodeToo`: code as well, for\n * `/voice/speak`, where the fast model would read a tag aloud wherever it is.\n * Not for offsets: `stripAudioTags`.\n */\nexport function stripAudioTagsForText(text: string, { inCodeToo = false }: { inCodeToo?: boolean } = {}): string {\n if (!text.includes('[[')) {\n return text\n }\n const ranges = inCodeToo ? [] : codeRanges(text)\n let out = ''\n let pos = 0\n for (const match of text.matchAll(anyDoubleBracket)) {\n if (inCode(ranges, match.index)) {\n continue\n }\n out += text.slice(pos, match.index)\n let end = match.index + match[0].length\n const next = text[end]\n if (next === ' ' && (out === '' || /\\s$/.test(out))) {\n end += 1\n } else if ((next === undefined || !/[\\p{L}\\p{N}]/u.test(next)) && out.endsWith(' ')) {\n out = out.slice(0, -1)\n }\n pos = end\n }\n return out + text.slice(pos)\n}\n","/**\n * Spoken languages a session may pin for speech-to-text, as Deepgram nova-3 codes.\n * `multi` is nova-3's multilingual mode, which a relay default language of `auto` maps to.\n * A closed list: the value is interpolated into the upstream URL.\n */\nexport const STT_LANGUAGES = [\n 'multi',\n 'en',\n 'en-US',\n 'en-GB',\n 'de',\n 'de-CH',\n 'fr',\n 'es',\n 'it',\n 'nl',\n 'pt',\n 'pt-BR',\n 'pl',\n 'sv',\n 'da',\n 'no',\n 'fi',\n 'tr',\n 'ru',\n 'uk',\n 'ja',\n 'ko',\n 'hi',\n] as const\n\nexport type SttLanguage = (typeof STT_LANGUAGES)[number]\n\nconst STT_LANGUAGE_SET: ReadonlySet<string> = new Set(STT_LANGUAGES)\n\n/** The requested language when it is on the list, else null (the caller falls back to the deployment default). */\nexport function parseSttLanguage(value: unknown): SttLanguage | null {\n return typeof value === 'string' && STT_LANGUAGE_SET.has(value) ? (value as SttLanguage) : null\n}\n\n/**\n * The ElevenLabs `language_code` for a pinned STT language: the bare ISO 639-1 part,\n * or null for `multi` / anything malformed.\n */\nexport function ttsLanguageCode(value: unknown): string | null {\n const lang = parseSttLanguage(typeof value === 'string' ? value.trim() : value)\n if (!lang || lang === 'multi') {\n return null\n }\n return lang.slice(0, 2)\n}\n\n/**\n * ElevenLabs refuses `language_code` on models that do not enforce a language; today\n * that is everything except the v2.5 Flash and Turbo models and the v3 / v4 family\n * (which Talk's text-to-dialogue stream uses).\n */\nexport function modelAcceptsLanguageCode(modelId: string): boolean {\n return /^eleven_(flash|turbo)_v2_5$/.test(modelId) || /^eleven_v[34](_|$)/.test(modelId)\n}\n","/**\n * Wire protocol v1 between a browser transport and a voice relay: two WebSockets (speech to text,\n * streamed text to speech) and two HTTP routes (re-transcription of one utterance, one spoken clip).\n * Frozen: a change to a frame is a breaking change and a new protocol version. Fields marked optional\n * are additive and old clients ignore them.\n */\n\n/** The version of the frames below. */\nexport const VOICE_WIRE_PROTOCOL_VERSION = 1\n\n/** Where the relay routes live by default; a host may mount them elsewhere. */\nexport const VOICE_RELAY_DEFAULT_PATHS = {\n stt: '/voice/transcribe-stream',\n tts: '/voice/speak-stream',\n retranscribe: '/voice/retranscribe',\n speak: '/voice/speak',\n} as const\n\nexport type VoiceRelayRoute = keyof typeof VOICE_RELAY_DEFAULT_PATHS\n\n/**\n * Query parameters the relay reads itself. Every other query parameter (or, for `speak`, every other\n * body field) is the host's opaque scope (`sessionId`, `organizationId`, `spaceId`, …).\n * `token` carries a bearer, since a browser cannot set headers on `new WebSocket()`.\n */\nexport const RELAY_QUERY_PARAMS = ['token', 'language', 'encoding', 'voiceId', 'languageCode'] as const\n\n// ── Speech to text: WS `stt` ────────────────────────────────────────────────\n\n/**\n * `linear16`: raw 16 kHz mono PCM (Talk), so one capture feeds the socket, a pre-open buffer and the\n * re-transcription ring. Absent: the provider sniffs the container (MediaRecorder webm/opus).\n */\nexport type SttEncoding = 'linear16'\n\n/** Closed list: the value selects upstream URL params. Anything else means the container format. */\nexport function parseSttEncoding(value: unknown): SttEncoding | null {\n return value === 'linear16' ? 'linear16' : null\n}\n\n/** The sample rate of `linear16` audio, on the STT socket and the re-transcription body alike. */\nexport const LINEAR16_SAMPLE_RATE = 16_000\n\n/** Client → relay text frame; every binary frame is audio. Any other text frame is dropped. */\nexport type SttClientFrame = { type: 'stop' }\n\nexport type SttServerFrame =\n /** The provider stream is open; audio sent before this is dropped. */\n | { type: 'ready' }\n /** The provider heard speech start; `timestamp` is its stream time in seconds. */\n | { type: 'speech_started'; timestamp?: number }\n | {\n type: 'transcript'\n transcript: string\n is_final: boolean\n speech_final: boolean\n /** Window start and length in stream seconds. */\n start?: number\n duration?: number\n /** First word's start and last word's end (the window runs on through trailing silence). */\n wordsStart?: number\n wordsEnd?: number\n /** Mean word confidence. */\n confidence?: number\n /** The detected language in `multi` mode, else the stream's language. */\n language?: string\n }\n /** The stream reaches its duration cap in `inMs`; a client that keeps listening opens a new one now. */\n | { type: 'expiring'; inMs: number }\n | { type: 'error'; error: string }\n /** The provider closed its stream. */\n | { type: 'closed' }\n\nexport type SttCloseReason = 'max-duration' | 'idle-timeout' | 'upstream-error'\n\n// ── Text to speech: WS `tts` ────────────────────────────────────────────────\n\n/** Every client frame is a short JSON text frame of at most this many bytes; binary frames are ignored. */\nexport const TTS_MAX_CLIENT_FRAME_BYTES = 64 * 1024\n\n/** The PCM the TTS stream answers with: s16le, mono, this rate. */\nexport const TTS_STREAM_SAMPLE_RATE = 24_000\n\nexport type TtsClientFrame =\n /** Reply text as it is written; `flush` asks the provider to speak what it holds now. */\n | { type: 'text'; text: string; flush?: boolean }\n /** No more text: the stream ends after the last audio. */\n | { type: 'end' }\n\n/**\n * Relay → client. Per audio piece an optional `alignment` (the piece's characters) is followed by\n * exactly ONE binary frame of PCM; a client pairs each binary frame with the alignment before it.\n */\nexport type TtsServerFrame =\n | { type: 'ready'; sampleRate: number }\n | { type: 'alignment'; text: string }\n | { type: 'done' }\n /** Only a status or error code, never provider text. */\n | { type: 'error'; error: string }\n\nexport type TtsCloseReason = 'done' | 'max-duration' | 'idle-timeout' | 'upstream-error' | 'text-limit'\n\n// ── Close codes, both sockets ───────────────────────────────────────────────\n\nexport const RELAY_CLOSE_CODES = {\n /** `done`, `max-duration`, `idle-timeout`. */\n normal: 1000,\n /** `text-limit` (TTS). */\n policy: 1008,\n /** `upstream-error`. */\n upstreamError: 1011,\n} as const\n\n// ── Re-transcription: POST `retranscribe` ───────────────────────────────────\n\n/** The body's content type: raw `linear16` at 16 kHz. */\nexport const RETRANSCRIBE_CONTENT_TYPE = 'audio/l16'\n\n/** 30 s of 16 kHz mono linear16: the client's utterance ring holds no more. Above it: 413. */\nexport const RETRANSCRIBE_MAX_BYTES = 960_000\n\n/** The 200 answer of `POST retranscribe`; errors are 400/401/403/413/415/429/501/502/504 with `{ message }`. */\nexport interface RetranscribeResult {\n transcript: string\n /** The pinned language, else the detected one. */\n language: string | null\n /** How sure the provider is of the detected language; null with a pinned language. */\n languageConfidence: number | null\n /** How sure the provider is of the words, so a client can compare two languages' transcripts. */\n confidence: number | null\n}\n\n// ── One spoken clip: POST `speak` ───────────────────────────────────────────\n\n/** The JSON body of `POST speak` (answer: `audio/mpeg`). Other fields are the host's scope. */\nexport interface SpeakRequestBody {\n text: string\n voiceId?: string | null\n languageCode?: string | null\n /** Speak on the expressive (v4) model so `[[...]]` audio tags are performed; for short clips. */\n expressive?: boolean\n /** Speak on the low-latency model. */\n lowLatency?: boolean\n}\n\n/** The error body of every relay HTTP answer other than 200. */\nexport interface RelayErrorBody {\n message: string\n code?: string\n}\n","import type { RetranscribeResult } from '../shared/wire'\nimport { LINEAR16_SAMPLE_RATE } from '../shared/wire'\nimport { buildDeepgramUrl } from './deepgram-request'\nimport type { RelayRuntime } from './runtime'\nimport type { DeepgramGrant, VoiceGrant } from './types'\n\ntype DeepgramPrerecorded = {\n results?: {\n channels?: {\n detected_language?: unknown\n language_confidence?: unknown\n alternatives?: { transcript?: unknown; confidence?: unknown }[]\n }[]\n }\n}\n\n/**\n * Deepgram prerecorded transcription of one buffered utterance (16 kHz linear16), with language\n * detection unless a language is pinned. Neither the audio nor the transcript is logged; a refused\n * keyterm prompt (400) is retried once without keyterms.\n */\nexport async function transcribe(\n rt: RelayRuntime,\n grant: VoiceGrant & { deepgram: DeepgramGrant },\n apiKey: string,\n audio: Uint8Array,\n pinned: string | null,\n): Promise<RetranscribeResult | 'timeout' | 'error'> {\n const { deepgram, principalId } = grant\n // `multi` is the streaming auto mode; the prerecorded API detects the language instead.\n const fixedLanguage = pinned && pinned !== 'multi' ? pinned : null\n let keyterms: readonly string[] = []\n try {\n keyterms = (await grant.keyterms?.(fixedLanguage)) ?? []\n } catch {\n rt.logger.warn('Speech keyterms could not be read; re-transcribing without them')\n }\n const urlWith = (terms: readonly string[]) =>\n buildDeepgramUrl(\n deepgram.host,\n 'https',\n '/v1/listen',\n {\n model: deepgram.model,\n encoding: 'linear16',\n sample_rate: String(LINEAR16_SAMPLE_RATE),\n smart_format: 'true',\n ...(fixedLanguage ? { language: fixedLanguage } : { detect_language: 'true' }),\n ...(terms.length > 0 ? { keyterm: terms } : {}),\n },\n { hostPattern: rt.deepgramHostPattern },\n )\n let response = await request(rt, principalId, apiKey, urlWith(keyterms), audio)\n if (typeof response !== 'string' && response.status === 400 && keyterms.length > 0) {\n // A refused prompt (over Deepgram's token limit, or unsupported with detection) must not cost the utterance.\n rt.logger.warn('Deepgram re-transcription refused the keyterms: status=400; retrying without them')\n response = await request(rt, principalId, apiKey, urlWith([]), audio)\n }\n if (typeof response === 'string') return response\n if (!response.ok) {\n // The error body may echo request details; the status is the diagnostic.\n rt.logger.warn(`Deepgram re-transcription rejected: status=${response.status}`)\n return 'error'\n }\n return parse(rt, response, fixedLanguage)\n}\n\nasync function request(\n rt: RelayRuntime,\n principalId: string,\n apiKey: string,\n url: URL,\n audio: Uint8Array,\n): Promise<Response | 'timeout' | 'error'> {\n rt.audit({\n event: 'deepgram-retranscription-requested',\n principalId,\n host: url.host,\n model: url.searchParams.get('model'),\n bytes: audio.length,\n mipOptOut: url.searchParams.get('mip_opt_out'),\n keyterms: url.searchParams.getAll('keyterm').length,\n })\n try {\n return await rt.fetch()(url, {\n method: 'POST',\n headers: { Authorization: `Token ${apiKey}`, 'Content-Type': 'application/octet-stream' },\n body: new Uint8Array(audio),\n signal: AbortSignal.timeout(rt.limits.retranscribe.timeoutMs),\n })\n } catch (err) {\n const timedOut = (err as { name?: unknown } | null)?.name === 'TimeoutError'\n rt.logger.warn(`Deepgram re-transcription ${timedOut ? 'timed out' : 'failed before a response'}`)\n return timedOut ? 'timeout' : 'error'\n }\n}\n\nasync function parse(\n rt: RelayRuntime,\n response: Response,\n fixedLanguage: string | null,\n): Promise<RetranscribeResult | 'error'> {\n let payload: DeepgramPrerecorded\n try {\n payload = (await response.json()) as DeepgramPrerecorded\n } catch {\n rt.logger.warn('Deepgram re-transcription answered with an unreadable body')\n return 'error'\n }\n const channel = payload.results?.channels?.[0]\n const transcript = channel?.alternatives?.[0]?.transcript\n const detected = typeof channel?.detected_language === 'string' ? channel.detected_language : null\n const confidence = channel?.language_confidence\n const wordsConfidence = channel?.alternatives?.[0]?.confidence\n return {\n transcript: typeof transcript === 'string' ? transcript : '',\n confidence: typeof wordsConfidence === 'number' && Number.isFinite(wordsConfidence) ? wordsConfidence : null,\n language: fixedLanguage ?? detected,\n languageConfidence:\n fixedLanguage === null && typeof confidence === 'number' && Number.isFinite(confidence) ? confidence : null,\n }\n}\n","import { createRequire } from 'node:module'\n\n// ── The browser's socket, as the relay sees it ──────────────────────────────\n\n/**\n * The client side of a relay stream: a `ws` socket, a crossws peer, … behind a small shim\n * (`wsRelaySocket`, the h3 entry's peer shim). The shim drops a send to a socket that is no longer\n * open, ends the socket on a transport error, and tells text frames (`string`) from binary ones.\n * `onClose` must fire once the socket is gone, also after the relay's own `close`.\n */\nexport interface RelaySocket {\n send(data: string | Uint8Array): void\n close(code?: number, reason?: string): void\n onMessage(listener: (data: string | Uint8Array) => void): void\n onClose(listener: () => void): void\n}\n\n/** The part of a `ws` WebSocket (`ws` 8) the shims use. */\nexport interface WsLike {\n readonly readyState: number\n send(data: string | Uint8Array, options?: { binary?: boolean }): void\n close(code?: number, reason?: string): void\n terminate(): void\n on(event: string, listener: (...args: any[]) => void): unknown\n}\n\nconst WS_CONNECTING = 0\nconst WS_OPEN = 1\n\n/** A `ws` server-side socket (e.g. from `WebSocketServer.handleUpgrade`) as a `RelaySocket`. */\nexport function wsRelaySocket(ws: WsLike): RelaySocket {\n // A malformed or oversized client frame emits 'error'; unlistened, it would end the process.\n ws.on('error', () => ws.terminate())\n return {\n send(data) {\n if (ws.readyState === WS_OPEN) ws.send(data, { binary: typeof data !== 'string' })\n },\n close: (code, reason) => ws.close(code, reason),\n onMessage(listener) {\n // ws 8 delivers text frames as a Buffer too; only `isBinary` tells control frames from audio.\n ws.on('message', (raw: Uint8Array | string, isBinary: boolean) => {\n if (isBinary) listener(typeof raw === 'string' ? new TextEncoder().encode(raw) : raw)\n else listener(typeof raw === 'string' ? raw : new TextDecoder().decode(raw))\n })\n },\n onClose: listener => void ws.on('close', () => listener()),\n }\n}\n\n// ── The provider's socket ────────────────────────────────────────────────────\n\n/** A rejected provider handshake (a non-101 answer). */\nexport interface UpstreamRejection {\n status: number\n statusText: string\n /** Reads the answer body; rejects when the read fails. It may echo the request, key included. */\n body(): Promise<string>\n /** Drains the body unread. */\n discard(): void\n}\n\nexport interface UpstreamHandlers {\n open(): void\n /** A text frame (every provider frame the relay reads is JSON text). */\n message(data: string): void\n rejected(rejection: UpstreamRejection): void\n /** A transport error; its message may quote request headers (the key). */\n error(error: { name: string; message: string; code?: unknown }): void\n close(code: number, reason: string): void\n}\n\n/** An outbound provider socket. Events fire only after `on` is called (dialling is asynchronous). */\nexport interface UpstreamSocket {\n readonly state: 'connecting' | 'open' | 'closed'\n send(data: string | Uint8Array): void\n close(): void\n on(handlers: UpstreamHandlers): void\n}\n\n/**\n * Opens a provider socket whose handshake carries the key in a header. May throw synchronously\n * (an invalid header value does); the relay answers that with fixed text and never logs the error.\n */\nexport type UpstreamDialer = (url: URL, headers: Record<string, string>) => UpstreamSocket\n\n/** The `ws` client constructor (`import WebSocket from 'ws'`). */\nexport type WsConstructor = new (url: string | URL, options: { headers: Record<string, string> }) => WsLike\n\ninterface IncomingAnswer {\n statusCode?: number\n statusMessage?: string\n on(event: string, listener: (...args: any[]) => void): unknown\n resume(): unknown\n}\n\n/** A dialer on the `ws` client: pass `wsDialer(WebSocket)` with `import WebSocket from 'ws'`. */\nexport function wsDialer(WebSocket: WsConstructor): UpstreamDialer {\n return (url, headers) => {\n const ws = new WebSocket(url, { headers })\n return {\n get state() {\n return ws.readyState === WS_CONNECTING ? 'connecting' : ws.readyState === WS_OPEN ? 'open' : 'closed'\n },\n send: data => ws.send(data),\n close: () => ws.close(),\n on(handlers) {\n ws.on('open', () => handlers.open())\n ws.on('message', (raw: Uint8Array | string) =>\n handlers.message(typeof raw === 'string' ? raw : new TextDecoder().decode(raw)),\n )\n ws.on('unexpected-response', (_request: unknown, res: IncomingAnswer) => {\n let guarded = false\n // A reset while reading the rejection is an unlistened 'error', which ends the process.\n const guard = (onError: () => void) => {\n if (!guarded) res.on('error', onError)\n guarded = true\n }\n handlers.rejected({\n status: res.statusCode ?? 0,\n statusText: res.statusMessage ?? '',\n body: () =>\n new Promise<string>((resolve, reject) => {\n let body = ''\n guard(() => reject(new Error('body read failed')))\n res.on('data', (chunk: Uint8Array) => {\n body += new TextDecoder().decode(chunk)\n })\n res.on('end', () => resolve(body))\n }),\n discard() {\n guard(() => undefined)\n res.resume()\n },\n })\n })\n ws.on('error', (e: Error & { code?: unknown }) => handlers.error(e))\n ws.on('close', (code: number, reason: Uint8Array) => handlers.close(code, new TextDecoder().decode(reason)))\n },\n }\n }\n}\n\n/**\n * The default dialer: `ws`, an optional peer dependency, loaded when the relay is created so a\n * missing install fails at startup rather than on the first stream.\n */\nexport function defaultDialer(): UpstreamDialer {\n let mod: { WebSocket?: WsConstructor } & WsConstructor\n try {\n mod = createRequire(import.meta.url)('ws')\n } catch {\n throw new Error(\"@skaile/forge-voice/server: install 'ws', or pass `dial` to createVoiceRelay\")\n }\n return wsDialer(mod.WebSocket ?? mod)\n}\n","import { modelAcceptsLanguageCode } from '../shared/voice-languages'\nimport { buildElevenLabsUrl } from './elevenlabs-request'\nimport { withoutKey } from './key-redact'\nimport type { RelayRuntime } from './runtime'\nimport type { RelayResult, SpokenClip } from './types'\n\n/**\n * Budget for one text-to-speech call, scaled with the text: the stream can run as long as the clip,\n * so 20 s of headroom plus 20 ms per character (3 min 40 s at 10k characters). A total budget: it\n * also bounds the error-body read and the audio relayed; expiry while the audio is relayed ends it early.\n */\nexport function ttsTimeoutMs(textLength: number): number {\n return 20_000 + textLength * 20\n}\n\nconst TIMEOUT_MESSAGE = 'ElevenLabs did not answer in time'\n/** A transport failure answers fixed text: an invalid header value fails inside `fetch` with an error that quotes the key. */\nconst TRANSPORT_MESSAGE = 'ElevenLabs could not be reached'\n\n/** By name: the rejection is a DOMException, which is not an `Error` in every realm. */\nfunction isTimeout(err: unknown): boolean {\n return (err as { name?: unknown } | null)?.name === 'TimeoutError'\n}\n\nfunction errorName(err: unknown): string {\n const name = (err as { name?: unknown } | null)?.name\n return typeof name === 'string' && /^[A-Za-z]{1,64}$/.test(name) ? name : 'Error'\n}\n\nexport interface ClipRequest {\n principalId: string\n apiKey: string\n /** The text as sent: without audio tags for the plain model, with ElevenLabs tags for the expressive one. */\n text: string\n voiceId: string\n model: string\n languageCode: string | null\n}\n\n/** Plain ElevenLabs streaming text-to-speech; the answer streams while the rest is still being synthesised. */\nexport async function speakPlain(rt: RelayRuntime, clip: ClipRequest): Promise<RelayResult<SpokenClip>> {\n const { apiKey, text, voiceId, model } = clip\n const url = buildElevenLabsUrl(`/v1/text-to-speech/${voiceId}/stream`, { output_format: 'mp3_44100_128' })\n rt.audit({\n event: 'elevenlabs-speech-requested',\n principalId: clip.principalId,\n voiceId,\n model,\n chars: text.length,\n enableLogging: url.searchParams.get('enable_logging'),\n })\n let response: Response\n try {\n response = await rt.fetch()(url, {\n method: 'POST',\n headers: { 'xi-api-key': apiKey, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n text,\n model_id: model,\n ...(clip.languageCode ? { language_code: clip.languageCode } : {}),\n }),\n signal: AbortSignal.timeout(ttsTimeoutMs(text.length)),\n })\n } catch (err) {\n if (isTimeout(err)) return { ok: false, status: 504, message: TIMEOUT_MESSAGE }\n rt.logger.warn(`ElevenLabs speech request failed: ${errorName(err)}`)\n return { ok: false, status: 502, message: TRANSPORT_MESSAGE }\n }\n if (!response.ok) {\n let errorText: string\n try {\n errorText = await response.text()\n } catch (err) {\n // The budget covers this read too; running out here is still a timeout.\n if (isTimeout(err)) return { ok: false, status: 504, message: TIMEOUT_MESSAGE }\n rt.logger.warn(`ElevenLabs error body read failed: ${errorName(err)}`)\n return { ok: false, status: 502, message: TRANSPORT_MESSAGE }\n }\n return { ok: false, status: 502, message: `ElevenLabs API error: ${withoutKey(errorText, apiKey)}` }\n }\n if (!response.body) return { ok: false, status: 502, message: TRANSPORT_MESSAGE }\n return { ok: true, value: { contentType: 'audio/mpeg', body: response.body } }\n}\n\n/**\n * The text with its audio tags (`[laughs]`) through text-to-dialogue on the stream model, so a clip\n * sounds like the streamed replies. Null on any failure (the caller falls back to the plain model);\n * only the status is logged, since an error body may echo the text.\n */\nexport async function speakExpressive(rt: RelayRuntime, clip: ClipRequest): Promise<SpokenClip | null> {\n const { apiKey, text, voiceId, model, languageCode } = clip\n const url = buildElevenLabsUrl('/v1/text-to-dialogue/stream', { output_format: 'mp3_44100_128' })\n rt.audit({\n event: 'elevenlabs-speech-requested',\n principalId: clip.principalId,\n voiceId,\n model,\n chars: text.length,\n enableLogging: url.searchParams.get('enable_logging'),\n })\n try {\n const response = await rt.fetch()(url, {\n method: 'POST',\n headers: { 'xi-api-key': apiKey, 'Content-Type': 'application/json' },\n body: JSON.stringify({\n inputs: [{ text, voice_id: voiceId }],\n model_id: model,\n ...(languageCode && modelAcceptsLanguageCode(model) ? { language_code: languageCode } : {}),\n }),\n signal: AbortSignal.timeout(ttsTimeoutMs(text.length)),\n })\n if (!response.ok || !response.body) {\n rt.logger.warn(`ElevenLabs expressive speech failed: ${response.status}; falling back`)\n await response.body?.cancel().catch(() => undefined)\n return null\n }\n return { contentType: 'audio/mpeg', body: response.body }\n } catch (err) {\n rt.logger.warn(`ElevenLabs expressive speech failed: ${isTimeout(err) ? 'timeout' : 'transport'}; falling back`)\n return null\n }\n}\n","import type { RelaySocket, UpstreamDialer, UpstreamSocket } from './sockets'\nimport type { RelayAuditLine, RelayLimits, RelayLogger } from './types'\n\n/** What the stream and route handlers share, resolved once by `createVoiceRelay`. */\nexport interface RelayRuntime {\n dial: UpstreamDialer\n fetch(): typeof fetch\n logger: RelayLogger\n audit(line: RelayAuditLine): void\n limits: RelayLimits\n deepgramHostPattern: RegExp\n}\n\n/** Dials a provider socket; a dial that throws (an invalid header value quotes the key) yields null, its error dropped. */\nexport function openUpstream(rt: RelayRuntime, url: URL, headers: Record<string, string>): UpstreamSocket | null {\n try {\n return rt.dial(url, headers)\n } catch {\n return null\n }\n}\n\n/** Tells the browser the stream cannot start, with fixed text, and frees its slot once it closes. */\nexport function refuseClient(client: RelaySocket, release: () => void, error: string): void {\n client.onClose(release)\n client.send(JSON.stringify({ type: 'error', error }))\n client.close(1011, 'upstream-error')\n}\n","import type { SttEncoding, SttServerFrame } from '../shared/wire'\nimport { LINEAR16_SAMPLE_RATE } from '../shared/wire'\nimport { buildDeepgramUrl } from './deepgram-request'\nimport { withoutKey } from './key-redact'\nimport { openUpstream, type RelayRuntime, refuseClient } from './runtime'\nimport type { RelaySocket } from './sockets'\nimport type { DeepgramGrant } from './types'\n\n/** One admitted speech-to-text stream. */\nexport interface SttStream {\n principalId: string\n apiKey: string\n deepgram: DeepgramGrant\n /** The requested language, already on the closed list; null: the grant's default. */\n language: string | null\n encoding: SttEncoding | null\n keyterms: readonly string[]\n release(): void\n}\n\n/**\n * The stream's language: the requested one, else the default. nova-3 has no `detect_language` on a\n * stream; `multi` is its multilingual mode, so a default of `auto` streams as `multi`.\n */\nexport function sttStreamLanguage(language: string | null, defaultLanguage: string): string {\n return language ?? (defaultLanguage === 'auto' ? 'multi' : defaultLanguage)\n}\n\ntype DeepgramWord = { start?: unknown; end?: unknown; confidence?: unknown }\n\n/** Mean word confidence, or undefined when Deepgram sent no scored words. */\nfunction meanWordConfidence(words: readonly DeepgramWord[]): number | undefined {\n const scores = words.map(w => w.confidence).filter((c): c is number => typeof c === 'number')\n return scores.length > 0 ? scores.reduce((sum, c) => sum + c, 0) / scores.length : undefined\n}\n\nconst finiteOrUndefined = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) ? value : undefined\n\n/** Pipes an upgraded client socket to a Deepgram live stream until either side ends. */\nexport function pipeStt(rt: RelayRuntime, client: RelaySocket, stream: SttStream): void {\n const { apiKey, deepgram, principalId, release } = stream\n const limits = rt.limits.stt\n const lang = sttStreamLanguage(stream.language, deepgram.defaultLanguage)\n const url = buildDeepgramUrl(\n deepgram.host,\n 'wss',\n '/v1/listen',\n {\n model: deepgram.model,\n language: lang,\n smart_format: 'true',\n interim_results: 'true',\n endpointing: '300',\n vad_events: 'true',\n ...(stream.encoding === 'linear16' ? { encoding: 'linear16', sample_rate: String(LINEAR16_SAMPLE_RATE) } : {}),\n ...(stream.keyterms.length > 0 ? { keyterm: stream.keyterms } : {}),\n },\n { hostPattern: rt.deepgramHostPattern },\n )\n rt.audit({\n event: 'deepgram-stream-opened',\n principalId,\n host: url.host,\n model: url.searchParams.get('model'),\n language: lang,\n mipOptOut: url.searchParams.get('mip_opt_out'),\n keyterms: url.searchParams.getAll('keyterm').length,\n })\n\n const upstream = openUpstream(rt, url, { Authorization: `Token ${apiKey}` })\n if (!upstream) {\n rt.logger.error('Deepgram stream could not be opened')\n refuseClient(client, release, 'Deepgram could not be reached')\n return\n }\n\n let clientGone = false\n // Deepgram events can fire after the client disconnected.\n const send = (frame: SttServerFrame) => {\n if (!clientGone) client.send(JSON.stringify(frame))\n }\n\n // Cost guards: a hard cap on the stream's lifetime and an idle timer reset on each client frame.\n const maxTimer = setTimeout(() => client.close(1000, 'max-duration'), limits.maxDurationMs)\n // A client that wants to keep listening rolls over to a fresh stream on this warning instead of losing the words at the cut.\n const expiryTimer = setTimeout(\n () => send({ type: 'expiring', inMs: limits.expiryWarningMs }),\n limits.maxDurationMs - limits.expiryWarningMs,\n )\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n const resetIdle = () => {\n clearTimeout(idleTimer)\n idleTimer = setTimeout(() => client.close(1000, 'idle-timeout'), limits.idleMs)\n }\n resetIdle()\n\n upstream.on({\n open: () => send({ type: 'ready' }),\n message(raw) {\n try {\n const data = JSON.parse(raw)\n if (data.type === 'SpeechStarted') {\n // Lets a client stop its own playback the moment the user starts talking (barge-in); the\n // stream timestamp lets it judge an echo by when its audio began, not when it arrived.\n send({ type: 'speech_started', timestamp: finiteOrUndefined(data.timestamp) })\n } else if (data.type === 'Results') {\n const alt = data.channel?.alternatives?.[0]\n if (alt) {\n const words: DeepgramWord[] = Array.isArray(alt.words) ? alt.words : []\n const detected =\n Array.isArray(alt.languages) && typeof alt.languages[0] === 'string' ? alt.languages[0] : null\n send({\n type: 'transcript',\n transcript: alt.transcript || '',\n is_final: data.is_final ?? false,\n speech_final: data.speech_final ?? false,\n start: finiteOrUndefined(data.start),\n duration: finiteOrUndefined(data.duration),\n wordsStart: finiteOrUndefined(words[0]?.start),\n // The window (start + duration) runs on through the trailing silence; this is the speech end.\n wordsEnd: finiteOrUndefined(words.at(-1)?.end),\n confidence: meanWordConfidence(words),\n language: detected ?? (lang === 'multi' ? undefined : lang),\n })\n }\n }\n } catch {\n rt.logger.error('Deepgram message parse error')\n }\n },\n rejected(res) {\n res.body().then(\n body => {\n rt.logger.error(`Deepgram rejected connection: ${res.status} ${res.statusText} - ${withoutKey(body, apiKey)}`)\n send({\n type: 'error',\n error: `Deepgram rejected: ${res.status} ${res.statusText} ${withoutKey(body, apiKey)}`,\n })\n // Frees the principal's slot now rather than after the idle timeout.\n client.close(1011, 'upstream-error')\n },\n () => rt.logger.error(`Deepgram rejected connection: ${res.status} ${res.statusText} - <body read failed>`),\n )\n },\n error(e) {\n const message = withoutKey(e.message, apiKey)\n rt.logger.error(`Deepgram WS error: ${message}`)\n send({ type: 'error', error: `Deepgram error: ${message}` })\n client.close(1011, 'upstream-error')\n },\n close(code, reason) {\n rt.logger.log?.(`Deepgram WS closed: ${code} ${reason}`)\n send({ type: 'closed' })\n },\n })\n\n client.onMessage(data => {\n resetIdle()\n if (upstream.state !== 'open') return\n if (typeof data !== 'string') {\n upstream.send(data)\n return\n }\n try {\n if (JSON.parse(data)?.type === 'stop') upstream.send(JSON.stringify({ type: 'CloseStream' }))\n } catch {\n // Not JSON; a text frame is never audio, so it is dropped.\n }\n })\n\n client.onClose(() => {\n clientGone = true\n clearTimeout(maxTimer)\n clearTimeout(expiryTimer)\n clearTimeout(idleTimer)\n release()\n try {\n upstream.close()\n } catch {\n /* already closed */\n }\n })\n}\n","import type { TtsServerFrame } from '../shared/wire'\nimport { TTS_STREAM_SAMPLE_RATE } from '../shared/wire'\nimport { buildElevenLabsUrl } from './elevenlabs-request'\nimport { openUpstream, type RelayRuntime, refuseClient } from './runtime'\nimport type { RelaySocket } from './sockets'\n\n/** One admitted text-to-speech stream; `voiceId` and `languageCode` are already validated. */\nexport interface TtsStream {\n principalId: string\n apiKey: string\n model: string\n voiceId: string\n languageCode: string | null\n release(): void\n}\n\ntype UpstreamAlignment = { chars?: unknown }\n\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\n/**\n * Pipes an upgraded client socket to ElevenLabs' text-to-dialogue stream: the reply text streams in\n * as the agent writes it, raw PCM (s16le, mono, 24 kHz) streams back, and the key never reaches the browser.\n */\nexport function pipeTts(rt: RelayRuntime, client: RelaySocket, stream: TtsStream): void {\n const { apiKey, model, voiceId, principalId, release } = stream\n const limits = rt.limits.tts\n const url = buildElevenLabsUrl(\n '/v1/text-to-dialogue/stream-input',\n {\n model_id: model,\n output_format: `pcm_${TTS_STREAM_SAMPLE_RATE}`,\n sync_alignment: 'true',\n ...(stream.languageCode ? { language_code: stream.languageCode } : {}),\n },\n { protocol: 'wss' },\n )\n rt.audit({\n event: 'elevenlabs-stream-opened',\n principalId,\n voiceId,\n model: url.searchParams.get('model_id'),\n enableLogging: url.searchParams.get('enable_logging'),\n })\n\n const upstream = openUpstream(rt, url, { 'xi-api-key': apiKey })\n if (!upstream) {\n rt.logger.error('ElevenLabs stream could not be opened')\n refuseClient(client, release, 'ElevenLabs could not be reached')\n return\n }\n // Text the client sends before the upstream handshake finishes; sent right after the init.\n const pending: string[] = []\n let chars = 0\n let done = false\n let ended = false\n let clientGone = false\n\n const send = (frame: TtsServerFrame) => {\n if (!clientGone) client.send(JSON.stringify(frame))\n }\n const toUpstream = (payload: unknown) => {\n const raw = JSON.stringify(payload)\n if (upstream.state === 'open') upstream.send(raw)\n else if (upstream.state === 'connecting') pending.push(raw)\n }\n const fail = (error: string) => {\n if (done) return\n done = true\n send({ type: 'error', error })\n client.close(1011, 'upstream-error')\n }\n\n const maxTimer = setTimeout(() => client.close(1000, 'max-duration'), limits.maxDurationMs)\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n const resetIdle = () => {\n clearTimeout(idleTimer)\n idleTimer = setTimeout(() => client.close(1000, 'idle-timeout'), limits.idleMs)\n }\n resetIdle()\n // A reply can pause for a long tool call; without input ElevenLabs would close the socket after 20 s.\n const keepAlive = setInterval(() => {\n if (!done && upstream.state === 'open') upstream.send(JSON.stringify({ keep_alive: true }))\n }, limits.keepAliveMs)\n\n upstream.on({\n open() {\n // v4 takes exactly one voice, named once in the init message.\n upstream.send(JSON.stringify({ voices: [voiceId] }))\n for (const raw of pending.splice(0)) upstream.send(raw)\n send({ type: 'ready', sampleRate: TTS_STREAM_SAMPLE_RATE })\n },\n message(raw) {\n let data: Record<string, unknown>\n try {\n data = JSON.parse(raw) as Record<string, unknown>\n } catch {\n rt.logger.error('ElevenLabs stream message parse error')\n return\n }\n if (!data || typeof data !== 'object') return\n if (typeof data.error === 'string' || (typeof data.code === 'number' && typeof data.message === 'string')) {\n // The message may echo the request; only the error code is logged and relayed.\n const code = typeof data.error === 'string' ? data.error : String(data.code)\n rt.logger.error(`ElevenLabs stream error: ${code}`)\n fail(code)\n return\n }\n if (typeof data.audio === 'string' && data.audio.length > 0 && !clientGone) {\n const alignment = data.alignment as UpstreamAlignment | null | undefined\n if (alignment && Array.isArray(alignment.chars)) {\n // Sent before its audio: the client pairs each binary frame with the alignment before it.\n send({ type: 'alignment', text: alignment.chars.map(String).join('') })\n }\n client.send(base64ToBytes(data.audio))\n }\n // Only the final after `close_socket` ends the reply; an earlier one would drop text in flight.\n if (data.is_final === true && !done && !ended) {\n fail('early-final')\n return\n }\n if (data.is_final === true && !done) {\n done = true\n send({ type: 'done' })\n client.close(1000, 'done')\n }\n },\n rejected(res) {\n // The body may echo the request: drained, never read into a log.\n res.discard()\n rt.logger.error(`ElevenLabs rejected stream: ${res.status} ${res.statusText}`)\n fail(String(res.status))\n },\n error(e) {\n if (clientGone) return\n rt.logger.error(`ElevenLabs stream WS error: ${e.name}`)\n fail(typeof e.code === 'string' ? e.code : 'upstream-error')\n },\n close(code) {\n // Closed without `is_final` (its idle timeout, a policy close): the reply is incomplete.\n if (!clientGone) fail(`upstream-closed-${code}`)\n },\n })\n\n client.onMessage(data => {\n resetIdle()\n if (typeof data !== 'string' || done) return\n let frame: { type?: unknown; text?: unknown; flush?: unknown }\n try {\n frame = JSON.parse(data) as typeof frame\n } catch {\n return\n }\n if (frame?.type === 'text' && typeof frame.text === 'string') {\n chars += frame.text.length\n if (chars > limits.maxTextChars) {\n done = true\n send({ type: 'error', error: 'text limit' })\n client.close(1008, 'text-limit')\n return\n }\n // Empty text frames forward nothing, so they cannot grow the pre-open buffer.\n if (frame.text.length > 0) {\n toUpstream({ inputs: [{ text: frame.text, voice_id: voiceId }] })\n if (frame.flush === true) toUpstream({ flush: true })\n }\n } else if (frame?.type === 'end' && !ended) {\n ended = true\n toUpstream({ close_socket: true })\n }\n })\n\n client.onClose(() => {\n clientGone = true\n clearTimeout(maxTimer)\n clearTimeout(idleTimer)\n clearInterval(keepAlive)\n release()\n try {\n upstream.close()\n } catch {\n /* already closed */\n }\n rt.audit({ event: 'elevenlabs-stream-closed', principalId, chars })\n })\n}\n","import { stripAudioTagsForText, toElevenLabsTags } from '../shared/audio-tags'\nimport { modelAcceptsLanguageCode, parseSttLanguage, ttsLanguageCode } from '../shared/voice-languages'\nimport {\n parseSttEncoding,\n RELAY_QUERY_PARAMS,\n RETRANSCRIBE_MAX_BYTES,\n type RetranscribeResult,\n type SpeakRequestBody,\n type VoiceRelayRoute,\n} from '../shared/wire'\nimport { formatAuditLine } from './audit'\nimport { DEEPGRAM_HOST_PATTERN, isAllowedDeepgramHost } from './deepgram-request'\nimport { transcribe } from './retranscribe'\nimport type { RelayRuntime } from './runtime'\nimport { defaultDialer, type RelaySocket } from './sockets'\nimport { speakExpressive, speakPlain } from './speak'\nimport { pipeStt, type SttStream, sttStreamLanguage } from './stt'\nimport { pipeTts, type TtsStream } from './tts'\nimport type {\n DeepgramGrant,\n ProviderKey,\n RelayLimits,\n RelayRefusal,\n RelayRequest,\n RelayResult,\n SpokenClip,\n VoiceAdmission,\n VoiceGrant,\n VoiceRelayConfig,\n VoiceRelayHost,\n} from './types'\n\nexport interface VoiceRelay<C = unknown> {\n /**\n * Runs the gates of a WebSocket route (`stt`, `tts`) before the upgrade: the Origin allowlist, the\n * host's `authorize`, the keyterm read, the per-principal cap and the key. A refusal is answered on\n * the upgrade request (HTTP status); an admission holds a slot until its stream ends.\n */\n admit(request: RelayRequest<C>): Promise<VoiceAdmission | RelayRefusal>\n /** After the upgrade: pipes the client socket to Deepgram's live stream. */\n stt(client: RelaySocket, admission: VoiceAdmission): void\n /** After the upgrade: pipes the client socket to ElevenLabs' text-to-dialogue stream. */\n tts(client: RelaySocket, admission: VoiceAdmission): void\n /** `POST retranscribe`: the body is raw 16 kHz linear16. Gates, then Deepgram prerecorded. */\n retranscribe(request: RelayRequest<C>, pcm: Uint8Array): Promise<RelayResult<RetranscribeResult>>\n /** `POST speak`: gates, then one clip from ElevenLabs as an `audio/mpeg` stream. */\n speak(request: RelayRequest<C>, body: SpeakRequestBody): Promise<RelayResult<SpokenClip>>\n /** Streams the principal holds open on a route (admitted, not yet closed). */\n activeStreams(kind: 'stt' | 'tts', principalId: string): number\n /** The caps and timers in effect (defaults merged with the host's). */\n readonly limits: RelayLimits\n}\n\nexport const DEFAULT_RELAY_LIMITS: RelayLimits = {\n // Generous enough never to bite normal dictation; they only cap abandoned or scripted sockets.\n stt: { maxConcurrent: 5, maxDurationMs: 10 * 60_000, idleMs: 90_000, expiryWarningMs: 30_000 },\n // One socket per spoken reply, each holding one of the plan's pooled dialogue sessions.\n tts: { maxConcurrent: 3, maxDurationMs: 5 * 60_000, idleMs: 2 * 60_000, keepAliveMs: 10_000, maxTextChars: 10_000 },\n retranscribe: { maxBytes: RETRANSCRIBE_MAX_BYTES, timeoutMs: 15_000 },\n // ElevenLabs caps one text-to-speech request at 10k characters; the cap bounds what one call can spend.\n speak: { maxTextChars: 10_000, maxExpressiveChars: 200 },\n}\n\n/** An admission must reach `relay.stt` / `relay.tts` within this, or its slot is freed. */\nconst ADMISSION_TTL_MS = 10_000\n\n/** ElevenLabs voice ids are opaque alphanumeric strings; anything else could reshape the request path. */\nconst VOICE_ID = /^[A-Za-z0-9]+$/\n\nconst STATUS_TEXT: Record<RelayRefusal['refuse'], string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 413: 'Payload Too Large',\n 429: 'Too Many Requests',\n 501: 'Not Implemented',\n}\n\nexport function isRelayRefusal(value: unknown): value is RelayRefusal {\n return typeof value === 'object' && value !== null && 'refuse' in value\n}\n\n/** The text an HTTP status line carries for a refusal. */\nexport function refusalStatusText(refusal: RelayRefusal): string {\n return STATUS_TEXT[refusal.refuse] ?? 'Error'\n}\n\nfunction refused<T>(refusal: RelayRefusal): RelayResult<T> {\n return {\n ok: false,\n status: refusal.refuse,\n message: refusal.message ?? refusalStatusText(refusal),\n ...(refusal.code ? { code: refusal.code } : {}),\n ...(refusal.retryAfterS !== undefined ? { retryAfterS: refusal.retryAfterS } : {}),\n }\n}\n\nconst fail = <T>(status: number, message: string): RelayResult<T> => ({ ok: false, status, message })\n\ntype Pending = ({ kind: 'stt'; stream: SttStream } | { kind: 'tts'; stream: TtsStream }) & {\n unclaimed?: ReturnType<typeof setTimeout>\n}\n\n/** Per-principal stream counters. Per process: with several replicas the cap is per instance. */\nclass Slots {\n private readonly active = new Map<string, number>()\n count(principalId: string): number {\n return this.active.get(principalId) ?? 0\n }\n take(principalId: string): () => void {\n this.active.set(principalId, this.count(principalId) + 1)\n let released = false\n return () => {\n if (released) return\n released = true\n const next = this.count(principalId) - 1\n if (next <= 0) this.active.delete(principalId)\n else this.active.set(principalId, next)\n }\n }\n}\n\nfunction mergeLimits(input: VoiceRelayHost['limits']): RelayLimits {\n return {\n stt: { ...DEFAULT_RELAY_LIMITS.stt, ...input?.stt },\n tts: { ...DEFAULT_RELAY_LIMITS.tts, ...input?.tts },\n retranscribe: { ...DEFAULT_RELAY_LIMITS.retranscribe, ...input?.retranscribe },\n speak: { ...DEFAULT_RELAY_LIMITS.speak, ...input?.speak },\n }\n}\n\n/**\n * The voice relay: speech-to-text and text-to-speech streams, re-transcription and spoken clips,\n * between a browser and Deepgram / ElevenLabs, holding the provider keys server-side. Framework-free;\n * a host adapter (the h3 entry, a NestJS gateway) reads requests and sockets and calls it.\n *\n * Privacy, enforced here and not configurable: every Deepgram URL carries `mip_opt_out=true` and every\n * ElevenLabs URL `enable_logging=false`, set last; a key is redacted from every relayed frame and log\n * line; no audio, transcript or text is logged; the WebSocket Origin check fails closed. Who may use\n * voice is the host's: `authorize` runs before any provider contact, and gets nothing from the relay.\n */\nexport function createVoiceRelay<C = unknown>(config: VoiceRelayConfig, host: VoiceRelayHost<C>): VoiceRelay<C> {\n const logger = host.logger ?? console\n const rt: RelayRuntime = {\n dial: config.dial ?? defaultDialer(),\n fetch: () => config.fetch ?? globalThis.fetch,\n logger,\n audit: host.audit ? line => host.audit!(line) : line => logger.warn(formatAuditLine(line)),\n limits: mergeLimits(host.limits),\n deepgramHostPattern: config.allowedHosts?.deepgram ?? DEEPGRAM_HOST_PATTERN,\n }\n const slots = { stt: new Slots(), tts: new Slots() }\n const pending = new WeakMap<VoiceAdmission, Pending>()\n const allowed = config.allowedOrigins\n\n // Fail closed: no configured origin, or a request without Origin, is refused.\n const originAllowed = (origin: string | null): boolean => {\n if (!origin) return false\n return typeof allowed === 'function' ? allowed(origin) : allowed.includes(origin)\n }\n\n const deepgramHostAllowed = (deepgram: DeepgramGrant): boolean => {\n const ok = isAllowedDeepgramHost(deepgram.host, rt.deepgramHostPattern)\n if (!ok) logger.error(`Deepgram host not allowed: ${deepgram.host}`)\n return ok\n }\n\n const readKey = async (key: ProviderKey): Promise<string | null> => (typeof key === 'string' ? key : key())\n\n /** Names and terms to listen for; a failed read streams without them rather than not at all. */\n const readKeyterms = async (grant: VoiceGrant, language: string | null): Promise<readonly string[]> => {\n try {\n return (await grant.keyterms?.(language)) ?? []\n } catch {\n logger.warn('Speech keyterms could not be read; streaming without them')\n return []\n }\n }\n\n /** The cap, then the key, then (the key read may have awaited) the cap again, then the slot. */\n const reserve = async (\n kind: 'stt' | 'tts',\n principalId: string,\n key: ProviderKey,\n ): Promise<{ apiKey: string; release: () => void } | RelayRefusal> => {\n const max = rt.limits[kind].maxConcurrent\n if (slots[kind].count(principalId) >= max) return { refuse: 429 }\n const apiKey = await readKey(key)\n if (!apiKey) return { refuse: 501 }\n if (slots[kind].count(principalId) >= max) return { refuse: 429 }\n return { apiKey, release: slots[kind].take(principalId) }\n }\n\n const admission = (entry: Pending, principalId: string): VoiceAdmission => {\n const handle: VoiceAdmission = {\n kind: entry.kind,\n principalId,\n release: () => {\n clearTimeout(unclaimed)\n if (pending.delete(handle)) entry.stream.release()\n },\n }\n // An upgrade that never completes must not hold the slot.\n const unclaimed = setTimeout(handle.release, ADMISSION_TTL_MS)\n ;(unclaimed as { unref?: () => void }).unref?.()\n pending.set(handle, { ...entry, unclaimed })\n return handle\n }\n\n const claim = (handle: VoiceAdmission, kind: 'stt' | 'tts'): Pending => {\n const entry = pending.get(handle)\n if (!entry || entry.kind !== kind) throw new TypeError(`Not an open ${kind} admission of this relay`)\n clearTimeout(entry.unclaimed)\n pending.delete(handle)\n return entry\n }\n\n /** A stream that fails to start (a throwing audit hook or send) still frees its slot. */\n const piped = (stream: { release(): void }, pipe: () => void) => {\n try {\n pipe()\n } catch (err) {\n stream.release()\n throw err\n }\n }\n\n return {\n async admit(request) {\n if (request.kind !== 'stt' && request.kind !== 'tts') {\n throw new TypeError(`admit() is for the WebSocket routes, not ${request.kind}`)\n }\n if (!originAllowed(request.origin)) return { refuse: 403 }\n const grant = await host.authorize(request)\n if (isRelayRefusal(grant)) return grant\n\n if (request.kind === 'stt') {\n const deepgram = grant.deepgram\n if (!deepgram || !deepgramHostAllowed(deepgram)) return { refuse: 501 }\n const language = parseSttLanguage(request.language)\n // Read before the cap check, so the slot is reserved with no await after it.\n const keyterms = await readKeyterms(grant, sttStreamLanguage(language, deepgram.defaultLanguage))\n const slot = await reserve('stt', grant.principalId, deepgram.apiKey)\n if (isRelayRefusal(slot)) return slot\n const stream: SttStream = {\n principalId: grant.principalId,\n apiKey: slot.apiKey,\n deepgram,\n language,\n encoding: parseSttEncoding(request.params.encoding),\n keyterms,\n release: slot.release,\n }\n return admission({ kind: 'stt', stream }, grant.principalId)\n }\n\n const elevenlabs = grant.elevenlabs\n if (!elevenlabs) return { refuse: 501 }\n const slot = await reserve('tts', grant.principalId, elevenlabs.apiKey)\n if (isRelayRefusal(slot)) return slot\n const requested = request.params.voiceId?.trim()\n const model = elevenlabs.models.stream\n const stream: TtsStream = {\n principalId: grant.principalId,\n apiKey: slot.apiKey,\n model,\n voiceId: requested && VOICE_ID.test(requested) ? requested : elevenlabs.voiceId,\n languageCode: modelAcceptsLanguageCode(model) ? ttsLanguageCode(request.params.languageCode) : null,\n release: slot.release,\n }\n return admission({ kind: 'tts', stream }, grant.principalId)\n },\n\n stt(client, handle) {\n const entry = claim(handle, 'stt')\n if (entry.kind === 'stt') piped(entry.stream, () => pipeStt(rt, client, entry.stream))\n },\n\n tts(client, handle) {\n const entry = claim(handle, 'tts')\n if (entry.kind === 'tts') piped(entry.stream, () => pipeTts(rt, client, entry.stream))\n },\n\n async retranscribe(request, pcm) {\n const limits = rt.limits.retranscribe\n if (pcm.length === 0) return fail(400, 'audio/l16 body is required')\n if (pcm.length > limits.maxBytes) return fail(413, `audio exceeds ${limits.maxBytes} bytes`)\n const grant = await host.authorize(request)\n if (isRelayRefusal(grant)) return refused(grant)\n const raw = request.language?.trim() || null\n const language = parseSttLanguage(raw)\n if (raw !== null && language === null) return fail(400, 'Unsupported language')\n const deepgram = grant.deepgram\n if (!deepgram || !deepgramHostAllowed(deepgram)) return fail(501, 'STT not configured')\n const apiKey = await readKey(deepgram.apiKey)\n if (!apiKey) return fail(501, 'STT not configured')\n const result = await transcribe(rt, { ...grant, deepgram }, apiKey, pcm, language)\n if (result === 'timeout') return fail(504, 'Deepgram did not answer in time')\n if (result === 'error') return fail(502, 'Deepgram transcription failed')\n return { ok: true, value: result }\n },\n\n async speak(request, body) {\n const limits = rt.limits.speak\n // Flash and multilingual v2 read `[[laughs]]` aloud as a word; only the expressive model performs tags.\n const text = typeof body.text === 'string' ? stripAudioTagsForText(body.text, { inCodeToo: true }) : ''\n if (!text.trim()) return fail(400, 'text is required')\n const tagged = body.expressive === true ? toElevenLabsTags(body.text) : null\n const expressiveText = tagged !== null && tagged.length <= limits.maxExpressiveChars ? tagged : null\n if (text.length > limits.maxTextChars) return fail(413, `text exceeds ${limits.maxTextChars} characters`)\n\n const grant = await host.authorize(request)\n if (isRelayRefusal(grant)) return refused(grant)\n const elevenlabs = grant.elevenlabs\n if (!elevenlabs) return fail(501, 'TTS not configured')\n const apiKey = await readKey(elevenlabs.apiKey)\n if (!apiKey) return fail(501, 'TTS not configured')\n\n const requested = typeof body.voiceId === 'string' ? body.voiceId.trim() : ''\n const voiceId = requested && VOICE_ID.test(requested) ? requested : elevenlabs.voiceId\n if (expressiveText !== null) {\n const clip = await speakExpressive(rt, {\n principalId: grant.principalId,\n apiKey,\n text: expressiveText,\n voiceId,\n model: elevenlabs.models.stream,\n languageCode: ttsLanguageCode(body.languageCode),\n })\n if (clip) return { ok: true, value: clip }\n // The expressive model failed: the clip is still spoken, by the model below and without its tags.\n }\n const model = body.lowLatency === true ? elevenlabs.models.clipFast : elevenlabs.models.clip\n return speakPlain(rt, {\n principalId: grant.principalId,\n apiKey,\n text,\n voiceId,\n model,\n // Only a language from the STT list, and only on a model that accepts one: others answer 400.\n languageCode: modelAcceptsLanguageCode(model) ? ttsLanguageCode(body.languageCode) : null,\n })\n },\n\n activeStreams: (kind, principalId) => slots[kind].count(principalId),\n limits: rt.limits,\n }\n}\n\n/** Headers as the relay reads them: lower-case names, one string each. */\nexport type RelayHeadersInput = Headers | Record<string, string | readonly string[] | undefined>\n\nfunction normalizeHeaders(headers: RelayHeadersInput): Record<string, string | undefined> {\n const out: Record<string, string | undefined> = {}\n if (typeof (headers as Headers).forEach === 'function' && typeof (headers as Headers).get === 'function') {\n ;(headers as Headers).forEach((value, name) => {\n out[name.toLowerCase()] = value\n })\n return out\n }\n for (const [name, value] of Object.entries(headers as Record<string, string | readonly string[] | undefined>)) {\n out[name.toLowerCase()] = typeof value === 'string' || value === undefined ? value : value.join(', ')\n }\n return out\n}\n\nconst RESERVED = new Set<string>(RELAY_QUERY_PARAMS)\nconst SPEAK_FIELDS = new Set(['text', 'voiceId', 'languageCode', 'expressive', 'lowLatency'])\n\n/**\n * A `RelayRequest` from the request URL (query: `token`, `language`, `encoding`, `voiceId`,\n * `languageCode`, the rest is scope) and headers. For `speak`, pass the JSON body: its string fields\n * other than the clip's own are scope too. The token is `?token=`, else an `Authorization: Bearer` header.\n */\nexport function relayRequest<C>(input: {\n kind: VoiceRelayRoute\n url: URL | string\n headers: RelayHeadersInput\n context: C\n body?: unknown\n}): RelayRequest<C> {\n const url = typeof input.url === 'string' ? new URL(input.url, 'http://localhost') : input.url\n const headers = normalizeHeaders(input.headers)\n const scope: Record<string, string> = {}\n const params: RelayRequest['params'] = {}\n for (const [key, value] of url.searchParams) {\n if (RESERVED.has(key)) params[key as keyof RelayRequest['params']] = value\n else scope[key] = value\n }\n if (input.kind === 'speak' && input.body && typeof input.body === 'object') {\n const body = input.body as Record<string, unknown>\n for (const [key, value] of Object.entries(body)) {\n if (!SPEAK_FIELDS.has(key) && typeof value === 'string') scope[key] = value\n }\n if (typeof body.languageCode === 'string') params.languageCode = body.languageCode\n if (typeof body.voiceId === 'string') params.voiceId = body.voiceId\n }\n const bearer = /^Bearer\\s+(.+)$/i.exec(headers.authorization ?? '')?.[1] ?? null\n return {\n kind: input.kind,\n origin: headers.origin ?? null,\n token: params.token ?? bearer,\n headers,\n scope,\n language: params.language ?? null,\n params,\n context: input.context,\n }\n}\n"],"mappings":";;AAEA,MAAM,SAAS;;;;;;AAOf,SAAgB,gBAAgB,MAA8B;CAC5D,QAAQ,KAAK,OAAb;EACE,KAAK,0BACH,OAAO,GAAG,OAAO,gCAAgC,KAAK,YAAY,QAAQ,KAAK,KAAK,SAAS,KAAK,MAAM,YAAY,KAAK,SAAS,eAAe,KAAK,UAAU,YAAY,KAAK;EACnL,KAAK,sCACH,OAAO,GAAG,OAAO,6CAA6C,KAAK,YAAY,QAAQ,KAAK,KAAK,SAAS,KAAK,MAAM,SAAS,KAAK,MAAM,eAAe,KAAK,UAAU,YAAY,KAAK;EAC1L,KAAK,4BACH,OAAO,GAAG,OAAO,kCAAkC,KAAK,YAAY,SAAS,KAAK,QAAQ,SAAS,KAAK,MAAM,kBAAkB,KAAK;EACvI,KAAK,4BACH,OAAO,GAAG,OAAO,kCAAkC,KAAK,YAAY,SAAS,KAAK;EACpF,KAAK,+BACH,OAAO,GAAG,OAAO,sCAAsC,KAAK,QAAQ,SAAS,KAAK,MAAM,SAAS,KAAK,MAAM,kBAAkB,K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as RelayResult, a as isRelayRefusal, b as VoiceGrant, c as DeepgramGrant, d as RelayAuditLine, f as RelayLimits, g as RelayRequest, h as RelayRefusal, i as createVoiceRelay, j as wsDialer, k as WsLike, l as ElevenLabsGrant, m as RelayLogger, n as RelayHeadersInput, o as refusalStatusText, p as RelayLimitsInput, r as VoiceRelay, s as relayRequest, t as DEFAULT_RELAY_LIMITS, u as ProviderKey, v as SpokenClip, w as UpstreamDialer, x as VoiceRelayConfig, y as VoiceAdmission } from "../relay.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* The audit line as one log string, e.g. `VOICE_PROVIDER_PRIVACY: Deepgram stream opened: user=u1
|
|
4
|
+
* host=api.eu.deepgram.com model=nova-3 language=de mip_opt_out=true keyterms=3`. The privacy values
|
|
5
|
+
* are read back from the URL actually sent. No audio, transcript, text, keyterm or key ever appears.
|
|
6
|
+
*/
|
|
7
|
+
export declare function formatAuditLine(line: RelayAuditLine): string;
|
|
8
|
+
/**
|
|
9
|
+
* The one place a Deepgram request URL is built. Deepgram keeps audio and transcripts in memory
|
|
10
|
+
* only for requests that opt out of its Model Improvement Program (`mip_opt_out=true`), so the
|
|
11
|
+
* opt-out is set here, last, and cannot be omitted or overridden by a caller.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* A bare Deepgram API host (`api.deepgram.com`, `api.eu.deepgram.com`): no scheme, port or path,
|
|
15
|
+
* so the key in the request header goes to Deepgram and nowhere else.
|
|
16
|
+
*/
|
|
17
|
+
export declare const DEEPGRAM_HOST_PATTERN: RegExp;
|
|
18
|
+
interface DeepgramUrlOptions {
|
|
19
|
+
/** The hosts a request may go to; default `DEEPGRAM_HOST_PATTERN`. Matched against the whole host. */
|
|
20
|
+
hostPattern?: RegExp;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Whether `host` is a bare host (no scheme, port, path or fragment, which could redirect the key) that
|
|
24
|
+
* the pattern matches as a whole. An unanchored or `g`-flagged pattern cannot widen this.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isAllowedDeepgramHost(host: string, hostPattern?: RegExp): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* A list value repeats the parameter (`keyterm=a&keyterm=b`), as Deepgram reads it; each value is
|
|
29
|
+
* percent-encoded by `URLSearchParams`, so a term can never add a parameter of its own. Throws for a
|
|
30
|
+
* host that does not match the pattern.
|
|
31
|
+
*/
|
|
32
|
+
export declare function buildDeepgramUrl(host: string, protocol: 'https' | 'wss', path: `/v1/${string}`, params: Record<string, string | readonly string[]>, { hostPattern }?: DeepgramUrlOptions): URL;
|
|
33
|
+
/**
|
|
34
|
+
* The one place an ElevenLabs request URL is built. `enable_logging=false` is ElevenLabs'
|
|
35
|
+
* per-request Zero Retention Mode: the text and audio of the request are not stored. It is set
|
|
36
|
+
* here, last, and cannot be omitted or overridden by a caller, the same way `buildDeepgramUrl`
|
|
37
|
+
* forces Deepgram's opt-out.
|
|
38
|
+
*/
|
|
39
|
+
export declare const ELEVENLABS_HOST = "api.elevenlabs.io";
|
|
40
|
+
/** `wss` for the streaming-input sockets (the text-to-dialogue stream), else `https`. */
|
|
41
|
+
export declare function buildElevenLabsUrl(path: `/v1/${string}`, params?: Record<string, string>, { protocol }?: {
|
|
42
|
+
protocol?: 'https' | 'wss';
|
|
43
|
+
}): URL;
|
|
44
|
+
/** A provider's text with the key it was called with removed, for a reply or a log line. */
|
|
45
|
+
export declare function withoutKey(text: string, key: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Budget for one text-to-speech call, scaled with the text: the stream can run as long as the clip,
|
|
48
|
+
* so 20 s of headroom plus 20 ms per character (3 min 40 s at 10k characters). A total budget: it
|
|
49
|
+
* also bounds the error-body read and the audio relayed; expiry while the audio is relayed ends it early.
|
|
50
|
+
*/
|
|
51
|
+
export declare function ttsTimeoutMs(textLength: number): number;
|
|
52
|
+
/**
|
|
53
|
+
* The stream's language: the requested one, else the default. nova-3 has no `detect_language` on a
|
|
54
|
+
* stream; `multi` is its multilingual mode, so a default of `auto` streams as `multi`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function sttStreamLanguage(language: string | null, defaultLanguage: string): string;
|
|
57
|
+
export { DEFAULT_RELAY_LIMITS, type DeepgramGrant, type DeepgramUrlOptions, type ElevenLabsGrant, type ProviderKey, type RelayAuditLine, type RelayHeadersInput, type RelayLimits, type RelayLimitsInput, type RelayLogger, type RelayRefusal, type RelayRequest, type RelayResult, type RelaySocket, type SpokenClip, type UpstreamDialer, type UpstreamHandlers, type UpstreamRejection, type UpstreamSocket, type VoiceAdmission, type VoiceGrant, type VoiceRelay, type VoiceRelayConfig, type VoiceRelayHost, type WsConstructor, type WsLike, createVoiceRelay, defaultDialer, isRelayRefusal, refusalStatusText, relayRequest, wsDialer, wsRelaySocket };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { _ as DEEPGRAM_HOST_PATTERN, t as DEFAULT_RELAY_LIMITS, h as ELEVENLABS_HOST, v as buildDeepgramUrl, g as buildElevenLabsUrl, n as createVoiceRelay, c as defaultDialer, b as formatAuditLine, y as isAllowedDeepgramHost, r as isRelayRefusal, i as refusalStatusText, a as relayRequest, o as sttStreamLanguage, s as ttsTimeoutMs, m as withoutKey, l as wsDialer, u as wsRelaySocket } from "../relay.mjs";
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire protocol v1 between a browser transport and a voice relay: two WebSockets (speech to text,
|
|
3
|
+
* streamed text to speech) and two HTTP routes (re-transcription of one utterance, one spoken clip).
|
|
4
|
+
* Frozen: a change to a frame is a breaking change and a new protocol version. Fields marked optional
|
|
5
|
+
* are additive and old clients ignore them.
|
|
6
|
+
*/
|
|
7
|
+
/** The version of the frames below. */
|
|
8
|
+
declare const VOICE_WIRE_PROTOCOL_VERSION = 1;
|
|
9
|
+
/** Where the relay routes live by default; a host may mount them elsewhere. */
|
|
10
|
+
declare const VOICE_RELAY_DEFAULT_PATHS: {
|
|
11
|
+
readonly stt: "/voice/transcribe-stream";
|
|
12
|
+
readonly tts: "/voice/speak-stream";
|
|
13
|
+
readonly retranscribe: "/voice/retranscribe";
|
|
14
|
+
readonly speak: "/voice/speak";
|
|
15
|
+
};
|
|
16
|
+
type VoiceRelayRoute = keyof typeof VOICE_RELAY_DEFAULT_PATHS;
|
|
17
|
+
/**
|
|
18
|
+
* Query parameters the relay reads itself. Every other query parameter (or, for `speak`, every other
|
|
19
|
+
* body field) is the host's opaque scope (`sessionId`, `organizationId`, `spaceId`, …).
|
|
20
|
+
* `token` carries a bearer, since a browser cannot set headers on `new WebSocket()`.
|
|
21
|
+
*/
|
|
22
|
+
declare const RELAY_QUERY_PARAMS: readonly ["token", "language", "encoding", "voiceId", "languageCode"];
|
|
23
|
+
/**
|
|
24
|
+
* `linear16`: raw 16 kHz mono PCM (Talk), so one capture feeds the socket, a pre-open buffer and the
|
|
25
|
+
* re-transcription ring. Absent: the provider sniffs the container (MediaRecorder webm/opus).
|
|
26
|
+
*/
|
|
27
|
+
type SttEncoding = 'linear16';
|
|
28
|
+
/** Closed list: the value selects upstream URL params. Anything else means the container format. */
|
|
29
|
+
declare function parseSttEncoding(value: unknown): SttEncoding | null;
|
|
30
|
+
/** The sample rate of `linear16` audio, on the STT socket and the re-transcription body alike. */
|
|
31
|
+
declare const LINEAR16_SAMPLE_RATE = 16000;
|
|
32
|
+
/** Client → relay text frame; every binary frame is audio. Any other text frame is dropped. */
|
|
33
|
+
type SttClientFrame = {
|
|
34
|
+
type: 'stop';
|
|
35
|
+
};
|
|
36
|
+
type SttServerFrame =
|
|
37
|
+
/** The provider stream is open; audio sent before this is dropped. */
|
|
38
|
+
{
|
|
39
|
+
type: 'ready';
|
|
40
|
+
} |
|
|
41
|
+
/** The provider heard speech start; `timestamp` is its stream time in seconds. */
|
|
42
|
+
{
|
|
43
|
+
type: 'speech_started';
|
|
44
|
+
timestamp?: number;
|
|
45
|
+
} | {
|
|
46
|
+
type: 'transcript';
|
|
47
|
+
transcript: string;
|
|
48
|
+
is_final: boolean;
|
|
49
|
+
speech_final: boolean;
|
|
50
|
+
/** Window start and length in stream seconds. */
|
|
51
|
+
start?: number;
|
|
52
|
+
duration?: number;
|
|
53
|
+
/** First word's start and last word's end (the window runs on through trailing silence). */
|
|
54
|
+
wordsStart?: number;
|
|
55
|
+
wordsEnd?: number;
|
|
56
|
+
/** Mean word confidence. */
|
|
57
|
+
confidence?: number;
|
|
58
|
+
/** The detected language in `multi` mode, else the stream's language. */
|
|
59
|
+
language?: string;
|
|
60
|
+
} |
|
|
61
|
+
/** The stream reaches its duration cap in `inMs`; a client that keeps listening opens a new one now. */
|
|
62
|
+
{
|
|
63
|
+
type: 'expiring';
|
|
64
|
+
inMs: number;
|
|
65
|
+
} | {
|
|
66
|
+
type: 'error';
|
|
67
|
+
error: string;
|
|
68
|
+
} |
|
|
69
|
+
/** The provider closed its stream. */
|
|
70
|
+
{
|
|
71
|
+
type: 'closed';
|
|
72
|
+
};
|
|
73
|
+
type SttCloseReason = 'max-duration' | 'idle-timeout' | 'upstream-error';
|
|
74
|
+
/** Every client frame is a short JSON text frame of at most this many bytes; binary frames are ignored. */
|
|
75
|
+
declare const TTS_MAX_CLIENT_FRAME_BYTES: number;
|
|
76
|
+
/** The PCM the TTS stream answers with: s16le, mono, this rate. */
|
|
77
|
+
declare const TTS_STREAM_SAMPLE_RATE = 24000;
|
|
78
|
+
type TtsClientFrame =
|
|
79
|
+
/** Reply text as it is written; `flush` asks the provider to speak what it holds now. */
|
|
80
|
+
{
|
|
81
|
+
type: 'text';
|
|
82
|
+
text: string;
|
|
83
|
+
flush?: boolean;
|
|
84
|
+
} |
|
|
85
|
+
/** No more text: the stream ends after the last audio. */
|
|
86
|
+
{
|
|
87
|
+
type: 'end';
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Relay → client. Per audio piece an optional `alignment` (the piece's characters) is followed by
|
|
91
|
+
* exactly ONE binary frame of PCM; a client pairs each binary frame with the alignment before it.
|
|
92
|
+
*/
|
|
93
|
+
type TtsServerFrame = {
|
|
94
|
+
type: 'ready';
|
|
95
|
+
sampleRate: number;
|
|
96
|
+
} | {
|
|
97
|
+
type: 'alignment';
|
|
98
|
+
text: string;
|
|
99
|
+
} | {
|
|
100
|
+
type: 'done';
|
|
101
|
+
} |
|
|
102
|
+
/** Only a status or error code, never provider text. */
|
|
103
|
+
{
|
|
104
|
+
type: 'error';
|
|
105
|
+
error: string;
|
|
106
|
+
};
|
|
107
|
+
type TtsCloseReason = 'done' | 'max-duration' | 'idle-timeout' | 'upstream-error' | 'text-limit';
|
|
108
|
+
declare const RELAY_CLOSE_CODES: {
|
|
109
|
+
/** `done`, `max-duration`, `idle-timeout`. */
|
|
110
|
+
readonly normal: 1000;
|
|
111
|
+
/** `text-limit` (TTS). */
|
|
112
|
+
readonly policy: 1008;
|
|
113
|
+
/** `upstream-error`. */
|
|
114
|
+
readonly upstreamError: 1011;
|
|
115
|
+
};
|
|
116
|
+
/** The body's content type: raw `linear16` at 16 kHz. */
|
|
117
|
+
declare const RETRANSCRIBE_CONTENT_TYPE = "audio/l16";
|
|
118
|
+
/** 30 s of 16 kHz mono linear16: the client's utterance ring holds no more. Above it: 413. */
|
|
119
|
+
declare const RETRANSCRIBE_MAX_BYTES = 960000;
|
|
120
|
+
/** The 200 answer of `POST retranscribe`; errors are 400/401/403/413/415/429/501/502/504 with `{ message }`. */
|
|
121
|
+
interface RetranscribeResult {
|
|
122
|
+
transcript: string;
|
|
123
|
+
/** The pinned language, else the detected one. */
|
|
124
|
+
language: string | null;
|
|
125
|
+
/** How sure the provider is of the detected language; null with a pinned language. */
|
|
126
|
+
languageConfidence: number | null;
|
|
127
|
+
/** How sure the provider is of the words, so a client can compare two languages' transcripts. */
|
|
128
|
+
confidence: number | null;
|
|
129
|
+
}
|
|
130
|
+
/** The JSON body of `POST speak` (answer: `audio/mpeg`). Other fields are the host's scope. */
|
|
131
|
+
interface SpeakRequestBody {
|
|
132
|
+
text: string;
|
|
133
|
+
voiceId?: string | null;
|
|
134
|
+
languageCode?: string | null;
|
|
135
|
+
/** Speak on the expressive (v4) model so `[[...]]` audio tags are performed; for short clips. */
|
|
136
|
+
expressive?: boolean;
|
|
137
|
+
/** Speak on the low-latency model. */
|
|
138
|
+
lowLatency?: boolean;
|
|
139
|
+
}
|
|
140
|
+
/** The error body of every relay HTTP answer other than 200. */
|
|
141
|
+
interface RelayErrorBody {
|
|
142
|
+
message: string;
|
|
143
|
+
code?: string;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Spoken languages a session may pin for speech-to-text, as Deepgram nova-3 codes.
|
|
147
|
+
* `multi` is nova-3's multilingual mode, which a relay default language of `auto` maps to.
|
|
148
|
+
* A closed list: the value is interpolated into the upstream URL.
|
|
149
|
+
*/
|
|
150
|
+
declare const STT_LANGUAGES: readonly ["multi", "en", "en-US", "en-GB", "de", "de-CH", "fr", "es", "it", "nl", "pt", "pt-BR", "pl", "sv", "da", "no", "fi", "tr", "ru", "uk", "ja", "ko", "hi"];
|
|
151
|
+
type SttLanguage = (typeof STT_LANGUAGES)[number];
|
|
152
|
+
/** The requested language when it is on the list, else null (the caller falls back to the deployment default). */
|
|
153
|
+
declare function parseSttLanguage(value: unknown): SttLanguage | null;
|
|
154
|
+
/**
|
|
155
|
+
* The ElevenLabs `language_code` for a pinned STT language: the bare ISO 639-1 part,
|
|
156
|
+
* or null for `multi` / anything malformed.
|
|
157
|
+
*/
|
|
158
|
+
declare function ttsLanguageCode(value: unknown): string | null;
|
|
159
|
+
/**
|
|
160
|
+
* ElevenLabs refuses `language_code` on models that do not enforce a language; today
|
|
161
|
+
* that is everything except the v2.5 Flash and Turbo models and the v3 / v4 family
|
|
162
|
+
* (which Talk's text-to-dialogue stream uses).
|
|
163
|
+
*/
|
|
164
|
+
declare function modelAcceptsLanguageCode(modelId: string): boolean;
|
|
165
|
+
/** Base language codes a term can be for (`multi` and regional variants fold into these). */
|
|
166
|
+
declare const SPEECH_TERM_LANGUAGES: [string, ...string[]];
|
|
167
|
+
declare const MAX_SPEECH_TERMS = 60;
|
|
168
|
+
declare const MAX_SPEECH_TERM_CHARS = 50;
|
|
169
|
+
declare const MAX_PRONUNCIATION_CHARS = 80;
|
|
170
|
+
/**
|
|
171
|
+
* Letters, digits, spaces and the punctuation names use; nothing that could act as markup. A stored
|
|
172
|
+
* term or pronunciation also has no double or trailing spaces (`tidySpeechTermText` folds them).
|
|
173
|
+
*/
|
|
174
|
+
declare const SPEECH_TERM_PATTERN: RegExp;
|
|
175
|
+
/** Folds whitespace the way stored terms are written, before they are validated. */
|
|
176
|
+
declare function tidySpeechTermText(value: string): string;
|
|
177
|
+
interface SpeechTerm {
|
|
178
|
+
/** The base language the term is for, one of `SPEECH_TERM_LANGUAGES` (`de`, `en`, …). */
|
|
179
|
+
language: string;
|
|
180
|
+
/** The word or name as it is written (at most `MAX_SPEECH_TERM_CHARS`). */
|
|
181
|
+
term: string;
|
|
182
|
+
/** How to say it, spelled the way a speaker of that language would read it (at most `MAX_PRONUNCIATION_CHARS`). */
|
|
183
|
+
pronunciation?: string;
|
|
184
|
+
}
|
|
185
|
+
/** Whether two entries name the same term: same language, same term ignoring case. */
|
|
186
|
+
declare function sameSpeechTerm(a: Pick<SpeechTerm, 'language' | 'term'>, b: Pick<SpeechTerm, 'language' | 'term'>): boolean;
|
|
187
|
+
/** The list with `entry` added, or replacing the same term in the same language. */
|
|
188
|
+
declare function withSpeechTerm(list: readonly SpeechTerm[], entry: SpeechTerm): SpeechTerm[];
|
|
189
|
+
/** The list without that term in that language. */
|
|
190
|
+
declare function withoutSpeechTerm(list: readonly SpeechTerm[], entry: Pick<SpeechTerm, 'language' | 'term'>): SpeechTerm[];
|
|
191
|
+
/** A term's base language matches the stream's; `multi` or no language means every term. */
|
|
192
|
+
declare function speechTermLanguageMatches(termLanguage: string, streamLanguage: SttLanguage | string | null): boolean;
|
|
193
|
+
/**
|
|
194
|
+
* Dev words Talk hears in every conversation about work, per base language. German speech uses
|
|
195
|
+
* the English words with German endings ("mergen", "gemergt"), which Deepgram heard as "Merchant".
|
|
196
|
+
*/
|
|
197
|
+
declare const BUILT_IN_KEYTERMS: Record<string, readonly string[]>;
|
|
198
|
+
/**
|
|
199
|
+
* Spellings German speech reads English dev words with. ElevenLabs reads "mergen" with a German
|
|
200
|
+
* g; respelled, the German voice says it the English way. Matched as whole words, case-insensitively.
|
|
201
|
+
*/
|
|
202
|
+
declare const BUILT_IN_PRONUNCIATIONS: Record<string, readonly {
|
|
203
|
+
term: string;
|
|
204
|
+
pronunciation: string;
|
|
205
|
+
}[]>;
|
|
206
|
+
/**
|
|
207
|
+
* Deepgram refuses a request whose keyterms exceed 500 tokens in total, and its tokenizer is not
|
|
208
|
+
* public. A term is counted at its UTF-8 bytes (spaces included) plus one per word, which no subword tokenizer
|
|
209
|
+
* exceeds (umlauts count twice), and the budget stays well below 500. Deepgram advises 20-50 terms.
|
|
210
|
+
*/
|
|
211
|
+
declare const KEYTERM_TOKEN_BUDGET = 400;
|
|
212
|
+
declare const MAX_KEYTERMS = 50;
|
|
213
|
+
/** The user's own terms may fill at most this share, so the assistant name and dev words always fit. */
|
|
214
|
+
declare const USER_KEYTERM_TOKEN_BUDGET = 240;
|
|
215
|
+
declare const MAX_USER_KEYTERMS = 30;
|
|
216
|
+
declare function estimateKeytermTokens(term: string): number;
|
|
217
|
+
/** A name fit to prompt with: short, made of words, no markup. Null when it is not. */
|
|
218
|
+
declare function cleanKeyterm(raw: string): string | null;
|
|
219
|
+
type KeytermSources = {
|
|
220
|
+
/** The stream's language; null or `multi` takes every language's terms. */
|
|
221
|
+
language: SttLanguage | string | null;
|
|
222
|
+
userTerms: readonly SpeechTerm[];
|
|
223
|
+
assistantName?: string | null;
|
|
224
|
+
/** Names of opted-in orgs, their projects and agents, most recently active first. */
|
|
225
|
+
names: readonly string[];
|
|
226
|
+
/** Names of the user's own sessions in opted-in orgs, most recently active first. */
|
|
227
|
+
sessionNames?: readonly string[];
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* The keyterms for one request in a fixed priority: the user's own terms (newest first, within
|
|
231
|
+
* their own share), the assistant's name, the built-in dev words, org/project/agent names, then
|
|
232
|
+
* own session names. Deduplicated
|
|
233
|
+
* case-insensitively, within {@link MAX_KEYTERMS} and {@link KEYTERM_TOKEN_BUDGET}; a term over the
|
|
234
|
+
* remaining budget is skipped and a shorter later one may still fit, so the result is deterministic.
|
|
235
|
+
*/
|
|
236
|
+
declare function buildKeyterms({ language, userTerms, assistantName, names, sessionNames }: KeytermSources): string[];
|
|
237
|
+
export { RETRANSCRIBE_CONTENT_TYPE as A, TTS_STREAM_SAMPLE_RATE as B, SttLanguage as C, LINEAR16_SAMPLE_RATE as D, ttsLanguageCode as E, SttClientFrame as F, VOICE_WIRE_PROTOCOL_VERSION as G, TtsCloseReason as H, SttCloseReason as I, VoiceRelayRoute as K, SttEncoding as L, RelayErrorBody as M, RetranscribeResult as N, RELAY_CLOSE_CODES as O, SpeakRequestBody as P, SttServerFrame as R, STT_LANGUAGES as S, parseSttLanguage as T, TtsServerFrame as U, TtsClientFrame as V, VOICE_RELAY_DEFAULT_PATHS as W, sameSpeechTerm as _, MAX_KEYTERMS as a, withSpeechTerm as b, MAX_SPEECH_TERM_CHARS as c, SPEECH_TERM_PATTERN as d, SpeechTerm as f, estimateKeytermTokens as g, cleanKeyterm as h, KeytermSources as i, RETRANSCRIBE_MAX_BYTES as j, RELAY_QUERY_PARAMS as k, MAX_USER_KEYTERMS as l, buildKeyterms as m, BUILT_IN_PRONUNCIATIONS as n, MAX_PRONUNCIATION_CHARS as o, USER_KEYTERM_TOKEN_BUDGET as p, parseSttEncoding as q, KEYTERM_TOKEN_BUDGET as r, MAX_SPEECH_TERMS as s, BUILT_IN_KEYTERMS as t, SPEECH_TERM_LANGUAGES as u, speechTermLanguageMatches as v, modelAcceptsLanguageCode as w, withoutSpeechTerm as x, tidySpeechTermText as y, TTS_MAX_CLIENT_FRAME_BYTES as z };
|