UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

234 lines (233 loc) • 8.54 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { i as asOptionalObjectRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { f as readProviderBinaryResponse, h as readProviderJsonResponse, n as assertOkOrThrowHttpError } from "./provider-http-errors-Dtgw3x-5.mjs"; import { p as sanitizeConfiguredModelProviderRequest } from "./provider-request-config-CCij-nof.mjs"; import { d as mergeSsrFPolicies } from "./ssrf-DHBNJw0c.mjs"; import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { _ as resolveProviderOperationTimeoutMs, d as postJsonRequest, f as postMultipartRequest, h as resolveProviderHttpRequestConfig, r as createProviderOperationDeadline } from "./shared-CfcMLHIP.mjs"; import { r as resolveGeneratedImageDownloadMaxBytes } from "./configured-max-bytes-lKIaFMol.mjs"; import { n as isProviderApiKeyConfiguredAsync, t as isProviderApiKeyConfigured } from "./provider-auth-availability-Bv9WFzc3.mjs"; import { a as resolveApiKeyForProvider } from "./provider-auth-runtime-DYG2Fn1g.mjs"; import "./provider-http-LcawLneq.mjs"; import { l as resolveInlineImageJsonResponseMaxBytes, s as parseOpenAiCompatibleImageResponse } from "./image-assets-C4Dd3W6i.mjs"; //#region src/image-generation/openai-compatible-image-urls.ts /** * Downloads `data[].url` entries of an OpenAI-compatible image response and * returns the payload with each one inlined as `b64_json`, so URL and inline * results share one asset parser. Only the provider origin is automatically * trusted; other private destinations require explicit policy. Provider HTTP * credentials are never sent to image URLs. */ async function inlineOpenAiCompatibleImageUrls(e, t) { if (!isRecord(e) || !Array.isArray(e.data)) return e; const n = new URL(t.providerUrl).origin; const r = t.dispatcherPolicy; const i = r?.mode === "explicit-proxy" ? { ...r, proxyTls: void 0, pinnedHostname: void 0 } : r ? { ...r, connect: void 0, pinnedHostname: void 0 } : void 0; const a = { policy: mergeSsrFPolicies(t.ssrfPolicy, { allowedOrigins: [n] }, t.allowPrivateNetwork ? { allowPrivateNetwork: true } : void 0), resolveDispatcherPolicy: (e) => e.origin === n ? r : i, useEnvProxyForEligibleUrls: true, auditContext: `${t.providerId}-image-download` }; const o = `${t.label} image download`; const s = []; let c = 0; for (const n of e.data) { const e = asOptionalObjectRecord(n); const r = e && !normalizeOptionalString(e.b64_json) ? normalizeOptionalString(e.url) : void 0; if (!e || !r) { s.push(n); continue; } if (c >= t.maxDownloads) throw new Error(`${t.operation} returned too many image URLs`); c += 1; const { response: i, release: l } = await fetchWithSsrFGuard({ ...a, url: r, init: { method: "GET" }, timeoutMs: t.timeoutMs(), signal: t.signal, fetchImpl: fetch }); try { await assertOkOrThrowHttpError(i, `${o} failed`, { bodyTimeoutMs: t.timeoutMs }); const n = i.headers.get("Content-Type")?.split(";")[0]?.trim().toLowerCase(); if (!n || !/^image\/[a-z0-9.+-]+$/.test(n)) { i.body?.cancel().catch(() => void 0); throw new Error(`${o}: expected an image Content-Type`); } const r = await readProviderBinaryResponse(i, o, "image", { maxBytes: t.maxBytes, timeoutMs: t.timeoutMs }); s.push({ ...e, b64_json: r.toString("base64"), mime_type: n }); } finally { await l(); } } return { ...e, data: s }; } //#endregion //#region src/image-generation/openai-compatible-image-provider.ts const DEFAULT_IMAGE_OPERATION_TIMEOUT_MS = 6e4; /** Creates an image-generation provider backed by OpenAI-style image endpoints. */ function createOpenAiCompatibleImageGenerationProvider(e) { const t = e.providerConfigKey ?? e.id; const n = e.normalizeModel ?? ((e, t) => normalizeOptionalString(e) ?? t); const r = e.resolveCount ?? (({ req: e }) => e.count ?? 1); return { id: e.id, label: e.label, defaultModel: e.defaultModel, ...e.defaultTimeoutMs !== void 0 ? { defaultTimeoutMs: e.defaultTimeoutMs } : {}, models: [...e.models], isConfigured: (t) => isProviderApiKeyConfigured({ provider: e.id, ...t }), isConfiguredAsync: (t) => isProviderApiKeyConfiguredAsync({ provider: e.id, ...t }), capabilities: e.capabilities, async generateImage(i) { const a = i.inputImages ?? []; const o = a.length > 0 ? "edit" : "generate"; const s = `${e.label} image ${o === "edit" ? "edit" : "generation"}`; const c = e.capabilities.edit.maxInputImages; if (o === "edit" && !e.capabilities.edit.enabled) throw new Error(`${e.label} image editing is not supported.`); if (o === "edit" && c !== void 0 && a.length > c) throw new Error(e.tooManyInputImagesError ?? `${e.label} image editing supports up to ${c} reference image${c === 1 ? "" : "s"}.`); const l = await resolveApiKeyForProvider({ provider: e.id, cfg: i.cfg, agentDir: i.agentDir, store: i.authStore, signal: i.signal }); if (!l.apiKey) throw new Error(e.missingApiKeyError ?? `${e.label} API key missing`); const u = i.cfg?.models?.providers?.[t]; const d = e.resolveBaseUrl?.({ req: i, providerConfig: u, defaultBaseUrl: e.defaultBaseUrl }) ?? normalizeOptionalString(u?.baseUrl) ?? e.defaultBaseUrl; const f = e.resolveAllowPrivateNetwork?.({ baseUrl: d, req: i, providerConfig: u }); const p = e.useConfiguredRequest ? sanitizeConfiguredModelProviderRequest(u?.request) : void 0; const { baseUrl: m, allowPrivateNetwork: h, headers: g, dispatcherPolicy: _ } = resolveProviderHttpRequestConfig({ baseUrl: d, defaultBaseUrl: e.defaultBaseUrl, allowPrivateNetwork: f, request: p, defaultHeaders: { Authorization: `Bearer ${l.apiKey}` }, provider: e.id, capability: "image", transport: "http" }); const v = n(i.model, e.defaultModel); const y = r({ req: i, mode: o }); const b = { req: i, inputImages: a, model: v, count: y, mode: o }; const x = o === "edit" ? e.buildEditRequest({ ...b, mode: o }) : e.buildGenerateRequest({ ...b, mode: o }); const S = createProviderOperationDeadline({ timeoutMs: i.timeoutMs ?? e.defaultTimeoutMs ?? DEFAULT_IMAGE_OPERATION_TIMEOUT_MS, label: e.failureLabels?.[o] ?? s }); const C = e.defaultTimeoutMs === void 0 ? i.timeoutMs : resolveProviderOperationTimeoutMs({ deadline: S, defaultTimeoutMs: e.defaultTimeoutMs }); const remainingTimeoutMs = () => resolveProviderOperationTimeoutMs({ deadline: S, defaultTimeoutMs: C ?? DEFAULT_IMAGE_OPERATION_TIMEOUT_MS }); const w = { url: `${m.replace(/\/+$/u, "")}/images/${o === "edit" ? "edits" : "generations"}`, headers: new Headers(g), timeoutMs: C, signal: i.signal, fetchFn: fetch, allowPrivateNetwork: h, ssrfPolicy: i.ssrfPolicy, dispatcherPolicy: _ }; if (x.kind === "multipart") w.headers.delete("Content-Type"); else w.headers.set("Content-Type", "application/json"); const { response: T, release: E } = await (x.kind === "multipart" ? postMultipartRequest({ ...w, body: x.form }) : postJsonRequest({ ...w, body: x.body })); try { await assertOkOrThrowHttpError(T, e.failureLabels?.[o] ?? `${s} failed`, { bodyTimeoutMs: remainingTimeoutMs }); const t = e.capabilities[o].maxCount ?? y; const n = resolveGeneratedImageDownloadMaxBytes(i.cfg); const r = await readProviderJsonResponse(T, `${e.id}.image-generation`, { maxBytes: resolveInlineImageJsonResponseMaxBytes(t, n), timeoutMs: remainingTimeoutMs }); const a = await inlineOpenAiCompatibleImageUrls(r, { providerId: e.id, label: e.label, operation: s, providerUrl: w.url, maxDownloads: t, maxBytes: n, timeoutMs: remainingTimeoutMs, signal: i.signal, allowPrivateNetwork: p?.allowPrivateNetwork, ssrfPolicy: i.ssrfPolicy, dispatcherPolicy: _ }); const c = parseOpenAiCompatibleImageResponse(a, { ...e.response, malformedResponseError: `${s} response malformed` }); if (c.length === 0) throw new Error(e.emptyResponseError ?? `${s} response missing image data`); return { images: c, model: v }; } finally { await E(); } } }; } //#endregion export { inlineOpenAiCompatibleImageUrls as n, createOpenAiCompatibleImageGenerationProvider as t };