UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

247 lines (246 loc) • 8.07 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { P as resolveIntegerOption } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./number-runtime-W4chuk8B.mjs"; import { r as resolveGeneratedImageDownloadMaxBytes } from "./configured-max-bytes-lKIaFMol.mjs"; import { n as isProviderApiKeyConfiguredAsync } from "./provider-auth-availability-Bv9WFzc3.mjs"; import "./media-generation-runtime-g6IBf-_Q.mjs"; import { t as postJsonResponse } from "./provider-json-post-BR01v-xE.mjs"; import "./provider-http-LcawLneq.mjs"; import { d as toImageDataUrl, l as resolveInlineImageJsonResponseMaxBytes, n as generatedImageAssetFromDataUrl, s as parseOpenAiCompatibleImageResponse, t as generatedImageAssetFromBase64 } from "./image-assets-C4Dd3W6i.mjs"; import "./image-generation-D00XjYzo.mjs"; import "./provider-auth-D_oAZ3fr.mjs"; import { i as normalizeOpenRouterBaseUrl } from "./provider-catalog-DXTNVH5w.mjs"; import { t as resolveOpenRouterGenerationRequestContext } from "./generation-request-context-DILQjDNk.mjs"; //#region extensions/openrouter/image-generation-provider.ts const DEFAULT_MODEL = "google/gemini-3.1-flash-image-preview"; const DEFAULT_TIMEOUT_MS = 18e4; const MAX_IMAGE_RESULTS = 4; const CHAT_ENCODED_PAYLOADS_PER_IMAGE = 2; const SUPPORTED_MODELS = [ DEFAULT_MODEL, "google/gemini-3-pro-image-preview", "openai/gpt-5.4-image-2" ]; const SUPPORTED_ASPECT_RATIOS = [ "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9" ]; const OPENROUTER_IMAGE_MALFORMED_RESPONSE = "OpenRouter image generation response malformed"; function throwMalformedOpenRouterImageResponse() { throw new Error(OPENROUTER_IMAGE_MALFORMED_RESPONSE); } function requireOpenRouterImageRecord(e) { if (!isRecord(e)) throwMalformedOpenRouterImageResponse(); return e; } function requireOpenRouterImageUrl(e) { const t = normalizeOptionalString(requireOpenRouterImageRecord(e).url); if (!t) throwMalformedOpenRouterImageResponse(); return t; } function pushDataUrlImage(e, t, n = true) { const r = generatedImageAssetFromDataUrl({ dataUrl: t, index: e.length }); if (!r) { if (n) throwMalformedOpenRouterImageResponse(); return; } e.push(r); } function extractImagesFromPart(e, t) { const n = requireOpenRouterImageRecord(t); if (n.type === "text") return; if (n.type === "image_url") { pushDataUrlImage(e, requireOpenRouterImageUrl(n.image_url ?? n.imageUrl)); return; } let r = normalizeOptionalString(n.b64_json); let i; if (!r) { if ("b64_json" in n) throwMalformedOpenRouterImageResponse(); const e = n.inlineData ?? n.inline_data; if (e === void 0 || e === null) return; const t = requireOpenRouterImageRecord(e); r = normalizeOptionalString(t.data); if (!r) throwMalformedOpenRouterImageResponse(); i = normalizeOptionalString(t.mimeType) ?? normalizeOptionalString(t.mime_type) ?? "image/png"; } const a = generatedImageAssetFromBase64({ base64: r, index: e.length, ...i === void 0 ? {} : { mimeType: i } }); if (!a) throwMalformedOpenRouterImageResponse(); e.push(a); } function extractOpenRouterImagesFromResponse(e) { const t = requireOpenRouterImageRecord(e).choices; if (t === void 0 || t === null) return []; if (!Array.isArray(t)) throwMalformedOpenRouterImageResponse(); const n = []; for (const e of t) { const t = requireOpenRouterImageRecord(e).message; if (t === void 0 || t === null) continue; const r = requireOpenRouterImageRecord(t); const i = r.images; if (i !== void 0 && i !== null) { if (!Array.isArray(i)) throwMalformedOpenRouterImageResponse(); for (const e of i) { const t = requireOpenRouterImageRecord(e); pushDataUrlImage(n, requireOpenRouterImageUrl(t.image_url ?? t.imageUrl)); } } const a = r.content; if (typeof a === "string" && a.length > 0) for (const e of a.matchAll(/data:image\/[^;]+;base64,[A-Za-z0-9+/=]+/g)) pushDataUrlImage(n, e[0], false); else if (Array.isArray(a)) for (const e of a) extractImagesFromPart(n, e); else if (a !== void 0 && a !== null) throwMalformedOpenRouterImageResponse(); } return n; } function buildInputReferences(e) { return (e.inputImages ?? []).map((e) => ({ type: "image_url", image_url: { url: toImageDataUrl(e) } })); } function buildDedicatedImageBody(e, t, n) { const r = { model: t, prompt: e.prompt, n: 1, ...n.aspect_ratio ? { aspect_ratio: n.aspect_ratio } : {}, ...n.image_size ? { resolution: n.image_size } : {} }; const i = buildInputReferences(e); if (i.length > 0) r.input_references = i; return r; } function normalizeDedicatedImageResponse(e) { if (!isRecord(e) || !Array.isArray(e.data)) return e; return { ...e, data: e.data.map((e) => { if (!isRecord(e) || e.mime_type !== void 0 || e.media_type === void 0) return e; return { ...e, mime_type: e.media_type }; }) }; } function buildMessageContent(e) { const t = buildInputReferences(e); if (t.length === 0) return e.prompt; return [{ type: "text", text: e.prompt }, ...t]; } function buildImageConfig(e, t) { if (!t.startsWith("google/gemini-")) return {}; const n = {}; const r = normalizeOptionalString(e.aspectRatio); if (r) n.aspect_ratio = r; const i = normalizeOptionalString(e.resolution); if (i) n.image_size = i; return n; } function buildOpenRouterImageGenerationProvider() { return { id: "openrouter", label: "OpenRouter", defaultModel: DEFAULT_MODEL, models: [...SUPPORTED_MODELS], isConfiguredAsync: (e) => isProviderApiKeyConfiguredAsync({ provider: "openrouter", ...e }), capabilities: { generate: { maxCount: MAX_IMAGE_RESULTS, supportsSize: false, supportsAspectRatio: true, supportsResolution: true }, edit: { enabled: true, maxCount: MAX_IMAGE_RESULTS, maxInputImages: 5, supportsSize: false, supportsAspectRatio: true, supportsResolution: true }, geometry: { aspectRatios: [...SUPPORTED_ASPECT_RATIOS], resolutions: [ "1K", "2K", "4K" ] } }, async generateImage(e) { const { baseUrl: t, allowPrivateNetwork: n, headers: r, dispatcherPolicy: i } = await resolveOpenRouterGenerationRequestContext({ cfg: e.cfg, agentDir: e.agentDir, authStore: e.authStore, capability: "image", jsonContentType: false }); const a = normalizeOptionalString(e.model) ?? DEFAULT_MODEL; const o = buildImageConfig(e, a); const s = resolveIntegerOption(e.count, 1, { min: 1, max: MAX_IMAGE_RESULTS }); const c = normalizeOpenRouterBaseUrl(t); return { images: (await Promise.all(Array.from({ length: c ? s : 1 }, async () => { const l = await postJsonResponse({ url: c ? `${c}/images` : `${t}/chat/completions`, headers: r, body: c ? buildDedicatedImageBody(e, a, o) : { model: a, messages: [{ role: "user", content: buildMessageContent(e) }], modalities: ["image", "text"], n: s, ...Object.keys(o).length > 0 ? { image_config: o } : {} }, timeoutMs: e.timeoutMs ?? DEFAULT_TIMEOUT_MS, fetchFn: fetch, allowPrivateNetwork: n, ssrfPolicy: e.ssrfPolicy, dispatcherPolicy: i, errorLabel: "OpenRouter image generation failed", responseLabel: "openrouter.image-generation", readOptions: { maxBytes: resolveInlineImageJsonResponseMaxBytes(c ? 1 : s * CHAT_ENCODED_PAYLOADS_PER_IMAGE, resolveGeneratedImageDownloadMaxBytes(e.cfg)) } }); const u = c ? parseOpenAiCompatibleImageResponse(normalizeDedicatedImageResponse(l), { malformedResponseError: OPENROUTER_IMAGE_MALFORMED_RESPONSE, sniffMimeType: true }) : extractOpenRouterImagesFromResponse(l); if (u.length === 0) throw new Error("OpenRouter image generation response missing image data"); return u; }))).flat(), model: a }; } }; } //#endregion export { buildOpenRouterImageGenerationProvider as t };