diff --git a/packages/minimax/README.md b/packages/minimax/README.md index 9b7ed6e..bfd4e21 100644 --- a/packages/minimax/README.md +++ b/packages/minimax/README.md @@ -194,11 +194,15 @@ The usage card shows: when the soonest of them runs out, from the credit details MiniMax's own client lists (`/minimax-cloud/api/v1/credit/details`); beside an M Plan it is aside, since the plan's windows come first; -- the plan: Free, or the M Plan's tier and when it ends; none when the +- the plan: Free, or the subscription's name as the console says it (else + its tier) and when it ends; none when the site has no membership API (the international site answers both of its calls with 404), and the card goes on with the credits; -- for an M Plan, its windows (5 hours, 7 days, and any model's own) from - `coding_plan/remains`. +- for a plan, its windows (5 hours, 7 days, and any model's own) from the + console's `token_plan/remains_percent`, so what MiniMax granted the account + is what shows: `126 / 150 %` left for its `总额度 150% · 已用 24%`, and + Unlimited for a window it doesn't limit. `coding_plan/remains` is the + fallback. These are read the way MiniMax Code reads them, with its signed account API. diff --git a/packages/minimax/index.mjs b/packages/minimax/index.mjs index 7dab3e4..aecacdf 100644 --- a/packages/minimax/index.mjs +++ b/packages/minimax/index.mjs @@ -557,36 +557,70 @@ async function membership(site, access, userID) { } } -// 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. +// planWindows reads the plan's windows, each model group's interval and week, +// "general" the plan's own, the rest aside. It reads the console's reply +// (planQuota), which says what MiniMax granted this account: "24%" used of +// "150%". Whatever a plan was given, an older plan's boost or a tier's own +// allowance, is that total, and a total other than 100 shows as a count in +// points ("126 / 150 %"). An item bucket counts its items. +// +// coding_plan/remains, the fallback, has only a whole remaining share, with +// weekly_boost_permille beside it; its count is that share multiplied, as +// MiniMax's CLI does, up to 1.5 points off. +// +// A model's window at status 3 is unlimited, and said so on "general"; both +// at status 3 with zero totals is a bucket the plan doesn't have. 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 pct = (v) => { + const n = Number.parseFloat(v) + return Number.isFinite(n) ? n : undefined + } 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 }, + { 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, + told: pct(k.current_interval_used_percent), total: pct(k.current_interval_total_percent), items: num(k.current_interval_used_count), of: num(k.current_interval_total_count) }, + { 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, + told: pct(k.current_weekly_used_percent), total: pct(k.current_weekly_total_percent) ?? (num(k.weekly_boost_permille) > 1000 ? num(k.weekly_boost_permille) / 10 : undefined), items: num(k.current_weekly_used_count), of: num(k.current_weekly_total_count) }, ]) { - 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)) } + if (x.status !== 3 && x.status !== 2 && x.left === undefined && x.told === undefined) continue 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" + const own = 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 (x.status === 3) { + if (general) out.push({ name: own, display: "Unlimited", aside: true }) + continue + } + const total = x.total > 0 ? x.total : 100 + const used = x.status === 2 ? 100 + : x.told !== undefined ? Math.max(0, Math.min(100, (x.told / total) * 100)) + : Math.max(0, Math.min(100, 100 - x.left)) + const w = { used } + if (span) w.span = span / 1000 + if (x.end > 0) w.resetsAt = new Date(ms(x.end)).toISOString() + if (x.items >= 0 && x.of > 0 && x.items <= x.of) { + w.amount = x.status === 2 ? x.of : x.items + w.limit = x.of + if (name.toLowerCase() === "video") w.unit = "videos" + } else if (total !== 100) { + w.limit = total + w.amount = x.status === 2 ? total : x.told ?? (used * total) / 100 + w.unit = "%" + } + w.name = own if (!general) { w.name = name[0].toUpperCase() + name.slice(1) + " · " + w.name w.aside = true @@ -597,15 +631,44 @@ function planWindows(body) { return out } +// magpie gives the whole usage call 20 seconds, and the console's endpoints +// aren't documented, so a stalled one gets little of that. The fallback's 10 +// keeps planQuota within the 15 that 0.2.1 could take. +const CONSOLE_MS = 5000 +const FALLBACK_MS = 10000 + +// planQuota asks the console's own reply first, then coding_plan/remains. async function planQuota(site, access, group) { - const res = await siteFetch(site, site.platform + "/v1/api/openplatform/coding_plan/remains", { - headers: { Accept: "application/json", Authorization: "Bearer " + access, ...(group ? { "X-Group-Id": group } : {}) }, - signal: AbortSignal.timeout(15000), - }, "M Plan") + const headers = { Accept: "application/json", Authorization: "Bearer " + access, ...(group ? { "X-Group-Id": group } : {}) } + try { + const res = await siteFetch(site, site.platform + "/backend/account/token_plan/remains_percent", { headers, signal: AbortSignal.timeout(CONSOLE_MS) }, "M Plan") + if (res.ok) { + const body = await res.json() + if (Array.isArray(body?.model_remains) && body.model_remains.length && !body.base_resp?.status_code) return planWindows(body) + } + } catch {} + const res = await siteFetch(site, site.platform + "/v1/api/openplatform/coding_plan/remains", { headers, signal: AbortSignal.timeout(FALLBACK_MS) }, "M Plan") if (!res.ok) throw new Error(`M Plan: HTTP ${res.status}`) return planWindows(await res.json()) } +// planTitle is the subscription's name as the console says it, +// "TokenPlanMax-年度会员"; undefined when it can't be read, and usageOf names +// the tier instead. +async function planTitle(site, access, group) { + try { + const res = await siteFetch(site, site.platform + "/v1/api/openplatform/charge/combo/cycle_audio_resource_package?biz_line=2&cycle_type=1&resource_package_type=7", { + headers: { Accept: "application/json", Authorization: "Bearer " + access, ...(group ? { "X-Group-Id": group } : {}) }, + signal: AbortSignal.timeout(CONSOLE_MS), + }, "M Plan") + if (!res.ok) return undefined + const t = (await res.json())?.current_subscribe?.current_subscribe_title + return typeof t === "string" && t.trim() ? t.trim() : undefined + } catch { + return undefined + } +} + // credits says a balance as a count of credits: "1234.50" is "1234.5 credits". function credits(b) { const n = Number(b) @@ -681,10 +744,13 @@ function creditsWindow(batches, now = Date.now()) { } } -// 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. +// usageOf is the card: the plan (the console's title, else its tier, else +// Free), the credits left, and the plan's windows when there are any. Plus, +// Max and Ultra are Token Plan's tiers, which M Plan's Go, Explore and Build +// replaced for new subscribers. function usageOf(m, windows = []) { - const plan = m.hasTokenPlan ? (m.tier ? "M Plan " + m.tier : "M Plan") : m.unknown ? undefined : "Free" + const line = /^(plus|max|ultra)$/i.test(m.tier ?? "") ? "Token Plan " : "M Plan " + const plan = m.hasTokenPlan ? (m.title ?? (m.tier ? line + m.tier : "M Plan")) : m.unknown ? undefined : "Free" return { ...(plan ? { plan } : {}), ...(m.hasTokenPlan && m.expiresAt ? { until: new Date(m.expiresAt < 1e12 ? m.expiresAt * 1000 : m.expiresAt).toISOString() } : {}), @@ -998,12 +1064,16 @@ function makePlugin(site) { const m = await membership(site, a.access, who.realUserID) let windows = [] let error + let title if (m.hasTokenPlan && m.opGroupId) { - try { - windows = await planQuota(site, a.access, m.opGroupId) - } catch (e) { - error = e?.message ?? String(e) - } + // asked together: a stalled title costs its 5 seconds at most, not 5 more after the windows + ;[windows, title] = await Promise.all([ + planQuota(site, a.access, m.opGroupId).catch((e) => { + error = e?.message ?? String(e) + return [] + }), + planTitle(site, a.access, m.opGroupId), + ]) } // the credits as a share of what the live batches granted // (#393); beside an M Plan they are its fallback, aside. A @@ -1014,7 +1084,7 @@ function makePlugin(site) { if (cw) windows = [...windows, m.hasTokenPlan ? { ...cw, aside: true } : cw] } catch {} return { - ...usageOf(m, windows), + ...usageOf(title ? { ...m, title } : m, windows), ...(error ? { error } : {}), user: who.email || who.name || who.realUserID, signIn: did ? "renewed" : "kept", diff --git a/packages/minimax/package.json b/packages/minimax/package.json index f48cb86..7107d7d 100644 --- a/packages/minimax/package.json +++ b/packages/minimax/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-minimax-auth", - "version": "0.2.1", + "version": "0.2.2", "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", diff --git a/packages/minimax/usage.test.mjs b/packages/minimax/usage.test.mjs index 671de34..b2f86a5 100644 --- a/packages/minimax/usage.test.mjs +++ b/packages/minimax/usage.test.mjs @@ -33,13 +33,58 @@ test("plan windows are read as magpie's MiniMax plan reader reads them", () => { expect(_internal.planWindows({ model_remains: [], base_resp: { status_code: 0 } })).toEqual([]) }) +// A user's report: the console said 总额度 150% · 已用 24% and the card only 83%. +// Shaped as that account's reply, with the times left out. +const consoleReply = { model_remains: [ + { model_name: "general", current_interval_status: 1, current_interval_total_count: -1, current_interval_used_count: -1, current_interval_used_percent: "1%", current_interval_total_percent: "100%", + current_weekly_status: 1, current_weekly_total_count: -1, current_weekly_used_count: -1, current_weekly_used_percent: "24%", current_weekly_total_percent: "150%" }, + { model_name: "video", current_interval_status: 1, current_interval_total_count: 3, current_interval_used_count: 0, current_interval_used_percent: "0%", current_interval_total_percent: "100%", + current_weekly_status: 1, current_weekly_total_count: 21, current_weekly_used_count: 1, current_weekly_used_percent: "5%", current_weekly_total_percent: "100%" }, +], base_resp: { status_code: 0 } } + +test("the console's reply says what was granted, whatever it is", () => { + const ws = _internal.planWindows(consoleReply) + expect(ws.map((w) => [w.name, w.used, w.amount, w.limit, w.unit])).toEqual([ + ["Allowance", 1, undefined, undefined, undefined], + ["7 days", 16, 24, 150, "%"], + ["Video · Allowance", 0, 0, 3, "videos"], + ["Video · 7 days", 5, 1, 21, "videos"], + ]) + const general = (fields) => _internal.planWindows({ model_remains: [{ model_name: "general", ...fields }], base_resp: { status_code: 0 } }) + // no list of offers: a total nobody has seen yet reads the same way + expect(general({ current_interval_status: 1, current_interval_used_percent: "50%", current_interval_total_percent: "200%", current_weekly_status: 1, current_weekly_used_percent: "30%", current_weekly_total_percent: "300%" }).map((w) => [w.used, w.amount, w.limit])) + .toEqual([[25, 50, 200], [10, 30, 300]]) + // a plain 100% total is a share alone; used up is 100 whatever the figures say + expect(general({ current_weekly_status: 1, current_weekly_used_percent: "24%", current_weekly_total_percent: "100%" })[0].limit).toBeUndefined() + expect(general({ current_weekly_status: 2, current_weekly_used_percent: "149%", current_weekly_total_percent: "150%" })[0]).toMatchObject({ used: 100, amount: 150, limit: 150 }) + // a week without a limit says so on the plan's own bucket + expect(general({ current_interval_status: 1, current_interval_used_percent: "1%", current_interval_total_percent: "100%", current_weekly_status: 3, current_weekly_total_count: -1 }).at(-1)) + .toEqual({ name: "7 days", display: "Unlimited", aside: true }) +}) + +test("coding_plan/remains alone multiplies its share by the boost", () => { + const week = (boost) => _internal.planWindows({ model_remains: [{ model_name: "general", current_weekly_status: 1, current_weekly_remaining_percent: 83, ...boost }], base_resp: { status_code: 0 } })[0] + expect(week({ weekly_boost_permille: 1500 })).toMatchObject({ used: 17, amount: 25.5, limit: 150, unit: "%" }) + for (const plain of [{}, { weekly_boost_permille: 1000 }, { weekly_boost_permille: 0 }]) { + expect(week(plain).used).toBe(17) + expect(week(plain).limit).toBeUndefined() + } +}) + +test("the plan is named as the console names it, else by its tier's line", () => { + expect(_internal.usageOf({ hasTokenPlan: true, title: "TokenPlanMax-年度会员", tier: "Max" }).plan).toBe("TokenPlanMax-年度会员") + expect(_internal.usageOf({ hasTokenPlan: true, tier: "Max" }).plan).toBe("Token Plan Max") + expect(_internal.usageOf({ hasTokenPlan: true, tier: "Explore" }).plan).toBe("M Plan Explore") + expect(_internal.usageOf({ hasTokenPlan: true }).plan).toBe("M Plan") +}) + 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: [] }) + .toEqual({ plan: "Token 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" } @@ -59,6 +104,43 @@ function account(f, { plan = false } = {}) { ], base_resp: { status_code: 0 } })) } +test("a plan reads the console's windows and title, and goes on without them", async () => { + f = fakeMiniMax() + account(f, { plan: true }) + f.route("GET /backend/account/token_plan/remains_percent", () => json(consoleReply)) + f.route("GET /v1/api/openplatform/charge/combo/cycle_audio_resource_package", () => json({ current_subscribe: { current_subscribe_title: "TokenPlanMax-年度会员" }, base_resp: { status_code: 0 } })) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.plan).toBe("TokenPlanMax-年度会员") + expect(u.windows.find((w) => w.name === "7 days")).toMatchObject({ used: 16, amount: 24, limit: 150 }) + const asked = f.seen.find((r) => r.path === "/backend/account/token_plan/remains_percent") + expect(asked.headers.get("authorization")).toBe("Bearer tok") + expect(asked.headers.get("x-group-id")).toBe("grp-7") + expect(f.seen.some((r) => r.path.includes("coding_plan"))).toBe(false) + + f.route("GET /backend/account/token_plan/remains_percent", () => new Response("nope", { status: 500 })) + f.route("GET /v1/api/openplatform/charge/combo/cycle_audio_resource_package", () => json({ base_resp: { status_code: 1033 } })) + const off = await hooks.auth.usage(async () => auth) + expect(off.plan).toBe("Token Plan Plus") + expect(off.windows.find((w) => w.name === "7 days").used).toBe(25) +}) + +// A stall is what the fallback is for, and magpie allows usage 20 seconds. Asked +// one after another these two would take 10 here. +test("the console's endpoints not answering leave the coding_plan/remains windows in time", async () => { + f = fakeMiniMax() + account(f, { plan: true }) + f.route("GET /backend/account/token_plan/remains_percent", () => new Promise(() => {})) + f.route("GET /v1/api/openplatform/charge/combo/cycle_audio_resource_package", () => new Promise(() => {})) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const start = Date.now() + const u = await hooks.auth.usage(async () => auth) + expect(Date.now() - start).toBeLessThan(8000) + expect(u.error).toBeUndefined() + expect(u.plan).toBe("Token Plan Plus") + expect(u.windows.map((w) => [w.name, w.used])).toEqual([["5 hours", 40], ["7 days", 25]]) +}, 15000) + test("a free account shows its credits", async () => { f = fakeMiniMax() account(f) @@ -80,7 +162,7 @@ test("an M Plan shows its tier, its end and its windows", async () => { 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.plan).toBe("Token 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]]) @@ -159,7 +241,7 @@ test("beside an M Plan the credits are aside; a ledger it can't read leaves the expect(u.error).toBeUndefined() f.route("GET /minimax-cloud/api/v1/credit/details", () => new Response("no", { status: 500 })) u = await hooks.auth.usage(async () => auth) - expect(u).toMatchObject({ plan: "M Plan Plus", balance: "88.5 credits" }) + expect(u).toMatchObject({ plan: "Token Plan Plus", balance: "88.5 credits" }) expect(u.error).toBeUndefined() })