UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

247 lines (246 loc) • 8.48 kB
import { d as pathExists } from "./fs-safe-BbWvmdVn.mjs"; import { i as resolveEnvironmentValue } from "./process-env-DVJdcOcM.mjs"; import { a as resolveExecutableFromPathEnv } from "./executable-path-D8oWZRS5.mjs"; import { i as getOrCreatePromise } from "./lazy-promise-DiCvjz9w.mjs"; import { n as runExec } from "./exec-aRIvS9s4.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/media-understanding/local-audio.ts const WHISPER_CPP_MODEL_DIRS = [ "/opt/homebrew/share/whisper-cpp", "/usr/local/share/whisper-cpp", "/usr/share/whisper-cpp" ]; async function listDirectoryEntries(e) { try { return await fs.readdir(e); } catch { return []; } } /** * Picks an installed ggml whisper.cpp model without hardcoding a filename. * Larger models transcribe better, so prefer non-tiny when several exist; * WHISPER_CPP_MODEL remains the explicit override. */ async function discoverWhisperCppModel() { for (const e of WHISPER_CPP_MODEL_DIRS) { const t = (await listDirectoryEntries(e)).filter((e) => e.startsWith("ggml-") && e.endsWith(".bin")).toSorted((e, t) => { return (e.includes("tiny") ? 1 : 0) - (t.includes("tiny") ? 1 : 0) || e.localeCompare(t); }); if (t[0]) return path.join(e, t[0]); } return null; } const libraryCache = /* @__PURE__ */ new Map(); const observedBackendCache = /* @__PURE__ */ new Map(); function commandId(e) { return path.basename(e.trim()).replace(/\.(?:exe|com|cmd|bat)$/i, "").toLowerCase(); } function resolveRequestedLocalAudioBackend(e) { const t = commandId(e.command); if (t === "sherpa-onnx-offline") { const t = e.args.findIndex((e) => e === "--provider"); return ((t >= 0 ? e.args[t + 1] : void 0) ?? e.args.find((e) => e.startsWith("--provider="))?.slice(11) ?? "cpu").trim().toLowerCase(); } if (t === "whisper-cli") { if (e.args.includes("-ng") || e.args.includes("--no-gpu")) return "cpu"; const t = e.args.findIndex((e) => e === "-dev" || e === "--device"); const n = (t >= 0 ? e.args[t + 1] : void 0) ?? e.args.find((e) => e.startsWith("--device="))?.slice(9); return n?.trim() ? `device:${n.trim()}` : void 0; } } function observationKey(e) { return `${e.command.trim()}\0${resolveRequestedLocalAudioBackend(e) ?? "default"}`; } function recordLocalAudioBackendObservation(e) { if (commandId(e.command) !== "whisper-cli") return; const t = /failed to initialize\s+(?:MTL\d+|Metal|CUDA\d*)\s+backend/i.test(e.output) ? "cpu" : /using\s+(?:MTL\d+|Metal)\s+backend/i.test(e.output) ? "metal" : /using\s+CUDA\d*\s+backend/i.test(e.output) ? "cuda" : /using\s+CPU\s+backend|no GPU found/i.test(e.output) ? "cpu" : void 0; if (t) observedBackendCache.set(observationKey(e), t); return t; } function expandHomeDir(e, t) { const n = e.trim().replace(/^"(.*)"$/, "$1"); if (n === "~") return t.HOME ?? n; if (n.startsWith("~/") || n.startsWith("~\\")) return t.HOME ? `${t.HOME}${path.sep}${n.slice(2)}` : n; return n; } async function inspectLinkedLibraries(e, t) { const n = `${t}\0${e}`; return await getOrCreatePromise(libraryCache, n, async () => { const n = t === "darwin" ? "otool" : t === "linux" ? "readelf" : null; if (!n) return null; try { const r = await runExec(n, t === "darwin" ? ["-L", e] : ["-d", e], { timeoutMs: 1500 }); return `${r.stdout}\n${r.stderr ?? ""}`; } catch { return null; } }, { cacheRejections: false }); } async function inspectWhisperBackend(e) { const t = await inspectLinkedLibraries(e.command, e.platform); if (/(?:ggml[-_]?cuda|libcuda|libcudart)/i.test(t ?? "")) return { capableBackend: "cuda", evidence: "whisper-cli links a CUDA ggml runtime" }; if (e.platform === "darwin" && e.arch === "arm64") { const n = await fs.realpath(e.command).catch(() => e.command); if (/(?:ggml[-_]?metal|Metal\.framework)/i.test(t ?? "") || /\/Cellar\/whisper-cpp\/[^/]+\/bin\/whisper-cli$/.test(n)) return { capableBackend: "metal", evidence: "Apple Silicon Homebrew whisper-cpp runtime with Metal support" }; } return { evidence: "whisper-cli backend cannot be proven without loading a model" }; } function rank(e) { if (e.id === "whisper-cli" && (e.observedBackend === "metal" || e.observedBackend === "cuda")) return 0; if (e.id === "sherpa-onnx-offline") return 1; if (e.id === "whisper-cli") return 2; return e.id === "parakeet-mlx" ? 3 : 4; } async function inspectLocalAudioSelection(e) { const t = process.env; const n = process.platform; const r = process.arch; const i = process.platform === "win32" ? ";" : path.delimiter; const a = (resolveEnvironmentValue(t, "PATH") ?? "").split(i).map((e) => expandHomeDir(e, t)); const [o, s, c, l] = [ "parakeet-mlx", "whisper-cli", "sherpa-onnx-offline", "whisper" ].map((e) => resolveExecutableFromPathEnv(e, a, t) ?? null); const u = t.WHISPER_CPP_MODEL?.trim(); const d = s !== null ? u && await pathExists(u) ? u : await discoverWhisperCppModel() : null; const f = s !== null && Boolean(d); const p = s ? await inspectWhisperBackend({ command: s, platform: n, arch: r }) : { evidence: "whisper-cli command not found" }; const m = t.SHERPA_ONNX_MODEL_DIR?.trim(); const h = m ? [ "tokens.txt", "encoder.onnx", "decoder.onnx", "joiner.onnx" ].map((e) => path.join(m, e)) : []; const g = c !== null && h.length === 4 && (await Promise.all(h.map((e) => pathExists(e)))).every(Boolean); const _ = o !== null && n === "darwin" && r === "arm64"; const v = [ "{{AttachmentPath}}", "--output-format", "txt", "--output-dir", "{{OutputDir}}", "--output-template", "{filename}" ]; const y = e?.trim().split(/[-_]/, 1)[0]; const b = y ? ["--language", y] : []; const x = [ "-m", d ?? "", "-otxt", "-of", "{{OutputBase}}", "-nt", ...b, "{{AttachmentPath}}" ]; const S = [ `--tokens=${h[0]}`, `--encoder=${h[1]}`, `--decoder=${h[2]}`, `--joiner=${h[3]}`, "{{AttachmentPath}}" ]; const C = [ "--model", "turbo", "--output_format", "txt", "--output_dir", "{{OutputDir}}", "--verbose", "False", ...b, "{{AttachmentPath}}" ]; const w = [ { id: "parakeet-mlx", resolvedCommand: o ?? void 0, ready: _, capableBackend: _ ? "mlx" : void 0, evidence: _ ? "parakeet-mlx is an MLX runtime on Apple Silicon; device use is unobserved" : "parakeet-mlx acceleration is only supported on Apple Silicon", reason: _ ? void 0 : "unsupported platform for MLX acceleration", args: v }, { id: "whisper-cli", resolvedCommand: s ?? void 0, ready: f, ...p, requestedBackend: resolveRequestedLocalAudioBackend({ command: "whisper-cli", args: x }), observedBackend: s ? observedBackendCache.get(observationKey({ command: s, args: x })) : void 0, reason: f ? void 0 : "model file not found", args: x }, { id: "sherpa-onnx-offline", resolvedCommand: c ?? void 0, ready: g, requestedBackend: "cpu", evidence: "OpenClaw auto args omit --provider, so sherpa-onnx uses its CPU default", reason: g ? void 0 : "SHERPA_ONNX_MODEL_DIR is missing required model files", args: S }, { id: "whisper", resolvedCommand: l ?? void 0, ready: Boolean(l), evidence: "Python Whisper chooses its runtime device when the model loads", reason: void 0, args: C } ].map(({ args: e, reason: t, resolvedCommand: n, ...r }) => Object.assign(r, { command: r.id, available: Boolean(n), selected: false, reason: n ? t : "command not found", entry: r.ready ? { type: "cli", command: n, args: e } : void 0 })); w.sort((e, t) => rank(e) - rank(t)); const T = w.find((e) => e.ready && e.entry); if (T) T.selected = true; return { candidates: w, entries: w.flatMap((e) => e.ready && e.entry ? [e.entry] : []), selected: T }; } function formatLocalAudioSelection(e) { const t = e.selected; if (!t) return null; const describeBackend = (e) => [ e.capableBackend ? `capable=${e.capableBackend}` : null, e.requestedBackend ? `requested=${e.requestedBackend}` : null, `observed=${e.observedBackend ?? "unknown"}` ].filter(Boolean).join(", "); const n = e.candidates.filter((e) => e.ready && e !== t).map((e) => `${e.command} (${describeBackend(e)})`); return `${t.command} (${describeBackend(t)}); ${t.evidence}${n.length > 0 ? `; fallbacks: ${n.join(", ")}` : ""}`; } //#endregion export { resolveRequestedLocalAudioBackend as i, inspectLocalAudioSelection as n, recordLocalAudioBackendObservation as r, formatLocalAudioSelection as t };