Vendor OpenClaw source as Adolf fork baseline
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
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
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
This commit is contained in:
11
extensions/byteplus/api.ts
Normal file
11
extensions/byteplus/api.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Public BytePlus provider plugin API exports.
|
||||
*/
|
||||
export { buildBytePlusCodingProvider, buildBytePlusProvider } from "./provider-catalog.js";
|
||||
export {
|
||||
buildBytePlusModelDefinition,
|
||||
BYTEPLUS_BASE_URL,
|
||||
BYTEPLUS_CODING_BASE_URL,
|
||||
BYTEPLUS_CODING_MODEL_CATALOG,
|
||||
BYTEPLUS_MODEL_CATALOG,
|
||||
} from "./models.js";
|
||||
61
extensions/byteplus/index.test.ts
Normal file
61
extensions/byteplus/index.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// Byteplus tests cover index plugin behavior.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { registerSingleProviderPlugin } from "openclaw/plugin-sdk/plugin-test-runtime";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import plugin from "./index.js";
|
||||
import { BYTEPLUS_CODING_MODEL_CATALOG, BYTEPLUS_MODEL_CATALOG } from "./models.js";
|
||||
|
||||
describe("byteplus plugin", () => {
|
||||
it("augments the catalog with bundled standard and plan models", async () => {
|
||||
const provider = await registerSingleProviderPlugin(plugin);
|
||||
const entries = await provider.augmentModelCatalog?.({
|
||||
env: process.env,
|
||||
entries: [],
|
||||
} as never);
|
||||
|
||||
const standardEntry = entries?.find(
|
||||
(entry) => entry.provider === "byteplus" && entry.id === BYTEPLUS_MODEL_CATALOG[0].id,
|
||||
);
|
||||
expect(standardEntry?.name).toBe(BYTEPLUS_MODEL_CATALOG[0].name);
|
||||
expect(standardEntry?.reasoning).toBe(BYTEPLUS_MODEL_CATALOG[0].reasoning);
|
||||
expect(standardEntry?.input).toEqual([...BYTEPLUS_MODEL_CATALOG[0].input]);
|
||||
expect(standardEntry?.contextWindow).toBe(BYTEPLUS_MODEL_CATALOG[0].contextWindow);
|
||||
|
||||
const planEntry = entries?.find(
|
||||
(entry) =>
|
||||
entry.provider === "byteplus-plan" && entry.id === BYTEPLUS_CODING_MODEL_CATALOG[0].id,
|
||||
);
|
||||
expect(planEntry?.name).toBe(BYTEPLUS_CODING_MODEL_CATALOG[0].name);
|
||||
expect(planEntry?.reasoning).toBe(BYTEPLUS_CODING_MODEL_CATALOG[0].reasoning);
|
||||
expect(planEntry?.input).toEqual([...BYTEPLUS_CODING_MODEL_CATALOG[0].input]);
|
||||
expect(planEntry?.contextWindow).toBe(BYTEPLUS_CODING_MODEL_CATALOG[0].contextWindow);
|
||||
});
|
||||
|
||||
it("declares its coding provider auth alias in the manifest", () => {
|
||||
const pluginJson = JSON.parse(
|
||||
readFileSync(resolve(import.meta.dirname, "openclaw.plugin.json"), "utf-8"),
|
||||
);
|
||||
|
||||
expect(pluginJson.providerAuthAliases).toEqual({
|
||||
"byteplus-plan": "byteplus",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps Kimi catalog metadata aligned with provider capabilities", () => {
|
||||
const standardKimi = BYTEPLUS_MODEL_CATALOG.find((entry) => entry.id === "kimi-k2-5-260127");
|
||||
const planKimi = BYTEPLUS_CODING_MODEL_CATALOG.find((entry) => entry.id === "kimi-k2.5");
|
||||
const thinkingKimi = BYTEPLUS_CODING_MODEL_CATALOG.find(
|
||||
(entry) => entry.id === "kimi-k2-thinking",
|
||||
);
|
||||
|
||||
for (const entry of [standardKimi, planKimi, thinkingKimi]) {
|
||||
expect(entry?.reasoning).toBe(true);
|
||||
expect(entry?.maxTokens).toBe(32768);
|
||||
expect(entry?.cost?.input).toBe(0.6);
|
||||
expect(entry?.cost?.output).toBe(2.5);
|
||||
expect(entry?.cost?.cacheRead).toBe(0.12);
|
||||
expect(entry?.cost?.cacheWrite).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
80
extensions/byteplus/index.ts
Normal file
80
extensions/byteplus/index.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* BytePlus provider plugin entrypoint for model and video generation providers.
|
||||
*/
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { createProviderApiKeyAuthMethod } from "openclaw/plugin-sdk/provider-auth-api-key";
|
||||
import { ensureModelAllowlistEntry } from "openclaw/plugin-sdk/provider-onboard";
|
||||
import { BYTEPLUS_PROVIDER_CATALOG_ENTRIES } from "./provider-catalog.js";
|
||||
import { buildBytePlusVideoGenerationProvider } from "./video-generation-provider.js";
|
||||
|
||||
const PROVIDER_ID = "byteplus";
|
||||
const BYTEPLUS_DEFAULT_MODEL_REF = "byteplus-plan/ark-code-latest";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: PROVIDER_ID,
|
||||
name: "BytePlus Provider",
|
||||
description: "Bundled BytePlus provider plugin",
|
||||
register(api) {
|
||||
api.registerProvider({
|
||||
id: PROVIDER_ID,
|
||||
label: "BytePlus",
|
||||
docsPath: "/concepts/model-providers#byteplus-international",
|
||||
envVars: ["BYTEPLUS_API_KEY"],
|
||||
auth: [
|
||||
createProviderApiKeyAuthMethod({
|
||||
providerId: PROVIDER_ID,
|
||||
methodId: "api-key",
|
||||
label: "BytePlus API key",
|
||||
hint: "API key",
|
||||
optionKey: "byteplusApiKey",
|
||||
flagName: "--byteplus-api-key",
|
||||
envVar: "BYTEPLUS_API_KEY",
|
||||
promptMessage: "Enter BytePlus API key",
|
||||
defaultModel: BYTEPLUS_DEFAULT_MODEL_REF,
|
||||
expectedProviders: ["byteplus"],
|
||||
applyConfig: (cfg) =>
|
||||
ensureModelAllowlistEntry({
|
||||
cfg,
|
||||
modelRef: BYTEPLUS_DEFAULT_MODEL_REF,
|
||||
}),
|
||||
wizard: {
|
||||
choiceId: "byteplus-api-key",
|
||||
choiceLabel: "BytePlus API key",
|
||||
groupId: "byteplus",
|
||||
groupLabel: "BytePlus",
|
||||
groupHint: "API key",
|
||||
},
|
||||
}),
|
||||
],
|
||||
catalog: {
|
||||
order: "paired",
|
||||
run: async (ctx) => {
|
||||
const apiKey = ctx.resolveProviderApiKey(PROVIDER_ID).apiKey;
|
||||
if (!apiKey) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
providers: Object.fromEntries(
|
||||
BYTEPLUS_PROVIDER_CATALOG_ENTRIES.map(({ id, buildProvider }) => [
|
||||
id,
|
||||
{ ...buildProvider(), apiKey },
|
||||
]),
|
||||
),
|
||||
};
|
||||
},
|
||||
},
|
||||
augmentModelCatalog: () =>
|
||||
BYTEPLUS_PROVIDER_CATALOG_ENTRIES.flatMap(({ id: provider, models }) =>
|
||||
models.map((entry) => ({
|
||||
provider,
|
||||
id: entry.id,
|
||||
name: entry.name,
|
||||
reasoning: entry.reasoning,
|
||||
input: [...entry.input],
|
||||
contextWindow: entry.contextWindow,
|
||||
})),
|
||||
),
|
||||
});
|
||||
api.registerVideoGenerationProvider(buildBytePlusVideoGenerationProvider());
|
||||
},
|
||||
});
|
||||
61
extensions/byteplus/live.test.ts
Normal file
61
extensions/byteplus/live.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
// Byteplus tests cover live plugin behavior.
|
||||
import { completeSimple, type Model } from "openclaw/plugin-sdk/llm";
|
||||
import {
|
||||
createSingleUserPromptMessage,
|
||||
extractNonEmptyAssistantText,
|
||||
isLiveTestEnabled,
|
||||
} from "openclaw/plugin-sdk/test-env";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BYTEPLUS_CODING_BASE_URL } from "./models.js";
|
||||
|
||||
const BYTEPLUS_KEY = process.env.BYTEPLUS_API_KEY ?? "";
|
||||
const BYTEPLUS_CODING_MODEL = process.env.BYTEPLUS_CODING_MODEL?.trim() || "ark-code-latest";
|
||||
const LIVE = isLiveTestEnabled(["BYTEPLUS_LIVE_TEST"]);
|
||||
|
||||
const describeLive = LIVE && BYTEPLUS_KEY ? describe : describe.skip;
|
||||
|
||||
function isBytePlusSubscriptionError(message: string): boolean {
|
||||
const lower = message.toLowerCase();
|
||||
return (
|
||||
lower.includes("coding plan subscription") ||
|
||||
lower.includes("subscription has expired") ||
|
||||
(lower.includes("subscription") && lower.includes("renewal"))
|
||||
);
|
||||
}
|
||||
|
||||
describeLive("byteplus coding plan live", () => {
|
||||
it("returns assistant text", async () => {
|
||||
const model: Model<"openai-completions"> = {
|
||||
id: BYTEPLUS_CODING_MODEL,
|
||||
name: `BytePlus Coding ${BYTEPLUS_CODING_MODEL}`,
|
||||
api: "openai-completions",
|
||||
provider: "byteplus-plan",
|
||||
baseUrl: BYTEPLUS_CODING_BASE_URL,
|
||||
reasoning: false,
|
||||
input: ["text"],
|
||||
cost: { input: 0.0001, output: 0.0002, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 256000,
|
||||
maxTokens: 4096,
|
||||
};
|
||||
|
||||
const res = await completeSimple(
|
||||
model,
|
||||
{
|
||||
messages: createSingleUserPromptMessage(),
|
||||
},
|
||||
{ apiKey: BYTEPLUS_KEY, maxTokens: 64 },
|
||||
);
|
||||
|
||||
if (res.stopReason === "error") {
|
||||
const message = res.errorMessage ?? "";
|
||||
if (isBytePlusSubscriptionError(message)) {
|
||||
expect(message.toLowerCase()).toContain("subscription");
|
||||
return;
|
||||
}
|
||||
throw new Error(message || "byteplus returned error with no message");
|
||||
}
|
||||
|
||||
const text = extractNonEmptyAssistantText(res.content);
|
||||
expect(text.length).toBeGreaterThan(0);
|
||||
}, 30000);
|
||||
});
|
||||
36
extensions/byteplus/models.ts
Normal file
36
extensions/byteplus/models.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* BytePlus model catalog helpers derived from the plugin manifest.
|
||||
*/
|
||||
import { buildManifestModelProviderConfig } from "openclaw/plugin-sdk/provider-catalog-shared";
|
||||
import type { ModelDefinitionConfig } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
import manifest from "./openclaw.plugin.json" with { type: "json" };
|
||||
|
||||
const BYTEPLUS_MANIFEST_PROVIDER = buildManifestModelProviderConfig({
|
||||
providerId: "byteplus",
|
||||
catalog: manifest.modelCatalog.providers.byteplus,
|
||||
});
|
||||
|
||||
const BYTEPLUS_CODING_MANIFEST_PROVIDER = buildManifestModelProviderConfig({
|
||||
providerId: "byteplus-plan",
|
||||
catalog: manifest.modelCatalog.providers["byteplus-plan"],
|
||||
});
|
||||
|
||||
/** Base URL for BytePlus chat/model APIs from the manifest catalog. */
|
||||
export const BYTEPLUS_BASE_URL = BYTEPLUS_MANIFEST_PROVIDER.baseUrl;
|
||||
/** Base URL for BytePlus Plan coding APIs from the manifest catalog. */
|
||||
export const BYTEPLUS_CODING_BASE_URL = BYTEPLUS_CODING_MANIFEST_PROVIDER.baseUrl;
|
||||
|
||||
/** BytePlus general model catalog entries. */
|
||||
export const BYTEPLUS_MODEL_CATALOG: ModelDefinitionConfig[] = BYTEPLUS_MANIFEST_PROVIDER.models;
|
||||
/** BytePlus coding/planning model catalog entries. */
|
||||
export const BYTEPLUS_CODING_MODEL_CATALOG: ModelDefinitionConfig[] =
|
||||
BYTEPLUS_CODING_MANIFEST_PROVIDER.models;
|
||||
|
||||
/** Clones one manifest model definition so callers can mutate safely. */
|
||||
export function buildBytePlusModelDefinition(entry: ModelDefinitionConfig): ModelDefinitionConfig {
|
||||
return {
|
||||
...entry,
|
||||
input: [...entry.input],
|
||||
cost: { ...entry.cost },
|
||||
};
|
||||
}
|
||||
170
extensions/byteplus/openclaw.plugin.json
Normal file
170
extensions/byteplus/openclaw.plugin.json
Normal file
@@ -0,0 +1,170 @@
|
||||
{
|
||||
"id": "byteplus",
|
||||
"activation": {
|
||||
"onStartup": false
|
||||
},
|
||||
"enabledByDefault": true,
|
||||
"providerCatalogEntry": "./provider-discovery.ts",
|
||||
"providers": ["byteplus", "byteplus-plan"],
|
||||
"setup": {
|
||||
"providers": [
|
||||
{
|
||||
"id": "byteplus",
|
||||
"envVars": ["BYTEPLUS_API_KEY"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"providerAuthAliases": {
|
||||
"byteplus-plan": "byteplus"
|
||||
},
|
||||
"modelCatalog": {
|
||||
"providers": {
|
||||
"byteplus": {
|
||||
"baseUrl": "https://ark.ap-southeast.bytepluses.com/api/v3",
|
||||
"api": "openai-completions",
|
||||
"models": [
|
||||
{
|
||||
"id": "seed-1-8-251228",
|
||||
"name": "Seed 1.8",
|
||||
"input": ["text", "image"],
|
||||
"contextWindow": 256000,
|
||||
"maxTokens": 4096,
|
||||
"cost": {
|
||||
"input": 0.0001,
|
||||
"output": 0.0002,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kimi-k2-5-260127",
|
||||
"name": "Kimi K2.5",
|
||||
"reasoning": true,
|
||||
"input": ["text", "image"],
|
||||
"contextWindow": 256000,
|
||||
"maxTokens": 32768,
|
||||
"cost": {
|
||||
"input": 0.6,
|
||||
"output": 2.5,
|
||||
"cacheRead": 0.12,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "glm-4-7-251222",
|
||||
"name": "GLM 4.7",
|
||||
"input": ["text", "image"],
|
||||
"contextWindow": 200000,
|
||||
"maxTokens": 4096,
|
||||
"cost": {
|
||||
"input": 0.0001,
|
||||
"output": 0.0002,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"byteplus-plan": {
|
||||
"baseUrl": "https://ark.ap-southeast.bytepluses.com/api/coding/v3",
|
||||
"api": "openai-completions",
|
||||
"models": [
|
||||
{
|
||||
"id": "ark-code-latest",
|
||||
"name": "Ark Coding Plan",
|
||||
"input": ["text"],
|
||||
"contextWindow": 256000,
|
||||
"maxTokens": 4096,
|
||||
"cost": {
|
||||
"input": 0.0001,
|
||||
"output": 0.0002,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "doubao-seed-code",
|
||||
"name": "Doubao Seed Code",
|
||||
"input": ["text"],
|
||||
"contextWindow": 256000,
|
||||
"maxTokens": 4096,
|
||||
"cost": {
|
||||
"input": 0.0001,
|
||||
"output": 0.0002,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "glm-4.7",
|
||||
"name": "GLM 4.7 Coding",
|
||||
"input": ["text"],
|
||||
"contextWindow": 200000,
|
||||
"maxTokens": 4096,
|
||||
"cost": {
|
||||
"input": 0.0001,
|
||||
"output": 0.0002,
|
||||
"cacheRead": 0,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kimi-k2-thinking",
|
||||
"name": "Kimi K2 Thinking",
|
||||
"reasoning": true,
|
||||
"input": ["text"],
|
||||
"contextWindow": 256000,
|
||||
"maxTokens": 32768,
|
||||
"cost": {
|
||||
"input": 0.6,
|
||||
"output": 2.5,
|
||||
"cacheRead": 0.12,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "kimi-k2.5",
|
||||
"name": "Kimi K2.5 Coding",
|
||||
"reasoning": true,
|
||||
"input": ["text"],
|
||||
"contextWindow": 256000,
|
||||
"maxTokens": 32768,
|
||||
"cost": {
|
||||
"input": 0.6,
|
||||
"output": 2.5,
|
||||
"cacheRead": 0.12,
|
||||
"cacheWrite": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"discovery": {
|
||||
"byteplus": "static",
|
||||
"byteplus-plan": "static"
|
||||
}
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "byteplus",
|
||||
"method": "api-key",
|
||||
"choiceId": "byteplus-api-key",
|
||||
"choiceLabel": "BytePlus API key",
|
||||
"groupId": "byteplus",
|
||||
"groupLabel": "BytePlus",
|
||||
"groupHint": "API key",
|
||||
"optionKey": "byteplusApiKey",
|
||||
"cliFlag": "--byteplus-api-key",
|
||||
"cliOption": "--byteplus-api-key <key>",
|
||||
"cliDescription": "BytePlus API key"
|
||||
}
|
||||
],
|
||||
"contracts": {
|
||||
"videoGenerationProviders": ["byteplus"]
|
||||
},
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
15
extensions/byteplus/package.json
Normal file
15
extensions/byteplus/package.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "@openclaw/byteplus-provider",
|
||||
"version": "2026.6.11",
|
||||
"private": true,
|
||||
"description": "OpenClaw BytePlus provider plugin",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@openclaw/plugin-sdk": "workspace:*"
|
||||
},
|
||||
"openclaw": {
|
||||
"extensions": [
|
||||
"./index.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
38
extensions/byteplus/provider-catalog.ts
Normal file
38
extensions/byteplus/provider-catalog.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* BytePlus model provider builders backed by the plugin manifest catalog.
|
||||
*/
|
||||
import { buildManifestModelProviderConfig } from "openclaw/plugin-sdk/provider-catalog-shared";
|
||||
import type { ModelProviderConfig } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
import { BYTEPLUS_CODING_MODEL_CATALOG, BYTEPLUS_MODEL_CATALOG } from "./models.js";
|
||||
import manifest from "./openclaw.plugin.json" with { type: "json" };
|
||||
|
||||
/** Builds the standard BytePlus model provider config. */
|
||||
export function buildBytePlusProvider(): ModelProviderConfig {
|
||||
return buildManifestModelProviderConfig({
|
||||
providerId: "byteplus",
|
||||
catalog: manifest.modelCatalog.providers.byteplus,
|
||||
});
|
||||
}
|
||||
|
||||
/** Builds the BytePlus Plan coding-provider config. */
|
||||
export function buildBytePlusCodingProvider(): ModelProviderConfig {
|
||||
return buildManifestModelProviderConfig({
|
||||
providerId: "byteplus-plan",
|
||||
catalog: manifest.modelCatalog.providers["byteplus-plan"],
|
||||
});
|
||||
}
|
||||
|
||||
export const BYTEPLUS_PROVIDER_CATALOG_ENTRIES = [
|
||||
{
|
||||
id: "byteplus",
|
||||
label: "BytePlus",
|
||||
models: BYTEPLUS_MODEL_CATALOG,
|
||||
buildProvider: buildBytePlusProvider,
|
||||
},
|
||||
{
|
||||
id: "byteplus-plan",
|
||||
label: "BytePlus Plan",
|
||||
models: BYTEPLUS_CODING_MODEL_CATALOG,
|
||||
buildProvider: buildBytePlusCodingProvider,
|
||||
},
|
||||
] as const;
|
||||
22
extensions/byteplus/provider-discovery.ts
Normal file
22
extensions/byteplus/provider-discovery.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Static provider discovery entries for BytePlus manifest-backed catalogs.
|
||||
*/
|
||||
import type { ProviderPlugin } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
import { BYTEPLUS_PROVIDER_CATALOG_ENTRIES } from "./provider-catalog.js";
|
||||
|
||||
const bytePlusProviderDiscovery: ProviderPlugin[] = BYTEPLUS_PROVIDER_CATALOG_ENTRIES.map(
|
||||
({ id, label, buildProvider }) => ({
|
||||
id,
|
||||
label,
|
||||
docsPath: "/providers/models",
|
||||
auth: [],
|
||||
staticCatalog: {
|
||||
order: "simple",
|
||||
run: async () => ({
|
||||
provider: buildProvider(),
|
||||
}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
export default bytePlusProviderDiscovery;
|
||||
16
extensions/byteplus/tsconfig.json
Normal file
16
extensions/byteplus/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "../tsconfig.package-boundary.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": ["./*.ts", "./src/**/*.ts"],
|
||||
"exclude": [
|
||||
"./**/*.test.ts",
|
||||
"./dist/**",
|
||||
"./node_modules/**",
|
||||
"./src/test-support/**",
|
||||
"./src/**/*test-helpers.ts",
|
||||
"./src/**/*test-harness.ts",
|
||||
"./src/**/*test-support.ts"
|
||||
]
|
||||
}
|
||||
494
extensions/byteplus/video-generation-provider.test.ts
Normal file
494
extensions/byteplus/video-generation-provider.test.ts
Normal file
@@ -0,0 +1,494 @@
|
||||
// Byteplus tests cover video generation provider plugin behavior.
|
||||
import { expectExplicitVideoGenerationCapabilities } from "openclaw/plugin-sdk/provider-test-contracts";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Submit/poll transport is mocked locally so each test can inject the BytePlus task JSON
|
||||
// bodies, while readProviderJsonResponse is kept REAL (via importActual) so the byte-bounded
|
||||
// reader actually streams and cancels oversized bodies under test instead of a stub.
|
||||
const { postJsonRequestMock, fetchWithTimeoutMock, resolveApiKeyForProviderMock } = vi.hoisted(
|
||||
() => ({
|
||||
postJsonRequestMock: vi.fn(),
|
||||
fetchWithTimeoutMock: vi.fn(),
|
||||
resolveApiKeyForProviderMock: vi.fn(async () => ({ apiKey: "provider-key" })),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("openclaw/plugin-sdk/provider-auth-runtime", () => ({
|
||||
resolveApiKeyForProvider: resolveApiKeyForProviderMock,
|
||||
}));
|
||||
|
||||
vi.mock("openclaw/plugin-sdk/provider-http", async (importActual) => {
|
||||
const actual = await importActual<typeof import("openclaw/plugin-sdk/provider-http")>();
|
||||
const resolveTimeoutMs = (timeoutMs: unknown): number =>
|
||||
typeof timeoutMs === "function" ? (timeoutMs() as number) : ((timeoutMs as number) ?? 60_000);
|
||||
return {
|
||||
// REAL byte-bounded JSON reader under test — not stubbed.
|
||||
readProviderJsonResponse: actual.readProviderJsonResponse,
|
||||
postJsonRequest: postJsonRequestMock,
|
||||
fetchProviderOperationResponse: async (params: {
|
||||
url: string;
|
||||
init?: RequestInit;
|
||||
timeoutMs?: unknown;
|
||||
fetchFn: typeof fetch;
|
||||
}) => fetchWithTimeoutMock(params.url, params.init ?? {}, resolveTimeoutMs(params.timeoutMs)),
|
||||
fetchProviderDownloadResponse: async (params: {
|
||||
url: string;
|
||||
init?: RequestInit;
|
||||
timeoutMs?: unknown;
|
||||
fetchFn: typeof fetch;
|
||||
}) => fetchWithTimeoutMock(params.url, params.init ?? {}, resolveTimeoutMs(params.timeoutMs)),
|
||||
assertOkOrThrowHttpError: async () => {},
|
||||
createProviderOperationDeadline: ({
|
||||
label,
|
||||
timeoutMs,
|
||||
}: {
|
||||
label: string;
|
||||
timeoutMs?: number;
|
||||
}) => ({ label, timeoutMs }),
|
||||
createProviderOperationTimeoutResolver:
|
||||
({ defaultTimeoutMs }: { defaultTimeoutMs: number }) =>
|
||||
() =>
|
||||
defaultTimeoutMs,
|
||||
resolveProviderOperationTimeoutMs: ({ defaultTimeoutMs }: { defaultTimeoutMs: number }) =>
|
||||
defaultTimeoutMs,
|
||||
resolveProviderHttpRequestConfig: (params: {
|
||||
baseUrl?: string;
|
||||
defaultBaseUrl: string;
|
||||
allowPrivateNetwork?: boolean;
|
||||
defaultHeaders?: Record<string, string>;
|
||||
}) => ({
|
||||
baseUrl: params.baseUrl ?? params.defaultBaseUrl,
|
||||
allowPrivateNetwork: params.allowPrivateNetwork === true,
|
||||
headers: new Headers(params.defaultHeaders),
|
||||
dispatcherPolicy: undefined,
|
||||
}),
|
||||
waitProviderOperationPollInterval: async () => {},
|
||||
};
|
||||
});
|
||||
|
||||
let buildBytePlusVideoGenerationProvider: typeof import("./video-generation-provider.js").buildBytePlusVideoGenerationProvider;
|
||||
|
||||
beforeAll(async () => {
|
||||
({ buildBytePlusVideoGenerationProvider } = await import("./video-generation-provider.js"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
postJsonRequestMock.mockReset();
|
||||
fetchWithTimeoutMock.mockReset();
|
||||
resolveApiKeyForProviderMock.mockClear();
|
||||
});
|
||||
|
||||
function mockSuccessfulBytePlusTask(params?: { model?: string }) {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: streamedJsonResponse({
|
||||
id: "task_123",
|
||||
}),
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
fetchWithTimeoutMock
|
||||
.mockResolvedValueOnce(
|
||||
streamedJsonResponse({
|
||||
id: "task_123",
|
||||
status: "succeeded",
|
||||
content: {
|
||||
video_url: "https://example.com/byteplus.mp4",
|
||||
},
|
||||
model: params?.model ?? "seedance-1-0-lite-t2v-250428",
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
headers: new Headers({ "content-type": "video/webm" }),
|
||||
arrayBuffer: async () => Buffer.from("webm-bytes"),
|
||||
});
|
||||
}
|
||||
|
||||
function requireBytePlusPostRequest(): { body?: Record<string, unknown>; url?: string } {
|
||||
const [call] = postJsonRequestMock.mock.calls;
|
||||
if (!call) {
|
||||
throw new Error("expected BytePlus video request");
|
||||
}
|
||||
const [request] = call;
|
||||
if (!request) {
|
||||
throw new Error("expected BytePlus video request");
|
||||
}
|
||||
if (typeof request !== "object" || Array.isArray(request)) {
|
||||
throw new Error("expected BytePlus video request options");
|
||||
}
|
||||
return request as { body?: Record<string, unknown>; url?: string };
|
||||
}
|
||||
|
||||
function requireBytePlusPostBody(): Record<string, unknown> {
|
||||
const request = requireBytePlusPostRequest();
|
||||
if (!request.body) {
|
||||
throw new Error("expected BytePlus video request body");
|
||||
}
|
||||
return request.body;
|
||||
}
|
||||
|
||||
function streamedVideoResponse(bytes: string): Response {
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(bytes));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ headers: { "content-type": "video/mp4" } },
|
||||
);
|
||||
}
|
||||
|
||||
// BytePlus submit/poll task JSON is now read through the byte-bounded reader, so the
|
||||
// mocked responses must expose a real readable body (not just a json() shortcut).
|
||||
function streamedJsonResponse(payload: unknown): Response {
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(JSON.stringify(payload)));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
// Builds a JSON body larger than the shared 16 MiB readProviderJsonResponse cap so the
|
||||
// bounded reader cancels the stream mid-flight; if the cap were removed the reader would
|
||||
// buffer the whole advertised payload before parsing. Tracks how many bytes were pulled
|
||||
// and whether the stream was canceled so callers can assert the body was not fully read.
|
||||
function makeOversizedJsonStream(): {
|
||||
body: ReadableStream<Uint8Array>;
|
||||
maxBytes: number;
|
||||
totalBytes: number;
|
||||
state: { bytesPulled: number; canceled: boolean };
|
||||
} {
|
||||
const maxBytes = 16 * 1024 * 1024; // matches PROVIDER_JSON_RESPONSE_MAX_BYTES.
|
||||
const ONE_MIB = 1024 * 1024;
|
||||
const TOTAL_CHUNKS = 32; // 32 MiB advertised body, double the cap.
|
||||
const chunk = new Uint8Array(ONE_MIB);
|
||||
const state = { bytesPulled: 0, canceled: false };
|
||||
let pulled = 0;
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (pulled >= TOTAL_CHUNKS) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
pulled += 1;
|
||||
state.bytesPulled += chunk.length;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
cancel() {
|
||||
state.canceled = true;
|
||||
},
|
||||
});
|
||||
return { body, maxBytes, totalBytes: TOTAL_CHUNKS * ONE_MIB, state };
|
||||
}
|
||||
|
||||
describe("byteplus video generation provider", () => {
|
||||
it("declares explicit mode capabilities", () => {
|
||||
expectExplicitVideoGenerationCapabilities(buildBytePlusVideoGenerationProvider());
|
||||
});
|
||||
|
||||
it("creates a content-generation task, polls, and downloads the video", async () => {
|
||||
mockSuccessfulBytePlusTask();
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
const result = await provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "A lantern floats upward into the night sky",
|
||||
cfg: {},
|
||||
});
|
||||
|
||||
expect(postJsonRequestMock).toHaveBeenCalledTimes(1);
|
||||
const request = requireBytePlusPostRequest();
|
||||
expect(request.url).toBe(
|
||||
"https://ark.ap-southeast.bytepluses.com/api/v3/contents/generations/tasks",
|
||||
);
|
||||
expect(result.videos).toHaveLength(1);
|
||||
const [video] = result.videos;
|
||||
if (!video) {
|
||||
throw new Error("Expected generated BytePlus video");
|
||||
}
|
||||
expect(video.fileName).toBe("video-1.webm");
|
||||
const metadata = result.metadata as Record<string, unknown>;
|
||||
expect(metadata.taskId).toBe("task_123");
|
||||
});
|
||||
|
||||
it("rejects generated video downloads that exceed the configured media cap", async () => {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: streamedJsonResponse({ id: "task_too_large" }),
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
fetchWithTimeoutMock
|
||||
.mockResolvedValueOnce(
|
||||
streamedJsonResponse({
|
||||
id: "task_too_large",
|
||||
status: "succeeded",
|
||||
content: {
|
||||
video_url: "https://example.com/too-large.mp4",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(streamedVideoResponse("too-large"));
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await expect(
|
||||
provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "short video",
|
||||
cfg: { agents: { defaults: { mediaMaxMb: 0.000001 } } },
|
||||
}),
|
||||
).rejects.toThrow("BytePlus generated video download exceeds 1 bytes");
|
||||
});
|
||||
|
||||
it("switches t2v image requests to i2v models and lowercases resolution", async () => {
|
||||
mockSuccessfulBytePlusTask({ model: "seedance-1-0-lite-i2v-250428" });
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "Animate this still image",
|
||||
resolution: "720P",
|
||||
inputImages: [{ url: "https://example.com/first-frame.png" }],
|
||||
cfg: {},
|
||||
});
|
||||
|
||||
expect(requireBytePlusPostBody()).toEqual({
|
||||
model: "seedance-1-0-lite-i2v-250428",
|
||||
resolution: "720p",
|
||||
content: [
|
||||
{ type: "text", text: "Animate this still image" },
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: { url: "https://example.com/first-frame.png" },
|
||||
role: "first_frame",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("maps declared providerOptions into the request body", async () => {
|
||||
mockSuccessfulBytePlusTask({ model: "seedance-1-0-pro-250528" });
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-pro-250528",
|
||||
prompt: "A cinematic lobster montage",
|
||||
providerOptions: {
|
||||
seed: 42,
|
||||
draft: true,
|
||||
camera_fixed: false,
|
||||
},
|
||||
cfg: {},
|
||||
});
|
||||
|
||||
const body = requireBytePlusPostBody();
|
||||
expect(body.model).toBe("seedance-1-0-pro-250528");
|
||||
expect(body.seed).toBe(42);
|
||||
expect(body.resolution).toBe("480p");
|
||||
expect(body.camera_fixed).toBe(false);
|
||||
});
|
||||
|
||||
it("drops malformed seed values before creating videos", async () => {
|
||||
mockSuccessfulBytePlusTask({ model: "seedance-1-0-pro-250528" });
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-pro-250528",
|
||||
prompt: "A cinematic lobster montage",
|
||||
providerOptions: {
|
||||
seed: 1.5,
|
||||
},
|
||||
cfg: {},
|
||||
});
|
||||
|
||||
expect(requireBytePlusPostBody()).not.toHaveProperty("seed");
|
||||
});
|
||||
|
||||
it("drops out-of-range duration values before creating videos", async () => {
|
||||
mockSuccessfulBytePlusTask({ model: "seedance-1-0-pro-250528" });
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-pro-250528",
|
||||
prompt: "A cinematic lobster montage",
|
||||
durationSeconds: 99,
|
||||
cfg: {},
|
||||
});
|
||||
|
||||
expect(requireBytePlusPostBody()).not.toHaveProperty("duration");
|
||||
});
|
||||
|
||||
it("drops malformed response duration metadata", async () => {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: streamedJsonResponse({
|
||||
id: "task_123",
|
||||
}),
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
fetchWithTimeoutMock
|
||||
.mockResolvedValueOnce(
|
||||
streamedJsonResponse({
|
||||
id: "task_123",
|
||||
status: "succeeded",
|
||||
content: {
|
||||
video_url: "https://example.com/byteplus.mp4",
|
||||
},
|
||||
duration: 1.5,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
headers: new Headers({ "content-type": "video/mp4" }),
|
||||
arrayBuffer: async () => Buffer.from("mp4-bytes"),
|
||||
});
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
const result = await provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "A lantern floats upward into the night sky",
|
||||
cfg: {},
|
||||
});
|
||||
|
||||
expect(result.metadata).toMatchObject({ duration: undefined });
|
||||
});
|
||||
|
||||
it("reports malformed create JSON with a provider-owned error", async () => {
|
||||
const release = vi.fn(async () => {});
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("{ not valid json"));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
release,
|
||||
});
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await expect(
|
||||
provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "bad create response",
|
||||
cfg: {},
|
||||
}),
|
||||
).rejects.toThrow("BytePlus video generation failed: malformed JSON response");
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects status responses missing a task status", async () => {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: streamedJsonResponse({ id: "task_missing_status" }),
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
fetchWithTimeoutMock.mockResolvedValueOnce(
|
||||
streamedJsonResponse({
|
||||
id: "task_missing_status",
|
||||
content: {
|
||||
video_url: "https://example.com/byteplus.mp4",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await expect(
|
||||
provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "missing status",
|
||||
cfg: {},
|
||||
}),
|
||||
).rejects.toThrow("BytePlus video status response missing task status");
|
||||
});
|
||||
|
||||
it("rejects malformed completed content", async () => {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: streamedJsonResponse({ id: "task_malformed_content" }),
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
fetchWithTimeoutMock.mockResolvedValueOnce(
|
||||
streamedJsonResponse({
|
||||
id: "task_malformed_content",
|
||||
status: "succeeded",
|
||||
content: ["https://example.com/byteplus.mp4"],
|
||||
}),
|
||||
);
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await expect(
|
||||
provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "malformed content",
|
||||
cfg: {},
|
||||
}),
|
||||
).rejects.toThrow("BytePlus video generation completed with malformed content");
|
||||
});
|
||||
|
||||
it("bounds the submit task JSON body and cancels an oversized stream", async () => {
|
||||
const stream = makeOversizedJsonStream();
|
||||
const release = vi.fn(async () => {});
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: new Response(stream.body, {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
release,
|
||||
});
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await expect(
|
||||
provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "oversized submit response",
|
||||
cfg: {},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
`BytePlus video generation failed: JSON response exceeds ${stream.maxBytes} bytes`,
|
||||
);
|
||||
expect(stream.state.canceled).toBe(true);
|
||||
// Only the bounded prefix is pulled, never the full advertised stream.
|
||||
expect(stream.state.bytesPulled).toBeLessThan(stream.totalBytes);
|
||||
// The submit request must still be released even though the body overflowed.
|
||||
expect(release).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("bounds the poll status JSON body and cancels an oversized stream", async () => {
|
||||
postJsonRequestMock.mockResolvedValue({
|
||||
response: streamedJsonResponse({ id: "task_oversized_poll" }),
|
||||
release: vi.fn(async () => {}),
|
||||
});
|
||||
const stream = makeOversizedJsonStream();
|
||||
fetchWithTimeoutMock.mockResolvedValueOnce(
|
||||
new Response(stream.body, {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
);
|
||||
|
||||
const provider = buildBytePlusVideoGenerationProvider();
|
||||
await expect(
|
||||
provider.generateVideo({
|
||||
provider: "byteplus",
|
||||
model: "seedance-1-0-lite-t2v-250428",
|
||||
prompt: "oversized poll response",
|
||||
cfg: {},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
`BytePlus video status request failed: JSON response exceeds ${stream.maxBytes} bytes`,
|
||||
);
|
||||
expect(stream.state.canceled).toBe(true);
|
||||
expect(stream.state.bytesPulled).toBeLessThan(stream.totalBytes);
|
||||
});
|
||||
});
|
||||
426
extensions/byteplus/video-generation-provider.ts
Normal file
426
extensions/byteplus/video-generation-provider.ts
Normal file
@@ -0,0 +1,426 @@
|
||||
/**
|
||||
* BytePlus Seedance video generation provider implementation.
|
||||
*/
|
||||
import { toImageDataUrl } from "openclaw/plugin-sdk/image-generation";
|
||||
import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
|
||||
import { isProviderApiKeyConfigured } from "openclaw/plugin-sdk/provider-auth";
|
||||
import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
|
||||
import {
|
||||
assertOkOrThrowHttpError,
|
||||
createProviderOperationDeadline,
|
||||
createProviderOperationTimeoutResolver,
|
||||
fetchProviderDownloadResponse,
|
||||
fetchProviderOperationResponse,
|
||||
postJsonRequest,
|
||||
readProviderJsonResponse,
|
||||
resolveProviderOperationTimeoutMs,
|
||||
resolveProviderHttpRequestConfig,
|
||||
waitProviderOperationPollInterval,
|
||||
type ProviderOperationTimeoutMs,
|
||||
} from "openclaw/plugin-sdk/provider-http";
|
||||
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
|
||||
import {
|
||||
asSafeIntegerInRange,
|
||||
isRecord,
|
||||
normalizeOptionalString,
|
||||
} from "openclaw/plugin-sdk/string-coerce-runtime";
|
||||
import type {
|
||||
GeneratedVideoAsset,
|
||||
VideoGenerationProvider,
|
||||
VideoGenerationRequest,
|
||||
} from "openclaw/plugin-sdk/video-generation";
|
||||
import { BYTEPLUS_BASE_URL } from "./models.js";
|
||||
|
||||
const DEFAULT_BYTEPLUS_VIDEO_MODEL = "seedance-1-0-lite-t2v-250428";
|
||||
const DEFAULT_TIMEOUT_MS = 120_000;
|
||||
const POLL_INTERVAL_MS = 5_000;
|
||||
const MAX_POLL_ATTEMPTS = 120;
|
||||
const BYTEPLUS_SEED_MAX = 2_147_483_647;
|
||||
const BYTEPLUS_MIN_DURATION_SECONDS = 2;
|
||||
const BYTEPLUS_MAX_DURATION_SECONDS = 12;
|
||||
const DEFAULT_GENERATED_VIDEO_MAX_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
type BytePlusTaskCreateResponse = {
|
||||
id?: unknown;
|
||||
};
|
||||
|
||||
type BytePlusTaskResponse = {
|
||||
id?: unknown;
|
||||
model?: unknown;
|
||||
status?: unknown;
|
||||
error?: unknown;
|
||||
content?: unknown;
|
||||
duration?: unknown;
|
||||
ratio?: unknown;
|
||||
resolution?: unknown;
|
||||
};
|
||||
|
||||
type BytePlusTaskStatus = "running" | "failed" | "queued" | "succeeded" | "cancelled";
|
||||
|
||||
async function readBytePlusJsonResponse<T>(response: Response, label: string): Promise<T> {
|
||||
// BytePlus submit/poll task bodies are read through the shared byte-bounded reader
|
||||
// (readResponseWithLimit, via readProviderJsonResponse) so a hostile or buggy endpoint
|
||||
// that streams an unbounded JSON body cannot force the runtime to buffer the whole
|
||||
// payload before parsing. Overflow cancels the stream and throws a bounded error;
|
||||
// malformed JSON keeps the existing `${label}: malformed JSON response` wrapping.
|
||||
const payload = await readProviderJsonResponse<unknown>(response, label);
|
||||
if (!isRecord(payload)) {
|
||||
throw new Error(`${label}: malformed JSON response`);
|
||||
}
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
function readBytePlusTaskStatus(payload: BytePlusTaskResponse): BytePlusTaskStatus {
|
||||
const status = normalizeOptionalString(payload.status);
|
||||
switch (status) {
|
||||
case "running":
|
||||
case "failed":
|
||||
case "queued":
|
||||
case "succeeded":
|
||||
case "cancelled":
|
||||
return status;
|
||||
case undefined:
|
||||
throw new Error("BytePlus video status response missing task status");
|
||||
default:
|
||||
throw new Error(`BytePlus video status response returned unknown task status: ${status}`);
|
||||
}
|
||||
}
|
||||
|
||||
function readBytePlusErrorMessage(error: unknown): string | undefined {
|
||||
return isRecord(error) ? normalizeOptionalString(error.message) : undefined;
|
||||
}
|
||||
|
||||
function readBytePlusVideoUrl(payload: BytePlusTaskResponse): string {
|
||||
const content = payload.content;
|
||||
if (content !== undefined && !isRecord(content)) {
|
||||
throw new Error("BytePlus video generation completed with malformed content");
|
||||
}
|
||||
const videoUrl = normalizeOptionalString(content?.video_url);
|
||||
if (!videoUrl) {
|
||||
throw new Error("BytePlus video generation completed without a video URL");
|
||||
}
|
||||
return videoUrl;
|
||||
}
|
||||
|
||||
function resolveBytePlusVideoBaseUrl(req: VideoGenerationRequest): string {
|
||||
return (
|
||||
normalizeOptionalString(req.cfg?.models?.providers?.byteplus?.baseUrl) ?? BYTEPLUS_BASE_URL
|
||||
);
|
||||
}
|
||||
|
||||
function resolveGeneratedVideoMaxBytes(req: VideoGenerationRequest): number {
|
||||
const configured = req.cfg.agents?.defaults?.mediaMaxMb;
|
||||
if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
|
||||
return Math.floor(configured * 1024 * 1024);
|
||||
}
|
||||
return DEFAULT_GENERATED_VIDEO_MAX_BYTES;
|
||||
}
|
||||
|
||||
function resolveBytePlusImageUrl(req: VideoGenerationRequest): string | undefined {
|
||||
const input = req.inputImages?.[0];
|
||||
if (!input) {
|
||||
return undefined;
|
||||
}
|
||||
const inputUrl = normalizeOptionalString(input.url);
|
||||
if (inputUrl) {
|
||||
return inputUrl;
|
||||
}
|
||||
if (!input.buffer) {
|
||||
throw new Error("BytePlus reference image is missing image data.");
|
||||
}
|
||||
return toImageDataUrl({ ...input, buffer: input.buffer, defaultMimeType: "image/png" });
|
||||
}
|
||||
|
||||
function resolveBytePlusSeed(value: unknown): number | undefined {
|
||||
return asSafeIntegerInRange(value, { min: -1, max: BYTEPLUS_SEED_MAX });
|
||||
}
|
||||
|
||||
function resolveBytePlusDurationSeconds(value: unknown): number | undefined {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return asSafeIntegerInRange(Math.round(value), {
|
||||
min: BYTEPLUS_MIN_DURATION_SECONDS,
|
||||
max: BYTEPLUS_MAX_DURATION_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
function readBytePlusDurationSeconds(value: unknown): number | undefined {
|
||||
return asSafeIntegerInRange(value, {
|
||||
min: BYTEPLUS_MIN_DURATION_SECONDS,
|
||||
max: BYTEPLUS_MAX_DURATION_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
async function pollBytePlusTask(params: {
|
||||
taskId: string;
|
||||
headers: Headers;
|
||||
timeoutMs?: number;
|
||||
baseUrl: string;
|
||||
fetchFn: typeof fetch;
|
||||
}): Promise<BytePlusTaskResponse> {
|
||||
const deadline = createProviderOperationDeadline({
|
||||
timeoutMs: params.timeoutMs,
|
||||
label: `BytePlus video generation task ${params.taskId}`,
|
||||
});
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) {
|
||||
const response = await fetchProviderOperationResponse({
|
||||
stage: "poll",
|
||||
url: `${params.baseUrl}/contents/generations/tasks/${params.taskId}`,
|
||||
init: {
|
||||
method: "GET",
|
||||
headers: params.headers,
|
||||
},
|
||||
timeoutMs: createProviderOperationTimeoutResolver({
|
||||
deadline,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
fetchFn: params.fetchFn,
|
||||
provider: "byteplus",
|
||||
requestFailedMessage: "BytePlus video status request failed",
|
||||
});
|
||||
const payload = await readBytePlusJsonResponse<BytePlusTaskResponse>(
|
||||
response,
|
||||
"BytePlus video status request failed",
|
||||
);
|
||||
switch (readBytePlusTaskStatus(payload)) {
|
||||
case "succeeded":
|
||||
return payload;
|
||||
case "failed":
|
||||
case "cancelled":
|
||||
throw new Error(
|
||||
readBytePlusErrorMessage(payload.error) || "BytePlus video generation failed",
|
||||
);
|
||||
default:
|
||||
await waitProviderOperationPollInterval({ deadline, pollIntervalMs: POLL_INTERVAL_MS });
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new Error(`BytePlus video generation task ${params.taskId} did not finish in time`);
|
||||
}
|
||||
|
||||
async function downloadBytePlusVideo(params: {
|
||||
url: string;
|
||||
timeoutMs?: ProviderOperationTimeoutMs;
|
||||
fetchFn: typeof fetch;
|
||||
maxBytes: number;
|
||||
}): Promise<GeneratedVideoAsset> {
|
||||
const response = await fetchProviderDownloadResponse({
|
||||
url: params.url,
|
||||
init: { method: "GET" },
|
||||
timeoutMs: params.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
fetchFn: params.fetchFn,
|
||||
provider: "byteplus",
|
||||
requestFailedMessage: "BytePlus generated video download failed",
|
||||
});
|
||||
const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "video/mp4";
|
||||
const buffer = await readResponseWithLimit(response, params.maxBytes, {
|
||||
onOverflow: ({ maxBytes }) =>
|
||||
new Error(`BytePlus generated video download exceeds ${maxBytes} bytes`),
|
||||
});
|
||||
return {
|
||||
buffer,
|
||||
mimeType,
|
||||
fileName: `video-1.${extensionForMime(mimeType)?.slice(1) ?? "mp4"}`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Builds the BytePlus video generation provider registered by the plugin. */
|
||||
export function buildBytePlusVideoGenerationProvider(): VideoGenerationProvider {
|
||||
return {
|
||||
id: "byteplus",
|
||||
label: "BytePlus",
|
||||
defaultModel: DEFAULT_BYTEPLUS_VIDEO_MODEL,
|
||||
models: [
|
||||
DEFAULT_BYTEPLUS_VIDEO_MODEL,
|
||||
"seedance-1-0-lite-i2v-250428",
|
||||
"seedance-1-0-pro-250528",
|
||||
"seedance-1-5-pro-251215",
|
||||
],
|
||||
isConfigured: ({ agentDir }) =>
|
||||
isProviderApiKeyConfigured({
|
||||
provider: "byteplus",
|
||||
agentDir,
|
||||
}),
|
||||
capabilities: {
|
||||
providerOptions: {
|
||||
seed: "number",
|
||||
draft: "boolean",
|
||||
camera_fixed: "boolean",
|
||||
},
|
||||
generate: {
|
||||
maxVideos: 1,
|
||||
maxDurationSeconds: 12,
|
||||
supportsAspectRatio: true,
|
||||
supportsResolution: true,
|
||||
supportsAudio: true,
|
||||
supportsWatermark: true,
|
||||
},
|
||||
imageToVideo: {
|
||||
enabled: true,
|
||||
maxVideos: 1,
|
||||
maxInputImages: 1,
|
||||
maxDurationSeconds: 12,
|
||||
supportsAspectRatio: true,
|
||||
supportsResolution: true,
|
||||
supportsAudio: true,
|
||||
supportsWatermark: true,
|
||||
},
|
||||
videoToVideo: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
async generateVideo(req) {
|
||||
if ((req.inputVideos?.length ?? 0) > 0) {
|
||||
throw new Error("BytePlus video generation does not support video reference inputs.");
|
||||
}
|
||||
const auth = await resolveApiKeyForProvider({
|
||||
provider: "byteplus",
|
||||
cfg: req.cfg,
|
||||
agentDir: req.agentDir,
|
||||
store: req.authStore,
|
||||
});
|
||||
if (!auth.apiKey) {
|
||||
throw new Error("BytePlus API key missing");
|
||||
}
|
||||
|
||||
const fetchFn = fetch;
|
||||
const deadline = createProviderOperationDeadline({
|
||||
timeoutMs: req.timeoutMs,
|
||||
label: "BytePlus video generation",
|
||||
});
|
||||
const { baseUrl, allowPrivateNetwork, headers, dispatcherPolicy } =
|
||||
resolveProviderHttpRequestConfig({
|
||||
baseUrl: resolveBytePlusVideoBaseUrl(req),
|
||||
defaultBaseUrl: BYTEPLUS_BASE_URL,
|
||||
allowPrivateNetwork: false,
|
||||
defaultHeaders: {
|
||||
Authorization: `Bearer ${auth.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
provider: "byteplus",
|
||||
capability: "video",
|
||||
transport: "http",
|
||||
});
|
||||
// Seedance 1.0 has separate T2V and I2V model IDs (e.g. seedance-1-0-lite-t2v-250428 vs
|
||||
// seedance-1-0-lite-i2v-250428). When input images are provided with a T2V model, auto-
|
||||
// switch to the corresponding I2V variant so the API does not reject with task_type mismatch.
|
||||
// 1.5 Pro uses a single model ID for both modes and is unaffected by this substitution.
|
||||
const hasInputImages = (req.inputImages?.length ?? 0) > 0;
|
||||
const requestedModel = normalizeOptionalString(req.model) || DEFAULT_BYTEPLUS_VIDEO_MODEL;
|
||||
const resolvedModel =
|
||||
hasInputImages && requestedModel.includes("-t2v-")
|
||||
? requestedModel.replace("-t2v-", "-i2v-")
|
||||
: requestedModel;
|
||||
|
||||
const content: Array<Record<string, unknown>> = [{ type: "text", text: req.prompt }];
|
||||
const imageUrl = resolveBytePlusImageUrl(req);
|
||||
if (imageUrl) {
|
||||
content.push({
|
||||
type: "image_url",
|
||||
image_url: { url: imageUrl },
|
||||
role: "first_frame",
|
||||
});
|
||||
}
|
||||
const body: Record<string, unknown> = {
|
||||
model: resolvedModel,
|
||||
content,
|
||||
};
|
||||
const aspectRatio = normalizeOptionalString(req.aspectRatio);
|
||||
if (aspectRatio) {
|
||||
body.ratio = aspectRatio;
|
||||
}
|
||||
// Seedance API requires lowercase resolution values (e.g. "480p", "720p"); uppercase
|
||||
// variants like "480P" are rejected with InvalidParameter.
|
||||
const resolution = normalizeOptionalString(req.resolution)?.toLowerCase();
|
||||
if (resolution) {
|
||||
body.resolution = resolution;
|
||||
}
|
||||
const duration = resolveBytePlusDurationSeconds(req.durationSeconds);
|
||||
if (duration !== undefined) {
|
||||
body.duration = duration;
|
||||
}
|
||||
if (typeof req.audio === "boolean") {
|
||||
body.generate_audio = req.audio;
|
||||
}
|
||||
if (typeof req.watermark === "boolean") {
|
||||
body.watermark = req.watermark;
|
||||
}
|
||||
|
||||
// Forward declared providerOptions: seed, draft, camerafixed.
|
||||
// draft=true forces 480p resolution for faster generation.
|
||||
const opts = req.providerOptions ?? {};
|
||||
const seed = resolveBytePlusSeed(opts.seed);
|
||||
const draft = opts.draft === true;
|
||||
// Official JSON body field is camera_fixed (with underscore).
|
||||
const cameraFixed = typeof opts.camera_fixed === "boolean" ? opts.camera_fixed : undefined;
|
||||
if (seed != null) {
|
||||
body.seed = seed;
|
||||
}
|
||||
if (draft && !body.resolution) {
|
||||
body.resolution = "480p";
|
||||
}
|
||||
if (cameraFixed != null) {
|
||||
body.camera_fixed = cameraFixed;
|
||||
}
|
||||
|
||||
const { response, release } = await postJsonRequest({
|
||||
url: `${baseUrl}/contents/generations/tasks`,
|
||||
headers,
|
||||
body,
|
||||
timeoutMs: resolveProviderOperationTimeoutMs({
|
||||
deadline,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
fetchFn,
|
||||
allowPrivateNetwork,
|
||||
dispatcherPolicy,
|
||||
});
|
||||
try {
|
||||
await assertOkOrThrowHttpError(response, "BytePlus video generation failed");
|
||||
const submitted = await readBytePlusJsonResponse<BytePlusTaskCreateResponse>(
|
||||
response,
|
||||
"BytePlus video generation failed",
|
||||
);
|
||||
const taskId = normalizeOptionalString(submitted.id);
|
||||
if (!taskId) {
|
||||
throw new Error("BytePlus video generation response missing task id");
|
||||
}
|
||||
const completed = await pollBytePlusTask({
|
||||
taskId,
|
||||
headers,
|
||||
timeoutMs: resolveProviderOperationTimeoutMs({
|
||||
deadline,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
baseUrl,
|
||||
fetchFn,
|
||||
});
|
||||
const videoUrl = readBytePlusVideoUrl(completed);
|
||||
const video = await downloadBytePlusVideo({
|
||||
url: videoUrl,
|
||||
timeoutMs: createProviderOperationTimeoutResolver({
|
||||
deadline,
|
||||
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
fetchFn,
|
||||
maxBytes: resolveGeneratedVideoMaxBytes(req),
|
||||
});
|
||||
return {
|
||||
videos: [video],
|
||||
model: normalizeOptionalString(completed.model) ?? resolvedModel,
|
||||
metadata: {
|
||||
taskId,
|
||||
status: normalizeOptionalString(completed.status),
|
||||
videoUrl,
|
||||
ratio: normalizeOptionalString(completed.ratio),
|
||||
resolution: normalizeOptionalString(completed.resolution),
|
||||
duration: readBytePlusDurationSeconds(completed.duration),
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user