UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

215 lines (214 loc) • 9.07 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs"; import { 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 "../../string-coerce-runtime-BwAZZDf5.mjs"; import { t as expectDefined } from "../../expect-runtime-DT3P17Ul.mjs"; import { t as bufferToBlobPart } from "../../blob-runtime-QF_Wblu0.mjs"; import { _ as resolveProviderOperationTimeoutMs, d as postJsonRequest, f as postMultipartRequest, h as resolveProviderHttpRequestConfig, r as createProviderOperationDeadline } from "../../shared-CfcMLHIP.mjs"; import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.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 { a as resolveApiKeyForProvider } from "../../provider-auth-runtime-DYG2Fn1g.mjs"; import "../../provider-http-LcawLneq.mjs"; import { a as imageSourceUploadFileName, l as resolveInlineImageJsonResponseMaxBytes, s as parseOpenAiCompatibleImageResponse } from "../../image-assets-C4Dd3W6i.mjs"; import "../../image-generation-D00XjYzo.mjs"; import "../../provider-auth-D_oAZ3fr.mjs"; import { d as extractFoundryEndpoint, m as isFoundryProviderApi, o as PROVIDER_ID, p as isFoundryMaiImageModel, r as DEFAULT_API } from "../../shared-DiLOhEpP.mjs"; import { t as prepareFoundryRuntimeAuth } from "../../runtime-DCch4p0z.mjs"; import { t as buildMicrosoftFoundryProvider } from "../../provider-CHTD1CeH.mjs"; //#region extensions/microsoft-foundry/index.ts const DEFAULT_TIMEOUT_MS = 6e5; const DEFAULT_IMAGE_SIZE = { width: 1024, height: 1024 }; const MAI_MIN_IMAGE_SIDE_PX = 768; const MAI_MAX_IMAGE_PIXELS = 1048576; const MAI_IMAGE_BASE_PATH = "/mai/v1"; const MAI_IMAGE_MAX_RESULTS = 1; const MAI_IMAGE_OUTPUT_MIME = "image/png"; const MAI_IMAGE_UPLOAD_MIME_TYPES = /* @__PURE__ */ new Set([ "image/jpeg", "image/jpg", "image/png" ]); function isMaiImageEditModel(e) { const t = normalizeOptionalLowercaseString(e); return t === "mai-image-2.5" || t === "mai-image-2.5-flash"; } function resolveMaiImageSize(e) { if (!e) return DEFAULT_IMAGE_SIZE; const t = e.match(/^(\d{1,5})x(\d{1,5})$/u); if (!t) throw new Error(`Microsoft Foundry MAI image size must use WIDTHxHEIGHT, got "${e}".`); const n = Number(t[1]); const r = Number(t[2]); if (n < MAI_MIN_IMAGE_SIDE_PX || r < MAI_MIN_IMAGE_SIDE_PX || n * r > MAI_MAX_IMAGE_PIXELS) throw new Error(`Microsoft Foundry MAI image size must be at least 768x768 and at most 1,048,576 total pixels, got "${e}".`); return { width: n, height: r }; } function parseMaiImageResponse(e, t) { const n = parseOpenAiCompatibleImageResponse(e, { defaultMimeType: MAI_IMAGE_OUTPUT_MIME, fileNamePrefix: "microsoft-foundry-image", malformedResponseError: `${t} response malformed`, sniffMimeType: true }); if (n.length === 0) throw new Error(`${t} response missing image data`); return n; } var microsoft_foundry_default = definePluginEntry({ id: "microsoft-foundry", name: "Microsoft Foundry Provider", description: "Microsoft Foundry provider with Entra ID and API key auth", register(e) { e.registerProvider(buildMicrosoftFoundryProvider()); e.registerImageGenerationProvider({ id: PROVIDER_ID, label: "Microsoft Foundry", defaultTimeoutMs: DEFAULT_TIMEOUT_MS, models: [], isConfiguredAsync: (e) => isProviderApiKeyConfiguredAsync({ provider: PROVIDER_ID, ...e }), capabilities: { generate: { maxCount: MAI_IMAGE_MAX_RESULTS, supportsSize: true }, edit: { enabled: true, maxCount: MAI_IMAGE_MAX_RESULTS, maxInputImages: 1, supportsSize: false }, output: { formats: ["png"] } }, async generateImage(e) { const t = e.cfg.models?.providers?.[PROVIDER_ID]; const n = normalizeOptionalString(e.model); if (!n) throw new Error("Microsoft Foundry MAI image generation requires a deployment name."); const r = t?.models?.find((e) => e.id === n)?.name; const i = r || n; const a = normalizeOptionalLowercaseString(n); const o = Boolean(r) && normalizeOptionalLowercaseString(r) !== a; if (!isFoundryMaiImageModel(i) && (o || a?.startsWith("mai-") && !a.startsWith("mai-image-"))) throw new Error(`Microsoft Foundry image generation supports MAI image deployments only, got "${i}".`); const s = e.inputImages ?? []; const c = s.length > 0 ? "edits" : "generations"; if (e.count !== void 0 && e.count !== 1) throw new Error("Microsoft Foundry MAI image models return one image per request."); if (s.length > 1) throw new Error("Microsoft Foundry MAI image edits support one input image."); if (c === "edits" && (o || isFoundryMaiImageModel(n)) && !isMaiImageEditModel(i)) throw new Error(`${i} does not support Microsoft Foundry MAI image edits.`); if (c === "edits" && !o && !isFoundryMaiImageModel(n)) throw new Error("Microsoft Foundry MAI image edits require MAI-Image-2.5 model metadata for custom deployment names."); const l = await resolveApiKeyForProvider({ provider: PROVIDER_ID, cfg: e.cfg, agentDir: e.agentDir, store: e.authStore }); if (!l.apiKey) throw new Error("Microsoft Foundry API key missing"); let u; if (l.apiKey !== "__entra_id_dynamic__") u = { headers: { "api-key": l.apiKey } }; else { const r = isFoundryProviderApi(t?.api) ? t.api : DEFAULT_API; const a = await prepareFoundryRuntimeAuth({ config: e.cfg, agentDir: e.agentDir, env: process.env, provider: PROVIDER_ID, modelId: n, model: { id: n, name: i, api: r, provider: PROVIDER_ID, baseUrl: t?.baseUrl ?? "" }, apiKey: l.apiKey, authMode: l.mode, ...l.profileId ? { profileId: l.profileId } : {} }); if (!a?.apiKey) throw new Error("Microsoft Foundry Entra ID token missing after runtime auth refresh."); u = { headers: { Authorization: `Bearer ${a.apiKey}` }, ...a.baseUrl ? { baseUrl: a.baseUrl } : {} }; } const d = extractFoundryEndpoint(u.baseUrl) ?? extractFoundryEndpoint(t?.baseUrl) ?? extractFoundryEndpoint(process.env.AZURE_OPENAI_ENDPOINT); if (!d) throw new Error("Microsoft Foundry endpoint missing for MAI image generation."); const f = `${d}${MAI_IMAGE_BASE_PATH}`; const { baseUrl: p, allowPrivateNetwork: m, headers: h, dispatcherPolicy: g } = resolveProviderHttpRequestConfig({ baseUrl: f, defaultBaseUrl: f, allowPrivateNetwork: false, defaultHeaders: u.headers, request: sanitizeConfiguredModelProviderRequest(t?.request), provider: PROVIDER_ID, capability: "image", transport: "http" }); const _ = c === "edits" ? "Microsoft Foundry MAI image edit" : "Microsoft Foundry MAI image generation"; const v = createProviderOperationDeadline({ timeoutMs: e.timeoutMs, label: _ }); const y = resolveProviderOperationTimeoutMs({ deadline: v, defaultTimeoutMs: DEFAULT_TIMEOUT_MS }); const b = { url: `${p.replace(/\/+$/u, "")}/images/${c}`, headers: new Headers(h), timeoutMs: y, fetchFn: fetch, allowPrivateNetwork: m, ssrfPolicy: e.ssrfPolicy, dispatcherPolicy: g }; let x; if (c === "edits") { b.headers.delete("Content-Type"); const t = expectDefined(s[0], "Microsoft Foundry edit source image"); const r = normalizeOptionalLowercaseString(t.mimeType) ?? MAI_IMAGE_OUTPUT_MIME; if (!MAI_IMAGE_UPLOAD_MIME_TYPES.has(r)) throw new Error("Microsoft Foundry MAI image edits require a PNG or JPEG input image."); const i = new FormData(); i.set("model", n); i.set("prompt", e.prompt); i.set("image", new Blob([bufferToBlobPart(t.buffer)], { type: r === "image/jpg" ? "image/jpeg" : r }), imageSourceUploadFileName({ image: t, index: 0, fileNamePrefix: "microsoft-foundry-input" })); x = postMultipartRequest({ ...b, body: i }); } else { b.headers.set("Content-Type", "application/json"); x = postJsonRequest({ ...b, body: { model: n, prompt: e.prompt, ...resolveMaiImageSize(e.size) } }); } const { response: S, release: C } = await x; try { await assertOkOrThrowHttpError(S, `${_} failed`); return { images: parseMaiImageResponse(await readProviderJsonResponse(S, "microsoft-foundry.image-generation", { maxBytes: resolveInlineImageJsonResponseMaxBytes(MAI_IMAGE_MAX_RESULTS, resolveGeneratedImageDownloadMaxBytes(e.cfg)) }), _), model: n }; } finally { await C(); } } }); } }); //#endregion export { microsoft_foundry_default as default };