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(video): support Runway task-based generation and provider cataloging
diegosouzapwc656123db9d1
diff --git a/open-sse/config/runway.ts b/open-sse/config/runway.tsnew file mode 100644index 0000000000..a76719d757--- /dev/null+++ b/open-sse/config/runway.ts@@ -0,0 +1,40 @@+export const RUNWAYML_DEFAULT_BASE_URL = "https://api.dev.runwayml.com/v1";+export const RUNWAYML_API_VERSION = "2024-11-06";++export const RUNWAYML_SUPPORTED_VIDEO_MODELS = [+ { id: "gen4.5", name: "Gen-4.5" },+ { id: "gen4_turbo", name: "Gen-4 Turbo" },+ { id: "veo3.1", name: "Veo 3.1" },+ { id: "veo3.1_fast", name: "Veo 3.1 Fast" },+ { id: "veo3", name: "Veo 3" },+ { id: "gen3a_turbo", name: "Gen-3 Alpha Turbo" },+];++export const RUNWAYML_IMAGE_REQUIRED_MODELS = new Set(["gen4_turbo", "gen3a_turbo"]);++export function normalizeRunwayBaseUrl(baseUrl?: string | null) {+ const normalized = String(baseUrl || "")+ .trim()+ .replace(/\/$/, "");+ if (!normalized) return RUNWAYML_DEFAULT_BASE_URL;++ const stripped = normalized+ .replace(/\/organization$/i, "")+ .replace(/\/tasks\/[^/]+$/i, "")+ .replace(/\/(?:image_to_video|text_to_video)$/i, "");++ return stripped.endsWith("/v1") ? stripped : `${stripped}/v1`;+}++export function buildRunwayApiUrl(path: string, baseUrl?: string | null) {+ const normalizedBaseUrl = normalizeRunwayBaseUrl(baseUrl);+ return `${normalizedBaseUrl}${path.startsWith("/") ? path : `/${path}`}`;+}++export function buildRunwayHeaders(apiKey: string) {+ return {+ Authorization: `Bearer ${apiKey}`,+ "Content-Type": "application/json",+ "X-Runway-Version": RUNWAYML_API_VERSION,+ };+}diff --git a/open-sse/config/videoRegistry.ts b/open-sse/config/videoRegistry.tsindex 809cc7f591..18f8d092ce 100644--- a/open-sse/config/videoRegistry.ts+++ b/open-sse/config/videoRegistry.ts@@ -2,10 +2,11 @@* Video Generation Provider Registry** Defines providers that support the /v1/videos/generations endpoint.- * Currently supports local providers (ComfyUI, SD WebUI with AnimateDiff).+ * Supports local providers plus hosted task-based APIs such as Runway.*/import { parseModelFromRegistry, getAllModelsFromRegistry } from "./registryUtils.ts";+import { RUNWAYML_SUPPORTED_VIDEO_MODELS } from "./runway.ts";interface VideoModel {id: string;@@ -42,6 +43,15 @@ export const VIDEO_PROVIDERS: Record<string, VideoProvider> = {format: "sdwebui-video",models: [{ id: "animatediff-webui", name: "AnimateDiff (WebUI)" }],},++ runwayml: {+ id: "runwayml",+ baseUrl: "https://api.dev.runwayml.com/v1",+ authType: "bearer",+ authHeader: "Authorization",+ format: "runwayml",+ models: RUNWAYML_SUPPORTED_VIDEO_MODELS,+ },};/**diff --git a/open-sse/handlers/videoGeneration.ts b/open-sse/handlers/videoGeneration.tsindex 44b01f9fce..4fc37b43b9 100644--- a/open-sse/handlers/videoGeneration.ts+++ b/open-sse/handlers/videoGeneration.ts@@ -16,6 +16,11 @@*/import { getVideoProvider, parseVideoModel } from "../config/videoRegistry.ts";+import {+ buildRunwayApiUrl,+ buildRunwayHeaders,+ RUNWAYML_IMAGE_REQUIRED_MODELS,+} from "../config/runway.ts";import {submitComfyWorkflow,pollComfyResult,@@ -55,6 +60,10 @@ export async function handleVideoGeneration({ body, credentials, log }) {return handleSDWebUIVideoGeneration({ model, provider, providerConfig, body, log });}+ if (providerConfig.format === "runwayml") {+ return handleRunwayVideoGeneration({ model, provider, providerConfig, body, credentials, log });+ }+return {success: false,status: 400,@@ -262,3 +271,356 @@ async function handleSDWebUIVideoGeneration({ model, provider, providerConfig, breturn { success: false, status: 502, error: `Video provider error: ${err.message}` };}}++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 --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.tsindex 744f3c4317..c80d5f4d89 100755--- a/src/app/api/providers/[id]/models/route.ts+++ b/src/app/api/providers/[id]/models/route.ts@@ -23,6 +23,7 @@ import { getAntigravityHeaders } from "@omniroute/open-sse/services/antigravityHimport { 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";+import { getVideoProvider } from "@omniroute/open-sse/config/videoRegistry.ts";import { resolveAntigravityVersion } from "@omniroute/open-sse/services/antigravityVersion.ts";import {AZURE_AI_DEFAULT_BASE_URL,@@ -337,6 +338,14 @@ export function getStaticModelsForProvider(}));}+ const videoProvider = getVideoProvider(provider);+ if (videoProvider) {+ return videoProvider.models.map((model) => ({+ id: model.id,+ name: model.name || model.id,+ }));+ }+return undefined;}diff --git a/src/lib/providers/validation.ts b/src/lib/providers/validation.tsindex 2e6fac32ea..50967e1528 100644--- a/src/lib/providers/validation.ts+++ b/src/lib/providers/validation.ts@@ -61,6 +61,11 @@ import {buildWatsonxChatUrl,buildWatsonxModelsUrl,} from "@omniroute/open-sse/config/watsonx.ts";+import {+ buildRunwayApiUrl,+ buildRunwayHeaders,+ normalizeRunwayBaseUrl,+} from "@omniroute/open-sse/config/runway.ts";const OPENAI_LIKE_FORMATS = new Set(["openai", "openai-responses"]);const GEMINI_LIKE_FORMATS = new Set(["gemini", "gemini-cli"]);@@ -1538,6 +1543,42 @@ async function validateNlpCloudProvider({ apiKey, providerSpecificData = {} }: areturn { valid: false, error: "Connection failed while testing NLP Cloud" };}+async function validateRunwayProvider({ apiKey, providerSpecificData = {} }: any) {+ const baseUrl = normalizeRunwayBaseUrl(providerSpecificData.baseUrl);++ try {+ const response = await validationRead(buildRunwayApiUrl("/organization", baseUrl), {+ method: "GET",+ headers: buildRunwayHeaders(apiKey),+ });++ if (response.ok) {+ return { valid: true, error: null, method: "runway_organization" };+ }++ if (response.status === 401 || response.status === 403) {+ return { valid: false, error: "Invalid API key" };+ }++ if (response.status === 429) {+ return {+ valid: true,+ error: null,+ method: "runway_organization",+ warning: "Rate limited, but credentials are valid",+ };+ }++ if (response.status >= 500) {+ return { valid: false, error: `Provider unavailable (${response.status})` };+ }+ } catch (error: any) {+ return toValidationErrorResult(error);+ }++ return { valid: false, error: "Connection failed while testing Runway" };+}+async function validateOpenAICompatibleProvider({ apiKey, providerSpecificData = {} }: any) {const baseUrl = normalizeBaseUrl(providerSpecificData.baseUrl);if (!baseUrl) {@@ -2473,6 +2514,7 @@ export async function validateProviderApiKey({ provider, apiKey, providerSpecificlarifai: validateClarifaiProvider,reka: validateRekaProvider,nlpcloud: validateNlpCloudProvider,+ runwayml: validateRunwayProvider,snowflake: validateSnowflakeProvider,gigachat: validateGigachatProvider,"grok-web": validateGrokWebProvider,diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.tsindex a90977ec47..6a66e4bac2 100644--- a/src/shared/constants/providers.ts+++ b/src/shared/constants/providers.ts@@ -379,6 +379,19 @@ export const APIKEY_PROVIDERS = {hasFree: true,freeNote: "Trial credits for new accounts",},+ runwayml: {+ id: "runwayml",+ alias: "runway",+ name: "Runway",+ icon: "movie",+ color: "#111827",+ textIcon: "RW",+ website: "https://docs.dev.runwayml.com",+ authHint:+ "Use your Runway API key in Authorization: Bearer <key>. OmniRoute targets the current Runway API at https://api.dev.runwayml.com/v1 and sends the required X-Runway-Version header automatically.",+ apiHint:+ "Runway video generation is task-based. OmniRoute submits text-to-video or image-to-video jobs, polls /v1/tasks/{id}, and normalizes the finished video outputs back into the OpenAI-like /v1/videos/generations response.",+ },anthropic: {id: "anthropic",alias: "anthropic",diff --git a/tests/unit/provider-models-route.test.ts b/tests/unit/provider-models-route.test.tsindex 90541bb807..ae0a99af59 100644--- a/tests/unit/provider-models-route.test.ts+++ b/tests/unit/provider-models-route.test.ts@@ -413,6 +413,22 @@ test("provider models route returns the local catalog for NLP Cloud", async () =assert.ok(body.models.some((model) => model.id === "dolphin-mixtral-8x7b"));});+test("provider models route returns the local catalog for Runway video models", async () => {+ const connection = await seedConnection("runwayml", {+ apiKey: "runway-key",+ });++ const response = await callRoute(connection.id);+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.provider, "runwayml");+ assert.equal(body.source, "local_catalog");+ assert.ok(body.models.some((model) => model.id === "gen4.5"));+ assert.ok(body.models.some((model) => model.id === "veo3.1"));+ assert.ok(body.models.some((model) => model.id === "gen3a_turbo"));+});+test("provider models route returns the local catalog for amazon-q via the kiro-compatible registry", async () => {const connection = await seedConnection("amazon-q", {authType: "oauth",diff --git a/tests/unit/provider-validation-specialty.test.ts b/tests/unit/provider-validation-specialty.test.tsindex c50f59896c..d8c4d8bfc2 100644--- a/tests/unit/provider-validation-specialty.test.ts+++ b/tests/unit/provider-validation-specialty.test.ts@@ -1324,3 +1324,48 @@ test("specialty validator rejects invalid NLP Cloud credentials", async () => {assert.equal(nlpCloud.error, "Invalid API key");});++test("specialty validator accepts Runway credentials on the organization endpoint", async () => {+ globalThis.fetch = async (url, init = {}) => {+ const target = String(url);++ if (target === "https://api.dev.runwayml.com/v1/organization") {+ const headers = init.headers as Record<string, string>;+ assert.equal(headers.Authorization, "Bearer runway-key");+ assert.equal(headers["X-Runway-Version"], "2024-11-06");+ return new Response(JSON.stringify({ id: "org_demo" }), { status: 200 });+ }++ throw new Error(`unexpected fetch: ${target}`);+ };++ const runway = await validateProviderApiKey({+ provider: "runwayml",+ apiKey: "runway-key",+ });++ assert.equal(runway.valid, true);+ assert.equal(runway.method, "runway_organization");+});++test("specialty validator rejects invalid Runway credentials", async () => {+ globalThis.fetch = async (url, init = {}) => {+ const target = String(url);++ if (target === "https://api.dev.runwayml.com/v1/organization") {+ const headers = init.headers as Record<string, string>;+ assert.equal(headers.Authorization, "Bearer runway-bad");+ assert.equal(headers["X-Runway-Version"], "2024-11-06");+ return new Response(JSON.stringify({ error: "unauthorized" }), { status: 401 });+ }++ throw new Error(`unexpected fetch: ${target}`);+ };++ const runway = await validateProviderApiKey({+ provider: "runwayml",+ apiKey: "runway-bad",+ });++ assert.equal(runway.error, "Invalid API key");+});diff --git a/tests/unit/providers-page-utils.test.ts b/tests/unit/providers-page-utils.test.tsindex 9f65833d20..0dd7ec0d62 100644--- a/tests/unit/providers-page-utils.test.ts+++ b/tests/unit/providers-page-utils.test.ts@@ -235,6 +235,7 @@ test("static catalog entries resolve local, search, audio, web-cookie and upstreconst modalProvider = providerPageUtils.resolveDashboardProviderInfo("modal");const rekaProvider = providerPageUtils.resolveDashboardProviderInfo("reka");const nlpCloudProvider = providerPageUtils.resolveDashboardProviderInfo("nlpcloud");+ const runwayProvider = providerPageUtils.resolveDashboardProviderInfo("runwayml");const embeddingProvider = providerPageUtils.resolveDashboardProviderInfo("voyage-ai");const rerankProvider = providerPageUtils.resolveDashboardProviderInfo("jina-ai");const perplexityWebProvider = providerPageUtils.resolveDashboardProviderInfo("perplexity-web");@@ -284,6 +285,8 @@ test("static catalog entries resolve local, search, audio, web-cookie and upstreassert.equal(rekaProvider?.name, providers.APIKEY_PROVIDERS.reka.name);assert.equal(nlpCloudProvider?.category, "apikey");assert.equal(nlpCloudProvider?.name, providers.APIKEY_PROVIDERS.nlpcloud.name);+ assert.equal(runwayProvider?.category, "apikey");+ assert.equal(runwayProvider?.name, providers.APIKEY_PROVIDERS.runwayml.name);assert.equal(embeddingProvider?.category, "apikey");assert.equal(embeddingProvider?.name, providers.APIKEY_PROVIDERS["voyage-ai"].name);@@ -328,6 +331,7 @@ test("managed provider connection ids include supported static categories and exassert.equal(providerCatalog.isManagedProviderConnectionId("modal"), true);assert.equal(providerCatalog.isManagedProviderConnectionId("reka"), true);assert.equal(providerCatalog.isManagedProviderConnectionId("nlpcloud"), true);+ assert.equal(providerCatalog.isManagedProviderConnectionId("runwayml"), true);assert.equal(providerCatalog.isManagedProviderConnectionId("voyage-ai"), true);assert.equal(providerCatalog.isManagedProviderConnectionId("jina-ai"), true);assert.equal(providerCatalog.isManagedProviderConnectionId("sdwebui"), true);@@ -376,6 +380,7 @@ test("grok-web taxonomy stays web-cookie only and does not leak into api-key entassert.equal("modal" in providers.APIKEY_PROVIDERS, true);assert.equal("reka" in providers.APIKEY_PROVIDERS, true);assert.equal("nlpcloud" in providers.APIKEY_PROVIDERS, true);+ assert.equal("runwayml" in providers.APIKEY_PROVIDERS, true);assert.equal("voyage-ai" in providers.APIKEY_PROVIDERS, true);assert.equal("jina-ai" in providers.APIKEY_PROVIDERS, true);@@ -473,6 +478,10 @@ test("grok-web taxonomy stays web-cookie only and does not leak into api-key entapiKeyEntries.some((entry) => entry.providerId === "nlpcloud"),true);+ assert.equal(+ apiKeyEntries.some((entry) => entry.providerId === "runwayml"),+ true+ );assert.equal(apiKeyEntries.some((entry) => entry.providerId === "voyage-ai"),truediff --git a/tests/unit/providers-route-managed-catalog.test.ts b/tests/unit/providers-route-managed-catalog.test.tsindex 112d8f9c87..98e38c83d0 100644--- a/tests/unit/providers-route-managed-catalog.test.ts+++ b/tests/unit/providers-route-managed-catalog.test.ts@@ -164,6 +164,14 @@ test("providers route accepts managed local, audio, web-cookie and search providname: "NLP Cloud Primary",},},+ {+ provider: "runwayml",+ body: {+ provider: "runwayml",+ apiKey: "runway-key",+ name: "Runway Primary",+ },+ },{provider: "voyage-ai",body: {diff --git a/tests/unit/registry-utils.test.ts b/tests/unit/registry-utils.test.tsindex e5e9a64c86..ffcb7b0fb2 100644--- a/tests/unit/registry-utils.test.ts+++ b/tests/unit/registry-utils.test.ts@@ -201,6 +201,7 @@ test("getAllVideoModels: returns video models with provider prefix", async () =>const models = getAllVideoModels();assert.ok(models.length >= 3, `Expected at least 3 video models, got ${models.length}`);assert.ok(models.some((m) => m.id === "comfyui/animatediff"));+ assert.ok(models.some((m) => m.id === "runwayml/gen4.5"));});test("getAllMusicModels: returns music models with provider prefix", async () => {diff --git a/tests/unit/video-generation-handler.test.ts b/tests/unit/video-generation-handler.test.tsindex 2c85ed396f..c1a37274fe 100644--- a/tests/unit/video-generation-handler.test.ts+++ b/tests/unit/video-generation-handler.test.ts@@ -376,3 +376,152 @@ test("handleVideoGeneration returns provider errors for ComfyUI failures and logglobalThis.setTimeout = originalSetTimeout;}});++test("handleVideoGeneration submits, polls and downloads Runway text-to-video tasks", async () => {+ const originalFetch = globalThis.fetch;+ const originalSetTimeout = globalThis.setTimeout;+ const seen = [];+ let pollCount = 0;++ globalThis.setTimeout = immediateTimeout;+ globalThis.fetch = async (url, init = {}) => {+ const target = String(url);+ seen.push({ url: target, init });++ if (target === "https://api.dev.runwayml.com/v1/text_to_video") {+ const headers = init.headers as Record<string, string>;+ const body = JSON.parse(String(init.body || "{}"));+ assert.equal(headers.Authorization, "Bearer runway-key");+ assert.equal(headers["X-Runway-Version"], "2024-11-06");+ assert.equal(body.model, "gen4.5");+ assert.equal(body.promptText, "cinematic sunrise");+ assert.equal(body.ratio, "1280:720");+ assert.equal(body.duration, 6);+ return new Response(JSON.stringify({ id: "task-runway-1" }), { status: 200 });+ }++ if (target === "https://api.dev.runwayml.com/v1/tasks/task-runway-1") {+ pollCount += 1;+ if (pollCount === 1) {+ return new Response(JSON.stringify({ id: "task-runway-1", status: "RUNNING" }), {+ status: 200,+ });+ }+ return new Response(+ JSON.stringify({+ id: "task-runway-1",+ status: "SUCCEEDED",+ output: ["https://cdn.runway.dev/output-1.mp4"],+ }),+ { status: 200 }+ );+ }++ if (target === "https://cdn.runway.dev/output-1.mp4") {+ return new Response(new Uint8Array([9, 8, 7, 6]), { status: 200 });+ }++ throw new Error(`Unexpected URL: ${target}`);+ };++ try {+ const result = await handleVideoGeneration({+ body: {+ model: "runwayml/gen4.5",+ prompt: "cinematic sunrise",+ size: "1280x720",+ duration: 6,+ },+ credentials: { apiKey: "runway-key" },+ log: null,+ });++ assert.equal(result.success, true);+ assert.deepEqual(result.data.data, [{ b64_json: "CQgHBg==", format: "mp4" }]);+ assert.deepEqual(+ seen.map((entry) => entry.url),+ [+ "https://api.dev.runwayml.com/v1/text_to_video",+ "https://api.dev.runwayml.com/v1/tasks/task-runway-1",+ "https://api.dev.runwayml.com/v1/tasks/task-runway-1",+ "https://cdn.runway.dev/output-1.mp4",+ ]+ );+ } finally {+ globalThis.fetch = originalFetch;+ globalThis.setTimeout = originalSetTimeout;+ }+});++test("handleVideoGeneration routes Runway image-to-video requests and can return output URLs", async () => {+ const originalFetch = globalThis.fetch;+ const originalSetTimeout = globalThis.setTimeout;+ let submittedBody;++ globalThis.setTimeout = immediateTimeout;+ globalThis.fetch = async (url, init = {}) => {+ const target = String(url);++ if (target === "https://api.dev.runwayml.com/v1/image_to_video") {+ submittedBody = JSON.parse(String(init.body || "{}"));+ return new Response(JSON.stringify({ id: "task-runway-2" }), { status: 200 });+ }++ if (target === "https://api.dev.runwayml.com/v1/tasks/task-runway-2") {+ return new Response(+ JSON.stringify({+ id: "task-runway-2",+ status: "SUCCEEDED",+ output: ["https://cdn.runway.dev/output-2.mp4"],+ }),+ { status: 200 }+ );+ }++ throw new Error(`Unexpected URL: ${target}`);+ };++ try {+ const result = await handleVideoGeneration({+ body: {+ model: "runwayml/gen4_turbo",+ prompt: "make the frame move",+ prompt_image: "https://assets.example.com/frame.png",+ response_format: "url",+ size: "720x1280",+ },+ credentials: { apiKey: "runway-key" },+ log: null,+ });++ assert.deepEqual(submittedBody, {+ model: "gen4_turbo",+ promptText: "make the frame move",+ ratio: "720:1280",+ duration: 5,+ promptImage: "https://assets.example.com/frame.png",+ });+ assert.equal(result.success, true);+ assert.deepEqual(result.data.data, [+ { url: "https://cdn.runway.dev/output-2.mp4", format: "mp4" },+ ]);+ } finally {+ globalThis.fetch = originalFetch;+ globalThis.setTimeout = originalSetTimeout;+ }+});++test("handleVideoGeneration rejects Runway models that require promptImage", async () => {+ const result = await handleVideoGeneration({+ body: {+ model: "runwayml/gen4_turbo",+ prompt: "animate this",+ },+ credentials: { apiKey: "runway-key" },+ log: null,+ });++ assert.equal(result.success, false);+ assert.equal(result.status, 400);+ assert.match(result.error, /requires promptImage/i);+});