UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

627 lines (626 loc) • 22.2 kB
import { n as resolveElevenLabsApiKeyWithProfileFallback } from "./.setup/config-compat-aShGS3Tj.mjs"; import { normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input"; import { asBoolean, asFiniteNumberInRange, asOptionalRecord, asSafeIntegerInRange, normalizeLowercaseStringOrEmpty, normalizeOptionalString, parseBooleanValue, parseFiniteNumber } from "openclaw/plugin-sdk/string-coerce-runtime"; import { parseStrictFiniteNumber, parseStrictInteger } from "openclaw/plugin-sdk/number-runtime"; import { MAX_AUDIO_BYTES, createSpeechDirectiveParser, normalizeApplyTextNormalization, normalizeLanguageCode, normalizeSeed, requireInRange, resolveSpeechProviderApiKey } from "openclaw/plugin-sdk/speech-provider"; //#region extensions/elevenlabs/shared.ts const DEFAULT_ELEVENLABS_BASE_URL = "https://api.elevenlabs.io"; function isValidElevenLabsVoiceId(e) { return /^[a-zA-Z0-9]{10,40}$/.test(e); } function normalizeElevenLabsBaseUrlWithProtocols(e, t) { const n = e?.trim(); if (!n) return DEFAULT_ELEVENLABS_BASE_URL; const r = n.replace(/\/+$/, ""); const i = URL.parse(r); if (!i) throw new Error("Invalid ElevenLabs baseUrl: value is not a valid URL"); if (!t.includes(i.protocol)) throw new Error(`Invalid ElevenLabs baseUrl: unsupported scheme "${i.protocol}" (expected ${t.join(" or ")})`); return r; } function normalizeElevenLabsBaseUrl(e) { return normalizeElevenLabsBaseUrlWithProtocols(e, ["http:", "https:"]); } function normalizeElevenLabsRealtimeBaseUrl(e) { const t = new URL(normalizeElevenLabsBaseUrlWithProtocols(e, [ "http:", "https:", "ws:", "wss:" ])); if (t.protocol === "http:" || t.protocol === "https:") t.protocol = t.protocol === "http:" ? "ws:" : "wss:"; return t.toString().replace(/\/+$/, ""); } //#endregion //#region extensions/elevenlabs/realtime-transcription-provider-factory.ts const ELEVENLABS_REALTIME_DEFAULT_MODEL = "scribe_v2_realtime"; const ELEVENLABS_REALTIME_DEFAULT_AUDIO_FORMAT = "ulaw_8000"; const ELEVENLABS_REALTIME_DEFAULT_SAMPLE_RATE = 8e3; const ELEVENLABS_REALTIME_DEFAULT_COMMIT_STRATEGY = "vad"; function readNestedElevenLabsConfig(e) { const t = asOptionalRecord(e); const n = asOptionalRecord(t?.providers); return asOptionalRecord(n?.elevenlabs ?? t?.elevenlabs ?? t) ?? {}; } function normalizeCommitStrategy(e) { const t = normalizeOptionalString(e)?.toLowerCase(); if (!t) return; if (t === "manual" || t === "vad") return t; throw new Error(`Invalid ElevenLabs realtime transcription commit strategy: ${t}`); } function normalizePositiveSafeInteger(e) { const t = parseFiniteNumber(e); return asSafeIntegerInRange(t, { min: 1 }); } function normalizeFiniteRange(e, t, n) { const r = parseFiniteNumber(e); return asFiniteNumberInRange(r, { min: t, max: n }); } function normalizeMinimumDurationMs(e) { const t = parseFiniteNumber(e); return asSafeIntegerInRange(t, { min: 50, max: 2e3 }); } function normalizeProviderConfig(e) { const t = readNestedElevenLabsConfig(e); return { apiKey: normalizeResolvedSecretInputString({ value: t.apiKey, path: "plugins.entries.voice-call.config.streaming.providers.elevenlabs.apiKey" }), baseUrl: normalizeOptionalString(t.baseUrl), modelId: normalizeOptionalString(t.modelId ?? t.model ?? t.sttModel), audioFormat: normalizeOptionalString(t.audioFormat ?? t.audio_format ?? t.encoding), sampleRate: normalizePositiveSafeInteger(t.sampleRate ?? t.sample_rate), languageCode: normalizeOptionalString(t.languageCode ?? t.language), commitStrategy: normalizeCommitStrategy(t.commitStrategy ?? t.commit_strategy), vadSilenceThresholdSecs: normalizeFiniteRange(t.vadSilenceThresholdSecs ?? t.vad_silence_threshold_secs, .3, 3), vadThreshold: normalizeFiniteRange(t.vadThreshold ?? t.vad_threshold, .1, .9), minSpeechDurationMs: normalizeMinimumDurationMs(t.minSpeechDurationMs ?? t.min_speech_duration_ms), minSilenceDurationMs: normalizeMinimumDurationMs(t.minSilenceDurationMs ?? t.min_silence_duration_ms) }; } function readErrorDetail(e) { return normalizeOptionalString(e.error) ?? normalizeOptionalString(e.message) ?? normalizeOptionalString(e.code) ?? "ElevenLabs realtime transcription error"; } function resolveElevenLabsRealtimeApiKey(e) { return e.apiKey ?? resolveElevenLabsApiKeyWithProfileFallback() ?? normalizeOptionalString(process.env.XI_API_KEY); } function buildElevenLabsRealtimeTranscriptionProvider({ createRealtimeTranscriptionWebSocketSession: e, isProviderAuthProfileConfiguredAsync: t, resolveProviderAuthProfileApiKey: n }) { const isConfigured = ({ providerConfig: e }) => Boolean(resolveElevenLabsRealtimeApiKey(normalizeProviderConfig(e))); return { id: "elevenlabs", label: "ElevenLabs Realtime Transcription", aliases: ["elevenlabs-realtime", "scribe-v2-realtime"], defaultModel: ELEVENLABS_REALTIME_DEFAULT_MODEL, autoSelectOrder: 40, resolveConfig: ({ rawConfig: e }) => normalizeProviderConfig(e), isConfigured, isConfiguredAsync: async (e) => isConfigured(e) || e.selectedExplicitly === true && await t({ provider: "elevenlabs", cfg: e.cfg, profileTypes: ["api_key"] }), createSession: (t) => { const r = normalizeProviderConfig(t.providerConfig); const i = resolveElevenLabsRealtimeApiKey(r); const a = normalizeElevenLabsRealtimeBaseUrl(r.baseUrl); const o = r.sampleRate ?? ELEVENLABS_REALTIME_DEFAULT_SAMPLE_RATE; const s = r.commitStrategy ?? ELEVENLABS_REALTIME_DEFAULT_COMMIT_STRATEGY; let c; return e({ providerId: "elevenlabs", callbacks: t, url: () => { const e = new URL(`${a}/v1/speech-to-text/realtime`); e.searchParams.set("model_id", r.modelId ?? ELEVENLABS_REALTIME_DEFAULT_MODEL); e.searchParams.set("audio_format", r.audioFormat ?? ELEVENLABS_REALTIME_DEFAULT_AUDIO_FORMAT); e.searchParams.set("commit_strategy", s); e.searchParams.set("include_timestamps", "false"); e.searchParams.set("include_language_detection", "false"); if (r.languageCode) e.searchParams.set("language_code", r.languageCode); if (r.vadSilenceThresholdSecs != null) e.searchParams.set("vad_silence_threshold_secs", String(r.vadSilenceThresholdSecs)); if (r.vadThreshold != null) e.searchParams.set("vad_threshold", String(r.vadThreshold)); if (r.minSpeechDurationMs != null) e.searchParams.set("min_speech_duration_ms", String(r.minSpeechDurationMs)); if (r.minSilenceDurationMs != null) e.searchParams.set("min_silence_duration_ms", String(r.minSilenceDurationMs)); return e.toString(); }, headers: async () => { const e = i || await n({ provider: "elevenlabs", cfg: t.cfg, profileTypes: ["api_key"] }); if (!e) throw new Error("ElevenLabs API key missing"); return { "xi-api-key": e }; }, connectTimeoutMessage: "ElevenLabs realtime transcription connection timeout", reconnectLimitMessage: "ElevenLabs realtime transcription reconnect limit reached", sendAudio: (e, t) => { t.sendJson({ message_type: "input_audio_chunk", audio_base_64: e.toString("base64"), sample_rate: o, ...s === "manual" ? { commit: true } : {} }); }, onClose: (e) => { e.sendJson({ message_type: "input_audio_chunk", audio_base_64: "", sample_rate: o, commit: true }); }, onMessage: (e, n) => { if (e.message_type === "session_started") { c = void 0; n.markReady(); return; } const r = typeof e.error === "string" || e.message_type?.includes("error"); if (!n.isReady() && r) { n.failConnect(new Error(readErrorDetail(e))); return; } switch (e.message_type) { case "partial_transcript": if (e.text) t.onPartial?.(e.text); return; case "committed_transcript": case "committed_transcript_with_timestamps": if (e.text) { const n = e.message_type !== "committed_transcript"; const r = n && c === e.text; c = n ? void 0 : e.text; if (!r) t.onTranscript?.(e.text); } return; default: if (r) t.onError?.(new Error(readErrorDetail(e))); } } }); } }; } //#endregion //#region extensions/elevenlabs/speech-provider-factory.ts const DEFAULT_ELEVENLABS_VOICE_ID = "pMsXgVXv3BLzUgSXRplE"; const DEFAULT_ELEVENLABS_MODEL_ID = "eleven_multilingual_v2"; const DEFAULT_ELEVENLABS_VOICE_SETTINGS = { stability: .5, similarityBoost: .75, style: 0, useSpeakerBoost: true, speed: 1 }; const ELEVENLABS_TTS_MODELS = [ "eleven_v3", "eleven_multilingual_v2", "eleven_flash_v2_5", "eleven_flash_v2", "eleven_turbo_v2_5", "eleven_monolingual_v1" ]; async function requestElevenLabsTts(e, t) { const { text: n, baseUrl: r, voiceId: i, modelId: a, outputFormat: o, seed: s, applyTextNormalization: c, languageCode: l, latencyTier: u, voiceSettings: d } = e; if (!isValidElevenLabsVoiceId(i)) throw new Error("Invalid voiceId format"); const f = normalizeLanguageCode(l); const p = normalizeApplyTextNormalization(c); const m = new URL(`${r}/v1/text-to-speech/${i}${t ? "/stream" : ""}`); m.searchParams.set("output_format", o); const h = a.trim().toLowerCase() !== "eleven_v3"; if (u !== void 0 && h) m.searchParams.set("optimize_streaming_latency", u.toString()); const g = o.trim().toLowerCase(); const _ = !g || g.startsWith("mp3_") ? "audio/mpeg" : void 0; const v = JSON.stringify({ text: n, model_id: a, seed: s, apply_text_normalization: p, language_code: f, voice_settings: { stability: d.stability, similarity_boost: d.similarityBoost, style: d.style, use_speaker_boost: d.useSpeakerBoost, speed: d.speed } }); const { assertOkOrThrowProviderError: y } = await import("openclaw/plugin-sdk/provider-http"); const { fetchWithSsrFGuard: b, ssrfPolicyFromHttpBaseUrlAllowedHostname: x } = await import("openclaw/plugin-sdk/ssrf-runtime"); const S = await b({ url: m.toString(), init: { method: "POST", headers: { "xi-api-key": e.apiKey, "Content-Type": "application/json", ..._ ? { Accept: _ } : {} }, body: v }, timeoutMs: e.timeoutMs, policy: x(r), auditContext: t ? "elevenlabs.tts.stream" : "elevenlabs.tts" }); try { await y(S.response, "ElevenLabs API error"); return S; } catch (e) { await S.release(); throw e; } } async function elevenLabsTTS(e) { const { readProviderBinaryResponse: t } = await import("openclaw/plugin-sdk/provider-http"); const { response: n, release: r } = await requestElevenLabsTts(e, false); try { return await t(n, "ElevenLabs API error", "audio"); } finally { await r(); } } function normalizeElevenLabsTtsModelId(e) { switch (e) { case "eleven_turbo_v2_5": return "eleven_flash_v2_5"; case "eleven_turbo_v2": return "eleven_flash_v2"; default: return e; } } function normalizeElevenLabsSeed(e) { return asSafeIntegerInRange(e, { min: 0, max: 4294967295 }); } function normalizeElevenLabsLatencyTier(e) { return asSafeIntegerInRange(e, { min: 0, max: 4 }); } const ELEVENLABS_OUTPUT_FAMILIES = /* @__PURE__ */ new Set([ "opus", "mp3", "pcm", "ulaw", "alaw", "wav" ]); function resolveElevenLabsOutputPlan(e) { const t = normalizeOptionalString(e.providerOverrides?.outputFormat) ?? (e.target === "voice-note" ? "opus_48000_64" : "mp3_44100_128"); const n = t.trim().toLowerCase().split("_", 1)[0]; return { outputFormat: t, fileExtension: n && ELEVENLABS_OUTPUT_FAMILIES.has(n) ? `.${n}` : ".bin", voiceCompatible: n === "opus" }; } function definedSettings(e) { for (const t in e) if (e[t] === void 0) delete e[t]; return e; } function normalizeVoiceSettings(e) { return definedSettings({ stability: asFiniteNumberInRange(e?.stability, { min: 0, max: 1 }), similarityBoost: asFiniteNumberInRange(e?.similarityBoost, { min: 0, max: 1 }), style: asFiniteNumberInRange(e?.style, { min: 0, max: 1 }), useSpeakerBoost: asBoolean(e?.useSpeakerBoost), speed: asFiniteNumberInRange(e?.speed, { min: .5, max: 2 }) }); } function normalizeElevenLabsProviderConfig(e) { const t = asOptionalRecord(e.providers); const n = asOptionalRecord(t?.elevenlabs); const r = asOptionalRecord(n?.voiceSettings); return { apiKey: normalizeResolvedSecretInputString({ value: n?.apiKey, path: "tts.providers.elevenlabs.apiKey" }), baseUrl: normalizeElevenLabsBaseUrl(normalizeOptionalString(n?.baseUrl)), voiceId: normalizeOptionalString(n?.voiceId) ?? DEFAULT_ELEVENLABS_VOICE_ID, modelId: normalizeElevenLabsTtsModelId(normalizeOptionalString(n?.modelId)) ?? DEFAULT_ELEVENLABS_MODEL_ID, seed: normalizeElevenLabsSeed(n?.seed), applyTextNormalization: normalizeOptionalString(n?.applyTextNormalization), languageCode: normalizeOptionalString(n?.languageCode), voiceSettings: { ...DEFAULT_ELEVENLABS_VOICE_SETTINGS, ...normalizeVoiceSettings(r) } }; } function readElevenLabsProviderConfig(e) { return normalizeElevenLabsProviderConfig({ providers: { elevenlabs: { ...e, apiKey: normalizeOptionalString(e.apiKey) } } }); } function resolveElevenLabsApiKey(...e) { return resolveSpeechProviderApiKey(...e, resolveElevenLabsApiKeyWithProfileFallback() ?? void 0, process.env.XI_API_KEY); } function resolveElevenLabsTtsRequest(e, t) { const n = readElevenLabsProviderConfig(e.providerConfig); const r = e.providerOverrides ?? {}; const i = resolveElevenLabsApiKey(n.apiKey); if (!i) throw new Error("ElevenLabs API key missing"); return { text: e.text, apiKey: i, baseUrl: n.baseUrl, voiceId: normalizeOptionalString(r.voiceId) ?? n.voiceId, modelId: normalizeElevenLabsTtsModelId(normalizeOptionalString(r.modelId)) ?? n.modelId, outputFormat: t.outputFormat, seed: normalizeElevenLabsSeed(r.seed) ?? n.seed, applyTextNormalization: normalizeOptionalString(r.applyTextNormalization) ?? n.applyTextNormalization, languageCode: normalizeOptionalString(r.languageCode) ?? n.languageCode, latencyTier: t.latencyTier, voiceSettings: { ...n.voiceSettings, ...normalizeVoiceSettings(asOptionalRecord(r.voiceSettings)) }, timeoutMs: e.timeoutMs }; } function buildElevenLabsSpeechProvider({ formatErrorMessage: e }) { const isConfigured = ({ providerConfig: e }) => Boolean(resolveElevenLabsApiKey(readElevenLabsProviderConfig(e).apiKey)); return { id: "elevenlabs", label: "ElevenLabs", autoSelectOrder: 20, defaultModel: DEFAULT_ELEVENLABS_MODEL_ID, models: ELEVENLABS_TTS_MODELS, resolveConfig: ({ rawConfig: e }) => normalizeElevenLabsProviderConfig(e), parseDirectiveToken: createSpeechDirectiveParser({ voiceid: [ "allowVoice", [ "voiceid", "voice_id", "elevenlabs_voice", "elevenlabsvoice" ], { parse: (e) => isValidElevenLabsVoiceId(e.value) ? { handled: true, overrides: { voiceId: e.value } } : { handled: true, warnings: [`invalid ElevenLabs voiceId "${e.value}"`] } } ], modelId: [ "allowModelId", [ "model", "modelid", "model_id", "elevenlabs_model", "elevenlabsmodel" ], { value: (e) => normalizeElevenLabsTtsModelId(e.value) } ], stability: [ "allowVoiceSettings", [ "stability", "similarity", "similarityboost", "similarity_boost", "style", "speed" ], { parse: (e) => { const t = e.key.startsWith("similarity") ? "similarityBoost" : e.key; const n = parseStrictFiniteNumber(e.value); if (n == null) return { handled: true, warnings: [`invalid ${t} value`] }; requireInRange(n, t === "speed" ? .5 : 0, t === "speed" ? 2 : 1, t); return { handled: true, overrides: { voiceSettings: { ...asOptionalRecord(e.currentOverrides?.voiceSettings), [t]: n } } }; } } ], speakerboost: [ "allowVoiceSettings", [ "speakerboost", "speaker_boost", "usespeakerboost", "use_speaker_boost" ], { parse: (e) => { const t = parseBooleanValue(e.value); return t == null ? { handled: true, warnings: ["invalid useSpeakerBoost value"] } : { handled: true, overrides: { voiceSettings: { ...asOptionalRecord(e.currentOverrides?.voiceSettings), useSpeakerBoost: t } } }; } } ], applyTextNormalization: [ "allowNormalization", [ "normalize", "applytextnormalization", "apply_text_normalization" ], { value: (e) => normalizeApplyTextNormalization(e.value) } ], languageCode: [ "allowNormalization", [ "language", "languagecode", "language_code" ], { value: (e) => normalizeLanguageCode(e.value) } ], seed: [ "allowSeed", ["seed"], { value: (e) => normalizeSeed(parseStrictInteger(e.value) ?? NaN) } ] }, { formatErrorMessage: e }), resolveTalkConfig: ({ baseTtsConfig: e, talkProviderConfig: t }) => { const n = normalizeElevenLabsProviderConfig(e); const r = asOptionalRecord(t.voiceSettings); const i = t.apiKey === void 0 ? resolveElevenLabsApiKey() : normalizeResolvedSecretInputString({ value: t.apiKey, path: "talk.providers.elevenlabs.apiKey" }); return { ...n, ...i === void 0 ? {} : { apiKey: i }, ...normalizeOptionalString(t.baseUrl) == null ? {} : { baseUrl: normalizeElevenLabsBaseUrl(normalizeOptionalString(t.baseUrl)) }, ...definedSettings({ voiceId: normalizeOptionalString(t.voiceId), modelId: normalizeElevenLabsTtsModelId(normalizeOptionalString(t.modelId)), seed: normalizeElevenLabsSeed(t.seed), applyTextNormalization: normalizeApplyTextNormalization(normalizeOptionalString(t.applyTextNormalization)), languageCode: normalizeLanguageCode(normalizeOptionalString(t.languageCode)) }), voiceSettings: { ...n.voiceSettings, ...normalizeVoiceSettings(r) } }; }, resolveTalkOverrides: ({ params: e }) => { const t = normalizeOptionalString(e.normalize); const n = normalizeLowercaseStringOrEmpty(normalizeOptionalString(e.language)); const r = normalizeElevenLabsLatencyTier(e.latencyTier); const i = normalizeVoiceSettings({ speed: e.speed, stability: e.stability, similarityBoost: e.similarity, style: e.style, useSpeakerBoost: e.speakerBoost }); return { ...definedSettings({ voiceId: normalizeOptionalString(e.voiceId), modelId: normalizeElevenLabsTtsModelId(normalizeOptionalString(e.modelId)), outputFormat: normalizeOptionalString(e.outputFormat), seed: normalizeElevenLabsSeed(e.seed) }), ...t == null ? {} : { applyTextNormalization: normalizeApplyTextNormalization(t) }, languageCode: normalizeLanguageCode(n), ...r == null ? {} : { latencyTier: r }, ...Object.keys(i).length === 0 ? {} : { voiceSettings: i } }; }, listVoices: async (e) => { const t = e.providerConfig ? readElevenLabsProviderConfig(e.providerConfig) : void 0; const n = resolveElevenLabsApiKey(e.apiKey, t?.apiKey); if (!n) throw new Error("ElevenLabs API key missing"); const r = normalizeElevenLabsBaseUrl(e.baseUrl ?? t?.baseUrl); const { assertOkOrThrowProviderError: i, readProviderJsonResponse: a } = await import("openclaw/plugin-sdk/provider-http"); const { fetchWithSsrFGuard: o, ssrfPolicyFromHttpBaseUrlAllowedHostname: s } = await import("openclaw/plugin-sdk/ssrf-runtime"); const { response: c, release: l } = await o({ url: `${r}/v1/voices`, init: { headers: { "xi-api-key": n } }, timeoutMs: e.timeoutMs, policy: s(r), auditContext: "elevenlabs.voices" }); try { await i(c, "ElevenLabs voices API error"); const e = await a(c, "elevenlabs.voices"); return Array.isArray(e.voices) ? e.voices.map((e) => ({ id: e.voice_id?.trim() ?? "", name: normalizeOptionalString(e.name), category: normalizeOptionalString(e.category), description: normalizeOptionalString(e.description) })).filter((e) => e.id.length > 0) : []; } finally { await l(); } }, isConfigured, isConfiguredAsync: async (e) => isConfigured(e), synthesize: async (e) => { const t = e.providerOverrides ?? {}; const n = resolveElevenLabsOutputPlan(e); return { audioBuffer: await elevenLabsTTS(resolveElevenLabsTtsRequest(e, { outputFormat: n.outputFormat, latencyTier: normalizeElevenLabsLatencyTier(t.latencyTier) })), ...n }; }, streamSynthesize: async (e) => { const t = e.providerOverrides ?? {}; const n = resolveElevenLabsOutputPlan(e); const r = resolveElevenLabsTtsRequest(e, { outputFormat: n.outputFormat, latencyTier: normalizeElevenLabsLatencyTier(t.latencyTier) }); const { createBoundedProviderBinaryStream: i } = await import("openclaw/plugin-sdk/provider-binary-stream"); const { assertProviderBinaryResponseContent: a } = await import("openclaw/plugin-sdk/provider-http"); const { response: o, release: s } = await requestElevenLabsTts(r, true); try { a(o, "ElevenLabs API error", "audio"); if (!o.body) throw new Error("ElevenLabs API response missing audio stream"); const e = i(o.body, { maxBytes: MAX_AUDIO_BYTES, createOverflowError: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`ElevenLabs API error: audio response exceeds ${e} bytes`), createReleaseError: () => /* @__PURE__ */ new Error("ElevenLabs TTS stream released"), cleanup: s }); return { audioStream: e.stream, ...n, release: e.release }; } catch (e) { await s(); throw e; } }, synthesizeTelephony: async (e) => { const t = "pcm_22050"; return { audioBuffer: await elevenLabsTTS(resolveElevenLabsTtsRequest(e, { outputFormat: t })), outputFormat: t, sampleRate: 22050 }; } }; } //#endregion //#region extensions/elevenlabs/capability-catalog.ts var capability_catalog_default = ((e) => ({ speechProviders: [buildElevenLabsSpeechProvider(e)], realtimeTranscriptionProviders: [buildElevenLabsRealtimeTranscriptionProvider(e)] })); //#endregion export { capability_catalog_default as default };