UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

270 lines (269 loc) • 10.4 kB
import { normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input"; import { createSpeechDirectiveParser, resolveSpeechProviderApiKey } from "openclaw/plugin-sdk/speech-provider"; import { asFiniteNumber, asOptionalRecord, filterStringRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime"; //#region extensions/azure-speech/speech-provider.ts const DEFAULT_AZURE_SPEECH_VOICE = "en-US-JennyNeural"; const DEFAULT_AZURE_SPEECH_LANG = "en-US"; const DEFAULT_AZURE_SPEECH_AUDIO_FORMAT = "audio-24khz-48kbitrate-mono-mp3"; const DEFAULT_AZURE_SPEECH_VOICE_NOTE_FORMAT = "ogg-24khz-16bit-mono-opus"; const DEFAULT_AZURE_SPEECH_TELEPHONY_FORMAT = "raw-8khz-8bit-mono-mulaw"; const DEFAULT_AZURE_SPEECH_VOICE_LIST_TIMEOUT_MS = 3e4; const AZURE_SPEECH_FILE_EXTENSIONS = [ ["ogg-", ".ogg"], ["webm-", ".webm"], ["riff-", ".wav"], ["raw-", ".pcm"], ["amr-", ".amr"] ]; function normalizeAzureSpeechBaseUrl(e) { const t = normalizeOptionalString(e.baseUrl) ?? normalizeOptionalString(e.endpoint); if (t) return t.replace(/\/+$/, "").replace(/\/cognitiveservices\/v1$/i, ""); const n = normalizeOptionalString(e.region); return n ? `https://${n}.tts.speech.microsoft.com` : void 0; } function azureSpeechUrl(e) { const t = normalizeAzureSpeechBaseUrl(e); if (!t) throw new Error("Azure Speech region or endpoint missing"); return `${t}${e.path}`; } function escapeXmlText(e) { return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); } function escapeXmlAttr(e) { return escapeXmlText(e).replace(/"/g, "&quot;").replace(/'/g, "&apos;"); } function readAzureVoiceTagStrings(e) { return Array.isArray(e) ? e.filter((e) => normalizeOptionalString(e) !== void 0) : void 0; } async function azureSpeechTTS(e, t) { const n = readAzureSpeechProviderConfig(e.providerConfig); const r = e.providerOverrides; const i = normalizeOptionalString(r?.voice ?? r?.voiceId); const a = normalizeOptionalString(r?.lang ?? r?.languageCode) ?? n.lang; const o = normalizeOptionalString(r?.outputFormat); const s = resolveApiKey(n.apiKey); if (!s) throw new Error("Azure Speech API key missing"); const { resolveGeneratedMediaMaxBytes: c } = await import("openclaw/plugin-sdk/media-generation-runtime"); const l = e.text; const u = t ?? o ?? (e.target === "voice-note" ? n.voiceNoteOutputFormat : n.outputFormat); const d = n.timeoutMs ?? e.timeoutMs; const f = c(e.cfg, "audio"); const p = i ?? n.voice; const m = azureSpeechUrl({ ...n, path: "/cognitiveservices/v1" }); const { assertOkOrThrowProviderError: h, readProviderBinaryResponse: g } = await import("openclaw/plugin-sdk/provider-http"); const { fetchWithSsrFGuard: _, ssrfPolicyFromHttpBaseUrlAllowedHostname: v } = await import("openclaw/plugin-sdk/ssrf-runtime"); const { response: y, release: b } = await _({ url: m, init: { method: "POST", headers: { "Content-Type": "application/ssml+xml", "Ocp-Apim-Subscription-Key": s, "X-Microsoft-OutputFormat": u, "User-Agent": "OpenClaw" }, body: `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${escapeXmlAttr(a)}"><voice name="${escapeXmlAttr(p)}">${escapeXmlText(l)}</voice></speak>` }, timeoutMs: d, policy: v(m), auditContext: "azure-speech.tts" }); try { await h(y, "Azure Speech TTS API error"); return { audioBuffer: await g(y, "Azure Speech TTS API error", "audio", { maxBytes: f, onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`Azure Speech TTS audio response exceeds ${e} bytes`) }), outputFormat: u }; } finally { await b(); } } function readAzureSpeechEnvRegion() { return normalizeOptionalString(process.env.AZURE_SPEECH_REGION) ?? normalizeOptionalString(process.env.SPEECH_REGION); } function normalizeAzureSpeechFields(e, t) { const n = normalizeOptionalString(e?.region); const r = n ?? readAzureSpeechEnvRegion(); const i = normalizeOptionalString(e?.endpoint) ?? (n ? void 0 : normalizeOptionalString(process.env.AZURE_SPEECH_ENDPOINT)); return { apiKey: t, region: r, endpoint: i, baseUrl: normalizeAzureSpeechBaseUrl({ baseUrl: normalizeOptionalString(e?.baseUrl), endpoint: i, region: r }), voice: normalizeOptionalString(e?.voice ?? e?.voiceId) ?? DEFAULT_AZURE_SPEECH_VOICE, lang: normalizeOptionalString(e?.lang ?? e?.languageCode) ?? DEFAULT_AZURE_SPEECH_LANG, outputFormat: normalizeOptionalString(e?.outputFormat) ?? DEFAULT_AZURE_SPEECH_AUDIO_FORMAT, voiceNoteOutputFormat: normalizeOptionalString(e?.voiceNoteOutputFormat) ?? DEFAULT_AZURE_SPEECH_VOICE_NOTE_FORMAT, timeoutMs: asFiniteNumber(e?.timeoutMs) }; } function normalizeAzureSpeechProviderConfig(e) { const t = asOptionalRecord(e.providers); const n = asOptionalRecord(t?.["azure-speech"]) ?? asOptionalRecord(t?.azure); return normalizeAzureSpeechFields(n, normalizeResolvedSecretInputString({ value: n?.apiKey, path: "tts.providers.azure-speech.apiKey" })); } function readAzureSpeechProviderConfig(e) { return normalizeAzureSpeechFields(e, normalizeOptionalString(e.apiKey)); } const parseDirectiveToken = createSpeechDirectiveParser({ voice: ["allowVoice", [ "voice", "voiceid", "voice_id", "azure_voice", "azurevoice", "azure_speech_voice" ]], lang: ["allowVoiceSettings", [ "lang", "language", "language_code", "languagecode", "azure_lang", "azure_language" ]], outputFormat: ["allowVoiceSettings", [ "output_format", "outputformat", "azure_format", "azure_output_format" ]] }); function resolveApiKey(...e) { return resolveSpeechProviderApiKey(...e, normalizeOptionalString(process.env.AZURE_SPEECH_KEY) ?? normalizeOptionalString(process.env.AZURE_SPEECH_API_KEY) ?? normalizeOptionalString(process.env.SPEECH_KEY)); } function buildAzureSpeechProvider() { const isConfigured = ({ providerConfig: e }) => { const t = readAzureSpeechProviderConfig(e); return Boolean(resolveApiKey(t.apiKey) && (t.baseUrl || t.region || t.endpoint)); }; return { id: "azure-speech", label: "Azure Speech", aliases: ["azure"], autoSelectOrder: 30, resolveConfig: ({ rawConfig: e }) => normalizeAzureSpeechProviderConfig(e), parseDirectiveToken, resolveTalkConfig: ({ baseTtsConfig: e, talkProviderConfig: t }) => { const n = normalizeAzureSpeechProviderConfig(e); const r = t.apiKey === void 0 ? void 0 : normalizeResolvedSecretInputString({ value: t.apiKey, path: "talk.providers.azure-speech.apiKey" }); const i = normalizeOptionalString(t.region); const a = normalizeOptionalString(t.endpoint ?? t.baseUrl); const o = normalizeAzureSpeechBaseUrl({ baseUrl: normalizeOptionalString(t.baseUrl) ?? (!i && !a ? n.baseUrl : void 0), endpoint: a, region: i ?? n.region }); return { ...n, ...filterStringRecord({ apiKey: r, region: i, endpoint: a, baseUrl: o, voice: normalizeOptionalString(t.voiceId), lang: normalizeOptionalString(t.languageCode), outputFormat: normalizeOptionalString(t.outputFormat) }) }; }, resolveTalkOverrides: ({ params: e }) => filterStringRecord({ voice: normalizeOptionalString(e.voiceId), lang: normalizeOptionalString(e.languageCode), outputFormat: normalizeOptionalString(e.outputFormat) }) ?? {}, listVoices: async (e) => { const t = e.providerConfig ? readAzureSpeechProviderConfig(e.providerConfig) : void 0; const n = resolveApiKey(e.apiKey, t?.apiKey); if (!n) throw new Error("Azure Speech API key missing"); const r = azureSpeechUrl({ baseUrl: e.baseUrl ?? t?.baseUrl, endpoint: t?.endpoint, region: t?.region ?? readAzureSpeechEnvRegion(), path: "/cognitiveservices/voices/list" }); const i = t?.timeoutMs ?? e.timeoutMs; const { assertOkOrThrowProviderError: a, readProviderJsonResponse: o } = await import("openclaw/plugin-sdk/provider-http"); const { fetchWithSsrFGuard: s, ssrfPolicyFromHttpBaseUrlAllowedHostname: c } = await import("openclaw/plugin-sdk/ssrf-runtime"); const { response: l, release: u } = await s({ url: r, init: { method: "GET", headers: { "Ocp-Apim-Subscription-Key": n } }, timeoutMs: i ?? DEFAULT_AZURE_SPEECH_VOICE_LIST_TIMEOUT_MS, policy: c(r), auditContext: "azure-speech.voices" }); try { await a(l, "Azure Speech voices API error"); const e = await o(l, "azure-speech.voices"); return Array.isArray(e) ? e.flatMap((e) => { const t = asOptionalRecord(e); const n = normalizeOptionalString(t?.ShortName); if (!t || !n || t.IsDeprecated === true || typeof t.IsDeprecated === "string" && t.IsDeprecated.toLowerCase() === "true") return []; const r = normalizeOptionalString(t.Status)?.toLowerCase(); if (r === "deprecated" || r === "retired" || r === "disabled") return []; const i = asOptionalRecord(t.VoiceTag); const a = readAzureVoiceTagStrings(i?.TailoredScenarios); const o = readAzureVoiceTagStrings(i?.VoicePersonalities); const s = [...a ?? [], ...o ?? []]; return [{ id: n, name: normalizeOptionalString(t.DisplayName) ?? normalizeOptionalString(t.LocalName), description: s.length > 0 ? s.join(", ") : void 0, locale: normalizeOptionalString(t.Locale), gender: normalizeOptionalString(t.Gender), personalities: o }]; }) : []; } finally { await u(); } }, isConfigured, isConfiguredAsync: async (e) => isConfigured(e), synthesize: async (e) => { const { audioBuffer: t, outputFormat: n } = await azureSpeechTTS(e); const r = n.toLowerCase(); return { audioBuffer: t, outputFormat: n, fileExtension: r.includes("mp3") ? ".mp3" : AZURE_SPEECH_FILE_EXTENSIONS.find(([e]) => r.startsWith(e))?.[1] ?? ".audio", voiceCompatible: r.startsWith("ogg-") && r.includes("opus") }; }, synthesizeTelephony: async (e) => { const { audioBuffer: t } = await azureSpeechTTS({ ...e, target: "telephony" }, DEFAULT_AZURE_SPEECH_TELEPHONY_FORMAT); return { audioBuffer: t, outputFormat: DEFAULT_AZURE_SPEECH_TELEPHONY_FORMAT, sampleRate: 8e3 }; } }; } //#endregion //#region extensions/azure-speech/capability-catalog.ts var capability_catalog_default = { speechProviders: [buildAzureSpeechProvider()] }; //#endregion export { capability_catalog_default as default };