Skip to content

Commit 9e002c1

Browse files
committed
fix(video): bound generated video downloads
1 parent bee163b commit 9e002c1

13 files changed

Lines changed: 358 additions & 14 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Docs: https://docs.openclaw.ai
66

77
### Fixes
88

9+
- Providers: bound generated video downloads from OpenAI, Runway, xAI, MiniMax, BytePlus, and DashScope-compatible providers.
910
- Cron: retry recurring jobs after transient model rate limits before waiting for the next scheduled slot.
1011

1112
## 2026.5.28

‎extensions/byteplus/video-generation-provider.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,18 @@ function requireBytePlusPostBody(): Record<string, unknown> {
6464
return request.body;
6565
}
6666

67+
function streamedVideoResponse(bytes: string): Response {
68+
return new Response(
69+
new ReadableStream({
70+
start(controller) {
71+
controller.enqueue(new TextEncoder().encode(bytes));
72+
controller.close();
73+
},
74+
}),
75+
{ headers: { "content-type": "video/mp4" } },
76+
);
77+
}
78+
6779
describe("byteplus video generation provider", () => {
6880
it("declares explicit mode capabilities", () => {
6981
expectExplicitVideoGenerationCapabilities(buildBytePlusVideoGenerationProvider());
@@ -95,6 +107,36 @@ describe("byteplus video generation provider", () => {
95107
expect(metadata.taskId).toBe("task_123");
96108
});
97109

110+
it("rejects generated video downloads that exceed the configured media cap", async () => {
111+
postJsonRequestMock.mockResolvedValue({
112+
response: {
113+
json: async () => ({ id: "task_too_large" }),
114+
},
115+
release: vi.fn(async () => {}),
116+
});
117+
fetchWithTimeoutMock
118+
.mockResolvedValueOnce({
119+
json: async () => ({
120+
id: "task_too_large",
121+
status: "succeeded",
122+
content: {
123+
video_url: "https://example.com/too-large.mp4",
124+
},
125+
}),
126+
})
127+
.mockResolvedValueOnce(streamedVideoResponse("too-large"));
128+
129+
const provider = buildBytePlusVideoGenerationProvider();
130+
await expect(
131+
provider.generateVideo({
132+
provider: "byteplus",
133+
model: "seedance-1-0-lite-t2v-250428",
134+
prompt: "short video",
135+
cfg: { agents: { defaults: { mediaMaxMb: 0.000001 } } },
136+
}),
137+
).rejects.toThrow("BytePlus generated video download exceeds 1 bytes");
138+
});
139+
98140
it("switches t2v image requests to i2v models and lowercases resolution", async () => {
99141
mockSuccessfulBytePlusTask({ model: "seedance-1-0-lite-i2v-250428" });
100142

‎extensions/byteplus/video-generation-provider.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
waitProviderOperationPollInterval,
1414
type ProviderOperationTimeoutMs,
1515
} from "openclaw/plugin-sdk/provider-http";
16+
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
1617
import {
1718
asSafeIntegerInRange,
1819
isRecord,
@@ -32,6 +33,7 @@ const MAX_POLL_ATTEMPTS = 120;
3233
const BYTEPLUS_SEED_MAX = 2_147_483_647;
3334
const BYTEPLUS_MIN_DURATION_SECONDS = 2;
3435
const BYTEPLUS_MAX_DURATION_SECONDS = 12;
36+
const DEFAULT_GENERATED_VIDEO_MAX_BYTES = 16 * 1024 * 1024;
3537

3638
type BytePlusTaskCreateResponse = {
3739
id?: unknown;
@@ -104,6 +106,14 @@ function resolveBytePlusVideoBaseUrl(req: VideoGenerationRequest): string {
104106
);
105107
}
106108

109+
function resolveGeneratedVideoMaxBytes(req: VideoGenerationRequest): number {
110+
const configured = req.cfg.agents?.defaults?.mediaMaxMb;
111+
if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
112+
return Math.floor(configured * 1024 * 1024);
113+
}
114+
return DEFAULT_GENERATED_VIDEO_MAX_BYTES;
115+
}
116+
107117
function toDataUrl(buffer: Buffer, mimeType: string): string {
108118
return `data:${mimeType};base64,${buffer.toString("base64")}`;
109119
}
@@ -197,6 +207,7 @@ async function downloadBytePlusVideo(params: {
197207
url: string;
198208
timeoutMs?: ProviderOperationTimeoutMs;
199209
fetchFn: typeof fetch;
210+
maxBytes: number;
200211
}): Promise<GeneratedVideoAsset> {
201212
const response = await fetchProviderDownloadResponse({
202213
url: params.url,
@@ -207,9 +218,12 @@ async function downloadBytePlusVideo(params: {
207218
requestFailedMessage: "BytePlus generated video download failed",
208219
});
209220
const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "video/mp4";
210-
const arrayBuffer = await response.arrayBuffer();
221+
const buffer = await readResponseWithLimit(response, params.maxBytes, {
222+
onOverflow: ({ maxBytes }) =>
223+
new Error(`BytePlus generated video download exceeds ${maxBytes} bytes`),
224+
});
211225
return {
212-
buffer: Buffer.from(arrayBuffer),
226+
buffer,
213227
mimeType,
214228
fileName: `video-1.${extensionForMime(mimeType)?.slice(1) ?? "mp4"}`,
215229
};
@@ -393,6 +407,7 @@ export function buildBytePlusVideoGenerationProvider(): VideoGenerationProvider
393407
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
394408
}),
395409
fetchFn,
410+
maxBytes: resolveGeneratedVideoMaxBytes(req),
396411
});
397412
return {
398413
videos: [video],

‎extensions/minimax/video-generation-provider.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,18 @@ function mockCallArg(mock: { mock: { calls: unknown[][] } }, index = 0): Record<
4848
return call[0] as Record<string, unknown>;
4949
}
5050

51+
function streamedVideoResponse(bytes: string): Response {
52+
return new Response(
53+
new ReadableStream({
54+
start(controller) {
55+
controller.enqueue(new TextEncoder().encode(bytes));
56+
controller.close();
57+
},
58+
}),
59+
{ headers: { "content-type": "video/mp4" } },
60+
);
61+
}
62+
5163
describe("minimax video generation provider", () => {
5264
it("declares explicit mode capabilities", () => {
5365
const provider = buildMinimaxVideoGenerationProvider();
@@ -102,6 +114,38 @@ describe("minimax video generation provider", () => {
102114
expect(result.metadata?.fileId).toBe("file-1");
103115
});
104116

117+
it("rejects generated video downloads that exceed the configured media cap", async () => {
118+
postJsonRequestMock.mockResolvedValue({
119+
response: {
120+
json: async () => ({
121+
task_id: "task-too-large",
122+
base_resp: { status_code: 0 },
123+
}),
124+
},
125+
release: vi.fn(async () => {}),
126+
});
127+
fetchWithTimeoutMock
128+
.mockResolvedValueOnce({
129+
json: async () => ({
130+
task_id: "task-too-large",
131+
status: "Success",
132+
video_url: "https://example.com/too-large.mp4",
133+
base_resp: { status_code: 0 },
134+
}),
135+
})
136+
.mockResolvedValueOnce(streamedVideoResponse("too-large"));
137+
138+
const provider = buildMinimaxVideoGenerationProvider();
139+
await expect(
140+
provider.generateVideo({
141+
provider: "minimax",
142+
model: "MiniMax-Hailuo-2.3",
143+
prompt: "short video",
144+
cfg: { agents: { defaults: { mediaMaxMb: 0.000001 } } },
145+
}),
146+
).rejects.toThrow("MiniMax generated video download exceeds 1 bytes");
147+
});
148+
105149
it("downloads via file_id when the status response omits video_url", async () => {
106150
postJsonRequestMock.mockResolvedValue({
107151
response: {

‎extensions/minimax/video-generation-provider.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
waitProviderOperationPollInterval,
1414
type ProviderOperationTimeoutMs,
1515
} from "openclaw/plugin-sdk/provider-http";
16+
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
1617
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
1718
import type {
1819
GeneratedVideoAsset,
@@ -26,6 +27,7 @@ const DEFAULT_TIMEOUT_MS = 120_000;
2627
const DEFAULT_OPERATION_TIMEOUT_MS = 1_200_000;
2728
const POLL_INTERVAL_MS = 10_000;
2829
const MAX_POLL_ATTEMPTS = 120;
30+
const DEFAULT_GENERATED_VIDEO_MAX_BYTES = 16 * 1024 * 1024;
2931
const MINIMAX_MODEL_ALLOWED_DURATIONS: Readonly<Record<string, readonly number[]>> = {
3032
"MiniMax-Hailuo-2.3": [6, 10],
3133
"MiniMax-Hailuo-02": [6, 10],
@@ -78,6 +80,14 @@ function resolveMinimaxVideoBaseUrl(
7880
}
7981
}
8082

83+
function resolveGeneratedVideoMaxBytes(req: VideoGenerationRequest): number {
84+
const configured = req.cfg.agents?.defaults?.mediaMaxMb;
85+
if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
86+
return Math.floor(configured * 1024 * 1024);
87+
}
88+
return DEFAULT_GENERATED_VIDEO_MAX_BYTES;
89+
}
90+
8191
function assertMinimaxBaseResp(baseResp: MinimaxBaseResp | undefined, context: string): void {
8292
if (!baseResp || typeof baseResp.status_code !== "number" || baseResp.status_code === 0) {
8393
return;
@@ -213,6 +223,7 @@ async function downloadVideoFromUrl(params: {
213223
url: string;
214224
timeoutMs?: ProviderOperationTimeoutMs;
215225
fetchFn: typeof fetch;
226+
maxBytes: number;
216227
}): Promise<GeneratedVideoAsset> {
217228
const response = await fetchProviderDownloadResponse({
218229
url: params.url,
@@ -223,9 +234,12 @@ async function downloadVideoFromUrl(params: {
223234
requestFailedMessage: "MiniMax generated video download failed",
224235
});
225236
const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "video/mp4";
226-
const arrayBuffer = await response.arrayBuffer();
237+
const buffer = await readResponseWithLimit(response, params.maxBytes, {
238+
onOverflow: ({ maxBytes }) =>
239+
new Error(`MiniMax generated video download exceeds ${maxBytes} bytes`),
240+
});
227241
return {
228-
buffer: Buffer.from(arrayBuffer),
242+
buffer,
229243
mimeType,
230244
fileName: `video-1.${extensionForMime(mimeType)?.slice(1) ?? "mp4"}`,
231245
};
@@ -237,6 +251,7 @@ async function downloadVideoFromFileId(params: {
237251
timeoutMs?: ProviderOperationTimeoutMs;
238252
baseUrl: string;
239253
fetchFn: typeof fetch;
254+
maxBytes: number;
240255
}): Promise<GeneratedVideoAsset> {
241256
const url = new URL(`${params.baseUrl}/v1/files/retrieve`);
242257
url.searchParams.set("file_id", params.fileId);
@@ -267,9 +282,12 @@ async function downloadVideoFromFileId(params: {
267282
requestFailedMessage: "MiniMax generated video download failed",
268283
});
269284
const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "video/mp4";
270-
const arrayBuffer = await response.arrayBuffer();
285+
const buffer = await readResponseWithLimit(response, params.maxBytes, {
286+
onOverflow: ({ maxBytes }) =>
287+
new Error(`MiniMax generated video download exceeds ${maxBytes} bytes`),
288+
});
271289
return {
272-
buffer: Buffer.from(arrayBuffer),
290+
buffer,
273291
mimeType,
274292
fileName:
275293
normalizeOptionalString(metadata.file?.filename) ||
@@ -413,6 +431,7 @@ function buildMinimaxVideoProvider(providerId: string): VideoGenerationProvider
413431
defaultTimeoutMs: DEFAULT_TIMEOUT_MS,
414432
}),
415433
fetchFn,
434+
maxBytes: resolveGeneratedVideoMaxBytes(req),
416435
})
417436
: fileId
418437
? await downloadVideoFromFileId({
@@ -424,6 +443,7 @@ function buildMinimaxVideoProvider(providerId: string): VideoGenerationProvider
424443
}),
425444
baseUrl,
426445
fetchFn,
446+
maxBytes: resolveGeneratedVideoMaxBytes(req),
427447
})
428448
: (() => {
429449
throw new Error(

‎extensions/openai/video-generation-provider.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,18 @@ function providerHttpConfigRequest(): Record<string, unknown> {
8787
return request as Record<string, unknown>;
8888
}
8989

90+
function streamedVideoResponse(bytes: string): Response {
91+
return new Response(
92+
new ReadableStream({
93+
start(controller) {
94+
controller.enqueue(new TextEncoder().encode(bytes));
95+
controller.close();
96+
},
97+
}),
98+
{ headers: { "content-type": "video/mp4" } },
99+
);
100+
}
101+
90102
describe("openai video generation provider", () => {
91103
it("declares the openai-codex alias for default-model ordering", () => {
92104
const provider = buildOpenAIVideoGenerationProvider();
@@ -156,6 +168,38 @@ describe("openai video generation provider", () => {
156168
expect(result.metadata?.status).toBe("completed");
157169
});
158170

171+
it("rejects generated video downloads that exceed the configured media cap", async () => {
172+
postJsonRequestMock.mockResolvedValue({
173+
response: {
174+
json: async () => ({
175+
id: "vid_too_large",
176+
model: "sora-2",
177+
status: "queued",
178+
}),
179+
},
180+
release: vi.fn(async () => {}),
181+
});
182+
fetchWithTimeoutMock
183+
.mockResolvedValueOnce({
184+
json: async () => ({
185+
id: "vid_too_large",
186+
model: "sora-2",
187+
status: "completed",
188+
}),
189+
})
190+
.mockResolvedValueOnce(streamedVideoResponse("too-large"));
191+
192+
const provider = buildOpenAIVideoGenerationProvider();
193+
await expect(
194+
provider.generateVideo({
195+
provider: "openai",
196+
model: "sora-2",
197+
prompt: "short video",
198+
cfg: { agents: { defaults: { mediaMaxMb: 0.000001 } } },
199+
}),
200+
).rejects.toThrow("OpenAI generated video download exceeds 1 bytes");
201+
});
202+
159203
it("uses JSON input_reference.image_url for image-to-video requests", async () => {
160204
postJsonRequestMock.mockResolvedValue({
161205
response: {

‎extensions/openai/video-generation-provider.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
sanitizeConfiguredModelProviderRequest,
1717
type ProviderOperationTimeoutMs,
1818
} from "openclaw/plugin-sdk/provider-http";
19+
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
1920
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2021
import type {
2122
GeneratedVideoAsset,
@@ -29,6 +30,7 @@ const DEFAULT_OPENAI_VIDEO_MODEL = "sora-2";
2930
const DEFAULT_TIMEOUT_MS = 120_000;
3031
const POLL_INTERVAL_MS = 2_500;
3132
const MAX_POLL_ATTEMPTS = 120;
33+
const DEFAULT_GENERATED_VIDEO_MAX_BYTES = 16 * 1024 * 1024;
3234
const OPENAI_VIDEO_SECONDS = [4, 8, 12] as const;
3335
const OPENAI_VIDEO_SIZES = ["720x1280", "1280x720", "1024x1792", "1792x1024"] as const;
3436

@@ -76,6 +78,14 @@ function resolveDurationSeconds(durationSeconds: number | undefined): "4" | "8"
7678
return String(nearest) as "4" | "8" | "12";
7779
}
7880

81+
function resolveGeneratedVideoMaxBytes(req: VideoGenerationRequest): number {
82+
const configured = req.cfg.agents?.defaults?.mediaMaxMb;
83+
if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
84+
return Math.floor(configured * 1024 * 1024);
85+
}
86+
return DEFAULT_GENERATED_VIDEO_MAX_BYTES;
87+
}
88+
7989
function resolveSize(params: {
8090
size?: string;
8191
aspectRatio?: string;
@@ -233,6 +243,7 @@ async function downloadOpenAIVideo(
233243
timeoutMs?: ProviderOperationTimeoutMs;
234244
baseUrl: string;
235245
fetchFn: typeof fetch;
246+
maxBytes: number;
236247
} & OpenAIVideoRequestPolicy,
237248
): Promise<GeneratedVideoAsset> {
238249
const url = new URL(`${params.baseUrl}/videos/${params.videoId}/content`);
@@ -253,9 +264,12 @@ async function downloadOpenAIVideo(
253264
});
254265
try {
255266
const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "video/mp4";
256-
const arrayBuffer = await response.arrayBuffer();
267+
const buffer = await readResponseWithLimit(response, params.maxBytes, {
268+
onOverflow: ({ maxBytes }) =>
269+
new Error(`OpenAI generated video download exceeds ${maxBytes} bytes`),
270+
});
257271
return {
258-
buffer: Buffer.from(arrayBuffer),
272+
buffer,
259273
mimeType,
260274
fileName: `video-1.${extensionForMime(mimeType)?.slice(1) ?? "mp4"}`,
261275
};
@@ -436,6 +450,7 @@ export function buildOpenAIVideoGenerationProvider(): VideoGenerationProvider {
436450
fetchFn,
437451
allowPrivateNetwork,
438452
dispatcherPolicy,
453+
maxBytes: resolveGeneratedVideoMaxBytes(req),
439454
});
440455
return {
441456
videos: [video],

0 commit comments

Comments
 (0)