Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(providers): expand image provider registry and model support
diegosouzapwce8e9b96ca58
diff --git a/open-sse/config/imageRegistry.ts b/open-sse/config/imageRegistry.tsindex c9d8c40411..6ac8cb6eec 100644--- a/open-sse/config/imageRegistry.ts+++ b/open-sse/config/imageRegistry.ts@@ -5,6 +5,68 @@* Each provider has its own request format and endpoint.*/+const IMAGE_MODEL_ALIASES = {+ "flux-kontext": {+ provider: "pollinations",+ model: "flux-kontext",+ name: "FLUX Kontext",+ listInCatalog: true,+ },+ "flux-kontext-max": {+ provider: "together",+ model: "black-forest-labs/FLUX.1.1-pro",+ name: "FLUX Kontext Max",+ listInCatalog: true,+ },+ "flux-redux": {+ provider: "together",+ model: "black-forest-labs/FLUX.1-redux",+ name: "FLUX Redux",+ listInCatalog: true,+ },+ "flux-depth": {+ provider: "together",+ model: "black-forest-labs/FLUX.1-depth",+ name: "FLUX Depth",+ listInCatalog: true,+ },+ "flux-canny": {+ provider: "together",+ model: "black-forest-labs/FLUX.1-canny",+ name: "FLUX Canny",+ listInCatalog: true,+ },+ "flux-dev-lora": {+ provider: "together",+ model: "black-forest-labs/FLUX.1-dev-lora",+ name: "FLUX Dev LoRA",+ listInCatalog: true,+ },+ kontext: {+ provider: "pollinations",+ model: "flux-kontext",+ name: "FLUX Kontext",+ listInCatalog: false,+ },+ "pollinations/kontext": {+ provider: "pollinations",+ model: "flux-kontext",+ name: "FLUX Kontext",+ listInCatalog: false,+ },+};++function resolveImageModelAlias(modelStr) {+ const alias = IMAGE_MODEL_ALIASES[modelStr];+ return alias ? { provider: alias.provider, model: alias.model } : null;+}++function findImageModelConfig(providerId, modelId) {+ const provider = IMAGE_PROVIDERS[providerId];+ if (!provider) return null;+ return provider.models.find((model) => model.id === modelId) || null;+}+export const IMAGE_PROVIDERS = {openai: {id: "openai",@@ -40,6 +102,10 @@ export const IMAGE_PROVIDERS = {{ id: "black-forest-labs/FLUX.1.1-pro", name: "FLUX 1.1 Pro" },{ id: "black-forest-labs/FLUX.1-schnell-Free", name: "FLUX 1 Schnell (Free)" },{ id: "stabilityai/stable-diffusion-xl-base-1.0", name: "SDXL Base 1.0" },+ { id: "black-forest-labs/FLUX.1-redux", name: "FLUX.1 Redux" },+ { id: "black-forest-labs/FLUX.1-depth", name: "FLUX.1 Depth" },+ { id: "black-forest-labs/FLUX.1-canny", name: "FLUX.1 Canny" },+ { id: "black-forest-labs/FLUX.1-dev-lora", name: "FLUX.1 Dev LoRA" },],supportedSizes: ["1024x1024", "512x512"],},@@ -165,11 +231,111 @@ export const IMAGE_PROVIDERS = {{ id: "gptimage", name: "GPT Image 1 Mini" },{ id: "qwen-image", name: "Qwen Image Plus" },{ id: "wan-image", name: "Wan 2.7 Image" },- { id: "kontext", name: "FLUX.1 Kontext" },+ { id: "flux-kontext", name: "FLUX.1 Kontext" },+ { id: "flux-kontext-max", name: "FLUX.1 Kontext Max" },{ id: "gptimage-large", name: "GPT Image 1.5" },],supportedSizes: ["1024x1024", "512x512"],},++ "fal-ai": {+ id: "fal-ai",+ baseUrl: "https://fal.run",+ authType: "apikey",+ authHeader: "key",+ format: "fal-ai",+ models: [+ { id: "fal-ai/flux-pro/v1.1", name: "FLUX.1 Pro v1.1" },+ { id: "fal-ai/flux-pro/v1.1-ultra", name: "FLUX.1 Pro v1.1 Ultra" },+ { id: "fal-ai/flux/schnell", name: "FLUX.1 Schnell" },+ { id: "bria/text-to-image/3.2", name: "Bria 3.2" },+ { id: "fal-ai/bytedance/seedream/v3/text-to-image", name: "SeeDream V3" },+ { id: "fal-ai/bytedance/dreamina/v3.1/text-to-image", name: "Dreamina V3.1" },+ { id: "fal-ai/ideogram/v3", name: "Ideogram V3" },+ { id: "fal-ai/imagen4/preview", name: "Imagen 4 Preview" },+ { id: "fal-ai/imagen4/preview/fast", name: "Imagen 4 Preview Fast" },+ { id: "fal-ai/imagen4/preview/ultra", name: "Imagen 4 Preview Ultra" },+ { id: "fal-ai/recraft/v3/text-to-image", name: "Recraft V3 via Fal" },+ { id: "fal-ai/stable-diffusion-v35-medium", name: "Stable Diffusion v3.5 Medium" },+ ],+ supportedSizes: ["1024x1024", "1024x1280", "1280x1024"],+ },++ "stability-ai": {+ id: "stability-ai",+ baseUrl: "https://api.stability.ai",+ authType: "apikey",+ authHeader: "bearer",+ format: "stability-ai",+ models: [+ { id: "sd3", name: "sd3" },+ { id: "sd3-large", name: "sd3-large" },+ { id: "sd3-large-turbo", name: "sd3-large-turbo" },+ { id: "sd3-medium", name: "sd3-medium" },+ { id: "sd3.5-large", name: "sd3.5-large" },+ { id: "sd3.5-large-turbo", name: "sd3.5-large-turbo" },+ { id: "sd3.5-medium", name: "sd3.5-medium" },+ { id: "stable-image-ultra", name: "Stable Image Ultra" },+ { id: "stable-image-core", name: "Stable Image Core" },+ { id: "inpaint", name: "Inpaint" },+ { id: "outpaint", name: "Outpaint" },+ { id: "erase", name: "Erase" },+ { id: "search-and-replace", name: "Search and Replace" },+ { id: "search-and-recolor", name: "Search and Recolor" },+ { id: "remove-background", name: "Remove Background" },+ { id: "replace-background-and-relight", name: "Replace Background and Relight" },+ { id: "fast", name: "Fast Upscale" },+ { id: "conservative", name: "Conservative Upscale" },+ { id: "creative", name: "Creative Upscale" },+ { id: "sketch", name: "Sketch Control" },+ { id: "structure", name: "Structure Control" },+ { id: "style", name: "Style Control" },+ { id: "style-transfer", name: "Style Transfer" },+ ],+ supportedSizes: ["1024x1024", "1024x1280", "1280x1024"],+ },++ "black-forest-labs": {+ id: "black-forest-labs",+ baseUrl: "https://api.bfl.ai",+ authType: "apikey",+ authHeader: "x-key",+ format: "black-forest-labs",+ models: [+ { id: "flux-kontext-pro", name: "flux-kontext-pro" },+ { id: "flux-kontext-max", name: "flux-kontext-max" },+ { id: "flux-pro-1.0-fill", name: "flux-pro-1.0-fill" },+ { id: "flux-pro-1.0-expand", name: "flux-pro-1.0-expand" },+ { id: "flux-pro-1.1", name: "flux-pro-1.1" },+ { id: "flux-pro-1.1-ultra", name: "flux-pro-1.1-ultra" },+ { id: "flux-dev", name: "flux-dev" },+ { id: "flux-pro", name: "flux-pro" },+ ],+ supportedSizes: ["1024x1024", "1024x1280", "1280x1024"],+ },++ recraft: {+ id: "recraft",+ baseUrl: "https://external.api.recraft.ai",+ authType: "apikey",+ authHeader: "bearer",+ format: "recraft",+ models: [+ { id: "recraftv2", name: "recraftv2" },+ { id: "recraftv3", name: "recraftv3" },+ ],+ supportedSizes: ["1024x1024", "1024x1280", "1280x1024"],+ },++ topaz: {+ id: "topaz",+ baseUrl: "https://api.topazlabs.com",+ authType: "apikey",+ authHeader: "x-api-key",+ format: "topaz",+ models: [{ id: "topaz-enhance", name: "topaz-enhance" }],+ supportedSizes: ["1024x1024"],+ },};/**@@ -186,14 +352,25 @@ export function getImageProvider(providerId) {export function parseImageModel(modelStr) {if (!modelStr) return { provider: null, model: null };+ const directAlias = resolveImageModelAlias(modelStr);+ if (directAlias) {+ return directAlias;+ }+// Try each provider prefixfor (const [providerId, config] of Object.entries(IMAGE_PROVIDERS)) {if (modelStr.startsWith(providerId + "/")) {- return { provider: providerId, model: modelStr.slice(providerId.length + 1) };+ const model = modelStr.slice(providerId.length + 1);+ const aliased =+ resolveImageModelAlias(`${providerId}/${model}`) || resolveImageModelAlias(model);+ return aliased || { provider: providerId, model };}// Check alias if availableif (config.alias && modelStr.startsWith(config.alias + "/")) {- return { provider: providerId, model: modelStr.slice(config.alias.length + 1) };+ const model = modelStr.slice(config.alias.length + 1);+ const aliased =+ resolveImageModelAlias(`${providerId}/${model}`) || resolveImageModelAlias(model);+ return aliased || { provider: providerId, model };}}@@ -222,5 +399,20 @@ export function getAllImageModels() {});}}+ for (const [alias, target] of Object.entries(IMAGE_MODEL_ALIASES)) {+ if (!target.listInCatalog) continue;+ const providerConfig = IMAGE_PROVIDERS[target.provider];+ const modelConfig = findImageModelConfig(target.provider, target.model);+ models.push({+ id: alias,+ name: target.name || modelConfig?.name || alias,+ provider: target.provider,+ supportedSizes: providerConfig?.supportedSizes || [],+ });+ }return models;}++export function getImageModelAliases() {+ return IMAGE_MODEL_ALIASES;+}diff --git a/open-sse/handlers/imageGeneration.ts b/open-sse/handlers/imageGeneration.tsindex 8948ebec2d..743c67762c 100644--- a/open-sse/handlers/imageGeneration.ts+++ b/open-sse/handlers/imageGeneration.ts@@ -26,6 +26,84 @@ import {extractComfyOutputFiles,} from "../utils/comfyuiClient.ts";+const OPENAI_IMAGE_TO_IMAGE_MODELS = new Set([+ "black-forest-labs/FLUX.1-redux",+ "black-forest-labs/FLUX.1-depth",+ "black-forest-labs/FLUX.1-canny",+ "black-forest-labs/FLUX.1.1-pro",+ "FLUX.1-redux",+ "FLUX.1-depth",+ "FLUX.1-canny",+ "FLUX.1.1-pro",+ "flux-kontext-max",+ "flux-kontext",+ "flux-kontext-pro",+]);++const BFL_MODEL_ENDPOINTS = {+ "flux-kontext-pro": "/v1/flux-kontext-pro",+ "flux-kontext-max": "/v1/flux-kontext-max",+ "flux-pro-1.0-fill": "/v1/flux-pro-1.0-fill",+ "flux-pro-1.0-expand": "/v1/flux-pro-1.0-expand",+ "flux-pro-1.1": "/v1/flux-pro-1.1",+ "flux-pro-1.1-ultra": "/v1/flux-pro-1.1-ultra",+ "flux-dev": "/v1/flux-dev",+ "flux-pro": "/v1/flux-pro",+};++const BFL_EDIT_MODELS = new Set([+ "flux-kontext-pro",+ "flux-kontext-max",+ "flux-pro-1.0-fill",+ "flux-pro-1.0-expand",+]);++const BFL_FAILURE_STATUSES = new Set(["Error", "Failed", "Content Moderated", "Request Moderated"]);++const STABILITY_GENERATION_ENDPOINTS = {+ sd3: "/v2beta/stable-image/generate/sd3",+ "sd3-large": "/v2beta/stable-image/generate/sd3",+ "sd3-large-turbo": "/v2beta/stable-image/generate/sd3",+ "sd3-medium": "/v2beta/stable-image/generate/sd3",+ "sd3.5-large": "/v2beta/stable-image/generate/sd3",+ "sd3.5-large-turbo": "/v2beta/stable-image/generate/sd3",+ "sd3.5-medium": "/v2beta/stable-image/generate/sd3",+ "stable-image-ultra": "/v2beta/stable-image/generate/ultra",+ "stable-image-core": "/v2beta/stable-image/generate/core",+};++const STABILITY_EDIT_ENDPOINTS = {+ inpaint: "/v2beta/stable-image/edit/inpaint",+ outpaint: "/v2beta/stable-image/edit/outpaint",+ erase: "/v2beta/stable-image/edit/erase",+ "search-and-replace": "/v2beta/stable-image/edit/search-and-replace",+ "search-and-recolor": "/v2beta/stable-image/edit/search-and-recolor",+ "remove-background": "/v2beta/stable-image/edit/remove-background",+ "replace-background-and-relight": "/v2beta/stable-image/edit/replace-background-and-relight",+ fast: "/v2beta/stable-image/upscale/fast",+ conservative: "/v2beta/stable-image/upscale/conservative",+ creative: "/v2beta/stable-image/upscale/creative",+ sketch: "/v2beta/stable-image/control/sketch",+ structure: "/v2beta/stable-image/control/structure",+ style: "/v2beta/stable-image/control/style",+ "style-transfer": "/v2beta/stable-image/control/style-transfer",+};++const STABILITY_CONTROL_MODELS = new Set(["sketch", "structure", "style", "style-transfer"]);++const FAL_PRESET_SIZES = {+ "1024x1024": "square_hd",+ "512x512": "square",+ "1792x1024": "landscape_16_9",+ "1024x1792": "portrait_16_9",+ "1024x768": "landscape_4_3",+ "768x1024": "portrait_4_3",+ "1536x1024": "landscape_3_2",+ "1024x1536": "portrait_3_2",+ "576x1024": "portrait_16_9",+ "1024x576": "landscape_16_9",+};+/*** Handle image generation request* @param {object} options@@ -123,6 +201,61 @@ export async function handleImageGeneration({ body, credentials, log, resolvedPr});}+ if (providerConfig.format === "fal-ai") {+ return handleFalAIImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+ });+ }++ if (providerConfig.format === "stability-ai") {+ return handleStabilityAIImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+ });+ }++ if (providerConfig.format === "black-forest-labs") {+ return handleBlackForestLabsImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+ });+ }++ if (providerConfig.format === "recraft") {+ return handleRecraftImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+ });+ }++ if (providerConfig.format === "topaz") {+ return handleTopazImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+ });+ }+if (providerConfig.format === "nanobanana") {return handleNanoBananaImageGeneration({model,@@ -314,6 +447,11 @@ async function handleOpenAIImageGeneration({if (body.response_format !== undefined) upstreamBody.response_format = body.response_format;if (body.style !== undefined) upstreamBody.style = body.style;+ const { imageUrl } = extractImageInputs(body);+ if (imageUrl && OPENAI_IMAGE_TO_IMAGE_MODELS.has(model)) {+ upstreamBody.image_url = imageUrl;+ }+// Build headersconst headers = {"Content-Type": "application/json",@@ -387,6 +525,850 @@ async function handleOpenAIImageGeneration({return result;}+async function handleFalAIImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+}) {+ const startTime = Date.now();+ const token = credentials.apiKey || credentials.accessToken;+ const { imageUrl, imageUrls } = extractImageInputs(body);+ const upstreamBody: Record<string, unknown> = {+ prompt: body.prompt,+ sync_mode: body.sync_mode ?? true,+ };++ if (body.n !== undefined) upstreamBody.num_images = Number(body.n) || 1;+ if (body.negative_prompt) upstreamBody.negative_prompt = body.negative_prompt;+ if (body.seed !== undefined) upstreamBody.seed = body.seed;+ if (body.style) upstreamBody.style = normalizeRecraftStyle(body.style);++ const outputFormat = normalizeRequestedImageFormat(body, "png");+ if (outputFormat) upstreamBody.output_format = outputFormat;++ if (model.includes("flux-pro/v1.1") && !model.includes("ultra")) {+ upstreamBody.image_size = mapFalImageSize(body.size, "landscape_4_3");+ } else if (+ model.includes("bytedance/") ||+ model.includes("stable-diffusion") ||+ model.includes("ideogram") ||+ model.includes("recraft/v3")+ ) {+ upstreamBody.image_size = mapFalImageSize(body.size, "square_hd");+ } else {+ upstreamBody.aspect_ratio = body.aspect_ratio || mapFalAspectRatio(body.size, "1:1");+ }++ if (body.quality === "hd" && model.includes("ultra")) {+ upstreamBody.raw = true;+ }++ if (imageUrl && model.includes("flux-pro/v1.1-ultra")) {+ upstreamBody.image_url = imageUrl;+ }++ if (imageUrls.length > 0 && model.includes("ideogram")) {+ upstreamBody.image_urls = imageUrls;+ }++ if (log) {+ const promptPreview = String(body.prompt ?? "").slice(0, 60);+ log.info("IMAGE", `${provider}/${model} (fal-ai) | prompt: "${promptPreview}..."`);+ }++ try {+ const response = await fetch(`${providerConfig.baseUrl.replace(/\/$/, "")}/${model}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Key ${token}`,+ },+ body: JSON.stringify(upstreamBody),+ });++ if (!response.ok) {+ const errorText = await response.text();+ if (log)+ log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);+ return saveImageErrorResult({+ provider,+ model,+ status: response.status,+ startTime,+ error: errorText,+ requestBody: upstreamBody,+ });+ }++ const payload = await response.json();+ const images = await normalizeProviderImagePayload(payload, body, log);+ return saveImageSuccessResult({+ provider,+ model,+ startTime,+ requestBody: upstreamBody,+ responseBody: { images_count: images.length },+ created: payload.created,+ images,+ });+ } catch (err) {+ if (log) log.error("IMAGE", `${provider} fetch error: ${err.message}`);+ return saveImageErrorResult({+ provider,+ model,+ status: 502,+ startTime,+ error: `Image provider error: ${err.message}`,+ });+ }+}++async function handleStabilityAIImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+}) {+ const startTime = Date.now();+ const token = credentials.apiKey || credentials.accessToken;+ const endpoint = STABILITY_GENERATION_ENDPOINTS[model] || STABILITY_EDIT_ENDPOINTS[model];++ if (!endpoint) {+ return {+ success: false,+ status: 400,+ error: `Unsupported Stability AI image model: ${model}`,+ };+ }++ const { imageUrl, maskUrl } = extractImageInputs(body);+ const upstreamBody: Record<string, unknown> = {+ output_format:+ model === "remove-background"+ ? normalizeRequestedImageFormat(body, "png", ["png", "webp"])+ : normalizeRequestedImageFormat(body, "png"),+ };++ if (body.prompt) upstreamBody.prompt = body.prompt;+ if (body.negative_prompt) upstreamBody.negative_prompt = body.negative_prompt;+ if (body.seed !== undefined) upstreamBody.seed = body.seed;++ try {+ if (STABILITY_GENERATION_ENDPOINTS[model]) {+ if (model.startsWith("sd3") && model !== "sd3") {+ upstreamBody.model = model;+ }++ if (imageUrl) {+ upstreamBody.mode = "image-to-image";+ upstreamBody.image = (await resolveImageSource(imageUrl)).base64;+ if (body.strength !== undefined) upstreamBody.strength = body.strength;+ } else {+ upstreamBody.mode = "text-to-image";+ }++ if (!model.startsWith("sd3") || !imageUrl) {+ upstreamBody.aspect_ratio = body.aspect_ratio || mapImageSize(body.size);+ }++ if (body.style_preset) upstreamBody.style_preset = body.style_preset;+ } else {+ if (imageUrl) {+ upstreamBody.image = (await resolveImageSource(imageUrl)).base64;+ }++ if (maskUrl && shouldIncludeStabilityMask(model)) {+ upstreamBody.mask = (await resolveImageSource(maskUrl)).base64;+ }++ if (body.search_prompt) upstreamBody.search_prompt = body.search_prompt;+ if (body.grow_mask !== undefined) upstreamBody.grow_mask = body.grow_mask;+ if (body.control_strength !== undefined)+ upstreamBody.control_strength = body.control_strength;+ if (body.creativity !== undefined) upstreamBody.creativity = body.creativity;+ if (body.left !== undefined) upstreamBody.left = body.left;+ if (body.right !== undefined) upstreamBody.right = body.right;+ if (body.up !== undefined) upstreamBody.up = body.up;+ if (body.down !== undefined) upstreamBody.down = body.down;+ if (body.style_preset) upstreamBody.style_preset = body.style_preset;++ if (STABILITY_CONTROL_MODELS.has(model) && !upstreamBody.prompt) {+ upstreamBody.prompt = body.prompt || "";+ }+ }++ if (log) {+ const promptPreview = String(body.prompt ?? "").slice(0, 60);+ log.info("IMAGE", `${provider}/${model} (stability-ai) | prompt: "${promptPreview}..."`);+ }++ const response = await fetch(`${providerConfig.baseUrl.replace(/\/$/, "")}${endpoint}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json",+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify(upstreamBody),+ });++ if (!response.ok) {+ const errorText = await response.text();+ if (log)+ log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);+ return saveImageErrorResult({+ provider,+ model,+ status: response.status,+ startTime,+ error: errorText,+ requestBody: upstreamBody,+ });+ }++ const contentType = response.headers.get("content-type") || "";+ let payload;+ if (contentType.includes("application/json")) {+ payload = await response.json();+ } else {+ const buffer = Buffer.from(await response.arrayBuffer());+ payload = { image: buffer.toString("base64") };+ }++ const images = await normalizeProviderImagePayload(payload, body, log);+ return saveImageSuccessResult({+ provider,+ model,+ startTime,+ requestBody: upstreamBody,+ responseBody: { images_count: images.length },+ created: payload.created,+ images,+ });+ } catch (err) {+ if (log) log.error("IMAGE", `${provider} fetch error: ${err.message}`);+ return saveImageErrorResult({+ provider,+ model,+ status: 502,+ startTime,+ error: `Image provider error: ${err.message}`,+ });+ }+}++async function handleBlackForestLabsImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+}) {+ const startTime = Date.now();+ const token = credentials.apiKey || credentials.accessToken;+ const endpoint = BFL_MODEL_ENDPOINTS[model];++ if (!endpoint) {+ return {+ success: false,+ status: 400,+ error: `Unsupported Black Forest Labs image model: ${model}`,+ };+ }++ const { imageUrl, maskUrl } = extractImageInputs(body);+ const upstreamBody: Record<string, unknown> = {+ prompt: body.prompt,+ output_format: normalizeRequestedImageFormat(body, "png"),+ };++ try {+ if (BFL_EDIT_MODELS.has(model) && imageUrl) {+ upstreamBody.input_image = (await resolveImageSource(imageUrl)).base64;+ } else if (imageUrl && isHttpUrl(imageUrl)) {+ upstreamBody.image_url = imageUrl;+ }++ if (maskUrl && (model === "flux-pro-1.0-fill" || model === "flux-kontext-pro")) {+ upstreamBody.mask = (await resolveImageSource(maskUrl)).base64;+ }++ if (model === "flux-kontext-pro" || model === "flux-kontext-max") {+ upstreamBody.aspect_ratio = body.aspect_ratio || mapImageSize(body.size);+ } else if (typeof body.size === "string" && body.size.includes("x")) {+ const { width, height } = parseSizeToDimensions(body.size, 1024);+ upstreamBody.width = width;+ upstreamBody.height = height;+ }++ if (body.seed !== undefined) upstreamBody.seed = body.seed;+ if (body.n !== undefined && model.includes("ultra"))+ upstreamBody.num_images = Number(body.n) || 1;+ if (body.quality === "hd" && model.includes("ultra")) upstreamBody.raw = true;+ if (body.left !== undefined) upstreamBody.left = body.left;+ if (body.right !== undefined) upstreamBody.right = body.right;+ if (body.top !== undefined) upstreamBody.top = body.top;+ if (body.bottom !== undefined) upstreamBody.bottom = body.bottom;+ if (body.steps !== undefined) upstreamBody.steps = body.steps;+ if (body.guidance !== undefined) upstreamBody.guidance = body.guidance;+ if (body.grow_mask !== undefined) upstreamBody.grow_mask = body.grow_mask;+ if (body.safety_tolerance !== undefined) upstreamBody.safety_tolerance = body.safety_tolerance;++ if (log) {+ const promptPreview = String(body.prompt ?? "").slice(0, 60);+ log.info("IMAGE", `${provider}/${model} (black-forest-labs) | prompt: "${promptPreview}..."`);+ }++ const response = await fetch(`${providerConfig.baseUrl.replace(/\/$/, "")}${endpoint}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json",+ "x-key": token,+ },+ body: JSON.stringify(upstreamBody),+ });++ if (!response.ok) {+ const errorText = await response.text();+ if (log)+ log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);+ return saveImageErrorResult({+ provider,+ model,+ status: response.status,+ startTime,+ error: errorText,+ requestBody: upstreamBody,+ });+ }++ const initialPayload = await response.json();+ const finalPayload = initialPayload.polling_url+ ? await pollBlackForestLabsResult({+ pollingUrl: initialPayload.polling_url,+ token,+ body,+ log,+ })+ : initialPayload;++ const images = await normalizeProviderImagePayload(finalPayload, body, log);+ return saveImageSuccessResult({+ provider,+ model,+ startTime,+ requestBody: upstreamBody,+ responseBody: { images_count: images.length },+ created: finalPayload.created,+ images,+ });+ } catch (err) {+ if (log) log.error("IMAGE", `${provider} fetch error: ${err.message}`);+ return saveImageErrorResult({+ provider,+ model,+ status: 502,+ startTime,+ error: `Image provider error: ${err.message}`,+ });+ }+}++async function handleRecraftImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+}) {+ const startTime = Date.now();+ const token = credentials.apiKey || credentials.accessToken;+ const upstreamBody: Record<string, unknown> = {+ model,+ prompt: body.prompt,+ };++ if (body.n !== undefined) upstreamBody.n = body.n;+ if (body.size !== undefined) upstreamBody.size = body.size;+ if (body.response_format !== undefined) upstreamBody.response_format = body.response_format;+ if (body.style !== undefined) upstreamBody.style = body.style;++ if (log) {+ const promptPreview = String(body.prompt ?? "").slice(0, 60);+ log.info("IMAGE", `${provider}/${model} (recraft) | prompt: "${promptPreview}..."`);+ }++ try {+ const response = await fetch(+ `${providerConfig.baseUrl.replace(/\/$/, "")}/v1/images/generations`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${token}`,+ },+ body: JSON.stringify(upstreamBody),+ }+ );++ if (!response.ok) {+ const errorText = await response.text();+ if (log)+ log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);+ return saveImageErrorResult({+ provider,+ model,+ status: response.status,+ startTime,+ error: errorText,+ requestBody: upstreamBody,+ });+ }++ const payload = await response.json();+ const images = await normalizeProviderImagePayload(payload, body, log);+ return saveImageSuccessResult({+ provider,+ model,+ startTime,+ requestBody: upstreamBody,+ responseBody: { images_count: images.length },+ created: payload.created,+ images,+ });+ } catch (err) {+ if (log) log.error("IMAGE", `${provider} fetch error: ${err.message}`);+ return saveImageErrorResult({+ provider,+ model,+ status: 502,+ startTime,+ error: `Image provider error: ${err.message}`,+ });+ }+}++async function handleTopazImageGeneration({+ model,+ provider,+ providerConfig,+ body,+ credentials,+ log,+}) {+ const startTime = Date.now();+ const token = credentials.apiKey || credentials.accessToken;+ const { imageUrl } = extractImageInputs(body);++ if (!imageUrl) {+ return {+ success: false,+ status: 400,+ error: `Topaz model ${model} requires an input image`,+ };+ }++ try {+ const imageSource = await resolveImageSource(imageUrl);+ const formData = new FormData();+ const blob = new Blob([imageSource.buffer], { type: imageSource.contentType || "image/png" });+ formData.append("image", blob, "image.png");++ if (typeof body.size === "string" && body.size.includes("x")) {+ const { width, height } = parseSizeToDimensions(body.size, 1024);+ formData.append("output_width", String(width));+ formData.append("output_height", String(height));+ }++ if (log) {+ const promptPreview = String(body.prompt ?? "enhance image").slice(0, 60);+ log.info("IMAGE", `${provider}/${model} (topaz) | prompt: "${promptPreview}..."`);+ }++ const response = await fetch(`${providerConfig.baseUrl.replace(/\/$/, "")}/image/v1/enhance`, {+ method: "POST",+ headers: {+ Accept: "image/jpeg",+ "X-API-Key": token,+ },+ body: formData,+ });++ if (!response.ok) {+ const errorText = await response.text();+ if (log)+ log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);+ return saveImageErrorResult({+ provider,+ model,+ status: response.status,+ startTime,+ error: errorText,+ });+ }++ const contentType = response.headers.get("content-type") || "image/jpeg";+ const buffer = Buffer.from(await response.arrayBuffer());+ const base64 = buffer.toString("base64");+ const wantsBase64 = body.response_format === "b64_json";+ const images = [+ wantsBase64+ ? { b64_json: base64, revised_prompt: body.prompt }+ : { url: `data:${contentType};base64,${base64}`, revised_prompt: body.prompt },+ ];++ return saveImageSuccessResult({+ provider,+ model,+ startTime,+ responseBody: { images_count: images.length },+ images,+ });+ } catch (err) {+ if (log) log.error("IMAGE", `${provider} fetch error: ${err.message}`);+ return saveImageErrorResult({+ provider,+ model,+ status: 502,+ startTime,+ error: `Image provider error: ${err.message}`,+ });+ }+}++async function pollBlackForestLabsResult({ pollingUrl, token, body, log }) {+ const timeoutMs = normalizePositiveNumber(body.timeout_ms, 300000);+ const pollIntervalMs = normalizePositiveNumber(body.poll_interval_ms, 1500);+ const deadline = Date.now() + timeoutMs;++ while (Date.now() < deadline) {+ const response = await fetch(pollingUrl, {+ method: "GET",+ headers: {+ "x-key": token,+ },+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`BFL polling failed (${response.status}): ${errorText}`);+ }++ const payload = await response.json();+ const status = payload?.status;++ if (status === "Ready") {+ return payload;+ }++ if (BFL_FAILURE_STATUSES.has(status)) {+ throw new Error(`BFL image generation failed: ${status}`);+ }++ if (log) {+ log.info("IMAGE", `black-forest-labs polling status: ${String(status || "Pending")}`);+ }++ await sleep(pollIntervalMs);+ }++ throw new Error(`BFL polling timed out after ${timeoutMs}ms`);+}++function extractImageInputs(body) {+ const imageUrls = [];+ const seen = new Set();++ const pushCandidate = (candidate) => {+ if (typeof candidate !== "string") return;+ const trimmed = candidate.trim();+ if (!trimmed || seen.has(trimmed)) return;+ seen.add(trimmed);+ imageUrls.push(trimmed);+ };++ pushCandidate(body?.image_url);+ pushCandidate(body?.image);++ if (Array.isArray(body?.imageUrls)) {+ for (const candidate of body.imageUrls) pushCandidate(candidate);+ }++ if (Array.isArray(body?.image_urls)) {+ for (const candidate of body.image_urls) pushCandidate(candidate);+ }++ if (Array.isArray(body?.messages)) {+ for (const msg of body.messages) {+ if (!Array.isArray(msg?.content)) continue;+ for (const part of msg.content) {+ if (part?.type === "image_url") {+ pushCandidate(part?.image_url?.url);+ }+ }+ }+ }++ return {+ imageUrl: imageUrls[0] || null,+ imageUrls,+ maskUrl:+ typeof body?.mask_url === "string"+ ? body.mask_url+ : typeof body?.mask === "string"+ ? body.mask+ : null,+ };+}++async function resolveImageSource(source) {+ if (typeof source !== "string" || source.trim().length === 0) {+ throw new Error("Invalid image source");+ }++ const trimmed = source.trim();+ const dataUriMatch = /^data:([^;]+);base64,(.+)$/i.exec(trimmed);+ if (dataUriMatch) {+ const [, contentType, base64] = dataUriMatch;+ return {+ buffer: Buffer.from(base64, "base64"),+ base64,+ contentType,+ };+ }++ if (isHttpUrl(trimmed)) {+ const response = await fetch(trimmed);+ if (!response.ok) {+ throw new Error(`Failed to fetch image source (${response.status})`);+ }+ const buffer = Buffer.from(await response.arrayBuffer());+ return {+ buffer,+ base64: buffer.toString("base64"),+ contentType: response.headers.get("content-type") || "application/octet-stream",+ };+ }++ return {+ buffer: Buffer.from(trimmed, "base64"),+ base64: trimmed,+ contentType: "application/octet-stream",+ };+}++function parseSizeToDimensions(size, fallback = 1024) {+ if (typeof size !== "string" || !size.includes("x")) {+ return { width: fallback, height: fallback };+ }++ const [widthRaw, heightRaw] = size.split("x");+ const width = Number(widthRaw);+ const height = Number(heightRaw);+ return {+ width: Number.isFinite(width) && width > 0 ? width : fallback,+ height: Number.isFinite(height) && height > 0 ? height : fallback,+ };+}++function normalizeRequestedImageFormat(+ body,+ fallback = "png",+ allowedFormats = ["jpeg", "png", "webp"]+) {+ const formatCandidate =+ typeof body?.output_format === "string"+ ? body.output_format.toLowerCase()+ : typeof body?.response_format === "string" &&+ !["url", "b64_json"].includes(body.response_format.toLowerCase())+ ? body.response_format.toLowerCase()+ : fallback;++ if (allowedFormats.includes(formatCandidate)) {+ return formatCandidate;+ }++ return fallback;+}++function mapFalImageSize(size, fallback = "square_hd") {+ if (typeof size !== "string") return fallback;+ if (FAL_PRESET_SIZES[size]) return FAL_PRESET_SIZES[size];+ if (size.includes("x")) {+ const { width, height } = parseSizeToDimensions(size, 1024);+ return { width, height };+ }+ return fallback;+}++function mapFalAspectRatio(size, fallback = "1:1") {+ if (!size) return fallback;+ return mapImageSize(size);+}++function normalizeRecraftStyle(style) {+ if (style === "vivid") return "digital_illustration";+ if (style === "natural") return "realistic_image";+ return style;+}++function shouldIncludeStabilityMask(model) {+ return new Set([+ "inpaint",+ "erase",+ "search-and-replace",+ "search-and-recolor",+ "replace-background-and-relight",+ ]).has(model);+}++async function normalizeProviderImagePayload(payload, body, log) {+ const candidates = [];++ const pushCandidate = (value) => {+ if (value === undefined || value === null) return;+ candidates.push(value);+ };++ if (Array.isArray(payload?.data)) {+ for (const item of payload.data) pushCandidate(item);+ }++ if (Array.isArray(payload?.images)) {+ for (const item of payload.images) pushCandidate(item);+ }++ if (payload?.image) pushCandidate({ b64_json: payload.image });+ if (payload?.url) pushCandidate({ url: payload.url });+ if (payload?.sample) pushCandidate({ url: payload.sample });+ if (payload?.result?.sample) pushCandidate({ url: payload.result.sample });+ if (Array.isArray(payload?.result?.images)) {+ for (const item of payload.result.images) pushCandidate(item);+ }++ const normalized = [];+ for (const candidate of candidates) {+ const item = await normalizeProviderImageCandidate(candidate, body);+ if (item) normalized.push(item);+ }++ if (normalized.length === 0 && log) {+ log.warn(+ "IMAGE",+ `Provider returned no recognizable image payload: ${JSON.stringify(payload).slice(0, 240)}`+ );+ }++ return normalized;+}++async function normalizeProviderImageCandidate(candidate, body) {+ const wantsBase64 = body?.response_format === "b64_json";+ let url = null;+ let b64 = null;++ if (typeof candidate === "string") {+ const dataUriMatch = /^data:[^;]+;base64,(.+)$/i.exec(candidate);+ if (dataUriMatch) {+ b64 = dataUriMatch[1];+ } else if (isHttpUrl(candidate)) {+ url = candidate;+ } else {+ b64 = candidate;+ }+ } else if (candidate && typeof candidate === "object") {+ url =+ firstString(candidate.url, candidate.image_url, candidate.sample, candidate.file_url) || null;+ b64 =+ firstString(candidate.b64_json, candidate.image, candidate.base64, candidate.data) || null;+ }++ if (wantsBase64 && !b64 && url) {+ b64 = (await resolveImageSource(url)).base64;+ }++ if (url && !wantsBase64) {+ return { url, revised_prompt: body?.prompt };+ }++ if (b64) {+ return { b64_json: b64, revised_prompt: body?.prompt };+ }++ if (url) {+ return { url, revised_prompt: body?.prompt };+ }++ return null;+}++function firstString(...values) {+ for (const value of values) {+ if (typeof value === "string" && value.length > 0) return value;+ }+ return null;+}++function isHttpUrl(value) {+ return typeof value === "string" && /^https?:\/\//i.test(value);+}++function saveImageSuccessResult({+ provider,+ model,+ startTime,+ requestBody = null,+ responseBody = null,+ created = null,+ images,+}) {+ saveCallLog({+ method: "POST",+ path: "/v1/images/generations",+ status: 200,+ model: `${provider}/${model}`,+ provider,+ duration: Date.now() - startTime,+ requestBody,+ responseBody,+ }).catch(() => {});++ return {+ success: true,+ data: {+ created: created || Math.floor(Date.now() / 1000),+ data: images,+ },+ };+}++function saveImageErrorResult({ provider, model, status, startTime, error, requestBody = null }) {+ saveCallLog({+ method: "POST",+ path: "/v1/images/generations",+ status,+ model: `${provider}/${model}`,+ provider,+ duration: Date.now() - startTime,+ error: typeof error === "string" ? error.slice(0, 500) : String(error).slice(0, 500),+ requestBody,+ }).catch(() => {});++ return {+ success: false,+ status,+ error,+ };+}+/*** Fetch a single image endpoint and normalize response*/diff --git a/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx b/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsxindex 4384cc6be3..f06b7ad2fd 100644--- a/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx+++ b/src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx@@ -3,6 +3,8 @@import { useState, useEffect, useRef } from "react";import { useTranslations } from "next-intl";import Link from "next/link";+import { IMAGE_PROVIDERS } from "@omniroute/open-sse/config/imageRegistry.ts";+import { AI_PROVIDERS } from "@/shared/constants/providers";type Modality = "image" | "video" | "music" | "speech" | "transcription";type GenerationResult = {@@ -12,6 +14,19 @@ type GenerationResult = {audioUrl?: string;};+const PROVIDER_METADATA = AI_PROVIDERS as Record<string, { name?: string }>;+const IMAGE_PROVIDER_MODELS = Object.entries(IMAGE_PROVIDERS).map(([providerId, config]) => ({+ id: providerId,+ name: PROVIDER_METADATA[providerId]?.name || providerId,+ models: config.models.map((model) => ({+ id: `${providerId}/${model.id}`,+ name: model.name,+ })),+}));+const IMAGE_PROVIDERS_REQUIRING_CREDENTIALS = Object.entries(IMAGE_PROVIDERS)+ .filter(([, config]) => config.authType !== "none")+ .map(([providerId]) => providerId);+const MODALITY_CONFIG: Record<Modality,{@@ -30,7 +45,7 @@ const MODALITY_CONFIG: Record<label: "Image Generation",placeholder: "A serene landscape with mountains at sunset...",color: "from-purple-500 to-pink-500",- needsCredentials: ["openai", "xai", "fireworks", "nebius", "hyperbolic"],+ needsCredentials: IMAGE_PROVIDERS_REQUIRING_CREDENTIALS,},video: {icon: "videocam",@@ -67,82 +82,12 @@ const MODALITY_CONFIG: Record<},};-// Static provider+model registry (mirrors open-sse/config/*Registry.ts)+// Provider+model registry (image is derived from the runtime image registry to avoid drift)const PROVIDER_MODELS: Record<Modality,{ id: string; name: string; models: { id: string; name: string }[] }[]> = {- image: [- {- id: "openai",- name: "OpenAI",- models: [- { id: "openai/dall-e-3", name: "DALL-E 3" },- { id: "openai/dall-e-2", name: "DALL-E 2" },- ],- },- {- id: "xai",- name: "xAI (Grok)",- models: [{ id: "xai/grok-2-image-1212", name: "Grok 2 Image" }],- },- {- id: "together",- name: "Together AI",- models: [- { id: "together/stabilityai/stable-diffusion-xl-base-1.0", name: "SDXL" },- { id: "together/black-forest-labs/FLUX.1-schnell-Free", name: "FLUX.1 Schnell" },- ],- },- {- id: "fireworks",- name: "Fireworks AI",- models: [- {- id: "fireworks/accounts/fireworks/models/stable-diffusion-xl-1024-v1-0",- name: "SDXL 1024",- },- { id: "fireworks/accounts/fireworks/models/flux-1-dev-fp8", name: "FLUX.1 Dev" },- ],- },- {- id: "nebius",- name: "Nebius AI",- models: [- { id: "nebius/black-forest-labs/flux-dev", name: "FLUX Dev" },- { id: "nebius/black-forest-labs/flux-schnell", name: "FLUX Schnell" },- ],- },- {- id: "hyperbolic",- name: "Hyperbolic",- models: [- { id: "hyperbolic/SDXL1.0-base", name: "SDXL Base" },- { id: "hyperbolic/stable-diffusion-2", name: "SD 2" },- ],- },- {- id: "nanobanana",- name: "NanoBanana",- models: [- { id: "nanobanana/nanobanana-flash", name: "NanoBanana Flash" },- { id: "nanobanana/nanobanana-pro", name: "NanoBanana Pro" },- ],- },- {- id: "sdwebui",- name: "SD WebUI",- models: [{ id: "sdwebui/sd_xl_base_1.0", name: "SDXL Base (Local)" }],- },- {- id: "comfyui",- name: "ComfyUI",- models: [- { id: "comfyui/flux-dev", name: "FLUX Dev (Local)" },- { id: "comfyui/sdxl", name: "SDXL (Local)" },- ],- },- ],+ image: IMAGE_PROVIDER_MODELS,video: [{id: "comfyui",diff --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.tsindex 959585fc68..ade9d19249 100755--- a/src/app/api/providers/[id]/models/route.ts+++ b/src/app/api/providers/[id]/models/route.ts@@ -17,6 +17,7 @@ import { getStaticQoderModels } from "@omniroute/open-sse/services/qoderCli.ts";import { getAntigravityHeaders } from "@omniroute/open-sse/services/antigravityHeaders.ts";import { getAntigravityModelsDiscoveryUrls } from "@omniroute/open-sse/config/antigravityUpstream.ts";import { getGlmModelsUrl } from "@omniroute/open-sse/config/glmProvider.ts";+import { getImageProvider } from "@omniroute/open-sse/config/imageRegistry.ts";type JsonRecord = Record<string, unknown>;@@ -161,7 +162,19 @@ export function getStaticModelsForProvider(provider: string): Array<{ id: string; name: string }> | undefined {const staticModelsFn = STATIC_MODEL_PROVIDERS[provider];- return staticModelsFn ? staticModelsFn() : undefined;+ if (staticModelsFn) {+ return staticModelsFn();+ }++ const imageProvider = getImageProvider(provider);+ if (imageProvider) {+ return imageProvider.models.map((model) => ({+ id: model.id,+ name: model.name || model.id,+ }));+ }++ return undefined;}// Provider models endpoints configuration@@ -771,15 +784,12 @@ export async function GET(}// Static model providers (no remote /models API)- const staticModelsFn =- provider in STATIC_MODEL_PROVIDERS- ? STATIC_MODEL_PROVIDERS[provider as keyof typeof STATIC_MODEL_PROVIDERS]- : undefined;- if (staticModelsFn) {+ const staticModels = getStaticModelsForProvider(provider);+ if (staticModels) {return buildResponse({provider,connectionId,- models: staticModelsFn(),+ models: staticModels,});}@@ -802,7 +812,7 @@ export async function GET(provider in PROVIDER_MODELS_CONFIG? PROVIDER_MODELS_CONFIG[provider as keyof typeof PROVIDER_MODELS_CONFIG]: undefined;- const localCatalog = PROVIDER_MODELS[provider] || [];+ const localCatalog = getStaticModelsForProvider(provider) || PROVIDER_MODELS[provider] || [];if (!config && localCatalog.length > 0) {return buildResponse({provider,diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.tsindex 95c4763b05..bb751b1e31 100644--- a/src/shared/constants/providers.ts+++ b/src/shared/constants/providers.ts@@ -862,6 +862,51 @@ export const APIKEY_PROVIDERS = {website: "https://api.laozhang.ai",passthroughModels: true,},+ "fal-ai": {+ id: "fal-ai",+ alias: "fal",+ name: "Fal.ai",+ icon: "image",+ color: "#2563EB",+ textIcon: "FL",+ website: "https://fal.ai",+ },+ "stability-ai": {+ id: "stability-ai",+ alias: "stability",+ name: "Stability AI",+ icon: "image",+ color: "#8B5CF6",+ textIcon: "SA",+ website: "https://stability.ai",+ },+ "black-forest-labs": {+ id: "black-forest-labs",+ alias: "bfl",+ name: "Black Forest Labs",+ icon: "image",+ color: "#111827",+ textIcon: "BF",+ website: "https://blackforestlabs.ai",+ },+ recraft: {+ id: "recraft",+ alias: "recraft",+ name: "Recraft",+ icon: "image",+ color: "#EC4899",+ textIcon: "RC",+ website: "https://recraft.ai",+ },+ topaz: {+ id: "topaz",+ alias: "topaz",+ name: "Topaz",+ icon: "image",+ color: "#059669",+ textIcon: "TP",+ website: "https://topazlabs.com",+ },};// Search Providersdiff --git a/tests/unit/image-generation-handler.test.ts b/tests/unit/image-generation-handler.test.tsindex 3ea07dd4ba..649ee6541b 100644--- a/tests/unit/image-generation-handler.test.ts+++ b/tests/unit/image-generation-handler.test.ts@@ -6,7 +6,8 @@ import { join } from "node:path";process.env.DATA_DIR = mkdtempSync(join(tmpdir(), "omniroute-images-"));-const { IMAGE_PROVIDERS } = await import("../../open-sse/config/imageRegistry.ts");+const { IMAGE_PROVIDERS, parseImageModel, getAllImageModels } =+ await import("../../open-sse/config/imageRegistry.ts");const { handleImageGeneration } = await import("../../open-sse/handlers/imageGeneration.ts");function immediateTimeout(callback, _ms, ...args) {@@ -247,6 +248,329 @@ test("handleImageGeneration treats unknown provider prefixes as invalid image moassert.match(result.error, /Invalid image model: mystery\/model-1/);});+test("image registry resolves flux aliases and exposes planned catalog aliases", () => {+ assert.deepEqual(parseImageModel("flux-kontext"), {+ provider: "pollinations",+ model: "flux-kontext",+ });+ assert.deepEqual(parseImageModel("pollinations/kontext"), {+ provider: "pollinations",+ model: "flux-kontext",+ });+ assert.deepEqual(parseImageModel("flux-redux"), {+ provider: "together",+ model: "black-forest-labs/FLUX.1-redux",+ });++ const modelIds = new Set(getAllImageModels().map((model) => model.id));+ for (const alias of [+ "flux-kontext",+ "flux-kontext-max",+ "flux-redux",+ "flux-depth",+ "flux-canny",+ "flux-dev-lora",+ ]) {+ assert.equal(modelIds.has(alias), true, `Expected alias ${alias} in image catalog`);+ }+});++test("handleImageGeneration calls Fal AI with Key auth and normalizes URL results to base64", async () => {+ const originalFetch = globalThis.fetch;+ let requestCapture;++ globalThis.fetch = async (url, options = {}) => {+ const stringUrl = String(url);+ if (stringUrl === "https://fal.run/fal-ai/flux-pro/v1.1-ultra") {+ requestCapture = {+ url: stringUrl,+ headers: options.headers,+ body: JSON.parse(String(options.body || "{}")),+ };++ return new Response(+ JSON.stringify({+ images: [{ url: "https://cdn.example.com/fal-ultra.png" }],+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ }++ if (stringUrl === "https://cdn.example.com/fal-ultra.png") {+ return new Response(new Uint8Array([5, 6, 7]), {+ status: 200,+ headers: { "content-type": "image/png" },+ });+ }++ throw new Error(`Unexpected URL: ${stringUrl}`);+ };++ try {+ const result = await handleImageGeneration({+ body: {+ model: "fal-ai/fal-ai/flux-pro/v1.1-ultra",+ prompt: "cinematic skyline",+ size: "1024x1792",+ n: 2,+ image_url: "https://example.com/source.png",+ response_format: "b64_json",+ },+ credentials: { apiKey: "fal-key" },+ log: null,+ });++ assert.equal(result.success, true);+ assert.equal(requestCapture.url, "https://fal.run/fal-ai/flux-pro/v1.1-ultra");+ assert.equal(requestCapture.headers.Authorization, "Key fal-key");+ assert.equal(requestCapture.body.aspect_ratio, "9:16");+ assert.equal(requestCapture.body.image_url, "https://example.com/source.png");+ assert.equal(requestCapture.body.num_images, 2);+ assert.equal(requestCapture.body.sync_mode, true);+ assert.equal(result.data.data[0].b64_json, "BQYH");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("handleImageGeneration routes Stability AI edit models to native endpoints", async () => {+ const originalFetch = globalThis.fetch;+ let requestCapture;++ globalThis.fetch = async (url, options = {}) => {+ const stringUrl = String(url);+ if (stringUrl === "https://example.com/stability-input.png") {+ return new Response(new Uint8Array([4, 5]), {+ status: 200,+ headers: { "content-type": "image/png" },+ });+ }++ if (stringUrl === "https://api.stability.ai/v2beta/stable-image/edit/inpaint") {+ requestCapture = {+ url: stringUrl,+ headers: options.headers,+ body: JSON.parse(String(options.body || "{}")),+ };++ return new Response(JSON.stringify({ image: "c3RhYmlsaXR5LWltYWdl" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }++ throw new Error(`Unexpected URL: ${stringUrl}`);+ };++ try {+ const result = await handleImageGeneration({+ body: {+ model: "stability-ai/inpaint",+ prompt: "replace the sky with aurora",+ negative_prompt: "rain",+ image_url: "https://example.com/stability-input.png",+ mask: "data:image/png;base64,AA==",+ response_format: "b64_json",+ },+ credentials: { apiKey: "stability-key" },+ log: null,+ });++ assert.equal(result.success, true);+ assert.equal(requestCapture.url, "https://api.stability.ai/v2beta/stable-image/edit/inpaint");+ assert.equal(requestCapture.headers.Authorization, "Bearer stability-key");+ assert.equal(requestCapture.body.image, "BAU=");+ assert.equal(requestCapture.body.mask, "AA==");+ assert.equal(requestCapture.body.output_format, "png");+ assert.equal(result.data.data[0].b64_json, "c3RhYmlsaXR5LWltYWdl");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("handleImageGeneration polls Black Forest Labs results and sends base64 input images", async () => {+ const originalFetch = globalThis.fetch;+ const originalSetTimeout = globalThis.setTimeout;+ let createCapture;+ let pollCapture;++ globalThis.setTimeout = immediateTimeout;+ globalThis.fetch = async (url, options = {}) => {+ const stringUrl = String(url);+ if (stringUrl === "https://example.com/bfl-input.png") {+ return new Response(new Uint8Array([1, 2]), {+ status: 200,+ headers: { "content-type": "image/png" },+ });+ }++ if (stringUrl === "https://api.bfl.ai/v1/flux-kontext-pro") {+ createCapture = {+ url: stringUrl,+ headers: options.headers,+ body: JSON.parse(String(options.body || "{}")),+ };++ return new Response(JSON.stringify({ polling_url: "https://api.bfl.ai/result/123" }), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }++ if (stringUrl === "https://api.bfl.ai/result/123") {+ pollCapture = {+ url: stringUrl,+ headers: options.headers,+ };++ return new Response(+ JSON.stringify({+ status: "Ready",+ result: { sample: "https://cdn.example.com/bfl-result.png" },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ }++ if (stringUrl === "https://cdn.example.com/bfl-result.png") {+ return new Response(new Uint8Array([9, 8, 7]), {+ status: 200,+ headers: { "content-type": "image/png" },+ });+ }++ throw new Error(`Unexpected URL: ${stringUrl}`);+ };++ try {+ const result = await handleImageGeneration({+ body: {+ model: "black-forest-labs/flux-kontext-pro",+ prompt: "change the car color to blue",+ image_url: "https://example.com/bfl-input.png",+ size: "1024x1792",+ response_format: "b64_json",+ },+ credentials: { apiKey: "bfl-key" },+ log: null,+ });++ assert.equal(result.success, true);+ assert.equal(createCapture.url, "https://api.bfl.ai/v1/flux-kontext-pro");+ assert.equal(createCapture.headers["x-key"], "bfl-key");+ assert.equal(createCapture.body.input_image, "AQI=");+ assert.equal(createCapture.body.aspect_ratio, "9:16");+ assert.equal(pollCapture.headers["x-key"], "bfl-key");+ assert.equal(result.data.data[0].b64_json, "CQgH");+ } finally {+ globalThis.fetch = originalFetch;+ globalThis.setTimeout = originalSetTimeout;+ }+});++test("handleImageGeneration calls native Recraft endpoint with model in body", async () => {+ const originalFetch = globalThis.fetch;+ let captured;++ globalThis.fetch = async (url, options = {}) => {+ captured = {+ url: String(url),+ headers: options.headers,+ body: JSON.parse(String(options.body || "{}")),+ };++ return new Response(+ JSON.stringify({+ data: [{ url: "https://cdn.example.com/recraft.png" }],+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ };++ try {+ const result = await handleImageGeneration({+ body: {+ model: "recraft/recraftv3",+ prompt: "vector fox logo",+ size: "1024x1024",+ style: "digital_illustration",+ },+ credentials: { apiKey: "recraft-key" },+ log: null,+ });++ assert.equal(result.success, true);+ assert.equal(captured.url, "https://external.api.recraft.ai/v1/images/generations");+ assert.equal(captured.headers.Authorization, "Bearer recraft-key");+ assert.deepEqual(captured.body, {+ model: "recraftv3",+ prompt: "vector fox logo",+ size: "1024x1024",+ style: "digital_illustration",+ });+ assert.equal(result.data.data[0].url, "https://cdn.example.com/recraft.png");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("handleImageGeneration uploads source images to Topaz and returns base64 output", async () => {+ const originalFetch = globalThis.fetch;+ let requestCapture;++ globalThis.fetch = async (url, options = {}) => {+ const stringUrl = String(url);+ if (stringUrl === "https://example.com/topaz-input.png") {+ return new Response(new Uint8Array([1, 2, 3]), {+ status: 200,+ headers: { "content-type": "image/png" },+ });+ }++ if (stringUrl === "https://api.topazlabs.com/image/v1/enhance") {+ const formData = options.body as FormData;+ requestCapture = {+ url: stringUrl,+ headers: options.headers,+ outputWidth: formData.get("output_width"),+ outputHeight: formData.get("output_height"),+ image: formData.get("image"),+ };++ return new Response(new Uint8Array([7, 7, 7]), {+ status: 200,+ headers: { "content-type": "image/jpeg" },+ });+ }++ throw new Error(`Unexpected URL: ${stringUrl}`);+ };++ try {+ const result = await handleImageGeneration({+ body: {+ model: "topaz/topaz-enhance",+ prompt: "enhance image",+ image_url: "https://example.com/topaz-input.png",+ size: "2048x2048",+ response_format: "b64_json",+ },+ credentials: { apiKey: "topaz-key" },+ log: null,+ });++ assert.equal(result.success, true);+ assert.equal(requestCapture.url, "https://api.topazlabs.com/image/v1/enhance");+ assert.equal(requestCapture.headers["X-API-Key"], "topaz-key");+ assert.equal(requestCapture.outputWidth, "2048");+ assert.equal(requestCapture.outputHeight, "2048");+ assert.ok(requestCapture.image instanceof File);+ assert.equal(result.data.data[0].b64_json, "BwcH");+ } finally {+ globalThis.fetch = originalFetch;+ }+});+test("handleImageGeneration transforms Gemini image responses from Antigravity", async () => {const originalFetch = globalThis.fetch;let captured;