Skip to content

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

merge main into kie media provider branch

wauputr4a591b4fc4bc1
diff --cc open-sse/config/audioRegistry.ts
index f6ba4ffe27,f453dd6236..b08a02962c
--- a/open-sse/config/audioRegistry.ts
+++ b/open-sse/config/audioRegistry.ts
@@@ -259,19 -247,33 +259,47 @@@ export const AUDIO_SPEECH_PROVIDERS: Re
],
},
+ kie: {
+ id: "kie",
+ baseUrl: "https://api.kie.ai",
+ authType: "apikey",
+ authHeader: "bearer",
+ format: "kie-audio",
+ models: [
+ { id: "elevenlabs/text-to-speech-multilingual-v2", name: "ElevenLabs TTS v2" },
+ { id: "elevenlabs/text-to-speech-turbo-2-5", name: "ElevenLabs TTS Turbo 2.5" },
+ { id: "elevenlabs/text-to-dialogue-v3", name: "ElevenLabs Text to Dialogue v3" },
+ { id: "elevenlabs/sound-effect-v2", name: "ElevenLabs Sound Effect v2" },
+ ],
+ },
++
+ "aws-polly": {
+ id: "aws-polly",
+ // POST https://polly.{region}.amazonaws.com/v1/speech
+ // Auth: AWS SigV4. The provider apiKey stores Secret Access Key; PSD stores accessKeyId/region.
+ baseUrl: "https://polly.us-east-1.amazonaws.com",
+ authType: "apikey",
+ authHeader: "aws-sigv4",
+ format: "aws-polly",
+ models: [
+ { id: "standard", name: "Polly Standard" },
+ { id: "neural", name: "Polly Neural" },
+ { id: "long-form", name: "Polly Long-Form" },
+ { id: "generative", name: "Polly Generative" },
+ ],
+ },
+ "xiaomi-mimo": {
+ id: "xiaomi-mimo",
+ baseUrl: "https://api.xiaomimimo.com/v1/chat/completions",
+ authType: "apikey",
+ authHeader: "bearer",
+ format: "xiaomi-mimo-tts",
+ models: [
+ { id: "mimo-v2.5-tts", name: "MiMo V2.5 TTS" },
+ { id: "mimo-v2.5-tts-voicedesign", name: "MiMo V2.5 Voice Design" },
+ { id: "mimo-v2.5-tts-voiceclone", name: "MiMo V2.5 Voice Clone" },
+ ],
+ },
};
/**
diff --cc open-sse/executors/index.ts
index 2153aa5b51,9f21c25f2f..ba3a195676
--- a/open-sse/executors/index.ts
+++ b/open-sse/executors/index.ts
@@@ -14,7 -14,13 +14,14 @@@ import { VertexExecutor } from "./verte
import { CliproxyapiExecutor } from "./cliproxyapi.ts";
import { PerplexityWebExecutor } from "./perplexity-web.ts";
import { GrokWebExecutor } from "./grok-web.ts";
+import { KieExecutor } from "./kie.ts";
+ import { ChatGptWebExecutor } from "./chatgpt-web.ts";
+ import { BlackboxWebExecutor } from "./blackbox-web.ts";
+ import { MuseSparkWebExecutor } from "./muse-spark-web.ts";
+ import { AzureOpenAIExecutor } from "./azure-openai.ts";
+ import { GitlabExecutor } from "./gitlab.ts";
+ import { NlpCloudExecutor } from "./nlpcloud.ts";
+ import { PetalsExecutor } from "./petals.ts";
const executors = {
antigravity: new AntigravityExecutor(),
@@@ -39,7 -52,12 +53,13 @@@
"perplexity-web": new PerplexityWebExecutor(),
"pplx-web": new PerplexityWebExecutor(), // Alias
"grok-web": new GrokWebExecutor(),
+ kie: new KieExecutor(),
+ "chatgpt-web": new ChatGptWebExecutor(),
+ "cgpt-web": new ChatGptWebExecutor(), // Alias
+ "blackbox-web": new BlackboxWebExecutor(),
+ "bb-web": new BlackboxWebExecutor(), // Alias
+ "muse-spark-web": new MuseSparkWebExecutor(),
+ "ms-web": new MuseSparkWebExecutor(), // Alias
};
const defaultCache = new Map();
@@@ -71,4 -89,10 +91,11 @@@ export { CliproxyapiExecutor } from "./
export { VertexExecutor } from "./vertex.ts";
export { PerplexityWebExecutor } from "./perplexity-web.ts";
export { GrokWebExecutor } from "./grok-web.ts";
+export { KieExecutor } from "./kie.ts";
+ export { ChatGptWebExecutor } from "./chatgpt-web.ts";
+ export { BlackboxWebExecutor } from "./blackbox-web.ts";
+ export { MuseSparkWebExecutor } from "./muse-spark-web.ts";
+ export { AzureOpenAIExecutor } from "./azure-openai.ts";
+ export { GitlabExecutor } from "./gitlab.ts";
+ export { NlpCloudExecutor } from "./nlpcloud.ts";
+ export { PetalsExecutor } from "./petals.ts";
diff --cc open-sse/handlers/audioSpeech.ts
index be07120491,d4d224531f..2342a6d9ea
--- a/open-sse/handlers/audioSpeech.ts
+++ b/open-sse/handlers/audioSpeech.ts
@@@ -19,15 -20,8 +20,16 @@@ import { stripTrailingSlashes } from ".
import { getSpeechProvider, parseSpeechModel } from "../config/audioRegistry.ts";
import { buildAuthHeaders } from "../config/registryUtils.ts";
+import { kieExecutor } from "../executors/kie.ts";
import { errorResponse } from "../utils/error.ts";
+import {
+ getKieCallbackUrl,
+ getKieErrorMessage,
+ getKieErrorStatus,
+ isJsonObject,
+ parseKieResultJson,
+} from "../utils/kieTask.ts";
+ import { signAwsRequest } from "../utils/awsSigV4.ts";
/**
* Return a CORS error response from an upstream fetch failure
@@@ -412,101 -440,133 +531,228 @@@ async function handlePlayHtSpeech(provi
return audioStreamResponse(res);
}
+/**
+ * Handle Kie.ai TTS
+ * Kie.ai has model-specific endpoints or uses unified jobs API.
+ */
+async function handleKieAudioSpeech(providerConfig, body, modelId, token) {
+ const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
-
+ const voice = normalizeKieElevenLabsVoice(body.voice);
+
+ const payload = {
+ model: modelId,
+ callBackUrl: getKieCallbackUrl(body),
+ input: {
+ text: body.input,
+ voice,
+ stability: typeof body.stability === "number" ? body.stability : 0.5,
+ similarity_boost: typeof body.similarity_boost === "number" ? body.similarity_boost : 0.75,
+ style: typeof body.style === "number" ? body.style : 0,
+ speed: typeof body.speed === "number" ? body.speed : 1,
+ timestamps: body.timestamps === true,
+ previous_text: body.previous_text || "",
+ next_text: body.next_text || "",
+ language_code: body.language_code || "",
+ },
+ };
+
+ let data;
+ try {
+ data = await kieExecutor.createTask({
+ baseUrl,
+ token,
+ payload,
+ });
+ } catch (err: unknown) {
+ const status = getKieErrorStatus(err, 502);
+ return Response.json(
+ {
+ error: { message: getKieErrorMessage(err, "Kie audio createTask failed"), code: status },
+ },
+ {
+ status,
- headers: { "Access-Control-Allow-Origin": getCorsOrigin() },
++ headers: { ...CORS_HEADERS },
+ }
+ );
+ }
- const taskId = data?.data?.taskId || data?.taskId;
+
++ const taskId = data?.data?.taskId || data?.taskId;
+ if (taskId) {
+ return pollKieAudioResult(baseUrl, modelId, taskId, token);
+ }
+
+ const audioUrl = findKieAudioUrl(data);
+ if (typeof audioUrl === "string" && audioUrl.length > 0) {
+ const audioRes = await fetch(audioUrl);
+ return audioStreamResponse(audioRes);
+ }
+
+ return errorResponse(
+ 502,
+ data?.msg || data?.message || "Kie audio generation did not return taskId or audio URL"
+ );
+}
+
+/**
+ * Internal polling for Kie.ai async audio tasks
+ */
+async function pollKieAudioResult(baseUrl, modelId, taskId, token) {
++ void modelId;
+ const statusUrl = kieExecutor.getTaskStatusUrl(baseUrl);
+ try {
+ const { data, state } = await kieExecutor.pollTask({
+ statusUrl,
+ taskId: String(taskId),
+ token,
+ timeoutMs: 60000,
+ pollIntervalMs: 2000,
+ });
+
+ if (state === "success") {
+ const url = findKieAudioUrl(data);
+ if (url) {
+ const audioRes = await fetch(url);
+ return audioStreamResponse(audioRes);
+ }
+ return errorResponse(502, "Kie audio task completed without audio URL");
+ }
+ } catch (err: unknown) {
+ return errorResponse(
+ getKieErrorStatus(err, 504),
+ getKieErrorMessage(err, "Kie audio generation timed out or failed")
+ );
+ }
+
+ return errorResponse(504, "Kie audio generation timed out or failed");
+}
+
+ /**
+ * Handle AWS Polly TTS
+ * POST /v1/speech signed with AWS SigV4.
+ * The configured apiKey stores AWS Secret Access Key; providerSpecificData.accessKeyId stores
+ * AWS Access Key ID, with optional region/baseUrl/defaultVoice/sessionToken.
+ */
+ async function handleAwsPollySpeech(providerConfig, body, modelId, token, credentials) {
+ const providerSpecificData = getAwsPollyProviderData(credentials);
+ const accessKeyId =
+ getStringValue(providerSpecificData.accessKeyId) ||
+ getStringValue(providerSpecificData.awsAccessKeyId);
+ const secretAccessKey = getStringValue(token);
+
+ if (!accessKeyId) {
+ return errorResponse(400, "AWS Polly requires providerSpecificData.accessKeyId");
+ }
+ if (!secretAccessKey) {
+ return errorResponse(401, "No AWS Secret Access Key for AWS Polly");
+ }
+
+ const region = resolveAwsPollyRegion(providerSpecificData);
+ const baseUrl = resolveAwsPollyBaseUrl(providerSpecificData, region);
+ const url = `${baseUrl}/v1/speech`;
+ const outputFormat = normalizeAwsPollyOutputFormat(body.response_format);
+ const sampleRate = getAwsPollySampleRate(
+ body.response_format,
+ body.sample_rate || body.sampleRate
+ );
+
+ const requestBody = {
+ Engine: normalizeAwsPollyEngine(modelId),
+ OutputFormat: outputFormat,
+ Text: body.input,
+ TextType: normalizeAwsPollyTextType(body),
+ VoiceId:
+ getStringValue(body.voice) || getStringValue(providerSpecificData.defaultVoice) || "Joanna",
+ ...(getStringValue(body.language_code || body.languageCode)
+ ? { LanguageCode: getStringValue(body.language_code || body.languageCode) }
+ : {}),
+ ...(sampleRate ? { SampleRate: sampleRate } : {}),
+ };
+ const serializedBody = JSON.stringify(requestBody);
+
+ const signedHeaders = signAwsRequest({
+ method: "POST",
+ url,
+ region,
+ service: "polly",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: serializedBody,
+ credentials: {
+ accessKeyId,
+ secretAccessKey,
+ sessionToken:
+ getStringValue(providerSpecificData.sessionToken) ||
+ getStringValue(providerSpecificData.awsSessionToken),
+ },
+ });
+
+ const res = await fetch(url, {
+ method: "POST",
+ headers: signedHeaders,
+ body: serializedBody,
+ });
+
+ if (!res.ok) {
+ return upstreamErrorResponse(res, await res.text());
+ }
+
+ return audioStreamResponse(res, outputFormat === "pcm" ? "audio/pcm" : "audio/mpeg");
+ }
+
+ /**
+ * Xiaomi MiMo TTS uses chat/completions with an audio config instead of OpenAI's /audio/speech
+ * request body.
+ */
+ async function handleXiaomiMimoSpeech(providerConfig, body, modelId, token, credentials) {
+ const providerSpecificData = getProviderSpecificData(credentials);
+ const url = normalizeXiaomiMimoSpeechUrl(providerSpecificData.baseUrl || providerConfig.baseUrl);
+ const audioMimeType = normalizeXiaomiMimoMimeType(body.response_format);
+ if (!audioMimeType) {
+ return errorResponse(400, "Xiaomi MiMo TTS supports response_format mp3 or wav only");
+ }
+
+ const res = await fetch(url, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...buildAuthHeaders(providerConfig, token),
+ },
+ body: JSON.stringify({
+ model: modelId,
+ messages: [{ role: "assistant", content: body.input }],
+ audio: {
+ format: audioMimeType,
+ voice: body.voice || getStringValue(providerSpecificData.defaultVoice) || "mimo_default",
+ },
+ }),
+ });
+
+ if (!res.ok) {
+ return upstreamErrorResponse(res, await res.text());
+ }
+
+ const contentType = res.headers.get("content-type") || "";
+ if (contentType.startsWith("audio/")) {
+ return audioStreamResponse(res, audioMimeType);
+ }
+
+ const data = await res.json();
+ const audioBase64 = getXiaomiMimoAudioData(data);
+ if (!audioBase64) {
+ return errorResponse(502, "Xiaomi MiMo TTS response did not contain audio data");
+ }
+
+ const audioBuffer = Uint8Array.from(atob(audioBase64), (c) => c.charCodeAt(0));
+ return new Response(audioBuffer, {
+ status: 200,
+ headers: {
+ ...CORS_HEADERS,
+ "Content-Type": audioMimeType,
+ },
+ });
+ }
+
/**
* Handle Coqui TTS (local, no auth)
* POST {baseUrl} with { text, speaker_id } → WAV audio
@@@ -598,7 -656,7 +842,7 @@@ export async function handleAudioSpeech
if (!providerConfig) {
return errorResponse(
400,
- `No speech provider found for model "${body.model}". Use format provider/model. Available: openai, hyperbolic, deepgram, nvidia, elevenlabs, huggingface, inworld, cartesia, playht, coqui, tortoise, qwen`
- `No speech provider found for model "${body.model}". Use format provider/model. Available: openai, hyperbolic, deepgram, nvidia, elevenlabs, huggingface, inworld, cartesia, playht, aws-polly, xiaomi-mimo, coqui, tortoise, qwen`
++ `No speech provider found for model "${body.model}". Use format provider/model. Available: openai, hyperbolic, deepgram, nvidia, elevenlabs, huggingface, inworld, cartesia, playht, kie, aws-polly, xiaomi-mimo, coqui, tortoise, qwen`
);
}
@@@ -643,10 -701,14 +887,18 @@@
return handlePlayHtSpeech(providerConfig, body, modelId, token);
}
+ if (providerConfig.format === "kie-audio") {
+ return handleKieAudioSpeech(providerConfig, body, modelId, token);
+ }
+
+ if (providerConfig.format === "aws-polly") {
+ return handleAwsPollySpeech(providerConfig, body, modelId, token, credentials);
+ }
+
+ if (providerConfig.format === "xiaomi-mimo-tts") {
+ return handleXiaomiMimoSpeech(providerConfig, body, modelId, token, credentials);
+ }
+
if (providerConfig.format === "coqui") {
return handleCoquiSpeech(providerConfig, body);
}
diff --cc open-sse/handlers/audioTranscription.ts
index d2e512c83f,53a3ce4d2d..c2dfeb2d38
--- a/open-sse/handlers/audioTranscription.ts
+++ b/open-sse/handlers/audioTranscription.ts
@@@ -1,5 -1,4 +1,5 @@@
- import { getCorsOrigin } from "../utils/cors.ts";
-import { CORS_HEADERS } from "../utils/cors.ts";
++import { CORS_HEADERS, getCorsOrigin } from "../utils/cors.ts";
+import { Buffer } from "node:buffer";
/**
* Audio Transcription Handler
*
@@@ -283,100 -278,9 +280,100 @@@ async function handleHuggingFaceTranscr
// HuggingFace returns { text } directly
const text = data.text || "";
- return Response.json({ text }, { headers: { "Access-Control-Allow-Origin": getCorsOrigin() } });
+ return Response.json({ text }, { headers: { ...CORS_HEADERS } });
}
+/**
+ * Handle Kie.ai transcription
+ */
+async function handleKieAudioTranscription(providerConfig, file, modelId, token) {
+ const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
+ const fileBuffer = await file.arrayBuffer();
+ const fileBase64 = Buffer.from(fileBuffer).toString("base64");
+ let data;
+ try {
+ data = await kieExecutor.createTask({
+ baseUrl,
+ token,
+ payload: {
+ model: modelId,
+ input: {
+ file_name: getUploadedFileName(file),
+ file_base64: fileBase64,
+ },
+ },
+ });
+ } catch (err: unknown) {
+ const status =
+ typeof err === "object" && err !== null && "status" in err
+ ? Number((err as { status?: unknown }).status) || 502
+ : 502;
+ return Response.json(
+ {
+ error: {
+ message: err instanceof Error ? err.message : "Kie transcription createTask failed",
+ code: status,
+ },
+ },
+ {
+ status,
+ headers: { "Access-Control-Allow-Origin": getCorsOrigin() },
+ }
+ );
+ }
+ const taskId = data?.data?.taskId || data?.taskId;
+
+ if (taskId) {
+ return pollKieTranscriptionResult(baseUrl, modelId, taskId, token);
+ }
+
+ return Response.json(
+ { text: data?.data?.text || data?.text || "" },
+ { headers: { "Access-Control-Allow-Origin": getCorsOrigin() } }
+ );
+}
+
+/**
+ * Internal polling for Kie.ai async transcription tasks
+ */
+async function pollKieTranscriptionResult(baseUrl, modelId, taskId, token) {
+ void modelId;
+ const statusUrl = kieExecutor.getTaskStatusUrl(baseUrl);
+ try {
+ const { data, state } = await kieExecutor.pollTask({
+ statusUrl,
+ taskId: String(taskId),
+ token,
+ timeoutMs: 120000,
+ pollIntervalMs: 2000,
+ });
+
+ if (state === "success") {
+ const text =
+ data?.data?.response?.text ||
+ data?.data?.resultText ||
+ data?.data?.text ||
+ data?.text ||
+ "";
+ return Response.json(
+ { text },
+ { headers: { "Access-Control-Allow-Origin": getCorsOrigin() } }
+ );
+ }
+ } catch (err: unknown) {
+ const status =
+ typeof err === "object" && err !== null && "status" in err
+ ? Number((err as { status?: unknown }).status) || 504
+ : 504;
+ return errorResponse(
+ status,
+ err instanceof Error ? err.message : "Kie transcription generation timed out or failed"
+ );
+ }
+
+ return errorResponse(504, "Kie transcription generation timed out or failed");
+}
+
/**
* Handle audio transcription request
*
diff --cc open-sse/handlers/imageGeneration.ts
index dad16c939d,09777ece75..c58aaf627c
--- a/open-sse/handlers/imageGeneration.ts
+++ b/open-sse/handlers/imageGeneration.ts
@@@ -17,56 -17,31 +17,63 @@@ import { randomUUID } from "crypto"
*/
import { getImageProvider, parseImageModel } from "../config/imageRegistry.ts";
+import { kieExecutor } from "../executors/kie.ts";
import { mapImageSize } from "../translator/image/sizeMapper.ts";
+ import { getCodexClientVersion, getCodexUserAgent } from "../config/codexClient.ts";
+ import { ChatGptWebExecutor } from "../executors/chatgpt-web.ts";
+ import { getChatGptImage, findChatGptImageBySha256 } from "../services/chatgptImageCache.ts";
+ import { createHash } from "node:crypto";
import { saveCallLog } from "@/lib/usageDb";
+import { sleep } from "../utils/sleep.ts";
+import {
+ getKieErrorMessage,
+ getKieErrorStatus,
+ isJsonObject,
+ parseKieResultJson,
+} from "../utils/kieTask.ts";
import {
submitComfyWorkflow,
pollComfyResult,
fetchComfyOutput,
extractComfyOutputFiles,
} from "../utils/comfyuiClient.ts";
+ import { fetchRemoteImage } from "@/shared/network/remoteImageFetch";
+interface KieImageOptions {
+ model: string;
+ provider: string;
+ providerConfig: {
+ baseUrl: string;
+ statusUrl?: string;
+ };
+ body: Record<string, unknown> & {
+ prompt?: unknown;
+ size?: unknown;
+ n?: unknown;
+ timeout_ms?: unknown;
+ poll_interval_ms?: unknown;
+ };
+ credentials?: {
+ apiKey?: string;
+ accessToken?: string;
+ } | null;
+ log?: {
+ info: (scope: string, message: string) => void;
+ error: (scope: string, message: string) => void;
+ } | null;
+}
+
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",
+ "black-forest-labs/FLUX.2-max",
+ "black-forest-labs/FLUX.2-pro",
+ "black-forest-labs/FLUX.2-flex",
+ "black-forest-labs/FLUX.2-dev",
+ "openai/gpt-image-1.5",
+ "Wan-AI/Wan2.6-image",
+ "Qwen/Qwen-Image-2.0-Pro",
+ "Qwen/Qwen-Image-2.0",
+ "google/flash-image-3.1",
+ "google/gemini-3-pro-image",
"flux-kontext-max",
"flux-kontext",
"flux-kontext-pro",
diff --cc open-sse/handlers/videoGeneration.ts
index d5134bc8b9,4fc37b43b9..bd4fafb75f
--- a/open-sse/handlers/videoGeneration.ts
+++ b/open-sse/handlers/videoGeneration.ts
@@@ -16,8 -16,11 +16,13 @@@
*/
import { getVideoProvider, parseVideoModel } from "../config/videoRegistry.ts";
+import { kieExecutor } from "../executors/kie.ts";
+import { isJsonObject, parseKieResultJson } from "../utils/kieTask.ts";
+ import {
+ buildRunwayApiUrl,
+ buildRunwayHeaders,
+ RUNWAYML_IMAGE_REQUIRED_MODELS,
+ } from "../config/runway.ts";
import {
submitComfyWorkflow,
pollComfyResult,
@@@ -57,10 -60,10 +62,14 @@@ export async function handleVideoGenera
return handleSDWebUIVideoGeneration({ model, provider, providerConfig, body, log });
}
+ if (providerConfig.format === "kie-video") {
+ return handleKieVideoGeneration({ model, provider, providerConfig, body, credentials, log });
+ }
+
+ if (providerConfig.format === "runwayml") {
+ return handleRunwayVideoGeneration({ model, provider, providerConfig, body, credentials, log });
+ }
+
return {
success: false,
status: 400,
@@@ -269,134 -272,355 +278,487 @@@ async function handleSDWebUIVideoGenera
}
}
+function normalizeKieVideoResult(recordData: unknown): string[] {
+ const record = isJsonObject(recordData) ? recordData : {};
+ const data = isJsonObject(record.data) ? record.data : {};
+ const response = isJsonObject(data.response) ? data.response : {};
+ const resultJson = parseKieResultJson(recordData);
+
+ const urls = Array.isArray(resultJson?.resultUrls)
+ ? (resultJson.resultUrls as string[])
+ : Array.isArray(resultJson?.videoUrls)
+ ? (resultJson.videoUrls as string[])
+ : Array.isArray(response.resultUrls)
+ ? (response.resultUrls as string[])
+ : [];
+
+ return urls.filter((url: unknown) => typeof url === "string" && url.length > 0);
+}
+
+async function handleKieVideoGeneration({
+ model,
+ provider,
+ providerConfig,
+ body,
+ credentials,
+ log,
+}: {
+ model: string;
+ provider: string;
+ providerConfig: {
+ baseUrl: string;
+ statusUrl?: string;
+ };
+ body: Record<string, unknown> & {
+ prompt?: unknown;
+ duration?: unknown;
+ aspect_ratio?: unknown;
+ sound?: unknown;
+ timeout_ms?: unknown;
+ poll_interval_ms?: unknown;
+ };
+ credentials?: {
+ apiKey?: string;
+ accessToken?: string;
+ } | null;
+ log?: {
+ info: (scope: string, message: string) => void;
+ error: (scope: string, message: string) => void;
+ } | null;
+}) {
+ const startTime = Date.now();
+ const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
+ const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
+ const token = credentials?.apiKey || credentials?.accessToken;
+ const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
+ const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
+
+ if (!token) {
+ return { success: false, status: 401, error: "KIE API key is required" };
+ }
+
+ const payload = {
+ model,
+ input: {
+ prompt,
+ duration: body.duration ? String(body.duration) : "5",
+ aspect_ratio: typeof body.aspect_ratio === "string" ? body.aspect_ratio : "16:9",
+ sound: body.sound === true,
+ },
+ };
+
+ if (log) {
+ const promptPreview = String(body.prompt ?? "").slice(0, 60);
+ log.info("VIDEO", `${provider}/${model} (kie-video) | prompt: "${promptPreview}..."`);
+ }
+
+ try {
+ const createData = await kieExecutor.createTask({ baseUrl, token, payload });
+ const taskId = createData?.data?.taskId || createData?.taskId;
+ if (!taskId) {
+ const errorMessage =
+ createData?.msg ||
+ createData?.message ||
+ createData?.error ||
+ "KIE video generation did not return taskId";
+ if (log) {
+ log.error("VIDEO", `KIE createTask failed: ${JSON.stringify(createData)}`);
+ }
+ return { success: false, status: 502, error: errorMessage };
+ }
+
+ const statusUrl = providerConfig.statusUrl || `${baseUrl}/api/v1/jobs/recordInfo`;
+
+ const { data: recordData, state } = await kieExecutor.pollTask({
+ statusUrl,
+ taskId: String(taskId),
+ token,
+ timeoutMs,
+ pollIntervalMs,
+ });
+
+ if (state === "success") {
+ const videoUrls = normalizeKieVideoResult(recordData);
+ const videos = videoUrls.map((url) => ({ url, format: "mp4" }));
+
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 200,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ responseBody: { videos_count: videos.length },
+ }).catch(() => {});
+
+ return {
+ success: true,
+ data: { created: Math.floor(Date.now() / 1000), data: videos },
+ };
+ }
+
+ const record = isJsonObject(recordData) ? recordData : {};
+ const data = isJsonObject(record.data) ? record.data : {};
+ const errorMessage = data.failMsg || data.errorMessage || record.msg || "KIE video task failed";
+ return { success: false, status: 502, error: String(errorMessage) };
+ } catch (err: unknown) {
+ return {
+ success: false,
+ status: isJsonObject(err) && Number.isFinite(Number(err.status)) ? Number(err.status) : 502,
+ error: `Video provider error: ${err instanceof Error ? err.message : String(err)}`,
+ };
+ }
+}
++
+ async function handleRunwayVideoGeneration({
+ model,
+ provider,
+ providerConfig,
+ body,
+ credentials,
+ log,
+ }) {
+ const startTime = Date.now();
+ const token = credentials?.apiKey || credentials?.accessToken;
+ if (!token) {
+ return { success: false, status: 400, error: "No credentials for Runway provider" };
+ }
+
+ const promptImage = resolveRunwayPromptImage(body);
+ const useImageToVideo = Boolean(promptImage);
+ if (!useImageToVideo && RUNWAYML_IMAGE_REQUIRED_MODELS.has(model)) {
+ return {
+ success: false,
+ status: 400,
+ error: `Runway model ${model} requires promptImage for image-to-video generation`,
+ };
+ }
+
+ const ratio = resolveRunwayRatio(body);
+ const duration = resolveRunwayDuration(body);
+ const timeoutMs = resolvePositiveInteger(body.timeout_ms, 300000);
+ const pollIntervalMs = resolvePositiveInteger(body.poll_interval_ms, 5000);
+ const submitUrl = buildRunwayApiUrl(
+ useImageToVideo ? "/image_to_video" : "/text_to_video",
+ providerConfig.baseUrl
+ );
+ const headers = buildRunwayHeaders(token);
+
+ const upstreamBody = {
+ model,
+ promptText: body.prompt,
+ ratio,
+ duration,
+ };
+
+ if (useImageToVideo) upstreamBody.promptImage = promptImage;
+ if (typeof body.seed === "number" && Number.isFinite(body.seed)) {
+ upstreamBody.seed = Math.max(0, Math.floor(body.seed));
+ }
+
+ if (log) {
+ const promptPreview = String(body.prompt ?? "").slice(0, 60);
+ log.info(
+ "VIDEO",
+ `${provider}/${model} (runway ${useImageToVideo ? "image_to_video" : "text_to_video"}) | prompt: "${promptPreview}..."`
+ );
+ }
+
+ try {
+ const submitResponse = await fetch(submitUrl, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(upstreamBody),
+ });
+
+ if (!submitResponse.ok) {
+ const errorText = await submitResponse.text();
+ if (log) {
+ log.error(
+ "VIDEO",
+ `${provider} submit error ${submitResponse.status}: ${errorText.slice(0, 200)}`
+ );
+ }
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: submitResponse.status,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ error: errorText.slice(0, 500),
+ }).catch(() => {});
+ return { success: false, status: submitResponse.status, error: errorText };
+ }
+
+ const submitData = await submitResponse.json();
+ const taskId = typeof submitData?.id === "string" ? submitData.id : "";
+ if (!taskId) {
+ const errorText = `Runway submit did not return task id: ${JSON.stringify(submitData).slice(0, 400)}`;
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 502,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ error: errorText,
+ }).catch(() => {});
+ return { success: false, status: 502, error: errorText };
+ }
+
+ const deadline = Date.now() + timeoutMs;
+ let lastTask = null;
+
+ while (Date.now() < deadline) {
+ const taskResponse = await fetch(
+ buildRunwayApiUrl(`/tasks/${encodeURIComponent(taskId)}`, providerConfig.baseUrl),
+ {
+ method: "GET",
+ headers,
+ }
+ );
+
+ if (!taskResponse.ok) {
+ const errorText = await taskResponse.text();
+ if (log) {
+ log.error(
+ "VIDEO",
+ `${provider} poll error ${taskResponse.status}: ${errorText.slice(0, 200)}`
+ );
+ }
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: taskResponse.status,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ error: errorText.slice(0, 500),
+ responseBody: { taskId, stage: "poll" },
+ }).catch(() => {});
+ return { success: false, status: taskResponse.status, error: errorText };
+ }
+
+ const task = await taskResponse.json();
+ lastTask = task;
+ const status = String(task?.status || "").toUpperCase();
+
+ if (status === "SUCCEEDED") {
+ const videos = await normalizeRunwayVideoResult(task, body);
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 200,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ responseBody: { videos_count: videos.length, taskId, mode: "async" },
+ }).catch(() => {});
+ return {
+ success: true,
+ data: { created: Math.floor(Date.now() / 1000), data: videos },
+ };
+ }
+
+ if (RUNWAY_TERMINAL_FAILURE_STATUSES.has(status)) {
+ const errorText =
+ extractRunwayFailureMessage(task) || `Runway task failed with status ${status}`;
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 502,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ error: errorText.slice(0, 500),
+ responseBody: { taskId, status },
+ }).catch(() => {});
+ return { success: false, status: 502, error: errorText };
+ }
+
+ await sleep(pollIntervalMs);
+ }
+
+ const timeoutError = `Runway task timeout after ${timeoutMs}ms (taskId=${taskId}, status=${String(
+ lastTask?.status || "unknown"
+ )})`;
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 504,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ error: timeoutError,
+ responseBody: { taskId, status: lastTask?.status ?? null },
+ }).catch(() => {});
+ return { success: false, status: 504, error: timeoutError };
+ } catch (err) {
+ if (log) log.error("VIDEO", `${provider} runway error: ${err.message}`);
+ saveCallLog({
+ method: "POST",
+ path: "/v1/videos/generations",
+ status: 502,
+ model: `${provider}/${model}`,
+ provider,
+ duration: Date.now() - startTime,
+ error: err.message,
+ }).catch(() => {});
+ return { success: false, status: 502, error: `Video provider error: ${err.message}` };
+ }
+ }
+
+ const RUNWAY_TERMINAL_FAILURE_STATUSES = new Set([
+ "FAILED",
+ "CANCELED",
+ "CANCELLED",
+ "ABORTED",
+ "DELETED",
+ ]);
+
+ function resolveRunwayPromptImage(body) {
+ const directCandidates = [
+ body.promptImage,
+ body.prompt_image,
+ body.image,
+ body.image_url,
+ body.imageUrl,
+ body.provider_options?.promptImage,
+ body.provider_options?.prompt_image,
+ ];
+
+ for (const candidate of directCandidates) {
+ if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
+ if (candidate && typeof candidate === "object") return candidate;
+ if (Array.isArray(candidate) && candidate.length > 0) return candidate;
+ }
+
+ const arrayCandidates = [
+ body.imageUrls,
+ body.image_urls,
+ body.provider_options?.imageUrls,
+ body.provider_options?.image_urls,
+ ];
+ for (const candidate of arrayCandidates) {
+ if (Array.isArray(candidate) && candidate.length > 0) return candidate;
+ }
+
+ return null;
+ }
+
+ function resolveRunwayRatio(body) {
+ const aspectRatio = typeof body.aspect_ratio === "string" ? body.aspect_ratio : body.aspectRatio;
+ if (aspectRatio === "1280:720" || aspectRatio === "720:1280") return aspectRatio;
+ if (aspectRatio === "16:9") return "1280:720";
+ if (aspectRatio === "9:16") return "720:1280";
+
+ const size = typeof body.size === "string" ? body.size : "";
+ const [widthRaw, heightRaw] = size.split("x");
+ const width = Number(widthRaw);
+ const height = Number(heightRaw);
+ if (Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0) {
+ return width >= height ? "1280:720" : "720:1280";
+ }
+
+ return "1280:720";
+ }
+
+ function resolveRunwayDuration(body) {
+ if (Number.isFinite(body.duration)) {
+ return clampRunwayDuration(body.duration);
+ }
+
+ if (Number.isFinite(body.frames) && Number.isFinite(body.fps) && Number(body.fps) > 0) {
+ return clampRunwayDuration(Number(body.frames) / Number(body.fps));
+ }
+
+ return 5;
+ }
+
+ function clampRunwayDuration(value) {
+ const duration = Math.round(Number(value));
+ if (!Number.isFinite(duration)) return 5;
+ return Math.min(10, Math.max(2, duration));
+ }
+
+ function resolvePositiveInteger(value, fallback) {
+ const numeric = Number(value);
+ if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
+ return Math.floor(numeric);
+ }
+
+ function extractRunwayOutputUrls(task) {
+ const rawOutput = Array.isArray(task?.output)
+ ? task.output
+ : Array.isArray(task?.result)
+ ? task.result
+ : [];
+
+ return rawOutput
+ .map((entry) => {
+ if (typeof entry === "string") return entry;
+ if (!entry || typeof entry !== "object") return null;
+ return entry.url || entry.uri || entry.videoUrl || entry.video_url || null;
+ })
+ .filter((value) => typeof value === "string" && value.length > 0);
+ }
+
+ function extractRunwayFailureMessage(task) {
+ const directCandidates = [
+ task?.failure,
+ task?.failureReason,
+ task?.error,
+ task?.errorMessage,
+ task?.message,
+ ];
+ for (const candidate of directCandidates) {
+ if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
+ }
+
+ if (task?.failure && typeof task.failure === "object") {
+ const nestedCandidates = [
+ task.failure.message,
+ task.failure.reason,
+ task.failure.error,
+ task.failure.code,
+ ];
+ for (const candidate of nestedCandidates) {
+ if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
+ }
+ }
+
+ return null;
+ }
+
+ async function normalizeRunwayVideoResult(task, body) {
+ const urls = extractRunwayOutputUrls(task);
+ if (urls.length === 0) {
+ throw new Error(
+ `Runway task completed without output URLs: ${JSON.stringify(task).slice(0, 400)}`
+ );
+ }
+
+ if (body.response_format === "url") {
+ return urls.map((url) => ({ url, format: "mp4" }));
+ }
+
+ const videos = [];
+ for (const url of urls) {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Runway output fetch failed (${response.status})`);
+ }
+ const arrayBuffer = await response.arrayBuffer();
+ videos.push({
+ b64_json: Buffer.from(arrayBuffer).toString("base64"),
+ format: "mp4",
+ });
+ }
+
+ return videos;
+ }
+
+ function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+ }
diff --cc src/lib/providers/validation.ts
index 3cf56f0a6c,8ea188b5f7..a3de7bccd3
--- a/src/lib/providers/validation.ts
+++ b/src/lib/providers/validation.ts
@@@ -533,55 -755,73 +755,122 @@@ async function validateInworldProvider(
}
}
+async function validateKieProvider({ apiKey, providerSpecificData = {} }: any) {
+ try {
+ // Use credit check endpoint as requested by user based on Kie.ai docs.
+ const response = await validationRead("https://api.kie.ai/api/v1/chat/credit", {
+ method: "GET",
+ headers: applyCustomUserAgent(
+ {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ providerSpecificData
+ ),
+ });
+
+ if (response.ok) {
+ return { valid: true, error: null };
+ }
+
+ if (response.status === 401 || response.status === 403) {
+ return { valid: false, error: "Invalid Kie.ai API key" };
+ }
+
- // Fallback: if credits endpoint is 404/not supported, try minimal chat probe
++ // Fallback: if credits endpoint is 404/not supported, try minimal chat probe.
+ const chatRes = await validationWrite("https://api.kie.ai/api/v1/chat/completions", {
+ method: "POST",
+ headers: buildBearerHeaders(apiKey, providerSpecificData),
+ body: JSON.stringify({
+ model: providerSpecificData.validationModelId || "gpt-4o-mini",
+ messages: [{ role: "user", content: "test" }],
+ max_tokens: 1,
+ }),
+ });
+
+ if (
+ chatRes.ok ||
+ (chatRes.status >= 400 &&
+ chatRes.status < 500 &&
+ chatRes.status !== 401 &&
+ chatRes.status !== 403)
+ ) {
+ return { valid: true, error: null };
+ }
+
+ return { valid: false, error: `Validation failed: ${chatRes.status}` };
+ } catch (error: unknown) {
+ return toValidationErrorResult(error);
+ }
+}
+
+ function getAwsProviderString(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
+ }
+
+ function getAwsPollyRegion(providerSpecificData: any = {}) {
+ return (
+ getAwsProviderString(providerSpecificData.region) ||
+ getAwsProviderString(providerSpecificData.awsRegion) ||
+ process.env.AWS_REGION ||
+ process.env.AWS_DEFAULT_REGION ||
+ "us-east-1"
+ );
+ }
+
+ function getAwsPollyBaseUrl(providerSpecificData: any = {}, region: string) {
+ return (
+ getAwsProviderString(providerSpecificData.baseUrl) || `https://polly.${region}.amazonaws.com`
+ ).replace(/\/+$/, "");
+ }
+
+ async function validateAwsPollyProvider({ apiKey, providerSpecificData = {} }: any) {
+ const accessKeyId =
+ getAwsProviderString(providerSpecificData.accessKeyId) ||
+ getAwsProviderString(providerSpecificData.awsAccessKeyId);
+ const secretAccessKey = getAwsProviderString(apiKey);
+
+ if (!accessKeyId) {
+ return { valid: false, error: "Missing AWS accessKeyId" };
+ }
+ if (!secretAccessKey) {
+ return { valid: false, error: "Missing AWS Secret Access Key" };
+ }
+
+ const region = getAwsPollyRegion(providerSpecificData);
+ const baseUrl = getAwsPollyBaseUrl(providerSpecificData, region).replace(/\/v1\/voices$/i, "");
+ const url = `${baseUrl}/v1/voices?Engine=standard`;
+
+ try {
+ const signedHeaders = signAwsRequest({
+ method: "GET",
+ url,
+ region,
+ service: "polly",
+ credentials: {
+ accessKeyId,
+ secretAccessKey,
+ sessionToken:
+ getAwsProviderString(providerSpecificData.sessionToken) ||
+ getAwsProviderString(providerSpecificData.awsSessionToken),
+ },
+ });
+
+ const response = await validationRead(url, {
+ method: "GET",
+ headers: applyCustomUserAgent(signedHeaders, providerSpecificData),
+ });
+
+ if (response.ok) return { valid: true, error: null };
+ if (response.status === 401 || response.status === 403) {
+ return { valid: false, error: "Invalid API key" };
+ }
+ return { valid: false, error: `Validation failed: ${response.status}` };
+ } catch (error: any) {
+ return toValidationErrorResult(error);
+ }
+ }
+
async function validateBailianCodingPlanProvider({ apiKey, providerSpecificData = {} }: any) {
try {
const rawBaseUrl =
@@@ -1332,9 -2908,19 +2957,20 @@@ export async function validateProviderA
deepgram: validateDeepgramProvider,
assemblyai: validateAssemblyAIProvider,
nanobanana: validateNanoBananaProvider,
+ "fal-ai": ({ apiKey, providerSpecificData }: any) =>
+ validateImageProviderApiKey({ provider: "fal-ai", apiKey, providerSpecificData }),
+ "stability-ai": ({ apiKey, providerSpecificData }: any) =>
+ validateImageProviderApiKey({ provider: "stability-ai", apiKey, providerSpecificData }),
+ "black-forest-labs": ({ apiKey, providerSpecificData }: any) =>
+ validateImageProviderApiKey({ provider: "black-forest-labs", apiKey, providerSpecificData }),
+ recraft: ({ apiKey, providerSpecificData }: any) =>
+ validateImageProviderApiKey({ provider: "recraft", apiKey, providerSpecificData }),
+ topaz: ({ apiKey, providerSpecificData }: any) =>
+ validateImageProviderApiKey({ provider: "topaz", apiKey, providerSpecificData }),
elevenlabs: validateElevenLabsProvider,
inworld: validateInworldProvider,
+ kie: validateKieProvider,
+ "aws-polly": validateAwsPollyProvider,
"bailian-coding-plan": validateBailianCodingPlanProvider,
heroku: validateHerokuProvider,
databricks: validateDatabricksProvider,