Skip to content
Merged
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
2 changes: 1 addition & 1 deletion desktop/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "opencodex-desktop"
version = "2.65.0-vadymhimself.23"
version = "2.65.0-vadymhimself.24"
description = "OpenCodex desktop shell"
authors = ["OpenCodex contributors"]
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenCodex",
"version": "2.65.0-vadymhimself.23",
"version": "2.65.0-vadymhimself.24",
"identifier": "com.opencodex.desktop",
"build": {
"frontendDist": "../ui",
Expand Down
5 changes: 5 additions & 0 deletions fixtures/external/kimi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Documented Kimi answers

Samples of what Kimi's `GET /coding/v1/usages` sends, taken from Kimi's own published client code, not captured from live traffic. A test that needs one of these loads it from here; it never hand-types a shorter or tidier copy.

- client-test-usages-full.json: the usages payload in the test "parses the full payload" of Kimi's own client, MoonshotAI/kimi-code, `packages/oauth/test/managed-usage.test.ts` (https://github.com/MoonshotAI/kimi-code/blob/main/packages/oauth/test/managed-usage.test.ts), read 2026-11-15. The fields are copied as written there and serialized as JSON, the way that test's own fetch mock serializes its body; the vendor's parser reading it is `packages/oauth/src/managed-usage.ts`. It is the vendor's documented shape, not a live capture: no live `/usages` body has been recorded. It holds no key, account or request id.
1 change: 1 addition & 0 deletions fixtures/external/kimi/client-test-usages-full.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"goods_version":2,"usages":{"limit_5h":{"used_ratio":0.3,"reset_time":"2026-09-11T18:00:00Z"},"limit_7d":{"used_ratio":0.2,"reset_time":"2026-09-17T00:00:00Z"},"limit_month_total":{"used_ratio":0.4,"reset_time":"2026-10-01T00:00:00Z"},"limit_month_code":{"used_ratio":0.25,"reset_time":"2026-10-01T00:00:00Z"}}}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bitkyc08/opencodex",
"version": "2.65.0-vadymhimself.23",
"version": "2.65.0-vadymhimself.24",
"description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code",
"type": "module",
"main": "./bin/package-main.mjs",
Expand Down
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": 3826,
"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
60 changes: 60 additions & 0 deletions tests/providers/provider-quota.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1971,6 +1971,66 @@ describe("fetchProviderQuotaReports", () => {
expect(seen).toEqual([]);
});

test("Kimi quota reads Kimi Code's documented usages shape: 5-hour, weekly and monthly pools", async () => {
await saveCredential("kimi", { access: "kimi-access-secret", refresh: "kimi-refresh-secret", expires: Date.now() + 3600_000 });
// Kimi's own client test payload (fixtures/external/kimi/README.md).
const usages = readFileSync(repoPath("fixtures/external/kimi/client-test-usages-full.json"), "utf8");
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(usages, { status: 200 });
}) as typeof fetch;

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

expect(result.reports[0]?.quota).toEqual({
fiveHourPercent: 30,
fiveHourResetAt: Date.parse("2026-09-11T18:00:00Z"),
weeklyPercent: 20,
weeklyResetAt: Date.parse("2026-09-17T00:00:00Z"),
monthlyPercent: 40,
monthlyResetAt: Date.parse("2026-10-01T00:00:00Z"),
updatedAt: expect.any(Number),
});
});

test("Kimi quota usages shape: when usages is present, legacy limits and totalQuota blocks are not read", async () => {
await saveCredential("kimi", { access: "kimi-access-secret", refresh: "kimi-refresh-secret", expires: Date.now() + 3600_000 });
// Edge input, not a provider sample: the documented usages plus legacy blocks that must be ignored.
const documented = JSON.parse(readFileSync(repoPath("fixtures/external/kimi/client-test-usages-full.json"), "utf8"));
globalThis.fetch = (async () => new Response(JSON.stringify({
...documented,
limits: [{ window: { duration: 300, timeUnit: "TIME_UNIT_MINUTE" }, detail: { limit: "100", remaining: "1" } }],
totalQuota: { limit: "100", remaining: "1" },
}), { status: 200 })) as typeof fetch;

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

expect(result.reports[0]?.quota?.fiveHourPercent).toBe(30);
expect(result.reports[0]?.quota?.monthlyPercent).toBe(40);
});

// Edge input, not a provider sample: ratio forms the parser must accept or skip.
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
Loading