From 97fdba8ca6629dc846926b3f2ba792a0af2f4b9f Mon Sep 17 00:00:00 2001 From: Klarkxy Date: Thu, 12 Nov 2026 08:47:15 +0800 Subject: [PATCH] minimax 0.2.8: native Magpie image, video and web search (#1008) MiniMax Code accounts now serve magpie's image, video and web search natively: /v1/images/generations and /v1/images/edits through generate_image, video through submit_video_generation, and search through the connector's web tools. - Edits: magpie's multipart body (model, prompt, n, size, quality, image / image[] parts) is parsed, and each image goes through the live catalog's upload_temp_url signed-form flow. A mask part is refused with a 400 (generate_image takes no mask). A video frame sent as data: is uploaded the same way, and https refs pass through. - A 401 is renewed per tool call, and only that call is sent again, so a 401 on get_asset_url never runs a paid generate_image twice. - Upload hosts are https only. A video download drops content-encoding and content-length (fetch already decoded it). - Envelope refusals carry a status: 1002, 1039, 1041, 1045, 2045, 2056 and 2062 are 429; 1008 and 2053 are 402 (MiniMax's published error codes, not confirmed for the MiniMax Code agent API). - 0.2.8, since 0.2.7 (#1014) is on npm. native.mjs is in files. What was run at c020d32e51f9b28e29528ea59d38bc167baf8624 (temp HOME, fake fetch only, no real MiniMax calls): - mote (macOS): bun test packages/minimax, 193 pass, 0 fail. bun scripts/check.mjs exit 0. - WSL Ubuntu 24.04: 193 pass, 0 fail. - Broken by hand, one at a time, each turned a test red: no per-call 401 renewal (2), mask accepted (1), http upload host accepted (1), no envelope status (2), content-encoding kept (1). Earlier rounds broke multipart parsing, the status in toolHttpError and mediaRef's schemes, each red too. - Merges cleanly onto main 234e073c. Not tried: the real upload_temp_url answer, the /visible/ wait (8s) against MiniMax, and a real magpie drawing through a MiniMax account. --- packages/minimax/README.md | 39 ++ packages/minimax/connector-tools.mjs | 11 + packages/minimax/index.mjs | 215 +++++-- packages/minimax/models.test.mjs | 14 +- packages/minimax/native.mjs | 823 +++++++++++++++++++++++++++ packages/minimax/native.test.mjs | 671 ++++++++++++++++++++++ packages/minimax/package.json | 4 +- 7 files changed, 1718 insertions(+), 59 deletions(-) create mode 100644 packages/minimax/native.mjs create mode 100644 packages/minimax/native.test.mjs diff --git a/packages/minimax/README.md b/packages/minimax/README.md index aeec6a2..02b9241 100644 --- a/packages/minimax/README.md +++ b/packages/minimax/README.md @@ -81,6 +81,45 @@ that server to your agent to use the tools with any of its chat models. | `get_asset_url` | Get a fresh download URL for a generated asset's `node_id` | | `list_tools`, `tool_schema`, `call_tool` | Discover and call the account's current Matrix tools and read their live schemas | +## Native Magpie image, video, and web search + +This plugin also registers MiniMax Code as a backend for Magpie's built-in +media and search, so you can use them from Settings and drop the named tools +from an agent's catalog if you only need those three capabilities. The named +tools above stay available. + +Once you are signed in to MiniMax Code (China) or MiniMax Code (Global): + +- **Image generation** (Settings → Models → Images → Image generation, served + at `/mcp/magpie/image`): choose **MiniMax Image**. Text-to-image uses the + same Matrix `generate_image` API as the named tool (a `requests` array, then + `get_asset_url` for the download URL). Magpie sends edits as multipart + form data; the image bytes, and any `data:` URL, are uploaded through MiniMax Code's `upload_temp_url` flow + before `generate_image`. HTTPS URLs are passed through. `generate_image` + takes no mask, so a mask edit is refused (HTTP 400). A size such as + `1024x1024` is mapped to MiniMax's `area` (so it does not fall through to + the vendor's 4K default). Right after a generation, `get_asset_url` may + first answer a watermarked `/visible/` URL (#974); the plugin waits a + few seconds and asks again for the original. +- **Video generation** (Settings → Models → Images → Video generation, served + through Magpie's videos API): choose **MiniMax H3**, **MiniMax H3 Max**, or + **MiniMax Hailuo 2.3**. A job is submitted with `submit_video_generation` and + polled with `query_video_generation`, using those real model ids. Text-to-video + works out of the box. A first or last frame given as a `data:` URL is + uploaded the same way; an HTTPS URL is passed through. +- **Web search** (Settings → Models → Web search → Search APIs, served at + `/mcp/magpie/web-search`): enable **MiniMax Code** or **MiniMax Code (Global)** + in the search API list. Searches use `/mavis/api/v1/mcp/web_search` with the + signed-in account, the same API as the `web_search` tool. No separate API key + is needed. + +The image and video models also appear on the MiniMax Code provider's model +list (they give images or video, not chat). Leave chat on M3 / M2.7. + +Magpie's Library can already give skills to the **MiniMax Code** desktop app +when Magpie detects that app on the machine. That target lives in Magpie +itself, not in this plugin. + On the combined MCP server these are named `minimax_generate_image`, `minimax_submit_video_generation`, and so on. In the Library's routed server, the separator is `minimax__generate_image`. diff --git a/packages/minimax/connector-tools.mjs b/packages/minimax/connector-tools.mjs index 288fb1f..2665e6b 100644 --- a/packages/minimax/connector-tools.mjs +++ b/packages/minimax/connector-tools.mjs @@ -264,6 +264,17 @@ export function compactToolsOn(options) { return options?.compactTools === true } +// callMatrixTool runs one Matrix tool on the live catalog, the way the +// named tools do: list, route, then call. Native Magpie image/video +// generation uses this so it talks to the same connector APIs. +export async function callMatrixTool(request, site, name, args, { signal, timeoutMs, account } = {}) { + if (typeof request !== "function") throw new Error("callMatrixTool needs the request transport") + const short = name.startsWith(MATRIX) ? name.slice(MATRIX.length) : name + const cat = await catalog(request, site, signal, account) + const entry = find(cat, MATRIX + short) + return invoke(request, site, entry, args ?? {}, signal, timeoutMs ?? (LONG.has(short) ? GEN_MS : CALL_MS), account) +} + export function createConnectorTools(request, options = {}) { if (typeof request !== "function") throw new Error("createConnectorTools needs the request transport") const tool = {} diff --git a/packages/minimax/index.mjs b/packages/minimax/index.mjs index 31ed64b..1675194 100644 --- a/packages/minimax/index.mjs +++ b/packages/minimax/index.mjs @@ -15,6 +15,7 @@ import { readFile } from "node:fs/promises" import { join } from "node:path" import { compactToolsOn, createConnectorTools } from "./connector-tools.mjs" import { createWebTools } from "./web-tools.mjs" +import { mediaConfigModels, withMediaModels, createSearchHook, handleMediaFetch } from "./native.mjs" const CLIENT_ID = "mcode-public" const SCOPE = "agent.default" @@ -200,19 +201,22 @@ function variants(m) { const reasons = (m) => m.thinking !== "off" function configModels(magpie) { - return Object.fromEntries(MODELS.map((m) => { - const inputs = inputsOf(m, magpie) - return [m.id, { - name: m.name, - reasoning: reasons(m), - tool_call: true, - attachment: attachment(m, inputs), - modalities: { input: inputs, output: ["text"] }, - limit: limits(m.id, m.context, m.output), - cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 }, - variants: variants(m), - }] - })) + return { + ...Object.fromEntries(MODELS.map((m) => { + const inputs = inputsOf(m, magpie) + return [m.id, { + name: m.name, + reasoning: reasons(m), + tool_call: true, + attachment: attachment(m, inputs), + modalities: { input: inputs, output: ["text"] }, + limit: limits(m.id, m.context, m.output), + cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 }, + variants: variants(m), + }] + })), + ...mediaConfigModels(), + } } function modelOf(site, provider, m, magpie) { @@ -1035,6 +1039,8 @@ function makePlugin(site) { p.api ??= api(site) p.models = { ...configModels(host), ...(p.models ?? {}) } }, + // Magpie lists this beside Tavily and the rest, signed in as this site + search: createSearchHook(site, (access, path, body, opts) => postTool(site, access, path, body, opts)), // the conversation's id, which MiniMax Code sends with each request "chat.headers": async (input, output) => { const id = input?.model?.providerID ?? input?.provider?.info?.id @@ -1050,7 +1056,7 @@ function makePlugin(site) { const { a } = await fresh(async () => auth) const ms = await liveModels(site, a.access) if (!ms.length) return provider.models - return Object.fromEntries(ms.map((m) => [m.id, modelOf(site, provider, m, host)])) + return withMediaModels(Object.fromEntries(ms.map((m) => [m.id, modelOf(site, provider, m, host)])), site, provider) } catch (e) { if (e instanceof SignInExpired) throw e return provider.models @@ -1086,7 +1092,8 @@ function makePlugin(site) { async fetch(input, init) { const req = input instanceof Request ? input : null let body = init?.body - if (body === undefined && req) body = await req.clone().text() + if (body === undefined && req) body = await req.clone().arrayBuffer() + const url = req ? req.url : input instanceof URL ? input.href : input const send = (a) => { const headers = new Headers(init?.headers ?? req?.headers) headers.delete("content-length") @@ -1103,11 +1110,27 @@ function makePlugin(site) { // waits for the last. Asked uncompressed, it sends the // events as they come. headers.set("accept-encoding", "identity") - return siteFetch(site, req ? req.url : input instanceof URL ? input.href : input, { ...init, method: init?.method ?? req?.method ?? "POST", headers, body }, "chat") + return siteFetch(site, url, { ...init, method: init?.method ?? req?.method ?? "POST", headers, body }, "chat") } let { a, renewed: did } = await fresh(getAuth) + // A 401 is renewed per tool call inside the transport, and + // only that call is asked again: retrying the whole media + // request would run a paid generate_image a second time when + // the 401 came on the get_asset_url after it. + const mediaRequest = makeTokenRequest(site, a.access, async (rejected) => { + ;({ a } = await fresh(getAuth, rejected)) + did = true + return a.access + }) let res try { + res = await handleMediaFetch(url, { + method: init?.method ?? req?.method ?? "POST", + body, + headers: init?.headers ?? req?.headers, + signal: init?.signal ?? req?.signal, + }, { request: mediaRequest, siteId: site.id }) + if (res) return answer(res, did) res = await send(a) if (res.status === 401) { // the token was turned away before its end: a newer one @@ -1248,6 +1271,124 @@ function makePlugin(site) { // Tools run outside a chat account's scope. Read the explicitly selected // account afresh for each call; the site's first stored account is the default. +function toolHttpError(site, status) { + return Object.assign(new Error(site.name + " tool API: HTTP " + status), { status }) +} + +function redactSecrets(message, secrets) { + let out = String(message) + for (const secret of secrets) if (secret) out = out.replaceAll(secret, "") + return out +} + +function toolRequestInit(site, access, path, body, abort) { + return { + url: new URL(path, site.llm).href, + init: { + method: "POST", + headers: { "Content-Type": "application/json", "User-Agent": "MiniMaxAgent", Authorization: "Bearer " + access }, + body: JSON.stringify(body ?? {}), + signal: abort, + }, + what: site.name + " tool API", + } +} + +// MiniMax reports some account refusals inside the envelope (HTTP 200) +// rather than as an HTTP status. These codes, from MiniMax's published +// error code list, are thrown with the HTTP status they mean, so magpie +// rests the account for search the way it does for a real 429 or 402: +// rate, token, connection and plan-window limits are 429; no balance or +// credit is 402. Any other code is thrown with no status. +const REFUSAL_STATUS = new Map([ + [1002, 429], [1039, 429], [1041, 429], [1045, 429], [2045, 429], [2056, 429], [2062, 429], + [1008, 402], [2053, 402], +]) +function envelopeError(code, message) { + const err = new Error("MiniMax tool API: " + (message ?? "status " + code)) + const status = REFUSAL_STATUS.get(code) + if (status) err.status = status + return err +} + +// parseToolEnvelope reads one tool API response: a non-OK status is +// thrown with that status (so a 401 can be renewed), then the JSON +// envelope and base_resp are checked the same way for chat tools and +// the native media/search path. +async function parseToolEnvelope(res, site, abort) { + if (!res.ok) throw toolHttpError(site, res.status) + let env + try { env = obj(JSON.parse(await res.text())) } catch { + abort.throwIfAborted() + throw new Error("MiniMax tool API: invalid JSON response") + } + if (!env) throw new Error("MiniMax tool API: expected a JSON object") + if (env.code !== undefined) { + const { code: rawCode, message, ...payload } = env + const code = num(rawCode) + if (code === undefined) throw new Error("MiniMax tool API: invalid response code") + if (code !== 0) throw envelopeError(code, str(env, "message")) + if (env.base_resp === undefined) env = { ...payload, base_resp: { status_code: code, status_msg: message } } + } + if (env.base_resp !== undefined) { + const br = obj(env.base_resp) + const code = br && num(br.status_code) + if (code === undefined) throw new Error("MiniMax tool API: invalid base_resp") + if (code !== 0) throw envelopeError(code, str(br, "status_msg")) + } + checked(env, "MiniMax tool API") + abort.throwIfAborted() + return env +} + +async function postTool(site, access, path, body, { signal, timeoutMs = 30000 } = {}) { + const abort = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])]) + abort.throwIfAborted() + const req = toolRequestInit(site, access, path, body, abort) + const res = await siteFetch(site, req.url, req.init, req.what) + try { + return await parseToolEnvelope(res, site, abort) + } catch (e) { + e.message = redactSecrets(e.message, [access]) + throw e + } +} + +// makeTokenRequest is the tool transport for one signed-in account. Like +// createToolRequest, a 401 is renewed per HTTP call: renewAccess(rejected) +// gives a newer token, and only the call that got the 401 is sent again. +// Later calls keep the newer token. Without renewAccess a 401 is thrown +// with its status. +function makeTokenRequest(site, access, renewAccess) { + let current = access + const secrets = new Set([access]) + return async (siteID, path, body, { signal, timeoutMs = 30000 } = {}) => { + if (siteID !== site.id) throw new Error("account must belong to the selected MiniMax Code site") + const abort = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(signal ? [signal] : [])]) + abort.throwIfAborted() + const send = (token) => { + abort.throwIfAborted() + const req = toolRequestInit(site, token, path, body, abort) + return siteFetch(site, req.url, req.init, req.what) + } + try { + const sent = current + let res = await send(sent) + if (res.status === 401 && renewAccess) { + await res.body?.cancel() + // another call may have renewed it already + if (current === sent) current = await renewAccess(sent) + secrets.add(current) + res = await send(current) + } + return await parseToolEnvelope(res, site, abort) + } catch (e) { + e.message = redactSecrets(e.message, secrets) + throw e + } + } +} + function createToolRequest({ client, directory }) { const sessions = new Map() return async (siteID, path, body, { signal, timeoutMs = 30000, account } = {}) => { @@ -1293,18 +1434,10 @@ function createToolRequest({ client, directory }) { const fresh = sessions.get(id) let { a } = await wait(fresh(getAuth)) const secrets = new Set([a.access, a.refresh].filter(Boolean)) - const redact = (message) => { - let out = String(message) - for (const secret of secrets) out = out.replaceAll(secret, "") - return out - } const send = (auth) => { abort.throwIfAborted() - const req = { - url: new URL(path, site.llm).href, - init: { method: "POST", headers: { "Content-Type": "application/json", "User-Agent": "MiniMaxAgent", Authorization: "Bearer " + auth.access }, body: JSON.stringify(body) }, - } - return siteFetch(site, req.url, { ...req.init, signal: abort }, site.name + " tool API") + const req = toolRequestInit(site, auth.access, path, body, abort) + return siteFetch(site, req.url, req.init, req.what) } try { let res = await send(a) @@ -1317,34 +1450,10 @@ function createToolRequest({ client, directory }) { if (a.refresh) secrets.add(a.refresh) res = await send(a) } - if (!res.ok) throw new Error(site.name + " tool API: HTTP " + res.status) - let env - try { env = obj(JSON.parse(await res.text())) } catch (e) { - abort.throwIfAborted() - throw new Error("MiniMax tool API: invalid JSON response") - } - if (!env) throw new Error("MiniMax tool API: expected a JSON object") - // The gateway may succeed while the tool payload reports a billing - // or execution error. Both status layers must pass independently. - if (env.code !== undefined) { - const { code: rawCode, message, ...payload } = env - const code = num(rawCode) - if (code === undefined) throw new Error("MiniMax tool API: invalid response code") - if (code !== 0) throw new Error("MiniMax tool API: " + (str(env, "message") ?? "status " + code)) - if (env.base_resp === undefined) env = { ...payload, base_resp: { status_code: code, status_msg: message } } - } - if (env.base_resp !== undefined) { - const br = obj(env.base_resp) - const code = br && num(br.status_code) - if (code === undefined) throw new Error("MiniMax tool API: invalid base_resp") - if (code !== 0) throw new Error("MiniMax tool API: " + (str(br, "status_msg") ?? "status " + code)) - } - checked(env, "MiniMax tool API") - abort.throwIfAborted() - return env + return await parseToolEnvelope(res, site, abort) } catch (e) { abort.throwIfAborted() - e.message = redact(e.message) + e.message = redactSecrets(e.message, secrets) throw e } } @@ -1360,4 +1469,4 @@ export const MiniMaxCodeAuthPlugin = makePlugin(SITES["minimax-code"]) export const MiniMaxCodeGlobalAuthPlugin = makePlugin(SITES["minimax-code-global"]) // for tests -export const _internal = { SITES, MODELS, createToolRequest, signed, md5, parseModels, planWindows, membershipOf, usageOf, credits, creditsWindow, ledgerBatches, variants, renewing, renewed, startDevice, pollDevice, checkinOf } +export const _internal = { SITES, MODELS, createToolRequest, postTool, makeTokenRequest, parseToolEnvelope, toolHttpError, signed, md5, parseModels, planWindows, membershipOf, usageOf, credits, creditsWindow, ledgerBatches, variants, renewing, renewed, startDevice, pollDevice, checkinOf } diff --git a/packages/minimax/models.test.mjs b/packages/minimax/models.test.mjs index 31c7b9a..6906f61 100644 --- a/packages/minimax/models.test.mjs +++ b/packages/minimax/models.test.mjs @@ -18,14 +18,20 @@ async function given(hooks) { return { id: "minimax-code", models: Object.fromEntries(Object.entries(p.models).map(([id, m]) => [id, { id, ...m }])) } } -test("the config declares MiniMax Code's four models on the Anthropic API", async () => { +test("the config declares MiniMax Code's chat models on the Anthropic API, plus image and video models", async () => { const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) const cfg = { provider: {} } await hooks.config(cfg) const p = cfg.provider["minimax-code"] expect(p.npm).toBe("@ai-sdk/anthropic") expect(p.api).toBe(_internal.SITES["minimax-code"].llm + "/mavis/api/v1/llm/v1") - expect(Object.keys(p.models).sort()).toEqual(["MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M3", "MiniMax-M3.1-Flash-Preview"]) + const chat = ["MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M3", "MiniMax-M3.1-Flash-Preview"] + const media = ["MiniMax-H3", "MiniMax-H3-Max", "MiniMax-Hailuo-2.3", "MiniMax-Image"] + expect(Object.keys(p.models).sort()).toEqual([...chat, ...media].sort()) + expect(p.models["MiniMax-Image"].modalities).toEqual({ input: ["text", "image"], output: ["image"] }) + expect(p.models["MiniMax-Image"].provider).toEqual({ npm: "@ai-sdk/openai-compatible" }) + expect(p.models["MiniMax-H3"].modalities.output).toEqual(["video"]) + expect(p.models["MiniMax-M3"].modalities.output).toEqual(["text"]) expect(p.models["MiniMax-M3"].variants).toEqual({ none: { thinking: { type: "disabled" } }, high: { thinking: { type: "adaptive" } } }) expect(Object.keys(p.models["MiniMax-M3.1-Flash-Preview"].variants)).toEqual(["low", "medium", "high", "xhigh", "max"]) expect(p.models["MiniMax-M3.1-Flash-Preview"].variants.xhigh).toEqual({ thinking: { type: "adaptive" }, effort: "xhigh" }) @@ -78,7 +84,7 @@ test("the live list is MiniMax Code's model config", async () => { const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) const p = await given(hooks) const ms = await hooks.provider.models(p, { auth }) - expect(Object.keys(ms)).toEqual(["MiniMax-M4", "MiniMax-M3", "MiniMax-M2.7"]) + expect(Object.keys(ms)).toEqual(["MiniMax-M4", "MiniMax-M3", "MiniMax-M2.7", "MiniMax-Image", "MiniMax-H3", "MiniMax-H3-Max", "MiniMax-Hailuo-2.3"]) expect(ms["MiniMax-M4"]).toMatchObject({ id: "MiniMax-M4", providerID: "minimax-code", name: "M4", api: { id: "MiniMax-M4", npm: "@ai-sdk/anthropic" }, limit: { context: 1000000, output: 128000 } }) expect(ms["MiniMax-M4"].variants).toEqual({ low: { thinking: { type: "adaptive" }, effort: "low" }, high: { thinking: { type: "adaptive" }, effort: "high" } }) expect(ms["MiniMax-M3"].capabilities.input.image).toBe(true) @@ -97,7 +103,7 @@ test("a list refused with the account is asked again without it", async () => { : json({ providers: [{ providerId: "minimax", config: { models: { "MiniMax-M3": { name: "MiniMax-M3" } } } }] }))) const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) const ms = await hooks.provider.models(await given(hooks), { auth }) - expect(Object.keys(ms)).toEqual(["MiniMax-M3"]) + expect(Object.keys(ms)).toEqual(["MiniMax-M3", "MiniMax-Image", "MiniMax-H3", "MiniMax-H3-Max", "MiniMax-Hailuo-2.3"]) expect(f.seen.length).toBe(2) }) diff --git a/packages/minimax/native.mjs b/packages/minimax/native.mjs new file mode 100644 index 0000000..7907fca --- /dev/null +++ b/packages/minimax/native.mjs @@ -0,0 +1,823 @@ +// Magpie-native image generation, video generation, and web search for +// MiniMax Code. These use the same MiniMax Code APIs as the plugin's named +// tools (the Matrix connector for image and video, /mavis/api/v1/mcp/web_search +// for search). Magpie lists them in Settings → Images / Video / Web search +// and serves them through /mcp/magpie/image, its videos API, and +// /mcp/magpie/web-search, so an agent can drop the separate MiniMax tools. +// +// The named tools stay; this is additive. +// +// How Magpie finds them: +// - web search: the plugin search hook ({search: {: {name, auth, execute}}}), +// listed beside Tavily and the rest, signed in as this provider. +// - image: a model that gives images alone, spoken with +// @ai-sdk/openai-compatible, drawn at the OpenAI images API through this +// plugin's fetch (plugin:///v1/images/generations and /images/edits). +// - video: models whose capabilities.output includes video, started at +// the OpenAI-shaped videos API through the same fetch +// (plugin:///v1/videos). +// +// generate_image has no model id of its own in the live catalog, so the +// image model is listed as MiniMax-Image. Video models are the real +// submit_video_generation enums: MiniMax-H3, MiniMax-H3-Max, MiniMax-Hailuo-2.3. +// +// Magpie's plugin drawer that isn't Codex or SenseNova sends edits as +// multipart/form-data (image bytes, optional mask). generate_image takes +// no mask, so a mask part is refused with a 400 rather than drawn from as +// one more reference image. A local video frame +// arrives as a data: URL. Those bytes are uploaded through the live +// catalog's upload_temp_url flow (a signed form, then a POST of the +// file) before generate_image / submit_video_generation. HTTPS URLs are +// passed through. get_asset_url is retried briefly while the URL still +// has /visible/, the watermarked rendition reported in #974. + +import { callMatrixTool, _internal as matrix } from "./connector-tools.mjs" + +const IMAGE_NPM = "@ai-sdk/openai-compatible" +const MATRIX = "connector__matrix__" +const LIST_MS = 30 * 1000 +const UPLOAD_MS = 55 * 1000 +const MAX_UPLOAD = 64 * 1024 * 1024 +const IMAGE_MIMES = new Set(["image/jpeg", "image/png", "image/webp", "image/heic", "image/heif"]) + +export const IMAGE_MODEL_ID = "MiniMax-Image" +export const VIDEO_MODEL_IDS = Object.freeze(["MiniMax-H3", "MiniMax-H3-Max", "MiniMax-Hailuo-2.3"]) + +const VIDEO_NAMES = { + "MiniMax-H3": "MiniMax H3", + "MiniMax-H3-Max": "MiniMax H3 Max", + "MiniMax-Hailuo-2.3": "MiniMax Hailuo 2.3", +} + +const VIDEO_DEFAULTS = { + "MiniMax-H3": { duration: 6, resolution: "2K" }, + "MiniMax-H3-Max": { duration: 6, resolution: "768P" }, + "MiniMax-Hailuo-2.3": { duration: 6, resolution: "768P" }, +} + +export const MEDIA_MODEL_IDS = Object.freeze([IMAGE_MODEL_ID, ...VIDEO_MODEL_IDS]) + +const emptyCost = { input: 0, output: 0, cache_read: 0, cache_write: 0 } +const emptyCache = { input: 0, output: 0, cache: { read: 0, write: 0 } } + +// mediaConfigModels are the image and video models added to the provider +// config (and kept when the live chat list is used), so Magpie can offer +// them in Settings → Images and Video. +export function mediaConfigModels() { + const out = { + [IMAGE_MODEL_ID]: { + name: "MiniMax Image", + reasoning: false, + tool_call: false, + attachment: true, + modalities: { input: ["text", "image"], output: ["image"] }, + limit: { context: 0, output: 0 }, + cost: { ...emptyCost }, + variants: {}, + provider: { npm: IMAGE_NPM }, + }, + } + for (const id of VIDEO_MODEL_IDS) { + out[id] = { + name: VIDEO_NAMES[id], + reasoning: false, + tool_call: false, + attachment: true, + modalities: { input: ["text", "image"], output: ["video"] }, + limit: { context: 0, output: 0 }, + cost: { ...emptyCost }, + variants: {}, + } + } + return out +} + +// mediaModelOf is one media model as provider.models returns it (OpenCode +// internal form). Image models name @ai-sdk/openai-compatible so Magpie +// lists them as drawers; video models only need output.video. +export function mediaModelOf(site, provider, m) { + const image = m.outputs[0] === "image" + return { + id: m.id, + providerID: provider.id, + name: m.name, + api: { id: m.id, url: site.llm + "/mavis/api/v1/llm/v1", npm: image ? IMAGE_NPM : "@ai-sdk/anthropic" }, + status: "active", + headers: {}, + options: {}, + cost: emptyCache, + limit: { context: 0, output: 0 }, + capabilities: { + temperature: false, + reasoning: false, + attachment: true, + toolcall: false, + input: { text: true, image: true, audio: false, video: false, pdf: false }, + output: { text: false, image, audio: false, video: !image, pdf: false }, + interleaved: false, + }, + release_date: "", + variants: {}, + } +} + +export function mediaModels(site, provider) { + const conf = mediaConfigModels() + return Object.fromEntries(MEDIA_MODEL_IDS.map((id) => { + const c = conf[id] + return [id, mediaModelOf(site, provider, { id, name: c.name, outputs: c.modalities.output })] + })) +} + +// withMediaModels appends the image and video models after the chat list, +// replacing any same-id row the live catalog may one day include. +export function withMediaModels(chat, site, provider) { + return { ...chat, ...mediaModels(site, provider) } +} + +// ---- web search hook ---------------------------------------------------------- + +const SEARCH_BAGS = ["organic", "results", "news", "videos", "places", "shopping", "web"] + +// pagesFrom maps MiniMax Code's web_search payload to Magpie search pages +// ({title, url, text, age}). +export function pagesFrom(payload) { + const out = [] + const seen = new Set() + const push = (row) => { + if (!row || typeof row !== "object" || Array.isArray(row)) return + const url = str(row.url ?? row.link ?? row.href) + const title = str(row.title ?? row.name) || url + if (!url && !title) return + const key = url || title + if (seen.has(key)) return + seen.add(key) + out.push({ + title, + url, + text: str(row.text ?? row.content ?? row.snippet ?? row.description ?? row.summary), + age: str(row.age ?? row.date ?? row.published_time ?? row.published), + }) + } + if (Array.isArray(payload)) { + payload.forEach(push) + return out + } + if (!payload || typeof payload !== "object") return out + let any = false + for (const key of SEARCH_BAGS) { + if (Array.isArray(payload[key])) { + payload[key].forEach(push) + any = true + } + } + if (!any && payload.data && typeof payload.data === "object") return pagesFrom(payload.data) + return out +} + +// createSearchHook is the plugin search hook for one MiniMax Code site. +// post(access, path, body, opts) POSTs a JSON body with that access token +// and returns the parsed object (base_resp already checked). A throw from +// post should carry a numeric status (401, 402, 403, 429) when the API +// refused the account, so Magpie can rest it for search. +export function createSearchHook(site, post) { + return { + [site.id]: { + name: site.name, + auth: site.id, + async execute({ query, count } = {}, ctx = {}) { + const q = typeof query === "string" ? query.trim() : "" + if (!q) throw new Error("query is required") + const a = await ctx.getAuth?.() + if (!a?.access) throw new Error("not signed in to " + site.name) + const body = { query: q } + if (Number.isInteger(count) && count > 0) body.count = count + ctx.abort?.throwIfAborted?.() + const env = await post(a.access, "/mavis/api/v1/mcp/web_search", body, { signal: ctx.abort, timeoutMs: 120000 }) + const { base_resp: _b, statusInfo: _s, ...payload } = env && typeof env === "object" ? env : {} + return pagesFrom(payload) + }, + }, + } +} + +// ---- OpenAI images / videos API through the plugin's fetch -------------------- + +const GEN_MS = 10 * 60 * 1000 +const CALL_MS = 55 * 1000 + +// mediaPath is the OpenAI-shaped images or videos route on url, or null +// when the request is ordinary chat and should go on to MiniMax Code. +export function mediaPath(url) { + let path + try { + path = new URL(url, "http://local").pathname + } catch { + return null + } + if (path.endsWith("/images/generations")) return { kind: "image.generations" } + if (path.endsWith("/images/edits")) return { kind: "image.edits" } + if (path.endsWith("/videos")) return { kind: "video.create" } + const got = /\/videos\/([^/]+)(?:\/(content))?$/.exec(path) + if (!got) return null + let id + try { id = decodeURIComponent(got[1]) } catch { id = got[1] } + return { kind: got[2] === "content" ? "video.content" : "video.get", id } +} + +// handleMediaFetch answers an OpenAI images or videos request by calling +// MiniMax Code's Matrix tools. It returns null when url is not a media +// route, so the chat fetch can send the request on. headers must include +// the request Content-Type when the body is multipart/form-data, as Magpie +// sends it for /images/edits. +export async function handleMediaFetch(url, { method, body, headers, signal } = {}, { request, siteId } = {}) { + const route = mediaPath(url) + if (!route) return null + if (typeof request !== "function" || !siteId) { + return errorResponse(500, "MiniMax Code media: missing request transport") + } + const verb = (method ?? "GET").toUpperCase() + try { + if (route.kind === "image.generations" || route.kind === "image.edits") { + if (verb !== "POST") return errorResponse(405, "use POST to generate an image") + return await generateImage(request, siteId, body, headers, signal, route.kind === "image.edits") + } + if (route.kind === "video.create") { + if (verb !== "POST") return errorResponse(405, "use POST to start a video") + return await startVideo(request, siteId, body, headers, signal) + } + if (verb !== "GET") return errorResponse(405, "use GET to read a video") + if (route.kind === "video.get") return await getVideo(request, siteId, route.id, signal) + return await videoContent(request, siteId, route.id, signal) + } catch (e) { + const status = e?.status && Number.isInteger(e.status) ? e.status : 502 + return errorResponse(status, e?.message ?? String(e)) + } +} + +async function generateImage(request, siteId, body, headers, signal, edits) { + const input = await mediaInput(body, headers) + const req = input.fields + const prompt = str(req.prompt) + if (!prompt) throw Object.assign(new Error("prompt is required"), { status: 400 }) + const n = integer(req.n, 1) + if (n < 1 || n > 10) throw Object.assign(new Error("n must be an integer from 1 to 10"), { status: 400 }) + const item = { prompt, n } + const aspect = str(req.aspect_ratio) || aspectFromSize(req.size) + if (aspect) item.aspect_ratio = aspect + const area = areaOf(req) + if (area) item.area = area + const refs = await referenceImages(request, siteId, req, input.files, signal, edits) + if (refs) item.reference_images = refs + const result = await callMatrixTool(request, siteId, "generate_image", { requests: [item] }, { signal, timeoutMs: GEN_MS }) + const items = Array.isArray(result?.success_items) ? result.success_items : [] + if (!items.length) throw new Error("MiniMax Image returned no images") + const data = [] + for (const row of items) { + const node = str(row?.node_id) + if (!node) throw new Error("MiniMax Image returned no node_id") + data.push({ url: await assetUrl(request, siteId, node, signal) }) + } + return jsonResponse({ created: Math.floor(Date.now() / 1000), data }) +} + +async function startVideo(request, siteId, body, headers, signal) { + const req = (await mediaInput(body, headers)).fields + const model = str(req.model) + if (!VIDEO_MODEL_IDS.includes(model)) { + throw Object.assign(new Error("model must be one of " + VIDEO_MODEL_IDS.join(", ")), { status: 400 }) + } + const prompt = str(req.prompt) + if (!prompt) throw Object.assign(new Error("prompt is required"), { status: 400 }) + const defaults = VIDEO_DEFAULTS[model] + const duration = durationOf(req.seconds, defaults.duration, model) + const args = { model, prompt, duration } + const resolution = resolutionOf(req.size, defaults.resolution, model) + if (resolution) args.resolution = resolution + const ratio = str(req.ratio) || aspectFromSize(req.size) + if (ratio && ratio !== "auto") args.ratio = ratio + const start = await resolveMedia(request, siteId, req.input_reference ?? req.input_image, signal) + const end = await resolveMedia(request, siteId, req.last_frame ?? req.last_frame_image, signal) + if (start) { + args.input_image = start + args.reference_type = "first_frame" + } + if (end) args.last_frame_image = end + const refs = await resolveMediaList(request, siteId, req.reference_images, signal) + if (refs) args.reference_images = refs + const result = await callMatrixTool(request, siteId, "submit_video_generation", args, { signal, timeoutMs: CALL_MS }) + const task = str(result?.task_id ?? result?.taskId ?? result?.id) + if (!task) throw new Error("MiniMax video returned no task_id") + return jsonResponse({ + id: encodeVideoId(model, task), + object: "video", + created_at: Math.floor(Date.now() / 1000), + status: "queued", + progress: 0, + model, + seconds: String(duration), + }) +} + +async function getVideo(request, siteId, id, signal) { + const { model, task } = decodeVideoId(id) + const result = await queryVideo(request, siteId, model, task, signal) + const status = videoStatus(result) + const obj = { + id, + object: "video", + created_at: integer(result?.created_at, Math.floor(Date.now() / 1000)), + status: status.openai, + progress: status.progress, + model, + } + if (result?.duration != null) obj.seconds = String(result.duration) + if (status.openai === "failed") { + obj.error = { code: str(result?.error_code ?? result?.code) || "failed", message: str(result?.error_message ?? result?.message ?? result?.failure) || "the video failed" } + } + return jsonResponse(obj) +} + +async function videoContent(request, siteId, id, signal) { + const { model, task } = decodeVideoId(id) + const result = await queryVideo(request, siteId, model, task, signal) + const status = videoStatus(result) + if (status.openai !== "completed") { + throw Object.assign(new Error("the video is not ready yet (" + status.openai + ")"), { status: 409 }) + } + const node = str(result?.node_id ?? result?.success_items?.[0]?.node_id) + if (!node) throw new Error("MiniMax video returned no node_id") + const url = await assetUrl(request, siteId, node, signal) + const res = await _native.fetch(url, { signal, redirect: "follow" }) + if (!res.ok) throw new Error("MiniMax video download: HTTP " + res.status) + const headers = new Headers(res.headers) + // fetch has already decoded the body: passing these on would have the + // client decode it again, or expect the encoded length + headers.delete("content-encoding") + headers.delete("content-length") + if (!headers.get("content-type")) headers.set("content-type", "video/mp4") + return new Response(res.body, { status: 200, headers }) +} + +async function queryVideo(request, siteId, model, task, signal) { + return callMatrixTool(request, siteId, "query_video_generation", { model, task_id: task }, { signal, timeoutMs: CALL_MS }) +} + +// assetUrl asks get_asset_url, and retries for a short while when the +// answer still has /visible/ (the watermarked rendition #974 reports +// right after a generation). If the wait runs out, the last URL is +// returned as-is. +async function assetUrl(request, siteId, nodeId, signal) { + const deadline = Date.now() + _native.visibleWaitMs + let url = "" + for (;;) { + const asset = await callMatrixTool(request, siteId, "get_asset_url", { node_id: nodeId }, { signal, timeoutMs: CALL_MS }) + url = str(asset?.download_url ?? asset?.url ?? asset?.temp_url) + if (!url) throw new Error("get_asset_url returned no download_url") + if (!url.includes("/visible/") || Date.now() >= deadline) return url + const wait = Math.min(_native.visibleStepMs, Math.max(0, deadline - Date.now())) + if (!wait) return url + await _native.sleep(wait, signal) + } +} + +export function encodeVideoId(model, task) { + return model + "::" + task +} + +export function decodeVideoId(id) { + const split = String(id ?? "").indexOf("::") + if (split <= 0) throw Object.assign(new Error("not a MiniMax Code video id"), { status: 404 }) + const model = id.slice(0, split) + const task = id.slice(split + 2) + if (!VIDEO_MODEL_IDS.includes(model) || !task) throw Object.assign(new Error("not a MiniMax Code video id"), { status: 404 }) + return { model, task } +} + +export function videoStatus(result) { + const raw = str(result?.status ?? result?.task_status ?? result?.state ?? result?.taskStatus).toLowerCase() + if (raw === "succeeded" || raw === "success" || raw === "completed" || raw === "done") return { openai: "completed", progress: 100 } + if (raw === "failed" || raw === "error" || raw === "cancelled" || raw === "canceled" || raw === "expired") return { openai: "failed", progress: integer(result?.progress, 0) } + if (raw === "running" || raw === "processing" || raw === "in_progress" || raw === "generating") { + const p = integer(result?.progress, 0) + return { openai: "in_progress", progress: p > 0 && p < 100 ? p : 50 } + } + return { openai: "queued", progress: integer(result?.progress, 0) } +} + +async function referenceImages(request, siteId, req, files, signal, edits) { + // generate_image has no mask input: a mask uploaded as a reference image + // would be drawn from as one more picture, so it is refused, the way + // magpie refuses mask edits for drawers that can't take one. + if ((files ?? []).some((f) => f.field === "mask")) + throw Object.assign(new Error("MiniMax Image does not support mask edits"), { status: 400 }) + const parts = (files ?? []).filter((f) => f.field === "image" || f.field === "image[]") + if (parts.length) { + const out = [] + for (const part of parts) out.push(await uploadBytes(request, siteId, part, signal)) + return out + } + const fromList = await resolveMediaList(request, siteId, req.reference_images, signal) + if (fromList) return fromList + const one = await resolveMedia(request, siteId, req.image ?? req.image_url, signal) + if (one) return [one] + if (edits) throw Object.assign(new Error("image edits need a reference image"), { status: 400 }) + return undefined +} + +async function resolveMediaList(request, siteId, value, signal) { + if (!Array.isArray(value) || !value.length) return undefined + const out = [] + for (const item of value) { + const u = await resolveMedia(request, siteId, item, signal) + if (!u) throw Object.assign(new Error("reference images must be HTTPS or data: URLs"), { status: 400 }) + out.push(u) + } + return out +} + +async function resolveMedia(request, siteId, value, signal) { + const ref = mediaRef(value) + if (!ref) return undefined + if (ref.url.startsWith("data:")) { + const file = parseDataUrl(ref.url) + if (ref.mime_type) file.mime = normalizeMime(ref.mime_type) || file.mime + return uploadBytes(request, siteId, file, signal) + } + return ref +} + +// mediaRef reads one media argument: an HTTPS URL (kept as-is) or a +// data: URL (uploaded later). Other schemes, including http: and file:, +// are refused. +export function mediaRef(value) { + if (typeof value === "string") { + const url = value.trim() + if (!url) return undefined + if (url.startsWith("data:")) return { url } + if (url.startsWith("file:") || /^[.]{0,2}\//.test(url) || !/^[a-z][a-z0-9+.-]*:/i.test(url) || !/^https:/i.test(url)) { + throw Object.assign(new Error("media must be an HTTPS URL or a data: URL"), { status: 400 }) + } + return { url } + } + if (value && typeof value === "object") { + const url = str(value.url) + if (!url) return undefined + const one = mediaRef(url) + const mime = maybeMime(value.mime_type) + if (mime) one.mime_type = mime + return one + } + return undefined +} + +async function uploadBytes(request, siteId, file, signal) { + const bytes = file?.bytes + if (!bytes || !bytes.length) throw Object.assign(new Error("the reference image was empty"), { status: 400 }) + if (bytes.length > MAX_UPLOAD) throw Object.assign(new Error("the reference image is larger than 64 MB"), { status: 400 }) + const mime = normalizeMime(file.mime) || "application/octet-stream" + const filename = str(file.filename) || filenameOf(mime) + const signed = await requestUpload(request, siteId, { bytes, mime, filename }, signal) + if (signed.maxBytes != null && bytes.length > signed.maxBytes) { + throw new Error("the reference image is larger than the upload limit (" + signed.maxBytes + " bytes)") + } + if (signed.uploadHost) await postSignedUpload(signed, { bytes, mime, filename }, signal) + else if (!signed.sentBytes) throw new Error("upload_temp_url returned no upload_host") + const url = str(signed.tempUrl) + if (!url) throw new Error("upload_temp_url returned no temp_url") + const out = { url } + const mt = maybeMime(mime) + if (mt) out.mime_type = mt + return out +} + +async function requestUpload(request, siteId, file, signal) { + const cat = await matrix.catalog(request, siteId, signal) + const entry = findUpload(cat) + let schema = {} + if (entry.input_schema_json) { + try { + const v = JSON.parse(entry.input_schema_json) + if (v && typeof v === "object" && !Array.isArray(v)) schema = v + } catch { + throw new Error("MiniMax connector list: malformed input_schema_json") + } + } + const { args, sentBytes } = uploadArgsFromSchema(schema, file) + const result = await matrix.invoke(request, siteId, entry, args, signal, UPLOAD_MS) + return { ...parseSignedUpload(result), sentBytes } +} + +function findUpload(cat) { + const match = cat.tools.find((t) => { + const run = t.runtime_tool_name ?? "" + const prov = t.provider_tool_name ?? "" + return run === MATRIX + "upload_temp_url" || run.endsWith("__upload_temp_url") || prov === "upload_temp_url" || /(?:^|_)upload_temp_url$/.test(prov) + }) + if (match) return match + return matrix.find(cat, MATRIX + "upload_temp_url") +} + +function uploadArgsFromSchema(schema, file) { + const props = schema && typeof schema === "object" ? schema.properties ?? {} : {} + const names = Object.keys(props) + const pick = (...cands) => cands.find((n) => names.includes(n)) + const args = {} + const fn = pick("filename", "file_name", "name", "fileName") + if (fn) args[fn] = file.filename + const mt = pick("mime_type", "mimeType", "content_type", "contentType", "mime") + if (mt) args[mt] = file.mime + const sz = pick("size_bytes", "size", "bytes", "content_length") + if (sz) args[sz] = file.bytes.length + const dataKey = pick("data", "content", "content_base64", "bytes_base64", "file_base64", "base64") + if (dataKey) args[dataKey] = Buffer.from(file.bytes).toString("base64") + if (!names.length) return { args: { filename: file.filename, mime_type: file.mime }, sentBytes: false } + if (!Object.keys(args).length) { + if (pick("file_path", "path", "local_path")) { + throw new Error("upload_temp_url on this account takes a local path, which the plugin cannot supply") + } + return { args: { filename: file.filename, mime_type: file.mime }, sentBytes: false } + } + return { args, sentBytes: Boolean(dataKey) } +} + +function parseSignedUpload(value) { + let raw = value + if (typeof raw === "string") { + try { raw = JSON.parse(raw) } catch { raw = null } + } + if (raw && typeof raw === "object" && !Array.isArray(raw) && typeof raw.result_json === "string") { + try { + const inner = JSON.parse(raw.result_json) + if (inner && typeof inner === "object") raw = inner + } catch {} + } + if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("upload_temp_url returned no upload form") + if (raw.code !== undefined && Number(raw.code) !== 0) { + throw new Error("upload_temp_url: " + (str(raw.message) ?? "request failed") + " (code=" + raw.code + ")") + } + const uploadHost = str(raw.upload_host ?? raw.uploadHost ?? raw.upload_url ?? raw.uploadUrl) + const tempUrl = str(raw.temp_url ?? raw.tempUrl ?? raw.url) + const fields = raw.fields && typeof raw.fields === "object" && !Array.isArray(raw.fields) ? raw.fields : {} + const normalized = {} + for (const [key, item] of Object.entries(fields)) if (typeof item === "string") normalized[key] = item + const fileFieldName = str(raw.file_field_name ?? raw.fileFieldName) || "file" + const maxBytes = Number.isFinite(Number(raw.max_bytes ?? raw.maxBytes)) ? Number(raw.max_bytes ?? raw.maxBytes) : null + return { uploadHost, tempUrl, fields: normalized, fileFieldName, maxBytes } +} + +async function postSignedUpload(signed, file, signal) { + if (!allowedUploadHost(signed.uploadHost)) { + throw new Error("upload_temp_url returned an upload host that is not HTTPS") + } + const form = new FormData() + for (const [key, item] of Object.entries(signed.fields)) form.append(key, item) + form.append(signed.fileFieldName, new Blob([file.bytes], { type: file.mime }), file.filename) + const abort = AbortSignal.any([AbortSignal.timeout(UPLOAD_MS), ...(signal ? [signal] : [])]) + let res + try { + res = await _native.fetch(signed.uploadHost, { method: "POST", body: form, signal: abort, redirect: "follow" }) + } catch (e) { + abort.throwIfAborted?.() + throw new Error("MiniMax upload: " + (e?.message ?? String(e))) + } + if (!res.ok) throw new Error("MiniMax upload: HTTP " + res.status) +} + +function allowedUploadHost(url) { + let u + try { u = new URL(url) } catch { return false } + return u.protocol === "https:" +} + +function parseDataUrl(url) { + const m = /^data:([^,]*),(.*)$/s.exec(url) + if (!m) throw Object.assign(new Error("media data: URL is malformed"), { status: 400 }) + const meta = m[1] + const payload = m[2] + const isB64 = /;base64(?:;|$)/i.test(";" + meta) + const mime = normalizeMime(meta.replace(/;base64$/i, "").replace(/;base64;/ig, ";").replace(/;charset=[^;]*/ig, "").replace(/^;|;$/g, "")) || "application/octet-stream" + let bytes + try { + bytes = isB64 ? Buffer.from(payload, "base64") : Buffer.from(decodeURIComponent(payload)) + } catch { + throw Object.assign(new Error("media data: URL isn't valid"), { status: 400 }) + } + if (!bytes.length) throw Object.assign(new Error("the reference image was empty"), { status: 400 }) + return { bytes: new Uint8Array(bytes), mime, filename: filenameOf(mime), field: "image" } +} + +async function mediaInput(body, headers) { + if (body && typeof FormData !== "undefined" && body instanceof FormData) return fromFormData(body) + const ct = getHeader(headers, "content-type") + const mime = ct.split(";")[0].trim().toLowerCase() + if (mime === "multipart/form-data") return fromMultipart(body, ct) + return { fields: jsonBody(body), files: [] } +} + +async function fromMultipart(body, contentType) { + const bytes = await bytesOf(body) + const res = new Response(bytes, { headers: { "content-type": contentType } }) + let form + try { + form = await res.formData() + } catch { + throw Object.assign(new Error("request body must be multipart form data"), { status: 400 }) + } + return fromFormData(form) +} + +async function fromFormData(form) { + const fields = {} + const files = [] + for (const [name, value] of form.entries()) { + if (typeof value === "string") { + if (fields[name] === undefined) fields[name] = value + continue + } + const bytes = new Uint8Array(await value.arrayBuffer()) + const mime = normalizeMime(value.type) || sniffMime(bytes) + const filename = str(value.name) || filenameOf(mime) + files.push({ field: name, bytes, mime, filename }) + } + return { fields, files } +} + +async function bytesOf(body) { + if (body == null || body === "") return new Uint8Array() + if (typeof body === "string") return new TextEncoder().encode(body) + if (body instanceof ArrayBuffer) return new Uint8Array(body) + if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength) + if (typeof Blob !== "undefined" && body instanceof Blob) return new Uint8Array(await body.arrayBuffer()) + throw Object.assign(new Error("request body must be a JSON object or multipart form data"), { status: 400 }) +} + +function getHeader(headers, name) { + if (!headers) return "" + if (typeof headers.get === "function") return headers.get(name) ?? "" + const want = name.toLowerCase() + for (const [k, v] of Object.entries(headers)) { + if (k.toLowerCase() === want) return Array.isArray(v) ? (v[0] ?? "") : (v ?? "") + } + return "" +} + +function normalizeMime(value) { + const v = String(value ?? "").trim().toLowerCase() + if (!v || v === "application/octet-stream") return "" + if (v === "image/jpg") return "image/jpeg" + return v +} + +function maybeMime(value) { + const v = normalizeMime(value) + return IMAGE_MIMES.has(v) ? v : undefined +} + +function filenameOf(mime) { + const ext = { "image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp", "image/heic": ".heic", "image/heif": ".heif" }[normalizeMime(mime)] ?? "" + return "image" + ext +} + +function sniffMime(bytes) { + if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return "image/png" + if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg" + if (bytes.length >= 12 && bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return "image/webp" + return "application/octet-stream" +} + +function aspectFromSize(size) { + const s = str(size) + if (!s) return undefined + if (/^\d+:\d+$/.test(s) || s === "auto" || s === "adaptive") return s === "adaptive" ? "adaptive" : s + const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(s) + if (!m) return undefined + const w = Number(m[1]), h = Number(m[2]) + if (!w || !h) return undefined + const g = gcd(w, h) + return w / g + ":" + h / g +} + +function areaOf(req) { + const a = str(req.area) + if (a === "1K" || a === "2K" || a === "4K") return a + const q = str(req.quality).toLowerCase() + if (q === "low") return "1K" + if (q === "medium") return "2K" + if (q === "high" || q === "xhigh" || q === "max") return "4K" + return areaFromSize(req.size) +} + +// areaFromSize maps an OpenAI-style size (1024x1024, …) onto MiniMax's +// area tier, so Magpie's usual square doesn't fall through to the vendor +// 4K default. +function areaFromSize(size) { + const s = str(size) + if (s === "1K" || s === "2K" || s === "4K") return s + const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(s) + if (!m) return undefined + const long = Math.max(Number(m[1]), Number(m[2])) + if (!long) return undefined + if (long <= 1280) return "1K" + if (long <= 2560) return "2K" + return "4K" +} + +function resolutionOf(size, fallback, model) { + const s = str(size) + if (!s) return fallback + const u = s.toUpperCase() + if (["480P", "768P", "1080P", "2K"].includes(u)) return clampResolution(u, model) + if (/480|640/.test(u)) return clampResolution("480P", model) + if (/1080|1920/.test(u)) return clampResolution(model === "MiniMax-Hailuo-2.3" ? "1080P" : "2K", model) + if (/2K|1440|2560/.test(u)) return clampResolution("2K", model) + if (/720|768|1280/.test(u)) return clampResolution("768P", model) + return fallback +} + +function clampResolution(value, model) { + const allowed = { + "MiniMax-H3": ["768P", "2K"], + "MiniMax-H3-Max": ["480P", "768P"], + "MiniMax-Hailuo-2.3": ["768P", "1080P"], + }[model] ?? [value] + return allowed.includes(value) ? value : allowed[allowed.length - 1] +} + +function durationOf(seconds, fallback, model) { + let n = fallback + if (seconds != null && seconds !== "") { + const v = typeof seconds === "number" ? seconds : Number(seconds) + if (!Number.isFinite(v)) throw Object.assign(new Error("seconds must be a number"), { status: 400 }) + n = Math.round(v) + } + const limits = { + "MiniMax-H3": [4, 15], + "MiniMax-H3-Max": [5, 15], + "MiniMax-Hailuo-2.3": [6, 10], + }[model] ?? [1, 15] + if (model === "MiniMax-Hailuo-2.3") return n >= 10 ? 10 : 6 + return Math.min(limits[1], Math.max(limits[0], n)) +} + +function jsonBody(body) { + if (body == null || body === "") return {} + if (typeof body === "object" && !Array.isArray(body) && !(body instanceof Uint8Array) && !(typeof Buffer !== "undefined" && Buffer.isBuffer?.(body)) && !(body instanceof ArrayBuffer)) return body + const text = typeof body === "string" ? body : new TextDecoder().decode(body) + if (!text.trim()) return {} + try { + const v = JSON.parse(text) + if (!v || typeof v !== "object" || Array.isArray(v)) throw new Error() + return v + } catch { + throw Object.assign(new Error("request body must be a JSON object"), { status: 400 }) + } +} + +function jsonResponse(obj, status = 200) { + return new Response(JSON.stringify(obj), { status, headers: { "content-type": "application/json" } }) +} + +function errorResponse(status, message) { + return jsonResponse({ error: { message, type: status >= 500 ? "api_error" : "invalid_request_error" } }, status) +} + +function str(v) { + return typeof v === "string" && v.trim() ? v.trim() : "" +} + +function integer(v, fallback) { + if (typeof v === "number" && Number.isInteger(v)) return v + if (typeof v === "string" && v.trim() && Number.isInteger(Number(v))) return Number(v) + return fallback +} + +function gcd(a, b) { + a = Math.abs(a) + b = Math.abs(b) + while (b) [a, b] = [b, a % b] + return a || 1 +} + +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason ?? new Error("aborted")) + return + } + const t = setTimeout(resolve, ms) + const onAbort = () => { + clearTimeout(t) + reject(signal.reason ?? new Error("aborted")) + } + signal?.addEventListener("abort", onAbort, { once: true }) + }) +} + +// for tests +export const _native = { + IMAGE_NPM, MATRIX, mediaPath, aspectFromSize, durationOf, resolutionOf, areaOf, areaFromSize, mediaRef, + visibleWaitMs: 8000, visibleStepMs: 1000, sleep, + // the upload POST and the video download; tests swap in a fake + fetch: (...args) => globalThis.fetch(...args), +} diff --git a/packages/minimax/native.test.mjs b/packages/minimax/native.test.mjs new file mode 100644 index 0000000..ef05a6d --- /dev/null +++ b/packages/minimax/native.test.mjs @@ -0,0 +1,671 @@ +// Magpie-native search, image and video: the search hook, the media models +// Magpie lists, and the OpenAI-shaped images/videos routes the plugin's +// fetch answers by calling MiniMax Code's real Matrix and web_search APIs. +import "./nonet.mjs" +import { expect, test } from "bun:test" +import { MiniMaxCodeAuthPlugin, MiniMaxCodeGlobalAuthPlugin, MiniMaxCodeToolsPlugin, _internal } from "./index.mjs" +import { callMatrixTool } from "./connector-tools.mjs" +import { + pagesFrom, mediaPath, handleMediaFetch, encodeVideoId, decodeVideoId, videoStatus, + createSearchHook, mediaRef, _native, +} from "./native.mjs" +import { fakeMiniMax, json } from "./fake.mjs" + +const LIST = "/minimax-cloud/api/v1/connectors/connected-tools/list" +const CALL = "/minimax-cloud/api/v1/connectors/tools/call" +const SEARCH = "/mavis/api/v1/mcp/web_search" + +const entry = (name, over = {}) => ({ + provider: "matrix", + provider_tool_name: "mcp_" + name, + runtime_tool_name: "connector__matrix__" + name, + description: name + " tool", + input_schema_json: JSON.stringify({ type: "object" }), + ...over, +}) +const catalog = (tools, over = {}) => ({ tools, partial: false, provider_failures: [], ...over }) + +function transport(script) { + const sent = [] + const request = async (site, path, body, opts = {}) => { + sent.push({ site, path, body, signal: opts.signal, timeoutMs: opts.timeoutMs, account: opts.account }) + const h = script[path] + if (!h) throw new Error("no fake for " + path) + if (Array.isArray(h)) { + const next = h.shift() + if (!next) throw new Error("no more fakes for " + path) + return typeof next === "function" ? next({ site, body }) : next + } + return typeof h === "function" ? h({ site, body }) : h + } + return { request, sent } +} + +// fakeFetch stands in for the upload POST and the video download +// (_native.fetch): no loopback server, and the upload host stays https. +async function withFakeFetch(handler, fn) { + const previous = _native.fetch + _native.fetch = async (input, init) => handler(new Request(input, init)) + try { return await fn() } finally { _native.fetch = previous } +} + +test("pagesFrom reads MiniMax Code's organic results as Magpie search pages", () => { + expect(pagesFrom({ organic: [{ title: "Source", url: "https://example.com", snippet: "hi", date: "2026" }] })).toEqual([ + { title: "Source", url: "https://example.com", text: "hi", age: "2026" }, + ]) + expect(pagesFrom({ + news: [{ title: "N", url: "https://n.example" }], + organic: [{ title: "N", url: "https://n.example" }], + })).toEqual([{ title: "N", url: "https://n.example", text: "", age: "" }]) +}) + +test("each MiniMax Code site offers a search hook signed in as itself", async () => { + const cn = await MiniMaxCodeAuthPlugin({ client: {} }) + const global = await MiniMaxCodeGlobalAuthPlugin({ client: {} }) + expect(Object.keys(cn.search)).toEqual(["minimax-code"]) + expect(cn.search["minimax-code"]).toMatchObject({ name: "MiniMax Code", auth: "minimax-code" }) + expect(Object.keys(global.search)).toEqual(["minimax-code-global"]) + expect(global.search["minimax-code-global"].auth).toBe("minimax-code-global") +}) + +test("the search hook posts web_search with the signed-in account and returns pages", async () => { + const calls = [] + const hook = createSearchHook({ id: "minimax-code", name: "MiniMax Code" }, async (access, path, body, opts) => { + calls.push({ access, path, body, timeoutMs: opts.timeoutMs }) + return { base_resp: { status_code: 0 }, organic: [{ title: "T " + body.query, url: "https://example.com/" + body.count, content: "ok" }] } + }) + const pages = await hook["minimax-code"].execute( + { query: " MiniMax ", count: 3 }, + { getAuth: async () => ({ access: "tok-1", type: "oauth" }) }, + ) + expect(pages).toEqual([{ title: "T MiniMax", url: "https://example.com/3", text: "ok", age: "" }]) + expect(calls[0]).toEqual({ access: "tok-1", path: SEARCH, body: { query: "MiniMax", count: 3 }, timeoutMs: 120000 }) +}) + +test("the search hook refuses an empty query and a missing sign-in", async () => { + const hook = createSearchHook({ id: "minimax-code", name: "MiniMax Code" }, async () => { throw new Error("should not post") }) + expect(hook["minimax-code"].execute({ query: " " }, { getAuth: async () => ({ access: "t" }) })).rejects.toThrow("query is required") + expect(hook["minimax-code"].execute({ query: "q" }, { getAuth: async () => ({}) })).rejects.toThrow("not signed in") +}) + +test("mediaPath recognizes OpenAI images and videos routes under the chat base", () => { + const base = "https://agent.minimax.cn/mavis/api/v1/llm/v1" + expect(mediaPath(base + "/images/generations")).toEqual({ kind: "image.generations" }) + expect(mediaPath(base + "/images/edits")).toEqual({ kind: "image.edits" }) + expect(mediaPath(base + "/videos")).toEqual({ kind: "video.create" }) + expect(mediaPath(base + "/videos/" + encodeURIComponent("MiniMax-H3::t1"))).toEqual({ kind: "video.get", id: "MiniMax-H3::t1" }) + expect(mediaPath(base + "/videos/" + encodeURIComponent("MiniMax-H3::t1") + "/content")).toEqual({ kind: "video.content", id: "MiniMax-H3::t1" }) + expect(mediaPath(base + "/messages")).toBeNull() + expect(mediaPath("https://example.com/videos-understand")).toBeNull() +}) + +test("handleMediaFetch leaves a chat request to the plugin's ordinary fetch", async () => { + expect(await handleMediaFetch("https://agent.minimax.cn/mavis/api/v1/llm/v1/messages", { method: "POST", body: "{}" }, { request: async () => { throw new Error("no") }, siteId: "minimax-code" })).toBeNull() +}) + +test("an images/generations request calls generate_image then get_asset_url", async () => { + const t = transport({ + [LIST]: catalog([entry("generate_image"), entry("get_asset_url")]), + [CALL]: [ + { result_json: JSON.stringify({ success_items: [{ node_id: "n1", file_name: "a.png" }] }) }, + { result_json: JSON.stringify({ code: 0, download_url: "https://cdn.example/a.png" }) }, + ], + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/generations", + { method: "POST", body: JSON.stringify({ model: "MiniMax-Image", prompt: "a cat", n: 1, quality: "high" }) }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(200) + const body = await res.json() + expect(body.data).toEqual([{ url: "https://cdn.example/a.png" }]) + const calls = t.sent.filter((s) => s.path === CALL) + expect(JSON.parse(calls[0].body.arguments_json)).toEqual({ requests: [{ prompt: "a cat", n: 1, area: "4K" }] }) + expect(JSON.parse(calls[1].body.arguments_json)).toEqual({ node_id: "n1" }) + expect(calls[0].body.runtime_tool_name).toBe("connector__matrix__generate_image") + expect(calls[1].body.runtime_tool_name).toBe("connector__matrix__get_asset_url") +}) + +test("image edits without a reference image are refused; http and ftp URLs are refused", async () => { + const missing = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/edits", + { method: "POST", body: JSON.stringify({ prompt: "edit" }) }, + { request: async () => { throw new Error("no") }, siteId: "minimax-code" }, + ) + expect(missing.status).toBe(400) + expect((await missing.json()).error.message).toContain("reference image") + + const ftp = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/generations", + { method: "POST", body: JSON.stringify({ prompt: "edit", image: "ftp://files.example/a.png" }) }, + { request: async () => { throw new Error("no") }, siteId: "minimax-code" }, + ) + expect(ftp.status).toBe(400) + expect((await ftp.json()).error.message).toContain("HTTPS URL") + + const http = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/generations", + { method: "POST", body: JSON.stringify({ prompt: "edit", image: "http://cdn.example/a.png" }) }, + { request: async () => { throw new Error("no") }, siteId: "minimax-code" }, + ) + expect(http.status).toBe(400) +}) + +test("POST /videos submits a Hailuo or H3 task and encodes model with the task id", async () => { + const t = transport({ + [LIST]: catalog([entry("submit_video_generation")]), + [CALL]: { result_json: JSON.stringify({ task_id: "task-9" }) }, + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/videos", + { method: "POST", body: JSON.stringify({ model: "MiniMax-Hailuo-2.3", prompt: "a wave", seconds: "10" }) }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(200) + const body = await res.json() + expect(body).toMatchObject({ id: "MiniMax-Hailuo-2.3::task-9", object: "video", status: "queued", model: "MiniMax-Hailuo-2.3", seconds: "10" }) + expect(JSON.parse(t.sent[1].body.arguments_json)).toEqual({ + model: "MiniMax-Hailuo-2.3", prompt: "a wave", duration: 10, resolution: "768P", + }) +}) + +test("GET /videos/{id} maps MiniMax query status to OpenAI's", async () => { + const t = transport({ + [LIST]: catalog([entry("query_video_generation")]), + [CALL]: { result_json: JSON.stringify({ status: "running", progress: 40 }) }, + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/videos/" + encodeURIComponent("MiniMax-H3::task-9"), + { method: "GET" }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(await res.json()).toMatchObject({ id: "MiniMax-H3::task-9", status: "in_progress", progress: 40, model: "MiniMax-H3" }) + expect(JSON.parse(t.sent[1].body.arguments_json)).toEqual({ model: "MiniMax-H3", task_id: "task-9" }) +}) + +test("GET /videos/{id}/content downloads the asset URL after a succeeded query", async () => { + const asked = [] + await withFakeFetch((req) => { + asked.push(req.url) + // as if the CDN had gzipped it: fetch has already decoded the body + return new Response("MP4", { headers: { "content-type": "video/mp4", "content-encoding": "gzip", "content-length": "99" } }) + }, async () => { + const t = transport({ + [LIST]: catalog([entry("query_video_generation"), entry("get_asset_url")]), + [CALL]: [ + { result_json: JSON.stringify({ status: "succeeded", node_id: "n-v" }) }, + { result_json: JSON.stringify({ download_url: "https://cdn.example/v.mp4" }) }, + ], + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/videos/" + encodeURIComponent("MiniMax-H3-Max::t") + "/content", + { method: "GET" }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(200) + expect(res.headers.get("content-type")).toContain("video/mp4") + expect(res.headers.get("content-encoding")).toBeNull() + expect(res.headers.get("content-length")).toBeNull() + expect(await res.text()).toBe("MP4") + }) + expect(asked).toEqual(["https://cdn.example/v.mp4"]) +}) + +test("video id encoding keeps the model for a later query", () => { + expect(decodeVideoId(encodeVideoId("MiniMax-H3", "abc-1"))).toEqual({ model: "MiniMax-H3", task: "abc-1" }) + expect(() => decodeVideoId("not-one")).toThrow("not a MiniMax Code video id") +}) + +test("videoStatus maps MiniMax's words to OpenAI's", () => { + expect(videoStatus({ status: "succeeded" })).toEqual({ openai: "completed", progress: 100 }) + expect(videoStatus({ status: "queued" })).toEqual({ openai: "queued", progress: 0 }) + expect(videoStatus({ status: "failed", progress: 12 })).toEqual({ openai: "failed", progress: 12 }) +}) + +test("the loader fetch answers /images/generations without calling the chat API", async () => { + let f + try { + f = fakeMiniMax() + f.route("POST " + LIST, () => json(catalog([entry("generate_image"), entry("get_asset_url")]))) + f.route("POST " + CALL, (r) => { + const name = r.json.runtime_tool_name + if (name.endsWith("generate_image")) return json({ result_json: JSON.stringify({ success_items: [{ node_id: "n2", file_name: "b.png" }] }) }) + if (name.endsWith("get_asset_url")) return json({ result_json: JSON.stringify({ download_url: "https://cdn.example/b.png" }) }) + return json({ error: "unexpected " + name }, 500) + }) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000 } + const out = await hooks.auth.loader(async () => auth) + const res = await out.fetch(f.origin + "/mavis/api/v1/llm/v1/images/generations", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ prompt: "a tree" }), + }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(await res.json()).toMatchObject({ data: [{ url: "https://cdn.example/b.png" }] }) + expect(f.seen.some((s) => s.path === "/mavis/api/v1/llm/v1/messages")).toBe(false) + } finally { + f?.close() + } +}) + +test("the named tools are still exported beside the native hooks", async () => { + const tools = await MiniMaxCodeToolsPlugin({ client: {}, directory: "/tmp" }) + expect(tools.tool.web_search).toBeDefined() + expect(tools.tool.generate_image).toBeDefined() + expect(tools.tool.submit_video_generation).toBeDefined() + expect(tools.tool.query_video_generation).toBeDefined() +}) + +test("callMatrixTool routes a short name through the live catalog", async () => { + const t = transport({ + [LIST]: catalog([entry("get_asset_url")]), + [CALL]: { result_json: JSON.stringify({ download_url: "https://cdn.example/x" }) }, + }) + const out = await callMatrixTool(t.request, "minimax-code", "get_asset_url", { node_id: "n" }) + expect(out).toEqual({ download_url: "https://cdn.example/x" }) +}) + +test("duration and resolution follow each video model's limits", () => { + expect(_native.durationOf("8", 6, "MiniMax-H3")).toBe(8) + expect(_native.durationOf("2", 6, "MiniMax-H3")).toBe(4) + expect(_native.durationOf("7", 6, "MiniMax-Hailuo-2.3")).toBe(6) + expect(_native.durationOf("11", 6, "MiniMax-Hailuo-2.3")).toBe(10) + expect(_native.resolutionOf("1920x1080", "768P", "MiniMax-Hailuo-2.3")).toBe("1080P") + expect(_native.resolutionOf("1920x1080", "2K", "MiniMax-H3")).toBe("2K") + expect(_native.aspectFromSize("1280x720")).toBe("16:9") + expect(_native.areaFromSize("1024x1024")).toBe("1K") + expect(_native.areaFromSize("1920x1080")).toBe("2K") + expect(_native.areaFromSize("3840x2160")).toBe("4K") + expect(_native.areaOf({ size: "1024x1024" })).toBe("1K") + expect(_native.areaOf({ size: "1024x1024", quality: "high" })).toBe("4K") +}) + + +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64") +const UPLOAD_SCHEMA = JSON.stringify({ + type: "object", + additionalProperties: false, + properties: { filename: { type: "string" }, mime_type: { type: "string" } }, + required: ["filename", "mime_type"], +}) + +// magpieEditsBody is the multipart body draw.go builds for a plugin +// drawer that is not Codex or SenseNova: text fields, then image file +// part(s) named image (or image[] when there are several), optional mask. +function magpieEditsBody({ model = "MiniMax-Image", prompt, n = 1, size, quality, images, mask }) { + const boundary = "----MagpieFormBoundary7MA4YWxkTrZu0gW" + const chunks = [] + const field = (name, value) => { + if (value == null || value === "") return + chunks.push(Buffer.from("--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n")) + } + field("model", model) + field("prompt", prompt) + field("n", String(n)) + field("size", size) + field("quality", quality) + const pics = images.map((img) => ({ ...img, field: images.length > 1 ? "image[]" : "image" })) + if (mask) pics.push({ ...mask, field: "mask" }) + pics.forEach((img, i) => { + const ext = img.mime === "image/jpeg" ? ".jpg" : img.mime === "image/webp" ? ".webp" : ".png" + chunks.push(Buffer.from( + "--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + img.field + "\"; filename=\"image" + i + ext + "\"\r\nContent-Type: " + img.mime + "\r\n\r\n", + )) + chunks.push(img.bytes) + chunks.push(Buffer.from("\r\n")) + }) + chunks.push(Buffer.from("--" + boundary + "--\r\n")) + return { body: Buffer.concat(chunks), headers: { "content-type": "multipart/form-data; boundary=" + boundary } } +} + +test("an images/edits multipart body is uploaded through upload_temp_url, then generate_image", async () => { + const posted = [] + await withFakeFetch(async (req) => { + expect(req.url).toBe("https://upload.example/put") + const form = await req.formData() + posted.push({ policy: form.get("policy"), file: form.get("file") }) + return new Response("ok") + }, async () => { + const t = transport({ + [LIST]: catalog([ + entry("upload_temp_url", { input_schema_json: UPLOAD_SCHEMA }), + entry("generate_image"), + entry("get_asset_url"), + ]), + [CALL]: (r) => { + const name = r.body.runtime_tool_name + const args = JSON.parse(r.body.arguments_json) + if (name.endsWith("upload_temp_url")) { + expect(args).toEqual({ filename: "image0.png", mime_type: "image/png" }) + return { + result_json: JSON.stringify({ + upload_host: "https://upload.example/put", + temp_url: "https://temp.example/a.png", + fields: { policy: "sig" }, + file_field_name: "file", + }), + } + } + if (name.endsWith("generate_image")) { + expect(args).toEqual({ + requests: [{ + prompt: "make it night", + n: 1, + aspect_ratio: "1:1", + area: "1K", + reference_images: [{ url: "https://temp.example/a.png", mime_type: "image/png" }], + }], + }) + return { result_json: JSON.stringify({ success_items: [{ node_id: "n-edit", file_name: "out.png" }] }) } + } + if (name.endsWith("get_asset_url")) return { result_json: JSON.stringify({ download_url: "https://cdn.example/out.png" }) } + throw new Error("unexpected " + name) + }, + }) + const form = await magpieEditsBody({ + prompt: "make it night", + n: 1, + size: "1024x1024", + images: [{ bytes: PNG, mime: "image/png" }], + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/edits", + { method: "POST", body: form.body, headers: form.headers }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(200) + expect(await res.json()).toMatchObject({ data: [{ url: "https://cdn.example/out.png" }] }) + expect(posted).toHaveLength(1) + expect(posted[0].policy).toBe("sig") + expect(posted[0].file).toBeInstanceOf(Blob) + expect(Buffer.from(await posted[0].file.arrayBuffer()).equals(PNG)).toBe(true) + }) +}) + +test("a video data: input_reference is uploaded; an https URL is passed through", async () => { + const posted = [] + await withFakeFetch(async (req) => { + expect(req.url).toBe("https://upload.example/put") + posted.push(await req.formData()) + return new Response("ok") + }, async () => { + const t = transport({ + [LIST]: catalog([ + entry("upload_temp_url", { input_schema_json: UPLOAD_SCHEMA }), + entry("submit_video_generation"), + ]), + [CALL]: (r) => { + const name = r.body.runtime_tool_name + const args = JSON.parse(r.body.arguments_json) + if (name.endsWith("upload_temp_url")) { + return { + result_json: JSON.stringify({ + upload_host: "https://upload.example/put", + temp_url: "https://temp.example/frame.png", + fields: {}, + }), + } + } + if (name.endsWith("submit_video_generation")) { + expect(args.input_image).toEqual({ url: "https://temp.example/frame.png", mime_type: "image/png" }) + expect(args.reference_type).toBe("first_frame") + return { result_json: JSON.stringify({ task_id: "task-data" }) } + } + throw new Error("unexpected " + name) + }, + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/videos", + { + method: "POST", + body: JSON.stringify({ + model: "MiniMax-H3", + prompt: "a wave from this frame", + input_reference: "data:image/png;base64," + PNG.toString("base64"), + }), + }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(200) + expect((await res.json()).id).toBe("MiniMax-H3::task-data") + expect(posted).toHaveLength(1) + }) + + const t2 = transport({ + [LIST]: catalog([entry("submit_video_generation")]), + [CALL]: { result_json: JSON.stringify({ task_id: "task-https" }) }, + }) + const kept = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/videos", + { + method: "POST", + body: JSON.stringify({ + model: "MiniMax-H3", + prompt: "a wave", + input_reference: "https://cdn.example/frame.png", + }), + }, + { request: t2.request, siteId: "minimax-code" }, + ) + expect(kept.status).toBe(200) + expect(JSON.parse(t2.sent.filter((s) => s.path === CALL)[0].body.arguments_json)).toMatchObject({ + input_image: { url: "https://cdn.example/frame.png" }, + reference_type: "first_frame", + }) +}) + +test("get_asset_url is asked again while the URL still has /visible/", async () => { + const previous = { visibleWaitMs: _native.visibleWaitMs, visibleStepMs: _native.visibleStepMs, sleep: _native.sleep } + const sleeps = [] + _native.visibleWaitMs = 5000 + _native.visibleStepMs = 1000 + _native.sleep = async (ms) => { sleeps.push(ms) } + try { + const t = transport({ + [LIST]: catalog([entry("generate_image"), entry("get_asset_url")]), + [CALL]: [ + { result_json: JSON.stringify({ success_items: [{ node_id: "n-w", file_name: "w.png" }] }) }, + { result_json: JSON.stringify({ download_url: "https://cdn.example/visible/w.png" }) }, + { result_json: JSON.stringify({ download_url: "https://cdn.example/original/w.png" }) }, + ], + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/generations", + { method: "POST", body: JSON.stringify({ prompt: "a cat" }) }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(200) + expect((await res.json()).data).toEqual([{ url: "https://cdn.example/original/w.png" }]) + expect(t.sent.filter((s) => s.path === CALL && s.body.runtime_tool_name.endsWith("get_asset_url"))).toHaveLength(2) + expect(sleeps).toEqual([1000]) + } finally { + Object.assign(_native, previous) + } +}) + +test("a 401 on the media path is renewed and the second ask succeeds", async () => { + let f + try { + f = fakeMiniMax() + let lists = 0 + f.route("POST /oauth2/token", () => json({ access_token: "tok-2", refresh_token: "r2", expires_in: 3600 })) + f.route("POST " + LIST, (r) => { + lists++ + if (r.headers.get("authorization") === "Bearer tok") return json({ error: "expired" }, 401) + return json(catalog([entry("generate_image"), entry("get_asset_url")])) + }) + f.route("POST " + CALL, (r) => { + const name = r.json.runtime_tool_name + if (name.endsWith("generate_image")) return json({ result_json: JSON.stringify({ success_items: [{ node_id: "n2", file_name: "b.png" }] }) }) + if (name.endsWith("get_asset_url")) return json({ result_json: JSON.stringify({ download_url: "https://cdn.example/b.png" }) }) + return json({ error: "unexpected " + name }, 500) + }) + const hooks = await MiniMaxCodeAuthPlugin({ client: { auth: { set: async () => true } } }) + const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000 } + const out = await hooks.auth.loader(async () => auth) + const res = await out.fetch(f.origin + "/mavis/api/v1/llm/v1/images/generations", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ prompt: "a tree" }), + }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + expect(await res.json()).toMatchObject({ data: [{ url: "https://cdn.example/b.png" }] }) + expect(lists).toBe(3) // failed list, then generate_image list + get_asset_url list + const tokens = f.seen.filter((s) => s.path === LIST || s.path === CALL).map((s) => s.headers.get("authorization")) + expect(tokens[0]).toBe("Bearer tok") + expect(tokens.slice(1).every((h) => h === "Bearer tok-2")).toBe(true) + } finally { + f?.close() + } +}) + +test("the search hook carries a numeric status when the API refuses the account", async () => { + let f + try { + f = fakeMiniMax() + f.route("POST " + SEARCH, () => json({ error: "slow down" }, 429)) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const err = await hooks.search["minimax-code"].execute( + { query: "MiniMax" }, + { getAuth: async () => ({ access: "tok-1", type: "oauth" }) }, + ).catch((e) => e) + expect(err.status).toBe(429) + expect(err.message).toContain("HTTP 429") + } finally { + f?.close() + } +}) + +test("mediaRef accepts https and data: only", () => { + expect(mediaRef("https://cdn.example/a.png")).toEqual({ url: "https://cdn.example/a.png" }) + expect(mediaRef("data:image/png;base64,xx")).toEqual({ url: "data:image/png;base64,xx" }) + expect(() => mediaRef("http://cdn.example/a.png")).toThrow("HTTPS URL") + expect(() => mediaRef("ftp://files.example/a.png")).toThrow("HTTPS URL") + expect(() => mediaRef("/tmp/a.png")).toThrow("HTTPS URL") +}) + +test("an images/edits body with a mask part is refused with a 400, and nothing is uploaded or generated", async () => { + const t = transport({ + [LIST]: catalog([ + entry("upload_temp_url", { input_schema_json: UPLOAD_SCHEMA }), + entry("generate_image"), + entry("get_asset_url"), + ]), + [CALL]: (r) => { throw new Error("unexpected " + r.body.runtime_tool_name) }, + }) + let uploads = 0 + await withFakeFetch(() => { uploads++; return new Response("ok") }, async () => { + const form = magpieEditsBody({ + prompt: "paint the masked part red", + images: [{ bytes: PNG, mime: "image/png" }], + mask: { bytes: PNG, mime: "image/png" }, + }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/edits", + { method: "POST", body: form.body, headers: form.headers }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain("does not support mask edits") + }) + expect(uploads).toBe(0) + expect(t.sent.filter((s) => s.path === CALL)).toHaveLength(0) +}) + +test("an upload host that isn't https is refused, loopback included", async () => { + for (const host of ["http://127.0.0.1:9/put", "http://localhost/put", "http://[::1]/put", "http://upload.example/put"]) { + let uploads = 0 + const t = transport({ + [LIST]: catalog([entry("upload_temp_url", { input_schema_json: UPLOAD_SCHEMA }), entry("generate_image")]), + [CALL]: (r) => { + if (r.body.runtime_tool_name.endsWith("upload_temp_url")) + return { result_json: JSON.stringify({ upload_host: host, temp_url: "https://temp.example/a.png", fields: {} }) } + throw new Error("unexpected " + r.body.runtime_tool_name) + }, + }) + await withFakeFetch(() => { uploads++; return new Response("ok") }, async () => { + const form = magpieEditsBody({ prompt: "x", images: [{ bytes: PNG, mime: "image/png" }] }) + const res = await handleMediaFetch( + "https://agent.minimax.cn/mavis/api/v1/llm/v1/images/edits", + { method: "POST", body: form.body, headers: form.headers }, + { request: t.request, siteId: "minimax-code" }, + ) + expect(res.status).not.toBe(200) + expect((await res.json()).error.message).toContain("not HTTPS") + }) + expect(uploads).toBe(0) + } +}) + +test("a 401 on get_asset_url after generate_image renews and repeats only get_asset_url", async () => { + let f + try { + f = fakeMiniMax() + let generates = 0 + let assetAsks = 0 + f.route("POST /oauth2/token", () => json({ access_token: "tok-2", refresh_token: "r2", expires_in: 3600 })) + f.route("POST " + LIST, () => json(catalog([entry("generate_image"), entry("get_asset_url")]))) + f.route("POST " + CALL, (r) => { + const name = r.json.runtime_tool_name + if (name.endsWith("generate_image")) { + generates++ + return json({ result_json: JSON.stringify({ success_items: [{ node_id: "n2", file_name: "b.png" }] }) }) + } + if (name.endsWith("get_asset_url")) { + assetAsks++ + // the token expired while the generation ran + if (r.headers.get("authorization") === "Bearer tok") return json({ error: "expired" }, 401) + return json({ result_json: JSON.stringify({ download_url: "https://cdn.example/b.png" }) }) + } + return json({ error: "unexpected " + name }, 500) + }) + const hooks = await MiniMaxCodeAuthPlugin({ client: { auth: { set: async () => true } } }) + const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000 } + const out = await hooks.auth.loader(async () => auth) + const res = await out.fetch(f.origin + "/mavis/api/v1/llm/v1/images/generations", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ prompt: "a tree" }), + }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + expect(await res.json()).toMatchObject({ data: [{ url: "https://cdn.example/b.png" }] }) + expect(generates).toBe(1) + expect(assetAsks).toBe(2) + expect(f.seen.filter((s) => s.path === "/oauth2/token")).toHaveLength(1) + } finally { + f?.close() + } +}) + +test("a refusal inside base_resp carries the HTTP status it means", async () => { + const { parseToolEnvelope } = _internal + const site = _internal.SITES["minimax-code"] + const parse = (env) => parseToolEnvelope(new Response(JSON.stringify(env)), site, new AbortController().signal).catch((e) => e) + expect((await parse({ base_resp: { status_code: 1002, status_msg: "rate limit" } })).status).toBe(429) + expect((await parse({ base_resp: { status_code: 2056, status_msg: "usage limit exceeded" } })).status).toBe(429) + expect((await parse({ base_resp: { status_code: 1008, status_msg: "insufficient balance" } })).status).toBe(402) + expect((await parse({ code: 1039, message: "token limit" })).status).toBe(429) + const other = await parse({ base_resp: { status_code: 2013, status_msg: "invalid params" } }) + expect(other.message).toContain("invalid params") + expect(other.status).toBeUndefined() +}) + +test("the search hook rests the account on a base_resp rate limit", async () => { + let f + try { + f = fakeMiniMax() + f.route("POST " + SEARCH, () => json({ base_resp: { status_code: 1002, status_msg: "rate limit" } })) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const err = await hooks.search["minimax-code"].execute( + { query: "MiniMax" }, + { getAuth: async () => ({ access: "tok-1", type: "oauth" }) }, + ).catch((e) => e) + expect(err.status).toBe(429) + } finally { + f?.close() + } +}) diff --git a/packages/minimax/package.json b/packages/minimax/package.json index e347a93..b265078 100644 --- a/packages/minimax/package.json +++ b/packages/minimax/package.json @@ -1,11 +1,11 @@ { "name": "@magpie-community/opencode-minimax-auth", - "version": "0.2.7", + "version": "0.2.8", "description": "OpenCode provider plugins for MiniMax Code accounts: their credits and M Plan, China (minimax-code) and international (minimax-code-global), with MiniMax Code's own device sign-in", "type": "module", "main": "./opencode.mjs", "exports": { "./server": "./magpie.mjs", ".": "./opencode2.mjs" }, - "files": ["index.mjs", "opencode.mjs", "opencode2.mjs", "magpie.mjs", "connector-tools.mjs", "matrix-tools.json", "web-tools.mjs", "README.md"], + "files": ["index.mjs", "opencode.mjs", "opencode2.mjs", "magpie.mjs", "connector-tools.mjs", "native.mjs", "matrix-tools.json", "web-tools.mjs", "README.md"], "keywords": ["opencode", "opencode-plugin", "minimax", "mcode", "minimax-code"], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/minimax" },