UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

258 lines (257 loc) • 8.8 kB
import { readdirSync } from "node:fs"; import path from "node:path"; import { isStringArray } from "openclaw/plugin-sdk/collection-input-runtime"; import { asOptionalRecord, filterStringRecord } from "openclaw/plugin-sdk/string-coerce-runtime"; //#region extensions/tts-local-cli/speech-provider.ts const VALID_OUTPUT_FORMATS = [ "mp3", "opus", "wav" ]; const AUDIO_EXTENSIONS = /* @__PURE__ */ new Set([ ".wav", ".mp3", ".opus", ".ogg", ".m4a" ]); const DEFAULT_TIMEOUT_MS = 12e4; const MAX_AUDIO_OUTPUT_BYTES = 52428800; const MAX_CLI_STDERR_BYTES = 1048576; function normalizeOutputFormat(e) { if (typeof e !== "string") return "mp3"; const t = e.toLowerCase().trim(); return VALID_OUTPUT_FORMATS.find((e) => e === t) ?? "mp3"; } function resolveCliProviderConfig(e) { const t = asOptionalRecord(e.providers); return asOptionalRecord(t?.["tts-local-cli"]) ?? asOptionalRecord(t?.cli) ?? {}; } function getConfig(e, t = DEFAULT_TIMEOUT_MS) { const n = typeof e.command === "string" ? e.command.trim() : ""; if (!n) return null; return { command: n, args: isStringArray(e.args) ? e.args : [], outputFormat: normalizeOutputFormat(e.outputFormat), timeoutMs: typeof e.timeoutMs === "number" ? e.timeoutMs : t, cwd: typeof e.cwd === "string" ? e.cwd : void 0, env: filterStringRecord(e.env) }; } function stripEmojis(e) { return e.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu, " ").replace(/\s+/g, " ").trim(); } function applyTemplate(e, t) { return e.replace(/{{\s*(\w+)\s*}}/gi, (e, n) => { return t[n.charAt(0).toUpperCase() + n.slice(1).toLowerCase()] ?? t[n] ?? ""; }); } function parseCommand(e) { const t = []; let n = ""; let r = false; let i = false; let a = ""; for (const o of e.trim()) if (i) { if (o === a) i = false; else n += o; } else if (o === "\"" || o === "'") { r = true; i = true; a = o; } else if (o === " " || o === " ") { if (r) { t.push(n); n = ""; r = false; } } else { r = true; n += o; } if (r) t.push(n); return { cmd: t[0] || "", initialArgs: t.slice(1) }; } function findAudioFile(e, t) { const n = readdirSync(e).filter((e) => AUDIO_EXTENSIONS.has(path.extname(e).toLowerCase())); const r = n.find((e) => e.includes(t)) ?? n[0]; return r === void 0 ? null : path.join(e, r); } function hasMpegFrameHeader(e, t) { const n = e[t + 1] ?? 0; const r = e[t + 2] ?? 0; return e.length >= t + 4 && e[t] === 255 && (n & 224) === 224 && (n & 24) !== 8 && (n & 6) !== 0 && (r & 240) !== 240 && (r & 12) !== 12; } function hasId3v2MpegFrame(e) { if (e.length < 10) return false; const t = e[3] ?? 0; const n = e[4] ?? 0; const r = e[5] ?? 0; if (t < 2 || t > 4 || n === 255) return false; if ((r & (255 ^ (t === 2 ? 192 : t === 3 ? 224 : 240))) !== 0) return false; const i = e[6] ?? 0; const a = e[7] ?? 0; const o = e[8] ?? 0; const s = e[9] ?? 0; if ((i | a | o | s) & 128) return false; const c = i << 21 | a << 14 | o << 7 | s; const l = t === 4 && (r & 16) !== 0 ? 10 : 0; const u = 10 + c + l; return u < e.length && hasMpegFrameHeader(e, u); } function detectAudioFormat(e) { const t = e.toString("ascii", 0, 12); if (t.startsWith("RIFF") && t.slice(8, 12) === "WAVE") return "wav"; if (hasMpegFrameHeader(e, 0) || t.startsWith("ID3") && hasId3v2MpegFrame(e)) return "mp3"; return t.startsWith("OggS") ? "ogg" : null; } async function readAudioFile(e) { const { readRegularFileSync: t } = await import("openclaw/plugin-sdk/security-runtime"); return t({ filePath: e, maxBytes: MAX_AUDIO_OUTPUT_BYTES }).buffer; } async function synthesizeCli(e, t) { const { resolvePreferredOpenClawTmpDir: n, withTempWorkspace: r } = await import("openclaw/plugin-sdk/temp-path"); const { createSubsystemLogger: i } = await import("openclaw/plugin-sdk/runtime-env"); const a = i("tts-local-cli"); const o = getConfig(e.providerConfig, e.timeoutMs); if (!o) throw new Error("CLI TTS not configured"); const s = t === "telephony"; a.debug(`synthesize: target=${t}`); return await r({ rootDir: n(), prefix: "openclaw-cli-tts-" }, async (n) => { const r = s ? "telephony" : "speech"; const runCli = async () => { const t = stripEmojis(e.text); if (!t) throw new Error("CLI TTS: text is empty after removing emojis"); const i = { Text: t, OutputPath: path.join(n.dir, `${r}.${o.outputFormat}`), OutputDir: n.dir, OutputBase: r }; const { cmd: a, initialArgs: s } = parseCommand(o.command); if (!a) throw new Error("CLI TTS: invalid command"); const c = [...s, ...o.args]; const l = c.map((e) => applyTemplate(e, i)); const u = c.some((e) => /{{\s*text\s*}}/i.test(e)) ? "" : t; const { runCommandBuffered: d } = await import("openclaw/plugin-sdk/process-runtime"); const f = await d([a, ...l], { cwd: o.cwd, env: o.env, input: u, maxOutputBytes: { stdout: MAX_AUDIO_OUTPUT_BYTES, stderr: MAX_CLI_STDERR_BYTES }, timeoutMs: o.timeoutMs }); if (f.termination === "timeout") throw new Error(`CLI TTS timed out after ${o.timeoutMs}ms`); if (f.termination === "output-limit") { const e = f.outputLimitStream ?? "stdout"; throw new Error(`CLI TTS ${e} exceeded ${e === "stderr" ? MAX_CLI_STDERR_BYTES : MAX_AUDIO_OUTPUT_BYTES} bytes`); } if (f.code !== null && f.code !== 0) throw new Error(`CLI TTS exit ${f.code}: ${f.stderr.toString("utf8")}`); if (f.termination !== "exit" && f.termination !== "error") throw new Error(`CLI TTS failed: ${f.error?.message ?? f.termination}`); if (f.termination === "error" && f.code !== 0) throw new Error(`CLI TTS failed: ${f.error?.message ?? f.termination}`); const p = findAudioFile(n.dir, r); if (p) { const e = await readAudioFile(p); const t = detectAudioFormat(e) ?? (path.extname(p).toLowerCase() === ".m4a" ? "m4a" : null); if (!t) throw new Error(`CLI TTS: unknown format for ${p}`); return { buffer: e, actualFormat: t, audioPath: p }; } if (f.termination === "error" && f.errorStream !== "stderr") throw new Error(`CLI TTS failed: ${f.error?.message ?? f.termination}`); const m = f.stdout; if (m.length > 0) { const e = detectAudioFormat(m); if (!e) throw new Error("CLI TTS stdout audio format is not recognized; emit WAV, MP3, or Ogg Opus bytes, or write a supported audio file"); return { buffer: m, actualFormat: e }; } if (f.termination === "error") throw new Error(`CLI TTS failed: ${f.error?.message ?? f.termination}`); throw new Error("CLI TTS produced no output"); }; const i = await runCli(); if (!s) a.debug(`synthesize: format=${i.actualFormat}, size=${i.buffer.length}`); const c = s ? "pcm" : t === "voice-note" ? "opus" : o.outputFormat; let l = i.buffer; if (i.actualFormat !== c) { const e = `input.${i.actualFormat}`; const t = i.audioPath ?? path.join(n.dir, e); if (!i.audioPath) await n.write(e, i.buffer); const r = c === "pcm" ? "telephony.pcm" : `converted.${c}`; const a = [ "-y", "-i", t ]; if (c === "pcm") a.push("-c:a", "pcm_s16le", "-ar", "16000", "-ac", "1", "-f", "s16le"); else if (c === "opus") a.push("-c:a", "libopus", "-b:a", "64k", "-f", "opus"); else if (c === "wav") a.push("-c:a", "pcm_s16le", "-f", "wav"); else a.push("-c:a", "libmp3lame", "-b:a", "128k", "-f", "mp3"); const { runFfmpeg: o } = await import("openclaw/plugin-sdk/media-runtime"); const { writeExternalFileWithinRoot: s } = await import("openclaw/plugin-sdk/security-runtime"); await s({ rootDir: n.dir, path: r, write: async (e) => { await o([...a, e]); } }); l = await readAudioFile(path.join(n.dir, r)); } return { audioBuffer: l, outputFormat: c }; }); } function buildCliSpeechProvider() { const isConfigured = (e) => getConfig(e.providerConfig) !== null; return { id: "tts-local-cli", aliases: ["cli"], label: "Local CLI", autoSelectOrder: 1e3, defaultTimeoutMs: DEFAULT_TIMEOUT_MS, resolveConfig(e) { return resolveCliProviderConfig(e.rawConfig); }, isConfigured, isConfiguredAsync: async (e) => isConfigured(e), async synthesize(e) { const t = await synthesizeCli(e, e.target === "voice-note" ? "voice-note" : "audio-file"); return { ...t, fileExtension: t.outputFormat === "opus" ? ".ogg" : `.${t.outputFormat}`, voiceCompatible: e.target === "voice-note" && t.outputFormat === "opus" }; }, async synthesizeTelephony(e) { return { ...await synthesizeCli(e, "telephony"), sampleRate: 16e3 }; } }; } //#endregion //#region extensions/tts-local-cli/capability-catalog.ts var capability_catalog_default = { speechProviders: [buildCliSpeechProvider()] }; //#endregion export { capability_catalog_default as default };