Skip to content

Commit 2903177

Browse files
byongshintvcodex
andcommitted
fix(quota): address A6API review findings
Co-authored-by: OpenAI Codex <[email protected]>
1 parent c299ed7 commit 2903177

2 files changed

Lines changed: 63 additions & 6 deletions

File tree

‎src/providers/quota.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { resolveEnvValue } from "../config";
44
import { getValidAccessToken, getValidAccessTokenForAccount } from "../oauth";
55
import { getAccountCredential, getAccountSet, getCredential } from "../oauth/store";
66
import { antigravityUserAgent } from "../adapters/client-fingerprint";
7+
import { apiKeyPoolEntryId } from "./api-keys";
78
import { getProviderRegistryEntry, providerCodexAccountMode } from "./registry";
89
import type { OcxConfig, OcxProviderConfig } from "../types";
910
import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "./openai-tiers";
@@ -63,7 +64,11 @@ export function clearProviderQuotaCache(): void {
6364

6465
function cacheKey(config: OcxConfig): string {
6566
const providers = Object.entries(config.providers)
66-
.map(([name, provider]) => `${name}:${provider.adapter}:${provider.authMode ?? "key"}:${providerCodexAccountMode(name, provider) ?? "none"}:${provider.disabled === true ? "off" : "on"}:${provider.baseUrl}`)
67+
.map(([name, provider]) => {
68+
const resolvedKey = resolveEnvValue(provider.apiKey)?.trim();
69+
const activeKeyId = resolvedKey ? apiKeyPoolEntryId(resolvedKey) : "none";
70+
return `${name}:${provider.adapter}:${provider.authMode ?? "key"}:${providerCodexAccountMode(name, provider) ?? "none"}:${provider.disabled === true ? "off" : "on"}:${provider.baseUrl}:${activeKeyId}`;
71+
})
6772
.sort()
6873
.join("|");
6974
return `${config.defaultProvider}|${config.activeCodexAccountId ?? ""}|${providers}`;
@@ -160,16 +165,16 @@ async function fetchA6apiQuota(provider: string, config: OcxProviderConfig): Pro
160165
const usedUnits = firstFinite(token, ["total_used"]);
161166
const availableUnits = firstFinite(token, ["total_available"]);
162167
if (limitUsd === undefined || grantedUnits === undefined || usedUnits === undefined
163-
|| availableUnits === undefined || limitUsd <= 0 || grantedUnits <= 0) return null;
168+
|| availableUnits === undefined || limitUsd <= 0 || grantedUnits <= 0
169+
|| usedUnits < 0 || availableUnits < 0) return null;
164170
const usdPerUnit = limitUsd / grantedUnits;
165171
const usedUsd = usedUnits * usdPerUnit;
166172
const remainingUsd = Math.max(0, availableUnits * usdPerUnit);
167173
const percent = normalizePercent((usedUsd / limitUsd) * 100);
168174
if (percent === undefined) return null;
169-
const resetAt = normalizeResetAt(token?.expires_at);
170175
const label = `API credits ($${remainingUsd.toFixed(2)} of $${limitUsd.toFixed(2)} remaining)`;
171176
return report(provider, "a6api:billing", {
172-
customWindows: [{ label, percent, ...(resetAt !== undefined ? { resetAt } : {}) }],
177+
customWindows: [{ label, percent }],
173178
updatedAt: Date.now(),
174179
});
175180
}
@@ -909,7 +914,7 @@ async function maybeFetchProviderQuota(
909914
if (provider.authMode === "key" && isCanonicalKimiCodeBaseUrl(provider.baseUrl)) {
910915
return fetchKimiQuota(name, provider);
911916
}
912-
if ((provider.authMode ?? "key") === "key" && name === "a6api") {
917+
if ((provider.authMode ?? "key") === "key" && isCanonicalA6apiBaseUrl(provider.baseUrl)) {
913918
return fetchA6apiQuota(name, provider);
914919
}
915920
return null;

‎tests/provider-quota.test.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,6 @@ describe("fetchProviderQuotaReports", () => {
270270
expect(result.reports[0]?.quota.customWindows).toEqual([{
271271
label: "API credits ($15.00 of $20.00 remaining)",
272272
percent: 25,
273-
resetAt: Date.parse("2026-08-01T00:00:00Z"),
274273
}]);
275274
expect(seen.map(row => row.url).sort()).toEqual([
276275
"https://api.a6api.com/api/usage/token/",
@@ -306,6 +305,59 @@ describe("fetchProviderQuotaReports", () => {
306305
expect(result.reports).toEqual([]);
307306
});
308307

308+
test.each([
309+
{ total_used: -1, total_available: 101 },
310+
{ total_used: 1, total_available: -1 },
311+
])("A6API quota drops negative usage totals", async usage => {
312+
globalThis.fetch = (async (input: RequestInfo | URL) => {
313+
const url = String(input);
314+
return new Response(JSON.stringify(url.includes("subscription")
315+
? { data: { hard_limit_usd: 10 } }
316+
: { data: { total_granted: 100, ...usage } }), { status: 200 });
317+
}) as typeof fetch;
318+
319+
const result = await fetchProviderQuotaReports(a6apiOnlyConfig(), true);
320+
321+
expect(result.reports).toEqual([]);
322+
});
323+
324+
test("A6API quota is detected by canonical base URL for custom provider names", async () => {
325+
globalThis.fetch = (async (input: RequestInfo | URL) => new Response(JSON.stringify(
326+
String(input).includes("subscription")
327+
? { data: { hard_limit_usd: 10 } }
328+
: { data: { total_granted: 100, total_used: 25, total_available: 75 } },
329+
), { status: 200 })) as typeof fetch;
330+
const config = a6apiOnlyConfig();
331+
config.defaultProvider = "my-a6";
332+
config.providers = { "my-a6": config.providers.a6api! };
333+
334+
const result = await fetchProviderQuotaReports(config, true);
335+
336+
expect(result.reports[0]?.provider).toBe("my-a6");
337+
expect(result.reports[0]?.quota.customWindows?.[0]?.percent).toBe(25);
338+
});
339+
340+
test("A6API quota cache follows the active API key", async () => {
341+
const authorizations: string[] = [];
342+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
343+
const headers = init?.headers as Record<string, string> | undefined;
344+
authorizations.push(headers?.Authorization ?? "");
345+
const secondAccount = headers?.Authorization === "Bearer second-account-key";
346+
return new Response(JSON.stringify(String(input).includes("subscription")
347+
? { data: { hard_limit_usd: secondAccount ? 30 : 10 } }
348+
: { data: { total_granted: 100, total_used: 20, total_available: 80 } }), { status: 200 });
349+
}) as typeof fetch;
350+
const config = a6apiOnlyConfig();
351+
352+
const first = await fetchProviderQuotaReports(config);
353+
config.providers.a6api!.apiKey = "second-account-key";
354+
const second = await fetchProviderQuotaReports(config);
355+
356+
expect(first.reports[0]?.quota.customWindows?.[0]?.label).toContain("of $10.00 remaining");
357+
expect(second.reports[0]?.quota.customWindows?.[0]?.label).toContain("of $30.00 remaining");
358+
expect(authorizations).toContain("Bearer second-account-key");
359+
});
360+
309361
test("Kimi quota never sends OAuth credentials to a non-canonical base URL", async () => {
310362
await saveCredential("kimi", { access: "kimi-access-secret", refresh: "kimi-refresh-secret", expires: Date.now() + 3600_000 });
311363
const seen: string[] = [];

0 commit comments

Comments
 (0)