UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

224 lines (223 loc) • 7.76 kB
import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { t as _usingCtx } from "../../usingCtx-rhpPzaNq.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "../../tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { t as runCommandBuffered } from "../../exec-aRIvS9s4.mjs"; import { n as resolveFfmpegBin } from "../../ffmpeg-exec-DAuj0BaS.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import "../../process-runtime-DcBPEA8Y.mjs"; import { a as createProviderOperationTimeoutResolver, r as createProviderOperationDeadline } from "../../shared-CfcMLHIP.mjs"; import { t as tempWorkspace } from "../../fs-safe-compat-Cbx7s6au.mjs"; import "../../media-ffmpeg-jfWNfuYH.mjs"; import "../../temp-path-CW7QMeae.mjs"; import { n as openProviderWebSocket } from "../../provider-http-LcawLneq.mjs"; import { t as setDeepgramQueryParam } from "../../audio-query-DOw6Aw3H.mjs"; import { open } from "node:fs/promises"; //#region extensions/deepgram/audio-flux.ts const DEEPGRAM_FLUX_SAMPLE_RATE = 16e3; const DEEPGRAM_FLUX_AUDIO_CHUNK_BYTES = 2560; const DEEPGRAM_FLUX_MAX_MESSAGE_BYTES = 1048576; const DEEPGRAM_FLUX_MAX_TRANSCRIPT_BYTES = 262144; const DEEPGRAM_FLUX_QUERY_KEYS = /* @__PURE__ */ new Set([ "eager_eot_threshold", "eot_threshold", "eot_timeout_ms", "keyterm", "language_hint", "mip_opt_out", "numerals", "profanity_filter", "redact", "tag" ]); function isDeepgramFluxModel(e) { return e?.trim().toLowerCase().startsWith("flux-") ?? false; } function readFluxEvent(e) { const t = Array.isArray(e) ? Buffer.concat(e) : Buffer.isBuffer(e) ? e : Buffer.from(e); let n; try { n = JSON.parse(t.toString("utf8")); } catch { throw new Error("Audio transcription failed: malformed JSON response"); } const r = asOptionalRecord(n); if (!r) throw new Error("Audio transcription failed: malformed JSON response"); return r; } function readFluxErrorDetail(e) { const t = asOptionalRecord(e.error); for (const n of [ e.description, e.message, t?.message ]) if (typeof n === "string" && n.trim()) return n.trim(); return "Deepgram Flux transcription error"; } function sendSocketFrame(e, t) { return new Promise((n, r) => { e.send(t, (e) => e ? r(e) : n()); }); } async function transcribeDeepgramFluxAudio(e) { try { var t = _usingCtx(); const n = createProviderOperationDeadline({ timeoutMs: e.request.timeoutMs, label: "Deepgram Flux transcription" }); const r = createProviderOperationTimeoutResolver({ deadline: n, defaultTimeoutMs: e.request.timeoutMs }); const i = t.a(await tempWorkspace({ rootDir: resolvePreferredOpenClawTmpDir(), prefix: "audio-transcription-" })).path("audio.pcm"); const a = e.request.buffer; const o = e.request.signal; const s = r(); const c = await runCommandBuffered([ resolveFfmpegBin(), "-hide_banner", "-loglevel", "error", "-i", "pipe:0", "-vn", "-sn", "-dn", "-c:a", "pcm_s16le", "-ar", String(DEEPGRAM_FLUX_SAMPLE_RATE), "-ac", "1", "-f", "s16le", i ], { input: a, maxOutputBytes: 65536, signal: o, terminateOnOutputError: true, timeoutMs: s }); if (c.termination !== "exit" || c.code !== 0) { const e = c.stderr.toString("utf8").trim(); throw new Error(`Audio transcription failed: ffmpeg ${c.termination}${e ? `: ${e}` : ""}`, { cause: c.error }); } const l = t.a(await open(i, "r")); if ((await l.stat()).size === 0) throw new Error("Audio transcription failed: decoded audio is empty"); const u = e.requestConfig.baseUrl; const d = e.request.language; const f = e.model; const p = e.request.query; const m = URL.parse(u); if (!m) throw new Error("Invalid Deepgram baseUrl: value is not a valid URL"); if (m.protocol === "http:") m.protocol = "ws:"; else if (m.protocol === "https:") m.protocol = "wss:"; else if (m.protocol !== "ws:" && m.protocol !== "wss:") throw new Error(`Invalid Deepgram baseUrl: unsupported scheme "${m.protocol}" (expected http, https, ws, or wss)`); const h = m.pathname.replace(/\/+$/u, ""); m.pathname = `${h ? h.replace(/\/v1$/u, "/v2") : "/v2"}/listen`; m.search = ""; m.searchParams.set("model", f); m.searchParams.set("encoding", "linear16"); m.searchParams.set("sample_rate", String(DEEPGRAM_FLUX_SAMPLE_RATE)); const g = { ...p, language_hint: f === "flux-general-multi" ? p?.language_hint ?? (d?.trim() || void 0) : void 0 }; for (const [e, t] of Object.entries(g)) if (t !== void 0 && DEEPGRAM_FLUX_QUERY_KEYS.has(e)) setDeepgramQueryParam(m.searchParams, e, t); const _ = m.toString(); const v = r(); const y = await openProviderWebSocket({ allowPrivateNetwork: e.requestConfig.allowPrivateNetwork, baseUrl: e.requestConfig.baseUrl, dispatcherPolicy: e.requestConfig.dispatcherPolicy, headers: e.requestConfig.headers, maxPayloadBytes: DEEPGRAM_FLUX_MAX_MESSAGE_BYTES, signal: e.request.signal, timeoutMs: v, trustConfiguredBaseUrlOrigin: e.requestConfig.trustConfiguredBaseUrlOrigin, url: _ }); return { text: await new Promise((e, t) => { const n = []; let i = 0; let a = ""; let o = false; let s = false; let c; const settle = (n) => { if (o) return; o = true; clearTimeout(c); c = void 0; if (n.error) t(n.error); else e(n.text ?? ""); }; y.on("open", () => { (async () => { try { const e = Buffer.alloc(DEEPGRAM_FLUX_AUDIO_CHUNK_BYTES); for (;;) { if (o) return; const { bytesRead: t } = await l.read(e); if (t === 0 || o) break; await sendSocketFrame(y, e.subarray(0, t)); } if (o) return; await sendSocketFrame(y, JSON.stringify({ type: "CloseStream" })); s = true; } catch (e) { settle({ error: /* @__PURE__ */ new Error(`Audio transcription failed: ${e instanceof Error ? e.message : String(e)}`) }); } })(); }); y.on("message", (e) => { try { const t = readFluxEvent(e); if (t.type === "Error" || t.type === "error") { settle({ error: /* @__PURE__ */ new Error(`Audio transcription failed: ${readFluxErrorDetail(t)}`) }); return; } if (t.type !== "TurnInfo") return; if (typeof t.transcript !== "string") throw new Error("Audio transcription response missing transcript"); if (t.event === "EndOfTurn") { i += Buffer.byteLength(t.transcript, "utf8"); n.push(t.transcript); a = ""; } else a = t.transcript; if (i + Buffer.byteLength(a, "utf8") > DEEPGRAM_FLUX_MAX_TRANSCRIPT_BYTES) settle({ error: /* @__PURE__ */ new Error("Audio transcription failed: transcript exceeds size limit") }); } catch (e) { settle({ error: e instanceof Error ? e : new Error(String(e)) }); } }); y.on("error", (e) => { settle({ error: /* @__PURE__ */ new Error(`Audio transcription failed: ${e.message}`) }); }); y.on("close", (e, t) => { if (!s) { settle({ error: /* @__PURE__ */ new Error("Audio transcription failed: Flux closed before flush") }); return; } if (e !== 1e3 && e !== 1005) { const n = t.toString().trim(); settle({ error: /* @__PURE__ */ new Error(`Audio transcription failed: Flux closed abnormally (code ${e}${n ? `: ${n}` : ""})`) }); return; } settle({ text: [...n, a].map((e) => e.trim()).filter(Boolean).join(" ") }); }); c = setTimeout(() => settle({ error: /* @__PURE__ */ new Error("Deepgram Flux transcription timed out") }), r()); }).finally(() => y.terminate()), model: e.model }; } catch (e) { t.e = e; } finally { await t.d(); } } //#endregion export { isDeepgramFluxModel, transcribeDeepgramFluxAudio };