Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(tts): unify voice providers behind one synthesis router
nirholasc86dc506fea1
diff --git a/api/_lib/tts-edge.js b/api/_lib/tts-edge.jsnew file mode 100644index 000000000..3b2df7aa3--- /dev/null+++ b/api/_lib/tts-edge.js@@ -0,0 +1,243 @@+// @ts-check+// Free Microsoft Edge (Read Aloud) TTS lane — synthesis + the live voice list.+//+// Same unofficial WebSocket protocol as the edge-tts Python package+// (pypi.org/project/edge-tts): no API key, no account, no vendor bill, ~500+// neural voices across ~100 locales. That makes it the platform's zero-cost+// default lane, and the only lane an anonymous visitor can drive without a+// credit balance.+//+// Shared by the legacy per-provider proxy (api/tts/edge.js) and the unified+// router (api/_lib/voice-providers.js) so the protocol quirks below live in+// exactly one place.++import { createHash, randomUUID } from 'node:crypto';+import WebSocket from 'ws';++const TRUSTED_CLIENT_TOKEN = '6A5AA1D4EAFF4E9FB37E23D68491D6F4';+// speech.platform.bing.com is the host the readaloud protocol actually lives+// on. speech.microsoft.com (used previously) serves the Speech Studio web app,+// which answers every path with a 200 HTML page — hence the constant+// "Unexpected server response: 200" handshake failures.+const WSS_BASE = `wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=${TRUSTED_CLIENT_TOKEN}`;+const VOICE_LIST_URL = `https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=${TRUSTED_CLIENT_TOKEN}`;+const AUDIO_FORMAT = 'audio-24khz-48kbitrate-mono-mp3';+// Must track the Edg/ version in WS_HEADERS' User-Agent below. The endpoint+// 403s GEC versions it considers stale, so bump this alongside edge-tts+// releases (their constants.py carries the current known-good value).+const CHROMIUM_FULL_VERSION = '143.0.3650.75';++// e.g. "en-US-AriaNeural", "zh-CN-XiaoxiaoNeural"+export const EDGE_VOICE_RE = /^[a-zA-Z]{2,8}-[a-zA-Z]{2,8}-[a-zA-Z]{5,50}$/;+export const EDGE_RATE_RE = /^[+-]\d+%$/;+export const EDGE_PITCH_RE = /^[+-]\d+Hz$/;+export const EDGE_DEFAULT_VOICE = 'en-US-AriaNeural';++// Sec-MS-GEC DRM token, required by the readaloud endpoint since late 2024.+// SHA-256 of the current Windows file time (100ns ticks since 1601-01-01,+// rounded DOWN to the nearest 5 minutes) concatenated with the client token —+// same scheme the edge-tts reference implementation ships. Handshakes without+// it are intermittently rejected with a non-101 response ("Unexpected server+// response: 200").+function secMsGecToken() {+ const WIN_EPOCH_SECONDS = 11_644_473_600; // 1601-01-01 → 1970-01-01+ let seconds = Math.floor(Date.now() / 1000) + WIN_EPOCH_SECONDS;+ seconds -= seconds % 300;+ // seconds → 100ns ticks would overflow Number; appending seven zeros is the+ // same multiplication by 10^7 done in string space.+ return createHash('sha256')+ .update(`${seconds}0000000${TRUSTED_CLIENT_TOKEN}`)+ .digest('hex')+ .toUpperCase();+}++const WS_HEADERS = {+ Pragma: 'no-cache',+ 'Cache-Control': 'no-cache',+ Origin: 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',+ 'Accept-Encoding': 'gzip, deflate, br, zstd',+ 'Accept-Language': 'en-US,en;q=0.9',+ 'User-Agent':+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0',+};++function isoTimestamp() {+ return new Date().toISOString().replace(/\.\d+/, '.000');+}++function mkId() {+ return randomUUID().replace(/-/g, '');+}++function buildSsml(voice, text, rate, pitch) {+ const esc = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ return (+ `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>` ++ `<voice name='${voice}'>` ++ `<prosody pitch='${pitch}' rate='${rate}' volume='+0%'>${esc}</prosody>` ++ `</voice></speak>`+ );+}++/**+ * One synthesis attempt over the readaloud WebSocket.+ * @returns {Promise<Buffer>} the complete mp3 clip.+ */+export function synthesizeEdgeOnce(voice, text, rate = '+0%', pitch = '+0Hz') {+ return new Promise((resolve, reject) => {+ const connId = mkId();+ const url =+ `${WSS_BASE}&Sec-MS-GEC=${secMsGecToken()}` ++ `&Sec-MS-GEC-Version=1-${CHROMIUM_FULL_VERSION}&ConnectionId=${connId}`;+ const ws = new WebSocket(url, { headers: WS_HEADERS });++ const chunks = [];+ let finished = false;++ const timeout = setTimeout(() => {+ if (!finished) {+ ws.terminate();+ reject(new Error('edge-tts synthesis timed out'));+ }+ }, 30_000);++ ws.on('open', () => {+ const configMsg =+ `X-Timestamp:${isoTimestamp()}\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n` ++ JSON.stringify({+ context: {+ synthesis: {+ audio: {+ metadataoptions: {+ sentenceBoundaryEnabled: 'false',+ wordBoundaryEnabled: 'false',+ },+ outputFormat: AUDIO_FORMAT,+ },+ },+ },+ });+ ws.send(configMsg);++ const requestId = mkId();+ const ssmlMsg =+ `X-RequestId:${requestId}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${isoTimestamp()}\r\nPath:ssml\r\n\r\n` ++ buildSsml(voice, text, rate, pitch);+ ws.send(ssmlMsg);+ });++ ws.on('message', (data, isBinary) => {+ if (!isBinary) {+ const msg = data.toString();+ if (msg.includes('Path:turn.end')) {+ finished = true;+ clearTimeout(timeout);+ ws.close();+ resolve(Buffer.concat(chunks));+ }+ return;+ }+ // Binary frame: first 2 bytes = big-endian header length, then header, then audio.+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);+ const headerLen = buf.readUInt16BE(0);+ const header = buf.subarray(2, 2 + headerLen).toString();+ if (header.includes('Path:audio')) {+ chunks.push(buf.subarray(2 + headerLen));+ }+ });++ ws.on('error', (err) => {+ clearTimeout(timeout);+ reject(err);+ });++ ws.on('close', (code) => {+ clearTimeout(timeout);+ if (!finished) reject(new Error(`edge-tts WebSocket closed unexpectedly (${code})`));+ });+ });+}++/**+ * Synthesize with one retry. Microsoft's endpoint intermittently rejects the+ * WebSocket upgrade with an HTTP 200 instead of a 101 — a transient handshake+ * failure that almost always clears on an immediate second attempt.+ * @returns {Promise<Buffer>}+ */+export async function synthesizeEdge(voice, text, rate = '+0%', pitch = '+0Hz') {+ let lastErr = null;+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ return await synthesizeEdgeOnce(voice, text, rate, pitch);+ } catch (err) {+ lastErr = err;+ if (attempt === 0) await new Promise((r) => setTimeout(r, 250));+ }+ }+ throw lastErr;+}++// ── Voice catalog ────────────────────────────────────────────────────────────+// Microsoft publishes the full neural voice list at a plain HTTPS endpoint, so+// the catalog is always live rather than a hardcoded snapshot that rots. It+// changes on Microsoft's release cadence (weeks), hence the long TTL.++const VOICE_TTL_MS = 6 * 60 * 60 * 1000;+let voiceCache = null; // { at: epochMs, voices: [...] }++/**+ * Normalize one upstream entry to the platform's shared voice shape.+ * Upstream fields: ShortName, FriendlyName, Gender, Locale, VoiceTag.+ */+function normalizeEdgeVoice(v) {+ const tag = v.VoiceTag || {};+ // FriendlyName is "Microsoft Aria Online (Natural) - English (United States)";+ // the middle word is the only part worth showing in a picker.+ const short = String(v.ShortName || '');+ const display = short.split('-').slice(2).join('-').replace(/Neural$/, '') || short;+ return {+ id: short,+ name: display,+ provider: 'edge',+ gender: String(v.Gender || '').toLowerCase() || null,+ locale: v.Locale || null,+ language: v.Locale ? String(v.Locale).split('-')[0] : null,+ labels: {+ categories: Array.isArray(tag.ContentCategories) ? tag.ContentCategories : [],+ personalities: Array.isArray(tag.VoicePersonalities) ? tag.VoicePersonalities : [],+ },+ preview_url: null,+ };+}++/**+ * The live Edge neural voice catalog, cached per warm instance.+ * @returns {Promise<{ voices: Array, cached: boolean }>}+ * @throws {Error & { status:number }} 502 when Microsoft is unreachable.+ */+export async function listEdgeVoices({ force = false } = {}) {+ if (!force && voiceCache && Date.now() - voiceCache.at < VOICE_TTL_MS) {+ return { voices: voiceCache.voices, cached: true };+ }++ let resp;+ try {+ resp = await fetch(+ `${VOICE_LIST_URL}&Sec-MS-GEC=${secMsGecToken()}&Sec-MS-GEC-Version=1-${CHROMIUM_FULL_VERSION}`,+ { headers: WS_HEADERS, signal: AbortSignal.timeout(10_000) },+ );+ } catch (e) {+ throw Object.assign(new Error('Could not reach the Edge voice list'), { status: 502, cause: e });+ }+ if (!resp.ok) {+ throw Object.assign(new Error(`Edge voice list returned ${resp.status}`), { status: 502 });+ }++ const data = await resp.json();+ const voices = (Array.isArray(data) ? data : [])+ .filter((v) => v && typeof v.ShortName === 'string' && EDGE_VOICE_RE.test(v.ShortName))+ .map(normalizeEdgeVoice);++ voiceCache = { at: Date.now(), voices };+ return { voices, cached: false };+}diff --git a/api/_lib/tts-gemini.js b/api/_lib/tts-gemini.jsnew file mode 100644index 000000000..020d7e8f9--- /dev/null+++ b/api/_lib/tts-gemini.js@@ -0,0 +1,247 @@+// @ts-check+// Gemini native TTS lane — 30 prebuilt voices, controllable by prompt.+//+// Two rungs, in this order:+// 1. Vertex AI (`GOOGLE_CLOUD_PROJECT`) authenticated with the GCP service+// account and billed to the platform's Google credits. This is the lane+// that actually runs in production: same anchor doctrine as+// api/_lib/vertex-gemini.js — no third-party quota, no API key to rot,+// standing owner-approved spend (docs/ops/gcp-credits-plan.md).+// 2. The Generative Language API with `GEMINI_API_KEY`, for local dev and as+// a backstop when the Vertex token mint fails.+//+// Gemini TTS returns raw little-endian s16 PCM at 24 kHz, so every clip is+// wrapped in a RIFF/WAVE header before it leaves this module: browsers sniff+// the container, and the content-type we report stays truthful.+//+// Unlike every other lane here, the voice is only half the character: Gemini+// takes a natural-language style instruction in the prompt itself ("Say this+// in a warm, conspiratorial whisper:"), which the Voice Lab exposes as the+// "direction" field.++import { pcmToWav } from './tts-nvidia.js';+import { getGcpAccessToken } from './gcp-auth.js';+import { env } from './env.js';++// Preview TTS models. Flash is the real-time lane; Pro is the quality lane.+export const GEMINI_TTS_MODELS = [+ {+ id: 'gemini-2.5-flash-preview-tts',+ label: 'Gemini 2.5 Flash TTS',+ note: 'Fast · style-directable · 24 languages',+ },+ {+ id: 'gemini-2.5-pro-preview-tts',+ label: 'Gemini 2.5 Pro TTS',+ note: 'Highest quality · follows long directions',+ },+];+export const GEMINI_TTS_DEFAULT_MODEL = 'gemini-2.5-flash-preview-tts';+const GEMINI_MODEL_IDS = new Set(GEMINI_TTS_MODELS.map((m) => m.id));++export function isGeminiTtsModel(id) {+ return typeof id === 'string' && GEMINI_MODEL_IDS.has(id);+}++// Gemini's 30 prebuilt voices with the character Google documents for each.+// Ids are case-sensitive on the wire.+export const GEMINI_VOICES = [+ { id: 'Zephyr', character: 'Bright' },+ { id: 'Puck', character: 'Upbeat' },+ { id: 'Charon', character: 'Informative' },+ { id: 'Kore', character: 'Firm' },+ { id: 'Fenrir', character: 'Excitable' },+ { id: 'Leda', character: 'Youthful' },+ { id: 'Orus', character: 'Firm' },+ { id: 'Aoede', character: 'Breezy' },+ { id: 'Callirrhoe', character: 'Easy-going' },+ { id: 'Autonoe', character: 'Bright' },+ { id: 'Enceladus', character: 'Breathy' },+ { id: 'Iapetus', character: 'Clear' },+ { id: 'Umbriel', character: 'Easy-going' },+ { id: 'Algieba', character: 'Smooth' },+ { id: 'Despina', character: 'Smooth' },+ { id: 'Erinome', character: 'Clear' },+ { id: 'Algenib', character: 'Gravelly' },+ { id: 'Rasalgethi', character: 'Informative' },+ { id: 'Laomedeia', character: 'Upbeat' },+ { id: 'Achernar', character: 'Soft' },+ { id: 'Alnilam', character: 'Firm' },+ { id: 'Schedar', character: 'Even' },+ { id: 'Gacrux', character: 'Mature' },+ { id: 'Pulcherrima', character: 'Forward' },+ { id: 'Achird', character: 'Friendly' },+ { id: 'Zubenelgenubi', character: 'Casual' },+ { id: 'Vindemiatrix', character: 'Gentle' },+ { id: 'Sadachbia', character: 'Lively' },+ { id: 'Sadaltager', character: 'Knowledgeable' },+ { id: 'Sulafat', character: 'Warm' },+];+export const GEMINI_DEFAULT_VOICE = 'Kore';+const GEMINI_VOICE_IDS = new Set(GEMINI_VOICES.map((v) => v.id));++export function isGeminiVoice(id) {+ return typeof id === 'string' && GEMINI_VOICE_IDS.has(id);+}++// Gemini TTS emits 24 kHz mono s16.+const SAMPLE_RATE_HZ = 24_000;+const DEFAULT_TIMEOUT_MS = 45_000;++// The preview TTS models are not served from every Vertex region; us-central1+// is the one that has carried them since launch. Env-tunable so a region move+// needs no code change.+function vertexLocation() {+ return process.env.GOOGLE_CLOUD_LOCATION_TTS || 'us-central1';+}++/** True when either rung can serve. Read per call so late-injected env works. */+export function geminiTtsConfigured() {+ return Boolean(process.env.GOOGLE_CLOUD_PROJECT || env.GEMINI_API_KEY);+}++/** Which rungs are live, for the catalog endpoint's provider report. */+export function geminiTtsLanes() {+ return {+ vertex: Boolean(process.env.GOOGLE_CLOUD_PROJECT),+ apiKey: Boolean(env.GEMINI_API_KEY),+ };+}++function tagged(message, code, extra = {}) {+ return Object.assign(new Error(message), { code, ...extra });+}++/**+ * Compose the request payload. `direction` is a natural-language style+ * instruction Gemini honors as part of the prompt; it is prefixed rather than+ * sent as a separate field because that is the documented control surface.+ */+function buildBody({ text, voice, direction }) {+ const prompt = direction ? `${direction.replace(/:\s*$/, '')}: ${text}` : text;+ return {+ contents: [{ role: 'user', parts: [{ text: prompt }] }],+ generationConfig: {+ responseModalities: ['AUDIO'],+ speechConfig: {+ voiceConfig: { prebuiltVoiceConfig: { voiceName: voice } },+ },+ },+ };+}++/** Pull the base64 PCM out of a generateContent response. */+function extractAudio(data) {+ const parts = data?.candidates?.[0]?.content?.parts || [];+ for (const part of parts) {+ const inline = part?.inlineData || part?.inline_data;+ const b64 = inline?.data;+ if (typeof b64 === 'string' && b64.length) return Buffer.from(b64, 'base64');+ }+ const blocked = data?.promptFeedback?.blockReason || data?.candidates?.[0]?.finishReason;+ throw tagged(+ blocked ? `Gemini TTS returned no audio (${blocked})` : 'Gemini TTS returned no audio',+ blocked === 'SAFETY' || blocked === 'PROHIBITED_CONTENT' ? 'content_blocked' : 'provider_error',+ );+}++async function callGemini({ url, headers, body, timeoutMs }) {+ let resp;+ try {+ resp = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...headers },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (e) {+ throw tagged(`Could not reach Gemini TTS: ${e?.message || 'fetch failed'}`, 'provider_unreachable');+ }+ if (!resp.ok) {+ const detail = await resp.text().catch(() => '');+ const code =+ resp.status === 429 ? 'rate_limited'+ : resp.status === 401 || resp.status === 403 ? 'invalid_key'+ : 'provider_error';+ throw tagged(`Gemini TTS returned ${resp.status}: ${detail.slice(0, 300)}`, code, {+ status: resp.status,+ });+ }+ return extractAudio(await resp.json());+}++/**+ * Synthesize one clip. Resolves with the COMPLETE audio buffer so a caller can+ * fail over to another lane before a byte reaches the client.+ *+ * @param {{ text:string, voice?:string, model?:string, direction?:string, timeoutMs?:number }} opts+ * @returns {Promise<{ audio:Buffer, contentType:string, format:string, voiceName:string, model:string, lane:string, sampleRateHz:number }>}+ * @throws {Error & { code:string }} not_configured | invalid_key | rate_limited |+ * content_blocked | provider_unreachable | provider_error+ */+export async function synthesizeGeminiTts({+ text,+ voice = GEMINI_DEFAULT_VOICE,+ model = GEMINI_TTS_DEFAULT_MODEL,+ direction = '',+ timeoutMs = DEFAULT_TIMEOUT_MS,+} = {}) {+ if (!text || !String(text).trim()) throw tagged('text is required', 'invalid_argument');+ const voiceName = isGeminiVoice(voice) ? voice : GEMINI_DEFAULT_VOICE;+ const modelId = isGeminiTtsModel(model) ? model : GEMINI_TTS_DEFAULT_MODEL;+ const body = buildBody({ text: String(text), voice: voiceName, direction: String(direction || '') });++ const laneErrors = [];+ let pcm = null;+ let lane = '';++ // ── Rung 1: Vertex AI on platform credits ────────────────────────────────+ if (process.env.GOOGLE_CLOUD_PROJECT) {+ const project = process.env.GOOGLE_CLOUD_PROJECT;+ const location = vertexLocation();+ try {+ const token = await getGcpAccessToken();+ pcm = await callGemini({+ url:+ `https://${location}-aiplatform.googleapis.com/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${modelId}:generateContent`,+ headers: { authorization: `Bearer ${token}` },+ body,+ timeoutMs,+ });+ lane = 'vertex';+ } catch (e) {+ laneErrors.push(`vertex: ${e?.code || 'error'} ${e?.message || ''}`.trim());+ }+ }++ // ── Rung 2: Generative Language API key ──────────────────────────────────+ if (!pcm && env.GEMINI_API_KEY) {+ try {+ pcm = await callGemini({+ url: `https://generativelanguage.googleapis.com/v1beta/models/${modelId}:generateContent`,+ headers: { 'x-goog-api-key': env.GEMINI_API_KEY },+ body,+ timeoutMs,+ });+ lane = 'api-key';+ } catch (e) {+ laneErrors.push(`api-key: ${e?.code || 'error'} ${e?.message || ''}`.trim());+ }+ }++ if (!pcm) {+ if (!laneErrors.length) throw tagged('Gemini TTS is not configured', 'not_configured');+ throw tagged(`Gemini TTS failed — ${laneErrors.join('; ')}`, 'provider_error');+ }++ return {+ audio: pcmToWav(pcm, { sampleRateHz: SAMPLE_RATE_HZ }),+ contentType: 'audio/wav',+ format: 'wav',+ voiceName,+ model: modelId,+ lane,+ sampleRateHz: SAMPLE_RATE_HZ,+ };+}diff --git a/api/_lib/voice-providers.js b/api/_lib/voice-providers.jsnew file mode 100644index 000000000..0da2bbcb1--- /dev/null+++ b/api/_lib/voice-providers.js@@ -0,0 +1,460 @@+// @ts-check+// The platform's voice registry: one description of every synthesis lane, and+// one function that renders text on any of them.+//+// Before this file each lane had its own endpoint, its own voice-id vocabulary+// and its own billing story, so a picker could only ever show one provider's+// voices. Everything user-facing (/voice, the agent voice editor, the widget+// studio) now reads `VOICE_PROVIDERS` for what exists and posts to+// /api/tts/synthesize to hear it.+//+// Billing doctrine (owner policy 2026-08-06 — no free tier on a vendor-billed+// feature):+// free — no vendor invoice at all (Edge) or a free vendor tier+// (NVIDIA NIM). Served without charge.+// credits — the vendor bills the platform (ElevenLabs, OpenAI). Metered to+// the caller's prepaid credit wallet, or bypassed entirely with+// BYOK where the provider supports it.+// gcp — billed to the platform's Google credits under the standing+// owner-approved spend (docs/ops/gcp-credits-plan.md), same+// doctrine as the Vertex chat anchor. Free to the caller.++import { env } from './env.js';+import { TTS_ELEVEN_USD_PER_1K, TTS_OPENAI_USD_PER_1K } from './pricing/catalog.js';+import { synthesizeNvidiaTts, nvidiaTtsConfigured, VOICE_TO_MAGPIE } from './tts-nvidia.js';+import {+ synthesizeEdge,+ listEdgeVoices,+ EDGE_VOICE_RE,+ EDGE_RATE_RE,+ EDGE_PITCH_RE,+ EDGE_DEFAULT_VOICE,+} from './tts-edge.js';+import {+ synthesizeGeminiTts,+ geminiTtsConfigured,+ geminiTtsLanes,+ GEMINI_VOICES,+ GEMINI_TTS_MODELS,+ GEMINI_DEFAULT_VOICE,+ GEMINI_TTS_DEFAULT_MODEL,+} from './tts-gemini.js';+import { TTS_VOICES, DEFAULT_VOICE as OPENAI_DEFAULT_VOICE } from './tts-voices.js';+import {+ ELEVEN_BASE,+ DEFAULT_TTS_MODEL as ELEVEN_DEFAULT_MODEL,+ TTS_MODELS as ELEVEN_MODELS,+ isValidModel as isElevenModel,+ normalizeVoiceSettings,+ listVoices as listElevenVoices,+ isConfigured as elevenConfigured,+} from './elevenlabs.js';++export const OPENAI_TTS_MODELS = [+ { id: 'gpt-4o-mini-tts', label: 'GPT-4o mini TTS', note: 'Steerable · accepts a spoken direction' },+ { id: 'tts-1', label: 'TTS-1', note: 'Lowest latency' },+ { id: 'tts-1-hd', label: 'TTS-1 HD', note: 'Highest fidelity' },+];+const OPENAI_MODEL_IDS = new Set(OPENAI_TTS_MODELS.map((m) => m.id));+const OPENAI_DEFAULT_MODEL = 'gpt-4o-mini-tts';+const OPENAI_FORMATS = {+ mp3: 'audio/mpeg',+ opus: 'audio/ogg',+ aac: 'audio/aac',+ flac: 'audio/flac',+ wav: 'audio/wav',+};++const OPENAI_VOICE_IDS = new Set(TTS_VOICES.map((v) => v.id));+const NVIDIA_VOICE_IDS = new Set(Object.keys(VOICE_TO_MAGPIE));++const SYNTH_TIMEOUT_MS = 45_000;++/**+ * Static description of every lane. `id` values are the wire vocabulary shared+ * by /api/tts/catalog, /api/tts/synthesize and the client.+ */+export const VOICE_PROVIDERS = Object.freeze([+ {+ id: 'edge',+ label: 'Microsoft Edge',+ tagline: 'Free · ~500 neural voices · 100+ locales',+ billing: 'free',+ usdPer1k: 0,+ byok: false,+ clone: false,+ direction: false,+ anonymous: true,+ docs: 'https://learn.microsoft.com/azure/ai-services/speech-service/language-support',+ },+ {+ id: 'gemini',+ label: 'Google Gemini',+ tagline: 'Free on platform credits · 30 voices · style-directable',+ billing: 'gcp',+ usdPer1k: 0,+ byok: false,+ clone: false,+ direction: true,+ anonymous: true,+ docs: 'https://ai.google.dev/gemini-api/docs/speech-generation',+ },+ {+ id: 'nvidia',+ label: 'NVIDIA Magpie',+ tagline: 'Free · multilingual · the avatar real-time lane',+ billing: 'free',+ usdPer1k: 0,+ byok: false,+ clone: false,+ direction: false,+ anonymous: true,+ docs: 'https://build.nvidia.com/nvidia/magpie-tts-multilingual',+ },+ {+ id: 'openai',+ label: 'OpenAI',+ tagline: 'Credits · 11 voices · accepts a spoken direction',+ billing: 'credits',+ usdPer1k: TTS_OPENAI_USD_PER_1K,+ byok: false,+ clone: false,+ direction: true,+ anonymous: false,+ docs: 'https://platform.openai.com/docs/guides/text-to-speech',+ },+ {+ id: 'elevenlabs',+ label: 'ElevenLabs',+ tagline: 'Credits or your own key · full library · voice cloning',+ billing: 'credits',+ usdPer1k: TTS_ELEVEN_USD_PER_1K,+ byok: true,+ clone: true,+ direction: false,+ anonymous: false,+ docs: 'https://elevenlabs.io/docs/capabilities/text-to-speech',+ },+]);++export const PROVIDER_IDS = VOICE_PROVIDERS.map((p) => p.id);++export function getProvider(id) {+ return VOICE_PROVIDERS.find((p) => p.id === id) || null;+}++/** Which lanes this deployment can actually serve right now. */+export function providerAvailability({ elevenUserKey = false } = {}) {+ return {+ edge: true, // keyless by construction+ gemini: geminiTtsConfigured(),+ nvidia: nvidiaTtsConfigured(),+ openai: Boolean(env.OPENAI_API_KEY),+ elevenlabs: elevenConfigured() || elevenUserKey,+ };+}++/** The models selectable on a lane (empty when the lane has no model choice). */+export function providerModels(providerId) {+ if (providerId === 'elevenlabs') return ELEVEN_MODELS;+ if (providerId === 'openai') return OPENAI_TTS_MODELS;+ if (providerId === 'gemini') return GEMINI_TTS_MODELS;+ return [];+}++/** The lane's default voice id. */+export function providerDefaultVoice(providerId) {+ switch (providerId) {+ case 'edge': return EDGE_DEFAULT_VOICE;+ case 'gemini': return GEMINI_DEFAULT_VOICE;+ case 'nvidia': return OPENAI_DEFAULT_VOICE; // Magpie is addressed by OpenAI-style ids+ case 'openai': return OPENAI_DEFAULT_VOICE;+ default: return null;+ }+}++/**+ * USD this request will cost the caller. 0 for every free / GCP-credit lane+ * and for BYOK; the credit lanes bill per 1k characters.+ */+export function usdForSynthesis({ provider, chars, byok = false }) {+ if (byok) return 0;+ const p = getProvider(provider);+ if (!p || !p.usdPer1k) return 0;+ return Math.max(0.0001, (chars / 1000) * p.usdPer1k);+}++/** The credit-ledger action id for a metered lane, or null when free. */+export function creditActionFor(provider) {+ if (provider === 'elevenlabs') return 'tts.eleven';+ if (provider === 'openai') return 'tts.openai';+ return null;+}++// ── Catalogs ─────────────────────────────────────────────────────────────────++const GEMINI_VOICE_LIST = GEMINI_VOICES.map((v) => ({+ id: v.id,+ name: v.id,+ provider: 'gemini',+ gender: null,+ locale: null,+ language: 'multi',+ labels: { description: v.character, use_case: 'conversational' },+ preview_url: null,+}));++const OPENAI_VOICE_LIST = TTS_VOICES.map((v) => ({+ id: v.id,+ name: v.name,+ provider: 'openai',+ gender: null,+ locale: null,+ language: 'multi',+ labels: { description: v.description },+ preview_url: null,+}));++const NVIDIA_VOICE_LIST = TTS_VOICES.filter((v) => NVIDIA_VOICE_IDS.has(v.id)).map((v) => ({+ id: v.id,+ name: v.name,+ provider: 'nvidia',+ gender: null,+ locale: null,+ language: 'multi',+ labels: { description: v.description, persona: VOICE_TO_MAGPIE[v.id] },+ preview_url: null,+}));++/** Normalize an ElevenLabs catalog entry into the shared voice shape. */+function normalizeElevenVoice(v) {+ const labels = v.labels || {};+ return {+ id: v.voice_id,+ name: v.name,+ provider: 'elevenlabs',+ gender: labels.gender || null,+ locale: null,+ language: labels.language || 'multi',+ category: v.category || null,+ labels,+ preview_url: v.preview_url || null,+ };+}++/**+ * Every voice on one lane, in the shared shape.+ * @param {string} providerId+ * @param {{ elevenKey?: string|null, byok?: boolean }} [opts]+ * @returns {Promise<Array>}+ */+export async function listProviderVoices(providerId, { elevenKey = null, byok = false } = {}) {+ switch (providerId) {+ case 'edge': {+ const { voices } = await listEdgeVoices();+ return voices;+ }+ case 'gemini':+ return GEMINI_VOICE_LIST;+ case 'nvidia':+ return NVIDIA_VOICE_LIST;+ case 'openai':+ return OPENAI_VOICE_LIST;+ case 'elevenlabs': {+ if (!elevenKey) return [];+ const { voices } = await listElevenVoices(byok ? { apiKey: elevenKey } : {});+ return voices.map(normalizeElevenVoice);+ }+ default:+ return [];+ }+}++// ── Synthesis ────────────────────────────────────────────────────────────────++function tagged(message, code, extra = {}) {+ return Object.assign(new Error(message), { code, ...extra });+}++/**+ * Render text on one lane. Always resolves with the COMPLETE clip so callers+ * can meter, cache and fail over before a byte reaches the client.+ *+ * @param {{+ * provider: string, text: string, voiceId?: string, model?: string,+ * direction?: string, speed?: number, rate?: string, pitch?: string,+ * format?: string, language?: string, voiceSettings?: object|null,+ * elevenKey?: string|null,+ * }} opts+ * @returns {Promise<{ audio:Buffer, contentType:string, format:string, provider:string, model:string, voiceId:string, lane?:string }>}+ */+export async function synthesizeVoice(opts) {+ const provider = String(opts.provider || '');+ const text = String(opts.text || '').trim();+ if (!text) throw tagged('text is required', 'invalid_argument');++ switch (provider) {+ case 'edge': {+ const voiceId = EDGE_VOICE_RE.test(String(opts.voiceId || ''))+ ? String(opts.voiceId)+ : EDGE_DEFAULT_VOICE;+ // Edge takes prosody as SSML strings; accept the numeric `speed` every+ // other lane uses and convert, so one client control drives them all.+ const rate =+ opts.rate && EDGE_RATE_RE.test(opts.rate)+ ? opts.rate+ : `${Math.round((clampSpeed(opts.speed) - 1) * 100) >= 0 ? '+' : ''}${Math.round((clampSpeed(opts.speed) - 1) * 100)}%`;+ const pitch = opts.pitch && EDGE_PITCH_RE.test(opts.pitch) ? opts.pitch : '+0Hz';+ const audio = await synthesizeEdge(voiceId, text, rate, pitch);+ if (!audio.length) throw tagged('Edge TTS returned empty audio', 'provider_error');+ return {+ audio,+ contentType: 'audio/mpeg',+ format: 'mp3',+ provider,+ model: 'edge-readaloud',+ voiceId,+ };+ }++ case 'gemini': {+ const out = await synthesizeGeminiTts({+ text,+ voice: opts.voiceId,+ model: opts.model || GEMINI_TTS_DEFAULT_MODEL,+ direction: opts.direction,+ timeoutMs: SYNTH_TIMEOUT_MS,+ });+ return {+ audio: out.audio,+ contentType: out.contentType,+ format: out.format,+ provider,+ model: out.model,+ voiceId: out.voiceName,+ lane: out.lane,+ };+ }++ case 'nvidia': {+ const voiceId = OPENAI_VOICE_IDS.has(String(opts.voiceId))+ ? String(opts.voiceId)+ : OPENAI_DEFAULT_VOICE;+ const out = await synthesizeNvidiaTts({+ text,+ voice: voiceId,+ language: opts.language || 'en-US',+ format: opts.format === 'pcm' ? 'pcm' : 'wav',+ timeoutMs: SYNTH_TIMEOUT_MS,+ });+ return {+ audio: out.audio,+ contentType: out.contentType,+ format: out.format,+ provider,+ model: out.model,+ voiceId,+ };+ }++ case 'openai': {+ const key = env.OPENAI_API_KEY;+ if (!key) throw tagged('OpenAI is not configured', 'not_configured');+ const voiceId = OPENAI_VOICE_IDS.has(String(opts.voiceId))+ ? String(opts.voiceId)+ : OPENAI_DEFAULT_VOICE;+ const model = OPENAI_MODEL_IDS.has(String(opts.model))+ ? String(opts.model)+ : OPENAI_DEFAULT_MODEL;+ const formatKey = OPENAI_FORMATS[opts.format] ? opts.format : 'mp3';+ const payload = {+ model,+ voice: voiceId,+ input: text,+ response_format: formatKey,+ speed: clampSpeed(opts.speed),+ };+ // Only gpt-4o-mini-tts understands a spoken direction; sending it to+ // tts-1 is a 400.+ if (opts.direction && model === 'gpt-4o-mini-tts') payload.instructions = String(opts.direction);++ let resp;+ try {+ resp = await fetch('https://api.openai.com/v1/audio/speech', {+ method: 'POST',+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(SYNTH_TIMEOUT_MS),+ });+ } catch (e) {+ throw tagged(`Could not reach OpenAI: ${e?.message || 'fetch failed'}`, 'provider_unreachable');+ }+ if (!resp.ok) {+ const detail = await resp.text().catch(() => '');+ throw tagged(+ `OpenAI returned ${resp.status}: ${detail.slice(0, 300)}`,+ resp.status === 429 ? 'rate_limited' : 'provider_error',+ );+ }+ return {+ audio: Buffer.from(await resp.arrayBuffer()),+ contentType: OPENAI_FORMATS[formatKey],+ format: formatKey,+ provider,+ model,+ voiceId,+ };+ }++ case 'elevenlabs': {+ const apiKey = opts.elevenKey;+ if (!apiKey) throw tagged('ElevenLabs is not configured', 'not_configured');+ const voiceId = String(opts.voiceId || '').trim();+ if (!voiceId) throw tagged('voiceId is required for ElevenLabs', 'invalid_argument');+ const model = isElevenModel(opts.model) ? opts.model : ELEVEN_DEFAULT_MODEL;+ const settings = normalizeVoiceSettings(opts.voiceSettings || {});++ let resp;+ try {+ resp = await fetch(`${ELEVEN_BASE}/text-to-speech/${encodeURIComponent(voiceId)}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ accept: 'audio/mpeg',+ 'xi-api-key': apiKey,+ },+ body: JSON.stringify({ text, model_id: model, voice_settings: settings }),+ signal: AbortSignal.timeout(SYNTH_TIMEOUT_MS),+ });+ } catch (e) {+ throw tagged(`Could not reach ElevenLabs: ${e?.message || 'fetch failed'}`, 'provider_unreachable');+ }+ if (!resp.ok) {+ const detail = await resp.text().catch(() => '');+ throw tagged(+ `ElevenLabs returned ${resp.status}: ${detail.slice(0, 300)}`,+ resp.status === 429 ? 'rate_limited' : resp.status === 401 ? 'invalid_key' : 'provider_error',+ );+ }+ return {+ audio: Buffer.from(await resp.arrayBuffer()),+ contentType: 'audio/mpeg',+ format: 'mp3',+ provider,+ model,+ voiceId,+ };+ }++ default:+ throw tagged(`Unknown voice provider "${provider}"`, 'invalid_argument');+ }+}++function clampSpeed(speed) {+ const n = Number(speed);+ if (!Number.isFinite(n)) return 1;+ return Math.min(2, Math.max(0.5, n));+}++export { geminiTtsLanes };diff --git a/api/tts/catalog.js b/api/tts/catalog.jsnew file mode 100644index 000000000..b4bfac7d7--- /dev/null+++ b/api/tts/catalog.js@@ -0,0 +1,156 @@+/**+ * GET /api/tts/catalog+ *+ * Every voice the platform can synthesize, across every lane, in one shape.+ * This is what the Voice Lab picker and the agent voice editor read, so a+ * voice that appears in a picker is always a voice /api/tts/synthesize will+ * actually render.+ *+ * Query:+ * provider=edge|gemini|nvidia|openai|elevenlabs restrict to one lane+ * q=<text> substring filter (name, locale, labels)+ * language=<tag> e.g. "en", "ja"+ * limit=<n> cap voices returned (default 400, max 2000)+ *+ * Auth: optional. Anonymous callers get the keyless lanes (Edge, Gemini,+ * NVIDIA); the metered lanes (OpenAI, ElevenLabs) need a session, and+ * ElevenLabs additionally needs either the platform key or an `x-eleven-key`+ * BYOK header. A lane that cannot serve is reported in `providers` as false+ * rather than omitted, so the UI can explain *why* it is empty.+ *+ * Response: {+ * providers: [{ id, label, tagline, billing, usdPer1k, byok, clone,+ * direction, available, models, defaultVoice, reason? }],+ * voices: [{ id, name, provider, gender, locale, language, labels, preview_url }],+ * counts: { <provider>: n }, total, truncated+ * }+ */++import { cors, json, method, wrap } from '../_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { resolveElevenKey } from '../_lib/elevenlabs.js';+import {+ VOICE_PROVIDERS,+ providerAvailability,+ providerModels,+ providerDefaultVoice,+ listProviderVoices,+} from '../_lib/voice-providers.js';++const DEFAULT_LIMIT = 400;+const MAX_LIMIT = 2000;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, 'http://localhost');+ const only = url.searchParams.get('provider');+ const q = (url.searchParams.get('q') || '').trim().toLowerCase();+ const language = (url.searchParams.get('language') || '').trim().toLowerCase();+ const limit = Math.min(+ MAX_LIMIT,+ Math.max(1, Number(url.searchParams.get('limit')) || DEFAULT_LIMIT),+ );++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const signedIn = Boolean(session || bearer);+ const { apiKey: elevenKey, byok } = resolveElevenKey(req);++ const availability = providerAvailability({ elevenUserKey: byok });++ // A lane is listed even when it cannot serve, with the reason attached, so+ // the picker can show "sign in" or "add a key" instead of a silent gap.+ const providers = VOICE_PROVIDERS.map((p) => {+ let available = availability[p.id];+ let reason = null;+ if (!available) {+ reason = p.id === 'elevenlabs' ? 'Add your own ElevenLabs key below' : 'Not configured on this server';+ } else if (!p.anonymous && !signedIn) {+ available = false;+ reason = 'Sign in to use this lane';+ }+ return {+ ...p,+ available,+ reason,+ models: providerModels(p.id),+ defaultVoice: providerDefaultVoice(p.id),+ };+ });++ const wanted = providers.filter(+ (p) => p.available && (!only || p.id === only),+ );++ // One slow lane must never blank the whole picker: each catalog is fetched+ // independently and a failure degrades that lane to empty + a reason.+ const settled = await Promise.all(+ wanted.map(async (p) => {+ try {+ const voices = await listProviderVoices(p.id, { elevenKey, byok });+ return { id: p.id, voices };+ } catch (e) {+ console.warn('[tts/catalog] lane failed', p.id, e?.message || e);+ return { id: p.id, voices: [], error: e?.message || 'catalog unavailable' };+ }+ }),+ );++ const counts = {};+ let all = [];+ for (const lane of settled) {+ let voices = lane.voices;+ if (language) {+ voices = voices.filter(+ (v) =>+ String(v.language || '').toLowerCase().startsWith(language) ||+ String(v.locale || '').toLowerCase().startsWith(language),+ );+ }+ if (q) {+ voices = voices.filter((v) => {+ const hay = [+ v.name,+ v.id,+ v.locale,+ v.language,+ v.category,+ ...Object.values(v.labels || {}).flat(),+ ]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();+ return hay.includes(q);+ });+ }+ counts[lane.id] = voices.length;+ all = all.concat(voices);+ if (lane.error) {+ const p = providers.find((x) => x.id === lane.id);+ if (p) {+ p.available = false;+ p.reason = lane.error;+ }+ }+ }++ const total = all.length;+ const truncated = total > limit;++ return json(+ res,+ 200,+ {+ providers,+ voices: truncated ? all.slice(0, limit) : all,+ counts,+ total,+ truncated,+ signedIn,+ byok,+ },+ { 'cache-control': 'private, max-age=60' },+ );+});diff --git a/api/tts/edge.js b/api/tts/edge.jsindex 3f2830354..4fb88b7c7 100644--- a/api/tts/edge.js+++ b/api/tts/edge.js@@ -1,9 +1,9 @@/*** POST /api/tts/edge*- * Microsoft Edge TTS proxy using the same unofficial WebSocket protocol as- * the edge-tts Python package (pypi.org/project/edge-tts).- * No API key required — uses the public TrustedClientToken.+ * Microsoft Edge TTS proxy. No API key required — the protocol and the voice+ * catalog live in api/_lib/tts-edge.js, shared with the unified router+ * (/api/tts/synthesize) so the handshake quirks are implemented once.* Caches synthesized clips in R2 by sha256(voice + text + rate + pitch) for 30 days.** Body: { voice: string, text: string, rate?: string, pitch?: string }@@ -13,151 +13,18 @@* Response: audio/mpeg*/-import { createHash } from 'node:crypto';-import WebSocket from 'ws';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';import { limits } from '../_lib/rate-limit.js';import { sha256 } from '../_lib/crypto.js';import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';--const TRUSTED_CLIENT_TOKEN = '6A5AA1D4EAFF4E9FB37E23D68491D6F4';-// speech.platform.bing.com is the host the readaloud protocol actually lives-// on. speech.microsoft.com (used previously) serves the Speech Studio web app,-// which answers every path with a 200 HTML page — hence the constant-// "Unexpected server response: 200" handshake failures.-const WSS_BASE = `wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken=${TRUSTED_CLIENT_TOKEN}`;-const AUDIO_FORMAT = 'audio-24khz-48kbitrate-mono-mp3';-// Must track the Edg/ version in WS_HEADERS' User-Agent below. The endpoint-// 403s GEC versions it considers stale, so bump this alongside edge-tts-// releases (their constants.py carries the current known-good value).-const CHROMIUM_FULL_VERSION = '143.0.3650.75';--// Sec-MS-GEC DRM token, required by the readaloud endpoint since late 2024.-// SHA-256 of the current Windows file time (100ns ticks since 1601-01-01,-// rounded DOWN to the nearest 5 minutes) concatenated with the client token —-// same scheme the edge-tts reference implementation ships. Handshakes without-// it are intermittently rejected with a non-101 response ("Unexpected server-// response: 200").-function secMsGecToken() {- const WIN_EPOCH_SECONDS = 11_644_473_600; // 1601-01-01 → 1970-01-01- let seconds = Math.floor(Date.now() / 1000) + WIN_EPOCH_SECONDS;- seconds -= seconds % 300;- // seconds → 100ns ticks would overflow Number; appending seven zeros is the- // same multiplication by 10^7 done in string space.- return createHash('sha256')- .update(`${seconds}0000000${TRUSTED_CLIENT_TOKEN}`)- .digest('hex')- .toUpperCase();-}--const WS_HEADERS = {- Pragma: 'no-cache',- 'Cache-Control': 'no-cache',- Origin: 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',- 'Accept-Encoding': 'gzip, deflate, br, zstd',- 'Accept-Language': 'en-US,en;q=0.9',- 'User-Agent':- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0',-};--// e.g. "en-US-AriaNeural", "zh-CN-XiaoxiaoNeural"-const VOICE_RE = /^[a-zA-Z]{2,8}-[a-zA-Z]{2,8}-[a-zA-Z]{5,50}$/;-const RATE_RE = /^[+-]\d+%$/;-const PITCH_RE = /^[+-]\d+Hz$/;--function isoTimestamp() {- return new Date().toISOString().replace(/\.\d+/, '.000');-}--function mkId() {- return crypto.randomUUID().replace(/-/g, '');-}--function buildSsml(voice, text, rate, pitch) {- const esc = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');- return (- `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>` +- `<voice name='${voice}'>` +- `<prosody pitch='${pitch}' rate='${rate}' volume='+0%'>${esc}</prosody>` +- `</voice></speak>`- );-}--function synthesize(voice, text, rate, pitch) {- return new Promise((resolve, reject) => {- const connId = mkId();- const url =- `${WSS_BASE}&Sec-MS-GEC=${secMsGecToken()}` +- `&Sec-MS-GEC-Version=1-${CHROMIUM_FULL_VERSION}&ConnectionId=${connId}`;- const ws = new WebSocket(url, { headers: WS_HEADERS });-- const chunks = [];- let finished = false;-- const timeout = setTimeout(() => {- if (!finished) {- ws.terminate();- reject(new Error('edge-tts synthesis timed out'));- }- }, 30_000);-- ws.on('open', () => {- const configMsg =- `X-Timestamp:${isoTimestamp()}\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n` +- JSON.stringify({- context: {- synthesis: {- audio: {- metadataoptions: {- sentenceBoundaryEnabled: 'false',- wordBoundaryEnabled: 'false',- },- outputFormat: AUDIO_FORMAT,- },- },- },- });- ws.send(configMsg);-- const requestId = mkId();- const ssmlMsg =- `X-RequestId:${requestId}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${isoTimestamp()}\r\nPath:ssml\r\n\r\n` +- buildSsml(voice, text, rate, pitch);- ws.send(ssmlMsg);- });-- ws.on('message', (data, isBinary) => {- if (!isBinary) {- const msg = data.toString();- if (msg.includes('Path:turn.end')) {- finished = true;- clearTimeout(timeout);- ws.close();- resolve(Buffer.concat(chunks));- }- return;- }- // Binary frame: first 2 bytes = big-endian header length, then header, then audio.- const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);- const headerLen = buf.readUInt16BE(0);- const header = buf.subarray(2, 2 + headerLen).toString();- if (header.includes('Path:audio')) {- chunks.push(buf.subarray(2 + headerLen));- }- });-- ws.on('error', (err) => {- clearTimeout(timeout);- reject(err);- });-- ws.on('close', (code) => {- clearTimeout(timeout);- if (!finished) reject(new Error(`edge-tts WebSocket closed unexpectedly (${code})`));- });- });-}+import {+ synthesizeEdge,+ EDGE_VOICE_RE,+ EDGE_RATE_RE,+ EDGE_PITCH_RE,+ EDGE_DEFAULT_VOICE,+} from '../_lib/tts-edge.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;@@ -176,19 +43,19 @@ export default wrap(async (req, res) => {}const body = await readJson(req);- const voice = String(body.voice || 'en-US-AriaNeural').trim();+ const voice = String(body.voice || EDGE_DEFAULT_VOICE).trim();const text = String(body.text || '').trim();const rate = String(body.rate || '+0%').trim();const pitch = String(body.pitch || '+0Hz').trim();- if (!VOICE_RE.test(voice))+ if (!EDGE_VOICE_RE.test(voice))return error(res, 400, 'validation_error', 'invalid voice name');if (!text) return error(res, 400, 'validation_error', 'text is required');if (text.length > 500)return error(res, 400, 'validation_error', 'text exceeds 500 chars per request');- if (!RATE_RE.test(rate))+ if (!EDGE_RATE_RE.test(rate))return error(res, 400, 'validation_error', 'rate must be like +0% or -10%');- if (!PITCH_RE.test(pitch))+ if (!EDGE_PITCH_RE.test(pitch))return error(res, 400, 'validation_error', 'pitch must be like +0Hz or -5Hz');// ── R2 cache lookup ───────────────────────────────────────────────────────@@ -210,24 +77,11 @@ export default wrap(async (req, res) => {}// ── Synthesize via Microsoft Edge TTS ────────────────────────────────────- // Microsoft's unofficial Edge-TTS endpoint intermittently rejects the- // WebSocket upgrade with an HTTP 200 instead of a 101 ("Unexpected server- // response: 200") — a transient handshake failure that almost always clears- // on an immediate second attempt. Retry once before surfacing an error.let audioBuffer;- let synthErr;- for (let attempt = 0; attempt < 2; attempt++) {- try {- audioBuffer = await synthesize(voice, text, rate, pitch);- synthErr = null;- break;- } catch (err) {- synthErr = err;- if (attempt === 0) await new Promise((r) => setTimeout(r, 250));- }- }- if (synthErr) {- console.error('[tts/edge] synthesis failed after retry', synthErr);+ try {+ audioBuffer = await synthesizeEdge(voice, text, rate, pitch);+ } catch (err) {+ console.error('[tts/edge] synthesis failed after retry', err);return error(res, 502, 'upstream_error', 'Edge TTS synthesis failed');}diff --git a/api/tts/eleven/library.js b/api/tts/eleven/library.jsnew file mode 100644index 000000000..a6e2d14c3--- /dev/null+++ b/api/tts/eleven/library.js@@ -0,0 +1,185 @@+/**+ * GET /api/tts/eleven/library — search the public ElevenLabs Voice Library+ * POST /api/tts/eleven/library — add one of those voices to the account+ *+ * The Voice Library is the several-thousand-voice catalog ElevenLabs users+ * share publicly. It is a different surface from /api/tts/eleven/voices, which+ * lists only the voices already attached to the account. A shared voice cannot+ * be synthesized directly: it has to be added to an account first, which is+ * what the POST does (ElevenLabs returns a normal voice_id you can then pass+ * to /api/tts/synthesize).+ *+ * GET query:+ * q, gender, accent, age, category, language, use_cases, page_size (<=100), page+ * GET response: { voices: [...], has_more, page }+ *+ * POST body: { publicUserId, voiceId, name? }+ * POST response: { voiceId, name }+ *+ * BYOK: an `x-eleven-key` header adds the voice to the caller's own ElevenLabs+ * account instead of the platform's, which is the only way a user on a free+ * ElevenLabs plan can grow their own library without spending platform quota.+ */++import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { ELEVEN_BASE, resolveElevenKey, invalidateVoiceCache } from '../../_lib/elevenlabs.js';++const MAX_PAGE_SIZE = 100;+const DEFAULT_PAGE_SIZE = 30;++// Pass-through filters the shared-voices endpoint understands. Anything else a+// client sends is dropped rather than forwarded, so a typo can't turn into an+// opaque upstream 422.+const FILTERS = ['gender', 'accent', 'age', 'category', 'language', 'use_cases', 'descriptives'];++/** Trim a shared-voice record to the fields a picker actually renders. */+function normalize(v) {+ return {+ id: v.voice_id,+ publicUserId: v.public_owner_id,+ name: v.name,+ provider: 'elevenlabs',+ shared: true,+ description: v.description || null,+ gender: v.gender || null,+ accent: v.accent || null,+ age: v.age || null,+ category: v.category || null,+ language: v.language || 'multi',+ useCase: v.use_case || null,+ descriptive: v.descriptive || null,+ preview_url: v.preview_url || null,+ clonedByCount: v.cloned_by_count ?? null,+ usageCharacterCount1y: v.usage_character_count_1y ?? null,+ freeUsersAllowed: v.free_users_allowed !== false,+ labels: {+ gender: v.gender || null,+ accent: v.accent || null,+ age: v.age || null,+ use_case: v.use_case || null,+ descriptive: v.descriptive || null,+ },+ };+}++async function handleGet(req, res, apiKey) {+ const url = new URL(req.url, 'http://localhost');+ const pageSize = Math.min(+ MAX_PAGE_SIZE,+ Math.max(1, Number(url.searchParams.get('page_size')) || DEFAULT_PAGE_SIZE),+ );+ const page = Math.max(0, Number(url.searchParams.get('page')) || 0);++ const upstream = new URL(`${ELEVEN_BASE}/shared-voices`);+ upstream.searchParams.set('page_size', String(pageSize));+ upstream.searchParams.set('page', String(page));+ const q = (url.searchParams.get('q') || '').trim();+ if (q) upstream.searchParams.set('search', q);+ for (const f of FILTERS) {+ const value = (url.searchParams.get(f) || '').trim();+ if (value) upstream.searchParams.set(f, value);+ }++ let resp;+ try {+ resp = await fetch(upstream, {+ headers: { 'xi-api-key': apiKey },+ signal: AbortSignal.timeout(15_000),+ });+ } catch (e) {+ console.error('[tts/eleven/library] fetch failed', e);+ return error(res, 502, 'upstream_unreachable', 'Could not reach the ElevenLabs voice library');+ }+ if (!resp.ok) {+ const detail = await resp.text().catch(() => '');+ console.error('[tts/eleven/library] upstream error', resp.status, detail.slice(0, 300));+ return error(res, 502, 'upstream_error', `ElevenLabs returned ${resp.status}`);+ }++ const data = await resp.json();+ return json(+ res,+ 200,+ {+ voices: (data.voices || []).map(normalize),+ has_more: Boolean(data.has_more),+ page,+ page_size: pageSize,+ },+ { 'cache-control': 'private, max-age=300' },+ );+}++async function handlePost(req, res, apiKey, userId) {+ const rl = await limits.ttsSpeakUser(String(userId));+ if (!rl.success) return rateLimited(res, rl, 'Too many requests, try again later');++ const body = await readJson(req);+ const publicUserId = String(body.publicUserId || '').trim();+ const voiceId = String(body.voiceId || '').trim();+ const name = String(body.name || '').trim().slice(0, 64);++ if (!publicUserId) return error(res, 400, 'validation_error', 'publicUserId is required');+ if (!voiceId) return error(res, 400, 'validation_error', 'voiceId is required');+ if (!name) return error(res, 400, 'validation_error', 'name is required');++ let resp;+ try {+ resp = await fetch(+ `${ELEVEN_BASE}/voices/add/${encodeURIComponent(publicUserId)}/${encodeURIComponent(voiceId)}`,+ {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'xi-api-key': apiKey },+ body: JSON.stringify({ new_name: name }),+ signal: AbortSignal.timeout(20_000),+ },+ );+ } catch (e) {+ console.error('[tts/eleven/library] add failed', e);+ return error(res, 502, 'upstream_unreachable', 'Could not reach ElevenLabs');+ }++ if (!resp.ok) {+ // The quota and plan errors here are the ones users actually hit (voice+ // slots full, shared voice restricted to paid plans), so the upstream+ // detail is surfaced verbatim rather than flattened to "502".+ const detail = await resp.text().catch(() => '');+ let message = `ElevenLabs returned ${resp.status}`;+ try {+ const parsed = JSON.parse(detail);+ message = parsed?.detail?.message || parsed?.detail?.status || message;+ } catch {+ // Non-JSON body: keep the status-only message.+ }+ return error(res, resp.status === 401 ? 401 : 422, 'upstream_error', message);+ }++ const data = await resp.json().catch(() => ({}));+ invalidateVoiceCache();+ return json(res, 200, { voiceId: data.voice_id || voiceId, name });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer.userId;++ const { apiKey } = resolveElevenKey(req);+ if (!apiKey)+ return error(+ res,+ 503,+ 'not_configured',+ 'ElevenLabs is not configured on this server. Send your own key in the x-eleven-key header to browse the library.',+ );++ return req.method === 'POST'+ ? handlePost(req, res, apiKey, userId)+ : handleGet(req, res, apiKey);+});diff --git a/api/tts/synthesize.js b/api/tts/synthesize.jsnew file mode 100644index 000000000..ea2df89bc--- /dev/null+++ b/api/tts/synthesize.js@@ -0,0 +1,272 @@+/**+ * POST /api/tts/synthesize+ *+ * One endpoint that renders text on any voice lane the platform exposes:+ * Microsoft Edge, Gemini, NVIDIA Magpie, OpenAI and ElevenLabs. Callers pass+ * the `provider` + `voiceId` pair they got from /api/tts/catalog; everything+ * else (protocol, container, billing) is handled here.+ *+ * Body: {+ * provider: 'edge'|'gemini'|'nvidia'|'openai'|'elevenlabs',+ * voiceId: string,+ * text: string, // <= 1000 chars+ * model?: string, // lane-specific; validated per lane+ * direction?: string, // style instruction (gemini, gpt-4o-mini-tts)+ * speed?: number, // 0.5 .. 2.0+ * format?: string, // openai/nvidia only; other lanes fix theirs+ * language?: string, // nvidia+ * voice_settings?: object, // elevenlabs+ * }+ *+ * Billing (`x-tts-billing` reports which rung served):+ * free — Edge / NVIDIA: no vendor invoice, nothing charged.+ * gcp — Gemini on Vertex: platform Google credits, nothing charged.+ * byok — the request carried `x-eleven-key`: the user's ElevenLabs account pays.+ * credits — a vendor-billed lane on the platform key: metered to the caller's+ * prepaid credit wallet before the upstream call, refunded if the+ * clip never renders. 402 + top_up_url when short.+ * cached — R2 cache hit: no upstream call, nothing charged.+ *+ * Response: audio in the lane's container (content-type is always truthful).+ */++import { randomUUID } from 'node:crypto';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, method, wrap, error, json, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sha256 } from '../_lib/crypto.js';+import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';+import { chargeCreditsForAction, refundCredits } from '../_lib/credits.js';+import { resolveElevenKey } from '../_lib/elevenlabs.js';+import {+ getProvider,+ providerAvailability,+ synthesizeVoice,+ usdForSynthesis,+ creditActionFor,+} from '../_lib/voice-providers.js';++export const maxDuration = 60;++const MAX_TEXT = 1000;+const MAX_DIRECTION = 500;++// Upstream error code → HTTP status, so a client can tell "your fault" from+// "our fault" without parsing prose.+const STATUS_BY_CODE = {+ invalid_argument: 400,+ content_blocked: 422,+ not_configured: 503,+ invalid_key: 502,+ rate_limited: 429,+ provider_unreachable: 502,+ provider_error: 502,+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ let body;+ try {+ body = await readJson(req, 50_000);+ } catch (e) {+ return error(res, e.status || 400, 'bad_request', e.message);+ }++ const providerId = String(body.provider || 'edge').trim();+ const provider = getProvider(providerId);+ if (!provider) return error(res, 400, 'validation_error', `unknown provider "${providerId}"`);++ const text = String(body.text || '').trim();+ if (!text) return error(res, 400, 'validation_error', 'text is required');+ if (text.length > MAX_TEXT)+ return error(res, 400, 'validation_error', `text exceeds ${MAX_TEXT} characters`);++ const direction = String(body.direction || '').trim().slice(0, MAX_DIRECTION);++ // ── Auth + rate limit ─────────────────────────────────────────────────────+ // The keyless lanes serve anonymous visitors (that is the point of a free+ // lane); the vendor-billed ones need an identity to meter against.+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id ?? bearer?.userId ?? null;++ if (!provider.anonymous && !userId)+ return error(res, 401, 'unauthorized', `sign in to use the ${provider.label} voices`);++ if (userId) {+ const rl = await limits.ttsSpeakUser(String(userId));+ if (!rl.success) return rateLimited(res, rl, 'TTS rate limit exceeded, try again later');+ } else {+ const rl = await limits.ttsSpeakIp(clientIp(req));+ if (!rl.success)+ return rateLimited(res, rl, 'TTS rate limit exceeded, sign in for a higher limit');+ }++ const { apiKey: elevenKey, byok } = resolveElevenKey(req);+ const availability = providerAvailability({ elevenUserKey: byok });+ if (!availability[providerId]) {+ return error(+ res,+ 503,+ 'not_configured',+ providerId === 'elevenlabs'+ ? 'ElevenLabs is not configured on this server. Send your own key in the x-eleven-key header.'+ : `${provider.label} is not configured on this server`,+ );+ }++ const voiceId = String(body.voiceId || '').trim();+ const model = String(body.model || '').trim();+ const speed = Number(body.speed);+ const format = typeof body.format === 'string' ? body.format : undefined;+ const language = typeof body.language === 'string' ? body.language : undefined;+ const voiceSettings =+ body.voice_settings && typeof body.voice_settings === 'object' ? body.voice_settings : null;++ // ── R2 cache ──────────────────────────────────────────────────────────────+ // Checked BEFORE metering: a cached clip costs nothing upstream, so it is+ // never charged. BYOK clips are keyed separately — they render on a+ // different account and must not be served from (or into) the shared cache.+ const cacheHash = await sha256(+ [+ providerId,+ voiceId,+ text,+ model,+ direction,+ Number.isFinite(speed) ? speed : '',+ format || '',+ language || '',+ voiceSettings ? JSON.stringify(voiceSettings) : '',+ byok ? 'byok' : '',+ ].join('\x00'),+ );+ const cacheKey = `tts/synth/${providerId}/${cacheHash}`;++ const cached = await headObject(cacheKey).catch(() => null);+ if (cached) {+ try {+ const buf = await getObjectBuffer(cacheKey);+ // HeadObjectCommand output is the raw S3 shape (PascalCase).+ res.setHeader('content-type', cached.ContentType || 'audio/mpeg');+ res.setHeader('content-length', String(buf.length));+ res.setHeader('x-tts-provider', providerId);+ res.setHeader('x-tts-cache', 'hit');+ res.setHeader('x-tts-billing', 'cached');+ res.setHeader('cache-control', 'private, max-age=86400');+ return res.end(buf);+ } catch {+ // Cache read failed — synthesize fresh.+ }+ }++ // ── Metering ──────────────────────────────────────────────────────────────+ const action = creditActionFor(providerId);+ const usd = usdForSynthesis({ provider: providerId, chars: text.length, byok });+ const billing =+ byok && providerId === 'elevenlabs' ? 'byok'+ : provider.billing === 'gcp' ? 'gcp'+ : usd > 0 ? 'credits'+ : 'free';++ let creditCharge = null;+ if (billing === 'credits' && action) {+ const idempotencyKey = `tts:${providerId}:${randomUUID()}`;+ try {+ const charged = await chargeCreditsForAction({+ user: session || { id: userId },+ action,+ usd,+ refType: 'tts',+ refId: cacheHash,+ idempotencyKey,+ meta: { chars: text.length, provider: providerId, voiceId, model },+ });+ creditCharge = { idempotencyKey, chargedUsd: charged.chargedUsd };+ } catch (err) {+ if (err?.code === 'insufficient_credits') {+ return json(res, 402, {+ error: 'insufficient_credits',+ feature: action,+ available_usd: err.available_usd,+ required_usd: err.required_usd,+ top_up_url: '/credits',+ message:+ `${provider.label} synthesis is metered to your credit balance. ` ++ 'Top up with $THREE at /credits, switch to a free voice lane, ' ++ (provider.byok ? 'or bring your own key.' : 'or pick a free provider.'),+ });+ }+ throw err;+ }+ }++ const refundMetering = async () => {+ if (creditCharge?.chargedUsd > 0) {+ await refundCredits({+ userId,+ amountUsd: creditCharge.chargedUsd,+ action,+ refType: 'tts',+ refId: cacheHash,+ idempotencyKey: `${creditCharge.idempotencyKey}:refund`,+ meta: { reason: 'synthesis_failed' },+ }).catch((e) => console.warn('[tts/synthesize] credit refund failed:', e?.message || e));+ }+ };++ // ── Synthesize ────────────────────────────────────────────────────────────+ let out;+ try {+ out = await synthesizeVoice({+ provider: providerId,+ text,+ voiceId,+ model,+ direction,+ speed,+ format,+ language,+ voiceSettings,+ elevenKey,+ });+ } catch (err) {+ console.error('[tts/synthesize] lane failed', providerId, err?.code, err?.message);+ await refundMetering();+ return error(+ res,+ STATUS_BY_CODE[err?.code] || 502,+ err?.code || 'upstream_error',+ err?.message || `${provider.label} synthesis failed`,+ );+ }++ if (!out.audio?.length) {+ await refundMetering();+ return error(res, 502, 'upstream_error', `${provider.label} returned empty audio`);+ }++ putObject({+ key: cacheKey,+ body: out.audio,+ contentType: out.contentType,+ metadata: { 'created-at': new Date().toISOString() },+ }).catch((e) => console.warn('[tts/synthesize] R2 cache write failed:', e.message));++ res.statusCode = 200;+ res.setHeader('content-type', out.contentType);+ res.setHeader('content-length', String(out.audio.length));+ res.setHeader('x-tts-provider', providerId);+ res.setHeader('x-tts-voice', out.voiceId);+ res.setHeader('x-tts-model', out.model);+ res.setHeader('x-tts-format', out.format);+ res.setHeader('x-tts-cache', 'miss');+ res.setHeader('x-tts-billing', billing);+ if (out.lane) res.setHeader('x-tts-lane', out.lane);+ if (creditCharge?.chargedUsd > 0)+ res.setHeader('x-tts-charged-usd', creditCharge.chargedUsd.toFixed(6));+ res.setHeader('cache-control', 'private, max-age=86400');+ return res.end(out.audio);+});diff --git a/pages/voice.html b/pages/voice.htmlindex ed11ac8b5..e87e8a7cf 100644--- a/pages/voice.html+++ b/pages/voice.html@@ -671,8 +671,192 @@}.vl-byok-row input:focus { border-color: #ffffff; }+ /* ── Voice browser ──────────────────────────── */+ .vb-filters {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ margin-bottom: 12px;+ }+ .vb-filters input[type="search"] {+ flex: 1;+ min-width: 200px;+ padding: 10px 12px;+ background: #070707;+ border: 1px solid #212121;+ border-radius: 9px;+ color: #e8e8e8;+ font: inherit;+ font-size: 14px;+ outline: none;+ transition: border-color 0.15s;+ }+ .vb-filters input[type="search"]:focus { border-color: #ffffff; }+ .vb-filters select {+ padding: 10px 12px;+ background: #070707;+ border: 1px solid #212121;+ border-radius: 9px;+ color: #e8e8e8;+ font: inherit;+ font-size: 14px;+ cursor: pointer;+ outline: none;+ }+ .vb-filters select:focus { border-color: #ffffff; }+ .vb-pills {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ margin-bottom: 16px;+ }+ .vb-pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ background: rgba(255,255,255,0.04);+ border: 1px solid #1a1a1a;+ color: #999999;+ padding: 7px 12px;+ border-radius: 999px;+ font: 500 12.5px system-ui, sans-serif;+ cursor: pointer;+ transition: background 0.12s, color 0.12s, border-color 0.12s;+ }+ .vb-pill:hover:not(.disabled) {+ background: rgba(255,255,255,0.08);+ border-color: rgba(255,255,255,0.3);+ color: #ffffff;+ }+ .vb-pill:focus-visible { outline: 2px solid #ffffff; outline-offset: 2px; }+ .vb-pill.active {+ background: #ffffff;+ border-color: #ffffff;+ color: #000000;+ }+ .vb-pill.disabled { opacity: 0.4; cursor: not-allowed; }+ .vb-pill-billing {+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ padding: 2px 6px;+ border-radius: 4px;+ background: rgba(61,193,255,0.14);+ color: #3dc1ff;+ }+ .vb-pill-billing[data-billing="credits"] {+ background: rgba(255,193,61,0.14);+ color: #ffc13d;+ }+ .vb-pill.active .vb-pill-billing { background: rgba(0,0,0,0.1); color: #000000; }+ .vb-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ gap: 10px;+ }+ .vb-card {+ background: #070707;+ border: 1px solid #1a1a1a;+ border-radius: 12px;+ padding: 14px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ cursor: pointer;+ transition: border-color 0.15s, transform 0.15s, background 0.15s;+ }+ .vb-card:hover { border-color: #303030; background: #0b0b0b; transform: translateY(-1px); }+ .vb-card.selected { border-color: #ffffff; background: #0d0d0d; }+ .vb-card-top {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 8px;+ }+ .vb-card-name {+ margin: 0;+ font-size: 14px;+ font-weight: 600;+ color: #e8e8e8;+ line-height: 1.3;+ word-break: break-word;+ }+ .vb-badge {+ flex: none;+ font-size: 10px;+ font-weight: 600;+ letter-spacing: 0.03em;+ text-transform: uppercase;+ color: #888888;+ border: 1px solid #222222;+ border-radius: 5px;+ padding: 2px 6px;+ white-space: nowrap;+ }+ .vb-tags { display: flex; gap: 5px; flex-wrap: wrap; }+ .vb-tag {+ font-size: 11px;+ color: #777777;+ background: rgba(255,255,255,0.05);+ border-radius: 4px;+ padding: 2px 7px;+ }+ .vb-card-desc {+ margin: 0;+ font-size: 12px;+ line-height: 1.5;+ color: #777777;+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ }+ .vb-card-actions { display: flex; gap: 6px; margin-top: auto; padding-top: 4px; }+ .vb-skeleton {+ height: 132px;+ cursor: default;+ background: linear-gradient(90deg, #0a0a0a 25%, #111111 50%, #0a0a0a 75%);+ background-size: 200% 100%;+ animation: vb-shimmer 1.4s ease-in-out infinite;+ }+ @keyframes vb-shimmer {+ 0% { background-position: 200% 0; }+ 100% { background-position: -200% 0; }+ }+ @media (prefers-reduced-motion: reduce) {+ .vb-skeleton { animation: none; }+ .vb-card:hover { transform: none; }+ }+ .vb-more { margin-top: 14px; width: 100%; justify-content: center; }+ #vbStatus[data-tone="err"] { color: var(--err, #ff6b6b); }+ #vbStatus[data-tone="ok"] { color: var(--ok, #4ade80); }+ #vbStatus[data-tone="warn"] { color: var(--warn, #ffc13d); }++ /* Playground extras: direction + speed */+ .vl-pg-field input[type="text"] {+ width: 100%;+ padding: 10px 12px;+ background: #070707;+ border: 1px solid #212121;+ border-radius: 9px;+ color: #e8e8e8;+ font: inherit;+ font-size: 14px;+ outline: none;+ transition: border-color 0.15s;+ }+ .vl-pg-field input[type="text"]:focus { border-color: #ffffff; }+ .vl-pg-field input[type="range"] { width: 100%; accent-color: #ffffff; }+ .vl-pg-billing {+ font-size: 12px;+ color: #777777;+ margin-top: 10px;+ }+/* ── Responsive ─────────────────────────────── */@media (max-width: 640px) {+ .vb-grid { grid-template-columns: 1fr; }.vl-root { padding: 20px 16px 60px; }.vl-header h1 { font-size: 26px; }.vl-wave-wrap { height: 160px; }@@ -777,6 +961,28 @@</div><!-- ── Voice Library ─────────────────────────── -->+ <div class="vl-section" id="browserSection">+ <div class="vl-section-head">+ <h2 class="vl-section-title" data-i18n="voice.browse_voices">Browse voices</h2>+ <span class="vl-pg-hint" id="vbStatus" role="status" aria-live="polite" style="font-size:12px;color:#777777;"></span>+ </div>+ <div class="vl-card">+ <div class="vl-card-body">+ <div class="vb-filters">+ <label class="sr-only" for="vbSearch">Search voices</label>+ <input type="search" id="vbSearch" placeholder="Search by name, accent, or use case..." autocomplete="off" spellcheck="false" />+ <label class="sr-only" for="vbLanguage">Language</label>+ <select id="vbLanguage">+ <option value="">All languages</option>+ </select>+ </div>+ <div class="vb-pills" id="vbProviders" role="group" aria-label="Voice providers"></div>+ <div class="vb-grid" id="vbGrid"></div>+ <button class="vl-btn vl-btn-ghost vl-btn-sm vb-more" id="vbMore" type="button" hidden>Show more</button>+ </div>+ </div>+ </div>+<div class="vl-section" id="librarySection"><div class="vl-section-head"><h2 class="vl-section-title" data-i18n="voice.my_voices">My Voices</h2>@@ -800,9 +1006,25 @@<div class="vl-pg-field"><label for="pgVoice" data-i18n="voice.voice">Voice</label><select id="pgVoice">- <option value="" disabled selected data-i18n="voice.clone_a_voice_first">Clone a voice first</option>+ <option value="" disabled selected data-i18n="voice.pick_a_voice_first">Pick a voice above</option></select></div>+ <div class="vl-pg-field" id="pgModelField" hidden>+ <label for="pgModel" data-i18n="voice.model">Model</label>+ <select id="pgModel"></select>+ </div>+ </div>+ <div class="vl-pg-row" id="pgDirectionRow" hidden>+ <div class="vl-pg-field">+ <label for="pgDirection" data-i18n="voice.direction">Direction — how it should be said</label>+ <input type="text" id="pgDirection" maxlength="200" placeholder="Warm and unhurried, like you're telling a friend a secret" />+ </div>+ </div>+ <div class="vl-pg-row">+ <div class="vl-pg-field">+ <label for="pgSpeed">Speed <span id="pgSpeedVal">1.00×</span></label>+ <input type="range" id="pgSpeed" min="0.5" max="2" step="0.05" value="1" aria-describedby="pgSpeedVal" />+ </div></div><textarea class="vl-pg-textarea" id="pgText" placeholder="Type something to hear it spoken..." maxlength="500">Hello, I'm a three.ws agent. Nice to meet you.</textarea><div class="vl-pg-samples" id="pgSamples">diff --git a/src/voice/voice-browser.js b/src/voice/voice-browser.jsnew file mode 100644index 000000000..9726ca1e9--- /dev/null+++ b/src/voice/voice-browser.js@@ -0,0 +1,444 @@+// Multi-provider voice browser for the Voice Lab.+//+// Reads /api/tts/catalog (every lane the deployment can serve, in one shape)+// plus /api/tts/eleven/library (the public ElevenLabs Voice Library, which is+// paged upstream and therefore fetched on demand rather than merged into the+// catalog). Previews play through /api/tts/synthesize, so what you hear in the+// browser is exactly what the playground and an agent will render.++import { withElevenKey } from './eleven-key.js';++const PREVIEW_LINE = "Hey, I'm your agent. This is how I sound.";++const BILLING_COPY = {+ free: { label: 'Free', title: 'No vendor cost. Never charged.' },+ gcp: { label: 'Free', title: 'Runs on the platform Google Cloud credits. Never charged.' },+ credits: { label: 'Credits', title: 'Metered to your prepaid credit balance, per 1k characters.' },+};++// One <audio> for the whole browser: starting a preview always stops the one+// already playing, so a fast clicker never stacks overlapping voices.+const previewAudio = new Audio();+let previewToken = 0;++function esc(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++function debounce(fn, ms) {+ let t = 0;+ return (...args) => {+ clearTimeout(t);+ t = setTimeout(() => fn(...args), ms);+ };+}++/** Human tags for a card, deduped and capped so a card never overflows. */+function voiceTags(v) {+ const raw = [+ v.gender,+ v.accent,+ v.age,+ v.locale,+ v.labels?.description,+ v.labels?.use_case,+ v.labels?.descriptive,+ v.labels?.persona,+ ...(v.labels?.personalities || []),+ ...(v.labels?.categories || []),+ ];+ const seen = new Set();+ const out = [];+ for (const tag of raw) {+ const t = String(tag || '').trim();+ if (!t) continue;+ const key = t.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ out.push(t);+ if (out.length === 4) break;+ }+ return out;+}++export function mountVoiceBrowser({ root, onSelect }) {+ const els = {+ pills: root.querySelector('#vbProviders'),+ search: root.querySelector('#vbSearch'),+ language: root.querySelector('#vbLanguage'),+ grid: root.querySelector('#vbGrid'),+ status: root.querySelector('#vbStatus'),+ more: root.querySelector('#vbMore'),+ };++ let providers = [];+ let allVoices = [];+ let filtered = [];+ let shown = 0;+ let activeProvider = 'all';+ let selectedKey = null;+ let libraryPage = 0;+ let libraryHasMore = false;+ let reqToken = 0;++ const PAGE = 60;++ function setStatus(text, tone = 'info') {+ els.status.textContent = text;+ els.status.dataset.tone = tone;+ }++ function providerById(id) {+ return providers.find((p) => p.id === id) || null;+ }++ function keyOf(v) {+ return `${v.provider}:${v.id}`;+ }++ // ── Rendering ─────────────────────────────────────────────────────────────++ function renderPills() {+ const total = allVoices.length;+ const buttons = [+ `<button class="vb-pill${activeProvider === 'all' ? ' active' : ''}" data-provider="all" aria-pressed="${activeProvider === 'all'}">All voices</button>`,+ ...providers.map((p) => {+ const disabled = !p.available && p.id !== 'elevenlabs-library';+ return (+ `<button class="vb-pill${activeProvider === p.id ? ' active' : ''}${disabled ? ' disabled' : ''}"` ++ ` data-provider="${esc(p.id)}" aria-pressed="${activeProvider === p.id}"` ++ `${disabled ? ` title="${esc(p.reason || 'Unavailable')}"` : ` title="${esc(p.tagline)}"`}>` ++ `${esc(p.label)}` ++ `<span class="vb-pill-billing" data-billing="${esc(p.billing)}">${esc(BILLING_COPY[p.billing]?.label || '')}</span>` ++ `</button>`+ );+ }),+ ];+ els.pills.innerHTML = buttons.join('');+ els.pills.setAttribute('aria-label', `${total} voices across ${providers.length} providers`);+ }++ function renderCards(reset = true) {+ if (reset) shown = 0;+ const next = filtered.slice(0, shown + PAGE);+ shown = next.length;++ if (!next.length) {+ const p = providerById(activeProvider);+ els.grid.innerHTML =+ `<div class="vl-empty">` ++ `<div class="vl-empty-title">${p && !p.available ? esc(p.label) + ' is unavailable' : 'No voices match'}</div>` ++ esc(+ p && !p.available+ ? p.reason || 'This lane is not configured on this server.'+ : 'Clear the search or pick a different provider. The free Edge lane alone has around 500 voices.',+ ) ++ `</div>`;+ els.more.hidden = true;+ return;+ }++ els.grid.innerHTML = next.map(cardHtml).join('');+ els.more.hidden = shown >= filtered.length && !libraryHasMore;+ els.more.textContent = libraryHasMore && shown >= filtered.length+ ? 'Load more from the ElevenLabs library'+ : `Show more (${filtered.length - shown} left)`;+ }++ function cardHtml(v) {+ const key = keyOf(v);+ const p = providerById(v.shared ? 'elevenlabs-library' : v.provider);+ const tags = voiceTags(v);+ const billing = BILLING_COPY[p?.billing || 'free'];+ return `+ <article class="vb-card${selectedKey === key ? ' selected' : ''}" data-key="${esc(key)}">+ <div class="vb-card-top">+ <h3 class="vb-card-name">${esc(v.name)}</h3>+ <span class="vb-badge" data-provider="${esc(v.provider)}" title="${esc(billing?.title || '')}">${esc(p?.label || v.provider)}</span>+ </div>+ ${tags.length ? `<div class="vb-tags">${tags.map((t) => `<span class="vb-tag">${esc(t)}</span>`).join('')}</div>` : ''}+ ${v.description ? `<p class="vb-card-desc">${esc(v.description)}</p>` : ''}+ <div class="vb-card-actions">+ <button class="vl-btn vl-btn-ghost vl-btn-sm" data-act="preview" data-key="${esc(key)}">Preview</button>+ ${+ v.shared+ ? `<button class="vl-btn vl-btn-primary vl-btn-sm" data-act="add" data-key="${esc(key)}">Add to my voices</button>`+ : `<button class="vl-btn vl-btn-primary vl-btn-sm" data-act="use" data-key="${esc(key)}">Use this voice</button>`+ }+ </div>+ </article>`;+ }++ // ── Filtering ─────────────────────────────────────────────────────────────++ function applyFilter() {+ const q = els.search.value.trim().toLowerCase();+ const lang = els.language.value;+ filtered = allVoices.filter((v) => {+ if (activeProvider !== 'all') {+ const owner = v.shared ? 'elevenlabs-library' : v.provider;+ if (owner !== activeProvider) return false;+ }+ if (lang) {+ const l = String(v.locale || v.language || '').toLowerCase();+ if (l !== 'multi' && !l.startsWith(lang)) return false;+ }+ if (q) {+ const hay = [v.name, v.id, v.locale, v.description, ...voiceTags(v)]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();+ if (!hay.includes(q)) return false;+ }+ return true;+ });+ renderCards(true);+ setStatus(+ `${filtered.length} voice${filtered.length === 1 ? '' : 's'}` ++ (activeProvider === 'all' ? ` across ${providers.filter((p) => p.available).length} providers` : ''),+ );+ }++ // ── Loading ───────────────────────────────────────────────────────────────++ async function loadCatalog() {+ const token = ++reqToken;+ setStatus('Loading voices…');+ els.grid.innerHTML = Array.from({ length: 6 })+ .map(() => '<div class="vb-card vb-skeleton" aria-hidden="true"></div>')+ .join('');+ els.more.hidden = true;++ let data;+ try {+ const r = await fetch('/api/tts/catalog?limit=2000', {+ credentials: 'include',+ headers: withElevenKey({}),+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ data = await r.json();+ } catch (err) {+ if (token !== reqToken) return;+ els.grid.innerHTML =+ '<div class="vl-empty"><div class="vl-empty-title">Could not load the voice catalog</div>' ++ `${esc(err.message)}. Check your connection and retry.</div>`;+ setStatus('Catalog unavailable', 'err');+ return;+ }+ if (token !== reqToken) return;++ // The shared ElevenLabs library is a distinct browsing mode, not a lane:+ // its voices must be added to an account before they can be synthesized.+ const elevenlabs = data.providers.find((p) => p.id === 'elevenlabs');+ providers = [+ ...data.providers,+ {+ id: 'elevenlabs-library',+ label: 'ElevenLabs Library',+ tagline: 'Thousands of community voices — add one to your account to use it',+ billing: 'credits',+ available: Boolean(elevenlabs?.available),+ reason: elevenlabs?.reason || null,+ shared: true,+ },+ ];+ allVoices = data.voices;++ renderPills();+ populateLanguages();+ applyFilter();+ }++ function populateLanguages() {+ const seen = new Map();+ for (const v of allVoices) {+ const loc = String(v.locale || '');+ if (!loc) continue;+ const primary = loc.split('-')[0];+ if (!seen.has(primary)) seen.set(primary, loc);+ }+ const names =+ typeof Intl !== 'undefined' && Intl.DisplayNames+ ? new Intl.DisplayNames(['en'], { type: 'language' })+ : null;+ const options = [...seen.keys()]+ .map((code) => ({ code, label: names?.of(code) || code }))+ .sort((a, b) => a.label.localeCompare(b.label));+ const prev = els.language.value;+ els.language.innerHTML =+ '<option value="">All languages</option>' ++ options.map((o) => `<option value="${esc(o.code)}">${esc(o.label)}</option>`).join('');+ if (prev) els.language.value = prev;+ }++ async function loadLibraryPage({ reset = false } = {}) {+ if (reset) {+ libraryPage = 0;+ allVoices = allVoices.filter((v) => !v.shared);+ }+ const token = ++reqToken;+ setStatus('Searching the ElevenLabs library…');++ const params = new URLSearchParams({ page: String(libraryPage), page_size: '48' });+ const q = els.search.value.trim();+ if (q) params.set('q', q);+ if (els.language.value) params.set('language', els.language.value);++ let data;+ try {+ const r = await fetch(`/api/tts/eleven/library?${params}`, {+ credentials: 'include',+ headers: withElevenKey({}),+ });+ if (!r.ok) {+ const body = await r.json().catch(() => ({}));+ throw new Error(body.error_description || body.message || `HTTP ${r.status}`);+ }+ data = await r.json();+ } catch (err) {+ if (token !== reqToken) return;+ setStatus(`Library unavailable: ${err.message}`, 'err');+ els.grid.innerHTML =+ '<div class="vl-empty"><div class="vl-empty-title">The ElevenLabs library needs a key</div>' ++ 'Save your own ElevenLabs API key below, or sign in on a deployment where the platform key is set.</div>';+ els.more.hidden = true;+ return;+ }+ if (token !== reqToken) return;++ libraryHasMore = data.has_more;+ libraryPage += 1;+ allVoices = allVoices.concat(data.voices);+ applyFilter();+ }++ // ── Actions ───────────────────────────────────────────────────────────────++ function findVoice(key) {+ return allVoices.find((v) => keyOf(v) === key) || null;+ }++ async function preview(key, btn) {+ const v = findVoice(key);+ if (!v) return;+ const token = ++previewToken;++ previewAudio.pause();+ previewAudio.currentTime = 0;++ // A shared-library voice ships a real preview clip; playing it costs+ // nothing and needs no account, so never synthesize one.+ if (v.preview_url) {+ previewAudio.src = v.preview_url;+ previewAudio.play().catch(() => setStatus('Autoplay was blocked — press Preview again.', 'warn'));+ return;+ }++ const original = btn.textContent;+ btn.disabled = true;+ btn.textContent = 'Loading…';+ try {+ const r = await fetch('/api/tts/synthesize', {+ method: 'POST',+ credentials: 'include',+ headers: withElevenKey({ 'content-type': 'application/json' }),+ body: JSON.stringify({ provider: v.provider, voiceId: v.id, text: PREVIEW_LINE }),+ });+ if (!r.ok) {+ const body = await r.json().catch(() => ({}));+ throw new Error(body.error_description || body.message || `HTTP ${r.status}`);+ }+ if (token !== previewToken) return;+ const blob = await r.blob();+ if (previewAudio.src.startsWith('blob:')) URL.revokeObjectURL(previewAudio.src);+ previewAudio.src = URL.createObjectURL(blob);+ await previewAudio.play().catch(() => {});+ const billing = r.headers.get('x-tts-billing');+ setStatus(billing === 'credits' ? 'Preview rendered — charged to credits.' : 'Preview rendered.');+ } catch (err) {+ setStatus(`Preview failed: ${err.message}`, 'err');+ } finally {+ btn.disabled = false;+ btn.textContent = original;+ }+ }++ async function addSharedVoice(key, btn) {+ const v = findVoice(key);+ if (!v) return;+ const original = btn.textContent;+ btn.disabled = true;+ btn.textContent = 'Adding…';+ try {+ const r = await fetch('/api/tts/eleven/library', {+ method: 'POST',+ credentials: 'include',+ headers: withElevenKey({ 'content-type': 'application/json' }),+ body: JSON.stringify({ publicUserId: v.publicUserId, voiceId: v.id, name: v.name }),+ });+ const body = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(body.error_description || body.message || `HTTP ${r.status}`);+ setStatus(`"${v.name}" added to your ElevenLabs voices.`, 'ok');+ btn.textContent = 'Added';+ onSelect?.({ ...v, id: body.voiceId, provider: 'elevenlabs', shared: false });+ } catch (err) {+ setStatus(`Could not add the voice: ${err.message}`, 'err');+ btn.disabled = false;+ btn.textContent = original;+ }+ }++ function select(key) {+ const v = findVoice(key);+ if (!v) return;+ selectedKey = key;+ root.querySelectorAll('.vb-card').forEach((c) => {+ c.classList.toggle('selected', c.dataset.key === key);+ });+ onSelect?.(v);+ }++ // ── Wiring ────────────────────────────────────────────────────────────────++ els.pills.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-provider]');+ if (!btn || btn.classList.contains('disabled')) return;+ activeProvider = btn.dataset.provider;+ renderPills();+ if (activeProvider === 'elevenlabs-library') loadLibraryPage({ reset: true });+ else applyFilter();+ });++ const onSearch = debounce(() => {+ if (activeProvider === 'elevenlabs-library') loadLibraryPage({ reset: true });+ else applyFilter();+ }, 250);+ els.search.addEventListener('input', onSearch);+ els.language.addEventListener('change', onSearch);++ els.more.addEventListener('click', () => {+ if (shown >= filtered.length && libraryHasMore) loadLibraryPage();+ else renderCards(false);+ });++ els.grid.addEventListener('click', (e) => {+ const actionBtn = e.target.closest('[data-act]');+ if (actionBtn) {+ const { act, key } = actionBtn.dataset;+ if (act === 'preview') preview(key, actionBtn);+ else if (act === 'add') addSharedVoice(key, actionBtn);+ else if (act === 'use') select(key);+ return;+ }+ const card = e.target.closest('.vb-card');+ if (card && !card.classList.contains('vb-skeleton')) select(card.dataset.key);+ });++ loadCatalog();++ return { reload: loadCatalog, getProviders: () => providers };+}