UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

250 lines (249 loc) • 9.03 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { L as resolvePositiveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as estimateBase64DecodedBytes, t as canonicalizeBase64 } from "./base64-CnKpkbff.mjs"; import { n as assertOkOrThrowHttpError } from "./provider-http-errors-Dtgw3x-5.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./number-runtime-W4chuk8B.mjs"; import { d as postJsonRequest } from "./shared-CfcMLHIP.mjs"; import { i as resolveGeneratedMediaMaxBytes } from "./configured-max-bytes-lKIaFMol.mjs"; import "./media-runtime-B-kyz_D7.mjs"; import { n as isProviderApiKeyConfiguredAsync } from "./provider-auth-availability-Bv9WFzc3.mjs"; import "./media-generation-runtime-g6IBf-_Q.mjs"; import "./provider-http-LcawLneq.mjs"; import { d as toImageDataUrl } from "./image-assets-C4Dd3W6i.mjs"; import "./image-generation-D00XjYzo.mjs"; import "./provider-auth-D_oAZ3fr.mjs"; import { t as resolveOpenRouterGenerationRequestContext } from "./generation-request-context-DILQjDNk.mjs"; //#region extensions/openrouter/music-generation-provider.ts const DEFAULT_OPENROUTER_MUSIC_MODEL = "google/lyria-3-pro-preview"; const OPENROUTER_CLIP_MUSIC_MODEL = "google/lyria-3-clip-preview"; const DEFAULT_TIMEOUT_MS = 18e4; const OPENROUTER_SSE_ENVELOPE_OVERHEAD_BYTES = 65536; const OPENROUTER_MUSIC_MODELS = [DEFAULT_OPENROUTER_MUSIC_MODEL, OPENROUTER_CLIP_MUSIC_MODEL]; function imageToContentPart(e) { const t = normalizeOptionalString(e.url) ?? (e.buffer ? toImageDataUrl({ ...e, buffer: e.buffer, defaultMimeType: "image/png" }) : void 0); if (!t) throw new Error("OpenRouter music generation reference image is missing data."); return { type: "image_url", image_url: { url: t } }; } function readDeltaAudio(e) { const t = asOptionalRecord(e)?.choices; const n = Array.isArray(t) ? asOptionalRecord(t[0]) : void 0; const r = asOptionalRecord(asOptionalRecord(n?.delta)?.audio); if (!r) return; return { data: normalizeOptionalString(r.data), transcript: typeof r.transcript === "string" ? r.transcript : void 0 }; } function resolveOpenRouterSseEventMaxBytes(e) { return Math.ceil(e / 3) * 4 + e + OPENROUTER_SSE_ENVELOPE_OVERHEAD_BYTES; } function createOpenRouterMusicTooLargeError(e, t) { return /* @__PURE__ */ new Error(`OpenRouter music generation ${e} exceeded ${t} bytes`); } function readOpenRouterStreamError(e) { if (!isRecord(e) || !isRecord(e.error)) return; return normalizeOptionalString(e.error.message) ?? "unknown provider stream error"; } async function readOpenRouterAudioStream(e, t) { if (!e.body) throw new Error("OpenRouter music generation response missing stream body"); const n = e.body.getReader(); const r = new TextDecoder(); const i = { audioBuffers: [], audioBytes: 0, audioBase64Remainder: "", transcriptChunks: [], transcriptBytes: 0 }; function appendDecodedOpenRouterMusicAudio(e) { if (!e) return; const n = t - i.audioBytes; if (estimateBase64DecodedBytes(e) > n) throw createOpenRouterMusicTooLargeError("audio", t); const r = canonicalizeBase64(e); if (!r) throw new Error("OpenRouter music generation returned malformed base64 audio data"); const a = Buffer.from(r, "base64"); i.audioBytes += a.byteLength; i.audioBuffers.push(a); } function appendOpenRouterMusicAudio(e) { const t = i.audioBase64Remainder + e; const n = t.length - t.length % 4; i.audioBase64Remainder = t.slice(n); appendDecodedOpenRouterMusicAudio(t.slice(0, n)); } function finishOpenRouterMusicStream() { appendDecodedOpenRouterMusicAudio(i.audioBase64Remainder); i.audioBase64Remainder = ""; return { audioBuffer: Buffer.concat(i.audioBuffers, i.audioBytes), transcript: i.transcriptChunks.join("") }; } function appendOpenRouterMusicTranscript(e) { const n = i.transcriptBytes + Buffer.byteLength(e, "utf8"); if (n > t) throw createOpenRouterMusicTooLargeError("transcript", t); i.transcriptBytes = n; i.transcriptChunks.push(e); } function processOpenRouterSseLine(e) { if (!e.startsWith("data:")) return false; const t = e.slice(5).trim(); if (!t) return false; if (t === "[DONE]") return true; const n = JSON.parse(t); const r = readOpenRouterStreamError(n); if (r) throw new Error(`OpenRouter music generation failed: ${r}`); const i = readDeltaAudio(n); if (i?.data) appendOpenRouterMusicAudio(i.data); if (i?.transcript) appendOpenRouterMusicTranscript(i.transcript); return false; } const a = resolveOpenRouterSseEventMaxBytes(t); const o = []; let s = 0; try { for (;;) { const { value: e, done: i } = await n.read(); if (i) break; for (const n of e) { s = n === 10 ? 0 : s + 1; if (s > a) throw new Error(`OpenRouter music generation SSE event exceeded ${a} bytes for a ${t}-byte media limit`); } const c = r.decode(e, { stream: true }); let l = 0; for (let e = c.indexOf("\n"); e !== -1; e = c.indexOf("\n", l)) { let t = c.slice(l, e); l = e + 1; if (o.length > 0) { o.push(t); t = o.join(""); o.length = 0; } if (processOpenRouterSseLine(t.trim())) return finishOpenRouterMusicStream(); } if (l < c.length) o.push(c.slice(l)); } o.push(r.decode()); const e = o.join(""); s = Buffer.byteLength(e, "utf8"); if (s > a) throw new Error(`OpenRouter music generation SSE event exceeded ${a} bytes for a ${t}-byte media limit`); if (!processOpenRouterSseLine(e.trim())) throw new Error("OpenRouter music generation stream ended before completion"); return finishOpenRouterMusicStream(); } finally { n.cancel().catch(() => {}); try { n.releaseLock(); } catch {} } } function buildOpenRouterMusicGenerationProvider() { return { id: "openrouter", label: "OpenRouter", defaultModel: DEFAULT_OPENROUTER_MUSIC_MODEL, models: [...OPENROUTER_MUSIC_MODELS], isConfiguredAsync: (e) => isProviderApiKeyConfiguredAsync({ provider: "openrouter", ...e }), capabilities: { generate: { maxTracks: 1, maxDurationSeconds: 180, supportsLyrics: true, supportsInstrumental: true, supportsDuration: true, supportsFormat: true, supportedFormats: ["mp3", "wav"] }, edit: { enabled: true, maxTracks: 1, maxInputImages: 1, maxDurationSeconds: 180, supportsLyrics: true, supportsInstrumental: true, supportsDuration: true, supportsFormat: true, supportedFormats: ["mp3", "wav"] } }, async generateMusic(e) { if ((e.inputImages?.length ?? 0) > 1) throw new Error("OpenRouter music generation supports at most one reference image."); const { baseUrl: t, allowPrivateNetwork: n, headers: r, dispatcherPolicy: i } = await resolveOpenRouterGenerationRequestContext({ cfg: e.cfg, agentDir: e.agentDir, authStore: e.authStore, capability: "audio", jsonContentType: true }); const a = normalizeOptionalString(e.model) ?? DEFAULT_OPENROUTER_MUSIC_MODEL; const o = e.format ?? "wav"; const s = resolvePositiveTimerTimeoutMs(e.timeoutMs, DEFAULT_TIMEOUT_MS); const c = [e.prompt.trim()]; const l = normalizeOptionalString(e.lyrics); if (e.instrumental === true) c.push("Instrumental only. No vocals, no sung lyrics, no spoken word."); if (l) c.push(`Lyrics:\n${l}`); if (typeof e.durationSeconds === "number") c.push(`Target duration: about ${Math.round(e.durationSeconds)} seconds.`); const u = c.join("\n\n"); const d = e.inputImages ?? []; const f = d.length === 0 ? u : [{ type: "text", text: u }, ...d.map(imageToContentPart)]; const { response: p, release: m } = await postJsonRequest({ url: `${t}/chat/completions`, headers: r, body: { model: a, messages: [{ role: "user", content: f }], modalities: ["text", "audio"], audio: { format: o }, stream: true }, timeoutMs: s, fetchFn: fetch, allowPrivateNetwork: n, dispatcherPolicy: i }); try { await assertOkOrThrowHttpError(p, "OpenRouter music generation failed"); const t = await readOpenRouterAudioStream(p, resolveGeneratedMediaMaxBytes(e.cfg, "audio")); if (t.audioBuffer.byteLength === 0) throw new Error("OpenRouter music generation response missing audio data"); return { tracks: [{ buffer: t.audioBuffer, mimeType: o === "mp3" ? "audio/mpeg" : "audio/wav", fileName: `track-1.${o}` }], model: a, ...t.transcript ? { lyrics: [t.transcript] } : {}, metadata: { inputImageCount: e.inputImages?.length ?? 0, instrumental: e.instrumental === true, requestedFormat: o } }; } catch (e) { if (e instanceof Error && e.name === "TimeoutError") throw new Error(`OpenRouter music generation timed out after ${s}ms`, { cause: e }); throw e; } finally { await m(); } } }; } //#endregion export { buildOpenRouterMusicGenerationProvider as t };