UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

377 lines (376 loc) • 14.3 kB
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs"; import { a as extractErrorCode, d as readErrorName } from "../../error-coercion-hDrHOSGy.mjs"; import { t as formatErrorMessage } from "../../errors-BKzCeTYb.mjs"; import { n as estimateBase64DecodedBytes } from "../../base64-CnKpkbff.mjs"; import { i as readResponseWithLimit } from "../../http-response-body-B-i_0116.mjs"; import { f as readProviderBinaryResponse, h as readProviderJsonResponse } from "../../provider-http-errors-Dtgw3x-5.mjs"; import { a as redactProviderResponseErrorText } from "../../provider-request-header-redaction-Ckk_UIqk.mjs"; import { r as fetchWithSsrFGuard } from "../../fetch-guard-BLMw2n18.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import "../../ssrf-runtime-B6q6NM4E.mjs"; import "../../error-runtime-BM740gJj.mjs"; import "../../response-limit-runtime-DkiFHsEX.mjs"; import { t as executeProviderOperationWithRetry } from "../../operation-retry-CNR4uE0x.mjs"; import { _ as resolveProviderOperationTimeoutMs, r as createProviderOperationDeadline, v as waitProviderOperationPollInterval } from "../../shared-CfcMLHIP.mjs"; import { i as resolveGeneratedMediaMaxBytes } from "../../configured-max-bytes-lKIaFMol.mjs"; import "../../media-runtime-B-kyz_D7.mjs"; import "../../media-generation-runtime-g6IBf-_Q.mjs"; import { t as normalizeVideoGenerationDuration } from "../../duration-support-DVBDr7yA.mjs"; import "../../provider-http-LcawLneq.mjs"; import "../../video-generation-DxmLfLWw.mjs"; import { t as stripGoogleProviderPrefix } from "../../model-id-DTVzKSqj.mjs"; import { c as resolveGoogleGenerativeAiSdkHttpOptions } from "../../google-api-base-url-CSlG5eZd.mjs"; import { c as GOOGLE_VIDEO_ALLOWED_DURATION_SECONDS, f as createGoogleVideoGenerationProviderMetadata, r as DEFAULT_GOOGLE_VIDEO_MODEL } from "../../generation-provider-metadata-C-Rz3J9V.mjs"; import { t as parseGeminiAuth } from "../../gemini-auth-CPHuN1jC.mjs"; import { t as resolveGoogleApiClientHeaders } from "../../google-api-client-header-YL-v53wl.mjs"; import { t as canonicalizeGoogleProviderBase64 } from "../../base64-BehuD7PY.mjs"; import { t as resolveGoogleGenerationApiKey } from "../../generation-auth-DNDTty1p.mjs"; import { t as createGoogleGenAI } from "../../google-genai-runtime-S4_i9nun.mjs"; //#region extensions/google/video-generation-provider.ts const DEFAULT_TIMEOUT_MS = 18e4; const POLL_INTERVAL_MS = 1e4; const MAX_POLL_ATTEMPTS = 120; const GOOGLE_VIDEO_OPERATION_RESPONSE_MAX_BYTES = 16777216; const GOOGLE_VIDEO_EMPTY_RESULT_MESSAGE = "Google video generation response missing generated videos"; function resolveGoogleVideoRestBaseUrl(e) { const { baseUrl: t, apiVersion: n } = resolveGoogleGenerativeAiSdkHttpOptions(e); return `${t ?? "https://generativelanguage.googleapis.com"}${n ? `/${n}` : ""}`; } function parseVideoSize(e) { const t = normalizeOptionalString(e); if (!t) return; const n = /^(\d+)x(\d+)$/u.exec(t); if (!n) return; const r = Number.parseInt(n[1] ?? "", 10); const i = Number.parseInt(n[2] ?? "", 10); if (!Number.isFinite(r) || !Number.isFinite(i)) return; return { width: r, height: i }; } function resolveAspectRatio(e) { const t = normalizeOptionalString(e.aspectRatio); if (t === "16:9" || t === "9:16") return t; const n = parseVideoSize(e.size); if (!n) return; return n.width >= n.height ? "16:9" : "9:16"; } function resolveResolution(e) { if (e.resolution === "720P") return "720p"; if (e.resolution === "1080P") return "1080p"; const t = parseVideoSize(e.size); if (!t) return; const n = Math.max(t.width, t.height); return n >= 1920 ? "1080p" : n >= 1280 ? "720p" : void 0; } function resolveGoogleGeneratedVideoFileDownloadUrl(e) { const t = e.file; const n = normalizeOptionalString(t?.name) ?? normalizeOptionalString(t?.uri); if (!n || !/^files\/[^/?#]+$/u.test(n)) return; const r = resolveGoogleVideoRestBaseUrl(e.configuredBaseUrl); const i = new URL(`${r}/${n}:download`); i.searchParams.set("alt", "media"); i.searchParams.set("key", e.apiKey); return i.toString(); } function extractGoogleApiErrorCode(e) { const t = e?.status; if (typeof t === "number") return t; const n = e instanceof Error ? e.message : String(e); try { const e = JSON.parse(n); const t = typeof e.code === "number" ? e.code : e.error?.code; return typeof t === "number" ? t : void 0; } catch { return /\b404\b/u.test(n) ? 404 : void 0; } } function extractGeneratedVideos(e) { const t = e.response; const n = t?.generatedVideos; if (Array.isArray(n) && n.length > 0) return n; const r = (t?.generateVideoResponse)?.generatedSamples; return Array.isArray(r) ? r : []; } function redactGoogleVideoSdkError(e, t) { const n = new Error(redactProviderResponseErrorText(formatErrorMessage(e), t)); n.name = redactProviderResponseErrorText(readErrorName(e) || "Error", t); const r = extractErrorCode(e); Object.assign(n, { status: extractGoogleApiErrorCode(e), ...r ? { code: redactProviderResponseErrorText(r, t) } : {} }); return n; } async function requestGoogleVideoJson(e) { function createHttpError(t, n) { const r = [`HTTP ${t.status}`]; const i = t.statusText.trim(); if (i) r.push(i); if (typeof n === "string") { const e = n.trim(); if (e) r.push(e); } else if (n && typeof n === "object") r.push(JSON.stringify(n)); const a = new Error(redactProviderResponseErrorText(r.join(": "), e.headers)); Object.assign(a, { status: t.status, statusCode: t.status }); return a; } return await executeProviderOperationWithRetry({ provider: "google", stage: e.stage, operation: async () => { const { response: t, release: n } = await fetchWithSsrFGuard({ url: e.url, init: { method: e.method, headers: e.headers, ...e.body === void 0 ? {} : { body: JSON.stringify(e.body) } }, timeoutMs: resolveProviderOperationTimeoutMs({ deadline: e.deadline, defaultTimeoutMs: DEFAULT_TIMEOUT_MS }) }); try { if (!t.ok) { const e = new TextDecoder().decode(await readResponseWithLimit(t, GOOGLE_VIDEO_OPERATION_RESPONSE_MAX_BYTES, { onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`Google video operation response exceeds ${e} bytes`) })); let n = e; if (e) try { n = JSON.parse(e); } catch { n = e; } throw createHttpError(t, n); } return await readProviderJsonResponse(t, "Google video operation response", { maxBytes: GOOGLE_VIDEO_OPERATION_RESPONSE_MAX_BYTES, requestHeaders: e.headers }); } finally { await n(); } } }); } const googleVideoGenerationProvider = { ...createGoogleVideoGenerationProviderMetadata(), async generateVideo(e) { if ((e.inputImages?.length ?? 0) > 1) throw new Error("Google video generation supports at most one input image."); if ((e.inputVideos?.length ?? 0) > 1) throw new Error("Google video generation supports at most one input video."); if ((e.inputImages?.length ?? 0) > 0 && (e.inputVideos?.length ?? 0) > 0) throw new Error("Google video generation does not support image and video inputs together."); const t = await resolveGoogleGenerationApiKey(e); const n = normalizeOptionalString(e.cfg?.models?.providers?.google?.baseUrl); const r = resolveGoogleGenerativeAiSdkHttpOptions(n); const i = r.baseUrl; const a = resolveGoogleVideoRestBaseUrl(i); const o = { ...parseGeminiAuth(t).headers, ...resolveGoogleApiClientHeaders({ baseUrl: a, api: "google-generative-ai", capability: "video", transport: "http" }) }; const s = normalizeVideoGenerationDuration({ durationSeconds: e.durationSeconds, supportedDurationSeconds: GOOGLE_VIDEO_ALLOWED_DURATION_SECONDS }); const c = normalizeOptionalString(e.model) || "veo-3.1-fast-generate-preview"; const l = resolveAspectRatio({ aspectRatio: e.aspectRatio, size: e.size }); const u = resolveResolution({ resolution: e.resolution, size: e.size }); const d = (e.inputImages?.length ?? 0) > 0 || (e.inputVideos?.length ?? 0) > 0; const f = createProviderOperationDeadline({ timeoutMs: e.timeoutMs, label: "Google video generation" }); const p = createGoogleGenAI({ apiKey: t, httpOptions: { ...r, timeout: resolveProviderOperationTimeoutMs({ deadline: f, defaultTimeoutMs: DEFAULT_TIMEOUT_MS }) } }); const generateViaRest = async () => { const t = e.prompt; const n = stripGoogleProviderPrefix(normalizeOptionalString(c) || "veo-3.1-fast-generate-preview"); const r = n.startsWith("models/") ? n : `models/${n}`; let i = await requestGoogleVideoJson({ url: `${a}/${r}:predictLongRunning`, method: "POST", headers: o, deadline: f, stage: "create", body: { instances: [{ prompt: t }], parameters: { ...s !== void 0 ? { durationSeconds: s } : {}, ...l ? { aspectRatio: l } : {}, ...u ? { resolution: u } : {} } } }); for (let e = 0; !(i.done ?? false); e += 1) { if (e >= MAX_POLL_ATTEMPTS) throw new Error("Google video generation did not finish in time"); await waitProviderOperationPollInterval({ deadline: f, pollIntervalMs: POLL_INTERVAL_MS }); const t = i.name; if (typeof t !== "string" || !t) throw new Error("Google video operation response missing name for polling"); i = await requestGoogleVideoJson({ url: `${a}/${t}`, method: "GET", headers: o, deadline: f, stage: "poll" }); } const d = i.error; if (d) throw new Error(redactProviderResponseErrorText(JSON.stringify(d), o)); return i; }; let m = false; let h; try { const t = e.inputImages?.[0]; const n = e.inputVideos?.[0]; h = await p.models.generateVideos({ model: stripGoogleProviderPrefix(c), prompt: e.prompt, image: t?.buffer ? { imageBytes: t.buffer.toString("base64"), mimeType: normalizeOptionalString(t.mimeType) || "image/png" } : void 0, video: n?.buffer ? { videoBytes: n.buffer.toString("base64"), mimeType: normalizeOptionalString(n.mimeType) || "video/mp4" } : void 0, config: { ...s !== void 0 ? { durationSeconds: s } : {}, ...l ? { aspectRatio: l } : {}, ...u ? { resolution: u } : {} } }); } catch (e) { if (d || extractGoogleApiErrorCode(e) !== 404) throw redactGoogleVideoSdkError(e, o); m = true; h = await generateViaRest(); } if (!m) { let e = h; for (let t = 0; !(e.done ?? false); t += 1) { if (t >= MAX_POLL_ATTEMPTS) throw new Error("Google video generation did not finish in time"); await waitProviderOperationPollInterval({ deadline: f, pollIntervalMs: POLL_INTERVAL_MS }); resolveProviderOperationTimeoutMs({ deadline: f, defaultTimeoutMs: DEFAULT_TIMEOUT_MS }); e = await executeProviderOperationWithRetry({ provider: "google", stage: "poll", operation: () => p.operations.getVideosOperation({ operation: e }) }).catch((e) => { throw redactGoogleVideoSdkError(e, o); }); } if (e.error) throw new Error(redactProviderResponseErrorText(JSON.stringify(e.error), o)); h = e; } const g = extractGeneratedVideos(h); if (g.length === 0) throw new Error(GOOGLE_VIDEO_EMPTY_RESULT_MESSAGE); const _ = h; const v = resolveGeneratedMediaMaxBytes(e.cfg, "video"); return { videos: await Promise.all(g.map(async (e, n) => { const r = e.video; if (r?.videoBytes) { if (estimateBase64DecodedBytes(r.videoBytes) > v) throw new Error(`Google generated video download exceeds ${v} bytes`); const e = canonicalizeGoogleProviderBase64(r.videoBytes); if (!e) throw new Error("Google video generation returned malformed base64 video data"); return { buffer: Buffer.from(e, "base64"), mimeType: normalizeOptionalString(r.mimeType) || "video/mp4", fileName: `video-${n + 1}.mp4` }; } const download = async (e) => { const a = r?.mimeType; const o = resolveProviderOperationTimeoutMs({ deadline: f, defaultTimeoutMs: DEFAULT_TIMEOUT_MS }); const s = normalizeOptionalString(e); if (!s) return; const c = URL.parse(s); if (c?.protocol !== "https:") return; const l = /* @__PURE__ */ new Set(["https://generativelanguage.googleapis.com"]); const u = URL.parse(i ?? "")?.origin; if (u?.startsWith("https://")) l.add(u); if (!l.has(c.origin)) return; if (!c.searchParams.has("key")) c.searchParams.set("key", t); const d = c.toString(); return await executeProviderOperationWithRetry({ provider: "google", stage: "download", operation: async () => { const { response: e, release: r } = await fetchWithSsrFGuard({ url: d, timeoutMs: o }); try { if (!e.ok) { e.body?.cancel().catch(() => void 0); throw new Error(redactProviderResponseErrorText(`Failed to download Google generated video: ${e.status} ${e.statusText}`, { "x-goog-api-key": c.searchParams.get("key") ?? t })); } const r = "Google generated video download"; return { buffer: await readProviderBinaryResponse(e, r, "video", { maxBytes: v, chunkTimeoutMs: o, onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`${r} exceeds ${e} bytes`), onIdleTimeout: ({ chunkTimeoutMs: e }) => /* @__PURE__ */ new Error(`${r} stalled after ${e}ms`) }), mimeType: normalizeOptionalString(e.headers.get("content-type")) || normalizeOptionalString(a) || "video/mp4", fileName: `video-${n + 1}.mp4` }; } finally { await r(); } } }); }; const a = await download(r?.uri); if (a) return a; if (!r) throw new Error("Google generated video missing file handle"); const o = await download(resolveGoogleGeneratedVideoFileDownloadUrl({ file: r, apiKey: t, configuredBaseUrl: i })); if (!o) throw new Error("Google generated video missing bounded download URL"); return o; })), model: c, metadata: _.name ? { operationName: _.name } : void 0 }; } }; //#endregion export { googleVideoGenerationProvider };