repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/quota/src/providers/minimax.ts
Rawimport { fetchJson } from "../http.ts";
import {
amount,
durationLabel,
epoch,
finite,
label,
list,
object,
percent,
windowBucket,
} from "../parse.ts";
import type {
ProviderQuota,
QuotaBucket,
QuotaProvider,
QuotaValue,
} from "../types.ts";
const WINDOWS = [
["current_interval", "5h", 18000000, "start_time", "end_time"],
[
"current_weekly",
"Weekly",
604800000,
"weekly_start_time",
"weekly_end_time",
],
] as const;
/** Status enum from the official MiniMax CLI: 1 normal, 2 exhausted, 3 unlimited. */
const EXHAUSTED = 2;
const UNLIMITED = 3;
/**
* `usage_count` is remaining in older responses and used in newer ones; like the
* official CLI, pick the reading that agrees with the reported percentage.
*/
function resolveCounts(
count: number,
total: number,
leftPercent: number | undefined,
): { used: number; remaining: number } | undefined {
if (count < 0 || count > total) return undefined;
if (leftPercent === undefined)
return { used: total - count, remaining: count };
const asRemaining = Math.abs((count / total) * 100 - leftPercent);
const asUsed = Math.abs(((total - count) / total) * 100 - leftPercent);
if (Math.min(asRemaining, asUsed) > 1) return undefined;
return asUsed < asRemaining
? { used: count, remaining: total - count }
: { used: total - count, remaining: count };
}
function windowValue(
totalCount: number | undefined,
count: number | undefined,
leftPercent: number | undefined,
boostPermille: number | undefined,
status: unknown,
): QuotaValue {
if (status === UNLIMITED) return { state: "unlimited" };
// M Plan can report zero placeholders alongside usable percentages.
const total =
totalCount !== undefined && totalCount > 0 ? totalCount : undefined;
const counts =
total !== undefined && count !== undefined
? resolveCounts(count, total, leftPercent)
: undefined;
let value: QuotaValue = counts
? amount("unknown", counts.used, total, counts.remaining)
: total !== undefined && count === undefined
? amount("unknown", undefined, total)
: total === undefined && count !== undefined && count > 0
? amount("unknown", undefined, undefined, count)
: { state: "unknown" };
// Boost scales the displayed weekly percentage; remaining may exceed 100%.
const factor =
boostPermille !== undefined && boostPermille > 0 ? boostPermille / 1000 : 1;
const base =
leftPercent ??
(factor !== 1 && counts && total !== undefined
? (counts.remaining / total) * 100
: undefined);
if (base !== undefined) {
const left = base * factor;
const used = Math.min(100, Math.max(0, 100 - left));
if (value.state === "measured") value.usedPercent = used;
else
value = {
state: "measured",
unit: "percent",
used,
remaining: Math.max(0, left),
total: 100,
};
}
return value.state === "unknown" && status === EXHAUSTED
? percent(100)
: value;
}
/** Window length from reported bounds, rounded to minutes so labels stay readable. */
function windowSpan(start: unknown, end: unknown): number | undefined {
const from = epoch(start);
const to = epoch(end);
if (from === undefined || to === undefined) return undefined;
const span = Math.round((to - from) / 60000) * 60000;
return span > 0 ? span : undefined;
}
/** Best effort: weighted allowance per model pool, not requests. */
export function parseMinimax(data: unknown, cn = false): ProviderQuota {
const buckets: QuotaBucket[] = [];
for (const [index, raw] of list(object(data)["model_remains"]).entries()) {
const m = object(raw);
// Status 3 with zero totals marks a model outside the plan (MiniMax CLI #173).
if (
WINDOWS.every(
([prefix]) =>
m[`${prefix}_status`] === UNLIMITED &&
m[`${prefix}_total_count`] === 0,
)
)
continue;
const pool = label(m["model_name"]) ?? `Pool ${index + 1}`;
const scope = pool === "general" ? undefined : pool;
for (const [prefix, fallback, fallbackMs, start, end] of WINDOWS) {
const span = windowSpan(m[start], m[end]);
if (prefix === "current_interval" && !span && /video/i.test(pool))
continue;
const totalCount = finite(m[`${prefix}_total_count`]);
const count = finite(m[`${prefix}_usage_count`]);
const leftPercent = finite(m[`${prefix}_remaining_percent`]);
const status = m[`${prefix}_status`];
if (
totalCount === undefined &&
count === undefined &&
leftPercent === undefined &&
status !== EXHAUSTED &&
status !== UNLIMITED
)
continue;
const value = windowValue(
totalCount,
count,
leftPercent,
prefix === "current_weekly"
? finite(m["weekly_boost_permille"])
: undefined,
status,
);
buckets.push(
windowBucket(
`${pool}:${prefix}`,
durationLabel(span, fallback),
value,
span ?? fallbackMs,
epoch(m[end]),
scope,
),
);
}
}
return {
provider: cn ? "minimax-cn" : "minimax",
name: cn ? "MiniMax CN" : "MiniMax",
buckets,
observedAt: Date.now(),
};
}
function provider(cn: boolean): QuotaProvider {
return {
name: cn ? "MiniMax CN" : "MiniMax",
async fetch(key) {
if (cn)
throw new Error(
"MiniMax CN M Plan quota unavailable: current route not established; no legacy or cross-region fallback.",
);
if (!key.startsWith("sk-cp-"))
throw new Error(
"MiniMax M Plan quota requires a subscription key; PAYG or ambiguous credentials rejected.",
);
const data = await fetchJson(
"https://www.minimax.io/v1/token_plan/remains",
{
headers: {
Authorization: `Bearer ${key}`,
"Content-Type": "application/json",
},
},
);
if (object(object(data)["base_resp"])["status_code"] !== 0)
throw new Error("MiniMax quota unavailable");
return parseMinimax(data, cn);
},
};
}
export const minimax: QuotaProvider = provider(false);
export const minimaxCn: QuotaProvider = provider(true);