Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions src/providers/quota/vendor-probes-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -962,8 +962,8 @@ function unwrapKimiQuotaPayload(value: unknown): Record<string, unknown> | null
// A null/non-usable outer field is a placeholder, not data — an envelope like
// { usage: null, data: { usage: {...} } } must still unwrap to the nested payload.
const usable = (field: unknown): boolean => field !== undefined && field !== null;
const outerHasUsage = usable(body.usage) || usable(body.limits) || usable(body.totalQuota);
const nestedHasUsage = usable(nested.usage) || usable(nested.limits) || usable(nested.totalQuota);
const outerHasUsage = usable(body.usage) || usable(body.usages) || usable(body.limits) || usable(body.totalQuota);
const nestedHasUsage = usable(nested.usage) || usable(nested.usages) || usable(nested.limits) || usable(nested.totalQuota);
return !outerHasUsage && nestedHasUsage ? nested : body;
}

Expand Down Expand Up @@ -1009,13 +1009,29 @@ function isKimiWeeklyLimit(item: Record<string, unknown>, detail: Record<string,
return /weekly|7\s*(?:d|day)/.test(kimiLimitLabel(item, detail));
}

/**
* Kimi Code's own client reads `usages.{limit_5h,limit_7d,limit_month_total}`, each `{used_ratio, reset_time}` with the
* ratio 0..1 (MoonshotAI/kimi-code packages/oauth/src/managed-usage.ts). Plans that return it may still carry the legacy
* `limits[]` block as an unused placeholder (limit 100, remaining 100 = 0%), so when `usages` exists only it is read.
*/
function parseKimiUsageRatio(value: unknown): { percent: number; resetAt?: number } | null {
const row = asRecord(value);
const ratio = toFiniteNumber(row?.used_ratio);
if (!row || ratio === undefined) return null;
const resetAt = quotaResetAt(row);
return { percent: normalizePercent(Math.round(ratio * 10_000) / 100)!, ...(resetAt !== undefined ? { resetAt } : {}) };
}

function parseKimiQuotaPayload(value: unknown): ProviderQuota | null {
const body = unwrapKimiQuotaPayload(value);
if (!body) return null;
let weekly = parseKimiQuotaRow(body.usage);
const total = parseKimiQuotaRow(body.totalQuota);
let fiveHour: { percent: number; resetAt?: number } | null = null;
if (Array.isArray(body.limits)) {
const usages = asRecord(body.usages);
const monthly = parseKimiUsageRatio(usages?.limit_month_total);
// With `usages` present the legacy blocks are not read at all: they can be placeholders (see above).
let weekly = usages ? parseKimiUsageRatio(usages.limit_7d) : parseKimiQuotaRow(body.usage);
const total = usages ? null : parseKimiQuotaRow(body.totalQuota);
let fiveHour: { percent: number; resetAt?: number } | null = parseKimiUsageRatio(usages?.limit_5h);
if (!usages && Array.isArray(body.limits)) {
for (const rawItem of body.limits) {
const item = asRecord(rawItem);
if (!item) continue;
Expand All @@ -1039,6 +1055,10 @@ function parseKimiQuotaPayload(value: unknown): ProviderQuota | null {
weeklyPercent: weekly.percent,
...(weekly.resetAt !== undefined ? { weeklyResetAt: weekly.resetAt } : {}),
} : {}),
...(monthly ? {
monthlyPercent: monthly.percent,
...(monthly.resetAt !== undefined ? { monthlyResetAt: monthly.resetAt } : {}),
} : {}),
...(total ? { customWindows: [{ label: "Total subscription credits", percent: total.percent, ...(total.resetAt !== undefined ? { resetAt: total.resetAt } : {}) }] } : {}),
updatedAt: Date.now(),
};
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/file-size-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"tests/providers/cursor/cursor-blob.test.ts": 3657,
"tests/providers/kiro/kiro-adapter.test.ts": 2050,
"tests/providers/kiro/kiro-stream.test.ts": 2258,
"tests/providers/provider-quota.test.ts": 3766,
"tests/providers/provider-quota.test.ts": 3813,
"tests/responses/chat-completions-endpoint.test.ts": 3729,
"tests/responses/openai-responses-passthrough.test.ts": 4852,
"tests/responses/responses-compaction-routing.test.ts": 2772,
Expand Down
47 changes: 47 additions & 0 deletions tests/providers/provider-quota.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1971,6 +1971,53 @@
expect(seen).toEqual([]);
});

