Files
adolf/extensions/openrouter/video-model-catalog.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

301 lines
9.7 KiB
TypeScript

// Openrouter plugin module implements video model catalog behavior.
import type {
UnifiedModelCatalogEntry,
UnifiedModelCatalogProviderContext,
} from "openclaw/plugin-sdk/plugin-entry";
import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
import { getCachedLiveCatalogValue } from "openclaw/plugin-sdk/provider-catalog-shared";
import {
assertOkOrThrowHttpError,
readProviderJsonResponse,
resolveProviderHttpRequestConfig,
} from "openclaw/plugin-sdk/provider-http";
import {
normalizeOptionalString,
normalizeTrimmedStringList,
} from "openclaw/plugin-sdk/string-coerce-runtime";
import type {
VideoGenerationModelCapabilitiesContext,
VideoGenerationProviderCapabilities,
VideoGenerationResolution,
} from "openclaw/plugin-sdk/video-generation";
import { OPENROUTER_BASE_URL } from "./provider-catalog.js";
import { fetchOpenRouterVideoGet, type OpenRouterVideoDispatcherPolicy } from "./video-http.js";
const DEFAULT_HTTP_TIMEOUT_MS = 60_000;
type OpenRouterVideoModel = {
allowed_passthrough_parameters?: unknown;
canonical_slug?: unknown;
created?: unknown;
description?: unknown;
generate_audio?: unknown;
id?: unknown;
name?: unknown;
pricing_skus?: unknown;
seed?: unknown;
supported_aspect_ratios?: unknown;
supported_durations?: unknown;
supported_frame_images?: unknown;
supported_resolutions?: unknown;
supported_sizes?: unknown;
};
type OpenRouterVideoModelsResponse = {
data?: OpenRouterVideoModel[];
};
export type OpenRouterVideoModelCatalogCapabilities = VideoGenerationProviderCapabilities & {
allowedPassthroughParameters?: readonly string[];
canonicalSlug?: string;
created?: number;
description?: string;
pricingSkus?: Readonly<Record<string, string>>;
};
function normalizeStringArray(value: unknown): string[] {
return normalizeTrimmedStringList(value);
}
function normalizeNumberArray(value: unknown): number[] {
return Array.isArray(value)
? value.filter((entry): entry is number => typeof entry === "number" && Number.isFinite(entry))
: [];
}
function normalizeResolutionArray(value: unknown): VideoGenerationResolution[] {
return normalizeStringArray(value).map(
(entry) => entry.toUpperCase() as VideoGenerationResolution,
);
}
function normalizeFrameImageRoles(value: unknown): Array<"first_frame" | "last_frame"> {
const seen = new Set<"first_frame" | "last_frame">();
for (const entry of normalizeStringArray(value)) {
if (entry === "first_frame" || entry === "last_frame") {
seen.add(entry);
}
}
return [...seen];
}
function normalizeStringRecord(value: unknown): Record<string, string> | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return undefined;
}
const record: Record<string, string> = {};
for (const [key, raw] of Object.entries(value)) {
const normalized = normalizeOptionalString(raw);
if (normalized) {
record[key] = normalized;
}
}
return Object.keys(record).length > 0 ? record : undefined;
}
function buildOpenRouterVideoModeCapabilities(params: {
durations: number[];
aspectRatios: string[];
resolutions: VideoGenerationResolution[];
sizes: string[];
supportsAudio?: boolean;
}): NonNullable<VideoGenerationProviderCapabilities["generate"]> {
return {
maxVideos: 1,
...(params.durations.length > 0 ? { supportedDurationSeconds: params.durations } : {}),
...(params.aspectRatios.length > 0
? {
supportsAspectRatio: true,
aspectRatios: params.aspectRatios,
}
: {}),
...(params.resolutions.length > 0
? {
supportsResolution: true,
resolutions: params.resolutions,
}
: {}),
...(params.sizes.length > 0
? {
supportsSize: true,
sizes: params.sizes,
}
: {}),
...(params.supportsAudio === undefined ? {} : { supportsAudio: params.supportsAudio }),
};
}
function buildOpenRouterVideoModelCapabilities(
model: OpenRouterVideoModel,
): OpenRouterVideoModelCatalogCapabilities {
const aspectRatios = normalizeStringArray(model.supported_aspect_ratios);
const durations = normalizeNumberArray(model.supported_durations);
const frameImages = normalizeFrameImageRoles(model.supported_frame_images);
const resolutions = normalizeResolutionArray(model.supported_resolutions);
const sizes = normalizeStringArray(model.supported_sizes);
const allowedPassthroughParameters = normalizeStringArray(model.allowed_passthrough_parameters);
const supportsAudio =
typeof model.generate_audio === "boolean" ? model.generate_audio : undefined;
const modeCapabilities = buildOpenRouterVideoModeCapabilities({
durations,
aspectRatios,
resolutions,
sizes,
supportsAudio,
});
const base: VideoGenerationProviderCapabilities = {
providerOptions: {
callback_url: "string",
seed: "number",
},
generate: modeCapabilities,
imageToVideo: {
enabled: frameImages.length > 0,
...modeCapabilities,
...(frameImages.length > 0 ? { maxInputImages: frameImages.length } : {}),
},
videoToVideo: {
enabled: false,
},
};
const capabilities: OpenRouterVideoModelCatalogCapabilities = {
...base,
};
const canonicalSlug = normalizeOptionalString(model.canonical_slug);
if (canonicalSlug) {
capabilities.canonicalSlug = canonicalSlug;
}
const description = normalizeOptionalString(model.description);
if (description) {
capabilities.description = description;
}
if (typeof model.created === "number" && Number.isFinite(model.created)) {
capabilities.created = model.created;
}
const pricingSkus = normalizeStringRecord(model.pricing_skus);
if (pricingSkus) {
capabilities.pricingSkus = pricingSkus;
}
if (allowedPassthroughParameters.length > 0) {
capabilities.allowedPassthroughParameters = allowedPassthroughParameters;
}
return capabilities;
}
function projectOpenRouterVideoModelsToCatalogEntries(
payload: OpenRouterVideoModelsResponse,
): Array<UnifiedModelCatalogEntry<OpenRouterVideoModelCatalogCapabilities>> {
const entries: Array<UnifiedModelCatalogEntry<OpenRouterVideoModelCatalogCapabilities>> = [];
const seen = new Set<string>();
for (const model of payload.data ?? []) {
const id = normalizeOptionalString(model.id);
if (!id || seen.has(id)) {
continue;
}
seen.add(id);
const entry: UnifiedModelCatalogEntry<OpenRouterVideoModelCatalogCapabilities> = {
kind: "video_generation",
provider: "openrouter",
model: id,
source: "live",
capabilities: buildOpenRouterVideoModelCapabilities(model),
};
const name = normalizeOptionalString(model.name);
if (name) {
entry.label = name;
}
entries.push(entry);
}
return entries;
}
async function fetchOpenRouterVideoModels(params: {
baseUrl: string;
apiKey: string;
timeoutMs: number;
allowPrivateNetwork: boolean;
dispatcherPolicy: OpenRouterVideoDispatcherPolicy;
}): Promise<OpenRouterVideoModelsResponse> {
return await getCachedLiveCatalogValue({
keyParts: ["openrouter", "video-models", params.baseUrl, params.apiKey],
load: async () => {
const headers = new Headers({
Authorization: `Bearer ${params.apiKey}`,
"HTTP-Referer": "https://openclaw.ai",
"X-OpenRouter-Title": "OpenClaw",
});
const { response, release } = await fetchOpenRouterVideoGet({
url: "videos/models",
baseUrl: params.baseUrl,
headers,
timeoutMs: params.timeoutMs,
allowPrivateNetwork: params.allowPrivateNetwork,
dispatcherPolicy: params.dispatcherPolicy,
auditContext: "openrouter-video-models",
});
try {
await assertOkOrThrowHttpError(response, "OpenRouter video models request failed");
return await readProviderJsonResponse<OpenRouterVideoModelsResponse>(
response,
"OpenRouter video models request failed",
);
} finally {
await release();
}
},
});
}
export async function listOpenRouterVideoModelCatalog(
ctx: UnifiedModelCatalogProviderContext,
): Promise<Array<UnifiedModelCatalogEntry<OpenRouterVideoModelCatalogCapabilities>> | null> {
const { discoveryApiKey: apiKey } = ctx.resolveProviderApiKey("openrouter");
if (!apiKey) {
return null;
}
const { baseUrl, allowPrivateNetwork, dispatcherPolicy } = resolveProviderHttpRequestConfig({
provider: "openrouter",
capability: "video",
baseUrl: ctx.config.models?.providers?.openrouter?.baseUrl,
defaultBaseUrl: OPENROUTER_BASE_URL,
});
const payload = await fetchOpenRouterVideoModels({
baseUrl,
apiKey,
timeoutMs: ctx.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
allowPrivateNetwork,
dispatcherPolicy,
});
return projectOpenRouterVideoModelsToCatalogEntries(payload);
}
export async function resolveOpenRouterVideoModelCapabilities(
ctx: VideoGenerationModelCapabilitiesContext,
): Promise<VideoGenerationProviderCapabilities | undefined> {
const auth = await resolveApiKeyForProvider({
provider: "openrouter",
cfg: ctx.cfg,
agentDir: ctx.agentDir,
store: ctx.authStore,
});
if (!auth.apiKey) {
return undefined;
}
const { baseUrl, allowPrivateNetwork, dispatcherPolicy } = resolveProviderHttpRequestConfig({
provider: "openrouter",
capability: "video",
baseUrl: ctx.cfg?.models?.providers?.openrouter?.baseUrl,
defaultBaseUrl: OPENROUTER_BASE_URL,
});
const payload = await fetchOpenRouterVideoModels({
baseUrl,
apiKey: auth.apiKey,
timeoutMs: ctx.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
allowPrivateNetwork,
dispatcherPolicy,
});
return projectOpenRouterVideoModelsToCatalogEntries(payload).find(
(entry) => entry.model === ctx.model,
)?.capabilities;
}