Skip to content

Commit 20f19d8

Browse files
authored
fix(minimax): apply request policy to media generation requests (#102072)
* fix(minimax): apply request policy to media generation requests * fix(minimax): include image request policy * fix(minimax): apply request policy to follow-up media fetches * fix(minimax): preserve retries for guarded media fetches
1 parent 3b0d357 commit 20f19d8

7 files changed

Lines changed: 562 additions & 74 deletions

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

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,9 @@ describe("minimax image-generation provider", () => {
5656
}
5757

5858
function requireFirstPostJsonRequest(mock: ReturnType<typeof vi.fn>): {
59+
allowPrivateNetwork?: boolean;
5960
body?: unknown;
61+
headers?: unknown;
6062
ssrfPolicy?: unknown;
6163
url?: string;
6264
} {
@@ -68,7 +70,13 @@ describe("minimax image-generation provider", () => {
6870
if (!request || typeof request !== "object" || Array.isArray(request)) {
6971
throw new Error("expected MiniMax image request");
7072
}
71-
return request as { body?: unknown; url?: string };
73+
return request as {
74+
allowPrivateNetwork?: boolean;
75+
body?: unknown;
76+
headers?: unknown;
77+
ssrfPolicy?: unknown;
78+
url?: string;
79+
};
7280
}
7381

7482
it("generates PNG buffers through the shared provider HTTP path", async () => {
@@ -207,6 +215,62 @@ describe("minimax image-generation provider", () => {
207215
expect(request.ssrfPolicy).toEqual({ allowRfc2544BenchmarkRange: true });
208216
});
209217

218+
it("passes portal image request policy through the provider HTTP helper", async () => {
219+
mockMinimaxApiKey();
220+
const postJsonRequest = vi.spyOn(providerHttp, "postJsonRequest").mockResolvedValue({
221+
response: new Response(
222+
JSON.stringify({
223+
data: { image_base64: [Buffer.from("png-data").toString("base64")] },
224+
base_resp: { status_code: 0 },
225+
}),
226+
{ status: 200, headers: { "Content-Type": "application/json" } },
227+
),
228+
finalUrl: "https://api.minimaxi.com/v1/image_generation",
229+
release: async () => {},
230+
});
231+
const resolveHttpConfig = vi.spyOn(providerHttp, "resolveProviderHttpRequestConfig");
232+
const requestOverrides = {
233+
allowPrivateNetwork: true,
234+
headers: { "X-MiniMax-Image-Policy": "enabled" },
235+
};
236+
237+
const provider = buildMinimaxPortalImageGenerationProvider();
238+
await provider.generateImage({
239+
provider: "minimax-portal",
240+
model: "image-01",
241+
prompt: "draw a cat",
242+
cfg: {
243+
models: {
244+
providers: {
245+
minimax: {
246+
baseUrl: "https://wrong.example/anthropic",
247+
models: [],
248+
},
249+
"minimax-portal": {
250+
baseUrl: "https://api.minimaxi.com/anthropic",
251+
models: [],
252+
request: requestOverrides,
253+
},
254+
},
255+
},
256+
},
257+
});
258+
259+
expect(resolveHttpConfig).toHaveBeenCalledWith(
260+
expect.objectContaining({
261+
baseUrl: "https://api.minimaxi.com",
262+
provider: "minimax-portal",
263+
capability: "image",
264+
transport: "http",
265+
request: requestOverrides,
266+
}),
267+
);
268+
const request = requireFirstPostJsonRequest(postJsonRequest);
269+
expect(request.url).toBe("https://api.minimaxi.com/v1/image_generation");
270+
expect(request.allowPrivateNetwork).toBe(true);
271+
expect((request.headers as Headers).get("x-minimax-image-policy")).toBe("enabled");
272+
});
273+
210274
it("keeps the dedicated global image endpoint when text config uses the global API host", async () => {
211275
mockMinimaxApiKey();
212276
const fetchMock = mockSuccessfulMinimaxImageResponse();

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
postJsonRequest,
1212
readProviderJsonResponse,
1313
resolveProviderHttpRequestConfig,
14+
sanitizeConfiguredModelProviderRequest,
1415
} from "openclaw/plugin-sdk/provider-http";
1516

1617
const DEFAULT_MINIMAX_IMAGE_BASE_URL = "https://api.minimax.io";
@@ -138,14 +139,16 @@ function buildMinimaxImageProvider(providerId: string): ImageGenerationProvider
138139
} = resolveProviderHttpRequestConfig({
139140
baseUrl,
140141
defaultBaseUrl: DEFAULT_MINIMAX_IMAGE_BASE_URL,
141-
allowPrivateNetwork: false,
142142
defaultHeaders: {
143143
Authorization: `Bearer ${auth.apiKey}`,
144144
"Content-Type": "application/json",
145145
},
146146
provider: providerId,
147147
capability: "image",
148148
transport: "http",
149+
request: sanitizeConfiguredModelProviderRequest(
150+
req.cfg.models?.providers?.[providerId]?.request,
151+
),
149152
});
150153

151154
const body: Record<string, unknown> = {

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

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ import {
1010
const {
1111
resolveApiKeyForProviderMock,
1212
postJsonRequestMock,
13+
executeProviderOperationWithRetryMock,
1314
fetchWithTimeoutMock,
15+
fetchWithTimeoutGuardedMock,
1416
resolveProviderHttpRequestConfigMock,
1517
} = getMinimaxProviderHttpMocks();
1618

@@ -50,6 +52,28 @@ function mockCallArg(mock: { mock: { calls: unknown[][] } }, index = 0): Record<
5052
return call[0] as Record<string, unknown>;
5153
}
5254

55+
function expectMinimaxGuardedFetchCall(index: number, url: string) {
56+
const call = fetchWithTimeoutGuardedMock.mock.calls[index];
57+
if (!call) {
58+
throw new Error(`expected MiniMax guarded fetch call ${index + 1}`);
59+
}
60+
const [actualUrl, init, timeoutMs, fetchFn, options] = call;
61+
expect(actualUrl).toBe(url);
62+
expect((init as RequestInit | undefined)?.method).toBe("GET");
63+
expect(Number.isInteger(timeoutMs)).toBe(true);
64+
expect(timeoutMs).toBeGreaterThan(0);
65+
expect(fetchFn).toBe(fetch);
66+
return {
67+
options: options as Record<string, unknown> | undefined,
68+
};
69+
}
70+
71+
function expectAllowPrivateNetworkPolicy(options: Record<string, unknown> | undefined): void {
72+
expect(options).toEqual({
73+
ssrfPolicy: { allowPrivateNetwork: true },
74+
});
75+
}
76+
5377
function streamedAudioResponse(bytes: string): Response {
5478
return new Response(
5579
new ReadableStream({
@@ -400,7 +424,66 @@ describe("minimax music generation provider", () => {
400424
expect(body.lyrics_optimizer).toBe(true);
401425
});
402426

427+
it("retries guarded music URL downloads while preserving request policy", async () => {
428+
const requestOverrides = {
429+
allowPrivateNetwork: true,
430+
headers: { "X-MiniMax-Music-Policy": "enabled" },
431+
};
432+
postJsonRequestMock.mockResolvedValue({
433+
response: new Response(
434+
JSON.stringify({
435+
task_id: "task-retry",
436+
audio_url: "https://example.com/retry.mp3",
437+
base_resp: { status_code: 0 },
438+
}),
439+
{ headers: { "content-type": "application/json" } },
440+
),
441+
release: vi.fn(async () => {}),
442+
});
443+
fetchWithTimeoutMock
444+
.mockRejectedValueOnce(new Error("temporary download failure"))
445+
.mockResolvedValueOnce({
446+
headers: new Headers({ "content-type": "audio/mpeg" }),
447+
arrayBuffer: async () => Buffer.from("mp3-bytes"),
448+
});
449+
450+
const provider = buildMinimaxPortalMusicGenerationProvider();
451+
const result = await provider.generateMusic({
452+
provider: "minimax-portal",
453+
model: "music-2.6",
454+
prompt: "upbeat dance-pop",
455+
cfg: {
456+
models: {
457+
providers: {
458+
"minimax-portal": {
459+
baseUrl: "https://api.minimaxi.com",
460+
models: [],
461+
request: requestOverrides,
462+
},
463+
},
464+
},
465+
},
466+
});
467+
468+
expectAllowPrivateNetworkPolicy(
469+
expectMinimaxGuardedFetchCall(0, "https://example.com/retry.mp3").options,
470+
);
471+
expectAllowPrivateNetworkPolicy(
472+
expectMinimaxGuardedFetchCall(1, "https://example.com/retry.mp3").options,
473+
);
474+
expect(result.tracks).toHaveLength(1);
475+
expect(
476+
executeProviderOperationWithRetryMock.mock.calls.map(
477+
([params]) => (params as { stage: string }).stage,
478+
),
479+
).toContain("download");
480+
});
481+
403482
it("routes portal music generation through minimax-portal auth and HTTP config", async () => {
483+
const requestOverrides = {
484+
allowPrivateNetwork: true,
485+
headers: { "X-MiniMax-Music-Policy": "enabled" },
486+
};
404487
mockMusicGenerationResponse({
405488
task_id: "task-portal",
406489
audio_url: "https://example.com/portal.mp3",
@@ -422,6 +505,7 @@ describe("minimax music generation provider", () => {
422505
"minimax-portal": {
423506
baseUrl: "https://api.minimaxi.com/anthropic",
424507
models: [],
508+
request: requestOverrides,
425509
},
426510
},
427511
},
@@ -434,8 +518,13 @@ describe("minimax music generation provider", () => {
434518
expect(httpConfigParams.provider).toBe("minimax-portal");
435519
expect(httpConfigParams.capability).toBe("audio");
436520
expect(httpConfigParams.transport).toBe("http");
437-
expect(mockCallArg(postJsonRequestMock).url).toBe(
438-
"https://api.minimaxi.com/v1/music_generation",
521+
expect(httpConfigParams.request).toEqual(requestOverrides);
522+
const postParams = mockCallArg(postJsonRequestMock);
523+
expect(postParams.allowPrivateNetwork).toBe(true);
524+
expect((postParams.headers as Headers).get("x-minimax-music-policy")).toBe("enabled");
525+
expect(postParams.url).toBe("https://api.minimaxi.com/v1/music_generation");
526+
expectAllowPrivateNetworkPolicy(
527+
expectMinimaxGuardedFetchCall(0, "https://example.com/portal.mp3").options,
439528
);
440529
});
441530
});

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

Lines changed: 62 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runt
1010
import {
1111
assertOkOrThrowHttpError,
1212
createProviderOperationDeadline,
13-
fetchProviderDownloadResponse,
13+
executeProviderOperationWithRetry,
14+
fetchWithTimeoutGuarded,
1415
postJsonRequest,
1516
resolveProviderOperationTimeoutMs,
1617
resolveProviderHttpRequestConfig,
18+
sanitizeConfiguredModelProviderRequest,
1719
type ProviderOperationDeadline,
1820
} from "openclaw/plugin-sdk/provider-http";
1921
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
@@ -53,6 +55,11 @@ type MinimaxMusicStreamFrame = {
5355
base_resp?: MinimaxBaseResp;
5456
};
5557

58+
type MinimaxRequestPolicy = Pick<
59+
Parameters<typeof postJsonRequest>[0],
60+
"allowPrivateNetwork" | "dispatcherPolicy"
61+
>;
62+
5663
function resolveMinimaxMusicBaseUrl(
5764
cfg: Parameters<typeof resolveApiKeyForProvider>[0]["cfg"],
5865
providerId: string,
@@ -77,6 +84,18 @@ function assertMinimaxBaseResp(baseResp: MinimaxBaseResp | undefined, context: s
7784
);
7885
}
7986

87+
function resolveMinimaxGuardedRequestOptions(
88+
policy: MinimaxRequestPolicy,
89+
): Parameters<typeof fetchWithTimeoutGuarded>[4] | undefined {
90+
if (!policy.allowPrivateNetwork && !policy.dispatcherPolicy) {
91+
return undefined;
92+
}
93+
return {
94+
...(policy.allowPrivateNetwork ? { ssrfPolicy: { allowPrivateNetwork: true } } : {}),
95+
...(policy.dispatcherPolicy ? { dispatcherPolicy: policy.dispatcherPolicy } : {}),
96+
};
97+
}
98+
8099
function decodePossibleBinaryWithLimit(data: string, maxBytes: number): Buffer {
81100
const trimmed = data.trim();
82101
if (/^[0-9a-f]+$/iu.test(trimmed) && trimmed.length % 2 === 0) {
@@ -120,25 +139,46 @@ async function downloadTrackFromUrl(params: {
120139
timeoutMs?: number;
121140
fetchFn: typeof fetch;
122141
maxBytes: number;
142+
policy: MinimaxRequestPolicy;
123143
}): Promise<GeneratedMusicAsset> {
124-
const response = await fetchProviderDownloadResponse({
125-
url: params.url,
126-
init: { method: "GET" },
127-
timeoutMs: params.timeoutMs ?? DEFAULT_TIMEOUT_MS,
128-
fetchFn: params.fetchFn,
144+
const result = await executeProviderOperationWithRetry({
129145
provider: "minimax",
130-
requestFailedMessage: "MiniMax generated music download failed",
146+
stage: "download",
147+
operation: async () => {
148+
const guardedResult = await fetchWithTimeoutGuarded(
149+
params.url,
150+
{ method: "GET" },
151+
params.timeoutMs ?? DEFAULT_TIMEOUT_MS,
152+
params.fetchFn,
153+
resolveMinimaxGuardedRequestOptions(params.policy),
154+
);
155+
try {
156+
await assertOkOrThrowHttpError(
157+
guardedResult.response,
158+
"MiniMax generated music download failed",
159+
);
160+
} catch (error) {
161+
await guardedResult.release();
162+
throw error;
163+
}
164+
return guardedResult;
165+
},
131166
});
132-
const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "audio/mpeg";
133-
const ext = extensionForMime(mimeType)?.replace(/^\./u, "") || "mp3";
134-
return {
135-
buffer: await readResponseWithLimit(response, params.maxBytes, {
136-
onOverflow: ({ maxBytes }) =>
137-
new Error(`MiniMax generated music download exceeds ${maxBytes} bytes`),
138-
}),
139-
mimeType,
140-
fileName: `track-1.${ext}`,
141-
};
167+
try {
168+
const mimeType =
169+
normalizeOptionalString(result.response.headers.get("content-type")) ?? "audio/mpeg";
170+
const ext = extensionForMime(mimeType)?.replace(/^\./u, "") || "mp3";
171+
return {
172+
buffer: await readResponseWithLimit(result.response, params.maxBytes, {
173+
onOverflow: ({ maxBytes }) =>
174+
new Error(`MiniMax generated music download exceeds ${maxBytes} bytes`),
175+
}),
176+
mimeType,
177+
fileName: `track-1.${ext}`,
178+
};
179+
} finally {
180+
await result.release();
181+
}
142182
}
143183

144184
function createMinimaxMusicTimeoutError(deadline: ProviderOperationDeadline): Error {
@@ -352,14 +392,17 @@ function buildMinimaxMusicProvider(providerId: string): MusicGenerationProvider
352392
resolveProviderHttpRequestConfig({
353393
baseUrl: resolveMinimaxMusicBaseUrl(req.cfg, providerId),
354394
defaultBaseUrl: DEFAULT_MINIMAX_MUSIC_BASE_URL,
355-
allowPrivateNetwork: false,
356395
defaultHeaders: {
357396
Authorization: `Bearer ${auth.apiKey}`,
358397
},
359398
provider: providerId,
360399
capability: "audio",
361400
transport: "http",
401+
request: sanitizeConfiguredModelProviderRequest(
402+
req.cfg.models?.providers?.[providerId]?.request,
403+
),
362404
});
405+
const requestPolicy: MinimaxRequestPolicy = { allowPrivateNetwork, dispatcherPolicy };
363406
const jsonHeaders = new Headers(headers);
364407
jsonHeaders.set("Content-Type", "application/json");
365408

@@ -436,6 +479,7 @@ function buildMinimaxMusicProvider(providerId: string): MusicGenerationProvider
436479
}),
437480
fetchFn,
438481
maxBytes: resolveGeneratedMusicMaxBytes(req),
482+
policy: requestPolicy,
439483
})
440484
: inlineAudio
441485
? (() => {

0 commit comments

Comments
 (0)