openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
591 lines (590 loc) • 20.9 kB
JavaScript
import { n as resolveGoogleEnvApiKey } from "./.setup/gemini-auth-ChOImDFu.mjs";
import { n as GOOGLE_REALTIME_VOICE_METADATA, r as GOOGLE_PREBUILT_VOICES } from "./.setup/realtime-voice-metadata-Av6ZDzmC.mjs";
import { asOptionalRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { createLazyRuntimeSurface } from "openclaw/plugin-sdk/lazy-runtime";
import { createRealtimeVoiceAudioQueue } from "openclaw/plugin-sdk/realtime-voice-audio-queue";
import { createLazyRealtimeVoiceBridgeLifecycle } from "openclaw/plugin-sdk/realtime-voice-provider";
import { normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input";
import { createSpeechDirectiveParser, retryAsync } from "openclaw/plugin-sdk/speech-provider";
//#region extensions/google/realtime-voice-lazy.ts
const loadGoogleRealtimeVoiceProvider = createLazyRuntimeSurface(() => import("./.setup/realtime-voice-provider-Z6mfB4W-.mjs"), (e) => e.buildGoogleRealtimeVoiceProvider());
const GOOGLE_REALTIME_LAZY_MAX_PENDING_USER_MESSAGES = 128;
const GOOGLE_REALTIME_LAZY_MAX_PENDING_USER_MESSAGE_BYTES = 262144;
function createLazyGoogleRealtimeVoiceBridge(e) {
let t = false;
let n;
const r = createRealtimeVoiceAudioQueue("drop-oldest");
const i = [];
let a = 0;
const o = createLazyRealtimeVoiceBridgeLifecycle({
label: "Google",
request: e,
load: async (e) => (await loadGoogleRealtimeVoiceProvider()).createBridge(e),
clearPending: () => {
t = false;
r.clear();
i.length = 0;
a = 0;
n = void 0;
},
onProviderReady: (e) => {
if (e) {
t = true;
flushPending(e);
}
}
});
const requireBridge = () => {
const e = o.bridge;
if (!e) throw new Error("Google realtime voice bridge is not connected");
return e;
};
const flushPending = (e) => {
if (!o.isActive()) return;
for (const t of r.drain()) e.sendAudio(t);
const t = i.splice(0);
a = 0;
for (const n of t) e.sendUserMessage?.(n);
if (n !== void 0) {
const t = n;
n = void 0;
e.triggerGreeting?.(t);
}
};
return {
get supportsToolResultContinuation() {
return o.bridge?.supportsToolResultContinuation ?? false;
},
supportsToolResultSuppression: false,
connect: o.connect,
sendAudio: (e) => {
if (!o.isActive()) return;
const n = o.bridge;
if (t && n) {
n.sendAudio(e);
return;
}
r.enqueue(e);
},
setMediaTimestamp: () => {},
sendUserMessage: (n) => {
if (!o.isActive()) return;
const r = o.bridge;
if (t && r) {
r.sendUserMessage?.(n);
return;
}
const s = Buffer.byteLength(n, "utf8");
if (i.length >= GOOGLE_REALTIME_LAZY_MAX_PENDING_USER_MESSAGES || a + s > GOOGLE_REALTIME_LAZY_MAX_PENDING_USER_MESSAGE_BYTES) {
e.onError?.(/* @__PURE__ */ new Error("Google realtime voice pending user message queue overflow during startup"));
return;
}
i.push(n);
a += s;
},
triggerGreeting: (e) => {
if (!o.isActive()) return;
const r = o.bridge;
if (t && r) {
r.triggerGreeting?.(e);
return;
}
n = e;
},
handleBargeIn: (e) => {
if (o.isActive()) requireBridge().handleBargeIn?.(e);
},
submitToolResult: (e, t, n) => {
if (!o.isActive()) return;
return requireBridge().submitToolResult(e, t, n);
},
acknowledgeMark: () => {},
close: o.close,
isConnected: () => o.isActive() && (o.bridge?.isConnected() ?? false)
};
}
function createLazyGoogleRealtimeVoiceProvider() {
const resolveConfig = ({ cfg: e, rawConfig: t }) => {
const n = asOptionalRecord(t.providers);
const r = asOptionalRecord(n?.google) ?? asOptionalRecord(t.google) ?? t;
return {
...r,
...r.apiKey === void 0 ? e?.models?.providers?.google?.apiKey === void 0 ? {} : { apiKey: normalizeResolvedSecretInputString({
value: e.models.providers.google.apiKey,
path: "models.providers.google.apiKey"
}) } : { apiKey: normalizeResolvedSecretInputString({
value: r.apiKey,
path: "plugins.entries.voice-call.config.realtime.providers.google.apiKey"
}) }
};
};
const isConfigured = ({ cfg: e, providerConfig: t }) => Boolean(normalizeOptionalString(t.apiKey) ?? normalizeOptionalString(e?.models?.providers?.google?.apiKey) ?? resolveGoogleEnvApiKey());
return {
...GOOGLE_REALTIME_VOICE_METADATA,
resolveConfig,
isConfigured,
resolveConfigAsync: async (e) => resolveConfig(e),
isConfiguredAsync: async (e) => isConfigured(e),
createBridge: createLazyGoogleRealtimeVoiceBridge,
createBrowserSession: async (e) => {
const t = await loadGoogleRealtimeVoiceProvider();
if (!t.createBrowserSession) throw new Error("Google realtime voice browser sessions are unavailable");
return await t.createBrowserSession(e);
}
};
}
//#endregion
//#region extensions/google/speech-models.ts
const DEFAULT_GOOGLE_TTS_MODEL = "gemini-3.1-flash-tts-preview";
const DEFAULT_GOOGLE_TTS_VOICE = "Kore";
const GOOGLE_TTS_SAMPLE_RATE = 24e3;
const GOOGLE_AUDIO_PROFILE_PROMPT_TEMPLATE = "audio-profile-v1";
const GOOGLE_TTS_INTERACTIONS_MODELS = ["gemini-3.8-flash-tts", "gemini-3.8-flash-lite-tts"];
const GOOGLE_TTS_GENERATE_CONTENT_MODELS = [
"gemini-3.1-flash-tts-preview",
"gemini-2.5-flash-preview-tts",
"gemini-2.5-pro-preview-tts"
];
const GOOGLE_TTS_MODELS = [...GOOGLE_TTS_INTERACTIONS_MODELS, ...GOOGLE_TTS_GENERATE_CONTENT_MODELS];
function normalizeGoogleTtsModel(e) {
const t = normalizeOptionalString(e);
if (!t) return DEFAULT_GOOGLE_TTS_MODEL;
const n = t.startsWith("google/") ? t.slice(7) : t;
return n === "gemini-3.1-flash-tts" ? "gemini-3.1-flash-tts-preview" : n;
}
function isGoogleInteractionsTtsModel(e) {
return GOOGLE_TTS_INTERACTIONS_MODELS.some((t) => t === e);
}
function assertSupportedGoogleTtsModel(e) {
if (isGoogleInteractionsTtsModel(e)) return;
if (e.includes("gemini-3.8-") && e.includes("-tts")) throw new Error(`Google TTS model ${e} is not supported. OpenClaw sends Gemini 3.8 TTS through the Interactions API; supported models: ${GOOGLE_TTS_INTERACTIONS_MODELS.join(", ")}.`);
}
function normalizeGoogleTtsVoiceName(e) {
return normalizeOptionalString(e) ?? DEFAULT_GOOGLE_TTS_VOICE;
}
function normalizeGooglePromptTemplate(e) {
const t = normalizeOptionalString(e);
if (!t) return;
if (t === "audio-profile-v1") return t;
throw new Error(`Invalid Google TTS promptTemplate: ${t}`);
}
//#endregion
//#region extensions/google/speech-provider.ts
function readGoogleTtsSpeakers(e) {
if (e == null) return;
if (!Array.isArray(e)) throw new Error("Google TTS speakers must be an array of exactly two { speaker, voice } entries.");
const t = e.map((e, t) => {
const n = asOptionalRecord(e);
const r = normalizeOptionalString(n?.speaker ?? n?.name);
const i = normalizeOptionalString(n?.voice ?? n?.voiceName);
const a = normalizeOptionalString(n?.style);
if (!r || !i) throw new Error(`Google TTS speakers[${t}] needs a speaker name and a voice.`);
return {
speaker: r,
voice: i,
...a ? { style: a } : {}
};
});
if (t.length !== 2) throw new Error("Google TTS multi-speaker requires exactly two speakers.");
if (new Set(t.map((e) => e.speaker)).size !== 2) throw new Error("Google TTS speakers must use two different speaker names.");
return t;
}
function splitGoogleTtsDialogue(e, t) {
const n = new Set(t.map((e) => e.speaker));
const r = [];
const i = [];
for (const t of e.replace(/\r\n?/g, "\n").split("\n")) {
const e = t.trim();
if (!e) continue;
const a = /^([^:\n]{1,80}):([\s\S]*)$/u.exec(e);
const o = a?.[1]?.trim();
if (a && o && n.has(o)) {
const e = a[2]?.trim();
if (!e) continue;
if (r.length === 0 && i.length > 0) r.push({
speaker: o,
text: i.splice(0).join(" ")
});
const t = r.at(-1);
if (t?.speaker === o) t.text = `${t.text} ${e}`;
else r.push({
speaker: o,
text: e
});
continue;
}
const s = r.at(-1);
if (s) s.text = `${s.text} ${e}`;
else i.push(e);
}
if (r.length === 0) return;
return r;
}
function composeGoogleInteractionsSpeechStyle(e) {
return e.filter((e) => e !== void 0).join("\n\n") || void 0;
}
const GOOGLE_TTS_CHANNELS = 1;
const GOOGLE_TTS_BITS_PER_SAMPLE = 16;
var GoogleTtsRetryableError = class extends Error {
constructor(e) {
super(e);
this.name = "GoogleTtsRetryableError";
}
};
function isGoogleTtsRetryableError(e) {
if (e instanceof GoogleTtsRetryableError) return true;
if (!(e instanceof Error)) return false;
if (e.name === "AbortError") return true;
const t = e.message.toLowerCase();
return t.includes("aborted") || t.includes("timeout") || t.includes("fetch failed") || t.includes("network");
}
function normalizePromptSectionText(e) {
const t = normalizeOptionalString(e?.replace(/\r\n?/g, "\n"));
if (!t) return;
return t.replace(/\p{Cc}/gu, (e) => " \n\r".includes(e) || e.charCodeAt(0) > 127 ? e : "");
}
function isOpenClawGoogleAudioProfilePrompt(e) {
return e.includes("# AUDIO PROFILE:") && e.includes("### TRANSCRIPT") && e.startsWith("Synthesize speech from the TRANSCRIPT section only.");
}
function wrapPcm16MonoToWav(e, t = GOOGLE_TTS_SAMPLE_RATE) {
const n = t * GOOGLE_TTS_CHANNELS * (GOOGLE_TTS_BITS_PER_SAMPLE / 8);
const r = GOOGLE_TTS_CHANNELS * (GOOGLE_TTS_BITS_PER_SAMPLE / 8);
const i = Buffer.alloc(44);
i.write("RIFF", 0, "ascii");
i.writeUInt32LE(36 + e.length, 4);
i.write("WAVE", 8, "ascii");
i.write("fmt ", 12, "ascii");
i.writeUInt32LE(16, 16);
i.writeUInt16LE(1, 20);
i.writeUInt16LE(GOOGLE_TTS_CHANNELS, 22);
i.writeUInt32LE(t, 24);
i.writeUInt32LE(n, 28);
i.writeUInt16LE(r, 32);
i.writeUInt16LE(GOOGLE_TTS_BITS_PER_SAMPLE, 34);
i.write("data", 36, "ascii");
i.writeUInt32LE(e.length, 40);
return Buffer.concat([i, e]);
}
function stripWavContainerToPcm(e) {
if (e.subarray(0, 4).toString("ascii") !== "RIFF" || e.subarray(8, 12).toString("ascii") !== "WAVE") return e;
let t = 12;
while (t + 8 <= e.length) {
const n = e.subarray(t, t + 4).toString("ascii");
const r = e.readUInt32LE(t + 4);
const i = t + 8;
if (n === "data") return e.subarray(i, Math.min(i + r, e.length));
t = i + r + r % 2;
}
throw new Error("Google TTS WAV response missing PCM data");
}
function readGoogleInteractionsAudioData(e) {
const t = normalizeOptionalString(e.output_audio?.data ?? e.outputAudio?.data);
if (t) return t;
for (const t of e.steps ?? []) for (const e of t.content ?? []) {
const t = e.mimeType ?? e.mime_type;
if (e.type !== "audio" && !t?.startsWith("audio/")) continue;
const n = normalizeOptionalString(e.data);
if (n) return n;
}
}
function resolveGoogleTtsApiKey(e) {
return e.providerConfig.apiKey ?? normalizeResolvedSecretInputString({
value: e.cfg?.models?.providers?.google?.apiKey,
path: "models.providers.google.apiKey"
}) ?? resolveGoogleEnvApiKey();
}
function normalizeGoogleTtsProviderConfig(e) {
const t = asOptionalRecord(e.providers);
const n = asOptionalRecord(t?.google);
return {
...readGoogleTtsProviderConfig(n ?? {}),
apiKey: normalizeResolvedSecretInputString({
value: n?.apiKey,
path: "tts.providers.google.apiKey"
})
};
}
function readGoogleTtsProviderConfig(e) {
const t = normalizeGooglePromptTemplate(e.promptTemplate);
const n = normalizeOptionalString(e.personaPrompt);
const r = readGoogleTtsSpeakers(e.speakers);
return {
apiKey: normalizeOptionalString(e.apiKey),
baseUrl: normalizeOptionalString(e.baseUrl),
model: normalizeGoogleTtsModel(e.model),
voiceName: normalizeGoogleTtsVoiceName(e.voiceName ?? e.voice),
audioProfile: normalizeOptionalString(e.audioProfile),
speakerName: normalizeOptionalString(e.speakerName),
...r ? { speakers: r } : {},
...t ? { promptTemplate: t } : {},
...n ? { personaPrompt: n } : {}
};
}
function readGoogleTtsOverrides(e) {
if (!e) return {};
return {
model: normalizeOptionalString(e.model),
voiceName: normalizeOptionalString(e.voiceName ?? e.voice),
audioProfile: normalizeOptionalString(e.audioProfile),
speakerName: normalizeOptionalString(e.speakerName)
};
}
const parseDirectiveToken = createSpeechDirectiveParser({
voiceName: ["allowVoice", [
"voicename",
"voice_name",
"google_voice",
"googlevoice"
]],
model: ["allowModelId", ["google_model", "googlemodel"]]
});
async function synthesizeConfiguredGoogleTts(e) {
const t = readGoogleTtsProviderConfig(e.providerConfig);
const n = readGoogleTtsOverrides(e.providerOverrides);
const r = resolveGoogleTtsApiKey({
cfg: e.cfg,
providerConfig: t
});
if (!r) throw new Error("Google API key missing");
const { sanitizeConfiguredModelProviderRequest: i } = await import("openclaw/plugin-sdk/provider-http");
const { isTransientNetworkError: a } = await import("openclaw/plugin-sdk/retry-runtime");
const o = {
text: e.text,
apiKey: r,
baseUrl: t.baseUrl ?? normalizeOptionalString(e.cfg?.models?.providers?.google?.baseUrl),
request: i(e.cfg?.models?.providers?.google?.request),
model: normalizeGoogleTtsModel(n.model ?? t.model),
voiceName: normalizeGoogleTtsVoiceName(n.voiceName ?? t.voiceName),
audioProfile: n.audioProfile ?? t.audioProfile,
speakerName: n.speakerName ?? t.speakerName,
speakers: t.speakers,
personaPrompt: t.personaPrompt,
timeoutMs: e.timeoutMs
};
assertSupportedGoogleTtsModel(o.model);
const s = isGoogleInteractionsTtsModel(o.model);
const c = o.speakers ? splitGoogleTtsDialogue(o.text, o.speakers) : void 0;
if (!s && c) throw new Error("Google TTS multi-speaker dialogue requires gemini-3.8-flash-tts or gemini-3.8-flash-lite-tts.");
return retryAsync(async () => {
const { assertOkOrThrowProviderError: e, postJsonRequest: t, readProviderJsonResponse: n } = await import("openclaw/plugin-sdk/provider-http");
const { resolveGoogleGenerativeAiHttpRequestConfig: r } = await import("./.setup/http-request-BR8H-iw1.mjs");
const { canonicalizeGoogleProviderBase64: i } = await import("./.setup/base64-DFzsIO8d.mjs");
const { baseUrl: a, allowPrivateNetwork: l, headers: u, dispatcherPolicy: d } = r({
apiKey: o.apiKey,
baseUrl: o.baseUrl,
request: o.request,
capability: "audio",
transport: "http"
});
let f;
if (s) {
let e;
if (c) e = c.map((e) => {
const t = o.speakers?.find((t) => t.speaker === e.speaker);
const n = composeGoogleInteractionsSpeechStyle([
t?.style,
o.audioProfile,
o.personaPrompt
]);
return {
type: "text",
text: e.text,
annotations: [{
type: "speech_metadata",
speaker: e.speaker,
...n ? { style: n } : {}
}]
};
});
else {
const t = composeGoogleInteractionsSpeechStyle([o.audioProfile, o.personaPrompt]);
const n = o.speakerName;
const r = {
type: "text",
text: o.text
};
if (t || n) r.annotations = [{
type: "speech_metadata",
...n ? { speaker: n } : {},
...t ? { style: t } : {}
}];
e = [r];
}
f = {
model: o.model,
store: false,
input: [{
type: "user_input",
content: e
}],
response_format: {
type: "audio",
mime_type: "audio/l16",
sample_rate: GOOGLE_TTS_SAMPLE_RATE
},
generation_config: c ? { speech_config: {
mode: "conversational",
speakers: o.speakers?.map((e) => ({
speaker: e.speaker,
voice: e.voice
}))
} } : { speech_config: [{ voice: o.voiceName }] }
};
}
const { response: p, release: m } = await t({
url: s ? `${a}/interactions` : `${a}/models/${o.model}:generateContent`,
headers: u,
body: s ? f : {
contents: [{
role: "user",
parts: [{ text: [
o.audioProfile,
o.speakerName ? `Speaker name: ${o.speakerName}` : void 0,
o.text
].filter((e) => e !== void 0).join("\n\n") }]
}],
generationConfig: {
responseModalities: ["AUDIO"],
speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: o.voiceName } } }
}
},
timeoutMs: o.timeoutMs,
fetchFn: fetch,
pinDns: false,
allowPrivateNetwork: l,
dispatcherPolicy: d
});
try {
if (!p.ok) try {
await e(p, "Google TTS failed", { requestHeaders: u });
} catch (e) {
const t = e instanceof Error ? e.message : String(e);
if (p.status >= 500 && p.status < 600) throw new GoogleTtsRetryableError(t);
throw e;
}
const t = await n(p, "Google TTS response", {
requestHeaders: u,
onIdleTimeout: ({ chunkTimeoutMs: e }) => new GoogleTtsRetryableError(`Google TTS response: response body stalled for ${e}ms`)
});
const r = s ? readGoogleInteractionsAudioData(t) : t.candidates?.flatMap((e) => e.content?.parts ?? []).map((e) => normalizeOptionalString((e.inlineData ?? e.inline_data)?.data)).find((e) => e !== void 0);
if (!r) throw new GoogleTtsRetryableError("Google TTS response missing audio data");
const a = i(r);
if (!a) throw new Error("Google TTS response returned malformed base64 audio data");
return stripWavContainerToPcm(Buffer.from(a, "base64"));
} finally {
await m();
}
}, {
attempts: 2,
minDelayMs: 0,
shouldRetry: (e) => isGoogleTtsRetryableError(e) || a(e)
});
}
function buildGoogleSpeechProvider() {
const isConfigured = ({ cfg: e, providerConfig: t }) => Boolean(resolveGoogleTtsApiKey({
cfg: e,
providerConfig: readGoogleTtsProviderConfig(t)
}));
return {
id: "google",
label: "Google",
autoSelectOrder: 50,
defaultModel: DEFAULT_GOOGLE_TTS_MODEL,
models: GOOGLE_TTS_MODELS,
voices: GOOGLE_PREBUILT_VOICES,
resolveConfig: ({ rawConfig: e }) => normalizeGoogleTtsProviderConfig(e),
parseDirectiveToken,
resolveTalkConfig: ({ baseTtsConfig: e, talkProviderConfig: t }) => {
const n = normalizeGoogleTtsProviderConfig(e);
const r = normalizeOptionalString(t.baseUrl);
return {
...n,
...t.apiKey === void 0 ? {} : { apiKey: normalizeResolvedSecretInputString({
value: t.apiKey,
path: "talk.providers.google.apiKey"
}) },
...r ? { baseUrl: r } : {},
...normalizeOptionalString(t.modelId) == null ? {} : { model: normalizeGoogleTtsModel(t.modelId) },
...normalizeOptionalString(t.voiceId) == null ? {} : { voiceName: normalizeGoogleTtsVoiceName(t.voiceId) }
};
},
resolveTalkOverrides: ({ params: e }) => ({
...normalizeOptionalString(e.voiceId) == null ? {} : { voiceName: normalizeGoogleTtsVoiceName(e.voiceId) },
...normalizeOptionalString(e.modelId) == null ? {} : { model: normalizeGoogleTtsModel(e.modelId) }
}),
listVoices: async () => GOOGLE_PREBUILT_VOICES.map((e) => ({
id: e,
name: e
})),
isConfigured,
isConfiguredAsync: async (e) => isConfigured(e),
prepareSynthesis: (e) => {
const t = readGoogleTtsProviderConfig(e.providerConfig);
const n = readGoogleTtsOverrides(e.providerOverrides);
const r = normalizeGoogleTtsModel(n.model ?? t.model);
assertSupportedGoogleTtsModel(r);
if (isGoogleInteractionsTtsModel(r)) {
if (!isOpenClawGoogleAudioProfilePrompt(e.text)) return;
const t = /\n\n### TRANSCRIPT(?:\n|$)/u.exec(e.text);
if (!t) return;
const n = e.text.slice(t.index + t[0].length).trim();
return n ? { text: n } : void 0;
}
if (!(t.promptTemplate === "audio-profile-v1" || Boolean(t.personaPrompt)) || isOpenClawGoogleAudioProfilePrompt(e.text)) return;
const i = e.text.replace(/\r\n?/g, "\n").trim();
const a = normalizePromptSectionText(t.personaPrompt);
const o = normalizePromptSectionText(e.persona?.label) ?? normalizePromptSectionText(e.persona?.id);
const s = [[
"Synthesize speech from the TRANSCRIPT section only. Use the other sections only",
"as performance direction. Do not read section titles, notes, labels, or",
"configuration aloud."
].join("\n")];
if (o) s.push(`# AUDIO PROFILE: ${o}`);
if (a) s.push([
"### DIRECTOR'S NOTES",
"Provider notes:",
a
].join("\n"));
s.push(["### TRANSCRIPT", i].join("\n"));
return { text: s.join("\n\n") };
},
synthesize: async (e) => {
const t = await synthesizeConfiguredGoogleTts(e);
if (e.target === "voice-note") {
const { transcodeAudioBufferToOpus: n } = await import("openclaw/plugin-sdk/media-runtime");
return {
audioBuffer: await n({
audioBuffer: wrapPcm16MonoToWav(t),
inputExtension: "wav",
tempPrefix: "tts-google-",
timeoutMs: e.timeoutMs
}),
outputFormat: "opus",
fileExtension: ".opus",
voiceCompatible: true
};
}
return {
audioBuffer: wrapPcm16MonoToWav(t),
outputFormat: "wav",
fileExtension: ".wav",
voiceCompatible: false
};
},
synthesizeTelephony: async (e) => {
return {
audioBuffer: await synthesizeConfiguredGoogleTts(e),
outputFormat: "pcm",
sampleRate: GOOGLE_TTS_SAMPLE_RATE
};
}
};
}
//#endregion
//#region extensions/google/capability-catalog.ts
var capability_catalog_default = {
speechProviders: [buildGoogleSpeechProvider()],
realtimeVoiceProviders: [createLazyGoogleRealtimeVoiceProvider()]
};
//#endregion
export { capability_catalog_default as default };