The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
One pace for every voice: talking speed relative to the language's default voice (PR 1972)
Tim Gutberletbfa2fb2bf192
diff --git a/apps/agent/src/greeting-prewarm.ts b/apps/agent/src/greeting-prewarm.tsindex bb924b1e..e30981b9 100644--- a/apps/agent/src/greeting-prewarm.ts+++ b/apps/agent/src/greeting-prewarm.ts@@ -10,7 +10,8 @@ import type { ApiClient } from './api-client.ts'import { type BusinessHours, inMainLanguage, withWorkspaceLanguage } from './call-session.ts'import { type CallConfig, configForAssistant, isRealtime, pipelineOfAssistant } from './config.ts'import { createGreetingCache, greetingKey, synthesize } from './greeting-cache.ts'-import { createTts, greetingVoice, spokeWithBackup, talkingSpeedOf } from './pipeline.ts'+import { createTts, greetingVoice, spokeWithBackup, talkingSpeedOf, ttsFor, ttsModelOf } from './pipeline.ts'+import { ensurePaces } from './voice-pace.ts'import { forHours } from './prompt.ts'/**@@ -83,6 +84,16 @@ export async function prewarmGreetings(const body = (await api.greetings()) as { greetings?: GreetingEntry[] } | nullconst entries = body?.greetings ?? []if (!entries.length) return+ // Every assistant's voice pace (voice-pace.ts), so its calls and greetings speak at the uniform pace at once.+ const paceConfig = await loadConfig()+ for (const entry of entries) {+ const config = paceConfig+ if (isRealtime(config) || config.tts.provider !== 'elevenlabs') continue+ const language = mainLanguageOf(entry.assistant.languages)+ const tts = ttsFor(config.tts, entry.assistant.voice, language)+ if (tts.provider === 'elevenlabs')+ await ensurePaces({ apiKey: tts.apiKey, voiceId: tts.voiceId, model: ttsModelOf(tts), language })+ }const missing = []for (const greeting of greetingsToMake(entries, await loadConfig()))if (!cache.has(greeting.key)) missing.push(greeting)diff --git a/apps/agent/src/pipeline.ts b/apps/agent/src/pipeline.tsindex dcf1ccc2..9e727e8c 100644--- a/apps/agent/src/pipeline.ts+++ b/apps/agent/src/pipeline.ts@@ -4,7 +4,29 @@// voice-activity model: that saves the CPU a small server does not have, and the endpointing delay.// Or, when an admin picked one, a realtime model alone: it hears the caller and answers in its own voice.// The worker only sees LiveKit's interfaces and `CompleteJson`.-import { DEFAULT_VOICE_MODELS, noPrivateEndpointText, noTrainingFields, voiceModelFor, anyModeLanguages, fluxRecognizes, sttHears, type HearingModel, type Language, mainLanguageOf, otherLanguagesOf, providerLanguageCode, type SpeakingVoice, spokenLanguages, defaultVoiceFor, providerDefaultVoices, ELEVENLABS_VOICE_SETTINGS, SILENCE_FIRST_GAP_DEFAULT_S, TALKING_SPEED_PCT_DEFAULT, type TalkingSpeed, talkingSpeedPctOf } from '@linedesk/actions'+import {+ DEFAULT_VOICE_MODELS,+ noPrivateEndpointText,+ noTrainingFields,+ voiceModelFor,+ anyModeLanguages,+ fluxRecognizes,+ sttHears,+ type HearingModel,+ type Language,+ mainLanguageOf,+ otherLanguagesOf,+ providerLanguageCode,+ type SpeakingVoice,+ spokenLanguages,+ defaultVoiceFor,+ providerDefaultVoices,+ ELEVENLABS_VOICE_SETTINGS,+ SILENCE_FIRST_GAP_DEFAULT_S,+ TALKING_SPEED_PCT_DEFAULT,+ type TalkingSpeed,+ talkingSpeedPctOf,+} from '@linedesk/actions'import { DEFAULT_API_CONNECT_OPTIONS, tts as ttsTypes, type voice } from '@livekit/agents'import * as assemblyai from '@livekit/agents-plugin-assemblyai'import * as cartesia from '@livekit/agents-plugin-cartesia'@@ -13,8 +35,16 @@ import * as elevenlabs from '@livekit/agents-plugin-elevenlabs'import * as openai from '@livekit/agents-plugin-openai'import type { AssistantVoice } from '@linedesk/db/types'import { spellCodesTransform } from './spoken-codes.ts'-import { type AgentConfig, type CallConfig, isRealtime, llmDefaults, type RealtimeConfig, type TtsConfig } from './config.ts'+import {+ type AgentConfig,+ type CallConfig,+ isRealtime,+ llmDefaults,+ type RealtimeConfig,+ type TtsConfig,+} from './config.ts'import type { GreetingVoice } from './greeting-cache.ts'+import { paceCorrectedPct } from './voice-pace.ts'import { quotedData } from './prompt.ts'import type { CompleteJson } from './summary.ts'import { type GatedSession, gateReplies, type RealtimeReplyGate } from './realtime-replies.ts'@@ -48,10 +78,17 @@ const EAGER_END_OF_TURN = 0.5* The model: the assistant's own voice model when it is one of that provider's (voiceModelFor; call.start sends the* level's), else the provider's default.*/-export function ttsFor(tts: AgentConfig['tts'], assistantVoice?: AssistantVoice | null, language: Language = 'en'): TtsConfig & { voiceId?: string } {+export function ttsFor(+ tts: AgentConfig['tts'],+ assistantVoice?: AssistantVoice | null,+ language: Language = 'en',+): TtsConfig & { voiceId?: string } {const own = assistantVoice?.voice_id- const modelOf = (c: TtsConfig) => voiceModelFor(c.provider, assistantVoice?.provider === c.provider ? assistantVoice.model : undefined, c.model) || undefined- if (own && assistantVoice.provider === tts.provider) return { provider: tts.provider, apiKey: tts.apiKey, model: modelOf(tts), voiceId: own }+ const modelOf = (c: TtsConfig) =>+ voiceModelFor(c.provider, assistantVoice?.provider === c.provider ? assistantVoice.model : undefined, c.model) ||+ undefined+ if (own && assistantVoice.provider === tts.provider)+ return { provider: tts.provider, apiKey: tts.apiKey, model: modelOf(tts), voiceId: own }const other = own ? tts.others?.find(o => o.provider === assistantVoice.provider) : undefinedif (other) return { ...other, model: modelOf(other), voiceId: own }return {@@ -63,11 +100,21 @@ export function ttsFor(tts: AgentConfig['tts'], assistantVoice?: AssistantVoice}/** The voice id a call uses (see ttsFor). */-export const voiceFor = (tts: AgentConfig['tts'], assistantVoice?: AssistantVoice | null, language: Language = 'en'): string | undefined =>- ttsFor(tts, assistantVoice, language).voiceId+export const voiceFor = (+ tts: AgentConfig['tts'],+ assistantVoice?: AssistantVoice | null,+ language: Language = 'en',+): string | undefined => ttsFor(tts, assistantVoice, language).voiceId/** What a cached line in the assistant's voice is keyed by (with its text): provider, model, voice and speed. */-export function greetingVoice(config: AgentConfig, call: { assistant?: ({ voice?: AssistantVoice | null; languages?: Parameters<typeof mainLanguageOf>[0] } & TalkingSpeedFields) | null }) {+export function greetingVoice(+ config: AgentConfig,+ call: {+ assistant?:+ | ({ voice?: AssistantVoice | null; languages?: Parameters<typeof mainLanguageOf>[0] } & TalkingSpeedFields)+ | null+ },+) {const tts = ttsFor(config.tts, call.assistant?.voice, mainLanguageOf(call.assistant?.languages))return { provider: tts.provider, model: ttsModelOf(tts), voiceId: tts.voiceId, speed: talkingSpeedOf(call.assistant) }}@@ -110,7 +157,10 @@ export function callLanguagesOf(* The assistant as this call speaks: its languages replaced by the call's (callLanguagesOf), so the instructions name* the languages the speech recognition and voice can handle.*/-export function withCallLanguages<A extends { languages?: unknown }>(assistant: A | null, { main, others }: CallLanguages): A | null {+export function withCallLanguages<A extends { languages?: unknown }>(+ assistant: A | null,+ { main, others }: CallLanguages,+): A | null {if (!assistant) return assistantreturn { ...assistant, languages: { main, mode: others.length ? 'allowed' : 'english', allowed: [...others] } }}@@ -149,7 +199,8 @@ export function deepgramChoice(model: string, languages: CallLanguages = ENGLISHif (englishOnly(languages)) return { protocol: flux ? 'flux' : 'nova', model }const { main, others, everyLanguage } = languagesconst hinted = (codes: readonly Language[]) => codes.map(code => providerLanguageCode(code, 'deepgram'))- if (flux && fluxCovers(languages)) return { protocol: 'flux', model: FLUX_MULTILINGUAL, languageHint: hinted([main, ...others]) }+ if (flux && fluxCovers(languages))+ return { protocol: 'flux', model: FLUX_MULTILINGUAL, languageHint: hinted([main, ...others]) }// Only Nova-3 detects the language on a live stream (`multi`).return {protocol: 'nova',@@ -167,11 +218,45 @@ export function deepgramChoice(model: string, languages: CallLanguages = ENGLISH* but it cut callers off at a short pause in two thirds of the turns. Without a mode the LiveKit plugin ends every* turn after 100 ms of silence.*/-export const assemblyAiTurnMode = (fastTurnEnd = false): 'balanced' | 'max_accuracy' => (fastTurnEnd ? 'balanced' : 'max_accuracy')+export const assemblyAiTurnMode = (fastTurnEnd = false): 'balanced' | 'max_accuracy' =>+ fastTurnEnd ? 'balanced' : 'max_accuracy'/** AssemblyAI steers toward at most 10 languages; with more (or every language) it is not steered and hears all it knows. */const ASSEMBLYAI_MAX_LANGUAGES = 10/** The languages AssemblyAI's Universal-3 Pro streaming takes in `language_codes` (its API reference, 2026-11-17). */-const ASSEMBLYAI_LANGUAGES: ReadonlySet<string> = new Set(['af', 'ar', 'yue', 'ca', 'da', 'nl', 'en', 'et', 'fi', 'fr', 'gl', 'de', 'he', 'hi', 'it', 'ja', 'ko', 'zh', 'mr', 'no', 'nn', 'fa', 'pt', 'ro', 'ru', 'es', 'sv', 'tr', 'ur', 'vi', 'xh', 'zu'])+const ASSEMBLYAI_LANGUAGES: ReadonlySet<string> = new Set([+ 'af',+ 'ar',+ 'yue',+ 'ca',+ 'da',+ 'nl',+ 'en',+ 'et',+ 'fi',+ 'fr',+ 'gl',+ 'de',+ 'he',+ 'hi',+ 'it',+ 'ja',+ 'ko',+ 'zh',+ 'mr',+ 'no',+ 'nn',+ 'fa',+ 'pt',+ 'ro',+ 'ru',+ 'es',+ 'sv',+ 'tr',+ 'ur',+ 'vi',+ 'xh',+ 'zu',+])/** The models LiveKit's plugin takes the turn mode and languages for; it refuses both for any other model (a newer one typed in the model field). */const ASSEMBLYAI_U3_PRO = new Set(['u3-rt-pro', 'u3-rt-pro-beta-1', 'universal-3-5-pro', 'universal-3-6-pro'])@@ -211,15 +296,32 @@ export function createStt(config: AgentConfig['stt'], languages: CallLanguages =const { provider, apiKey, model, fastTurnEnd } = sttForCall(config, languages)const multi = !englishOnly(languages)const { main } = languages- if (provider === 'elevenlabs_stt') return new elevenlabs.STT({ apiKey, model, useRealtime: true, ...(multi ? {} : { languageCode: main }) })- if (provider === 'openai_stt') return new openai.STT({ apiKey, model, useRealtime: true, detectLanguage: multi, language: main })- if (provider === 'assemblyai_stt') return new assemblyai.STT({ apiKey, ...assemblyAiChoice(model, languages, fastTurnEnd) })+ if (provider === 'elevenlabs_stt')+ return new elevenlabs.STT({ apiKey, model, useRealtime: true, ...(multi ? {} : { languageCode: main }) })+ if (provider === 'openai_stt')+ return new openai.STT({ apiKey, model, useRealtime: true, detectLanguage: multi, language: main })+ if (provider === 'assemblyai_stt')+ return new assemblyai.STT({ apiKey, ...assemblyAiChoice(model, languages, fastTurnEnd) })const choice = deepgramChoice(model, languages)const { languageHint } = choice// Deepgram's Flux models speak a different protocol than Nova.- if (choice.protocol === 'flux') return new deepgram.STTv2({ apiKey, model: choice.model, eagerEotThreshold: EAGER_END_OF_TURN, mipOptOut: true, ...(languageHint ? { languageHint } : {}) })+ if (choice.protocol === 'flux')+ return new deepgram.STTv2({+ apiKey,+ model: choice.model,+ eagerEotThreshold: EAGER_END_OF_TURN,+ mipOptOut: true,+ ...(languageHint ? { languageHint } : {}),+ })if (!choice.language) return new deepgram.STT({ apiKey, model: choice.model, mipOptOut: true })- return new deepgram.STT({ apiKey, model: choice.model, language: choice.language, languageHint, endpointing: choice.endpointing, mipOptOut: true })+ return new deepgram.STT({+ apiKey,+ model: choice.model,+ language: choice.language,+ languageHint,+ endpointing: choice.endpointing,+ mipOptOut: true,+ })}/** The model the voice provider is asked for (each gets its default, DEFAULT_VOICE_MODELS, when the call names none). */@@ -237,18 +339,26 @@ export const ttsModelOf = (tts: TtsConfig) => tts.model || DEFAULT_VOICE_MODELS[* answers with no audio and no error), a refused key, an outage or a timeout. Without one it is still watched the same* way, so a voice that gives no audio is an error the session reports (voice-failures.ts) instead of a silent call.*/-export function createTts(config: AgentConfig['tts'], assistantVoice?: AssistantVoice | null, language: Language = 'en', speedPct = TALKING_SPEED_PCT_DEFAULT): CallVoice {+export function createTts(+ config: AgentConfig['tts'],+ assistantVoice?: AssistantVoice | null,+ language: Language = 'en',+ speedPct = TALKING_SPEED_PCT_DEFAULT,+): CallVoice {const own = ttsFor(config, assistantVoice, language)const primary = providerTts(own, language, speedPct)const others = [config, ...(config.others ?? [])].filter(other => other.provider !== own.provider)// A language's default voice is a Voice Library voice, which a free ElevenLabs plan can't use: the provider's own// default voice is the first backup then, before any other provider.const providerDefault = providerDefaultVoices[own.provider]- const sameProvider = !!providerDefault && own.voiceId !== providerDefault && own.voiceId === defaultVoiceFor(own.provider, language)+ const sameProvider =+ !!providerDefault && own.voiceId !== providerDefault && own.voiceId === defaultVoiceFor(own.provider, language)const backups = [...(sameProvider ? [providerTts({ ...own, voiceId: providerDefault }, language, speedPct)] : []),...(config.openAiBackup ? [createRealtimeLineTts(config.openAiBackup, speedPct)] : []),- ...others.map(other => providerTts({ ...other, voiceId: providerDefaultVoices[other.provider] }, language, speedPct)),+ ...others.map(other =>+ providerTts({ ...other, voiceId: providerDefaultVoices[other.provider] }, language, speedPct),+ ),]return new VoiceWithBackup(primary, backups)}@@ -257,8 +367,22 @@ function providerTts({ voiceId, ...tts }: TtsConfig & { voiceId?: string }, langconst spoken = language === 'en' ? {} : { language: providerLanguageCode(language, tts.provider) }const speed = speedPct !== TALKING_SPEED_PCT_DEFAULT ? speedPct / 100 : undefinedif (tts.provider === 'cartesia')- return new cartesia.TTS({ apiKey: tts.apiKey, model: ttsModelOf(tts), ...(voiceId ? { voice: voiceId } : {}), ...spoken, ...(speed ? { speed } : {}) })- return new elevenlabs.TTS({ apiKey: tts.apiKey, model: ttsModelOf(tts), ...(voiceId ? { voiceId } : {}), ...spoken, voiceSettings: elevenLabsVoiceSettings(speedPct), preferredAlignment: ELEVENLABS_ALIGNMENT, applyTextNormalization: ELEVENLABS_NORMALIZATION })+ return new cartesia.TTS({+ apiKey: tts.apiKey,+ model: ttsModelOf(tts),+ ...(voiceId ? { voice: voiceId } : {}),+ ...spoken,+ ...(speed ? { speed } : {}),+ })+ return new elevenlabs.TTS({+ apiKey: tts.apiKey,+ model: ttsModelOf(tts),+ ...(voiceId ? { voiceId } : {}),+ ...spoken,+ voiceSettings: elevenLabsVoiceSettings(speedPct),+ preferredAlignment: ELEVENLABS_ALIGNMENT,+ applyTextNormalization: ELEVENLABS_NORMALIZATION,+ })}/**@@ -299,14 +423,23 @@ export const VOICE_PROVIDER_REST_MS = 2 * 60 * 60_000export class VoiceWithBackup extends ttsTypes.FallbackAdapter {fellBack = false- constructor(primary: ttsTypes.TTS & { updateOptions(opts: { language?: string }): void }, backups: ttsTypes.TTS[], log: (line: string) => void = console.warn) {+ constructor(+ primary: ttsTypes.TTS & { updateOptions(opts: { language?: string }): void },+ backups: ttsTypes.TTS[],+ log: (line: string) => void = console.warn,+ ) {super({ ttsInstances: [primary, ...backups], maxRetryPerTTS: 0, recoveryDelayMs: VOICE_PROVIDER_REST_MS })- this.on('tts_availability_changed' as never, (({ tts, available }: ttsTypes.AvailabilityChangedEvent) => {- const backup = backups[0]- if (tts !== primary || available || this.fellBack || !backup) return- this.fellBack = true- log(`voice ${primary.provider} failed: speaking with ${backup.provider} ${backup.model} for the rest of the call`)- }) as never)+ this.on(+ 'tts_availability_changed' as never,+ (({ tts, available }: ttsTypes.AvailabilityChangedEvent) => {+ const backup = backups[0]+ if (tts !== primary || available || this.fellBack || !backup) return+ this.fellBack = true+ log(+ `voice ${primary.provider} failed: speaking with ${backup.provider} ${backup.model} for the rest of the call`,+ )+ }) as never,+ )}/** The language goes to the voice providers that take one; OpenAI's speech model reads it from the text. */@@ -323,9 +456,24 @@ export class VoiceWithBackup extends ttsTypes.FallbackAdapter {/** Whether a backup voice said any of this (VoiceWithBackup): then it is not cached as the voice's own audio. */export const spokeWithBackup = (tts: ttsTypes.TTS) => tts instanceof VoiceWithBackup && tts.fellBack-type TalkingSpeedFields = { talking_speed_pct?: number | null; talking_speed?: TalkingSpeed | null }-/** The assistant's talking speed in percent; a row of an older API has only slow, normal or fast, or nothing: 100. */-export const talkingSpeedOf = (assistant: TalkingSpeedFields | null | undefined): number => talkingSpeedPctOf(assistant)+type TalkingSpeedFields = {+ talking_speed_pct?: number | null+ talking_speed?: TalkingSpeed | null+ voice?: AssistantVoice | null+ languages?: Parameters<typeof mainLanguageOf>[0]+}+/**+ * The speed sent to the voice, in percent: the assistant's talking speed (a row of an older API has only slow, normal+ * or fast, or nothing: 100), for an ElevenLabs voice relative to its language's default voice (voice-pace.ts), so+ * every voice speaks at the same pace at the same setting.+ */+export const talkingSpeedOf = (assistant: TalkingSpeedFields | null | undefined): number => {+ const pct = talkingSpeedPctOf(assistant)+ const voice = assistant?.voice+ if (voice?.provider && voice.provider !== 'elevenlabs') return pct+ const language = mainLanguageOf(assistant?.languages)+ return paceCorrectedPct(pct, voice?.voice_id || defaultVoiceFor('elevenlabs', language), language)+}/** OpenRouter's `models`: the model first, then the ones it tries when that one fails. */const modelsField = (model: string, fallbacks: string[]) => (fallbacks.length ? { models: [model, ...fallbacks] } : {})@@ -342,7 +490,11 @@ export const tokenCap = (baseUrl: string, n: number) =>* OpenRouter's rule to route only to providers that don't train on the call, and with zero data retention unless the* instance admin turned that off (noTrainingFields).*/-export const replyRequestFields = (model: string, fallbacks: string[], baseUrl: string, zeroDataRetention = true) => ({ ...tokenCap(baseUrl, REPLY_MAX_TOKENS), ...modelsField(model, fallbacks), ...noTrainingFields(baseUrl, zeroDataRetention) })+export const replyRequestFields = (model: string, fallbacks: string[], baseUrl: string, zeroDataRetention = true) => ({+ ...tokenCap(baseUrl, REPLY_MAX_TOKENS),+ ...modelsField(model, fallbacks),+ ...noTrainingFields(baseUrl, zeroDataRetention),+})/** The conversation LLM: every request carries replyRequestFields. */function createLlm({ apiKey, baseUrl, model, fallbacks, zeroDataRetention }: AgentConfig['llm']) {@@ -374,16 +526,30 @@ export const MAX_TOOL_STEPS = 8/** Session options for one call. *//** LiveKit's own two (markdown, emoji) and codes said one character at a time (spoken-codes.ts), for every voice provider. */-export const TTS_TEXT_TRANSFORMS: NonNullable<voice.AgentSessionOptions['ttsTextTransforms']> = ['filter_markdown', 'filter_emoji', spellCodesTransform]--export function createPipeline(config: AgentConfig, assistantVoice?: AssistantVoice | null, silenceFirstGapS = SILENCE_FIRST_GAP_DEFAULT_S, languages: CallLanguages = ENGLISH_CALL, speedPct = TALKING_SPEED_PCT_DEFAULT): voice.AgentSessionOptions & { tts: CallVoice } {+export const TTS_TEXT_TRANSFORMS: NonNullable<voice.AgentSessionOptions['ttsTextTransforms']> = [+ 'filter_markdown',+ 'filter_emoji',+ spellCodesTransform,+]++export function createPipeline(+ config: AgentConfig,+ assistantVoice?: AssistantVoice | null,+ silenceFirstGapS = SILENCE_FIRST_GAP_DEFAULT_S,+ languages: CallLanguages = ENGLISH_CALL,+ speedPct = TALKING_SPEED_PCT_DEFAULT,+): voice.AgentSessionOptions & { tts: CallVoice } {const sttTurns = sttDetectsTurns(config.stt, languages)return {vad: null,stt: createStt(config.stt, languages),llm: createLlm(config.llm),tts: createTts(config.tts, assistantVoice, languages.main, speedPct),- turnHandling: { turnDetection: sttTurns ? 'stt' : undefined, endpointing: ENDPOINTING, preemptiveGeneration: { enabled: true } },+ turnHandling: {+ turnDetection: sttTurns ? 'stt' : undefined,+ endpointing: ENDPOINTING,+ preemptiveGeneration: { enabled: true },+ },// The caller counts as away after this much silence on both sides; the worker then asks whether they are still// there, and in the end says goodbye and hangs up (remindOnSilence in hang-up.ts).userAwayTimeout: silenceFirstGapS,@@ -392,13 +558,15 @@ export function createPipeline(config: AgentConfig, assistantVoice?: AssistantVo}}-/*** A realtime session's raw OpenAI events, as the plugin emits them (for timing, realtime-timing.ts), and its way to send* one (for the fixed lines, realtime-lines.ts).*/export type RealtimeEvents = {- on(event: 'openai_client_event_queued' | 'openai_server_event_received', listener: (event: { type?: string }) => void): unknown+ on(+ event: 'openai_client_event_queued' | 'openai_server_event_received',+ listener: (event: { type?: string }) => void,+ ): unknownsendEvent(event: object): void/** One reply at a time (realtime-replies.ts): every reply asked for waits until the model is not answering. */replies: RealtimeReplyGate@@ -419,12 +587,21 @@ export const REALTIME_TRUNCATION = {/** A full session.update with REALTIME_TRUNCATION in it (other events go through unchanged). */export function withRealtimeTruncation<E extends { type?: string; session?: object }>(event: E): E {- if (event.type !== 'session.update' || !event.session || !('type' in event.session) || event.session.type !== 'realtime') return event+ if (+ event.type !== 'session.update' ||+ !event.session ||+ !('type' in event.session) ||+ event.session.type !== 'realtime'+ )+ return eventreturn { ...event, session: { ...event.session, truncation: REALTIME_TRUNCATION } }}/** The plugin's session, as far as the truncation needs it: the session.update it builds on open and on a reconnect. */-type SessionUpdates = { createSessionUpdateEvent(): { type?: string; session?: object }; sendEvent(event: object): void }+type SessionUpdates = {+ createSessionUpdateEvent(): { type?: string; session?: object }+ sendEvent(event: object): void+}/*** Makes the session send REALTIME_TRUNCATION: once now (the session's first session.update is already queued without@@ -439,7 +616,10 @@ export function sendRealtimeTruncation(session: SessionUpdates) {/** The realtime model, handing each session it opens to `onSession` (one per call, again after a reconnect). */class ObservedRealtimeModel extends openai.realtime.RealtimeModel {readonly #onSession?: (session: RealtimeEvents) => void- constructor(onSession: ((session: RealtimeEvents) => void) | undefined, options: ConstructorParameters<typeof openai.realtime.RealtimeModel>[0]) {+ constructor(+ onSession: ((session: RealtimeEvents) => void) | undefined,+ options: ConstructorParameters<typeof openai.realtime.RealtimeModel>[0],+ ) {super(options)this.#onSession = onSession}@@ -458,7 +638,10 @@ const REALTIME_TRANSCRIPTION = 'gpt-4o-mini-transcribe'/** A phone handset is close to the mouth: near-field noise reduction cleans what the model hears. */const REALTIME_NOISE_REDUCTION = { type: 'near_field' } as const/** The caller's transcript (call log, summary): told the language when the call has only one. */-const realtimeTranscription = ({ main, others }: CallLanguages) => ({ model: REALTIME_TRANSCRIPTION, ...(others.length ? {} : { language: main }) })+const realtimeTranscription = ({ main, others }: CallLanguages) => ({+ model: REALTIME_TRANSCRIPTION,+ ...(others.length ? {} : { language: main }),+})/*** The session.update that turns the realtime model's own replies off (`replies` false) or on again: the input audio@@ -507,10 +690,20 @@ export const REALTIME_UNREACHABLE_URL = 'https://192.0.2.1/v1'* `speedPct`: the talking speed in percent, sent as a factor (OpenAI Realtime takes 0.25–1.5); at 100 nothing is sent.* `unreachable`: the model is pointed at REALTIME_UNREACHABLE_URL (call-test --realtime-unreachable).*/-export function createRealtimePipeline({ apiKey, model, voice: voiceName }: RealtimeConfig, silenceFirstGapS = SILENCE_FIRST_GAP_DEFAULT_S, speedPct = TALKING_SPEED_PCT_DEFAULT, languages: CallLanguages = ENGLISH_CALL, onSession?: (session: RealtimeEvents) => void, unreachable = false): voice.AgentSessionOptions {+export function createRealtimePipeline(+ { apiKey, model, voice: voiceName }: RealtimeConfig,+ silenceFirstGapS = SILENCE_FIRST_GAP_DEFAULT_S,+ speedPct = TALKING_SPEED_PCT_DEFAULT,+ languages: CallLanguages = ENGLISH_CALL,+ onSession?: (session: RealtimeEvents) => void,+ unreachable = false,+): voice.AgentSessionOptions {return {llm: new ObservedRealtimeModel(onSession, {- apiKey, model, voice: voiceName, turnDetection: REALTIME_TURNS,+ apiKey,+ model,+ voice: voiceName,+ turnDetection: REALTIME_TURNS,// A connection that does not open in time is given up sooner than LiveKit's 10 s (LIN-634, realtime-connect.ts).connOptions: { ...DEFAULT_API_CONNECT_OPTIONS, timeoutMs: REALTIME_CONNECT_TIMEOUT_MS },...(unreachable ? { baseURL: REALTIME_UNREACHABLE_URL } : {}),@@ -537,8 +730,16 @@ export const REALTIME_LINE_TTS = 'gpt-4o-mini-tts'type OpenAiVoice = NonNullable<ConstructorParameters<typeof openai.TTS>[0]>['voice']/** OpenAI's speech model in the realtime model's voice and pace: a fixed line then sounds like the rest of the call. */-export function createRealtimeLineTts({ apiKey, voice: voiceName }: Pick<RealtimeConfig, 'apiKey' | 'voice'>, speedPct = TALKING_SPEED_PCT_DEFAULT) {- return new openai.TTS({ apiKey, model: REALTIME_LINE_TTS, voice: voiceName as OpenAiVoice, ...(speedPct !== TALKING_SPEED_PCT_DEFAULT ? { speed: speedPct / 100 } : {}) })+export function createRealtimeLineTts(+ { apiKey, voice: voiceName }: Pick<RealtimeConfig, 'apiKey' | 'voice'>,+ speedPct = TALKING_SPEED_PCT_DEFAULT,+) {+ return new openai.TTS({+ apiKey,+ model: REALTIME_LINE_TTS,+ voice: voiceName as OpenAiVoice,+ ...(speedPct !== TALKING_SPEED_PCT_DEFAULT ? { speed: speedPct / 100 } : {}),+ })}/**@@ -547,15 +748,24 @@ export function createRealtimeLineTts({ apiKey, voice: voiceName }: Pick<Realtim* realtime voice (the model itself, asked to say a line, often said something else).*/export type LineVoice = { tts: () => ttsTypes.TTS; key: Omit<GreetingVoice, 'text'> }-type LineAssistant = ({ voice?: AssistantVoice | null; languages?: Parameters<typeof mainLanguageOf>[0] } & TalkingSpeedFields) | null | undefined+type LineAssistant =+ | ({ voice?: AssistantVoice | null; languages?: Parameters<typeof mainLanguageOf>[0] } & TalkingSpeedFields)+ | null+ | undefinedexport function lineVoiceOf(config: CallConfig, assistant: LineAssistant): LineVoice {const speed = talkingSpeedOf(assistant)if (isRealtime(config)) {const { realtime } = config- return { key: { provider: 'openai_tts', model: REALTIME_LINE_TTS, voiceId: realtime.voice, speed }, tts: () => createRealtimeLineTts(realtime, speed) }+ return {+ key: { provider: 'openai_tts', model: REALTIME_LINE_TTS, voiceId: realtime.voice, speed },+ tts: () => createRealtimeLineTts(realtime, speed),+ }+ }+ return {+ key: greetingVoice(config, { assistant }),+ tts: () => createTts(config.tts, assistant?.voice, mainLanguageOf(assistant?.languages), speed),}- return { key: greetingVoice(config, { assistant }), tts: () => createTts(config.tts, assistant?.voice, mainLanguageOf(assistant?.languages), speed) }}/** A realtime voice other than `voice`: the simulated on-call person of a call test must not sound like the assistant. */@@ -575,20 +785,29 @@ export type TransferSpeech = {onCallVoice: () => ttsTypes.TTS}-export function transferSpeechOf(config: CallConfig, assistant: LineAssistant, testCallerVoice = process.env.TEST_CALLER_VOICE_ID): TransferSpeech {+export function transferSpeechOf(+ config: CallConfig,+ assistant: LineAssistant,+ testCallerVoice = process.env.TEST_CALLER_VOICE_ID,+): TransferSpeech {const line = lineVoiceOf(config, assistant)const language = mainLanguageOf(assistant?.languages)if (!isRealtime(config)) {return {line,consult: { tts: () => createTts(config.tts, assistant?.voice, language), stt: config.stt, language },- onCallVoice: () => createTts(config.tts, testCallerVoice ? { provider: config.tts.provider, voice_id: testCallerVoice } : null),+ onCallVoice: () =>+ createTts(config.tts, testCallerVoice ? { provider: config.tts.provider, voice_id: testCallerVoice } : null),}}const { realtime, stages } = configreturn {line,- consult: { tts: () => createRealtimeLineTts(realtime), stt: { provider: 'openai_stt', apiKey: realtime.apiKey, model: REALTIME_TRANSCRIPTION }, language },+ consult: {+ tts: () => createRealtimeLineTts(realtime),+ stt: { provider: 'openai_stt', apiKey: realtime.apiKey, model: REALTIME_TRANSCRIPTION },+ language,+ },// The test caller's voice when the three stages are set up too (as on the three stages), else another realtime voice.onCallVoice: stages? transferSpeechOf(stages, assistant, testCallerVoice).onCallVoice@@ -597,7 +816,13 @@ export function transferSpeechOf(config: CallConfig, assistant: LineAssistant, t}/** Where one chat request goes; `zeroDataRetention` (OpenRouter, default on): see noTrainingFields. */-export type ChatModel = { apiKey: string; baseUrl: string; model: string; fallbacks?: string[]; zeroDataRetention?: boolean }+export type ChatModel = {+ apiKey: string+ baseUrl: string+ model: string+ fallbacks?: string[]+ zeroDataRetention?: boolean+}/*** The error text of a failed chat request: OpenRouter's "no endpoint" under our privacy routing gets the clear text that@@ -617,13 +842,26 @@ export function chatJson(chat: ChatModel, doFetch: typeof fetch = fetch, timeoutmethod: 'POST',headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },body: JSON.stringify({- model, ...modelsField(model, fallbacks), ...noTrainingFields(baseUrl, zeroDataRetention), response_format: { type: 'json_object' }, ...tokenCap(baseUrl, SUMMARY_MAX_TOKENS),- messages: [{ role: 'system', content: system }, { role: 'user', content: user }],+ model,+ ...modelsField(model, fallbacks),+ ...noTrainingFields(baseUrl, zeroDataRetention),+ response_format: { type: 'json_object' },+ ...tokenCap(baseUrl, SUMMARY_MAX_TOKENS),+ messages: [+ { role: 'system', content: system },+ { role: 'user', content: user },+ ],}),signal: AbortSignal.timeout(timeoutMs),})- const body = (await res.json().catch(() => null)) as { choices?: { message?: { content?: string } }[]; error?: { message?: string } } | null- if (!res.ok) throw new Error(`summary request failed (${res.status}): ${chatFailure(chat, res.status, body?.error?.message ?? res.statusText)}`)+ const body = (await res.json().catch(() => null)) as {+ choices?: { message?: { content?: string } }[]+ error?: { message?: string }+ } | null+ if (!res.ok)+ throw new Error(+ `summary request failed (${res.status}): ${chatFailure(chat, res.status, body?.error?.message ?? res.statusText)}`,+ )const content = body?.choices?.[0]?.message?.contentif (!content) throw new Error('summary response was empty')return content@@ -635,9 +873,20 @@ export function chatJson(chat: ChatModel, doFetch: typeof fetch = fetch, timeout* model, its summary model on OpenAI's chat API with the same key.*/export function summaryLlm(config: CallConfig): CompleteJson {- if (isRealtime(config)) return chatJson({ apiKey: config.realtime.apiKey, baseUrl: llmDefaults.openai.baseUrl, model: config.realtime.summaryModel })+ if (isRealtime(config))+ return chatJson({+ apiKey: config.realtime.apiKey,+ baseUrl: llmDefaults.openai.baseUrl,+ model: config.realtime.summaryModel,+ })const { llm } = config- return chatJson({ apiKey: llm.apiKey, baseUrl: llm.baseUrl, model: llm.summaryModel, fallbacks: llm.summaryFallbacks, zeroDataRetention: llm.zeroDataRetention })+ return chatJson({+ apiKey: llm.apiKey,+ baseUrl: llm.baseUrl,+ model: llm.summaryModel,+ fallbacks: llm.summaryFallbacks,+ zeroDataRetention: llm.zeroDataRetention,+ })}/**@@ -651,7 +900,15 @@ export async function warmUpLlm(chat: ChatModel, instructions: string, doFetch:const res = await doFetch(`${baseUrl}/chat/completions`, {method: 'POST',headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },- body: JSON.stringify({ model, ...tokenCap(baseUrl, 1), ...noTrainingFields(baseUrl, zeroDataRetention), messages: [{ role: 'system', content: instructions }, { role: 'user', content: 'Hello?' }] }),+ body: JSON.stringify({+ model,+ ...tokenCap(baseUrl, 1),+ ...noTrainingFields(baseUrl, zeroDataRetention),+ messages: [+ { role: 'system', content: instructions },+ { role: 'user', content: 'Hello?' },+ ],+ }),signal: AbortSignal.timeout(WARM_UP_TIMEOUT_MS),})// The same model and routing as the call's first reply: a model OpenRouter has no private endpoint for is named here.diff --git a/apps/agent/src/voice-pace.test.ts b/apps/agent/src/voice-pace.test.tsnew file mode 100644index 00000000..c123f31d--- /dev/null+++ b/apps/agent/src/voice-pace.test.ts@@ -0,0 +1,27 @@+import { expect, test } from 'vitest'+import { paceOfAlignment, PACE_SPEED_MAX_PCT, PACE_SPEED_MIN_PCT, uniformSpeedPct } from './voice-pace.ts'++test('a voice slower than the reference is sped up, a faster one slowed down, within ElevenLabs range', () => {+ // Measured 2026-11-28 with the same German sentence: Susi (the German default) 17.9, Laura 16.6, Mia Swiss 9.9.+ expect(uniformSpeedPct(100, 17.9, 17.9)).toBe(100)+ expect(uniformSpeedPct(100, 16.6, 17.9)).toBe(108)+ expect(uniformSpeedPct(110, 16.6, 17.9)).toBe(119)+ expect(uniformSpeedPct(100, 9.9, 17.9)).toBe(PACE_SPEED_MAX_PCT)+ expect(uniformSpeedPct(80, 30, 17.9)).toBe(PACE_SPEED_MIN_PCT)+})++test('until both paces are known the owner setting goes out unchanged', () => {+ expect(uniformSpeedPct(110, undefined, 17.9)).toBe(110)+ expect(uniformSpeedPct(110, 16.6, undefined)).toBe(110)+})++test('the pace of a sample: characters per second of speech, none for a sample too short to tell', () => {+ const characters = [...'x'.repeat(100)]+ expect(+ paceOfAlignment({ characters, character_start_times_seconds: [0.2], character_end_times_seconds: [5.2] }),+ ).toBe(20)+ expect(+ paceOfAlignment({ characters: ['a'], character_start_times_seconds: [0], character_end_times_seconds: [2] }),+ ).toBeNull()+ expect(paceOfAlignment(undefined)).toBeNull()+})diff --git a/apps/agent/src/voice-pace.ts b/apps/agent/src/voice-pace.tsnew file mode 100644index 00000000..514c17dd--- /dev/null+++ b/apps/agent/src/voice-pace.ts@@ -0,0 +1,155 @@+// One pace for every voice (Tim, 2026-11-28). ElevenLabs voices speak at very different paces at the same speed: the+// same German sentence took 6.3 s with Susi and 11.4 s with "Mia Swiss" (Voice Library). The talking speed an owner+// sets (80-120 %) was relative to each voice's own pace, so 110 % of a slow voice stayed slow. Now 100 % is the pace+// of the language's default voice (languageDefaultVoices; Jessica for English) for every voice: each voice's pace is+// measured once (a short sample with ElevenLabs' character timings, at speed 1), kept on disk next to the stored+// greetings, and the speed sent to ElevenLabs is the owner's percentage times reference pace / voice pace, within+// ElevenLabs' range (0.7-1.2). A voice not measured yet keeps the owner's percentage as before.+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { defaultVoiceFor, type Language, providerLanguageCode } from '@linedesk/actions'+import { GREETING_CACHE_DIR } from './greeting-cache.ts'++/** ElevenLabs' speed range (voice_settings.speed), in percent. */+export const PACE_SPEED_MIN_PCT = 70+export const PACE_SPEED_MAX_PCT = 120+/** How long a call waits for a voice's first measurement before it starts without it. */+export const PACE_WAIT_MS = 1500++/** The sentence a pace is measured with: about 110 characters, a typical reply. English for languages without one. */+const SAMPLES: Partial<Record<Language, string>> & { en: string } = {+ en: "Hello, this is Maya. I'm calling to confirm your appointment on Monday at nine. Does that still work for you?",+ de: 'Guten Tag, hier ist Maya. Ich rufe an, um Ihren Termin am Montag um neun Uhr zu bestätigen. Passt Ihnen das noch?',+ fr: 'Bonjour, ici Maya. Je vous appelle pour confirmer votre rendez-vous lundi à neuf heures. Est-ce que cela vous convient toujours ?',+ es: 'Hola, soy Maya. Le llamo para confirmar su cita del lunes a las nueve. ¿Le sigue viniendo bien?',+}++type Pace = { cps: number; at: string }+const FILE = join(GREETING_CACHE_DIR, 'voice-paces.json')+let paces: Record<string, Pace> | null = null+const pending = new Map<string, Promise<number | null>>()++const keyOf = (voiceId: string, language: Language) => `elevenlabs|${voiceId}|${language}`++function load(): Record<string, Pace> {+ if (paces) return paces+ try {+ paces = JSON.parse(readFileSync(FILE, 'utf8')) as Record<string, Pace>+ } catch {+ paces = {}+ }+ return paces+}++function save() {+ try {+ mkdirSync(dirname(FILE), { recursive: true })+ writeFileSync(FILE, JSON.stringify(load()))+ } catch (e) {+ console.warn(`voice paces not stored: ${e instanceof Error ? e.message : String(e)}`)+ }+}++/** The measured pace (characters a second at speed 1) of a voice in a language, or undefined. */+export const knownPace = (voiceId: string | undefined, language: Language): number | undefined =>+ voiceId ? load()[keyOf(voiceId, language)]?.cps : undefined++/** Characters a second of one sample, from ElevenLabs' character timings (start of the first to end of the last). */+export async function measurePace(+ { apiKey, voiceId, model, language }: { apiKey: string; voiceId: string; model?: string; language: Language },+ doFetch: typeof fetch = fetch,+): Promise<number | null> {+ const text = SAMPLES[language] ?? SAMPLES.en+ const res = await doFetch(+ `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voiceId)}/with-timestamps`,+ {+ method: 'POST',+ headers: { 'xi-api-key': apiKey, 'content-type': 'application/json' },+ body: JSON.stringify({+ text,+ ...(model ? { model_id: model } : {}),+ ...(language !== 'en' && SAMPLES[language]+ ? { language_code: providerLanguageCode(language, 'elevenlabs') }+ : {}),+ voice_settings: { speed: 1 },+ }),+ signal: AbortSignal.timeout(10_000),+ },+ )+ if (!res.ok) return null+ const body = (await res.json()) as {+ alignment?: {+ characters?: string[]+ character_start_times_seconds?: number[]+ character_end_times_seconds?: number[]+ }+ }+ return paceOfAlignment(body.alignment)+}++/** Characters a second of an alignment; null when it is too short to tell. */+export function paceOfAlignment(+ a:+ | { characters?: string[]; character_start_times_seconds?: number[]; character_end_times_seconds?: number[] }+ | undefined,+): number | null {+ const chars = a?.characters?.length ?? 0+ const start = a?.character_start_times_seconds?.[0]+ const end = a?.character_end_times_seconds?.at(-1)+ if (chars < 20 || start === undefined || end === undefined || end - start < 1) return null+ return chars / (end - start)+}++/** Measures a voice once (and keeps it); its pace, or null when it could not be measured. */+export function ensurePace(args: {+ apiKey: string+ voiceId: string+ model?: string+ language: Language+}): Promise<number | null> {+ const key = keyOf(args.voiceId, args.language)+ const known = load()[key]+ if (known) return Promise.resolve(known.cps)+ const running = pending.get(key)+ if (running) return running+ const measuring = measurePace(args)+ .then(cps => {+ if (cps) {+ load()[key] = { cps, at: new Date().toISOString() }+ save()+ }+ return cps+ })+ .catch(e => {+ console.warn(`voice pace of ${args.voiceId} not measured: ${e instanceof Error ? e.message : String(e)}`)+ return null+ })+ .finally(() => pending.delete(key))+ pending.set(key, measuring)+ return measuring+}++/** Measures the voice and its language's reference voice (the default one), for one call or the greeting prewarm. */+export function ensurePaces(args: { apiKey: string; voiceId?: string; model?: string; language: Language }) {+ const reference = defaultVoiceFor('elevenlabs', args.language)+ const ids = [...new Set([args.voiceId, reference].filter((id): id is string => !!id))]+ return Promise.all(ids.map(voiceId => ensurePace({ ...args, voiceId })))+}++/**+ * The speed to send for `speedPct` so the voice speaks at that percentage of the reference pace: unchanged until both+ * paces are known, within ElevenLabs' range, rounded to whole percent.+ */+export function uniformSpeedPct(+ speedPct: number,+ voicePace: number | undefined,+ referencePace: number | undefined,+): number {+ if (!voicePace || !referencePace) return speedPct+ const pct = Math.round((speedPct * referencePace) / voicePace)+ return Math.min(PACE_SPEED_MAX_PCT, Math.max(PACE_SPEED_MIN_PCT, pct))+}++/** The corrected speed of an ElevenLabs voice in a language (uniformSpeedPct with the kept paces). */+export const paceCorrectedPct = (speedPct: number, voiceId: string | undefined, language: Language): number =>+ uniformSpeedPct(speedPct, knownPace(voiceId, language), knownPace(defaultVoiceFor('elevenlabs', language), language))diff --git a/apps/agent/src/worker.ts b/apps/agent/src/worker.tsindex 1b213d51..283510b6 100644--- a/apps/agent/src/worker.ts+++ b/apps/agent/src/worker.ts@@ -55,6 +55,7 @@ import {type CallSession,} from './call-session.ts'import { dialOutbound } from './outbound-dial.ts'+import { ensurePaces, PACE_WAIT_MS } from './voice-pace.ts'import { earlyOrigin, livekitParticipants } from './early-origin.ts'import {type AgentConfig,@@ -92,6 +93,7 @@ import {realtimeLine,spokeWithBackup,ttsFor,+ ttsModelOf,realtimeRepliesEvent,type RealtimeEvents,summaryLlm,@@ -1083,6 +1085,18 @@ async function entry(ctx: JobContext) {)if (isRealtime(config))console.log(`call ${registered.callId}: realtime model ${config.realtime.model}, voice ${config.realtime.voice}`)+ // The voice's pace, measured once (voice-pace.ts): a voice not measured yet waits a moment, then speaks as before.+ const stagesOfCall = isRealtime(config) ? config.stages : config+ if (stagesOfCall?.tts.provider === 'elevenlabs') {+ const language = mainLanguageOf(registered.assistant?.languages)+ const voiceTts = ttsFor(stagesOfCall.tts, registered.assistant?.voice, language)+ if (voiceTts.provider === 'elevenlabs')+ await within(+ ensurePaces({ apiKey: voiceTts.apiKey, voiceId: voiceTts.voiceId, model: ttsModelOf(voiceTts), language }),+ PACE_WAIT_MS,+ null,+ )+ }const recorder = livekitRecorder(config.recording,process.env,