From 7c859cc532e2223a4364ba224ff4a05eb61050ee Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 22:38:41 +0800 Subject: [PATCH] minimax 0.1.0: MiniMax Code (mcode) accounts' credits and M Plan, China (minimax-code) and international (minimax-code-global), with MiniMax Code's own device sign-in (Magic_zero on Discord) A new package, @magpie-community/opencode-minimax-auth, written from MiniMax Code 0.6.2's bundle. Sign-in: MiniMax Code's OAuth device flow, the same one mcode uses (account.minimax.cn / account.minimax.io, client mcode-public, scope agent.default, audience agent-backend, PKCE S256). It also handles MiniMax's own variant, where there is no device_code, the user_code is polled for, and expired_in may be an at-ms. The account is named from MiniMax's signed /v1/api/user/info. mcode's ~/.minimax sign-in is never read or written. Each account is a sign-in of its own, so magpie can hold several. Refresh: two minutes before the token ends, or once on a 401. One refresh runs per account (keyed by the refresh token it spends), and its result answers for the old token for a minute, so a late reader doesn't spend a rotated token twice. Only invalid_grant with HTTP 400 signs the account out (signIn: expired); any other failure keeps it and uses the token in hand while it lasts. Chats: Anthropic messages at /mavis/api/v1/llm/v1/messages, carrying: - Authorization: Bearer - x-api-key sk-xxx (mcode's placeholder) - User-Agent MiniMaxAgent - X-Mavis-Agent-Id main - X-Mavis-Timezone-Offset - X-Mavis-Session-Id, from chat.headers' sessionID (otherwise a fixed id per run) A 402, 403 or 429 whose body says credits or quota ran out goes on as a 429 "usage limit reached". Models: the live config at GET /mavis/api/v1/models?region=&buildEnv=prod (asked again without auth on a 401/403), with mcode's built-in four as the fallback: MiniMax-M3.1-Flash-Preview, MiniMax-M3, MiniMax-M2.7 and MiniMax-M2.7-highspeed. Variants follow what mcode sends: adaptive thinking at an effort (output_config.effort), and none to turn thinking off. Usage: mcode's signed account API: user info, the type-0 workspace from get_user_extra_info, then get_membership_info. The card shows credits left (op_credit_summary / opcredit_balance), Free or "M Plan " with its end, and, for an M Plan, coding_plan/remains with X-Group-Id. That is read as magpie's readMiniMaxPlan reads it. There is no check-in. Tests: fakes only. nonet.mjs is imported first, so only 127.0.0.1 can be reached. They cover: - sign-in, the variant, refused, and other errors - refresh, a three-way race plus a late stale reader, per-account refreshes, invalid_grant, other failures, and 401 then refresh then retry - request headers and chat.headers - credits running out going on as a 429 - the live list, the retry without auth, and the fallback (the given object back) - signing, against fixed vectors and the bundle's formula - usage parsing (readMiniMaxPlan's own fixture), Free, M Plan, and a refused account bun test packages/minimax (27 pass) and bun scripts/check.mjs pass. End to end through magpie: origin/main b0486663, built with -tags nogui in a worktree since removed, under env -i with a sandbox HOME, a fake upstream on 127.0.0.1:47811, and a copy of the package with its hosts pointed there: - plugin add - plugin login minimax-code: the device flow and the account named; a second login of the same account merged into one - the live list: 2 models - provider test minimax-code: the chat went out with the headers above - quota: M Plan Plus, 321.5 credits, 5 hours and 7 days windows - an expired token refreshed and saved No request was made to MiniMax. --- README.md | 2 + packages/minimax/README.md | 102 +++++ packages/minimax/fake.mjs | 47 ++ packages/minimax/index.mjs | 723 ++++++++++++++++++++++++++++++ packages/minimax/models.test.mjs | 94 ++++ packages/minimax/nonet.mjs | 18 + packages/minimax/package.json | 11 + packages/minimax/refresh.test.mjs | 124 +++++ packages/minimax/request.test.mjs | 84 ++++ packages/minimax/sign.test.mjs | 57 +++ packages/minimax/signin.test.mjs | 97 ++++ packages/minimax/usage.test.mjs | 100 +++++ registry.json | 2 + 13 files changed, 1461 insertions(+) create mode 100644 packages/minimax/README.md create mode 100644 packages/minimax/fake.mjs create mode 100644 packages/minimax/index.mjs create mode 100644 packages/minimax/models.test.mjs create mode 100644 packages/minimax/nonet.mjs create mode 100644 packages/minimax/package.json create mode 100644 packages/minimax/refresh.test.mjs create mode 100644 packages/minimax/request.test.mjs create mode 100644 packages/minimax/sign.test.mjs create mode 100644 packages/minimax/signin.test.mjs create mode 100644 packages/minimax/usage.test.mjs diff --git a/README.md b/README.md index c1865e3..811879f 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ subscription and makes its requests. The packages work in OpenCode and in | [factory](packages/factory) | Factory (Droid) subscription | `factory` | | [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | +| [minimax](packages/minimax) | MiniMax Code (China): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code` | +| [minimax](packages/minimax) | MiniMax Code (international): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code-global` | | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | | [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` | | [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` | diff --git a/packages/minimax/README.md b/packages/minimax/README.md new file mode 100644 index 0000000..62c91cf --- /dev/null +++ b/packages/minimax/README.md @@ -0,0 +1,102 @@ +# @magpie-community/opencode-minimax-auth + +Signs in to MiniMax Code (mcode) accounts so their credits and M Plan can be +used. That covers the free credits and the daily check-in's credits. There is +one provider for each of MiniMax's two sites: + +| Provider id | Site | API | +|---|---|---| +| `minimax-code` | MiniMax Code, China (minimax.cn / minimaxi.com) | `https://agent.minimax.cn/mavis/api/v1/llm/v1` | +| `minimax-code-global` | MiniMax Code, international (minimax.io) | `https://agent.minimax.io/mavis/api/v1/llm/v1` | + +The package exports `MiniMaxCodeAuthPlugin` (`minimax-code`) and +`MiniMaxCodeGlobalAuthPlugin` (`minimax-code-global`). + +## Risk + +Read this before you use the package: +- **The credits are for MiniMax's services.** MiniMax gives them for use in + MiniMax Code, and its terms decide where else they may be used. This + package uses them from other agents. MiniMax hasn't approved that. +- **The risk to the account is yours.** MiniMax may limit, suspend or close + an account that uses them this way. +- **This is a community package.** It has nothing to do with MiniMax. + +## Signing in + +You sign in with MiniMax Code's own device sign-in: the same OAuth device +flow, PKCE S256 and client `mcode-public` that `mcode /login` uses. +- magpie opens MiniMax's page and shows the code to confirm there. +- The plugin then waits for the sign-in and finishes by itself. + +MiniMax Code's own sign-in is never read or changed. That is +`~/.minimax/auth/…`, so signing in here doesn't sign `mcode` out. + +The sign-in is kept as an OpenCode `oauth` auth: +- what it holds: the access and refresh tokens, their expiry, and the + MiniMax user id and email; +- OpenCode keeps it in `auth.json`; +- magpie keeps it in `plugin-auth.json`. + +Each account signs in on its own, so magpie can hold several and switch +between them. + +Refreshing: +- The access token is refreshed two minutes before it ends, or when MiniMax + turns it away (HTTP 401). The new token is saved. +- Only one refresh runs at a time for an account. Requests that arrive + meanwhile wait for it and use its token. +- The account counts as signed out only when MiniMax answers the refresh + with `invalid_grant` (HTTP 400). Any other failure keeps the sign-in, and + the current token is used while it lasts. + +## Requests + +Chats are Anthropic messages (`@ai-sdk/anthropic`) sent to +`/messages`. Each one carries MiniMax Code's headers: +- `Authorization: Bearer `; +- `x-api-key: sk-xxx`, the placeholder key MiniMax Code gives its SDK; +- `User-Agent: MiniMaxAgent`; +- `X-Mavis-Agent-Id: main`; +- `X-Mavis-Timezone-Offset`; +- `X-Mavis-Session-Id`. This is the conversation's id when magpie or + OpenCode passes one, and a fixed id for the plugin's run otherwise. + +A refusal that says the credits or quota ran out goes on as a 429. The 402, +403 or 429 statuses count, when the body says so. That way magpie can move +the conversation to another account. + +## Models + +When you are signed in, the models come from MiniMax Code's live model +config (`GET /mavis/api/v1/models`). The list includes each model's context, +image input and thinking options. If the live list doesn't answer, this +built-in list is used instead: + +| Model | Context | Images | Reasoning levels (variants) | +|---|---|---|---| +| MiniMax-M3.1-Flash-Preview | 512K | yes | low, medium, high, xhigh, max | +| MiniMax-M3 | 512K | yes | none, high | +| MiniMax-M2.7 | 200K | no | — (always thinks) | +| MiniMax-M2.7-highspeed | 200K | no | — (always thinks) | + +Variants map to what MiniMax Code sends: +- a level is adaptive thinking at that effort, which becomes + `output_config.effort`; +- `none` turns thinking off. + +## Usage + +The usage card shows: +- the credits left; +- the plan: Free, or the M Plan's tier and when it ends; +- for an M Plan, its windows (5 hours, 7 days, and any model's own) from + `coding_plan/remains`. + +These are read the way MiniMax Code reads them, with its signed account API. + +## Not here + +- **No check-in.** The package never claims the daily check-in's credits. + Check in from MiniMax Code or MiniMax's site. +- **No sign-out.** Signing out doesn't revoke the token on MiniMax's side. diff --git a/packages/minimax/fake.mjs b/packages/minimax/fake.mjs new file mode 100644 index 0000000..5534c83 --- /dev/null +++ b/packages/minimax/fake.mjs @@ -0,0 +1,47 @@ +// A fake of MiniMax's hosts for the tests: one local server standing in +// for the account, agent and platform hosts of both sites, which the +// plugin's SITES are pointed at. route(method, path) answers a request; +// seen lists what came. +import { _internal } from "./index.mjs" + +export function fakeMiniMax() { + const routes = new Map() + const seen = [] + const server = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + async fetch(req) { + const url = new URL(req.url) + const text = await req.text() + const r = { method: req.method, path: url.pathname, query: url.searchParams, headers: req.headers, text, url: url.pathname + url.search } + if ((req.headers.get("content-type") ?? "").includes("x-www-form-urlencoded")) r.form = Object.fromEntries(new URLSearchParams(text)) + else if (text) try { r.json = JSON.parse(text) } catch {} + seen.push(r) + const h = routes.get(req.method + " " + url.pathname) + if (!h) return new Response("no route " + req.method + " " + url.pathname, { status: 404 }) + return h(r) + }, + }) + const origin = `http://127.0.0.1:${server.port}` + const was = {} + for (const [id, s] of Object.entries(_internal.SITES)) { + was[id] = { ...s } + Object.assign(s, { account: origin, llm: origin, agent: origin, platform: origin }) + } + _internal.renewing.clear() + _internal.renewed.clear() + return { + origin, + seen, + route: (key, h) => routes.set(key, h), + close() { + server.stop(true) + for (const [id, s] of Object.entries(was)) Object.assign(_internal.SITES[id], s) + }, + } +} + +export const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "content-type": "application/json" } }) + +// a JWT as MiniMax's tokens are, with the claims given +export const jwtOf = (claims) => ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "sig"].join(".") diff --git a/packages/minimax/index.mjs b/packages/minimax/index.mjs new file mode 100644 index 0000000..1450f2b --- /dev/null +++ b/packages/minimax/index.mjs @@ -0,0 +1,723 @@ +// OpenCode provider plugins for MiniMax Code (mcode) accounts: the credits +// a MiniMax Code account gets (the daily check-in's among them) and its +// M Plan, on MiniMax Code's own models. +// - minimax-code: the China site (account.minimax.cn, agent.minimax.cn) +// - minimax-code-global: the international site (account.minimax.io, agent.minimax.io) +// An account signs in here, with MiniMax Code's device sign-in (OAuth 2 +// device flow with PKCE, client mcode-public): nothing is read from or +// written to MiniMax Code's own sign-in (~/.minimax). Its chats are +// Anthropic messages at /mavis/api/v1/llm/v1/messages, sent with +// MiniMax Code's headers. No check-in is made for the account. + +import { createHash, randomBytes, randomUUID } from "node:crypto" + +const CLIENT_ID = "mcode-public" +const SCOPE = "agent.default" +const AUDIENCE = "agent-backend" +const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" +const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is refreshed +const SIGN_IN_MS = 10 * 60 * 1000 // when the device code gives no end of its own +const KEEP_RENEWED_MS = 60 * 1000 // how long a refresh's result answers for the old token +const SIGN_SECRET = "I*7Cf%WZ#S&%1RlZJ&C2" // MiniMax Code's request signing (x-signature) +const NPM = "@ai-sdk/anthropic" +// the key the Anthropic SDK is given in MiniMax Code: a placeholder, the +// account going in Authorization +const PLACEHOLDER_KEY = "sk-xxx" + +// Each site's hosts, as MiniMax Code's prod build has them. Tests point +// these at fakes of their own. +const SITES = { + "minimax-code": { + id: "minimax-code", + name: "MiniMax Code", + region: "cn", + lang: "zh", + account: "https://account.minimax.cn", // OAuth + llm: "https://agent.minimax.cn", // chats and the model list + agent: "https://agent.minimaxi.com", // the account and its membership + platform: "https://www.minimaxi.com", // the M Plan's windows + }, + "minimax-code-global": { + id: "minimax-code-global", + name: "MiniMax Code (Global)", + region: "en", + lang: "en", + account: "https://account.minimax.io", + llm: "https://agent.minimax.io", + agent: "https://agent.minimax.io", + platform: "https://platform.minimax.io", + }, +} + +const api = (site) => site.llm + "/mavis/api/v1/llm/v1" +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +const md5 = (s) => createHash("md5").update(s).digest("hex") +const str = (o, k) => (typeof o?.[k] === "string" && o[k].trim() ? o[k].trim() : undefined) +const pos = (o, k) => (typeof o?.[k] === "number" && Number.isFinite(o[k]) && o[k] > 0 ? o[k] : undefined) +const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined) +const num = (v) => { + if (typeof v === "number" && Number.isFinite(v)) return v + if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) return Number(v) + return undefined +} + +// ---- the models ------------------------------------------------------------- + +// MiniMax Code's own list, for when the live one can't be had. +// thinking: "switchable" (on or off), "forced_on" (always on, at an effort) +const MODELS = [ + { id: "MiniMax-M3.1-Flash-Preview", name: "M3.1-Flash-Preview", context: 512000, output: 128000, images: true, thinking: "forced_on", efforts: ["low", "medium", "high", "xhigh", "max"] }, + { id: "MiniMax-M3", name: "MiniMax-M3", context: 512000, output: 128000, images: true, thinking: "switchable", efforts: [] }, + { id: "MiniMax-M2.7", name: "MiniMax-M2.7", context: 200000, output: 128000, images: false, thinking: "on", efforts: [] }, + { id: "MiniMax-M2.7-highspeed", name: "MiniMax-M2.7-highspeed", context: 200000, output: 128000, images: false, thinking: "on", efforts: [] }, +] + +// variants are a model's reasoning levels as @ai-sdk/anthropic options, +// sent as MiniMax Code sends them: adaptive thinking at an effort +// (output_config.effort), "none" turning thinking off where it can be. +function variants(m) { + const out = {} + if (m.thinking === "switchable") out.none = { thinking: { type: "disabled" } } + if (m.efforts?.length) for (const e of m.efforts) out[e] = { thinking: { type: "adaptive" }, effort: e } + else if (m.thinking === "switchable") out.high = { thinking: { type: "adaptive" } } + return out +} + +const reasons = (m) => m.thinking !== "off" + +function configModels() { + return Object.fromEntries(MODELS.map((m) => [m.id, { + name: m.name, + reasoning: reasons(m), + tool_call: true, + attachment: !!m.images, + modalities: { input: m.images ? ["text", "image"] : ["text"], output: ["text"] }, + limit: { context: m.context, output: m.output }, + cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 }, + variants: variants(m), + }])) +} + +function modelOf(site, provider, m) { + return { + id: m.id, + providerID: provider.id, + name: m.name, + api: { id: m.id, url: api(site), npm: NPM }, + status: "active", + headers: {}, + options: {}, + cost: { input: 0, output: 0, cache: { read: 0, write: 0 } }, + limit: { context: m.context ?? 0, output: m.output ?? 0 }, + capabilities: { + temperature: true, + reasoning: reasons(m), + attachment: !!m.images, + toolcall: true, + input: { text: true, image: !!m.images, audio: false, video: false, pdf: false }, + output: { text: true, image: false, audio: false, video: false, pdf: false }, + interleaved: false, + }, + release_date: "", + variants: variants(m), + } +} + +// parseModels reads MiniMax Code's model config ({providers:[{providerId: +// "minimax", config:{models:{:{…}}, model_order?}}]}) as models. +function parseModels(body) { + const p = (Array.isArray(body?.providers) ? body.providers : []).find((x) => x?.providerId === "minimax") + const ms = obj(obj(p?.config)?.models) + if (!ms) return [] + const order = Array.isArray(p.config.model_order) ? p.config.model_order.filter((id) => ms[id]) : [] + const ids = [...order, ...Object.keys(ms).filter((id) => !order.includes(id))] + const out = [] + for (const id of ids) { + const d = obj(ms[id]) + if (!d || !id.trim()) continue + const input = Array.isArray(d.modalities?.input) ? d.modalities.input : [] + const mode = str(d.thinking_config, "mode") + const efforts = (d.thinking?.effortOptions ?? d.thinking?.effort_options ?? d.effort_options ?? []) + .filter((e) => typeof e === "string" && e && e !== "default" && e !== "none") + out.push({ + id, + name: str(d, "name") ?? id, + context: num(d.limit?.context) ?? 0, + output: num(d.limit?.output) ?? 0, + images: input.includes("image") || d.attachment === true, + thinking: mode === "switchable" ? "switchable" + : mode === "forced_off" ? "off" + : mode === "forced_on" ? "forced_on" + : d.reasoning === false ? "off" : "on", + efforts, + }) + } + return out +} + +// liveModels asks MiniMax Code's model config, as mcode does at start: the +// signed-in account's first, then, when that is refused, no one's. +async function liveModels(site, access) { + const url = new URL("/mavis/api/v1/models", site.llm) + url.searchParams.set("region", site.region) + url.searchParams.set("buildEnv", "prod") + const ask = (auth) => fetch(url, { + headers: { Accept: "application/json", ...(auth ? { Authorization: "Bearer " + auth } : {}) }, + signal: AbortSignal.timeout(10000), + }) + let res = await ask(access) + if (res.status === 401 || res.status === 403) res = await ask("") + if (!res.ok) throw new Error(`${site.name}'s models: HTTP ${res.status}`) + return parseModels(await res.json()) +} + +// ---- signing in (OAuth device flow) --------------------------------------------- + +class OAuthError extends Error { + constructor(code, status, message) { + super(message ?? `MiniMax's sign-in server said ${code}${status ? ` (HTTP ${status})` : ""}`) + this.code = code + this.httpStatus = status + } +} + +// postForm posts an OAuth form, as MiniMax Code's client does; ok is false +// when the answer is an HTTP error or carries an "error". +async function postForm(url, fields) { + const res = await fetch(url, { + method: "POST", + headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(fields).toString(), + signal: AbortSignal.timeout(30000), + }) + let body + try { + body = obj(JSON.parse(await res.text())) + } catch {} + if (!body) throw new OAuthError("invalid_json_response", res.status) + const error = str(body, "error") + return { ok: res.ok && !error, status: res.status, body, error } +} + +const jwt = (t) => { + try { + return obj(JSON.parse(Buffer.from(String(t).split(".")[1] ?? "", "base64url").toString("utf8"))) + } catch { + return undefined + } +} + +// token reads a token answer: refresh is the one to keep when none is sent. +function token(body, refresh) { + const access = str(body, "access_token") + const expiresIn = pos(body, "expires_in") + if (!access || !expiresIn) throw new OAuthError("invalid_token_response") + const claims = jwt(access) + return { + access, + refresh: str(body, "refresh_token") ?? refresh ?? "", + expires: Date.now() + expiresIn * 1000, + subject: str(claims, "sub"), + accountID: str(claims, "account_id"), + } +} + +async function startDevice(site) { + const verifier = randomBytes(32).toString("base64url") + const challenge = createHash("sha256").update(verifier, "ascii").digest("base64url") + const r = await postForm(site.account + "/oauth2/device/code", { + client_id: CLIENT_ID, + scope: SCOPE, + audience: AUDIENCE, + code_challenge: challenge, + code_challenge_method: "S256", + }) + if (!r.ok) throw new OAuthError(r.error ?? "oauth_request_failed", r.status) + const b = r.body + const userCode = str(b, "user_code") + const deviceCode = str(b, "device_code") + const expiredIn = pos(b, "expired_in") + // MiniMax's own variant: no device_code, the user code polled for, an + // end that may be an at-ms, an interval in ms + const byUser = !deviceCode && !!userCode && expiredIn !== undefined + const uri = str(b, "verification_uri") ?? str(b, "verification_url") + const at = expiredIn === undefined ? undefined : expiredIn < 1e12 ? expiredIn : Math.ceil((expiredIn - Date.now()) / 1000) + const expiresIn = pos(b, "expires_in") ?? (at > 0 ? at : undefined) + const interval = pos(b, "interval") + if (!(deviceCode ?? (byUser ? userCode : undefined)) || !userCode || !uri) throw new OAuthError("invalid_device_authorization_response") + return { + verifier, + userCode, + poll: byUser ? { user_code: userCode } : { device_code: deviceCode }, + url: str(b, "verification_uri_complete") ?? uri, + deadline: Date.now() + (expiresIn ? expiresIn * 1000 : SIGN_IN_MS), + intervalMs: byUser && interval !== undefined ? interval : (interval ?? 5) * 1000, + } +} + +async function pollDevice(site, d) { + let wait = d.intervalMs + while (Date.now() < d.deadline) { + await sleep(wait) + const r = await postForm(site.account + "/oauth2/token", { + grant_type: DEVICE_GRANT, + ...d.poll, + client_id: CLIENT_ID, + code_verifier: d.verifier, + }) + const status = str(r.body, "status") + if (r.ok && status === "pending") continue + if (r.ok && status === "slow_down") { + wait += 5000 + continue + } + if (r.ok && (status === "denied" || status === "access_denied")) throw new OAuthError("access_denied", 0, "the sign-in was turned down") + if (r.ok && (status === "expired" || status === "expired_token")) throw new OAuthError("expired_token", 0, "the sign-in code expired") + if (r.ok) return token(r.body) + if (r.error === "authorization_pending") continue + if (r.error === "slow_down") { + wait += 5000 + continue + } + throw new OAuthError(r.error ?? "device_authorization_failed", r.status) + } + throw new OAuthError("expired_token", 0, "the sign-in code expired") +} + +// refreshToken trades a refresh token for a new access token. +async function refreshToken(site, refresh) { + const r = await postForm(site.account + "/oauth2/token", { + grant_type: "refresh_token", + refresh_token: refresh, + client_id: CLIENT_ID, + scope: SCOPE, + audience: AUDIENCE, + }) + if (!r.ok) throw new OAuthError(r.error ?? "oauth_request_failed", r.status) + return token(r.body, refresh) +} + +// signedOut is the one answer that means the account is signed out, as +// MiniMax Code reads it: invalid_grant with HTTP 400. Anything else (a +// 5xx, a timeout, another error) is passing, and the sign-in is kept. +const signedOut = (e) => e instanceof OAuthError && e.code === "invalid_grant" && e.httpStatus === 400 + +class SignInExpired extends Error { + constructor(site) { + super(`this ${site.name} account is signed out; sign in again`) + this.signIn = "expired" + } +} + +// ---- MiniMax Code's signed account API ------------------------------------------- + +// signed is a request of MiniMax Code's account API, signed as mcode signs +// one: yy over the path and query, the body ("{}" for a GET) and the time; +// x-signature over the time (and the body of a POST). +function signed(site, path, { access, userID, body, now = Date.now(), tz = new Date().getTimezoneOffset() * -60, platform = process.platform } = {}) { + const url = new URL(path, site.agent) + url.search = new URLSearchParams({ + device_platform: "mcode", biz_id: "3", app_id: "3001", version_code: "22201", + unix: String(now), timezone_offset: String(tz), sys_language: site.lang, lang: site.lang, + device_id: "0", os_name: platform, browser_name: "mcode", user_id: String(userID ?? "").trim() || "0", client: "mcode", + }).toString() + const at = url.pathname + url.search + const ts = Math.floor(now / 1000) + const json = body === undefined ? undefined : JSON.stringify(body) + const headers = { + Accept: "application/json", + "Content-Type": "application/json", + "User-Agent": "MiniMaxCode", + Authorization: "Bearer " + access, + yy: json === undefined ? md5(`${encodeURIComponent(at)}_{}${md5(String(now))}ooui`) : md5(`${encodeURIComponent(at)}_${json}${md5(String(now))}ooui`), + "x-timestamp": String(ts), + "x-signature": json === undefined ? md5(`${ts}${SIGN_SECRET}`) : md5(`${ts}${SIGN_SECRET}${json}`), + } + return { url: url.toString(), init: { method: json === undefined ? "GET" : "POST", headers, ...(json === undefined ? {} : { body: json }) } } +} + +class AccountRefused extends Error {} + +// checked throws on an answer MiniMax's account API says failed in its body. +function checked(env, what) { + const si = obj(env.statusInfo) + if (typeof si?.code === "number" && si.code !== 0) { + if (si.code === 1000048) throw new AccountRefused(`${what}: the sign-in was refused`) + throw new Error(`${what}: ${str(si, "message") ?? str(si, "msg") ?? "status " + si.code}`) + } + const br = obj(env.base_resp) + if (typeof br?.status_code === "number" && br.status_code !== 0) throw new Error(`${what}: ${str(br, "status_msg") ?? "status " + br.status_code}`) + return env +} + +async function accountCall(site, path, opts, what) { + const { url, init } = signed(site, path, opts) + const res = await fetch(url, { ...init, signal: AbortSignal.timeout(15000) }) + if (res.status === 401 || res.status === 403) throw new AccountRefused(`${what}: the sign-in was refused (HTTP ${res.status})`) + if (!res.ok) throw new Error(`${what}: HTTP ${res.status}`) + let env + try { + env = obj(JSON.parse(await res.text())) + } catch {} + if (!env) throw new Error(`${what}: not JSON`) + return checked(env, what) +} + +// identity is who the account is: its MiniMax user id, email and name. +async function identity(site, access) { + const env = await accountCall(site, "/v1/api/user/info", { access }, "account") + const d = obj(env.data) + const u = obj(d?.userInfo) ?? obj(d?.user_info) ?? obj(env.userInfo) ?? obj(env.user_info) + const id = str(u, "realUserID") ?? str(u, "real_user_id") + if (!id) throw new Error("account: no user id in the reply") + const first = (...ks) => ks.map((k) => str(u, k)).find(Boolean) + return { realUserID: id, email: first("userEmail", "email", "userMail", "user_email"), name: first("name", "userName", "user_name") } +} + +// membershipOf reads a membership answer (or a workspace) as mcode does. +function membershipOf(e) { + const d = obj(e?.data) + const pick = (k) => e?.[k] ?? d?.[k] + const s = (k) => (typeof pick(k) === "string" && pick(k).trim() ? pick(k).trim() : undefined) + const has = typeof pick("has_token_plan") === "boolean" ? pick("has_token_plan") : undefined + const ends = num(pick("token_plan_expires_at")) + const sum = obj(e?.op_credit_summary) ?? obj(d?.op_credit_summary) + const bal = str(sum, "total_remaining_amount") ?? (() => { + const v = pick("opcredit_balance") + return typeof v === "string" && v.trim() ? v.trim() : typeof v === "number" && Number.isFinite(v) ? String(v) : undefined + })() + return { + ...(has !== undefined ? { hasTokenPlan: has } : {}), + ...(s("op_group_id") ? { opGroupId: s("op_group_id") } : {}), + ...(s("token_plan_tier") ? { tier: s("token_plan_tier") } : {}), + ...(ends > 0 ? { expiresAt: ends } : {}), + ...(bal !== undefined ? { balance: bal } : {}), + } +} + +// membership is the account's plan and credits: its own workspace's +// (workspace_type 0), with what the membership API says of that workspace. +async function membership(site, access, userID) { + let ws + try { + const env = await accountCall(site, "/matrix/api/v1/user/get_user_extra_info", { access, userID, body: {} }, "workspace") + const list = Array.isArray(env.workspaces) ? env.workspaces : Array.isArray(env.data?.workspaces) ? env.data.workspaces : [] + for (const w of list) { + if (num(w?.workspace_type) !== 0) continue + const id = typeof w.workspace_id === "number" && w.workspace_id >= 0 ? w.workspace_id : str(w, "workspace_id") + if (id !== undefined) { + ws = { id, m: membershipOf(w) } + break + } + } + } catch (e) { + if (e instanceof AccountRefused) throw e + return membershipOf(await accountCall(site, "/matrix/api/v1/commerce/get_membership_info", { access, userID, body: {} }, "membership")) + } + if (!ws) return {} + try { + const m = membershipOf(await accountCall(site, "/matrix/api/v1/commerce/get_membership_info", { access, userID, body: { workspace_id: ws.id } }, "membership")) + const has = ws.m.hasTokenPlan === true || m.hasTokenPlan === true ? true : ws.m.hasTokenPlan === false || m.hasTokenPlan === false ? false : undefined + return { ...ws.m, ...m, ...(has !== undefined ? { hasTokenPlan: has } : {}), ...(ws.m.opGroupId || m.opGroupId ? { opGroupId: ws.m.opGroupId ?? m.opGroupId } : {}) } + } catch (e) { + if (e instanceof AccountRefused) throw e + return ws.m + } +} + +// planWindows reads the M Plan's windows from coding_plan/remains, as +// magpie's own MiniMax plan reader (readMiniMaxPlan) does: each model +// group's interval and week, "general" the plan's own, the rest aside. +function planWindows(body) { + const br = obj(body?.base_resp) + if (br && typeof br.status_code === "number" && br.status_code !== 0) throw new Error(str(br, "status_msg") ?? `MiniMax said ${br.status_code}`) + if (!br && !Array.isArray(body?.model_remains)) throw new Error("no plan in the reply") + const ms = (n) => (n < 1e12 ? n * 1000 : n) + const zero = (v) => num(v) === 0 + const out = [] + for (const k of Array.isArray(body.model_remains) ? body.model_remains : []) { + const name = String(k?.model_name ?? "").trim() + if (!name || (num(k.current_interval_status) === 3 && num(k.current_weekly_status) === 3 && zero(k.current_interval_total_count) && zero(k.current_weekly_total_count))) continue + const general = name.toLowerCase() === "general" + for (const x of [ + { left: num(k.current_interval_remaining_percent), status: num(k.current_interval_status) ?? 0, start: num(k.start_time) ?? 0, end: num(k.end_time) ?? 0, week: false }, + { left: num(k.current_weekly_remaining_percent), status: num(k.current_weekly_status) ?? 0, start: num(k.weekly_start_time) ?? 0, end: num(k.weekly_end_time) ?? 0, week: true }, + ]) { + if (x.status === 3 || (x.left === undefined && x.status !== 2)) continue + const w = { used: x.status === 2 ? 100 : Math.max(0, Math.min(100, 100 - x.left)) } + let span = 0 + if (x.start > 0 && x.end > x.start) span = ms(x.end) - ms(x.start) + else if (x.week) span = 7 * 86400_000 + if (span) w.span = span / 1000 + if (x.end > 0) w.resetsAt = new Date(ms(x.end)).toISOString() + w.name = x.week ? "7 days" + : span > 86400_000 && span % 86400_000 === 0 ? `${span / 86400_000} days` + : span >= 3600_000 && span % 3600_000 === 0 ? `${span / 3600_000} hours` + : span > 0 ? `${Math.floor(span / 60_000)} minutes` + : "Allowance" + if (!general) { + w.name = name[0].toUpperCase() + name.slice(1) + " · " + w.name + w.aside = true + } + out.push(w) + } + } + return out +} + +async function planQuota(site, access, group) { + const res = await fetch(site.platform + "/v1/api/openplatform/coding_plan/remains", { + headers: { Accept: "application/json", Authorization: "Bearer " + access, ...(group ? { "X-Group-Id": group } : {}) }, + signal: AbortSignal.timeout(15000), + }) + if (!res.ok) throw new Error(`M Plan: HTTP ${res.status}`) + return planWindows(await res.json()) +} + +// credits says a balance as a count of credits: "1234.50" is "1234.5 credits". +function credits(b) { + const n = Number(b) + if (!Number.isFinite(n)) return String(b) + return (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, "")) + " credits" +} + +// usageOf is the card: the plan (the M Plan's tier, else Free), the credits +// left, and the M Plan's windows when there are any. +function usageOf(m, windows = []) { + const plan = m.hasTokenPlan ? (m.tier ? "M Plan " + m.tier : "M Plan") : "Free" + return { + plan, + ...(m.hasTokenPlan && m.expiresAt ? { until: new Date(m.expiresAt < 1e12 ? m.expiresAt * 1000 : m.expiresAt).toISOString() } : {}), + ...(m.balance !== undefined ? { balance: credits(m.balance) } : {}), + windows, + } +} + +// ---- requests ----------------------------------------------------------------- + +// QUOTA says a refusal is about the account's credits or plan running out. +const QUOTA = /insufficient|balance|credit|quota|exhaust|limit|余额|积分|额度|不足|用完|上限/i + +// answer is the upstream's answer as magpie reads it: a refusal for running +// out of credits a 429 (so another account can take over), the sign-in +// noted as kept, or renewed when this request refreshed it. +async function answer(res, renewed) { + const headers = new Headers(res.headers) + headers.set("X-Magpie-Sign-In", renewed && res.ok ? "renewed" : "kept") + if (res.status !== 402 && res.status !== 403 && res.status !== 429) return new Response(res.body, { status: res.status, statusText: res.statusText, headers }) + const text = await res.text() + headers.delete("content-length") + headers.delete("content-encoding") + if (res.status === 429 || !QUOTA.test(text)) return new Response(text, { status: res.status, statusText: res.statusText, headers }) + let msg = text.trim() + try { + const v = JSON.parse(text) + msg = v?.error?.message ?? v?.message ?? v?.msg ?? v?.base_resp?.status_msg ?? msg + } catch {} + headers.set("content-type", "application/json") + return new Response(JSON.stringify({ type: "error", error: { type: "rate_limit_error", message: "usage limit reached: " + msg } }), { status: 429, statusText: "Too Many Requests", headers }) +} + +// ---- the plugins ---------------------------------------------------------------- + +// renewing is each refresh under way, by site and the refresh token it +// spends; renewed is what each just gave, kept a minute so a request that +// read the old token after the refresh was saved joins it rather than +// spending the old token again. +const renewing = new Map() +const renewed = new Map() + +function makePlugin(site) { + return async ({ client }) => { + const save = async (a) => { + try { + await client?.auth?.set?.({ path: { id: site.id }, body: a }) + } catch {} + } + + // fresh is the account with an access token that isn't about to end, + // refreshed (and saved) when it is, or when force is set (MiniMax + // turned the token away). One refresh at a time for an account: those + // who come meanwhile wait for it. renewed says this call refreshed. + const fresh = async (getAuth, force = false) => { + const a = await getAuth() + if (a?.type !== "oauth" || !a.access) throw new Error(`${site.name} isn't signed in`) + if (!force && !(a.expires && Date.now() >= a.expires - EARLY_MS)) return { a, renewed: false } + if (!a.refresh) { + if (Date.now() < a.expires) return { a, renewed: false } + throw new SignInExpired(site) + } + const key = site.id + "\n" + a.refresh + const done = renewed.get(key) + if (done && Date.now() - done.at < KEEP_RENEWED_MS) return { a: { ...a, ...done.got }, renewed: true } + let r = renewing.get(key) + if (!r) { + r = (async () => { + const t = await refreshToken(site, a.refresh) + const got = { access: t.access, refresh: t.refresh, expires: t.expires } + await save({ ...a, ...got }) + renewed.set(key, { got, at: Date.now() }) + return got + })().finally(() => renewing.delete(key)) + renewing.set(key, r) + } + try { + return { a: { ...a, ...(await r) }, renewed: true } + } catch (e) { + if (signedOut(e)) throw new SignInExpired(site) + // passing: the token in hand may still do + if (!force && Date.now() < a.expires) return { a, renewed: false } + throw Object.assign(new Error(`${site.name} token refresh: ${e?.message ?? e}`), { signIn: "kept" }) + } + } + + // one conversation id for requests that come with none of their own + const session = randomUUID() + + return { + config: async (config) => { + config.provider ??= {} + config.provider[site.id] ??= {} + const p = config.provider[site.id] + p.name ??= site.name + p.npm ??= NPM + p.api ??= api(site) + p.models = { ...configModels(), ...(p.models ?? {}) } + }, + // 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 + if (id !== site.id || !input?.sessionID) return + output.headers["X-Mavis-Session-Id"] = input.sessionID + }, + provider: { + id: site.id, + // MiniMax Code's live list, when it answers; else the list above + async models(provider, { auth }) { + if (auth?.type !== "oauth" || !auth.access) return provider.models + try { + 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)])) + } catch (e) { + if (e instanceof SignInExpired) throw e + return provider.models + } + }, + }, + auth: { + provider: site.id, + async loader(getAuth) { + const auth = await getAuth() + if (auth?.type !== "oauth") return {} + return { + baseURL: api(site), + apiKey: PLACEHOLDER_KEY, + async fetch(input, init) { + const req = input instanceof Request ? input : null + let body = init?.body + if (body === undefined && req) body = await req.clone().text() + const send = (a) => { + const headers = new Headers(init?.headers ?? req?.headers) + headers.delete("content-length") + headers.set("Authorization", "Bearer " + a.access) + headers.set("x-api-key", PLACEHOLDER_KEY) + headers.set("User-Agent", "MiniMaxAgent") + headers.set("X-Mavis-Agent-Id", "main") + headers.set("X-Mavis-Timezone-Offset", String(new Date().getTimezoneOffset() * -60)) + if (!headers.get("X-Mavis-Session-Id")) headers.set("X-Mavis-Session-Id", session) + if (!headers.has("anthropic-version")) headers.set("anthropic-version", "2023-06-01") + return fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method ?? "POST", headers, body }) + } + let { a, renewed: did } = await fresh(getAuth) + let res = await send(a) + if (res.status === 401) { + // the token was turned away before its end: refresh once + ;({ a } = await fresh(getAuth, true)) + did = true + res = await send(a) + } + return answer(res, did) + }, + } + }, + // the account's credits and M Plan; nothing is claimed (no check-in) + async usage(getAuth) { + const auth = await getAuth() + if (auth?.type !== "oauth" || !auth.access) return { error: "not signed in" } + let a, did + try { + ;({ a, renewed: did } = await fresh(getAuth)) + } catch (e) { + return { error: e?.message ?? String(e), ...(e?.signIn ? { signIn: e.signIn } : {}) } + } + try { + const who = a.realUserID ? { realUserID: a.realUserID, email: a.email, name: a.name } : await identity(site, a.access) + const m = await membership(site, a.access, who.realUserID) + let windows = [] + let error + if (m.hasTokenPlan && m.opGroupId) { + try { + windows = await planQuota(site, a.access, m.opGroupId) + } catch (e) { + error = e?.message ?? String(e) + } + } + return { + ...usageOf(m, windows), + ...(error ? { error } : {}), + user: who.email || who.name || who.realUserID, + signIn: did ? "renewed" : "kept", + } + } catch (e) { + return { error: e?.message ?? String(e), signIn: "kept" } + } + }, + methods: [ + { + type: "oauth", + label: `${site.name} account`, + async authorize() { + const d = await startDevice(site) + return { + url: d.url, + instructions: `Sign in to ${site.name} in the browser and confirm the code ${d.userCode}; this finishes by itself.`, + method: "auto", + async callback() { + try { + const t = await pollDevice(site, d) + let who = {} + try { + who = await identity(site, t.access) + } catch {} + const uid = who.realUserID ?? t.accountID ?? t.subject ?? "" + return { + type: "success", + access: t.access, + refresh: t.refresh, + expires: t.expires, + accountId: who.email || who.name || uid || site.name, + uid, + ...(who.realUserID ? { realUserID: who.realUserID } : {}), + ...(who.email ? { email: who.email } : {}), + ...(who.name ? { name: who.name } : {}), + } + } catch (e) { + return { type: "failed", error: `${site.name} sign-in: ${e?.message ?? e}` } + } + }, + } + }, + }, + ], + }, + } + } +} + +export const MiniMaxCodeAuthPlugin = makePlugin(SITES["minimax-code"]) +export const MiniMaxCodeGlobalAuthPlugin = makePlugin(SITES["minimax-code-global"]) + +// for tests +export const _internal = { SITES, MODELS, signed, md5, parseModels, planWindows, membershipOf, usageOf, credits, variants, renewing, renewed, startDevice, pollDevice } diff --git a/packages/minimax/models.test.mjs b/packages/minimax/models.test.mjs new file mode 100644 index 0000000..5490ebe --- /dev/null +++ b/packages/minimax/models.test.mjs @@ -0,0 +1,94 @@ +// The model list: MiniMax Code's live config when it answers, MiniMax +// Code's built-in four when it doesn't. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { MiniMaxCodeAuthPlugin, _internal } from "./index.mjs" +import { fakeMiniMax, json } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000 } + +async function given(hooks) { + const cfg = { provider: {} } + await hooks.config(cfg) + // as the host hands provider.models what the config declared + const p = cfg.provider["minimax-code"] + 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 () => { + 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"]) + 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" }) + expect(p.models["MiniMax-M3"].modalities.input).toEqual(["text", "image"]) + expect(p.models["MiniMax-M2.7"].modalities.input).toEqual(["text"]) + expect(p.models["MiniMax-M3"].limit).toEqual({ context: 512000, output: 128000 }) +}) + +test("the live list is MiniMax Code's model config", async () => { + f = fakeMiniMax() + f.route("GET /mavis/api/v1/models", () => json({ + version: "7", ttlSeconds: 300, + providers: [ + { providerId: "other", config: { models: { x: {} } } }, + { providerId: "minimax", config: { + model_order: ["MiniMax-M4", "MiniMax-M3"], + models: { + "MiniMax-M3": { name: "MiniMax-M3", limit: { context: 512000, output: 128000 }, modalities: { input: ["text", "image", "video"] }, reasoning: true, thinking_config: { mode: "switchable", default_value: "true" } }, + "MiniMax-M4": { name: "M4", limit: { context: 1000000, output: 128000 }, modalities: { input: ["text"] }, reasoning: true, thinking_config: { mode: "forced_on" }, thinking: { effortOptions: ["default", "low", "high"], defaultEffort: "default" } }, + "MiniMax-M2.7": { name: "MiniMax-M2.7", limit: { context: 200000, output: 128000 }, modalities: { input: ["text"] }, reasoning: true }, + }, + } }, + ], + })) + 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(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) + expect(ms["MiniMax-M3"].variants.none).toEqual({ thinking: { type: "disabled" } }) + expect(ms["MiniMax-M2.7"].variants).toEqual({}) + const r = f.seen[0] + expect(r.query.get("region")).toBe("cn") + expect(r.query.get("buildEnv")).toBe("prod") + expect(r.headers.get("authorization")).toBe("Bearer tok") +}) + +test("a list refused with the account is asked again without it", async () => { + f = fakeMiniMax() + f.route("GET /mavis/api/v1/models", (r) => (r.headers.get("authorization") + ? json({}, 401) + : 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(f.seen.length).toBe(2) +}) + +test("when the list can't be had, the built-in one is given back as it came", async () => { + for (const reply of [() => json({ error: "down" }, 500), () => new Response("not json"), () => json({ providers: [] })]) { + f = fakeMiniMax() + f.route("GET /mavis/api/v1/models", reply) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const p = await given(hooks) + // the very object it was given, which magpie reads as a fallback + expect(await hooks.provider.models(p, { auth })).toBe(p.models) + f.close() + f = null + } + // signed out: not asked at all + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const p = await given(hooks) + expect(await hooks.provider.models(p, { auth: undefined })).toBe(p.models) +}) diff --git a/packages/minimax/nonet.mjs b/packages/minimax/nonet.mjs new file mode 100644 index 0000000..af215dd --- /dev/null +++ b/packages/minimax/nonet.mjs @@ -0,0 +1,18 @@ +// Imported first by every test here: nothing a test runs reaches MiniMax. +// fetch and HTTP/2 go to this machine (a test's fake) or fail, so a test +// left without its fake, or work still going after it, can't send a token +// to account.minimax.cn, agent.minimax.io or any other of MiniMax's hosts. +import http2 from "node:http2" + +const local = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(u) +const realFetch = globalThis.fetch +globalThis.fetch = async (input, init) => { + const u = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + if (!local(u)) throw new Error("a test asked " + u + " with no fake in place") + return realFetch(input, init) +} +const connect = http2.connect +http2.connect = (origin, ...rest) => { + if (!local(String(origin))) throw new Error("a test connected to " + origin) + return connect(origin, ...rest) +} diff --git a/packages/minimax/package.json b/packages/minimax/package.json new file mode 100644 index 0000000..fbf88f6 --- /dev/null +++ b/packages/minimax/package.json @@ -0,0 +1,11 @@ +{ + "name": "@magpie-community/opencode-minimax-auth", + "version": "0.1.0", + "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": "./index.mjs", + "exports": "./index.mjs", + "files": ["index.mjs", "README.md"], + "keywords": ["opencode", "opencode-plugin", "minimax", "mcode", "minimax-code"], + "license": "MIT" +} diff --git a/packages/minimax/refresh.test.mjs b/packages/minimax/refresh.test.mjs new file mode 100644 index 0000000..8b94823 --- /dev/null +++ b/packages/minimax/refresh.test.mjs @@ -0,0 +1,124 @@ +// Refreshing the token: one refresh at a time for an account, the new +// token saved; only MiniMax's invalid_grant (HTTP 400) signs the account +// out, any other failure keeps it. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { MiniMaxCodeAuthPlugin } from "./index.mjs" +import { fakeMiniMax, json } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +// store is a sign-in as magpie keeps it: read afresh by getAuth, saved by +// client.auth.set +function store(a) { + const s = { auth: { type: "oauth", accountId: "a@example.com", ...a }, saves: [] } + s.getAuth = async () => s.auth + s.client = { auth: { set: async ({ path, body }) => { s.saves.push({ id: path.id, body }); s.auth = body } } } + return s +} + +const chat = (opts) => opts.fetch(opts.baseURL + "/messages", { method: "POST", headers: { "content-type": "application/json" }, body: '{"model":"MiniMax-M3","messages":[]}' }) +const ok = () => json({ type: "message", content: [] }) + +test("a token about to end is refreshed first and saved", async () => { + f = fakeMiniMax() + f.route("POST /oauth2/token", () => json({ access_token: "new", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 })) + f.route("POST /mavis/api/v1/llm/v1/messages", ok) + const s = store({ access: "old", refresh: "r1", expires: Date.now() + 10_000 }) + const hooks = await MiniMaxCodeAuthPlugin({ client: s.client }) + const res = await chat(await hooks.auth.loader(s.getAuth)) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + const ref = f.seen.find((r) => r.path === "/oauth2/token") + expect(ref.form).toMatchObject({ grant_type: "refresh_token", refresh_token: "r1", client_id: "mcode-public", scope: "agent.default", audience: "agent-backend" }) + expect(f.seen.find((r) => r.path.endsWith("/messages")).headers.get("authorization")).toBe("Bearer new") + expect(s.saves.length).toBe(1) + expect(s.saves[0]).toMatchObject({ id: "minimax-code", body: { type: "oauth", access: "new", refresh: "r2", accountId: "a@example.com" } }) +}) + +test("two requests racing refresh once; one reading the old token late joins it", async () => { + f = fakeMiniMax() + let refreshes = 0 + f.route("POST /oauth2/token", async () => { + refreshes++ + await Bun.sleep(50) + return json({ access_token: "new", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 }) + }) + f.route("POST /mavis/api/v1/llm/v1/messages", ok) + const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 }) + const hooks = await MiniMaxCodeAuthPlugin({ client: s.client }) + const opts = await hooks.auth.loader(s.getAuth) + const rs = await Promise.all([chat(opts), chat(opts), chat(opts)]) + for (const r of rs) expect(r.status).toBe(200) + expect(refreshes).toBe(1) + // a request that read the sign-in from before the save (another account + // slot's loader, a stale read) doesn't spend the rotated token again + const late = store({ access: "old", refresh: "r1", expires: Date.now() - 1 }) + const opts2 = await (await MiniMaxCodeAuthPlugin({ client: late.client })).auth.loader(late.getAuth) + expect((await chat(opts2)).status).toBe(200) + expect(refreshes).toBe(1) + const sent = f.seen.filter((r) => r.path.endsWith("/messages")).map((r) => r.headers.get("authorization")) + expect(sent).toEqual(Array(4).fill("Bearer new")) +}) + +test("each account refreshes on its own", async () => { + f = fakeMiniMax() + f.route("POST /oauth2/token", async (r) => json({ access_token: "new-" + r.form.refresh_token, refresh_token: r.form.refresh_token + "'", token_type: "Bearer", expires_in: 3600 })) + f.route("POST /mavis/api/v1/llm/v1/messages", ok) + const a = store({ access: "a", refresh: "ra", expires: Date.now() - 1 }) + const b = store({ access: "b", refresh: "rb", expires: Date.now() - 1 }) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + await Promise.all([chat(await hooks.auth.loader(a.getAuth)), chat(await hooks.auth.loader(b.getAuth))]) + const sent = f.seen.filter((r) => r.path.endsWith("/messages")).map((r) => r.headers.get("authorization")).sort() + expect(sent).toEqual(["Bearer new-ra", "Bearer new-rb"]) +}) + +test("invalid_grant with HTTP 400 signs the account out", async () => { + f = fakeMiniMax() + f.route("POST /oauth2/token", () => json({ error: "invalid_grant", error_description: "refresh token revoked" }, 400)) + const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 }) + const hooks = await MiniMaxCodeAuthPlugin({ client: s.client }) + const opts = await hooks.auth.loader(s.getAuth) + const e = await chat(opts).catch((e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBe("expired") + expect(e.message).toContain("sign in again") + expect(s.saves.length).toBe(0) + // the usage card says so too + const u = await hooks.auth.usage(s.getAuth) + expect(u.signIn).toBe("expired") +}) + +test("any other refresh failure keeps the account", async () => { + for (const [status, body] of [[500, { error: "server_error" }], [401, { error: "invalid_grant" }], [400, { error: "invalid_request" }], [503, {}]]) { + f = fakeMiniMax() + f.route("POST /oauth2/token", () => json(body, status)) + f.route("POST /mavis/api/v1/llm/v1/messages", ok) + // a token past its end: the request fails, the account kept + const s = store({ access: "old", refresh: "r1", expires: Date.now() - 1 }) + const hooks = await MiniMaxCodeAuthPlugin({ client: s.client }) + const e = await chat(await hooks.auth.loader(s.getAuth)).catch((e) => e) + expect(e.signIn).toBe("kept") + // a token about to end but not ended yet: it is used as it is + const t = store({ access: "still", refresh: "r1", expires: Date.now() + 30_000 }) + const res = await chat(await hooks.auth.loader(t.getAuth)) + expect(res.status).toBe(200) + expect(f.seen.at(-1).headers.get("authorization")).toBe("Bearer still") + f.close() + f = null + } +}) + +test("a token MiniMax turns away is refreshed once and the request sent again", async () => { + f = fakeMiniMax() + f.route("POST /oauth2/token", () => json({ access_token: "new", refresh_token: "r2", token_type: "Bearer", expires_in: 3600 })) + f.route("POST /mavis/api/v1/llm/v1/messages", (r) => (r.headers.get("authorization") === "Bearer new" ? ok() : json({ type: "error", error: { type: "authentication_error", message: "token expired" } }, 401))) + const s = store({ access: "old", refresh: "r1", expires: Date.now() + 3600_000 }) + const hooks = await MiniMaxCodeAuthPlugin({ client: s.client }) + const res = await chat(await hooks.auth.loader(s.getAuth)) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + expect(f.seen.filter((r) => r.path.endsWith("/messages")).length).toBe(2) + expect(s.auth.access).toBe("new") +}) diff --git a/packages/minimax/request.test.mjs b/packages/minimax/request.test.mjs new file mode 100644 index 0000000..d81e01f --- /dev/null +++ b/packages/minimax/request.test.mjs @@ -0,0 +1,84 @@ +// A chat goes out as MiniMax Code sends one: the account in Authorization, +// the SDK's key a placeholder, MiniMax Code's User-Agent and X-Mavis-* +// headers, the conversation's id from magpie's session. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { MiniMaxCodeAuthPlugin, MiniMaxCodeGlobalAuthPlugin } from "./index.mjs" +import { fakeMiniMax, json } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000 } +const body = '{"model":"MiniMax-M3.1-Flash-Preview","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}' + +test("a chat carries MiniMax Code's headers", async () => { + f = fakeMiniMax() + f.route("POST /mavis/api/v1/llm/v1/messages", () => json({ type: "message", content: [] })) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => auth) + expect(opts.baseURL).toBe(f.origin + "/mavis/api/v1/llm/v1") + expect(opts.apiKey).toBe("sk-xxx") + // magpie's chat.headers hook gives the conversation's id + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: "ses_1", model: { providerID: "minimax-code", id: "MiniMax-M3" }, provider: { info: { id: "minimax-code" } } }, out) + expect(out.headers).toEqual({ "X-Mavis-Session-Id": "ses_1" }) + // as the host sends it: the SDK's key, the hook's headers, the body + const res = await opts.fetch(opts.baseURL + "/messages", { + method: "POST", + headers: new Headers({ "x-api-key": "sk-xxx", "content-type": "application/json", "anthropic-beta": "interleaved-thinking-2025-05-14", ...out.headers }), + body, + }) + expect(res.status).toBe(200) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + const r = f.seen.at(-1) + expect(r.path).toBe("/mavis/api/v1/llm/v1/messages") + expect(r.text).toBe(body) + expect(r.headers.get("authorization")).toBe("Bearer tok") + expect(r.headers.get("x-api-key")).toBe("sk-xxx") + expect(r.headers.get("user-agent")).toBe("MiniMaxAgent") + expect(r.headers.get("x-mavis-agent-id")).toBe("main") + expect(r.headers.get("x-mavis-session-id")).toBe("ses_1") + expect(r.headers.get("x-mavis-timezone-offset")).toBe(String(new Date().getTimezoneOffset() * -60)) + expect(r.headers.get("anthropic-version")).toBe("2023-06-01") + expect(r.headers.get("anthropic-beta")).toBe("interleaved-thinking-2025-05-14") +}) + +test("chat.headers leaves other providers' requests alone", async () => { + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: "ses_1", model: { providerID: "minimax-code-global" }, provider: { info: { id: "minimax-code-global" } } }, out) + expect(out.headers).toEqual({}) +}) + +test("a request with no session of its own gets one that stays the same", async () => { + f = fakeMiniMax() + f.route("POST /mavis/api/v1/llm/v1/messages", () => json({})) + const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => auth) + await opts.fetch(opts.baseURL + "/messages", { method: "POST", body }) + await opts.fetch(opts.baseURL + "/messages", { method: "POST", body }) + const [a, b] = f.seen.map((r) => r.headers.get("x-mavis-session-id")) + expect(a).toMatch(/^[0-9a-f-]{36}$/) + expect(b).toBe(a) +}) + +test("credits run out is a 429, so another account takes over", async () => { + f = fakeMiniMax() + f.route("POST /mavis/api/v1/llm/v1/messages", () => json({ type: "error", error: { type: "permission_error", message: "积分余额不足" } }, 402)) + const opts = await (await MiniMaxCodeAuthPlugin({ client: {} })).auth.loader(async () => auth) + const res = await opts.fetch(opts.baseURL + "/messages", { method: "POST", body }) + expect(res.status).toBe(429) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error).toEqual({ type: "rate_limit_error", message: "usage limit reached: 积分余额不足" }) +}) + +test("other refusals go on as they came, the account kept", async () => { + f = fakeMiniMax() + f.route("POST /mavis/api/v1/llm/v1/messages", () => json({ type: "error", error: { type: "invalid_request_error", message: "bad model" } }, 400)) + const opts = await (await MiniMaxCodeAuthPlugin({ client: {} })).auth.loader(async () => auth) + const res = await opts.fetch(opts.baseURL + "/messages", { method: "POST", body }) + expect(res.status).toBe(400) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toBe("bad model") +}) diff --git a/packages/minimax/sign.test.mjs b/packages/minimax/sign.test.mjs new file mode 100644 index 0000000..6e74b56 --- /dev/null +++ b/packages/minimax/sign.test.mjs @@ -0,0 +1,57 @@ +// MiniMax Code's request signing for its account API (mcode 0.6.2, +// fetchAccountIdentity and postMatrixJson), where Oy is md5 in hex: +// GET: yy = Oy(`${encodeURIComponent(path+query)}_{}${Oy(String(ms))}ooui`) +// x-signature = Oy(`${s}I*7Cf%WZ#S&%1RlZJ&C2`) +// POST: yy = Oy(`${encodeURIComponent(path+query)}_${body}${Oy(String(ms))}ooui`) +// x-signature = Oy(`${s}I*7Cf%WZ#S&%1RlZJ&C2${body}`) +// with ms the request's time, s it in whole seconds (x-timestamp). The +// vectors below were worked out with those lines as the bundle has them. +import "./nonet.mjs" +import { expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { _internal } from "./index.mjs" + +const Oy = (e) => createHash("md5").update(e).digest("hex") +const site = { ..._internal.SITES["minimax-code"], agent: "https://agent.minimaxi.com" } +const global = { ..._internal.SITES["minimax-code-global"], agent: "https://agent.minimax.io" } +const now = 1790000000123 + +test("a GET is signed with an empty body", () => { + const { url, init } = _internal.signed(site, "/v1/api/user/info", { access: "tok", now, tz: 28800, platform: "darwin" }) + expect(url).toBe("https://agent.minimaxi.com/v1/api/user/info?device_platform=mcode&biz_id=3&app_id=3001&version_code=22201&unix=1790000000123&timezone_offset=28800&sys_language=zh&lang=zh&device_id=0&os_name=darwin&browser_name=mcode&user_id=0&client=mcode") + expect(init.method).toBe("GET") + expect(init.body).toBeUndefined() + expect(init.headers).toEqual({ + Accept: "application/json", + "Content-Type": "application/json", + "User-Agent": "MiniMaxCode", + Authorization: "Bearer tok", + yy: "ea384f50aae587ea2048557a2e1b30b1", + "x-timestamp": "1790000000", + "x-signature": "03015677c012162b07bc060014868ead", + }) +}) + +test("a POST is signed over its body", () => { + const { url, init } = _internal.signed(global, "/matrix/api/v1/commerce/get_membership_info", { access: "tok", userID: "u-42", body: { workspace_id: 7 }, now, tz: 0, platform: "linux" }) + expect(url).toBe("https://agent.minimax.io/matrix/api/v1/commerce/get_membership_info?device_platform=mcode&biz_id=3&app_id=3001&version_code=22201&unix=1790000000123&timezone_offset=0&sys_language=en&lang=en&device_id=0&os_name=linux&browser_name=mcode&user_id=u-42&client=mcode") + expect(init.method).toBe("POST") + expect(init.body).toBe('{"workspace_id":7}') + expect(init.headers.yy).toBe("078fc5529cd0bee0e3f4b587421d726d") + expect(init.headers["x-signature"]).toBe("cdc435f7a98e23c841ecd445dfa82439") +}) + +test("the signature follows the bundle's formula for any request", () => { + for (const [path, body] of [["/v1/api/user/info", undefined], ["/matrix/api/v1/user/get_user_extra_info", {}], ["/matrix/api/v1/commerce/get_membership_info", { workspace_id: "w 1" }]]) { + const t = Date.now() + const { url, init } = _internal.signed(site, path, { access: "x", userID: "9", body, now: t }) + const u = new URL(url) + const at = u.pathname + u.search + const s = Math.floor(t / 1e3) + const d = body === undefined ? undefined : JSON.stringify(body) + expect(init.headers.yy).toBe(d === undefined ? Oy(`${encodeURIComponent(at)}_{}${Oy(String(t))}ooui`) : Oy(`${encodeURIComponent(at)}_${d}${Oy(String(t))}ooui`)) + expect(init.headers["x-signature"]).toBe(d === undefined ? Oy(`${s}I*7Cf%WZ#S&%1RlZJ&C2`) : Oy(`${s}I*7Cf%WZ#S&%1RlZJ&C2${d}`)) + expect(init.headers["x-timestamp"]).toBe(String(s)) + expect(u.searchParams.get("user_id")).toBe("9") + } +}) diff --git a/packages/minimax/signin.test.mjs b/packages/minimax/signin.test.mjs new file mode 100644 index 0000000..dfeadec --- /dev/null +++ b/packages/minimax/signin.test.mjs @@ -0,0 +1,97 @@ +// Signing in with MiniMax Code's device flow, against a fake account host: +// the device code asked for as mcode asks (client mcode-public, PKCE S256), +// polled until it is approved, the account named by MiniMax's own user info. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { MiniMaxCodeAuthPlugin, MiniMaxCodeGlobalAuthPlugin } from "./index.mjs" +import { fakeMiniMax, json, jwtOf } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +const userInfo = () => json({ statusInfo: { code: 0 }, data: { userInfo: { realUserID: "u-42", userEmail: "a@example.com", name: "Ann" } } }) + +test("the device flow signs in, the account named by its email", async () => { + f = fakeMiniMax() + let polls = 0 + f.route("POST /oauth2/device/code", () => json({ + device_code: "dev-1", user_code: "ABCD-EFGH", verification_uri: "https://account.example/device", + verification_uri_complete: "https://account.example/device?code=ABCD-EFGH", expires_in: 60, interval: 0.01, + })) + f.route("POST /oauth2/token", () => (++polls < 3 + ? json({ error: "authorization_pending" }, 400) + : json({ access_token: jwtOf({ sub: "s-1", account_id: "acc-1" }), refresh_token: "r-1", token_type: "Bearer", expires_in: 3600, scope: "agent.default" }))) + f.route("GET /v1/api/user/info", userInfo) + + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const [method] = hooks.auth.methods + expect(method.type).toBe("oauth") + const a = await method.authorize() + expect(a.method).toBe("auto") + expect(a.url).toBe("https://account.example/device?code=ABCD-EFGH") + expect(a.instructions).toContain("ABCD-EFGH") + const got = await a.callback() + expect(got.type).toBe("success") + expect(got.refresh).toBe("r-1") + expect(got.accountId).toBe("a@example.com") + expect(got.uid).toBe("u-42") + expect(got.realUserID).toBe("u-42") + expect(got.expires).toBeGreaterThan(Date.now() + 3500_000) + + const dev = f.seen.find((r) => r.path === "/oauth2/device/code") + expect(dev.form).toMatchObject({ client_id: "mcode-public", scope: "agent.default", audience: "agent-backend", code_challenge_method: "S256" }) + const tok = f.seen.filter((r) => r.path === "/oauth2/token") + expect(tok.length).toBe(3) + for (const t of tok) { + expect(t.form).toMatchObject({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: "dev-1", client_id: "mcode-public" }) + // the verifier sent is the one the challenge was made of + expect(createHash("sha256").update(t.form.code_verifier, "ascii").digest("base64url")).toBe(dev.form.code_challenge) + } + // the account was asked for with MiniMax Code's signature + const info = f.seen.find((r) => r.path === "/v1/api/user/info") + expect(info.headers.get("authorization")).toStartWith("Bearer ") + expect(info.headers.get("x-signature")).toMatch(/^[0-9a-f]{32}$/) +}) + +test("MiniMax's own variant: no device code, the user code polled for, ends and interval in ms", async () => { + f = fakeMiniMax() + let polls = 0 + f.route("POST /oauth2/device/code", () => json({ user_code: "U-CODE", verification_url: "https://account.example/d", expired_in: Date.now() + 60_000, interval: 10 })) + f.route("POST /oauth2/token", () => (++polls < 2 + ? json({ status: "pending" }) + : json({ access_token: "plain-token", refresh_token: "r-2", token_type: "Bearer", expires_in: 3600 }))) + f.route("GET /v1/api/user/info", () => json({}, 500)) // the account can't be named: the token's own says who + + const hooks = await MiniMaxCodeGlobalAuthPlugin({ client: {} }) + const a = await hooks.auth.methods[0].authorize() + expect(a.url).toBe("https://account.example/d") + const got = await a.callback() + expect(got.type).toBe("success") + expect(got.access).toBe("plain-token") + expect(got.accountId).toBe("MiniMax Code (Global)") + for (const t of f.seen.filter((r) => r.path === "/oauth2/token")) { + expect(t.form.user_code).toBe("U-CODE") + expect(t.form.device_code).toBeUndefined() + } +}) + +test("a sign-in turned down fails, saying so", async () => { + f = fakeMiniMax() + f.route("POST /oauth2/device/code", () => json({ device_code: "d", user_code: "c", verification_uri: "https://x/", expires_in: 60, interval: 0.01 })) + f.route("POST /oauth2/token", () => json({ status: "denied" })) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const got = await (await hooks.auth.methods[0].authorize()).callback() + expect(got.type).toBe("failed") + expect(got.error).toContain("turned down") +}) + +test("an error that isn't pending ends the sign-in", async () => { + f = fakeMiniMax() + f.route("POST /oauth2/device/code", () => json({ device_code: "d", user_code: "c", verification_uri: "https://x/", expires_in: 60, interval: 0.01 })) + f.route("POST /oauth2/token", () => json({ error: "invalid_client" }, 401)) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const got = await (await hooks.auth.methods[0].authorize()).callback() + expect(got.type).toBe("failed") + expect(got.error).toContain("invalid_client") +}) diff --git a/packages/minimax/usage.test.mjs b/packages/minimax/usage.test.mjs new file mode 100644 index 0000000..bbd3583 --- /dev/null +++ b/packages/minimax/usage.test.mjs @@ -0,0 +1,100 @@ +// The usage card: the credits left, the M Plan's tier and end, and its +// windows read as magpie's own MiniMax plan reader (readMiniMaxPlan) reads +// them. Nothing is claimed: no check-in is made. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { MiniMaxCodeAuthPlugin, _internal } from "./index.mjs" +import { fakeMiniMax, json } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +const h = 3600 * 1000 + +// readMiniMaxPlan's own test (magpie internal/provider/planquota_test.go) +test("plan windows are read as magpie's MiniMax plan reader reads them", () => { + const ws = _internal.planWindows({ + model_remains: [ + { model_name: "general", start_time: 1790800000000, end_time: 1790800000000 + 5 * h, current_interval_remaining_percent: 72, current_interval_status: 1, current_interval_total_count: 0, + weekly_start_time: 1790500000000, weekly_end_time: 1790500000000 + 168 * h, current_weekly_remaining_percent: 90, current_weekly_status: 1, current_weekly_total_count: 0 }, + { model_name: "video", start_time: 1790800000000, end_time: 1790800000000 + 24 * h, current_interval_remaining_percent: 40, current_interval_status: 2, current_interval_total_count: 3, + current_weekly_status: 3, current_weekly_total_count: 0 }, + { model_name: "music", current_interval_remaining_percent: 100, current_interval_status: 3, current_interval_total_count: 0, + current_weekly_remaining_percent: 100, current_weekly_status: 3, current_weekly_total_count: 0 }, + ], + base_resp: { status_code: 0, status_msg: "success" }, + }) + expect(ws.length).toBe(3) + expect(ws[0]).toEqual({ name: "5 hours", used: 28, span: 5 * 3600, resetsAt: new Date(1790800000000 + 5 * h).toISOString() }) + expect(ws[1]).toMatchObject({ name: "7 days", used: 10, span: 7 * 86400 }) + expect(ws[1].aside).toBeUndefined() + expect(ws[2]).toMatchObject({ name: "Video · 24 hours", used: 100, aside: true }) + expect(() => _internal.planWindows({ base_resp: { status_code: 1004, status_msg: "login fail" } })).toThrow("login fail") + expect(_internal.planWindows({ model_remains: [], base_resp: { status_code: 0 } })).toEqual([]) +}) + +test("a membership is read from the answer or its data", () => { + expect(_internal.membershipOf({ data: { has_token_plan: true, op_group_id: "g1", token_plan_tier: "Plus", token_plan_expires_at: 1800000000000, op_credit_summary: { total_remaining_amount: "1234.50" } } })) + .toEqual({ hasTokenPlan: true, opGroupId: "g1", tier: "Plus", expiresAt: 1800000000000, balance: "1234.50" }) + expect(_internal.membershipOf({ opcredit_balance: 300 })).toEqual({ balance: "300" }) + expect(_internal.usageOf({ balance: "1234.50" })).toEqual({ plan: "Free", balance: "1234.5 credits", windows: [] }) + expect(_internal.usageOf({ hasTokenPlan: true, tier: "Plus", expiresAt: 1800000000000, balance: "0" })) + .toEqual({ plan: "M Plan Plus", until: new Date(1800000000000).toISOString(), balance: "0 credits", windows: [] }) +}) + +const auth = { type: "oauth", access: "tok", refresh: "r", expires: Date.now() + 3600_000, accountId: "a@example.com" } + +function account(f, { plan = false } = {}) { + f.route("GET /v1/api/user/info", () => json({ statusInfo: { code: 0 }, data: { userInfo: { realUserID: "u-42", userEmail: "a@example.com" } } })) + f.route("POST /matrix/api/v1/user/get_user_extra_info", () => json({ statusInfo: { code: 0 }, data: { workspaces: [ + { workspace_id: 9, workspace_type: 1 }, + { workspace_id: 7, workspace_type: 0, op_group_id: "grp-7", opcredit_balance: "50" }, + ] } })) + f.route("POST /matrix/api/v1/commerce/get_membership_info", () => json({ statusInfo: { code: 0 }, data: plan + ? { has_token_plan: true, token_plan_tier: "Plus", token_plan_expires_at: 1800000000000, op_credit_summary: { total_remaining_amount: "88.5" } } + : { has_token_plan: false, op_credit_summary: { total_remaining_amount: "1200" } } })) + f.route("GET /v1/api/openplatform/coding_plan/remains", () => json({ model_remains: [ + { model_name: "general", start_time: 1790800000000, end_time: 1790800000000 + 5 * h, current_interval_remaining_percent: 60, current_interval_status: 1, + weekly_start_time: 1790500000000, weekly_end_time: 1790500000000 + 168 * h, current_weekly_remaining_percent: 75, current_weekly_status: 1 }, + ], base_resp: { status_code: 0 } })) +} + +test("a free account shows its credits", async () => { + f = fakeMiniMax() + account(f) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u).toEqual({ plan: "Free", balance: "1200 credits", windows: [], user: "a@example.com", signIn: "kept" }) + // its own workspace's membership was asked for, signed, with its user id + const m = f.seen.find((r) => r.path === "/matrix/api/v1/commerce/get_membership_info") + expect(m.json).toEqual({ workspace_id: 7 }) + expect(m.query.get("user_id")).toBe("u-42") + expect(m.headers.get("x-signature")).toMatch(/^[0-9a-f]{32}$/) + // no plan, no windows asked for; and nothing claimed + expect(f.seen.some((r) => r.path.includes("coding_plan"))).toBe(false) + expect(f.seen.some((r) => r.path.includes("signin"))).toBe(false) +}) + +test("an M Plan shows its tier, its end and its windows", async () => { + f = fakeMiniMax() + account(f, { plan: true }) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.plan).toBe("M Plan Plus") + expect(u.until).toBe(new Date(1800000000000).toISOString()) + expect(u.balance).toBe("88.5 credits") + expect(u.windows.map((w) => [w.name, w.used])).toEqual([["5 hours", 40], ["7 days", 25]]) + const q = f.seen.find((r) => r.path === "/v1/api/openplatform/coding_plan/remains") + expect(q.headers.get("x-group-id")).toBe("grp-7") + expect(q.headers.get("authorization")).toBe("Bearer tok") +}) + +test("the account refused says so, the sign-in kept", async () => { + f = fakeMiniMax() + f.route("GET /v1/api/user/info", () => json({ statusInfo: { code: 1000048, message: "login expired" } })) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.error).toContain("refused") + expect(u.signIn).toBe("kept") + expect(await hooks.auth.usage(async () => undefined)).toEqual({ error: "not signed in" }) +}) diff --git a/registry.json b/registry.json index 9e39886..e38a38e 100644 --- a/registry.json +++ b/registry.json @@ -21,6 +21,8 @@ "summary": { "en": "Cursor Pro, Pro+, Ultra and Teams — every model your plan has, with tool calls.", "zh": "Cursor Pro、Pro+、Ultra 与 Teams:套餐里的所有模型,支持工具调用。" } }, { "package": "@magpie-community/opencode-kiro-auth", "name": "Kiro", "icon": "kiro-color", "providers": ["kiro"], "community": true, "replaces": "kiro", "summary": { "en": "Kiro Free, Pro, Pro+ and Power — Kiro's sign-in, kiro-cli's, or an API key.", "zh": "Kiro Free、Pro、Pro+ 与 Power:Kiro 登录、沿用 kiro-cli 的登录,或 API key。" } }, + { "package": "@magpie-community/opencode-minimax-auth", "name": "MiniMax Code", "icon": "minimax-color", "providers": ["minimax-code", "minimax-code-global"], "community": true, + "summary": { "en": "MiniMax Code account credits (daily check-in) and M Plan, with MiniMax Code's own device sign-in.", "zh": "用 MiniMax Code 账号的积分(每日签到)与 M Plan,使用 MiniMax Code 自己的设备登录。" } }, { "package": "@magpie-community/opencode-workbuddy-auth", "name": "WorkBuddy", "icon": "workbuddy-color", "providers": ["workbuddy", "workbuddy-ai"], "community": true, "replaces": "workbuddy", "summary": { "en": "WorkBuddy's China build (CodeBuddy plan) and its international build.", "zh": "WorkBuddy 国内版(CodeBuddy 套餐)与国际版。" } } ]