UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

222 lines (221 loc) • 8.06 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as appendConfigPathSegment } from "./dot-path-BJ4tyWKJ.mjs"; import { f as normalizeResolvedSecretInputString } from "./types.secrets-BmNLLnHp.mjs"; import "./secret-input-CpgOwFAi.mjs"; import { t as parseSpeechDirectiveNumberOverride } from "./directive-number-DokwHJHi.mjs"; //#region src/tts/directive-parser.ts /** Share alias dispatch and policy gating while providers retain their value contracts. */ function createSpeechDirectiveParser(e, t) { const n = new Map(Object.entries(e).flatMap(([e, [t, n, r]]) => n.map((n) => [n, { overrideKey: e, policy: t, ...r }]))); return (e) => { const r = n.get(e.key); if (!r) return { handled: false }; if (!e.policy[r.policy]) return { handled: true }; try { return r.parse ? r.parse(e) : r.number ? parseSpeechDirectiveNumberOverride({ ctx: e, overrideKey: r.overrideKey, ...r.number }) : { handled: true, overrides: { [r.overrideKey]: r.value ? r.value(e) : e.value } }; } catch (e) { if (!t?.formatErrorMessage) throw e; return { handled: true, warnings: [t.formatErrorMessage(e)] }; } }; } //#endregion //#region src/tts/openai-compatible-speech-provider.ts function resolveConfiguredSpeechVoice(e) { return normalizeOptionalString(e?.speakerVoice) ?? normalizeOptionalString(e?.speakerVoiceId) ?? normalizeOptionalString(e?.voice) ?? normalizeOptionalString(e?.voiceId); } function trimTrailingBaseUrl(e, t) { return (normalizeOptionalString(e) ?? t).replace(/\/+$/u, ""); } function readModelProviderConfig(e, t) { const n = asOptionalRecord(e); const r = asOptionalRecord(n?.models); const i = asOptionalRecord(r?.providers); return asOptionalRecord(i?.[t]); } function buildExtraJsonBodyFields(e, t) { const n = {}; for (const r of t ?? []) { const t = e[r.configKey]; if (t != null) n[r.requestKey ?? r.configKey] = t; } return n; } /** Build a complete SpeechProviderPlugin for OpenAI-compatible speech endpoints. */ function createOpenAiCompatibleSpeechProvider(e) { const t = e.configKey ?? e.id; const n = t.replace(/[^a-z0-9]+/giu, "").toLowerCase(); const r = createSpeechDirectiveParser({ voice: ["allowVoice", [ "voice", "voice_id", "voiceid", `${t}_voice`, `${n}voice` ]], model: ["allowModelId", [ "model", "model_id", "modelid", `${t}_model`, `${n}model` ]] }); const i = e.normalizeModel ?? ((e, t) => normalizeOptionalString(e) ?? t); const a = e.readExtraConfig ?? (() => ({})); function normalizeResponseFormat(t) { const n = normalizeOptionalLowercaseString(t); if (n && !e.responseFormats.includes(n)) throw new Error(`Invalid ${e.label} speech responseFormat: ${n}`); return n; } function normalizeBaseUrl(t) { const n = trimTrailingBaseUrl(t, e.defaultBaseUrl); const r = e.baseUrlPolicy; if (r?.kind !== "canonical") return n; const i = trimTrailingBaseUrl(e.defaultBaseUrl, e.defaultBaseUrl); const a = [i, ...r.aliases ?? []]; return !r.allowCustom || a.some((e) => trimTrailingBaseUrl(e, i) === n) ? i : n; } function normalizeConfig(n) { const r = asOptionalRecord(asOptionalRecord(n.providers)?.[t]) ?? asOptionalRecord(n[t]); return readProviderConfig(r, { model: e.defaultModel, voice: e.defaultVoice, apiKey: normalizeResolvedSecretInputString({ value: r?.apiKey, path: `${appendConfigPathSegment("tts.providers", t)}.apiKey` }) }); } function readProviderConfig(e, t = normalizeConfig({})) { return { apiKey: normalizeOptionalString(e?.apiKey) ?? t.apiKey, baseUrl: normalizeOptionalString(e?.baseUrl) == null ? t.baseUrl : normalizeBaseUrl(e?.baseUrl), model: i(normalizeOptionalString(e?.model ?? e?.modelId), t.model), voice: resolveConfiguredSpeechVoice(e) ?? t.voice, speed: asFiniteNumber(e?.speed) ?? t.speed, responseFormat: normalizeResponseFormat(e?.responseFormat) ?? t.responseFormat, ...a(e) }; } function resolveApiKey(n) { return n.providerConfig.apiKey ?? normalizeResolvedSecretInputString({ value: readModelProviderConfig(n.cfg, t)?.apiKey, path: `${appendConfigPathSegment("models.providers", t)}.apiKey` }) ?? normalizeOptionalString(process.env[e.envKey]); } return { id: e.id, label: e.label, autoSelectOrder: e.autoSelectOrder, defaultModel: e.defaultModel, defaultTimeoutMs: e.defaultTimeoutMs, models: [...e.models], voices: [...e.voices], resolveConfig: ({ rawConfig: e }) => normalizeConfig(e), parseDirectiveToken: r, resolveTalkConfig: ({ baseTtsConfig: n, talkProviderConfig: r }) => { const a = normalizeConfig(n); const o = normalizeResponseFormat(r.responseFormat); if (r.apiKey !== void 0) a.apiKey = normalizeResolvedSecretInputString({ value: r.apiKey, path: `${appendConfigPathSegment("talk.providers", t)}.apiKey` }); const s = normalizeOptionalString(r.baseUrl); if (s !== void 0) a.baseUrl = normalizeBaseUrl(s); const c = normalizeOptionalString(r.modelId); if (c !== void 0) a.model = i(c, e.defaultModel); a.voice = resolveConfiguredSpeechVoice(r) ?? a.voice; const l = asFiniteNumber(r.speed); if (l !== void 0) a.speed = l; if (o !== void 0) a.responseFormat = o; return a; }, resolveTalkOverrides: ({ params: e }) => ({ ...normalizeOptionalString(e.voiceId ?? e.voice) == null ? {} : { voice: normalizeOptionalString(e.voiceId ?? e.voice) }, ...normalizeOptionalString(e.modelId ?? e.model) == null ? {} : { model: normalizeOptionalString(e.modelId ?? e.model) }, ...asFiniteNumber(e.speed) == null ? {} : { speed: asFiniteNumber(e.speed) } }), listVoices: async () => e.voices.map((e) => ({ id: e, name: e })), isConfigured: ({ cfg: e, providerConfig: t }) => Boolean(resolveApiKey({ cfg: e, providerConfig: readProviderConfig(t) })), synthesize: async (n) => { const r = readProviderConfig(n.providerConfig); const a = n.providerOverrides; const o = normalizeOptionalString(a?.model ?? a?.modelId); const s = normalizeOptionalString(a?.voice ?? a?.voiceId); const c = asFiniteNumber(a?.speed) ?? r.speed; const l = resolveApiKey({ cfg: n.cfg, providerConfig: r }); if (!l) throw new Error(e.missingApiKeyError ?? `${e.label} API key missing`); const u = normalizeBaseUrl(r.baseUrl ?? readModelProviderConfig(n.cfg, t)?.baseUrl); const d = r.responseFormat ?? e.defaultResponseFormat; const { assertOkOrThrowHttpError: f, postJsonRequest: p, readProviderBinaryResponse: m, resolveProviderHttpRequestConfig: h } = await import("./plugin-sdk/provider-http.js"); const { allowPrivateNetwork: g, headers: _, dispatcherPolicy: v } = h({ baseUrl: u, defaultBaseUrl: e.defaultBaseUrl, allowPrivateNetwork: false, defaultHeaders: { Authorization: `Bearer ${l}`, "Content-Type": "application/json", ...e.extraHeaders }, provider: e.id, capability: "audio", transport: "http" }); const { response: y, release: b } = await p({ url: `${u}/audio/speech`, headers: _, body: { model: i(o ?? r.model, e.defaultModel), input: n.text, voice: s ?? r.voice, response_format: d, ...c == null ? {} : { speed: c }, ...buildExtraJsonBodyFields(r, e.extraJsonBodyFields) }, timeoutMs: n.timeoutMs, fetchFn: fetch, allowPrivateNetwork: g, dispatcherPolicy: v }); try { await f(y, e.apiErrorLabel ?? `${e.label} TTS API error`); return { audioBuffer: await m(y, e.apiErrorLabel ?? `${e.label} TTS API error`, "audio"), outputFormat: d, fileExtension: `.${d}`, voiceCompatible: e.voiceCompatibleResponseFormats.includes(d) }; } finally { await b(); } } }; } //#endregion export { createSpeechDirectiveParser as n, createOpenAiCompatibleSpeechProvider as t };