import { describe, expect, it, vi } from "vitest"; import { parseAnthropic, parseAnthropicHeaders, } from "../src/providers/anthropic.ts"; import { parseCodex, parseCodexHeaders } from "../src/providers/codex.ts"; import { parseCopilot } from "../src/providers/copilot.ts"; import { parseDeepSeek } from "../src/providers/deepseek.ts"; import { groq, parseGroqHeaders } from "../src/providers/groq.ts"; import { parseKimi } from "../src/providers/kimi.ts"; import { minimax, minimaxCn, parseMinimax } from "../src/providers/minimax.ts"; import { parseMoonshot } from "../src/providers/moonshot.ts"; import { parseOpenRouter } from "../src/providers/openrouter.ts"; import { parseZai } from "../src/providers/zai.ts"; const RESET = "2030-03-17T12:00:00Z"; describe("provider bucket contracts", () => { it("reads Groq requests-per-day headers and never polls", async () => { const quota = parseGroqHeaders({ "x-ratelimit-limit-requests": "1000", "x-ratelimit-limit-tokens": "8000", "x-ratelimit-remaining-requests": "999", "x-ratelimit-remaining-tokens": "7986", "x-ratelimit-reset-requests": "1m26.4s", "x-ratelimit-reset-tokens": "105ms", }); expect(quota?.buckets).toHaveLength(1); expect(quota?.buckets[0]).toMatchObject({ label: "Requests/day", kind: "allowance", value: { unit: "requests", used: 1, total: 1000, remaining: 999 }, }); expect(quota?.buckets[0]?.period?.resetsAt).toBeUndefined(); expect( parseGroqHeaders({ "x-ratelimit-limit-tokens": "8000" }), ).toBeUndefined(); await expect(groq.fetch("key")).rejects.toThrow(); }); it("maps documented DeepSeek and Moonshot balances without inventing totals", () => { // Documented response examples. const deepseek = parseDeepSeek({ is_available: true, balance_infos: [ { currency: "CNY", total_balance: "110.00", granted_balance: "10.00", topped_up_balance: "100.00", }, ], }); expect(deepseek.buckets).toEqual([ expect.objectContaining({ label: "Balance", kind: "balance", scope: undefined, value: expect.objectContaining({ remaining: 110, total: undefined, unitLabel: "CNY", }), }), ]); const moonshot = parseMoonshot( { code: 0, data: { available_balance: 49.6, voucher_balance: 46.6, cash_balance: 3, }, scode: "0x0", status: true, }, false, ); expect(moonshot.provider).toBe("moonshotai"); expect(moonshot.buckets[0]).toMatchObject({ kind: "balance", value: { remaining: 49.6, unitLabel: "USD" }, }); expect(parseMoonshot({ code: 0, data: {} }, true).buckets).toEqual([]); }); it("maps OpenRouter free-tier keys to the free daily request allowance only", () => { // Live free-tier shape (2026-10-28), reduced to quota fields. const now = Date.UTC(2030, 2, 17, 21, 30); const quota = parseOpenRouter( { data: { limit: 0, limit_remaining: 0, effective_budget: { limit_usd: 0, spend_usd: 0, remaining_usd: 0 }, usage_daily: 0, is_free_tier: true, free_model_daily_requests: { used: 50, limit: 50, remaining: 0 }, }, }, now, ); expect(quota.buckets).toHaveLength(1); expect(quota.buckets[0]).toMatchObject({ label: "Free daily", kind: "allowance", period: { resetsAt: Date.UTC(2030, 2, 18) }, value: { unit: "requests", used: 50, total: 50, remaining: 0 }, }); }); it("adds OpenRouter credit cap and spend windows only for paid keys", () => { const quota = parseOpenRouter({ data: { is_free_tier: false, effective_budget: { limit_usd: 20, spend_usd: 5, remaining_usd: 15, resets_at: RESET, }, usage_daily: 1.25, usage_weekly: 5, free_model_daily_requests: { used: 3, limit: 1000, remaining: 997 }, }, }); expect(quota.buckets.map((b) => b.label)).toEqual([ "Free daily", "Credit limit", "Daily spend", "Weekly spend", ]); expect(quota.buckets[1]).toMatchObject({ kind: "spend-cap", period: { resetsAt: Date.parse(RESET) }, value: { used: 5, total: 20, remaining: 15, unitLabel: "USD" }, }); }); it("preserves conflicting Kimi rate and plan measurements as distinct sources", () => { // Published endpoint example: a measured rate window and a different plan ratio coexist. const quota = parseKimi({ limits: [ { window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" }, detail: { limit: "100", used: "57", remaining: "43", resetTime: RESET, }, }, ], usages: { limit_5h: { used_ratio: 0, reset_time: RESET }, limit_month_total: { used_ratio: 0.1559 }, limit_month_code: { used_ratio: 0 }, }, }); expect(quota.buckets).toHaveLength(4); expect(quota.buckets[0]).toMatchObject({ id: "limits:18000000:all:0", label: "5h", value: { used: 57, total: 100, remaining: 43 }, }); expect(quota.buckets[1]).toMatchObject({ id: "usages:limit_5h", scope: "Plan", value: { used: 0, remaining: 100 }, }); expect(quota.buckets.map((b) => b.label)).toContain("Monthly total"); }); it("deduplicates Anthropic aliases but retains scoped limits regardless of is_active", () => { const quota = parseAnthropic({ five_hour: { utilization: 6, resets_at: RESET }, seven_day: { utilization: 54, resets_at: RESET }, limits: [ { kind: "session", percent: 6, resets_at: RESET, is_active: false }, { kind: "weekly_all", percent: 54, resets_at: RESET, is_active: false }, { kind: "weekly_scoped", percent: 81, scope: { model: { display_name: "Fable" } }, is_active: true, }, ], }); expect(quota.buckets).toHaveLength(3); expect(quota.buckets.map((b) => b.value)).toEqual([ expect.objectContaining({ used: 6 }), expect.objectContaining({ used: 54 }), expect.objectContaining({ used: 81 }), ]); expect(quota.buckets[2]).toMatchObject({ scope: "Fable", label: "Weekly" }); const missingLegacy = parseAnthropic({ limits: [ { kind: "weekly_scoped", percent: 81, scope: { model: { display_name: "Fable" } }, is_active: false, }, ], }); expect(missingLegacy.buckets).toHaveLength(1); expect(missingLegacy.buckets[0]?.value).toMatchObject({ used: 81 }); expect(parseAnthropic({}).buckets).toEqual([]); }); it("normalizes Anthropic header fractions without inventing missing weekly data", () => { const quota = parseAnthropicHeaders({ "anthropic-ratelimit-unified-5h-utilization": "0.26", "anthropic-ratelimit-unified-5h-reset": "1764554400", }); expect(quota?.buckets).toHaveLength(1); expect(quota?.buckets[0]).toMatchObject({ value: { used: 26, remaining: 74 }, period: { resetsAt: 1764554400000 }, }); }); it("preserves independent Zai windows and raw overrun counts from the live account shape", () => { const quota = parseZai({ data: { limits: [ { type: "CREDIT_LIMIT", unit: 3, number: 5, usage: 12000, currentValue: 0, remaining: 12000, percentage: 0, }, { type: "CREDIT_LIMIT", unit: 6, number: 1, usage: 60000, currentValue: 60021, remaining: 0, percentage: 100, nextResetTime: 1900000000000, }, { type: "TIME_LIMIT", unit: 5, percentage: 30 }, ], }, }); expect(quota.buckets).toHaveLength(3); expect(quota.buckets[0]).toMatchObject({ label: "5h", value: { used: 0, remaining: 12000, total: 12000, usedPercent: 0 }, period: { resetsAt: undefined }, }); expect(quota.buckets[1]).toMatchObject({ label: "Weekly", value: { used: 60021, total: 60000, remaining: 0, usedPercent: 100 }, period: { resetsAt: 1900000000000 }, }); expect(quota.buckets[2]).toMatchObject({ label: "Monthly", value: { used: 30 }, }); }); it("keeps Codex weekly primary, arbitrary durations and nullable windows", () => { const quota = parseCodex({ rate_limit: { primary_window: { used_percent: 42, limit_window_seconds: 604800, reset_at: 1900000000, }, secondary_window: null, }, }); expect(quota.buckets).toHaveLength(1); expect(quota.buckets[0]).toMatchObject({ id: "codex:primary", label: "Weekly", value: { used: 42, remaining: 58 }, period: { resetsAt: 1900000000000 }, }); expect( parseCodex({ rate_limit: { primary_window: { used_percent: 10, limit_window_seconds: 300 }, }, }).buckets[0]?.label, ).toBe("5m"); expect(parseCodex({ rate_limit: {} }).buckets).toEqual([]); expect( parseCodex({ rate_limit: { primary_window: { used_percent: "oops" } } }) .buckets[0]?.value, ).toEqual({ state: "unknown" }); expect( parseCodex({ rate_limit: { primary_window: { used_percent: 120 } } }) .buckets[0]?.value, ).toMatchObject({ used: 100 }); }); it("retains Codex extra buckets, credits and spend controls without summing them", () => { const quota = parseCodex({ additional_rate_limits: [ { metered_feature: "codex_other", limit_name: "Other model", rate_limit: { primary_window: { used_percent: 15, limit_window_seconds: 3600 }, }, }, ], credits: { unlimited: true }, spend_control: { individual_limit: { used: "12.5", limit: "100", remaining: "87.5", reset_at: 1900000000, }, }, }); expect(quota.buckets).toHaveLength(3); expect(quota.buckets[0]).toMatchObject({ scope: "Other model", label: "1h", }); expect(quota.buckets[1]).toMatchObject({ kind: "balance", value: { state: "unlimited" }, }); expect(quota.buckets[2]).toMatchObject({ kind: "spend-cap", value: { unit: "credits", used: 12.5, total: 100 }, }); const headers = parseCodexHeaders({ "x-codex-secondary-used-percent": "42", "x-codex-secondary-window-minutes": "10080", }); expect(headers?.buckets).toHaveLength(1); expect(headers?.buckets[0]).toMatchObject({ label: "Weekly", value: { used: 42 }, }); expect( parseCodexHeaders({ "x-codex-primary-used-percent": "NaN" }), ).toBeUndefined(); }); it.each([undefined, "0"])( "ignores empty Codex header windows with duration %s", (minutes) => { const headers: Record = { "x-codex-secondary-used-percent": "0", }; if (minutes !== undefined) headers["x-codex-secondary-window-minutes"] = minutes; expect(parseCodexHeaders(headers)).toBeUndefined(); }, ); it.each([ { "x-codex-secondary-window-minutes": "10080" }, { "x-codex-secondary-reset-at": "1900000000" }, ])("preserves genuine unused Codex windows with metadata %j", (metadata) => { const quota = parseCodexHeaders({ "x-codex-secondary-used-percent": "0", ...metadata, }); expect(quota?.buckets).toHaveLength(1); expect(quota?.buckets[0]?.value).toMatchObject({ used: 0, remaining: 100 }); }); it("maps Copilot quota categories, monthly resets and explicit unlimited values", () => { const quota = parseCopilot({ quota_reset_date_utc: RESET, quota_snapshots: { premium_interactions: { percent_remaining: 75 }, chat: { unlimited: true }, new_pool: {}, }, }); expect(quota.buckets.map((b) => b.label)).toEqual([ "Premium requests", "Chat", "new pool", ]); expect(quota.buckets[0]).toMatchObject({ value: { used: 25 }, period: { label: "Monthly", resetsAt: Date.parse(RESET) }, }); expect(quota.buckets[1]?.value).toEqual({ state: "unlimited" }); expect(quota.buckets[2]?.value).toEqual({ state: "unknown" }); }); it("preserves Kimi scope identities when rate limits reorder", () => { const a = { scope: "code", window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" }, detail: { used: "5", limit: "10" }, }; const b = { scope: "chat", window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" }, detail: { used: "2", limit: "10" }, }; const identities = (limits: unknown[]) => parseKimi({ limits }) .buckets.map((b) => [b.scope, b.id]) .sort(); expect(identities([a, b])).toEqual(identities([b, a])); }); it("distinguishes zero Codex spending cap from absent and malformed cap", () => { const cap = (limit: unknown) => parseCodex({ spend_control: { individual_limit: limit } }).buckets; expect(cap({ limit: "0" })[0]?.value).toMatchObject({ state: "measured", total: 0, }); expect(cap(null)).toEqual([]); expect(cap({ limit: "invalid" })[0]?.value).toEqual({ state: "unknown" }); }); it.each([ [minimaxCn, "sk-cp-fixture", "CN M Plan quota unavailable"], [minimax, "sk-api-payg", "subscription key"], [minimax, "ambiguous", "subscription key"], ] as const)( "rejects unsupported MiniMax connection before network: %s", async (provider, key, message) => { const fetch = vi.spyOn(globalThis, "fetch"); try { await expect(provider.fetch(key)).rejects.toThrow(message); expect(fetch).not.toHaveBeenCalled(); } finally { fetch.mockRestore(); } }, ); it("preserves MiniMax remaining-only and total-plus-percentage measurements", () => { const q = parseMinimax({ model_remains: [ { model_name: "a", current_interval_usage_count: 12 }, { model_name: "b", current_interval_total_count: 100, current_interval_remaining_percent: 25, }, ], }); expect(q.buckets[0]?.value).toMatchObject({ state: "measured", remaining: 12, total: undefined, }); expect(q.buckets[1]?.value).toMatchObject({ state: "measured", total: 100, usedPercent: 75, used: undefined, }); }); it.each([ [99, 1], [100, 0], [0, 100], [undefined, undefined], ] as const)( "does not treat MiniMax zero counts as capacity with %s percent remaining", (remaining, used) => { // Current M Plan response (2026-11-09): counts are zero placeholders. const quota = parseMinimax({ model_remains: [ { model_name: "general", current_interval_total_count: 0, current_interval_usage_count: 0, current_interval_remaining_percent: remaining, end_time: 1900000000000, }, ], }); expect(quota.buckets).toHaveLength(1); expect(quota.buckets[0]?.scope).toBeUndefined(); expect(quota.buckets[0]?.period?.resetsAt).toBe(1900000000000); expect(quota.buckets[0]?.value).toEqual( used === undefined ? { state: "unknown" } : { state: "measured", unit: "percent", used, remaining, total: 100, }, ); }, ); it("preserves an exhausted MiniMax allowance with a positive measured total", () => { const quota = parseMinimax({ model_remains: [ { model_name: "general", current_weekly_total_count: 100, current_weekly_usage_count: 0, }, ], }); expect(quota.buckets[0]?.value).toMatchObject({ state: "measured", used: 100, remaining: 0, total: 100, }); }); it("keeps all MiniMax model pools and treats zero percent remaining as exhausted", () => { const quota = parseMinimax({ model_remains: [ { model_name: "MiniMax-M2", current_interval_total_count: 100, current_interval_usage_count: 30, current_weekly_total_count: 1000, current_weekly_usage_count: 800, }, { model_name: "video", current_weekly_remaining_percent: 0 }, ], }); expect(quota.buckets).toHaveLength(3); expect(quota.buckets[0]?.value).toMatchObject({ used: 70, remaining: 30, total: 100, }); expect(quota.buckets[1]?.value).toMatchObject({ used: 200, remaining: 800, total: 1000, }); expect(quota.buckets[2]).toMatchObject({ scope: "video", label: "Weekly", value: { used: 100, remaining: 0 }, }); }); it("reads the official MiniMax CLI quota shape with derived windows, unlimited, and not-in-plan pools", () => { const start = 1900000000000; const hour = 3600000; const week = { weekly_start_time: start, weekly_end_time: start + 168 * hour, }; // Field set from MiniMax-AI/cli src/output/quota-table.ts; values synthetic. const quota = parseMinimax({ model_remains: [ { model_name: "MiniMax-M*", start_time: start, end_time: start + 5 * hour, current_interval_total_count: 1500, current_interval_usage_count: 1200, current_interval_remaining_percent: 20, current_interval_status: 1, ...week, current_weekly_total_count: 15000, current_weekly_usage_count: 3000, current_weekly_remaining_percent: 20, current_weekly_status: 1, weekly_boost_permille: 1500, }, { model_name: "speech-hd", start_time: start, end_time: start + 24 * hour, current_interval_total_count: 4000, current_interval_usage_count: 4000, current_interval_remaining_percent: 100, current_interval_status: 1, ...week, current_weekly_total_count: 0, current_weekly_usage_count: 0, current_weekly_status: 3, }, { model_name: "image-01", start_time: start, end_time: start + 24 * hour, current_interval_total_count: 50, current_interval_usage_count: 10, current_interval_remaining_percent: 80, current_interval_status: 1, ...week, current_weekly_total_count: 0, current_weekly_usage_count: 0, current_weekly_status: 3, }, { model_name: "MiniMax-Hailuo-02", start_time: start, end_time: start + 24 * hour, current_interval_total_count: 0, current_interval_usage_count: 0, current_interval_status: 3, ...week, current_weekly_total_count: 0, current_weekly_usage_count: 0, current_weekly_status: 3, }, ], }); expect( quota.buckets.map(({ label, scope, period, value }) => ({ label, scope, durationMs: period?.durationMs, value, })), ).toEqual([ { label: "5h", scope: "MiniMax-M*", durationMs: 5 * hour, // 1200 of 1500 only matches 20% remaining when read as used. value: expect.objectContaining({ used: 1200, remaining: 300, total: 1500, usedPercent: 80, }), }, { label: "Weekly", scope: "MiniMax-M*", durationMs: 168 * hour, // Boosted 20% × 1.5 = 30% remaining; counts stay as reported. value: expect.objectContaining({ used: 12000, remaining: 3000, total: 15000, usedPercent: 70, }), }, { label: "1d", scope: "speech-hd", durationMs: 24 * hour, value: expect.objectContaining({ used: 0, remaining: 4000 }), }, { label: "Weekly", scope: "speech-hd", durationMs: 168 * hour, value: { state: "unlimited" }, }, { label: "1d", scope: "image-01", durationMs: 24 * hour, value: expect.objectContaining({ used: 10, remaining: 40 }), }, { label: "Weekly", scope: "image-01", durationMs: 168 * hour, value: { state: "unlimited" }, }, ]); }); it.each([ [ "agreeing counts read as remaining", 100, 25, 25, { used: 75, remaining: 25 }, ], ["agreeing counts read as used", 100, 25, 75, { used: 25, remaining: 75 }], ["tolerance of one point", 100, 26, 75, { used: 26, remaining: 74 }], ["mismatching counts", 100, 50, 20, undefined], ["counts beyond total", 100, 150, 20, undefined], ] as const)( "resolves MiniMax usage_count direction: %s", (_name, total, count, remaining, counts) => { const [bucket] = parseMinimax({ model_remains: [ { model_name: "general", current_interval_total_count: total, current_interval_usage_count: count, current_interval_remaining_percent: remaining, }, ], }).buckets; expect(bucket?.value).toEqual( counts ? { state: "measured", unit: "unknown", total, ...counts, unitLabel: undefined, usedPercent: 100 - remaining, } : { state: "measured", unit: "percent", used: 100 - remaining, remaining, total: 100, }, ); }, ); it.each([ [ "percent above 100", { pct: 80, permille: 1500 }, { used: 0, remaining: 120 }, ], [ "percent below 100", { pct: 40, permille: 1500 }, { used: 40, remaining: 60 }, ], ["no boost", { pct: 40, permille: 1000 }, { used: 60, remaining: 40 }], [ "non-positive boost ignored", { pct: 40, permille: 0 }, { used: 60, remaining: 40 }, ], ] as const)( "scales MiniMax weekly remaining percent by boost: %s", (_name, { pct, permille }, expected) => { const [weekly] = parseMinimax({ model_remains: [ { model_name: "general", current_weekly_total_count: 0, current_weekly_usage_count: 0, current_weekly_remaining_percent: pct, weekly_boost_permille: permille, }, ], }).buckets; expect(weekly?.value).toEqual({ state: "measured", unit: "percent", total: 100, ...expected, }); }, ); it("applies MiniMax boost to count-derived weekly percent but never to the interval", () => { const [interval, weekly] = parseMinimax({ model_remains: [ { model_name: "general", current_interval_remaining_percent: 40, current_weekly_total_count: 100, current_weekly_usage_count: 40, weekly_boost_permille: 2000, }, ], }).buckets; expect(interval?.value).toMatchObject({ used: 60, remaining: 40 }); expect(weekly?.value).toMatchObject({ used: 60, remaining: 40, total: 100, usedPercent: 20, }); }); it("keeps MiniMax pools with only one not-in-plan-shaped window and marks reported exhaustion", () => { const quota = parseMinimax({ model_remains: [ { model_name: "general", current_interval_total_count: 0, current_interval_status: 3, current_weekly_total_count: 0, current_weekly_status: 2, }, ], }); expect(quota.buckets.map((bucket) => bucket.value)).toEqual([ { state: "unlimited" }, { state: "measured", unit: "percent", used: 100, remaining: 0, total: 100, }, ]); }); it.each([ ["absent", {}, "5h", 18000000, "Weekly", 604800000], [ "inverted", { start_time: 2, end_time: 1, weekly_start_time: 2, weekly_end_time: 1 }, "5h", 18000000, "Weekly", 604800000, ], [ "off by under a minute", { start_time: 1000, end_time: 1000 + 18000000 - 999, weekly_start_time: 1000, weekly_end_time: 1000 + 604800000 + 999, }, "5h", 18000000, "Weekly", 604800000, ], [ "daily and fortnightly", { start_time: 1000, end_time: 1000 + 86400000, weekly_start_time: 1000, weekly_end_time: 1000 + 2 * 604800000, }, "1d", 86400000, "14d", 2 * 604800000, ], ] as const)( "labels MiniMax windows from %s bounds", (_name, bounds, intervalLabel, intervalMs, weeklyLabel, weeklyMs) => { const quota = parseMinimax({ model_remains: [ { model_name: "general", current_interval_remaining_percent: 50, current_weekly_remaining_percent: 50, ...bounds, }, ], }); expect( quota.buckets.map((bucket) => [ bucket.label, bucket.period?.durationMs, ]), ).toEqual([ [intervalLabel, intervalMs], [weeklyLabel, weeklyMs], ]); }, ); it("shows a MiniMax video interval only when its window is reported", () => { const video = { current_interval_remaining_percent: 50, current_weekly_remaining_percent: 50, }; const quota = parseMinimax({ model_remains: [ { model_name: "video-a", ...video }, { model_name: "video-b", start_time: 1000, end_time: 1000 + 86400000, ...video, }, ], }); expect( quota.buckets.map((bucket) => `${bucket.scope} ${bucket.label}`), ).toEqual(["video-a Weekly", "video-b 1d", "video-b Weekly"]); }); });