diff --git a/packages/minimax/README.md b/packages/minimax/README.md index cd43ff8..009850e 100644 --- a/packages/minimax/README.md +++ b/packages/minimax/README.md @@ -107,6 +107,10 @@ Variants map to what MiniMax Code sends: The usage card shows: - the credits left; +- a Credits window: how much of the credits not yet expired is used, and + 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; - for an M Plan, its windows (5 hours, 7 days, and any model's own) from `coding_plan/remains`. diff --git a/packages/minimax/index.mjs b/packages/minimax/index.mjs index 4cf331d..97aa684 100644 --- a/packages/minimax/index.mjs +++ b/packages/minimax/index.mjs @@ -515,6 +515,74 @@ function credits(b) { return (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, "")) + " credits" } +// ---- the credits ledger ---------------------------------------------------------- + +// MiniMax's own client lists the account's credits batch by batch in +// Settings → Usage → Credit details (积分明细): GET +// /minimax-cloud/api/v1/credit/details, page_number, page_size 20 and +// include_expired, answering { details, total_count }. Each batch has +// credit_type (1 purchased, 2 check-in), granted_amount, consumed_amount +// and remaining_amount as decimal strings ("1,200.5"; a remaining below 0 +// is 0), granted_at_ms and expire_at_ms; a batch past expire_at_ms is +// Expired. It goes as the check-in's calls go, to the account host. +const LEDGER_PAGE = 20 +const LEDGER_PAGES = 10 + +// amountOf reads a ledger amount as the client does; null when it isn't one. +function amountOf(v, clampNegative = false) { + if (v === null || v === undefined || v === "") return null + let t = String(v).replace(/,/g, "").trim() + if (clampNegative && t.startsWith("-")) return /^\d+(\.\d+)?$/.test(t.slice(1)) ? 0 : null + if (!/^\d+(\.\d+)?$/.test(t)) return null + const n = Number(t) + return Number.isFinite(n) ? n : null +} + +// ledgerBatches is the batches of every page, or null when the list +// couldn't be read whole: a part of the ledger would tell a wrong share. +async function ledgerBatches(site, access, userID) { + const out = [] + for (let page = 1; page <= LEDGER_PAGES; page++) { + const env = await accountCall(site, "/minimax-cloud/api/v1/credit/details", { + access, userID, origin: site.agent, + query: { ...CHECKIN_QUERY, page_number: String(page), page_size: String(LEDGER_PAGE), include_expired: "true" }, + }, "credits") + const d = Array.isArray(env.details) ? env : obj(env.data) + if (!Array.isArray(d?.details) || typeof d.total_count !== "number") return null + out.push(...d.details) + if (out.length >= d.total_count || !d.details.length) return out.length >= d.total_count ? out : null + } + return null +} + +// creditsWindow is the batches not yet expired as one window: what they +// granted, what of it is used, and when the soonest of them runs out. None +// when no batch is live or a batch can't be read. +function creditsWindow(batches, now = Date.now()) { + let total = 0, left = 0, soonest + for (const b of batches) { + const granted = amountOf(b?.granted_amount), rest = amountOf(b?.remaining_amount, true), exp = Number(b?.expire_at_ms) + if (b?.credit_type !== 1 && b?.credit_type !== 2) continue + if (granted === null || rest === null || !Number.isFinite(exp)) return undefined + if (exp <= now) continue + total += granted + left += Math.min(rest, granted) + if (rest > 0 && (!soonest || exp < soonest.at)) soonest = { at: exp, n: rest } + } + if (!(total > 0)) return undefined + const used = Math.max(0, total - left) + const round = (n) => Math.round(n * 100) / 100 + return { + name: "Credits", + used: (100 * used) / total, + display: `${round(used)} / ${round(total)}`, + amount: round(used), + limit: round(total), + unit: "credits", + ...(soonest ? { runsOutAt: new Date(soonest.at).toISOString(), runsOut: round(soonest.n) } : {}), + } +} + // 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 = []) { @@ -822,6 +890,14 @@ function makePlugin(site) { error = e?.message ?? String(e) } } + // the credits as a share of what the live batches granted + // (#393); beside an M Plan they are its fallback, aside. A + // ledger that can't be read leaves the balance alone. + try { + const b = await ledgerBatches(site, a.access, who.realUserID) + const cw = b && creditsWindow(b) + if (cw) windows = [...windows, m.hasTokenPlan ? { ...cw, aside: true } : cw] + } catch {} return { ...usageOf(m, windows), ...(error ? { error } : {}), @@ -908,4 +984,4 @@ 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, checkinOf } +export const _internal = { SITES, MODELS, signed, md5, parseModels, planWindows, membershipOf, usageOf, credits, creditsWindow, ledgerBatches, variants, renewing, renewed, startDevice, pollDevice, checkinOf } diff --git a/packages/minimax/package.json b/packages/minimax/package.json index e70c069..cc5565d 100644 --- a/packages/minimax/package.json +++ b/packages/minimax/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-minimax-auth", - "version": "0.1.5", + "version": "0.1.6", "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", diff --git a/packages/minimax/usage.test.mjs b/packages/minimax/usage.test.mjs index bbd3583..22d934a 100644 --- a/packages/minimax/usage.test.mjs +++ b/packages/minimax/usage.test.mjs @@ -98,3 +98,67 @@ test("the account refused says so, the sign-in kept", async () => { expect(u.signIn).toBe("kept") expect(await hooks.auth.usage(async () => undefined)).toEqual({ error: "not signed in" }) }) + +// #393: the credits' share, from the ledger MiniMax's own client reads in +// Settings → Usage → Credit details (积分明细): live batches only, amounts +// as the client reads them (strings, commas, a remaining below 0 is 0). +const day = 86400 * 1000 +const batch = (type, granted, consumed, remaining, expires) => + ({ credit_type: type, granted_amount: granted, consumed_amount: consumed, remaining_amount: remaining, granted_at_ms: Date.now() - day, expire_at_ms: expires }) + +test("the credits ledger is a Credits window of the live batches", () => { + const now = Date.now() + const w = _internal.creditsWindow([ + batch(1, "1,000", "250", "750", now + 30 * day), + batch(2, "500", "500", "-3", now + 2 * day), // spent past its end + batch(2, "200", "0", "200", now + 5 * day), + batch(2, "9999", "0", "9999", now - day), // expired: left out + batch(3, "100", "0", "100", now + day), // a type the client doesn't show + ], now) + expect(w).toEqual({ name: "Credits", used: (100 * 750) / 1700, display: "750 / 1700", amount: 750, limit: 1700, unit: "credits", + runsOutAt: new Date(now + 5 * day).toISOString(), runsOut: 200 }) + expect(_internal.creditsWindow([batch(2, "100", "0", "100", now - 1)], now)).toBeUndefined() // nothing live + expect(_internal.creditsWindow([batch(1, "abc", "0", "1", now + day)], now)).toBeUndefined() // unreadable: unknown +}) + +function ledger(f, pages) { + f.route("GET /minimax-cloud/api/v1/credit/details", (r) => { + const n = Number(r.query.get("page_number")) + return json({ statusInfo: { code: 0 }, details: pages[n - 1] ?? [], total_count: pages.flat().length }) + }) +} + +test("a free account's card shows how much of its credits is used", async () => { + f = fakeMiniMax() + account(f) + const live = Date.now() + 30 * day + ledger(f, [Array.from({ length: 20 }, () => batch(2, "50", "10", "40", live)), [batch(1, "1000", "0", "1000", live)]]) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => auth) + expect(u.balance).toBe("1200 credits") + expect(u.windows).toEqual([{ name: "Credits", used: 10, display: "200 / 2000", amount: 200, limit: 2000, unit: "credits", + runsOutAt: new Date(live).toISOString(), runsOut: 40 }]) + const asks = f.seen.filter((r) => r.path === "/minimax-cloud/api/v1/credit/details") + expect(asks.map((r) => [r.method, r.query.get("page_number"), r.query.get("page_size"), r.query.get("include_expired"), r.query.get("user_id")])) + .toEqual([["GET", "1", "20", "true", "u-42"], ["GET", "2", "20", "true", "u-42"]]) + expect(asks[0].headers.get("x-signature")).toMatch(/^[0-9a-f]{32}$/) +}) + +test("beside an M Plan the credits are aside; a ledger it can't read leaves the balance alone", async () => { + f = fakeMiniMax() + account(f, { plan: true }) + ledger(f, [[batch(1, "100", "25", "75", Date.now() + day)]]) + const hooks = await MiniMaxCodeAuthPlugin({ client: {} }) + let u = await hooks.auth.usage(async () => auth) + expect(u.windows.map((w) => [w.name, w.used, !!w.aside])).toEqual([["5 hours", 40, false], ["7 days", 25, false], ["Credits", 25, true]]) + // a list cut short tells no share + f.route("GET /minimax-cloud/api/v1/credit/details", (r) => json({ statusInfo: { code: 0 }, + details: r.query.get("page_number") === "1" ? [batch(1, "100", "0", "100", Date.now() + day)] : [], total_count: 5 })) + u = await hooks.auth.usage(async () => auth) + expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "7 days"]) + 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.error).toBeUndefined() +})