feat(qwen): add qwen provider and video generation
parent
759373e887
commit
e3ac0f43df
@ -1,4 +1,4 @@
|
||||
ad87e3ff267b151ae163402f3cb52503e10641e332bcfbb6a574bbd7087a2484 config-baseline.json
|
||||
4c880eb1ce03486f47aa21f49317ad15fc8d92bb720d70205743b72e45cf5fa3 config-baseline.json
|
||||
03ff4a3e314f17dd8851aed3653269294bc62412bee05a6804dce840bd3d7551 config-baseline.core.json
|
||||
73b57f395a2ad983f1660112d0b2b998342f1ddbe3089b440d7f73d0665de739 config-baseline.channel.json
|
||||
9d5cb864e70768b66c1ecd881a9a584b7696ef2e5b32df686cfdc3fa21ddabbe config-baseline.plugin.json
|
||||
17fd37605bf6cb087932ec2ebcfa9dd22e669fa6b8b93081ab2deac9d24821c5 config-baseline.plugin.json
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { registerAmazonBedrockPlugin } from "./register.runtime.js";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "amazon-bedrock",
|
||||
name: "Amazon Bedrock Provider",
|
||||
description: "Bundled Amazon Bedrock provider policy plugin",
|
||||
async register(api) {
|
||||
const { registerAmazonBedrockPlugin } = await import("./register.runtime.js");
|
||||
await registerAmazonBedrockPlugin(api);
|
||||
register(api) {
|
||||
registerAmazonBedrockPlugin(api);
|
||||
},
|
||||
});
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { registerAnthropicPlugin } from "./register.runtime.js";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "anthropic",
|
||||
name: "Anthropic Provider",
|
||||
description: "Bundled Anthropic provider plugin",
|
||||
async register(api) {
|
||||
const { registerAnthropicPlugin } = await import("./register.runtime.js");
|
||||
await registerAnthropicPlugin(api);
|
||||
register(api) {
|
||||
registerAnthropicPlugin(api);
|
||||
},
|
||||
});
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { buildMicrosoftSpeechProvider } from "./speech-provider.js";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "microsoft",
|
||||
name: "Microsoft Speech",
|
||||
description: "Bundled Microsoft speech provider",
|
||||
async register(api) {
|
||||
const { buildMicrosoftSpeechProvider } = await import("./speech-provider.js");
|
||||
register(api) {
|
||||
api.registerSpeechProvider(buildMicrosoftSpeechProvider());
|
||||
},
|
||||
});
|
||||
|
||||
@ -1,118 +0,0 @@
|
||||
import { defineSingleProviderPluginEntry } from "openclaw/plugin-sdk/provider-entry";
|
||||
import { applyModelStudioNativeStreamingUsageCompat } from "./api.js";
|
||||
import {
|
||||
applyModelStudioConfig,
|
||||
applyModelStudioConfigCn,
|
||||
applyModelStudioStandardConfig,
|
||||
applyModelStudioStandardConfigCn,
|
||||
MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
} from "./onboard.js";
|
||||
import { buildModelStudioProvider } from "./provider-catalog.js";
|
||||
|
||||
const PROVIDER_ID = "modelstudio";
|
||||
|
||||
export default defineSingleProviderPluginEntry({
|
||||
id: PROVIDER_ID,
|
||||
name: "Model Studio Provider",
|
||||
description: "Bundled Model Studio provider plugin",
|
||||
provider: {
|
||||
label: "Model Studio",
|
||||
docsPath: "/providers/models",
|
||||
auth: [
|
||||
{
|
||||
methodId: "standard-api-key-cn",
|
||||
label: "Standard API Key for China (pay-as-you-go)",
|
||||
hint: "Endpoint: dashscope.aliyuncs.com",
|
||||
optionKey: "modelstudioStandardApiKeyCn",
|
||||
flagName: "--modelstudio-standard-api-key-cn",
|
||||
envVar: "MODELSTUDIO_API_KEY",
|
||||
promptMessage: "Enter Alibaba Cloud Model Studio API key (China)",
|
||||
defaultModel: MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyModelStudioStandardConfigCn(cfg),
|
||||
noteMessage: [
|
||||
"Get your API key at: https://bailian.console.aliyun.com/",
|
||||
"Endpoint: dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"Models: qwen3.6-plus, qwen3.5-plus, qwen3-coder-plus, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Alibaba Cloud Model Studio Standard (China)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: dashscope.aliyuncs.com",
|
||||
groupLabel: "Qwen (Alibaba Cloud Model Studio)",
|
||||
groupHint: "Standard / Coding Plan (CN / Global)",
|
||||
},
|
||||
},
|
||||
{
|
||||
methodId: "standard-api-key",
|
||||
label: "Standard API Key for Global/Intl (pay-as-you-go)",
|
||||
hint: "Endpoint: dashscope-intl.aliyuncs.com",
|
||||
optionKey: "modelstudioStandardApiKey",
|
||||
flagName: "--modelstudio-standard-api-key",
|
||||
envVar: "MODELSTUDIO_API_KEY",
|
||||
promptMessage: "Enter Alibaba Cloud Model Studio API key (Global/Intl)",
|
||||
defaultModel: MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyModelStudioStandardConfig(cfg),
|
||||
noteMessage: [
|
||||
"Get your API key at: https://modelstudio.console.alibabacloud.com/",
|
||||
"Endpoint: dashscope-intl.aliyuncs.com/compatible-mode/v1",
|
||||
"Models: qwen3.6-plus, qwen3.5-plus, qwen3-coder-plus, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Alibaba Cloud Model Studio Standard (Global/Intl)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: dashscope-intl.aliyuncs.com",
|
||||
groupLabel: "Qwen (Alibaba Cloud Model Studio)",
|
||||
groupHint: "Standard / Coding Plan (CN / Global)",
|
||||
},
|
||||
},
|
||||
{
|
||||
methodId: "api-key-cn",
|
||||
label: "Coding Plan API Key for China (subscription)",
|
||||
hint: "Endpoint: coding.dashscope.aliyuncs.com",
|
||||
optionKey: "modelstudioApiKeyCn",
|
||||
flagName: "--modelstudio-api-key-cn",
|
||||
envVar: "MODELSTUDIO_API_KEY",
|
||||
promptMessage: "Enter Alibaba Cloud Model Studio Coding Plan API key (China)",
|
||||
defaultModel: MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyModelStudioConfigCn(cfg),
|
||||
noteMessage: [
|
||||
"Get your API key at: https://bailian.console.aliyun.com/",
|
||||
"Endpoint: coding.dashscope.aliyuncs.com",
|
||||
"Models: qwen3.6-plus, glm-5, kimi-k2.5, MiniMax-M2.5, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Alibaba Cloud Model Studio Coding Plan (China)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: coding.dashscope.aliyuncs.com",
|
||||
groupLabel: "Qwen (Alibaba Cloud Model Studio)",
|
||||
groupHint: "Standard / Coding Plan (CN / Global)",
|
||||
},
|
||||
},
|
||||
{
|
||||
methodId: "api-key",
|
||||
label: "Coding Plan API Key for Global/Intl (subscription)",
|
||||
hint: "Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
optionKey: "modelstudioApiKey",
|
||||
flagName: "--modelstudio-api-key",
|
||||
envVar: "MODELSTUDIO_API_KEY",
|
||||
promptMessage: "Enter Alibaba Cloud Model Studio Coding Plan API key (Global/Intl)",
|
||||
defaultModel: MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyModelStudioConfig(cfg),
|
||||
noteMessage: [
|
||||
"Get your API key at: https://bailian.console.aliyun.com/",
|
||||
"Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
"Models: qwen3.6-plus, glm-5, kimi-k2.5, MiniMax-M2.5, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Alibaba Cloud Model Studio Coding Plan (Global/Intl)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
groupLabel: "Qwen (Alibaba Cloud Model Studio)",
|
||||
groupHint: "Standard / Coding Plan (CN / Global)",
|
||||
},
|
||||
},
|
||||
],
|
||||
catalog: {
|
||||
buildProvider: buildModelStudioProvider,
|
||||
allowExplicitBaseUrl: true,
|
||||
},
|
||||
applyNativeStreamingUsageCompat: ({ providerConfig }) =>
|
||||
applyModelStudioNativeStreamingUsageCompat(providerConfig),
|
||||
},
|
||||
});
|
||||
@ -1,69 +0,0 @@
|
||||
import {
|
||||
createModelCatalogPresetAppliers,
|
||||
type OpenClawConfig,
|
||||
} from "openclaw/plugin-sdk/provider-onboard";
|
||||
import {
|
||||
MODELSTUDIO_CN_BASE_URL,
|
||||
MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
MODELSTUDIO_GLOBAL_BASE_URL,
|
||||
MODELSTUDIO_STANDARD_CN_BASE_URL,
|
||||
MODELSTUDIO_STANDARD_GLOBAL_BASE_URL,
|
||||
} from "./models.js";
|
||||
import { buildModelStudioProvider } from "./provider-catalog.js";
|
||||
|
||||
export {
|
||||
MODELSTUDIO_CN_BASE_URL,
|
||||
MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
MODELSTUDIO_GLOBAL_BASE_URL,
|
||||
MODELSTUDIO_STANDARD_CN_BASE_URL,
|
||||
MODELSTUDIO_STANDARD_GLOBAL_BASE_URL,
|
||||
};
|
||||
|
||||
const modelStudioPresetAppliers = createModelCatalogPresetAppliers<[string]>({
|
||||
primaryModelRef: MODELSTUDIO_DEFAULT_MODEL_REF,
|
||||
resolveParams: (_cfg: OpenClawConfig, baseUrl: string) => {
|
||||
const provider = buildModelStudioProvider();
|
||||
return {
|
||||
providerId: "modelstudio",
|
||||
api: provider.api ?? "openai-completions",
|
||||
baseUrl,
|
||||
catalogModels: provider.models ?? [],
|
||||
aliases: [
|
||||
...(provider.models ?? []).map((model) => `modelstudio/${model.id}`),
|
||||
{ modelRef: MODELSTUDIO_DEFAULT_MODEL_REF, alias: "Qwen" },
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export function applyModelStudioProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyProviderConfig(cfg, MODELSTUDIO_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioProviderConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyProviderConfig(cfg, MODELSTUDIO_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyConfig(cfg, MODELSTUDIO_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyConfig(cfg, MODELSTUDIO_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioStandardProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyProviderConfig(cfg, MODELSTUDIO_STANDARD_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioStandardProviderConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyProviderConfig(cfg, MODELSTUDIO_STANDARD_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioStandardConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyConfig(cfg, MODELSTUDIO_STANDARD_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyModelStudioStandardConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return modelStudioPresetAppliers.applyConfig(cfg, MODELSTUDIO_STANDARD_CN_BASE_URL);
|
||||
}
|
||||
@ -1,71 +0,0 @@
|
||||
{
|
||||
"id": "modelstudio",
|
||||
"enabledByDefault": true,
|
||||
"providers": ["modelstudio"],
|
||||
"providerAuthEnvVars": {
|
||||
"modelstudio": ["MODELSTUDIO_API_KEY"]
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "modelstudio",
|
||||
"method": "standard-api-key-cn",
|
||||
"choiceId": "modelstudio-standard-api-key-cn",
|
||||
"choiceLabel": "Standard API Key for China (pay-as-you-go)",
|
||||
"choiceHint": "Endpoint: dashscope.aliyuncs.com",
|
||||
"groupId": "modelstudio",
|
||||
"groupLabel": "Qwen (Alibaba Cloud Model Studio)",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global)",
|
||||
"optionKey": "modelstudioStandardApiKeyCn",
|
||||
"cliFlag": "--modelstudio-standard-api-key-cn",
|
||||
"cliOption": "--modelstudio-standard-api-key-cn <key>",
|
||||
"cliDescription": "Alibaba Cloud Model Studio Standard API key (China)"
|
||||
},
|
||||
{
|
||||
"provider": "modelstudio",
|
||||
"method": "standard-api-key",
|
||||
"choiceId": "modelstudio-standard-api-key",
|
||||
"choiceLabel": "Standard API Key for Global/Intl (pay-as-you-go)",
|
||||
"choiceHint": "Endpoint: dashscope-intl.aliyuncs.com",
|
||||
"groupId": "modelstudio",
|
||||
"groupLabel": "Qwen (Alibaba Cloud Model Studio)",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global)",
|
||||
"optionKey": "modelstudioStandardApiKey",
|
||||
"cliFlag": "--modelstudio-standard-api-key",
|
||||
"cliOption": "--modelstudio-standard-api-key <key>",
|
||||
"cliDescription": "Alibaba Cloud Model Studio Standard API key (Global/Intl)"
|
||||
},
|
||||
{
|
||||
"provider": "modelstudio",
|
||||
"method": "api-key-cn",
|
||||
"choiceId": "modelstudio-api-key-cn",
|
||||
"choiceLabel": "Coding Plan API Key for China (subscription)",
|
||||
"choiceHint": "Endpoint: coding.dashscope.aliyuncs.com",
|
||||
"groupId": "modelstudio",
|
||||
"groupLabel": "Qwen (Alibaba Cloud Model Studio)",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global)",
|
||||
"optionKey": "modelstudioApiKeyCn",
|
||||
"cliFlag": "--modelstudio-api-key-cn",
|
||||
"cliOption": "--modelstudio-api-key-cn <key>",
|
||||
"cliDescription": "Alibaba Cloud Model Studio Coding Plan API key (China)"
|
||||
},
|
||||
{
|
||||
"provider": "modelstudio",
|
||||
"method": "api-key",
|
||||
"choiceId": "modelstudio-api-key",
|
||||
"choiceLabel": "Coding Plan API Key for Global/Intl (subscription)",
|
||||
"choiceHint": "Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
"groupId": "modelstudio",
|
||||
"groupLabel": "Qwen (Alibaba Cloud Model Studio)",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global)",
|
||||
"optionKey": "modelstudioApiKey",
|
||||
"cliFlag": "--modelstudio-api-key",
|
||||
"cliOption": "--modelstudio-api-key <key>",
|
||||
"cliDescription": "Alibaba Cloud Model Studio Coding Plan API key (Global/Intl)"
|
||||
}
|
||||
],
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyModelStudioNativeStreamingUsageCompat,
|
||||
buildModelStudioProvider,
|
||||
MODELSTUDIO_BASE_URL,
|
||||
MODELSTUDIO_DEFAULT_MODEL_ID,
|
||||
} from "./api.js";
|
||||
|
||||
describe("modelstudio provider catalog", () => {
|
||||
it("builds the bundled Model Studio provider defaults", () => {
|
||||
const provider = buildModelStudioProvider();
|
||||
|
||||
expect(provider.baseUrl).toBe(MODELSTUDIO_BASE_URL);
|
||||
expect(provider.api).toBe("openai-completions");
|
||||
expect(provider.models?.length).toBeGreaterThan(0);
|
||||
expect(
|
||||
provider.models?.find((model) => model.id === MODELSTUDIO_DEFAULT_MODEL_ID),
|
||||
).toBeTruthy();
|
||||
expect(provider.models?.find((model) => model.id === "qwen3.6-plus")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("opts native Model Studio baseUrls into streaming usage only inside the extension", () => {
|
||||
const nativeProvider = applyModelStudioNativeStreamingUsageCompat(buildModelStudioProvider());
|
||||
expect(
|
||||
nativeProvider.models?.every((model) => model.compat?.supportsUsageInStreaming === true),
|
||||
).toBe(true);
|
||||
|
||||
const customProvider = applyModelStudioNativeStreamingUsageCompat({
|
||||
...buildModelStudioProvider(),
|
||||
baseUrl: "https://proxy.example.com/v1",
|
||||
});
|
||||
expect(
|
||||
customProvider.models?.some((model) => model.compat?.supportsUsageInStreaming === true),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -1,10 +0,0 @@
|
||||
import type { ModelProviderConfig } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
import { MODELSTUDIO_BASE_URL, MODELSTUDIO_MODEL_CATALOG } from "./models.js";
|
||||
|
||||
export function buildModelStudioProvider(): ModelProviderConfig {
|
||||
return {
|
||||
baseUrl: MODELSTUDIO_BASE_URL,
|
||||
api: "openai-completions",
|
||||
models: MODELSTUDIO_MODEL_CATALOG.map((model) => ({ ...model })),
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,129 @@
|
||||
import { defineSingleProviderPluginEntry } from "openclaw/plugin-sdk/provider-entry";
|
||||
import { applyQwenNativeStreamingUsageCompat } from "./api.js";
|
||||
import { buildQwenMediaUnderstandingProvider } from "./media-understanding-provider.js";
|
||||
import {
|
||||
applyQwenConfig,
|
||||
applyQwenConfigCn,
|
||||
applyQwenStandardConfig,
|
||||
applyQwenStandardConfigCn,
|
||||
QWEN_DEFAULT_MODEL_REF,
|
||||
} from "./onboard.js";
|
||||
import { buildQwenProvider } from "./provider-catalog.js";
|
||||
import { buildQwenVideoGenerationProvider } from "./video-generation-provider.js";
|
||||
|
||||
const PROVIDER_ID = "qwen";
|
||||
|
||||
export default defineSingleProviderPluginEntry({
|
||||
id: PROVIDER_ID,
|
||||
name: "Qwen Provider",
|
||||
description: "Bundled Qwen Cloud provider plugin",
|
||||
provider: {
|
||||
label: "Qwen Cloud",
|
||||
docsPath: "/providers/qwen",
|
||||
aliases: ["modelstudio", "qwencloud"],
|
||||
auth: [
|
||||
{
|
||||
methodId: "standard-api-key-cn",
|
||||
label: "Standard API Key for China (pay-as-you-go)",
|
||||
hint: "Endpoint: dashscope.aliyuncs.com",
|
||||
optionKey: "modelstudioStandardApiKeyCn",
|
||||
flagName: "--modelstudio-standard-api-key-cn",
|
||||
envVar: "QWEN_API_KEY",
|
||||
promptMessage: "Enter Qwen Cloud API key (China standard endpoint)",
|
||||
defaultModel: QWEN_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyQwenStandardConfigCn(cfg),
|
||||
noteMessage: [
|
||||
"Manage API keys: https://home.qwencloud.com/api-keys",
|
||||
"Docs: https://docs.qwencloud.com/",
|
||||
"Endpoint: dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
"Models: qwen3.6-plus, qwen3.5-plus, qwen3-coder-plus, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Qwen Cloud Standard (China)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: dashscope.aliyuncs.com",
|
||||
groupLabel: "Qwen Cloud",
|
||||
groupHint: "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
},
|
||||
},
|
||||
{
|
||||
methodId: "standard-api-key",
|
||||
label: "Standard API Key for Global/Intl (pay-as-you-go)",
|
||||
hint: "Endpoint: dashscope-intl.aliyuncs.com",
|
||||
optionKey: "modelstudioStandardApiKey",
|
||||
flagName: "--modelstudio-standard-api-key",
|
||||
envVar: "QWEN_API_KEY",
|
||||
promptMessage: "Enter Qwen Cloud API key (Global/Intl standard endpoint)",
|
||||
defaultModel: QWEN_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyQwenStandardConfig(cfg),
|
||||
noteMessage: [
|
||||
"Manage API keys: https://home.qwencloud.com/api-keys",
|
||||
"Docs: https://docs.qwencloud.com/",
|
||||
"Endpoint: dashscope-intl.aliyuncs.com/compatible-mode/v1",
|
||||
"Models: qwen3.6-plus, qwen3.5-plus, qwen3-coder-plus, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Qwen Cloud Standard (Global/Intl)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: dashscope-intl.aliyuncs.com",
|
||||
groupLabel: "Qwen Cloud",
|
||||
groupHint: "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
},
|
||||
},
|
||||
{
|
||||
methodId: "api-key-cn",
|
||||
label: "Coding Plan API Key for China (subscription)",
|
||||
hint: "Endpoint: coding.dashscope.aliyuncs.com",
|
||||
optionKey: "modelstudioApiKeyCn",
|
||||
flagName: "--modelstudio-api-key-cn",
|
||||
envVar: "QWEN_API_KEY",
|
||||
promptMessage: "Enter Qwen Cloud Coding Plan API key (China)",
|
||||
defaultModel: QWEN_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyQwenConfigCn(cfg),
|
||||
noteMessage: [
|
||||
"Manage API keys: https://home.qwencloud.com/api-keys",
|
||||
"Docs: https://docs.qwencloud.com/",
|
||||
"Endpoint: coding.dashscope.aliyuncs.com",
|
||||
"Models: qwen3.6-plus, glm-5, kimi-k2.5, MiniMax-M2.5, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Qwen Cloud Coding Plan (China)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: coding.dashscope.aliyuncs.com",
|
||||
groupLabel: "Qwen Cloud",
|
||||
groupHint: "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
},
|
||||
},
|
||||
{
|
||||
methodId: "api-key",
|
||||
label: "Coding Plan API Key for Global/Intl (subscription)",
|
||||
hint: "Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
optionKey: "modelstudioApiKey",
|
||||
flagName: "--modelstudio-api-key",
|
||||
envVar: "QWEN_API_KEY",
|
||||
promptMessage: "Enter Qwen Cloud Coding Plan API key (Global/Intl)",
|
||||
defaultModel: QWEN_DEFAULT_MODEL_REF,
|
||||
applyConfig: (cfg) => applyQwenConfig(cfg),
|
||||
noteMessage: [
|
||||
"Manage API keys: https://home.qwencloud.com/api-keys",
|
||||
"Docs: https://docs.qwencloud.com/",
|
||||
"Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
"Models: qwen3.6-plus, glm-5, kimi-k2.5, MiniMax-M2.5, etc.",
|
||||
].join("\n"),
|
||||
noteTitle: "Qwen Cloud Coding Plan (Global/Intl)",
|
||||
wizard: {
|
||||
choiceHint: "Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
groupLabel: "Qwen Cloud",
|
||||
groupHint: "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
},
|
||||
},
|
||||
],
|
||||
catalog: {
|
||||
buildProvider: buildQwenProvider,
|
||||
allowExplicitBaseUrl: true,
|
||||
},
|
||||
applyNativeStreamingUsageCompat: ({ providerConfig }) =>
|
||||
applyQwenNativeStreamingUsageCompat(providerConfig),
|
||||
},
|
||||
register(api) {
|
||||
api.registerMediaUnderstandingProvider(buildQwenMediaUnderstandingProvider());
|
||||
api.registerVideoGenerationProvider(buildQwenVideoGenerationProvider());
|
||||
},
|
||||
});
|
||||
@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createRequestCaptureJsonFetch } from "../../test/helpers/plugins/media-understanding.js";
|
||||
import { describeQwenVideo } from "./media-understanding-provider.js";
|
||||
|
||||
describe("describeQwenVideo", () => {
|
||||
it("builds the expected OpenAI-compatible video payload", async () => {
|
||||
const { fetchFn, getRequest } = createRequestCaptureJsonFetch({
|
||||
choices: [
|
||||
{
|
||||
message: {
|
||||
content: [{ text: " first " }, { text: "second" }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await describeQwenVideo({
|
||||
buffer: Buffer.from("video-bytes"),
|
||||
fileName: "clip.mp4",
|
||||
mime: "video/mp4",
|
||||
apiKey: "test-key",
|
||||
timeoutMs: 1500,
|
||||
baseUrl: "https://example.com/v1",
|
||||
model: "qwen-vl-max",
|
||||
prompt: "summarize the clip",
|
||||
headers: { "X-Other": "1" },
|
||||
fetchFn,
|
||||
});
|
||||
const { url, init } = getRequest();
|
||||
|
||||
expect(result.model).toBe("qwen-vl-max");
|
||||
expect(result.text).toBe("first\nsecond");
|
||||
expect(url).toBe("https://example.com/v1/chat/completions");
|
||||
expect(init?.method).toBe("POST");
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal);
|
||||
|
||||
const headers = new Headers(init?.headers);
|
||||
expect(headers.get("authorization")).toBe("Bearer test-key");
|
||||
expect(headers.get("content-type")).toBe("application/json");
|
||||
expect(headers.get("x-other")).toBe("1");
|
||||
|
||||
const bodyText =
|
||||
typeof init?.body === "string"
|
||||
? init.body
|
||||
: Buffer.isBuffer(init?.body)
|
||||
? init.body.toString("utf8")
|
||||
: "";
|
||||
const body = JSON.parse(bodyText);
|
||||
expect(body.model).toBe("qwen-vl-max");
|
||||
expect(body.messages?.[0]?.content?.[0]?.text).toBe("summarize the clip");
|
||||
expect(body.messages?.[0]?.content?.[1]?.type).toBe("video_url");
|
||||
expect(body.messages?.[0]?.content?.[1]?.video_url?.url).toBe(
|
||||
`data:video/mp4;base64,${Buffer.from("video-bytes").toString("base64")}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,156 @@
|
||||
import {
|
||||
describeImageWithModel,
|
||||
describeImagesWithModel,
|
||||
type MediaUnderstandingProvider,
|
||||
type VideoDescriptionRequest,
|
||||
type VideoDescriptionResult,
|
||||
} from "openclaw/plugin-sdk/media-understanding";
|
||||
import {
|
||||
assertOkOrThrowHttpError,
|
||||
postJsonRequest,
|
||||
resolveProviderHttpRequestConfig,
|
||||
} from "openclaw/plugin-sdk/provider-http";
|
||||
import { QWEN_STANDARD_CN_BASE_URL, QWEN_STANDARD_GLOBAL_BASE_URL } from "./models.js";
|
||||
|
||||
const DEFAULT_QWEN_VIDEO_MODEL = "qwen-vl-max-latest";
|
||||
const DEFAULT_QWEN_VIDEO_PROMPT = "Describe the video in detail.";
|
||||
|
||||
type QwenVideoPayload = {
|
||||
choices?: Array<{
|
||||
message?: {
|
||||
content?: string | Array<{ text?: string }>;
|
||||
reasoning_content?: string;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
|
||||
function resolveQwenStandardBaseUrl(
|
||||
cfg: { models?: { providers?: Record<string, { baseUrl?: string } | undefined> } } | undefined,
|
||||
providerId: string,
|
||||
): string {
|
||||
const direct = cfg?.models?.providers?.[providerId]?.baseUrl?.trim();
|
||||
if (!direct) {
|
||||
return QWEN_STANDARD_GLOBAL_BASE_URL;
|
||||
}
|
||||
try {
|
||||
const url = new URL(direct);
|
||||
if (url.hostname === "coding-intl.dashscope.aliyuncs.com") {
|
||||
return QWEN_STANDARD_GLOBAL_BASE_URL;
|
||||
}
|
||||
if (url.hostname === "coding.dashscope.aliyuncs.com") {
|
||||
return QWEN_STANDARD_CN_BASE_URL;
|
||||
}
|
||||
return `${url.origin}${url.pathname}`.replace(/\/+$/u, "");
|
||||
} catch {
|
||||
return QWEN_STANDARD_GLOBAL_BASE_URL;
|
||||
}
|
||||
}
|
||||
|
||||
function coerceQwenText(payload: QwenVideoPayload): string | null {
|
||||
const message = payload.choices?.[0]?.message;
|
||||
if (!message) {
|
||||
return null;
|
||||
}
|
||||
if (typeof message.content === "string" && message.content.trim()) {
|
||||
return message.content.trim();
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
const text = message.content
|
||||
.map((part) => (typeof part.text === "string" ? part.text.trim() : ""))
|
||||
.filter(Boolean)
|
||||
.join("\n")
|
||||
.trim();
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
if (typeof message.reasoning_content === "string" && message.reasoning_content.trim()) {
|
||||
return message.reasoning_content.trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function describeQwenVideo(
|
||||
params: VideoDescriptionRequest,
|
||||
): Promise<VideoDescriptionResult> {
|
||||
const fetchFn = params.fetchFn ?? fetch;
|
||||
const model = params.model?.trim() || DEFAULT_QWEN_VIDEO_MODEL;
|
||||
const mime = params.mime?.trim() || "video/mp4";
|
||||
const prompt = params.prompt?.trim() || DEFAULT_QWEN_VIDEO_PROMPT;
|
||||
const { baseUrl, allowPrivateNetwork, headers, dispatcherPolicy } =
|
||||
resolveProviderHttpRequestConfig({
|
||||
baseUrl: params.baseUrl,
|
||||
defaultBaseUrl: QWEN_STANDARD_GLOBAL_BASE_URL,
|
||||
headers: params.headers,
|
||||
request: params.request,
|
||||
defaultHeaders: {
|
||||
"content-type": "application/json",
|
||||
authorization: `Bearer ${params.apiKey}`,
|
||||
},
|
||||
provider: "qwen",
|
||||
api: "openai-completions",
|
||||
capability: "video",
|
||||
transport: "media-understanding",
|
||||
});
|
||||
|
||||
const { response: res, release } = await postJsonRequest({
|
||||
url: `${baseUrl}/chat/completions`,
|
||||
headers,
|
||||
body: {
|
||||
model,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: prompt },
|
||||
{
|
||||
type: "video_url",
|
||||
video_url: {
|
||||
url: `data:${mime};base64,${params.buffer.toString("base64")}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
timeoutMs: params.timeoutMs,
|
||||
fetchFn,
|
||||
allowPrivateNetwork,
|
||||
dispatcherPolicy,
|
||||
});
|
||||
|
||||
try {
|
||||
await assertOkOrThrowHttpError(res, "Qwen video description failed");
|
||||
const payload = (await res.json()) as QwenVideoPayload;
|
||||
const text = coerceQwenText(payload);
|
||||
if (!text) {
|
||||
throw new Error("Qwen video description response missing content");
|
||||
}
|
||||
return { text, model };
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}
|
||||
|
||||
export function buildQwenMediaUnderstandingProvider(): MediaUnderstandingProvider {
|
||||
return {
|
||||
id: "qwen",
|
||||
capabilities: ["image", "video"],
|
||||
defaultModels: {
|
||||
image: "qwen-vl-max-latest",
|
||||
video: DEFAULT_QWEN_VIDEO_MODEL,
|
||||
},
|
||||
autoPriority: {
|
||||
video: 15,
|
||||
},
|
||||
describeImage: describeImageWithModel,
|
||||
describeImages: describeImagesWithModel,
|
||||
describeVideo: describeQwenVideo,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveQwenMediaUnderstandingBaseUrl(
|
||||
cfg: { models?: { providers?: Record<string, { baseUrl?: string } | undefined> } } | undefined,
|
||||
): string {
|
||||
return resolveQwenStandardBaseUrl(cfg, "qwen");
|
||||
}
|
||||
@ -1,4 +1,13 @@
|
||||
export {
|
||||
buildQwenDefaultModelDefinition,
|
||||
buildQwenModelDefinition,
|
||||
QWEN_CN_BASE_URL,
|
||||
QWEN_DEFAULT_COST,
|
||||
QWEN_DEFAULT_MODEL_ID,
|
||||
QWEN_DEFAULT_MODEL_REF,
|
||||
QWEN_GLOBAL_BASE_URL,
|
||||
QWEN_STANDARD_CN_BASE_URL,
|
||||
QWEN_STANDARD_GLOBAL_BASE_URL,
|
||||
buildModelStudioDefaultModelDefinition,
|
||||
buildModelStudioModelDefinition,
|
||||
MODELSTUDIO_CN_BASE_URL,
|
||||
@ -0,0 +1,81 @@
|
||||
import {
|
||||
createModelCatalogPresetAppliers,
|
||||
type OpenClawConfig,
|
||||
} from "openclaw/plugin-sdk/provider-onboard";
|
||||
import {
|
||||
QWEN_CN_BASE_URL,
|
||||
QWEN_DEFAULT_MODEL_REF,
|
||||
QWEN_GLOBAL_BASE_URL,
|
||||
QWEN_STANDARD_CN_BASE_URL,
|
||||
QWEN_STANDARD_GLOBAL_BASE_URL,
|
||||
} from "./models.js";
|
||||
import { buildQwenProvider } from "./provider-catalog.js";
|
||||
|
||||
export {
|
||||
QWEN_CN_BASE_URL,
|
||||
QWEN_DEFAULT_MODEL_REF,
|
||||
QWEN_GLOBAL_BASE_URL,
|
||||
QWEN_STANDARD_CN_BASE_URL,
|
||||
QWEN_STANDARD_GLOBAL_BASE_URL,
|
||||
};
|
||||
|
||||
const qwenPresetAppliers = createModelCatalogPresetAppliers<[string]>({
|
||||
primaryModelRef: QWEN_DEFAULT_MODEL_REF,
|
||||
resolveParams: (_cfg: OpenClawConfig, baseUrl: string) => {
|
||||
const provider = buildQwenProvider();
|
||||
return {
|
||||
providerId: "qwen",
|
||||
api: provider.api ?? "openai-completions",
|
||||
baseUrl,
|
||||
catalogModels: provider.models ?? [],
|
||||
aliases: [
|
||||
...(provider.models ?? []).flatMap((model) => [
|
||||
`qwen/${model.id}`,
|
||||
`modelstudio/${model.id}`,
|
||||
]),
|
||||
{ modelRef: QWEN_DEFAULT_MODEL_REF, alias: "Qwen" },
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export function applyQwenProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyProviderConfig(cfg, QWEN_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenProviderConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyProviderConfig(cfg, QWEN_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyConfig(cfg, QWEN_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyConfig(cfg, QWEN_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenStandardProviderConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyProviderConfig(cfg, QWEN_STANDARD_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenStandardProviderConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyProviderConfig(cfg, QWEN_STANDARD_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenStandardConfig(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyConfig(cfg, QWEN_STANDARD_GLOBAL_BASE_URL);
|
||||
}
|
||||
|
||||
export function applyQwenStandardConfigCn(cfg: OpenClawConfig): OpenClawConfig {
|
||||
return qwenPresetAppliers.applyConfig(cfg, QWEN_STANDARD_CN_BASE_URL);
|
||||
}
|
||||
|
||||
export const applyModelStudioProviderConfig = applyQwenProviderConfig;
|
||||
export const applyModelStudioProviderConfigCn = applyQwenProviderConfigCn;
|
||||
export const applyModelStudioConfig = applyQwenConfig;
|
||||
export const applyModelStudioConfigCn = applyQwenConfigCn;
|
||||
export const applyModelStudioStandardProviderConfig = applyQwenStandardProviderConfig;
|
||||
export const applyModelStudioStandardProviderConfigCn = applyQwenStandardProviderConfigCn;
|
||||
export const applyModelStudioStandardConfig = applyQwenStandardConfig;
|
||||
export const applyModelStudioStandardConfigCn = applyQwenStandardConfigCn;
|
||||
@ -0,0 +1,79 @@
|
||||
{
|
||||
"id": "qwen",
|
||||
"enabledByDefault": true,
|
||||
"providers": ["qwen"],
|
||||
"contracts": {
|
||||
"mediaUnderstandingProviders": ["qwen"],
|
||||
"videoGenerationProviders": ["qwen"]
|
||||
},
|
||||
"providerAuthEnvVars": {
|
||||
"qwen": ["QWEN_API_KEY", "MODELSTUDIO_API_KEY", "DASHSCOPE_API_KEY"]
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "qwen",
|
||||
"method": "standard-api-key-cn",
|
||||
"choiceId": "qwen-standard-api-key-cn",
|
||||
"deprecatedChoiceIds": ["modelstudio-standard-api-key-cn"],
|
||||
"choiceLabel": "Standard API Key for China (pay-as-you-go)",
|
||||
"choiceHint": "Endpoint: dashscope.aliyuncs.com",
|
||||
"groupId": "qwen",
|
||||
"groupLabel": "Qwen Cloud",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
"optionKey": "modelstudioStandardApiKeyCn",
|
||||
"cliFlag": "--modelstudio-standard-api-key-cn",
|
||||
"cliOption": "--modelstudio-standard-api-key-cn <key>",
|
||||
"cliDescription": "Qwen Cloud standard API key (China)"
|
||||
},
|
||||
{
|
||||
"provider": "qwen",
|
||||
"method": "standard-api-key",
|
||||
"choiceId": "qwen-standard-api-key",
|
||||
"deprecatedChoiceIds": ["modelstudio-standard-api-key"],
|
||||
"choiceLabel": "Standard API Key for Global/Intl (pay-as-you-go)",
|
||||
"choiceHint": "Endpoint: dashscope-intl.aliyuncs.com",
|
||||
"groupId": "qwen",
|
||||
"groupLabel": "Qwen Cloud",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
"optionKey": "modelstudioStandardApiKey",
|
||||
"cliFlag": "--modelstudio-standard-api-key",
|
||||
"cliOption": "--modelstudio-standard-api-key <key>",
|
||||
"cliDescription": "Qwen Cloud standard API key (Global/Intl)"
|
||||
},
|
||||
{
|
||||
"provider": "qwen",
|
||||
"method": "api-key-cn",
|
||||
"choiceId": "qwen-api-key-cn",
|
||||
"deprecatedChoiceIds": ["modelstudio-api-key-cn"],
|
||||
"choiceLabel": "Coding Plan API Key for China (subscription)",
|
||||
"choiceHint": "Endpoint: coding.dashscope.aliyuncs.com",
|
||||
"groupId": "qwen",
|
||||
"groupLabel": "Qwen Cloud",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
"optionKey": "modelstudioApiKeyCn",
|
||||
"cliFlag": "--modelstudio-api-key-cn",
|
||||
"cliOption": "--modelstudio-api-key-cn <key>",
|
||||
"cliDescription": "Qwen Cloud Coding Plan API key (China)"
|
||||
},
|
||||
{
|
||||
"provider": "qwen",
|
||||
"method": "api-key",
|
||||
"choiceId": "qwen-api-key",
|
||||
"deprecatedChoiceIds": ["modelstudio-api-key"],
|
||||
"choiceLabel": "Coding Plan API Key for Global/Intl (subscription)",
|
||||
"choiceHint": "Endpoint: coding-intl.dashscope.aliyuncs.com",
|
||||
"groupId": "qwen",
|
||||
"groupLabel": "Qwen Cloud",
|
||||
"groupHint": "Standard / Coding Plan (CN / Global) + multimodal roadmap",
|
||||
"optionKey": "modelstudioApiKey",
|
||||
"cliFlag": "--modelstudio-api-key",
|
||||
"cliOption": "--modelstudio-api-key <key>",
|
||||
"cliDescription": "Qwen Cloud Coding Plan API key (Global/Intl)"
|
||||
}
|
||||
],
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@openclaw/modelstudio-provider",
|
||||
"name": "@openclaw/qwen-provider",
|
||||
"version": "2026.4.1-beta.1",
|
||||
"private": true,
|
||||
"description": "OpenClaw Model Studio provider plugin",
|
||||
"description": "OpenClaw Qwen Cloud provider plugin",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": [
|
||||
@ -0,0 +1,10 @@
|
||||
import { describePluginRegistrationContract } from "../../test/helpers/plugins/plugin-registration-contract.js";
|
||||
|
||||
describePluginRegistrationContract({
|
||||
pluginId: "qwen",
|
||||
providerIds: ["qwen"],
|
||||
mediaUnderstandingProviderIds: ["qwen"],
|
||||
videoGenerationProviderIds: ["qwen"],
|
||||
requireDescribeImages: true,
|
||||
requireGenerateVideo: true,
|
||||
});
|
||||
@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyQwenNativeStreamingUsageCompat,
|
||||
buildQwenProvider,
|
||||
QWEN_BASE_URL,
|
||||
QWEN_DEFAULT_MODEL_ID,
|
||||
} from "./api.js";
|
||||
|
||||
describe("qwen provider catalog", () => {
|
||||
it("builds the bundled Qwen provider defaults", () => {
|
||||
const provider = buildQwenProvider();
|
||||
|
||||
expect(provider.baseUrl).toBe(QWEN_BASE_URL);
|
||||
expect(provider.api).toBe("openai-completions");
|
||||
expect(provider.models?.length).toBeGreaterThan(0);
|
||||
expect(provider.models?.find((model) => model.id === QWEN_DEFAULT_MODEL_ID)).toBeTruthy();
|
||||
expect(provider.models?.find((model) => model.id === "qwen3.6-plus")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("opts native Qwen baseUrls into streaming usage only inside the extension", () => {
|
||||
const nativeProvider = applyQwenNativeStreamingUsageCompat(buildQwenProvider());
|
||||
expect(
|
||||
nativeProvider.models?.every((model) => model.compat?.supportsUsageInStreaming === true),
|
||||
).toBe(true);
|
||||
|
||||
const customProvider = applyQwenNativeStreamingUsageCompat({
|
||||
...buildQwenProvider(),
|
||||
baseUrl: "https://proxy.example.com/v1",
|
||||
});
|
||||
expect(
|
||||
customProvider.models?.some((model) => model.compat?.supportsUsageInStreaming === true),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,12 @@
|
||||
import type { ModelProviderConfig } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
import { QWEN_BASE_URL, QWEN_MODEL_CATALOG } from "./models.js";
|
||||
|
||||
export function buildQwenProvider(): ModelProviderConfig {
|
||||
return {
|
||||
baseUrl: QWEN_BASE_URL,
|
||||
api: "openai-completions",
|
||||
models: QWEN_MODEL_CATALOG.map((model) => ({ ...model })),
|
||||
};
|
||||
}
|
||||
|
||||
export const buildModelStudioProvider = buildQwenProvider;
|
||||
@ -0,0 +1,2 @@
|
||||
export { buildQwenMediaUnderstandingProvider } from "./media-understanding-provider.js";
|
||||
export { buildQwenVideoGenerationProvider } from "./video-generation-provider.js";
|
||||
@ -0,0 +1,110 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildQwenVideoGenerationProvider } from "./video-generation-provider.js";
|
||||
|
||||
const {
|
||||
resolveApiKeyForProviderMock,
|
||||
postJsonRequestMock,
|
||||
fetchWithTimeoutMock,
|
||||
assertOkOrThrowHttpErrorMock,
|
||||
resolveProviderHttpRequestConfigMock,
|
||||
} = vi.hoisted(() => ({
|
||||
resolveApiKeyForProviderMock: vi.fn(async () => ({ apiKey: "qwen-key" })),
|
||||
postJsonRequestMock: vi.fn(),
|
||||
fetchWithTimeoutMock: vi.fn(),
|
||||
assertOkOrThrowHttpErrorMock: vi.fn(async () => {}),
|
||||
resolveProviderHttpRequestConfigMock: vi.fn((params) => ({
|
||||
baseUrl: params.baseUrl ?? params.defaultBaseUrl,
|
||||
allowPrivateNetwork: false,
|
||||
headers: new Headers(params.defaultHeaders),
|
||||
dispatcherPolicy: undefined,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("openclaw/plugin-sdk/provider-auth-runtime", () => ({
|
||||
resolveApiKeyForProvider: resolveApiKeyForProviderMock,
|
||||
}));
|
||||
|
||||
vi.mock("openclaw/plugin-sdk/provider-http", () => ({
|
||||
assertOkOrThrowHttpError: assertOkOrThrowHttpErrorMock,
|
||||
fetchWithTimeout: fetchWithTimeoutMock,
|
||||
postJsonRequest: postJsonRequestMock,
|
||||
resolveProviderHttpRequestConfig: resolveProviderHttpRequestConfigMock,
|
||||
}));
|
||||
|
||||
describe("qwen video generation provider", () => {
|
||||
afterEach(() => {
|
||||
resolveApiKeyForProviderMock.mockClear();
|
||||
postJsonRequestMock.mockReset();
|
||||
fetchWithTimeoutMock.mockReset();
|
||||
assertOkOrThrowHttpErrorMock.mockClear();
|
||||
resolveProviderHttpRequestConfigMock.mockClear();
|
||||
});
|
||||
|
||||
it("submits async Wan generation, polls task status, and downloads the resulting video", async () => {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: {
|
||||
json: async () => ({
|
||||
request_id: "req-1",
|
||||
output: {
|
||||
task_id: "task-1",
|
||||
},
|
||||
}),
|
||||
},
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
fetchWithTimeoutMock
|
||||
.mockResolvedValueOnce({
|
||||
json: async () => ({
|
||||
output: {
|
||||
task_status: "SUCCEEDED",
|
||||
results: [{ video_url: "https://example.com/out.mp4" }],
|
||||
},
|
||||
}),
|
||||
headers: new Headers(),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
arrayBuffer: async () => Buffer.from("mp4-bytes"),
|
||||
headers: new Headers({ "content-type": "video/mp4" }),
|
||||
});
|
||||
|
||||
const provider = buildQwenVideoGenerationProvider();
|
||||
const result = await provider.generateVideo({
|
||||
provider: "qwen",
|
||||
model: "wan2.6-r2v-flash",
|
||||
prompt: "animate this shot",
|
||||
cfg: {},
|
||||
inputImages: [{ url: "https://example.com/ref.png" }],
|
||||
durationSeconds: 6,
|
||||
audio: true,
|
||||
});
|
||||
|
||||
expect(postJsonRequestMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
url: "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis",
|
||||
body: expect.objectContaining({
|
||||
model: "wan2.6-r2v-flash",
|
||||
input: expect.objectContaining({
|
||||
prompt: "animate this shot",
|
||||
img_url: "https://example.com/ref.png",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(fetchWithTimeoutMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"https://dashscope-intl.aliyuncs.com/api/v1/tasks/task-1",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
120000,
|
||||
fetch,
|
||||
);
|
||||
expect(result.videos).toHaveLength(1);
|
||||
expect(result.videos[0]?.mimeType).toBe("video/mp4");
|
||||
expect(result.metadata).toEqual(
|
||||
expect.objectContaining({
|
||||
requestId: "req-1",
|
||||
taskId: "task-1",
|
||||
taskStatus: "SUCCEEDED",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,300 @@
|
||||
import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
|
||||
import {
|
||||
assertOkOrThrowHttpError,
|
||||
fetchWithTimeout,
|
||||
postJsonRequest,
|
||||
resolveProviderHttpRequestConfig,
|
||||
} from "openclaw/plugin-sdk/provider-http";
|
||||
import type {
|
||||
GeneratedVideoAsset,
|
||||
VideoGenerationProvider,
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResult,
|
||||
VideoGenerationSourceAsset,
|
||||
} from "openclaw/plugin-sdk/video-generation";
|
||||
import { QWEN_STANDARD_CN_BASE_URL, QWEN_STANDARD_GLOBAL_BASE_URL } from "./models.js";
|
||||
|
||||
const DEFAULT_QWEN_VIDEO_BASE_URL = "https://dashscope-intl.aliyuncs.com";
|
||||
const DEFAULT_QWEN_VIDEO_MODEL = "wan2.6-t2v";
|
||||
const DEFAULT_DURATION_SECONDS = 5;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 120_000;
|
||||
const POLL_INTERVAL_MS = 2_500;
|
||||
const MAX_POLL_ATTEMPTS = 120;
|
||||
const RESOLUTION_TO_SIZE: Record<string, string> = {
|
||||
"480P": "832*480",
|
||||
"720P": "1280*720",
|
||||
"1080P": "1920*1080",
|
||||
};
|
||||
|
||||
type QwenVideoGenerationResponse = {
|
||||
output?: {
|
||||
task_id?: string;
|
||||
task_status?: string;
|
||||
submit_time?: string;
|
||||
results?: Array<{
|
||||
video_url?: string;
|
||||
orig_prompt?: string;
|
||||
actual_prompt?: string;
|
||||
}>;
|
||||
video_url?: string;
|
||||
code?: string;
|
||||
message?: string;
|
||||
};
|
||||
request_id?: string;
|
||||
code?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
function resolveQwenVideoBaseUrl(req: VideoGenerationRequest): string {
|
||||
const direct = req.cfg?.models?.providers?.qwen?.baseUrl?.trim();
|
||||
if (!direct) {
|
||||
return DEFAULT_QWEN_VIDEO_BASE_URL;
|
||||
}
|
||||
try {
|
||||
const url = new URL(direct);
|
||||
if (url.hostname === "coding-intl.dashscope.aliyuncs.com") {
|
||||
return "https://dashscope-intl.aliyuncs.com";
|
||||
}
|
||||
if (url.hostname === "coding.dashscope.aliyuncs.com") {
|
||||
return "https://dashscope.aliyuncs.com";
|
||||
}
|
||||
if (url.hostname === "dashscope-intl.aliyuncs.com") {
|
||||
return "https://dashscope-intl.aliyuncs.com";
|
||||
}
|
||||
if (url.hostname === "dashscope.aliyuncs.com") {
|
||||
return "https://dashscope.aliyuncs.com";
|
||||
}
|
||||
return url.origin;
|
||||
} catch {
|
||||
return DEFAULT_QWEN_VIDEO_BASE_URL;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveDashscopeAigcApiBaseUrl(baseUrl: string): string {
|
||||
if (baseUrl.startsWith(QWEN_STANDARD_CN_BASE_URL)) {
|
||||
return "https://dashscope.aliyuncs.com";
|
||||
}
|
||||
if (baseUrl.startsWith(QWEN_STANDARD_GLOBAL_BASE_URL)) {
|
||||
return DEFAULT_QWEN_VIDEO_BASE_URL;
|
||||
}
|
||||
return baseUrl.replace(/\/+$/u, "");
|
||||
}
|
||||
|
||||
function resolveReferenceUrls(
|
||||
inputImages: VideoGenerationSourceAsset[] | undefined,
|
||||
inputVideos: VideoGenerationSourceAsset[] | undefined,
|
||||
): string[] {
|
||||
return [...(inputImages ?? []), ...(inputVideos ?? [])]
|
||||
.map((asset) => asset.url?.trim())
|
||||
.filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
function buildQwenVideoGenerationInput(req: VideoGenerationRequest): Record<string, unknown> {
|
||||
const input: Record<string, unknown> = {
|
||||
prompt: req.prompt,
|
||||
};
|
||||
const referenceUrls = resolveReferenceUrls(req.inputImages, req.inputVideos);
|
||||
if (
|
||||
referenceUrls.length === 1 &&
|
||||
(req.inputImages?.length ?? 0) === 1 &&
|
||||
!req.inputVideos?.length
|
||||
) {
|
||||
input.img_url = referenceUrls[0];
|
||||
} else if (referenceUrls.length > 0) {
|
||||
input.reference_urls = referenceUrls;
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function buildQwenVideoGenerationParameters(
|
||||
req: VideoGenerationRequest,
|
||||
): Record<string, unknown> | undefined {
|
||||
const parameters: Record<string, unknown> = {};
|
||||
const size =
|
||||
req.size?.trim() || (req.resolution ? RESOLUTION_TO_SIZE[req.resolution] : undefined);
|
||||
if (size) {
|
||||
parameters.size = size;
|
||||
}
|
||||
if (req.aspectRatio?.trim()) {
|
||||
parameters.aspect_ratio = req.aspectRatio.trim();
|
||||
}
|
||||
if (typeof req.durationSeconds === "number" && Number.isFinite(req.durationSeconds)) {
|
||||
parameters.duration = Math.max(1, Math.round(req.durationSeconds));
|
||||
}
|
||||
if (typeof req.audio === "boolean") {
|
||||
parameters.enable_audio = req.audio;
|
||||
}
|
||||
if (typeof req.watermark === "boolean") {
|
||||
parameters.watermark = req.watermark;
|
||||
}
|
||||
return Object.keys(parameters).length > 0 ? parameters : undefined;
|
||||
}
|
||||
|
||||
function extractVideoUrls(payload: QwenVideoGenerationResponse): string[] {
|
||||
const urls = [
|
||||
...(payload.output?.results?.map((entry) => entry.video_url).filter(Boolean) ?? []),
|
||||
payload.output?.video_url,
|
||||
].filter((value): value is string => typeof value === "string" && value.trim().length > 0);
|
||||
return [...new Set(urls)];
|
||||
}
|
||||
|
||||
async function pollTaskUntilComplete(params: {
|
||||
taskId: string;
|
||||
headers: Headers;
|
||||
timeoutMs?: number;
|
||||
fetchFn: typeof fetch;
|
||||
baseUrl: string;
|
||||
}): Promise<QwenVideoGenerationResponse> {
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) {
|
||||
const response = await fetchWithTimeout(
|
||||
`${params.baseUrl}/api/v1/tasks/${params.taskId}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: params.headers,
|
||||
},
|
||||
params.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
params.fetchFn,
|
||||
);
|
||||
await assertOkOrThrowHttpError(response, "Qwen video-generation task poll failed");
|
||||
const payload = (await response.json()) as QwenVideoGenerationResponse;
|
||||
const status = payload.output?.task_status?.trim().toUpperCase();
|
||||
if (status === "SUCCEEDED") {
|
||||
return payload;
|
||||
}
|
||||
if (status === "FAILED" || status === "CANCELED") {
|
||||
throw new Error(
|
||||
payload.output?.message?.trim() ||
|
||||
payload.message?.trim() ||
|
||||
`Qwen video generation task ${params.taskId} ${status.toLowerCase()}`,
|
||||
);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new Error(`Qwen video generation task ${params.taskId} did not finish in time`);
|
||||
}
|
||||
|
||||
async function downloadGeneratedVideos(params: {
|
||||
urls: string[];
|
||||
timeoutMs?: number;
|
||||
fetchFn: typeof fetch;
|
||||
}): Promise<GeneratedVideoAsset[]> {
|
||||
const videos: GeneratedVideoAsset[] = [];
|
||||
for (const [index, url] of params.urls.entries()) {
|
||||
const response = await fetchWithTimeout(
|
||||
url,
|
||||
{ method: "GET" },
|
||||
params.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||
params.fetchFn,
|
||||
);
|
||||
await assertOkOrThrowHttpError(response, "Qwen generated video download failed");
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
videos.push({
|
||||
buffer: Buffer.from(arrayBuffer),
|
||||
mimeType: response.headers.get("content-type")?.trim() || "video/mp4",
|
||||
fileName: `video-${index + 1}.mp4`,
|
||||
metadata: { sourceUrl: url },
|
||||
});
|
||||
}
|
||||
return videos;
|
||||
}
|
||||
|
||||
export function buildQwenVideoGenerationProvider(): VideoGenerationProvider {
|
||||
return {
|
||||
id: "qwen",
|
||||
label: "Qwen Cloud",
|
||||
defaultModel: DEFAULT_QWEN_VIDEO_MODEL,
|
||||
models: ["wan2.6-t2v", "wan2.6-i2v", "wan2.6-r2v", "wan2.6-r2v-flash", "wan2.7-r2v"],
|
||||
capabilities: {
|
||||
maxVideos: 1,
|
||||
maxInputImages: 1,
|
||||
maxInputVideos: 4,
|
||||
maxDurationSeconds: 10,
|
||||
supportsSize: true,
|
||||
supportsAspectRatio: true,
|
||||
supportsResolution: true,
|
||||
supportsAudio: true,
|
||||
supportsWatermark: true,
|
||||
},
|
||||
async generateVideo(req): Promise<VideoGenerationResult> {
|
||||
const fetchFn = fetch;
|
||||
const auth = await resolveApiKeyForProvider({
|
||||
provider: "qwen",
|
||||
cfg: req.cfg,
|
||||
agentDir: req.agentDir,
|
||||
store: req.authStore,
|
||||
});
|
||||
if (!auth.apiKey) {
|
||||
throw new Error("Qwen API key missing");
|
||||
}
|
||||
|
||||
const requestBaseUrl = resolveQwenVideoBaseUrl(req);
|
||||
const { baseUrl, allowPrivateNetwork, headers, dispatcherPolicy } =
|
||||
resolveProviderHttpRequestConfig({
|
||||
baseUrl: requestBaseUrl,
|
||||
defaultBaseUrl: DEFAULT_QWEN_VIDEO_BASE_URL,
|
||||
defaultHeaders: {
|
||||
Authorization: `Bearer ${auth.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
"X-DashScope-Async": "enable",
|
||||
},
|
||||
provider: "qwen",
|
||||
capability: "video",
|
||||
transport: "http",
|
||||
});
|
||||
|
||||
const model = req.model?.trim() || DEFAULT_QWEN_VIDEO_MODEL;
|
||||
const { response, release } = await postJsonRequest({
|
||||
url: `${resolveDashscopeAigcApiBaseUrl(baseUrl)}/api/v1/services/aigc/video-generation/video-synthesis`,
|
||||
headers,
|
||||
body: {
|
||||
model,
|
||||
input: buildQwenVideoGenerationInput(req),
|
||||
parameters: buildQwenVideoGenerationParameters({
|
||||
...req,
|
||||
durationSeconds: req.durationSeconds ?? DEFAULT_DURATION_SECONDS,
|
||||
}),
|
||||
},
|
||||
timeoutMs: req.timeoutMs,
|
||||
fetchFn,
|
||||
allowPrivateNetwork,
|
||||
dispatcherPolicy,
|
||||
});
|
||||
|
||||
try {
|
||||
await assertOkOrThrowHttpError(response, "Qwen video generation failed");
|
||||
const submitted = (await response.json()) as QwenVideoGenerationResponse;
|
||||
const taskId = submitted.output?.task_id?.trim();
|
||||
if (!taskId) {
|
||||
throw new Error("Qwen video generation response missing task_id");
|
||||
}
|
||||
const completed = await pollTaskUntilComplete({
|
||||
taskId,
|
||||
headers,
|
||||
timeoutMs: req.timeoutMs,
|
||||
fetchFn,
|
||||
baseUrl: resolveDashscopeAigcApiBaseUrl(baseUrl),
|
||||
});
|
||||
const urls = extractVideoUrls(completed);
|
||||
if (urls.length === 0) {
|
||||
throw new Error("Qwen video generation completed without output video URLs");
|
||||
}
|
||||
const videos = await downloadGeneratedVideos({
|
||||
urls,
|
||||
timeoutMs: req.timeoutMs,
|
||||
fetchFn,
|
||||
});
|
||||
return {
|
||||
videos,
|
||||
model,
|
||||
metadata: {
|
||||
requestId: submitted.request_id,
|
||||
taskId,
|
||||
taskStatus: completed.output?.task_status,
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@ -0,0 +1 @@
|
||||
export * from "openclaw/plugin-sdk/video-generation-core";
|
||||
@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "@openclaw/video-generation-core",
|
||||
"version": "2026.4.1-beta.1",
|
||||
"private": true,
|
||||
"description": "OpenClaw video generation runtime package",
|
||||
"type": "module"
|
||||
}
|
||||
@ -0,0 +1,6 @@
|
||||
export {
|
||||
generateVideo,
|
||||
listRuntimeVideoGenerationProviders,
|
||||
type GenerateVideoParams,
|
||||
type GenerateVideoRuntimeResult,
|
||||
} from "./src/runtime.js";
|
||||
@ -0,0 +1,164 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "../../../src/config/config.js";
|
||||
import type { VideoGenerationProvider } from "../api.js";
|
||||
import { generateVideo, listRuntimeVideoGenerationProviders } from "./runtime.js";
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const debug = vi.fn();
|
||||
return {
|
||||
createSubsystemLogger: vi.fn(() => ({ debug })),
|
||||
describeFailoverError: vi.fn(),
|
||||
getProviderEnvVars: vi.fn<(providerId: string) => string[]>(() => []),
|
||||
getVideoGenerationProvider: vi.fn<
|
||||
(providerId: string, config?: OpenClawConfig) => VideoGenerationProvider | undefined
|
||||
>(() => undefined),
|
||||
isFailoverError: vi.fn<(err: unknown) => boolean>(() => false),
|
||||
listVideoGenerationProviders: vi.fn<(config?: OpenClawConfig) => VideoGenerationProvider[]>(
|
||||
() => [],
|
||||
),
|
||||
parseVideoGenerationModelRef: vi.fn<
|
||||
(raw?: string) => { provider: string; model: string } | undefined
|
||||
>((raw?: string) => {
|
||||
const trimmed = raw?.trim();
|
||||
if (!trimmed) {
|
||||
return undefined;
|
||||
}
|
||||
const slash = trimmed.indexOf("/");
|
||||
if (slash <= 0 || slash === trimmed.length - 1) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
provider: trimmed.slice(0, slash),
|
||||
model: trimmed.slice(slash + 1),
|
||||
};
|
||||
}),
|
||||
resolveAgentModelFallbackValues: vi.fn<(value: unknown) => string[]>(() => []),
|
||||
resolveAgentModelPrimaryValue: vi.fn<(value: unknown) => string | undefined>(() => undefined),
|
||||
debug,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../api.js", () => ({
|
||||
createSubsystemLogger: mocks.createSubsystemLogger,
|
||||
describeFailoverError: mocks.describeFailoverError,
|
||||
getProviderEnvVars: mocks.getProviderEnvVars,
|
||||
getVideoGenerationProvider: mocks.getVideoGenerationProvider,
|
||||
isFailoverError: mocks.isFailoverError,
|
||||
listVideoGenerationProviders: mocks.listVideoGenerationProviders,
|
||||
parseVideoGenerationModelRef: mocks.parseVideoGenerationModelRef,
|
||||
resolveAgentModelFallbackValues: mocks.resolveAgentModelFallbackValues,
|
||||
resolveAgentModelPrimaryValue: mocks.resolveAgentModelPrimaryValue,
|
||||
}));
|
||||
|
||||
describe("video-generation runtime", () => {
|
||||
beforeEach(() => {
|
||||
mocks.createSubsystemLogger.mockClear();
|
||||
mocks.describeFailoverError.mockReset();
|
||||
mocks.getProviderEnvVars.mockReset();
|
||||
mocks.getProviderEnvVars.mockReturnValue([]);
|
||||
mocks.getVideoGenerationProvider.mockReset();
|
||||
mocks.isFailoverError.mockReset();
|
||||
mocks.isFailoverError.mockReturnValue(false);
|
||||
mocks.listVideoGenerationProviders.mockReset();
|
||||
mocks.listVideoGenerationProviders.mockReturnValue([]);
|
||||
mocks.parseVideoGenerationModelRef.mockClear();
|
||||
mocks.resolveAgentModelFallbackValues.mockReset();
|
||||
mocks.resolveAgentModelFallbackValues.mockReturnValue([]);
|
||||
mocks.resolveAgentModelPrimaryValue.mockReset();
|
||||
mocks.resolveAgentModelPrimaryValue.mockReturnValue(undefined);
|
||||
mocks.debug.mockReset();
|
||||
});
|
||||
|
||||
it("generates videos through the active video-generation provider", async () => {
|
||||
const authStore = { version: 1, profiles: {} } as const;
|
||||
let seenAuthStore: unknown;
|
||||
mocks.resolveAgentModelPrimaryValue.mockReturnValue("video-plugin/vid-v1");
|
||||
const provider: VideoGenerationProvider = {
|
||||
id: "video-plugin",
|
||||
capabilities: {},
|
||||
async generateVideo(req: { authStore?: unknown }) {
|
||||
seenAuthStore = req.authStore;
|
||||
return {
|
||||
videos: [
|
||||
{
|
||||
buffer: Buffer.from("mp4-bytes"),
|
||||
mimeType: "video/mp4",
|
||||
fileName: "sample.mp4",
|
||||
},
|
||||
],
|
||||
model: "vid-v1",
|
||||
};
|
||||
},
|
||||
};
|
||||
mocks.getVideoGenerationProvider.mockReturnValue(provider);
|
||||
|
||||
const result = await generateVideo({
|
||||
cfg: {
|
||||
agents: {
|
||||
defaults: {
|
||||
videoGenerationModel: { primary: "video-plugin/vid-v1" },
|
||||
},
|
||||
},
|
||||
} as OpenClawConfig,
|
||||
prompt: "animate a cat",
|
||||
agentDir: "/tmp/agent",
|
||||
authStore,
|
||||
});
|
||||
|
||||
expect(result.provider).toBe("video-plugin");
|
||||
expect(result.model).toBe("vid-v1");
|
||||
expect(result.attempts).toEqual([]);
|
||||
expect(seenAuthStore).toEqual(authStore);
|
||||
expect(result.videos).toEqual([
|
||||
{
|
||||
buffer: Buffer.from("mp4-bytes"),
|
||||
mimeType: "video/mp4",
|
||||
fileName: "sample.mp4",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists runtime video-generation providers through the owner runtime", () => {
|
||||
const providers: VideoGenerationProvider[] = [
|
||||
{
|
||||
id: "video-plugin",
|
||||
defaultModel: "vid-v1",
|
||||
models: ["vid-v1"],
|
||||
capabilities: {
|
||||
supportsAudio: true,
|
||||
},
|
||||
generateVideo: async () => ({
|
||||
videos: [{ buffer: Buffer.from("mp4-bytes"), mimeType: "video/mp4" }],
|
||||
}),
|
||||
},
|
||||
];
|
||||
mocks.listVideoGenerationProviders.mockReturnValue(providers);
|
||||
|
||||
expect(listRuntimeVideoGenerationProviders({ config: {} as OpenClawConfig })).toEqual(
|
||||
providers,
|
||||
);
|
||||
expect(mocks.listVideoGenerationProviders).toHaveBeenCalledWith({} as OpenClawConfig);
|
||||
});
|
||||
|
||||
it("explains native video-generation config and provider auth when no model is configured", async () => {
|
||||
mocks.listVideoGenerationProviders.mockReturnValue([
|
||||
{
|
||||
id: "qwen",
|
||||
defaultModel: "wan2.6-t2v",
|
||||
capabilities: {},
|
||||
generateVideo: async () => ({
|
||||
videos: [{ buffer: Buffer.from("mp4-bytes"), mimeType: "video/mp4" }],
|
||||
}),
|
||||
},
|
||||
]);
|
||||
mocks.getProviderEnvVars.mockReturnValue(["QWEN_API_KEY"]);
|
||||
|
||||
const promise = generateVideo({ cfg: {} as OpenClawConfig, prompt: "animate a cat" });
|
||||
|
||||
await expect(promise).rejects.toThrow("No video-generation model configured.");
|
||||
await expect(promise).rejects.toThrow(
|
||||
'Set agents.defaults.videoGenerationModel.primary to a provider/model like "',
|
||||
);
|
||||
await expect(promise).rejects.toThrow("qwen: QWEN_API_KEY");
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,189 @@
|
||||
import {
|
||||
createSubsystemLogger,
|
||||
describeFailoverError,
|
||||
getProviderEnvVars,
|
||||
getVideoGenerationProvider,
|
||||
isFailoverError,
|
||||
listVideoGenerationProviders,
|
||||
parseVideoGenerationModelRef,
|
||||
resolveAgentModelFallbackValues,
|
||||
resolveAgentModelPrimaryValue,
|
||||
type AuthProfileStore,
|
||||
type FallbackAttempt,
|
||||
type GeneratedVideoAsset,
|
||||
type OpenClawConfig,
|
||||
type VideoGenerationResolution,
|
||||
type VideoGenerationResult,
|
||||
type VideoGenerationSourceAsset,
|
||||
} from "../api.js";
|
||||
|
||||
const log = createSubsystemLogger("video-generation");
|
||||
|
||||
export type GenerateVideoParams = {
|
||||
cfg: OpenClawConfig;
|
||||
prompt: string;
|
||||
agentDir?: string;
|
||||
authStore?: AuthProfileStore;
|
||||
modelOverride?: string;
|
||||
size?: string;
|
||||
aspectRatio?: string;
|
||||
resolution?: VideoGenerationResolution;
|
||||
durationSeconds?: number;
|
||||
audio?: boolean;
|
||||
watermark?: boolean;
|
||||
inputImages?: VideoGenerationSourceAsset[];
|
||||
inputVideos?: VideoGenerationSourceAsset[];
|
||||
};
|
||||
|
||||
export type GenerateVideoRuntimeResult = {
|
||||
videos: GeneratedVideoAsset[];
|
||||
provider: string;
|
||||
model: string;
|
||||
attempts: FallbackAttempt[];
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function resolveVideoGenerationCandidates(params: {
|
||||
cfg: OpenClawConfig;
|
||||
modelOverride?: string;
|
||||
}): Array<{ provider: string; model: string }> {
|
||||
const candidates: Array<{ provider: string; model: string }> = [];
|
||||
const seen = new Set<string>();
|
||||
const add = (raw: string | undefined) => {
|
||||
const parsed = parseVideoGenerationModelRef(raw);
|
||||
if (!parsed) {
|
||||
return;
|
||||
}
|
||||
const key = `${parsed.provider}/${parsed.model}`;
|
||||
if (seen.has(key)) {
|
||||
return;
|
||||
}
|
||||
seen.add(key);
|
||||
candidates.push(parsed);
|
||||
};
|
||||
|
||||
add(params.modelOverride);
|
||||
add(resolveAgentModelPrimaryValue(params.cfg.agents?.defaults?.videoGenerationModel));
|
||||
for (const fallback of resolveAgentModelFallbackValues(
|
||||
params.cfg.agents?.defaults?.videoGenerationModel,
|
||||
)) {
|
||||
add(fallback);
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function throwVideoGenerationFailure(params: {
|
||||
attempts: FallbackAttempt[];
|
||||
lastError: unknown;
|
||||
}): never {
|
||||
if (params.attempts.length <= 1 && params.lastError) {
|
||||
throw params.lastError;
|
||||
}
|
||||
const summary =
|
||||
params.attempts.length > 0
|
||||
? params.attempts
|
||||
.map((attempt) => `${attempt.provider}/${attempt.model}: ${attempt.error}`)
|
||||
.join(" | ")
|
||||
: "unknown";
|
||||
throw new Error(`All video generation models failed (${params.attempts.length}): ${summary}`, {
|
||||
cause: params.lastError instanceof Error ? params.lastError : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
function buildNoVideoGenerationModelConfiguredMessage(cfg: OpenClawConfig): string {
|
||||
const providers = listVideoGenerationProviders(cfg);
|
||||
const sampleModel =
|
||||
providers.find((provider) => provider.defaultModel) ??
|
||||
({ id: "qwen", defaultModel: "wan2.6-t2v" } as const);
|
||||
const authHints = providers
|
||||
.flatMap((provider) => {
|
||||
const envVars = getProviderEnvVars(provider.id);
|
||||
if (envVars.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return [`${provider.id}: ${envVars.join(" / ")}`];
|
||||
})
|
||||
.slice(0, 3);
|
||||
return [
|
||||
`No video-generation model configured. Set agents.defaults.videoGenerationModel.primary to a provider/model like "${sampleModel.id}/${sampleModel.defaultModel}".`,
|
||||
authHints.length > 0
|
||||
? `If you want a specific provider, also configure that provider's auth/API key first (${authHints.join("; ")}).`
|
||||
: "If you want a specific provider, also configure that provider's auth/API key first.",
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function listRuntimeVideoGenerationProviders(params?: { config?: OpenClawConfig }) {
|
||||
return listVideoGenerationProviders(params?.config);
|
||||
}
|
||||
|
||||
export async function generateVideo(
|
||||
params: GenerateVideoParams,
|
||||
): Promise<GenerateVideoRuntimeResult> {
|
||||
const candidates = resolveVideoGenerationCandidates({
|
||||
cfg: params.cfg,
|
||||
modelOverride: params.modelOverride,
|
||||
});
|
||||
if (candidates.length === 0) {
|
||||
throw new Error(buildNoVideoGenerationModelConfiguredMessage(params.cfg));
|
||||
}
|
||||
|
||||
const attempts: FallbackAttempt[] = [];
|
||||
let lastError: unknown;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const provider = getVideoGenerationProvider(candidate.provider, params.cfg);
|
||||
if (!provider) {
|
||||
const error = `No video-generation provider registered for ${candidate.provider}`;
|
||||
attempts.push({
|
||||
provider: candidate.provider,
|
||||
model: candidate.model,
|
||||
error,
|
||||
});
|
||||
lastError = new Error(error);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const result: VideoGenerationResult = await provider.generateVideo({
|
||||
provider: candidate.provider,
|
||||
model: candidate.model,
|
||||
prompt: params.prompt,
|
||||
cfg: params.cfg,
|
||||
agentDir: params.agentDir,
|
||||
authStore: params.authStore,
|
||||
size: params.size,
|
||||
aspectRatio: params.aspectRatio,
|
||||
resolution: params.resolution,
|
||||
durationSeconds: params.durationSeconds,
|
||||
audio: params.audio,
|
||||
watermark: params.watermark,
|
||||
inputImages: params.inputImages,
|
||||
inputVideos: params.inputVideos,
|
||||
});
|
||||
if (!Array.isArray(result.videos) || result.videos.length === 0) {
|
||||
throw new Error("Video generation provider returned no videos.");
|
||||
}
|
||||
return {
|
||||
videos: result.videos,
|
||||
provider: candidate.provider,
|
||||
model: result.model ?? candidate.model,
|
||||
attempts,
|
||||
metadata: result.metadata,
|
||||
};
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
const described = isFailoverError(err) ? describeFailoverError(err) : undefined;
|
||||
attempts.push({
|
||||
provider: candidate.provider,
|
||||
model: candidate.model,
|
||||
error: described?.message ?? (err instanceof Error ? err.message : String(err)),
|
||||
reason: described?.reason,
|
||||
status: described?.status,
|
||||
code: described?.code,
|
||||
});
|
||||
log.debug(`video-generation candidate failed: ${candidate.provider}/${candidate.model}`);
|
||||
}
|
||||
}
|
||||
|
||||
throwVideoGenerationFailure({ attempts, lastError });
|
||||
}
|
||||
@ -0,0 +1,40 @@
|
||||
// Generated by scripts/generate-plugin-sdk-facades.mjs. Do not edit manually.
|
||||
import type { PluginSdkFacadeTypeMap } from "../generated/plugin-sdk-facade-type-map.generated.js";
|
||||
type FacadeEntry = PluginSdkFacadeTypeMap["qwen-definitions"];
|
||||
type FacadeModule = FacadeEntry["module"];
|
||||
import {
|
||||
createLazyFacadeObjectValue,
|
||||
loadBundledPluginPublicSurfaceModuleSync,
|
||||
} from "./facade-runtime.js";
|
||||
|
||||
function loadFacadeModule(): FacadeModule {
|
||||
return loadBundledPluginPublicSurfaceModuleSync<FacadeModule>({
|
||||
dirName: "qwen",
|
||||
artifactBasename: "api.js",
|
||||
});
|
||||
}
|
||||
export const buildQwenDefaultModelDefinition: FacadeModule["buildQwenDefaultModelDefinition"] = ((
|
||||
...args
|
||||
) =>
|
||||
loadFacadeModule()["buildQwenDefaultModelDefinition"](
|
||||
...args,
|
||||
)) as FacadeModule["buildQwenDefaultModelDefinition"];
|
||||
export const buildQwenModelDefinition: FacadeModule["buildQwenModelDefinition"] = ((...args) =>
|
||||
loadFacadeModule()["buildQwenModelDefinition"](
|
||||
...args,
|
||||
)) as FacadeModule["buildQwenModelDefinition"];
|
||||
export const QWEN_CN_BASE_URL: FacadeModule["QWEN_CN_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_CN_BASE_URL"];
|
||||
export const QWEN_DEFAULT_COST: FacadeModule["QWEN_DEFAULT_COST"] = createLazyFacadeObjectValue(
|
||||
() => loadFacadeModule()["QWEN_DEFAULT_COST"] as object,
|
||||
) as FacadeModule["QWEN_DEFAULT_COST"];
|
||||
export const QWEN_DEFAULT_MODEL_ID: FacadeModule["QWEN_DEFAULT_MODEL_ID"] =
|
||||
loadFacadeModule()["QWEN_DEFAULT_MODEL_ID"];
|
||||
export const QWEN_DEFAULT_MODEL_REF: FacadeModule["QWEN_DEFAULT_MODEL_REF"] =
|
||||
loadFacadeModule()["QWEN_DEFAULT_MODEL_REF"];
|
||||
export const QWEN_GLOBAL_BASE_URL: FacadeModule["QWEN_GLOBAL_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_GLOBAL_BASE_URL"];
|
||||
export const QWEN_STANDARD_CN_BASE_URL: FacadeModule["QWEN_STANDARD_CN_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_STANDARD_CN_BASE_URL"];
|
||||
export const QWEN_STANDARD_GLOBAL_BASE_URL: FacadeModule["QWEN_STANDARD_GLOBAL_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_STANDARD_GLOBAL_BASE_URL"];
|
||||
@ -0,0 +1,54 @@
|
||||
// Generated by scripts/generate-plugin-sdk-facades.mjs. Do not edit manually.
|
||||
import type { PluginSdkFacadeTypeMap } from "../generated/plugin-sdk-facade-type-map.generated.js";
|
||||
type FacadeEntry = PluginSdkFacadeTypeMap["qwen"];
|
||||
type FacadeModule = FacadeEntry["module"];
|
||||
import {
|
||||
createLazyFacadeArrayValue,
|
||||
createLazyFacadeObjectValue,
|
||||
loadBundledPluginPublicSurfaceModuleSync,
|
||||
} from "./facade-runtime.js";
|
||||
|
||||
function loadFacadeModule(): FacadeModule {
|
||||
return loadBundledPluginPublicSurfaceModuleSync<FacadeModule>({
|
||||
dirName: "qwen",
|
||||
artifactBasename: "api.js",
|
||||
});
|
||||
}
|
||||
export const applyQwenNativeStreamingUsageCompat: FacadeModule["applyQwenNativeStreamingUsageCompat"] =
|
||||
((...args) =>
|
||||
loadFacadeModule()["applyQwenNativeStreamingUsageCompat"](
|
||||
...args,
|
||||
)) as FacadeModule["applyQwenNativeStreamingUsageCompat"];
|
||||
export const buildQwenDefaultModelDefinition: FacadeModule["buildQwenDefaultModelDefinition"] = ((
|
||||
...args
|
||||
) =>
|
||||
loadFacadeModule()["buildQwenDefaultModelDefinition"](
|
||||
...args,
|
||||
)) as FacadeModule["buildQwenDefaultModelDefinition"];
|
||||
export const buildQwenModelDefinition: FacadeModule["buildQwenModelDefinition"] = ((...args) =>
|
||||
loadFacadeModule()["buildQwenModelDefinition"](
|
||||
...args,
|
||||
)) as FacadeModule["buildQwenModelDefinition"];
|
||||
export const QWEN_BASE_URL: FacadeModule["QWEN_BASE_URL"] = loadFacadeModule()["QWEN_BASE_URL"];
|
||||
export const QWEN_CN_BASE_URL: FacadeModule["QWEN_CN_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_CN_BASE_URL"];
|
||||
export const QWEN_DEFAULT_COST: FacadeModule["QWEN_DEFAULT_COST"] = createLazyFacadeObjectValue(
|
||||
() => loadFacadeModule()["QWEN_DEFAULT_COST"] as object,
|
||||
) as FacadeModule["QWEN_DEFAULT_COST"];
|
||||
export const QWEN_DEFAULT_MODEL_ID: FacadeModule["QWEN_DEFAULT_MODEL_ID"] =
|
||||
loadFacadeModule()["QWEN_DEFAULT_MODEL_ID"];
|
||||
export const QWEN_DEFAULT_MODEL_REF: FacadeModule["QWEN_DEFAULT_MODEL_REF"] =
|
||||
loadFacadeModule()["QWEN_DEFAULT_MODEL_REF"];
|
||||
export const QWEN_GLOBAL_BASE_URL: FacadeModule["QWEN_GLOBAL_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_GLOBAL_BASE_URL"];
|
||||
export const QWEN_STANDARD_CN_BASE_URL: FacadeModule["QWEN_STANDARD_CN_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_STANDARD_CN_BASE_URL"];
|
||||
export const QWEN_STANDARD_GLOBAL_BASE_URL: FacadeModule["QWEN_STANDARD_GLOBAL_BASE_URL"] =
|
||||
loadFacadeModule()["QWEN_STANDARD_GLOBAL_BASE_URL"];
|
||||
export const QWEN_MODEL_CATALOG: FacadeModule["QWEN_MODEL_CATALOG"] = createLazyFacadeArrayValue(
|
||||
() => loadFacadeModule()["QWEN_MODEL_CATALOG"] as unknown as readonly unknown[],
|
||||
) as FacadeModule["QWEN_MODEL_CATALOG"];
|
||||
export const isNativeQwenBaseUrl: FacadeModule["isNativeQwenBaseUrl"] = ((...args) =>
|
||||
loadFacadeModule()["isNativeQwenBaseUrl"](...args)) as FacadeModule["isNativeQwenBaseUrl"];
|
||||
export const buildQwenProvider: FacadeModule["buildQwenProvider"] = ((...args) =>
|
||||
loadFacadeModule()["buildQwenProvider"](...args)) as FacadeModule["buildQwenProvider"];
|
||||
@ -0,0 +1,27 @@
|
||||
// Shared video-generation implementation helpers for bundled and third-party plugins.
|
||||
|
||||
export type { AuthProfileStore } from "../agents/auth-profiles.js";
|
||||
export type { FallbackAttempt } from "../agents/model-fallback.types.js";
|
||||
export type { VideoGenerationProviderPlugin } from "../plugins/types.js";
|
||||
export type {
|
||||
GeneratedVideoAsset,
|
||||
VideoGenerationProvider,
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResolution,
|
||||
VideoGenerationResult,
|
||||
VideoGenerationSourceAsset,
|
||||
} from "../video-generation/types.js";
|
||||
export type { OpenClawConfig } from "../config/config.js";
|
||||
|
||||
export { describeFailoverError, isFailoverError } from "../agents/failover-error.js";
|
||||
export {
|
||||
resolveAgentModelFallbackValues,
|
||||
resolveAgentModelPrimaryValue,
|
||||
} from "../config/model-input.js";
|
||||
export {
|
||||
getVideoGenerationProvider,
|
||||
listVideoGenerationProviders,
|
||||
} from "../video-generation/provider-registry.js";
|
||||
export { parseVideoGenerationModelRef } from "../video-generation/model-ref.js";
|
||||
export { createSubsystemLogger } from "../logging/subsystem.js";
|
||||
export { getProviderEnvVars } from "../secrets/provider-env-vars.js";
|
||||
@ -0,0 +1,21 @@
|
||||
// Generated by scripts/generate-plugin-sdk-facades.mjs. Do not edit manually.
|
||||
import type { PluginSdkFacadeTypeMap } from "../generated/plugin-sdk-facade-type-map.generated.js";
|
||||
type FacadeEntry = PluginSdkFacadeTypeMap["video-generation-runtime"];
|
||||
type FacadeModule = FacadeEntry["module"];
|
||||
import { loadActivatedBundledPluginPublicSurfaceModuleSync } from "./facade-runtime.js";
|
||||
|
||||
function loadFacadeModule(): FacadeModule {
|
||||
return loadActivatedBundledPluginPublicSurfaceModuleSync<FacadeModule>({
|
||||
dirName: "video-generation-core",
|
||||
artifactBasename: "runtime-api.js",
|
||||
});
|
||||
}
|
||||
export const generateVideo: FacadeModule["generateVideo"] = ((...args) =>
|
||||
loadFacadeModule()["generateVideo"](...args)) as FacadeModule["generateVideo"];
|
||||
export const listRuntimeVideoGenerationProviders: FacadeModule["listRuntimeVideoGenerationProviders"] =
|
||||
((...args) =>
|
||||
loadFacadeModule()["listRuntimeVideoGenerationProviders"](
|
||||
...args,
|
||||
)) as FacadeModule["listRuntimeVideoGenerationProviders"];
|
||||
export type GenerateVideoParams = FacadeEntry["types"]["GenerateVideoParams"];
|
||||
export type GenerateVideoRuntimeResult = FacadeEntry["types"]["GenerateVideoRuntimeResult"];
|
||||
@ -0,0 +1,10 @@
|
||||
// Public video-generation helpers and types for provider plugins.
|
||||
|
||||
export type {
|
||||
GeneratedVideoAsset,
|
||||
VideoGenerationProvider,
|
||||
VideoGenerationRequest,
|
||||
VideoGenerationResolution,
|
||||
VideoGenerationResult,
|
||||
VideoGenerationSourceAsset,
|
||||
} from "../video-generation/types.js";
|
||||
@ -0,0 +1,16 @@
|
||||
export function parseVideoGenerationModelRef(
|
||||
raw: string | undefined,
|
||||
): { provider: string; model: string } | null {
|
||||
const trimmed = raw?.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
const slashIndex = trimmed.indexOf("/");
|
||||
if (slashIndex <= 0 || slashIndex === trimmed.length - 1) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
provider: trimmed.slice(0, slashIndex).trim(),
|
||||
model: trimmed.slice(slashIndex + 1).trim(),
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createEmptyPluginRegistry } from "../plugins/registry.js";
|
||||
|
||||
const { resolveRuntimePluginRegistryMock } = vi.hoisted(() => ({
|
||||
resolveRuntimePluginRegistryMock: vi.fn<
|
||||
(params?: unknown) => ReturnType<typeof createEmptyPluginRegistry> | undefined
|
||||
>(() => undefined),
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/loader.js", () => ({
|
||||
resolveRuntimePluginRegistry: resolveRuntimePluginRegistryMock,
|
||||
}));
|
||||
|
||||
let getVideoGenerationProvider: typeof import("./provider-registry.js").getVideoGenerationProvider;
|
||||
let listVideoGenerationProviders: typeof import("./provider-registry.js").listVideoGenerationProviders;
|
||||
|
||||
describe("video-generation provider registry", () => {
|
||||
beforeAll(async () => {
|
||||
({ getVideoGenerationProvider, listVideoGenerationProviders } =
|
||||
await import("./provider-registry.js"));
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resolveRuntimePluginRegistryMock.mockReset();
|
||||
resolveRuntimePluginRegistryMock.mockReturnValue(undefined);
|
||||
});
|
||||
|
||||
it("does not load plugins when listing without config", () => {
|
||||
expect(listVideoGenerationProviders()).toEqual([]);
|
||||
expect(resolveRuntimePluginRegistryMock).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it("uses active plugin providers without loading from disk", () => {
|
||||
const registry = createEmptyPluginRegistry();
|
||||
registry.videoGenerationProviders.push({
|
||||
pluginId: "custom-video",
|
||||
pluginName: "Custom Video",
|
||||
source: "test",
|
||||
provider: {
|
||||
id: "custom-video",
|
||||
label: "Custom Video",
|
||||
capabilities: {},
|
||||
generateVideo: async () => ({
|
||||
videos: [{ buffer: Buffer.from("video"), mimeType: "video/mp4" }],
|
||||
}),
|
||||
},
|
||||
});
|
||||
resolveRuntimePluginRegistryMock.mockReturnValue(registry);
|
||||
|
||||
const provider = getVideoGenerationProvider("custom-video");
|
||||
|
||||
expect(provider?.id).toBe("custom-video");
|
||||
expect(resolveRuntimePluginRegistryMock).toHaveBeenCalledWith();
|
||||
});
|
||||
|
||||
it("ignores prototype-like provider ids and aliases", () => {
|
||||
const registry = createEmptyPluginRegistry();
|
||||
registry.videoGenerationProviders.push(
|
||||
{
|
||||
pluginId: "blocked-video",
|
||||
pluginName: "Blocked Video",
|
||||
source: "test",
|
||||
provider: {
|
||||
id: "__proto__",
|
||||
aliases: ["constructor", "prototype"],
|
||||
capabilities: {},
|
||||
generateVideo: async () => ({
|
||||
videos: [{ buffer: Buffer.from("video"), mimeType: "video/mp4" }],
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
pluginId: "safe-video",
|
||||
pluginName: "Safe Video",
|
||||
source: "test",
|
||||
provider: {
|
||||
id: "safe-video",
|
||||
aliases: ["safe-alias", "constructor"],
|
||||
capabilities: {},
|
||||
generateVideo: async () => ({
|
||||
videos: [{ buffer: Buffer.from("video"), mimeType: "video/mp4" }],
|
||||
}),
|
||||
},
|
||||
},
|
||||
);
|
||||
resolveRuntimePluginRegistryMock.mockReturnValue(registry);
|
||||
|
||||
expect(listVideoGenerationProviders().map((provider) => provider.id)).toEqual(["safe-video"]);
|
||||
expect(getVideoGenerationProvider("__proto__")).toBeUndefined();
|
||||
expect(getVideoGenerationProvider("constructor")).toBeUndefined();
|
||||
expect(getVideoGenerationProvider("safe-alias")?.id).toBe("safe-video");
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,77 @@
|
||||
import { normalizeProviderId } from "../agents/model-selection.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import { isBlockedObjectKey } from "../infra/prototype-keys.js";
|
||||
import { resolvePluginCapabilityProviders } from "../plugins/capability-provider-runtime.js";
|
||||
import type { VideoGenerationProviderPlugin } from "../plugins/types.js";
|
||||
|
||||
const BUILTIN_VIDEO_GENERATION_PROVIDERS: readonly VideoGenerationProviderPlugin[] = [];
|
||||
const UNSAFE_PROVIDER_IDS = new Set(["__proto__", "constructor", "prototype"]);
|
||||
|
||||
function normalizeVideoGenerationProviderId(id: string | undefined): string | undefined {
|
||||
const normalized = normalizeProviderId(id ?? "");
|
||||
if (!normalized || isBlockedObjectKey(normalized)) {
|
||||
return undefined;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function isSafeVideoGenerationProviderId(id: string | undefined): id is string {
|
||||
return Boolean(id && !UNSAFE_PROVIDER_IDS.has(id));
|
||||
}
|
||||
|
||||
function resolvePluginVideoGenerationProviders(
|
||||
cfg?: OpenClawConfig,
|
||||
): VideoGenerationProviderPlugin[] {
|
||||
return resolvePluginCapabilityProviders({
|
||||
key: "videoGenerationProviders",
|
||||
cfg,
|
||||
});
|
||||
}
|
||||
|
||||
function buildProviderMaps(cfg?: OpenClawConfig): {
|
||||
canonical: Map<string, VideoGenerationProviderPlugin>;
|
||||
aliases: Map<string, VideoGenerationProviderPlugin>;
|
||||
} {
|
||||
const canonical = new Map<string, VideoGenerationProviderPlugin>();
|
||||
const aliases = new Map<string, VideoGenerationProviderPlugin>();
|
||||
const register = (provider: VideoGenerationProviderPlugin) => {
|
||||
const id = normalizeVideoGenerationProviderId(provider.id);
|
||||
if (!isSafeVideoGenerationProviderId(id)) {
|
||||
return;
|
||||
}
|
||||
canonical.set(id, provider);
|
||||
aliases.set(id, provider);
|
||||
for (const alias of provider.aliases ?? []) {
|
||||
const normalizedAlias = normalizeVideoGenerationProviderId(alias);
|
||||
if (isSafeVideoGenerationProviderId(normalizedAlias)) {
|
||||
aliases.set(normalizedAlias, provider);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (const provider of BUILTIN_VIDEO_GENERATION_PROVIDERS) {
|
||||
register(provider);
|
||||
}
|
||||
for (const provider of resolvePluginVideoGenerationProviders(cfg)) {
|
||||
register(provider);
|
||||
}
|
||||
|
||||
return { canonical, aliases };
|
||||
}
|
||||
|
||||
export function listVideoGenerationProviders(
|
||||
cfg?: OpenClawConfig,
|
||||
): VideoGenerationProviderPlugin[] {
|
||||
return [...buildProviderMaps(cfg).canonical.values()];
|
||||
}
|
||||
|
||||
export function getVideoGenerationProvider(
|
||||
providerId: string | undefined,
|
||||
cfg?: OpenClawConfig,
|
||||
): VideoGenerationProviderPlugin | undefined {
|
||||
const normalized = normalizeVideoGenerationProviderId(providerId);
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
return buildProviderMaps(cfg).aliases.get(normalized);
|
||||
}
|
||||
@ -0,0 +1,72 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
import {
|
||||
generateVideo,
|
||||
listRuntimeVideoGenerationProviders,
|
||||
type GenerateVideoRuntimeResult,
|
||||
} from "../plugin-sdk/video-generation-runtime.js";
|
||||
import type { VideoGenerationProvider } from "../video-generation/types.js";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
generateVideo: vi.fn<typeof generateVideo>(),
|
||||
listRuntimeVideoGenerationProviders: vi.fn<typeof listRuntimeVideoGenerationProviders>(),
|
||||
}));
|
||||
|
||||
vi.mock("../plugin-sdk/video-generation-runtime.js", () => ({
|
||||
generateVideo: mocks.generateVideo,
|
||||
listRuntimeVideoGenerationProviders: mocks.listRuntimeVideoGenerationProviders,
|
||||
}));
|
||||
|
||||
describe("video-generation runtime facade", () => {
|
||||
afterEach(() => {
|
||||
mocks.generateVideo.mockReset();
|
||||
mocks.listRuntimeVideoGenerationProviders.mockReset();
|
||||
});
|
||||
|
||||
it("delegates video generation to the plugin-sdk runtime", async () => {
|
||||
const result: GenerateVideoRuntimeResult = {
|
||||
videos: [{ buffer: Buffer.from("mp4-bytes"), mimeType: "video/mp4", fileName: "sample.mp4" }],
|
||||
provider: "video-plugin",
|
||||
model: "vid-v1",
|
||||
attempts: [],
|
||||
};
|
||||
mocks.generateVideo.mockResolvedValue(result);
|
||||
const params = {
|
||||
cfg: {
|
||||
agents: {
|
||||
defaults: {
|
||||
videoGenerationModel: { primary: "video-plugin/vid-v1" },
|
||||
},
|
||||
},
|
||||
} as OpenClawConfig,
|
||||
prompt: "animate a cat",
|
||||
agentDir: "/tmp/agent",
|
||||
authStore: { version: 1, profiles: {} },
|
||||
};
|
||||
|
||||
await expect(generateVideo(params)).resolves.toBe(result);
|
||||
expect(mocks.generateVideo).toHaveBeenCalledWith(params);
|
||||
});
|
||||
|
||||
it("delegates provider listing to the plugin-sdk runtime", () => {
|
||||
const providers: VideoGenerationProvider[] = [
|
||||
{
|
||||
id: "video-plugin",
|
||||
defaultModel: "vid-v1",
|
||||
models: ["vid-v1", "vid-v2"],
|
||||
capabilities: {
|
||||
maxDurationSeconds: 10,
|
||||
supportsAudio: true,
|
||||
},
|
||||
generateVideo: async () => ({
|
||||
videos: [{ buffer: Buffer.from("mp4-bytes"), mimeType: "video/mp4" }],
|
||||
}),
|
||||
},
|
||||
];
|
||||
mocks.listRuntimeVideoGenerationProviders.mockReturnValue(providers);
|
||||
const params = { config: {} as OpenClawConfig };
|
||||
|
||||
expect(listRuntimeVideoGenerationProviders(params)).toBe(providers);
|
||||
expect(mocks.listRuntimeVideoGenerationProviders).toHaveBeenCalledWith(params);
|
||||
});
|
||||
});
|
||||
@ -0,0 +1,6 @@
|
||||
export {
|
||||
generateVideo,
|
||||
listRuntimeVideoGenerationProviders,
|
||||
type GenerateVideoParams,
|
||||
type GenerateVideoRuntimeResult,
|
||||
} from "../plugin-sdk/video-generation-runtime.js";
|
||||
@ -0,0 +1,65 @@
|
||||
import type { AuthProfileStore } from "../agents/auth-profiles.js";
|
||||
import type { OpenClawConfig } from "../config/config.js";
|
||||
|
||||
export type GeneratedVideoAsset = {
|
||||
buffer: Buffer;
|
||||
mimeType: string;
|
||||
fileName?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type VideoGenerationResolution = "480P" | "720P" | "1080P";
|
||||
|
||||
export type VideoGenerationSourceAsset = {
|
||||
url?: string;
|
||||
buffer?: Buffer;
|
||||
mimeType?: string;
|
||||
fileName?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type VideoGenerationRequest = {
|
||||
provider: string;
|
||||
model: string;
|
||||
prompt: string;
|
||||
cfg: OpenClawConfig;
|
||||
agentDir?: string;
|
||||
authStore?: AuthProfileStore;
|
||||
timeoutMs?: number;
|
||||
size?: string;
|
||||
aspectRatio?: string;
|
||||
resolution?: VideoGenerationResolution;
|
||||
durationSeconds?: number;
|
||||
audio?: boolean;
|
||||
watermark?: boolean;
|
||||
inputImages?: VideoGenerationSourceAsset[];
|
||||
inputVideos?: VideoGenerationSourceAsset[];
|
||||
};
|
||||
|
||||
export type VideoGenerationResult = {
|
||||
videos: GeneratedVideoAsset[];
|
||||
model?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type VideoGenerationProviderCapabilities = {
|
||||
maxVideos?: number;
|
||||
maxInputImages?: number;
|
||||
maxInputVideos?: number;
|
||||
maxDurationSeconds?: number;
|
||||
supportsSize?: boolean;
|
||||
supportsAspectRatio?: boolean;
|
||||
supportsResolution?: boolean;
|
||||
supportsAudio?: boolean;
|
||||
supportsWatermark?: boolean;
|
||||
};
|
||||
|
||||
export type VideoGenerationProvider = {
|
||||
id: string;
|
||||
aliases?: string[];
|
||||
label?: string;
|
||||
defaultModel?: string;
|
||||
models?: string[];
|
||||
capabilities: VideoGenerationProviderCapabilities;
|
||||
generateVideo: (req: VideoGenerationRequest) => Promise<VideoGenerationResult>;
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue