openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
361 lines (360 loc) • 11.6 kB
JavaScript
import { t as XAI_BASE_URL } from "./model-definitions-DO0IXz00.mjs";
import { a as readXaiSpeechOverrides, c as resolveXaiSpeechResponseFormat, i as normalizeXaiTtsBaseUrl, l as xaiSpeechResponseFormatToFileExtension, n as createXaiSpeechProviderMetadata, o as readXaiSpeechProviderConfig, r as normalizeXaiLanguageCode, s as resolveDirectXaiAudioApiKey, t as XAI_TTS_FALLBACK_VOICES } from "./speech-provider-metadata-factory-lPG1xPsL.mjs";
import { t as xaiUserAgentHeaderFor } from "./xai-user-agent-DETyZ1LS.mjs";
import { t as WebSocket } from "./ws-runtime-BC0VsR8N.mjs";
import { asOptionalRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { canonicalizeBase64, rawDataToString } from "openclaw/plugin-sdk/realtime-voice-provider";
import { isProviderAuthProfileConfigured, isProviderAuthProfileConfiguredAsync } from "openclaw/plugin-sdk/provider-auth";
import { toStringifiedError } from "openclaw/plugin-sdk/error-runtime";
import { sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
//#region extensions/xai/tts.ts
const DEFAULT_TTS_MAX_BYTES = 16777216;
const XAI_TTS_VOICE_LIST_TIMEOUT_MS = 3e4;
const XAI_TTS_VOICE_LIST_MAX_BYTES = 1048576;
const XAI_TTS_STREAM_TEXT_DELTA_MAX_CHARS = 15e3;
async function listXaiTtsVoices(e) {
const t = normalizeXaiTtsBaseUrl(e.baseUrl);
const { assertOkOrThrowProviderError: n, readProviderJsonArrayFieldResponse: r } = await import("openclaw/plugin-sdk/provider-http");
const { fetchWithSsrFGuard: i, ssrfPolicyFromHttpBaseUrlAllowedOrigin: a } = await import("openclaw/plugin-sdk/ssrf-runtime");
const { response: o, release: s } = await i({
url: `${t}/tts/voices`,
init: {
method: "GET",
headers: {
Authorization: `Bearer ${e.apiKey}`,
...xaiUserAgentHeaderFor(t)
}
},
timeoutMs: XAI_TTS_VOICE_LIST_TIMEOUT_MS,
policy: a(t),
auditContext: "xai tts voices"
});
try {
await n(o, "xAI TTS voices API error");
return (await r(o, "xAI TTS voices", "voices", { maxBytes: XAI_TTS_VOICE_LIST_MAX_BYTES })).flatMap((e) => {
const t = asOptionalRecord(e);
const n = normalizeOptionalString(t?.voice_id);
if (!n) return [];
return [{
id: n,
name: normalizeOptionalString(t?.name),
locale: normalizeOptionalString(t?.language),
gender: normalizeOptionalString(t?.gender)
}];
});
} finally {
await s();
}
}
function prepareXaiTtsRequest({ language: e, responseFormat: t = "mp3", maxBytes: n = DEFAULT_TTS_MAX_BYTES, ...r }) {
const i = normalizeXaiLanguageCode(e) ?? "en";
return {
...r,
language: i,
responseFormat: t,
maxBytes: n
};
}
const XAI_NATIVE_TTS_STREAM_HOST = "api.x.ai";
async function xaiTTSStream(e) {
const t = prepareXaiTtsRequest(e);
const n = URL.parse(normalizeXaiTtsBaseUrl(t.baseUrl));
if (!n) throw new Error(`Invalid xAI TTS stream baseUrl: ${t.baseUrl}`);
if (n.protocol !== "https:") throw new Error(`xAI streaming TTS only supports HTTPS for the native ${XAI_NATIVE_TTS_STREAM_HOST} endpoint; got protocol "${n.protocol}"`);
const r = n.hostname.toLowerCase();
if (r !== XAI_NATIVE_TTS_STREAM_HOST) throw new Error(`xAI streaming TTS only supports the native ${XAI_NATIVE_TTS_STREAM_HOST} endpoint; got host "${r}"`);
const i = n.pathname.replace(/\/+$/, "");
if (n.username || n.password || n.port || i !== "/v1" || n.search || n.hash) throw new Error(`xAI streaming TTS requires the supported ${XAI_BASE_URL} base URL`);
n.protocol = "wss:";
n.pathname = `${n.pathname.replace(/\/+$/, "")}/tts`;
n.searchParams.set("language", t.language);
n.searchParams.set("voice", t.voiceId);
n.searchParams.set("codec", t.responseFormat);
if (t.speed != null) n.searchParams.set("speed", String(t.speed));
const a = n.toString();
const o = Math.ceil(t.maxBytes / 3) * 4 + 1024;
return await new Promise((e, n) => {
let r = false;
let i = false;
let s;
let c;
let l;
let errorStream;
let closeStream;
let u = false;
const clearTimers = () => {
if (c) {
clearTimeout(c);
c = void 0;
}
if (s) {
clearTimeout(s);
s = void 0;
}
};
const release = async () => {
if (i) return;
i = true;
clearTimers();
closeStream?.();
const e = l;
l = void 0;
if (!e) return;
if (e.readyState === WebSocket.OPEN || e.readyState === WebSocket.CONNECTING) e.close();
else if (e.readyState !== WebSocket.CLOSED) e.terminate();
};
const failConnect = (e) => {
if (r) return;
r = true;
release();
n(e);
};
const failStream = (e) => {
if (i || u) return;
clearTimers();
errorStream?.(e);
release();
};
const refreshSynthesisTimer = () => {
if (s) clearTimeout(s);
s = setTimeout(() => {
failStream(/* @__PURE__ */ new Error("xAI TTS stream synthesis timeout"));
}, t.timeoutMs);
};
try {
l = new WebSocket(a, {
maxPayload: o,
headers: {
Authorization: `Bearer ${t.apiKey}`,
...xaiUserAgentHeaderFor(t.baseUrl)
}
});
} catch (e) {
failConnect(toStringifiedError(e));
return;
}
c = setTimeout(() => {
failConnect(/* @__PURE__ */ new Error("xAI TTS stream connection timeout"));
}, t.timeoutMs);
l.once("unexpected-response", (e, t) => {
failConnect(/* @__PURE__ */ new Error(`xAI TTS stream connection failed (${t.statusCode ?? "unknown"}): ${t.statusMessage ?? "upgrade rejected"}`));
});
l.once("error", (e) => {
const t = toStringifiedError(e);
if (r) {
failStream(t);
return;
}
failConnect(t);
});
l.once("close", () => {
if (r) return;
failConnect(/* @__PURE__ */ new Error("xAI TTS stream connection closed before open"));
});
l.once("open", () => {
if (r) return;
r = true;
clearTimers();
refreshSynthesisTimer();
let n = 0;
let enqueue;
const a = new ReadableStream({
start(e) {
enqueue = (t) => {
if (u) return;
e.enqueue(t);
};
closeStream = () => {
if (u) return;
u = true;
e.close();
};
errorStream = (t) => {
if (u) return;
u = true;
e.error(t);
};
},
cancel() {
u = true;
release();
}
});
const handleServerEvent = (e) => {
switch (e.type) {
case "audio.delta": {
const r = normalizeOptionalString(e.delta);
if (!r) return;
const i = canonicalizeBase64(r);
if (!i) {
failStream(/* @__PURE__ */ new Error("xAI TTS stream returned malformed base64 audio data"));
return;
}
const a = Buffer.from(i, "base64");
n += a.length;
if (n > t.maxBytes) {
errorStream?.(/* @__PURE__ */ new Error(`xAI TTS audio stream exceeds ${t.maxBytes} bytes`));
release();
return;
}
enqueue?.(new Uint8Array(a));
refreshSynthesisTimer();
return;
}
case "audio.done":
release();
return;
case "error": failStream(new Error(normalizeOptionalString(e.message) ?? "xAI TTS stream error"));
}
};
l?.on("message", (e) => {
if (u || i) return;
try {
const t = rawDataToString(e);
handleServerEvent(JSON.parse(t));
} catch (e) {
failStream(toStringifiedError(e));
}
});
l?.on("close", () => {
if (u || i) return;
failStream(/* @__PURE__ */ new Error("xAI TTS stream closed before audio.done"));
});
try {
for (let e = 0; e < t.text.length;) {
const n = sliceUtf16Safe(t.text, e, e + XAI_TTS_STREAM_TEXT_DELTA_MAX_CHARS);
l?.send(JSON.stringify({
type: "text.delta",
delta: n
}));
e += n.length;
}
l?.send(JSON.stringify({ type: "text.done" }));
} catch (e) {
failStream(toStringifiedError(e));
}
e({
audioStream: a,
release
});
});
});
}
async function xaiTTS(e) {
const t = prepareXaiTtsRequest(e);
const n = normalizeXaiTtsBaseUrl(t.baseUrl);
const { assertOkOrThrowProviderError: r, postJsonRequest: i, readProviderBinaryResponse: a } = await import("openclaw/plugin-sdk/provider-http");
const { ssrfPolicyFromHttpBaseUrlAllowedOrigin: o } = await import("openclaw/plugin-sdk/ssrf-runtime");
const { response: s, release: c } = await i({
url: `${n}/tts`,
headers: new Headers({
Authorization: `Bearer ${t.apiKey}`,
"Content-Type": "application/json",
...xaiUserAgentHeaderFor(n)
}),
body: {
text: t.text,
voice_id: t.voiceId,
language: t.language,
output_format: { codec: t.responseFormat },
...t.speed != null && { speed: t.speed }
},
timeoutMs: t.timeoutMs,
fetchFn: fetch,
ssrfPolicy: o(n),
auditContext: "xai tts"
});
try {
await r(s, "xAI TTS API error");
return await a(s, "xAI TTS API error", "audio", {
maxBytes: t.maxBytes,
onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`xAI TTS audio response exceeds ${e} bytes`)
});
} finally {
await c();
}
}
//#endregion
//#region extensions/xai/speech-provider.ts
async function resolveXaiSpeechSynthesisRequest(e, t) {
const n = readXaiSpeechProviderConfig(e.providerConfig);
const r = readXaiSpeechOverrides(e.providerOverrides);
const { resolveGeneratedMediaMaxBytes: i } = await import("openclaw/plugin-sdk/media-generation-runtime");
return {
text: e.text,
apiKey: await resolveXaiAudioApiKey(n.apiKey, e.cfg),
baseUrl: n.baseUrl,
voiceId: r.voiceId ?? n.voiceId,
language: r.language ?? n.language,
speed: r.speed ?? n.speed,
responseFormat: t ?? resolveXaiSpeechResponseFormat(e.target, n.responseFormat),
timeoutMs: e.timeoutMs,
maxBytes: i(e.cfg, "audio")
};
}
function buildXaiSpeechProvider() {
return {
...createXaiSpeechProviderMetadata({
isProviderAuthProfileConfigured,
isProviderAuthProfileConfiguredAsync
}),
listVoices: async (e) => {
const t = readXaiSpeechProviderConfig(e.providerConfig ?? {});
const n = await resolveOptionalXaiAudioApiKey(normalizeOptionalString(e.apiKey) ?? t.apiKey, e.cfg);
if (!n) return XAI_TTS_FALLBACK_VOICES.map((e) => ({
id: e,
name: e
}));
return await listXaiTtsVoices({
apiKey: n,
baseUrl: normalizeXaiTtsBaseUrl(normalizeOptionalString(e.baseUrl) ?? t.baseUrl)
});
},
synthesize: async (e) => {
const t = await resolveXaiSpeechSynthesisRequest(e);
return {
audioBuffer: await xaiTTS(t),
outputFormat: t.responseFormat,
fileExtension: xaiSpeechResponseFormatToFileExtension(t.responseFormat),
voiceCompatible: false
};
},
streamSynthesize: async (e) => {
const t = await resolveXaiSpeechSynthesisRequest(e);
const n = await xaiTTSStream(t);
return {
audioStream: n.audioStream,
outputFormat: t.responseFormat,
fileExtension: xaiSpeechResponseFormatToFileExtension(t.responseFormat),
voiceCompatible: false,
release: n.release
};
},
synthesizeTelephony: async (e) => {
const t = await resolveXaiSpeechSynthesisRequest(e, "pcm");
return {
audioBuffer: await xaiTTS(t),
outputFormat: "pcm",
sampleRate: 24e3
};
}
};
}
async function resolveOptionalXaiAudioApiKey(e, t) {
const n = resolveDirectXaiAudioApiKey(e);
if (n) return n;
if (!t) return;
const { resolveApiKeyForProvider: r } = await import("openclaw/plugin-sdk/provider-auth-runtime");
const i = await r({
provider: "xai",
cfg: t
});
return normalizeOptionalString(i?.apiKey);
}
async function resolveXaiAudioApiKey(e, t) {
const n = await resolveOptionalXaiAudioApiKey(e, t);
if (n) return n;
throw new Error("xAI credentials missing for TTS. Sign in with `openclaw onboard --auth-choice xai-oauth`, or run `openclaw onboard --auth-choice xai-api-key`, or set XAI_API_KEY.");
}
//#endregion
export { buildXaiSpeechProvider };