test("Kimi quota reads the Kimi Code usages shape: 0..1 ratios, monthly pool, legacy placeholder ignored", async () => {
await saveCredential("kimi", { access: "kimi-access-secret", refresh: "kimi-refresh-secret", expires: Date.now() + 3600_000 });
globalThis.fetch = (async (input: RequestInfo | URL) => {
if (String(input) !== "https://api.kimi.com/coding/v1/usages") return new Response("not found", { status: 404 });
return new Response(JSON.stringify({
usages: {
limit_5h: { used_ratio: 0.15, reset_time: "2026-11-06T07:46:00.000Z" },
limit_month_total: { used_ratio: "0.0082", reset_time: "2026-12-06T03:22:00Z" },
limit_month_code: { used_ratio: 0.5, reset_time: "2026-12-06T03:22:00Z" },
},
limits: [{ window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" }, detail: { limit: "100", remaining: "100" } }],
totalQuota: { limit: "100", remaining: "99" },
}), { status: 200 });
}) as typeof fetch;

const result = await fetchProviderQuotaReports(kimiOnlyConfig(), true);

expect(result.reports[0]?.quota).toEqual({
fiveHourPercent: 15,
fiveHourResetAt: Date.parse("2026-11-06T07:46:00.000Z"),
monthlyPercent: 0.82,
monthlyResetAt: Date.parse("2026-12-06T03:22:00Z"),
updatedAt: expect.any(Number),
});
});

test("Kimi quota usages shape: a 0 ratio is 0%, limit_7d is weekly, a missing ratio is skipped", async () => {
await saveCredential("kimi", { access: "kimi-access-secret", refresh: "kimi-refresh-secret", expires: Date.now() + 3600_000 });
globalThis.fetch = (async () => new Response(JSON.stringify({
usages: {
limit_5h: { used_ratio: 0, reset_time: "2026-11-06T07:46:00Z" },
limit_7d: { used_ratio: "0.5", reset_time: "2026-11-10T00:00:00Z" },
limit_month_total: { reset_time: "2026-12-06T03:22:00Z" },
},
}), { status: 200 })) as typeof fetch;

const result = await fetchProviderQuotaReports(kimiOnlyConfig(), true);

expect(result.reports[0]?.quota).toEqual({
fiveHourPercent: 0,
fiveHourResetAt: Date.parse("2026-11-06T07:46:00Z"),
weeklyPercent: 50,
weeklyResetAt: Date.parse("2026-11-10T00:00:00Z"),
updatedAt: expect.any(Number),
});
});

test("Kimi quota refreshes an expired OAuth token before calling usages", async () => {
await saveCredential("kimi", { access: "expired-kimi-access", refresh: "kimi-refresh-secret", expires: Date.now() - 1 });
const seen: Array<{ url: string; authorization?: string }> = [];
Expand Down Expand Up @@ -2397,7 +2444,7 @@
globalThis.fetch = (async () => new Response("unavailable", { status: 500 })) as typeof fetch;
const expired = await fetchProviderQuotaReports(config);
const openai = expired.reports.find(row => row.provider === "openai");
expect(openai?.aggregation).toMatchObject({

Check failure on line 2447 in tests/providers/provider-quota.test.ts

View workflow job for this annotation

GitHub Actions / test 1/4

error: expect(received).toMatchObject(expected)

{ "currentAccount": { + "isMain": false, "plan": "prolite", "quota": null, }, + "excludedAccounts": 2, "includedAccounts": 0, "incomplete": true, + "kind": "capacity-weighted-v1", "missingQuotaAccounts": 1, + "partialWindowAccounts": 0, + "pausedAccounts": 0, "presentation": "coverage-only", + "reauthAccounts": 0, + "scope": "routable-known", "staleQuotaAccounts": 1, - "unknownPlanAccounts": 1, + "unknownPlanAccounts": 0, } - Expected - 1 + Received + 8 at <anonymous> (/home/runner/work/opencodex/opencodex/tests/providers/provider-quota.test.ts:2447:35)
presentation: "coverage-only",
includedAccounts: 0,
staleQuotaAccounts: 1,
Expand Down
Loading