From ece97350cd6ec8fff0d468fd618085603027cabd Mon Sep 17 00:00:00 2001 From: octo-patch <266937838+octo-patch@users.noreply.github.com> Date: Thu, 3 Dec 2026 05:58:48 +0800 Subject: [PATCH] feat(media): support MiniMax H3 text-to-image generation --- docs/API_REFERENCE.md | 7 +- packages/ai/scripts/generate-image-models.ts | 13 +-- packages/ai/src/image-models.generated.ts | 60 +++++++++++++ packages/ai/src/index.ts | 1 + packages/ai/src/minimax-image-models.ts | 6 ++ .../ai/src/providers/images/minimax-h3.ts | 56 +++++++++++++ packages/ai/src/providers/images/minimax.ts | 66 ++++++++++----- packages/ai/test/minimax-h3-images.test.ts | 84 +++++++++++++++++++ packages/ai/test/minimax-images.test.ts | 2 +- src/cli/commands/media.ts | 18 ++-- src/media/minimax.ts | 24 ++++-- src/server.ts | 8 +- tests/media/minimax.test.ts | 23 +++++ 13 files changed, 317 insertions(+), 51 deletions(-) create mode 100644 packages/ai/src/minimax-image-models.ts create mode 100644 packages/ai/src/providers/images/minimax-h3.ts create mode 100644 packages/ai/test/minimax-h3-images.test.ts diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 5fdefacd..2aa0bba6 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -906,6 +906,7 @@ durable job, so it survives process restarts and can be inspected or cancelled. ```bash memorix media generate image --prompt "..." --json +memorix media generate image --model MiniMax-H3-Image --prompt "A small blue sailboat" --json memorix media generate image --prompt "..." --image ./reference.png --json memorix media generate video --prompt "..." --json memorix media derive-pdf --asset --attach --json @@ -915,7 +916,11 @@ memorix media cancel --job --json ``` Set `MINIMAX_API_KEY` (or `MINIMAX_CN_API_KEY`) outside Git before using -generation. Image-to-image passes the reference image through MiniMax +generation. Select `MiniMax-H3-Image` or `MiniMax-H3-Image-Highspeed` for text-only +generation in either region. H3 requests allow at least ten minutes and are sent +once because another request can incur a second charge. Partial batches retain +the successful assets and report warnings for the failed images. +Image-to-image passes the reference image through MiniMax `subject_reference` for the image-01/image-01-live models. `memorix_media` is the matching single MCP tool in every profile, including `micro`. Its import/attach/list/show/derive-pdf/derive-audio/status/cancel actions are diff --git a/packages/ai/scripts/generate-image-models.ts b/packages/ai/scripts/generate-image-models.ts index ae44c0d0..28b9cb2f 100644 --- a/packages/ai/scripts/generate-image-models.ts +++ b/packages/ai/scripts/generate-image-models.ts @@ -3,6 +3,7 @@ import { writeFileSync } from "fs"; import { dirname, join } from "path"; import { fileURLToPath, pathToFileURL } from "url"; +import { MINIMAX_H3_IMAGE_MODELS, isMiniMaxH3ImageModel } from "../src/minimax-image-models.ts"; import type { ImagesApi, ImagesModel } from "../src/types.ts"; const __filename = fileURLToPath(import.meta.url); @@ -11,8 +12,8 @@ const packageRoot = join(__dirname, ".."); const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"; const MINIMAX_IMAGE_MODEL_IDS = ["image-01", "image-01-live"] as const; const MINIMAX_IMAGE_VARIANTS = [ - { provider: "minimax", baseUrl: "https://api.minimax.io/v1/image_generation" }, - { provider: "minimax-cn", baseUrl: "https://api.minimaxi.com/v1/image_generation" }, + { provider: "minimax", baseUrl: "https://api.minimax.io/v1/image_generation", h3Url: "https://api.minimax.io/v1/images/generations" }, + { provider: "minimax-cn", baseUrl: "https://api.minimaxi.com/v1/image_generation", h3Url: "https://api.minimax.cn/v1/images/generations" }, ] as const; const MIN_GENERATED_IMAGE_MODEL_COUNT = 1; const CATALOG_SHRINK_OVERRIDE_ENV = "MEMORIX_ALLOW_MODEL_CATALOG_SHRINK"; @@ -84,14 +85,14 @@ async function fetchOpenRouterImageModels(): Promise[] { - return MINIMAX_IMAGE_VARIANTS.flatMap(({ provider, baseUrl }) => - MINIMAX_IMAGE_MODEL_IDS.map((modelId) => ({ + return MINIMAX_IMAGE_VARIANTS.flatMap(({ provider, baseUrl, h3Url }) => + [...MINIMAX_IMAGE_MODEL_IDS, ...MINIMAX_H3_IMAGE_MODELS].map((modelId) => ({ id: modelId, name: modelId, api: "minimax-images", provider, - baseUrl, - input: ["text", "image"], + baseUrl: isMiniMaxH3ImageModel(modelId) ? h3Url : baseUrl, + input: isMiniMaxH3ImageModel(modelId) ? ["text"] : ["text", "image"], output: ["image"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, })), diff --git a/packages/ai/src/image-models.generated.ts b/packages/ai/src/image-models.generated.ts index 9745d339..8f927e5c 100644 --- a/packages/ai/src/image-models.generated.ts +++ b/packages/ai/src/image-models.generated.ts @@ -560,6 +560,36 @@ export const IMAGE_MODELS = { "output": 0, "cacheRead": 0, "cacheWrite": 0 + } + } satisfies ImagesModel<"minimax-images">, + "MiniMax-H3-Image": { + id: "MiniMax-H3-Image", + name: "MiniMax-H3-Image", + api: "minimax-images", + provider: "minimax", + baseUrl: "https://api.minimax.io/v1/images/generations", + input: ["text"], + output: ["image"], + cost: { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + } + } satisfies ImagesModel<"minimax-images">, + "MiniMax-H3-Image-Highspeed": { + id: "MiniMax-H3-Image-Highspeed", + name: "MiniMax-H3-Image-Highspeed", + api: "minimax-images", + provider: "minimax", + baseUrl: "https://api.minimax.io/v1/images/generations", + input: ["text"], + output: ["image"], + cost: { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 } } satisfies ImagesModel<"minimax-images">, }, @@ -592,6 +622,36 @@ export const IMAGE_MODELS = { "output": 0, "cacheRead": 0, "cacheWrite": 0 + } + } satisfies ImagesModel<"minimax-images">, + "MiniMax-H3-Image": { + id: "MiniMax-H3-Image", + name: "MiniMax-H3-Image", + api: "minimax-images", + provider: "minimax-cn", + baseUrl: "https://api.minimax.cn/v1/images/generations", + input: ["text"], + output: ["image"], + cost: { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 + } + } satisfies ImagesModel<"minimax-images">, + "MiniMax-H3-Image-Highspeed": { + id: "MiniMax-H3-Image-Highspeed", + name: "MiniMax-H3-Image-Highspeed", + api: "minimax-images", + provider: "minimax-cn", + baseUrl: "https://api.minimax.cn/v1/images/generations", + input: ["text"], + output: ["image"], + cost: { + "input": 0, + "output": 0, + "cacheRead": 0, + "cacheWrite": 0 } } satisfies ImagesModel<"minimax-images">, }, diff --git a/packages/ai/src/index.ts b/packages/ai/src/index.ts index ed7aeaa8..70b9a773 100644 --- a/packages/ai/src/index.ts +++ b/packages/ai/src/index.ts @@ -4,6 +4,7 @@ export { Type } from "typebox"; export * from "./api-registry.ts"; export * from "./env-api-keys.ts"; export * from "./image-models.ts"; +export * from "./minimax-image-models.ts"; export * from "./images.ts"; export * from "./images-api-registry.ts"; export * from "./models.ts"; diff --git a/packages/ai/src/minimax-image-models.ts b/packages/ai/src/minimax-image-models.ts new file mode 100644 index 00000000..e8d4f792 --- /dev/null +++ b/packages/ai/src/minimax-image-models.ts @@ -0,0 +1,6 @@ +export const MINIMAX_H3_IMAGE_MODELS = ["MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed"] as const; +export const MINIMAX_H3_IMAGE_TIMEOUT_MS = 600_000; + +export function isMiniMaxH3ImageModel(id: string): boolean { + return MINIMAX_H3_IMAGE_MODELS.some(modelId => modelId === id); +} diff --git a/packages/ai/src/providers/images/minimax-h3.ts b/packages/ai/src/providers/images/minimax-h3.ts new file mode 100644 index 00000000..eb93432a --- /dev/null +++ b/packages/ai/src/providers/images/minimax-h3.ts @@ -0,0 +1,56 @@ +import { request } from "node:https"; +import { text } from "node:stream/consumers"; +import { MINIMAX_H3_IMAGE_TIMEOUT_MS } from "../../minimax-image-models.ts"; +import type { MiniMaxImagesOptions } from "./minimax.ts"; + +export function buildH3Payload(model: string, prompt: string, options: MiniMaxImagesOptions = {}) { + const { width, height, aspectRatio, n, seed, responseFormat, promptOptimizer } = options; + if (seed !== undefined) throw new Error("MiniMax H3 image generation does not support seed"); + if (n !== undefined && (!Number.isSafeInteger(n) || n < 1 || n > 10)) { + throw new Error("MiniMax H3 image count must be an integer between 1 and 10"); + } + + let size: string | undefined; + if (width !== undefined || height !== undefined) { + if (!width || !height || !Number.isSafeInteger(width) || !Number.isSafeInteger(height) + || width < 1 || height < 1 || width * height < 655360 || width * height > 20000000 + || width > 3 * height || height > 3 * width) { + throw new Error("MiniMax H3 requires both dimensions, 655360 to 20000000 pixels, and a ratio from 1:3 to 3:1"); + } + if (aspectRatio !== undefined) throw new Error("MiniMax H3 accepts either explicit dimensions or an aspect ratio"); + size = `${width}x${height}`; + } + if (promptOptimizer === false && !size && !aspectRatio) { + throw new Error("MiniMax H3 requires dimensions or an aspect ratio when prompt enhancement is disabled"); + } + return { + model, prompt, + ...(size ? { size } : {}), + ...(aspectRatio ? { aspect_ratio: aspectRatio } : {}), + ...(n === undefined ? {} : { n }), + ...(responseFormat ? { response_format: responseFormat === "base64" ? "b64_json" : responseFormat } : {}), + ...(promptOptimizer === undefined ? {} : { disable_prompt_enhanced: !promptOptimizer }), + }; +} + +// Node fetch can time out waiting for headers after five minutes. A single HTTPS +// request keeps the full H3 deadline and never follows a redirect or replays the POST. +export function postH3(url: string, body: string, headers: Headers, options: MiniMaxImagesOptions): + Promise> { + const timeoutMs = options.timeoutMs ?? MINIMAX_H3_IMAGE_TIMEOUT_MS; + if (!Number.isInteger(timeoutMs) || timeoutMs < MINIMAX_H3_IMAGE_TIMEOUT_MS || timeoutMs > 2_147_483_647) { + throw new Error("MiniMax H3 requires a timeout between 600000 and 2147483647 milliseconds"); + } + const deadline = AbortSignal.timeout(timeoutMs); + const signal = options.signal ? AbortSignal.any([deadline, options.signal]) : deadline; + return new Promise((resolve, reject) => { + const req = request(url, { method: "POST", headers: Object.fromEntries(headers), agent: false, signal }, res => { + const responseHeaders = new Headers(); + for (let i = 0; i < res.rawHeaders.length; i += 2) responseHeaders.append(res.rawHeaders[i], res.rawHeaders[i + 1]); + const status = res.statusCode ?? 0; + resolve({ status, ok: status >= 200 && status < 300, headers: responseHeaders, text: () => text(res) }); + }); + req.on("error", reject); + req.end(body); + }); +} diff --git a/packages/ai/src/providers/images/minimax.ts b/packages/ai/src/providers/images/minimax.ts index 23693775..f9314f7a 100644 --- a/packages/ai/src/providers/images/minimax.ts +++ b/packages/ai/src/providers/images/minimax.ts @@ -6,6 +6,8 @@ import type { ImagesModel, ImagesOptions, } from "../../types.ts"; +import { isMiniMaxH3ImageModel } from "../../minimax-image-models.ts"; +import { buildH3Payload, postH3 } from "./minimax-h3.ts"; import { isIP } from "node:net"; import { headersToRecord } from "../../utils/headers.ts"; import { sanitizeSurrogates } from "../../utils/sanitize-unicode.ts"; @@ -57,6 +59,12 @@ interface MiniMaxImageGenerationResponse { }; } +interface H3Response { + request_id?: string; + error?: { message?: string }; + data?: Array<{ url?: string; b64_json?: string; error?: { code?: string; message?: string } }>; +} + export const generateImagesMiniMax: ImagesFunction<"minimax-images", MiniMaxImagesOptions> = async ( model: ImagesModel<"minimax-images">, context: ImagesContext, @@ -80,25 +88,39 @@ export const generateImagesMiniMax: ImagesFunction<"minimax-images", MiniMaxImag throw new Error("Request was aborted"); } - let payload = buildPayload(model, context, options); - const nextPayload = await options?.onPayload?.(payload, model); - if (nextPayload !== undefined) { - payload = nextPayload as MiniMaxImageGenerationRequest; - } - - const response = await fetch(model.baseUrl, { - method: "POST", - headers: buildHeaders(apiKey, model.headers, options?.headers), - body: JSON.stringify(payload), - signal: createRequestSignal(options), - }); + const h3 = isMiniMaxH3ImageModel(model.id); + const payload = buildPayload(model, context, options); + const replacement = await options?.onPayload?.(payload, model); + const body = JSON.stringify(replacement === undefined ? payload : replacement); + const headers = buildHeaders(apiKey, model.headers, options?.headers); + const response = h3 + ? await postH3(model.baseUrl, body, headers, options ?? {}) + : await fetch(model.baseUrl, { method: "POST", headers, body, signal: createRequestSignal(options) }); await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model); const responseText = await response.text(); - const responseBody = parseResponseBody(responseText); + if (h3) { + const parsed = parseResponseBody(responseText); + if (!response.ok || parsed.error) { + throw new Error(parsed.error?.message || `MiniMax H3 image generation failed with HTTP ${response.status}`); + } + output.responseId = parsed.request_id; + const warnings: string[] = []; + for (const [index, item] of (parsed.data ?? []).entries()) { + if (item.error) warnings.push(`Image ${index + 1}: ${item.error.message || item.error.code || "generation failed"}`); + else if (item.b64_json) output.output.push(base64ToContent(item.b64_json)); + else if (item.url) output.output.push(await imageUrlToContent(item.url, options)); + else warnings.push(`Image ${index + 1}: missing image data`); + } + if (!output.output.length) throw new Error(warnings.join("; ") || "MiniMax H3 image generation returned no images"); + for (const text of warnings) output.output.push({ type: "text", text }); + return output; + } + + const responseBody = parseResponseBody(responseText); const statusCode = responseBody.base_resp?.status_code; if (!response.ok || (statusCode !== undefined && statusCode !== 0)) { - throw new Error(getErrorMessage(response, responseBody)); + throw new Error(getErrorMessage(response.status, responseBody)); } output.responseId = responseBody.id; @@ -125,7 +147,7 @@ function buildPayload( model: ImagesModel<"minimax-images">, context: ImagesContext, options?: MiniMaxImagesOptions, -): MiniMaxImageGenerationRequest { +): MiniMaxImageGenerationRequest | ReturnType { const subjectReference = context.input .filter((item): item is ImageContent => item.type === "image") .map((item) => ({ @@ -141,6 +163,10 @@ function buildPayload( if (!prompt) { throw new Error("MiniMax image generation requires a text prompt"); } + if (isMiniMaxH3ImageModel(model.id)) { + if (subjectReference.length) throw new Error("MiniMax H3 image generation accepts text input only"); + return buildH3Payload(model.id, prompt, options); + } if (options?.n !== undefined && (!Number.isSafeInteger(options.n) || options.n < 1 || options.n > MAX_IMAGE_COUNT)) { throw new Error(`MiniMax image generation n must be an integer between 1 and ${MAX_IMAGE_COUNT}`); } @@ -182,21 +208,21 @@ function createRequestSignal(options?: MiniMaxImagesOptions): AbortSignal | unde return options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal; } -function parseResponseBody(responseText: string): MiniMaxImageGenerationResponse { - if (!responseText) return {}; +function parseResponseBody(responseText: string): T { + if (!responseText) return {} as T; try { - return JSON.parse(responseText) as MiniMaxImageGenerationResponse; + return JSON.parse(responseText) as T; } catch { throw new Error("MiniMax image generation returned invalid JSON"); } } -function getErrorMessage(response: Response, responseBody: MiniMaxImageGenerationResponse): string { +function getErrorMessage(httpStatus: number, responseBody: MiniMaxImageGenerationResponse): string { const statusMessage = responseBody.base_resp?.status_msg?.trim(); if (statusMessage) return `MiniMax image generation failed: ${statusMessage}`; const statusCode = responseBody.base_resp?.status_code; if (statusCode !== undefined) return `MiniMax image generation failed with status code ${statusCode}`; - return `MiniMax image generation failed with HTTP ${response.status}`; + return `MiniMax image generation failed with HTTP ${httpStatus}`; } async function imageUrlToContent(imageUrl: string, options?: MiniMaxImagesOptions): Promise { diff --git a/packages/ai/test/minimax-h3-images.test.ts b/packages/ai/test/minimax-h3-images.test.ts new file mode 100644 index 00000000..48740f1d --- /dev/null +++ b/packages/ai/test/minimax-h3-images.test.ts @@ -0,0 +1,84 @@ +import { Readable } from "node:stream"; +import { afterEach, expect, it, vi } from "vitest"; +import { getImageModel } from "../src/image-models.ts"; +import { generateImages } from "../src/images.ts"; + +const { request } = vi.hoisted(() => ({ request: vi.fn() })); +vi.mock("node:https", async importOriginal => ({ ...await importOriginal(), request })); + +const prompt = { input: [{ type: "text" as const, text: "A blue sailboat" }] }; +const png = "iVBORw0KGgo="; + +function respond(status: number, body: unknown) { + const end = vi.fn(); + request.mockImplementation((_url, _options, callback) => ({ + on: vi.fn(), + end: (data: string) => { + end(JSON.parse(data)); + callback(Object.assign(Readable.from([JSON.stringify(body)]), { statusCode: status, rawHeaders: [] })); + }, + })); + return end; +} + +afterEach(() => { + vi.resetAllMocks(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +it.each([ + ["minimax", "MiniMax-H3-Image", "https://api.minimax.io/v1/images/generations"], + ["minimax-cn", "MiniMax-H3-Image-Highspeed", "https://api.minimax.cn/v1/images/generations"], +] as const)("submits a single H3 request through %s and retains partial output", async (provider, id, url) => { + const deadline = vi.spyOn(AbortSignal, "timeout"); + const end = respond(200, { request_id: "h3-result", data: [ + { b64_json: png, size: "1024x1024" }, + { error: { code: "1027", message: "image withheld" } }, + ] }); + const onResponse = vi.fn(); + const model = getImageModel(provider, id); + expect(model.input).toEqual(["text"]); + const result = await generateImages(model, prompt, { + apiKey: "test-key", responseFormat: "base64", width: 1024, height: 1024, n: 2, promptOptimizer: false, onResponse, + }); + expect(end).toHaveBeenCalledWith({ model: id, prompt: "A blue sailboat", size: "1024x1024", n: 2, + disable_prompt_enhanced: true, response_format: "b64_json" }); + expect(request).toHaveBeenCalledExactlyOnceWith(url, expect.objectContaining({ + method: "POST", headers: expect.objectContaining({ authorization: "Bearer test-key" }), + }), expect.any(Function)); + expect(deadline).toHaveBeenCalledWith(600_000); + expect(onResponse).toHaveBeenCalledOnce(); + expect(result).toMatchObject({ responseId: "h3-result", stopReason: "stop", output: [ + { type: "image", mimeType: "image/png", data: png }, { type: "text", text: "Image 2: image withheld" }, + ] }); +}); + +it("downloads URL output without forwarding generation credentials", async () => { + respond(200, { data: [{ url: "https://images.example.test/image" }] }); + const download = vi.fn().mockResolvedValue(new Response(Buffer.from(png, "base64"))); + vi.stubGlobal("fetch", download); + const result = await generateImages(getImageModel("minimax", "MiniMax-H3-Image"), prompt, { apiKey: "test-key" }); + expect(result.output).toEqual([{ type: "image", mimeType: "image/png", data: png }]); + expect(download).toHaveBeenCalledExactlyOnceWith(new URL("https://images.example.test/image"), + expect.objectContaining({ redirect: "error" })); + expect(download.mock.calls[0][1].headers).toBeUndefined(); +}); + +it.each([307, 402, 422, 429, 500])("surfaces HTTP %i without retrying", async status => { + respond(status, { error: { message: "request failed", http_code: String(status) } }); + const result = await generateImages(getImageModel("minimax", "MiniMax-H3-Image"), prompt, + { apiKey: "test-key", maxRetries: 3 }); + expect(result).toMatchObject({ stopReason: "error", errorMessage: "request failed" }); + expect(request).toHaveBeenCalledOnce(); +}); + +it("rejects reference images, seeds and short deadlines before sending a generation", async () => { + const model = getImageModel("minimax", "MiniMax-H3-Image"); + const withImage = { input: [...prompt.input, { type: "image" as const, data: png, mimeType: "image/png" }] }; + for (const [context, options] of [[withImage, {}], [prompt, { seed: 1 }], [prompt, { timeoutMs: 90000 }]] as const) { + const result = await generateImages(model, context, { apiKey: "test-key", ...options }); + expect(result.stopReason).toBe("error"); + } + expect(request).not.toHaveBeenCalled(); +}); diff --git a/packages/ai/test/minimax-images.test.ts b/packages/ai/test/minimax-images.test.ts index 680d5e58..6a17f27b 100644 --- a/packages/ai/test/minimax-images.test.ts +++ b/packages/ai/test/minimax-images.test.ts @@ -23,7 +23,7 @@ describe("MiniMax images", () => { provider: "minimax-cn", baseUrl: "https://api.minimaxi.com/v1/image_generation", }); - expect(getImageModels("minimax").map((model) => model.id)).toEqual(["image-01", "image-01-live"]); + expect(getImageModels("minimax").map((model) => model.id)).toEqual(["image-01", "image-01-live", "MiniMax-H3-Image", "MiniMax-H3-Image-Highspeed"]); }); it("sends supported text-to-image fields and parses base64 output", async () => { diff --git a/src/cli/commands/media.ts b/src/cli/commands/media.ts index 3ec9eeb5..caad1f8f 100644 --- a/src/cli/commands/media.ts +++ b/src/cli/commands/media.ts @@ -1,4 +1,5 @@ import { defineCommand } from 'citty'; +import { isMiniMaxH3ImageModel } from '@memorix/ai'; import { loadDotenv } from '../../config/dotenv-loader.js'; import { attachMediaAssetToObservation } from '../../media/attachment.js'; @@ -12,6 +13,7 @@ import { MediaStore } from '../../media/media-store.js'; import { derivePdfText } from '../../media/pdf.js'; import { generateMiniMaxImages, + resolveImageModel, type MiniMaxImageGenerationInput, type MiniMaxVideoGenerationRequest, } from '../../media/minimax.js'; @@ -66,13 +68,6 @@ function parseAspectRatio(value: unknown): MiniMaxImageGenerationInput['aspectRa return ratio as MiniMaxImageGenerationInput['aspectRatio']; } -function parseMiniMaxModel(value: unknown): MiniMaxImageGenerationInput['model'] | undefined { - if (value === undefined || value === null || value === '') return undefined; - const model = String(value).trim(); - if (model === 'image-01' || model === 'image-01-live') return model; - throw new Error('MiniMax image model must be image-01 or image-01-live'); -} - function parseMiniMaxRegion(value: unknown): MiniMaxImageGenerationInput['region'] | undefined { if (value === undefined || value === null || value === '') return undefined; const region = String(value).trim().toLowerCase(); @@ -231,18 +226,20 @@ export default defineCommand({ const subjectImages = referenceImagePath ? [await readSubjectImage(referenceImagePath)] : undefined; + const model = resolveImageModel(getValue(args.model)); + const optimize = args.promptOptimizer === true || args['prompt-optimizer'] === true; const generated = await generateMiniMaxImages({ dataDir, projectId: project.id, prompt, - model: parseMiniMaxModel(args.model), + model, region: parseMiniMaxRegion(args.region), n: parseOptionalInteger(args.n, 'n', 1, 4), aspectRatio: parseAspectRatio(args.ratio), width: parseOptionalInteger(args.width, 'width', 1, 8_192), height: parseOptionalInteger(args.height, 'height', 1, 8_192), seed: parseOptionalInteger(args.seed, 'seed', 0, 2_147_483_647), - promptOptimizer: args.promptOptimizer === true || args['prompt-optimizer'] === true, + ...(optimize || !isMiniMaxH3ImageModel(model) ? { promptOptimizer: optimize } : {}), subjectImages, maxBytes: parseByteLimit(args.maxBytes ?? args['max-bytes'], 100 * 1024 * 1024), }); @@ -259,7 +256,8 @@ export default defineCommand({ : []; emitResult( { project, ...generated, observations }, - `Generated ${generated.assets.length} controlled image asset(s)${observations.length > 0 ? ` and attached ${observations.length} to memory` : ''}.`, + `Generated ${generated.assets.length} controlled image asset(s)${observations.length > 0 ? ` and attached ${observations.length} to memory` : ''}.` + + (generated.warnings?.length ? '\n' + generated.warnings.join('\n') : ''), asJson, ); return; diff --git a/src/media/minimax.ts b/src/media/minimax.ts index 13ed5f0f..7186298a 100644 --- a/src/media/minimax.ts +++ b/src/media/minimax.ts @@ -1,6 +1,9 @@ import { generateImages, getImageModel, + MINIMAX_H3_IMAGE_MODELS, + MINIMAX_H3_IMAGE_TIMEOUT_MS, + isMiniMaxH3ImageModel, type ImageContent, type ImagesInputContent, } from '@memorix/ai'; @@ -9,7 +12,7 @@ import { sanitizeCredentials } from '../memory/secret-filter.js'; import { importMediaBuffer } from './asset-store.js'; import type { MediaImportResult } from './types.js'; -const IMAGE_MODELS = ['image-01', 'image-01-live'] as const; +const IMAGE_MODELS = ['image-01', 'image-01-live', ...MINIMAX_H3_IMAGE_MODELS] as const; const MAX_PROMPT_LENGTH = 12_000; const DEFAULT_IMAGE_TIMEOUT_MS = 90_000; @@ -43,6 +46,7 @@ export interface GeneratedMiniMaxImages { model: MiniMaxImageModel; responseId?: string; assets: MediaImportResult[]; + warnings?: string[]; } export interface MiniMaxVideoGenerationRequest { @@ -84,7 +88,7 @@ export interface MiniMaxImageGenerator { promptOptimizer?: boolean; subjectImages?: Array<{ data: string; mimeType: string }>; timeoutMs: number; - }): Promise<{ responseId?: string; output: ImageContent[] }>; + }): Promise<{ responseId?: string; output: ImageContent[]; warnings?: string[] }>; } function requiredString(value: string | undefined, label: string): string { @@ -100,7 +104,7 @@ function resolveRegion(value: MiniMaxRegion | undefined): MiniMaxRegion { throw new Error('MiniMax region must be "global" or "cn"'); } -function resolveImageModel(value: string | undefined): MiniMaxImageModel { +export function resolveImageModel(value: string | undefined): MiniMaxImageModel { const model = value?.trim() || process.env.MINIMAX_IMAGE_MODEL?.trim() || 'image-01'; if ((IMAGE_MODELS as readonly string[]).includes(model)) return model as MiniMaxImageModel; throw new Error(`Unsupported MiniMax image model: ${model}. Supported models: ${IMAGE_MODELS.join(', ')}`); @@ -372,8 +376,10 @@ const defaultImageGenerator: MiniMaxImageGenerator = async (input) => { if (response.stopReason !== 'stop') { throw new Error(response.errorMessage || 'MiniMax image generation did not complete'); } + const warnings = response.output.flatMap(item => item.type === 'text' ? [sanitizeCredentials(item.text)] : []); return { responseId: response.responseId, + ...(warnings.length ? { warnings } : {}), output: response.output.filter((item): item is ImageContent => item.type === 'image'), }; }; @@ -395,12 +401,15 @@ export async function generateMiniMaxImages( region === 'cn' ? 'MINIMAX_CN_API_KEY' : 'MINIMAX_API_KEY', ); const baseUrl = resolveBaseUrl(input.baseUrl ?? process.env.MINIMAX_IMAGE_BASE_URL); - const timeoutMs = input.timeoutMs ?? DEFAULT_IMAGE_TIMEOUT_MS; - if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000 || timeoutMs > 5 * 60_000) { - throw new Error('MiniMax image timeout must be between 1000 and 300000 milliseconds'); + const h3 = isMiniMaxH3ImageModel(model); + const timeoutMs = input.timeoutMs ?? (h3 ? MINIMAX_H3_IMAGE_TIMEOUT_MS : DEFAULT_IMAGE_TIMEOUT_MS); + const minTimeout = h3 ? MINIMAX_H3_IMAGE_TIMEOUT_MS : 1_000; + const maxTimeout = h3 ? 2_147_483_647 : 5 * 60_000; + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < minTimeout || timeoutMs > maxTimeout) { + throw new Error(`MiniMax image timeout must be between ${minTimeout} and ${maxTimeout} milliseconds`); } - let generated: { responseId?: string; output: ImageContent[] }; + let generated: { responseId?: string; output: ImageContent[]; warnings?: string[] }; try { generated = await (dependencies.generate ?? defaultImageGenerator)({ provider, @@ -439,5 +448,6 @@ export async function generateMiniMaxImages( model, ...(generated.responseId ? { responseId: generated.responseId } : {}), assets, + ...(generated.warnings?.length ? { warnings: generated.warnings } : {}), }; } diff --git a/src/server.ts b/src/server.ts index efd2f38b..22f03bf0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -5512,10 +5512,6 @@ export async function createMemorixServer( throw new Error('MCP media generation is disabled. Use the CLI, or set MEMORIX_MCP_MEDIA_GENERATION=1 after reviewing provider billing.'); } if (!prompt?.trim()) throw new Error('prompt is required for image generation'); - const imageModel: 'image-01' | 'image-01-live' | undefined = model === 'image-01' || model === 'image-01-live' - ? model - : undefined; - if (model && !imageModel) throw new Error('generate-image accepts image-01 or image-01-live'); const imageRatio: '1:1' | '16:9' | '4:3' | '3:2' | '2:3' | '3:4' | '9:16' | '21:9' | undefined = ratio === '1:1' || ratio === '16:9' || ratio === '4:3' || ratio === '3:2' || ratio === '2:3' || ratio === '3:4' || ratio === '9:16' || ratio === '21:9' @@ -5530,12 +5526,12 @@ export async function createMemorixServer( if (!mimeType) throw new Error('Reference image must be a PNG, JPEG, GIF, or WebP image'); subjectImages = [{ data: bytes.toString('base64'), mimeType }]; } - const { generateMiniMaxImages } = await import('./media/minimax.js'); + const { generateMiniMaxImages, resolveImageModel } = await import('./media/minimax.js'); const generated = await generateMiniMaxImages({ dataDir: projectDir, projectId: project.id, prompt, - model: imageModel, + model: resolveImageModel(model), region, n, aspectRatio: imageRatio, diff --git a/tests/media/minimax.test.ts b/tests/media/minimax.test.ts index 63fb5a99..a8ffb77b 100644 --- a/tests/media/minimax.test.ts +++ b/tests/media/minimax.test.ts @@ -67,6 +67,29 @@ describe('MiniMax controlled image generation', () => { await expect(readMediaAsset(fixture.dataDir, result.assets[0].asset)).resolves.toEqual(PNG_BYTES); }); + it('keeps successful H3 assets and reports per-image failures', async () => { + const fixture = await createFixture(); + const result = await generateMiniMaxImages({ + ...fixture, model: 'MiniMax-H3-Image-Highspeed', region: 'cn', + apiKey: 'test-key', prompt: 'A blue sailboat', n: 2, + }, { + generate: async request => { + expect(request).toMatchObject({ + provider: 'minimax-cn', model: 'MiniMax-H3-Image-Highspeed', timeoutMs: 600_000, + }); + return { + responseId: 'h3-image-request', + output: [{ type: 'image', mimeType: 'image/png', data: PNG_BYTES.toString('base64') }], + warnings: ['Image 2: image withheld'], + }; + }, + }); + expect(result).toMatchObject({ + responseId: 'h3-image-request', warnings: ['Image 2: image withheld'], + assets: [{ asset: { kind: 'image', model: 'MiniMax-H3-Image-Highspeed' } }], + }); + }); + it('forwards reference images to the image generator for image-to-image', async () => { const fixture = await createFixture(); const generate = async (request: any) => {