Skip to content

Commit c299ed7

Browse files
byongshintvcodex
andcommitted
feat(quota): report A6API credit usage
Co-authored-by: OpenAI Codex <[email protected]>
1 parent c7e48fb commit c299ed7

2 files changed

Lines changed: 128 additions & 0 deletions

File tree

‎src/providers/quota.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const CACHE_TTL_MS = 5 * 60_000;
1515
const REQUEST_TIMEOUT_MS = 8_000;
1616
const KIMI_CODE_BASE_URL = "https://api.kimi.com/coding/v1";
1717
const KIMI_CODE_USAGE_URL = `${KIMI_CODE_BASE_URL}/usages`;
18+
const A6API_BASE_URL = "https://api.a6api.com";
1819
/** Keep a failed probe's previous row at most this long before dropping it. */
1920
const LAST_GOOD_MAX_AGE_MS = 30 * 60_000;
2021

@@ -118,6 +119,61 @@ function isBuiltInChatGptForwardProvider(name: string, provider: OcxProviderConf
118119
return name === OPENAI_CODEX_PROVIDER_ID && isCanonicalOpenAiForwardProvider(provider);
119120
}
120121

122+
function isCanonicalA6apiBaseUrl(baseUrl: string): boolean {
123+
const normalized = baseUrl.trim().replace(/\/+$/, "");
124+
return normalized === A6API_BASE_URL || normalized === `${A6API_BASE_URL}/v1`;
125+
}
126+
127+
function a6apiPayload(value: unknown): Record<string, unknown> | null {
128+
const body = asRecord(value);
129+
return asRecord(body?.data) ?? body;
130+
}
131+
132+
function firstFinite(record: Record<string, unknown> | null, names: string[]): number | undefined {
133+
if (!record) return undefined;
134+
for (const name of names) {
135+
const value = toFiniteNumber(record[name]);
136+
if (value !== undefined) return value;
137+
}
138+
return undefined;
139+
}
140+
141+
async function fetchA6apiQuota(provider: string, config: OcxProviderConfig): Promise<ProviderQuotaReport | null> {
142+
// Never send a configured API key to a lookalike host or through a redirect.
143+
if (!isCanonicalA6apiBaseUrl(config.baseUrl)) return null;
144+
const apiKey = resolveEnvValue(config.apiKey)?.trim();
145+
if (!apiKey) return null;
146+
const headers = { Accept: "application/json", Authorization: `Bearer ${apiKey}` } as const;
147+
const [subscriptionResponse, tokenResponse] = await Promise.all([
148+
fetch(`${A6API_BASE_URL}/dashboard/billing/subscription`, {
149+
headers, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
150+
}),
151+
fetch(`${A6API_BASE_URL}/api/usage/token/`, {
152+
headers, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
153+
}),
154+
]);
155+
if (!subscriptionResponse.ok || !tokenResponse.ok) return null;
156+
const subscription = a6apiPayload(await subscriptionResponse.json().catch(() => null));
157+
const token = a6apiPayload(await tokenResponse.json().catch(() => null));
158+
const limitUsd = firstFinite(subscription, ["hard_limit_usd"]);
159+
const grantedUnits = firstFinite(token, ["total_granted"]);
160+
const usedUnits = firstFinite(token, ["total_used"]);
161+
const availableUnits = firstFinite(token, ["total_available"]);
162+
if (limitUsd === undefined || grantedUnits === undefined || usedUnits === undefined
163+
|| availableUnits === undefined || limitUsd <= 0 || grantedUnits <= 0) return null;
164+
const usdPerUnit = limitUsd / grantedUnits;
165+
const usedUsd = usedUnits * usdPerUnit;
166+
const remainingUsd = Math.max(0, availableUnits * usdPerUnit);
167+
const percent = normalizePercent((usedUsd / limitUsd) * 100);
168+
if (percent === undefined) return null;
169+
const resetAt = normalizeResetAt(token?.expires_at);
170+
const label = `API credits ($${remainingUsd.toFixed(2)} of $${limitUsd.toFixed(2)} remaining)`;
171+
return report(provider, "a6api:billing", {
172+
customWindows: [{ label, percent, ...(resetAt !== undefined ? { resetAt } : {}) }],
173+
updatedAt: Date.now(),
174+
});
175+
}
176+
121177
function report(provider: string, source: string, quota: ProviderQuota): ProviderQuotaReport | null {
122178
if (!hasQuotaRows(quota)) return null;
123179
return {
@@ -853,6 +909,9 @@ async function maybeFetchProviderQuota(
853909
if (provider.authMode === "key" && isCanonicalKimiCodeBaseUrl(provider.baseUrl)) {
854910
return fetchKimiQuota(name, provider);
855911
}
912+
if ((provider.authMode ?? "key") === "key" && name === "a6api") {
913+
return fetchA6apiQuota(name, provider);
914+
}
856915
return null;
857916
} catch {
858917
return null;

‎tests/provider-quota.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,75 @@ describe("fetchProviderQuotaReports", () => {
237237
} as OcxConfig;
238238
}
239239

240+
function a6apiOnlyConfig(baseUrl = "https://api.a6api.com/v1"): OcxConfig {
241+
return {
242+
defaultProvider: "a6api",
243+
providers: {
244+
a6api: { adapter: "openai-chat", authMode: "key", baseUrl, apiKey: "a6api-secret" },
245+
},
246+
} as OcxConfig;
247+
}
248+
249+
test("A6API quota converts provider units to USD and exposes a displayable credit window", async () => {
250+
const seen: Array<{ url: string; authorization?: string; redirect?: RequestRedirect }> = [];
251+
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
252+
const url = String(input);
253+
const headers = init?.headers as Record<string, string> | undefined;
254+
seen.push({ url, authorization: headers?.Authorization, redirect: init?.redirect });
255+
if (url.endsWith("/dashboard/billing/subscription")) {
256+
return new Response(JSON.stringify({ data: { hard_limit_usd: "20" } }), { status: 200 });
257+
}
258+
return new Response(JSON.stringify({ data: {
259+
total_granted: "20000000",
260+
total_used: "5000000",
261+
total_available: "15000000",
262+
expires_at: "2026-08-01T00:00:00Z",
263+
} }), { status: 200 });
264+
}) as typeof fetch;
265+
266+
const result = await fetchProviderQuotaReports(a6apiOnlyConfig(), true);
267+
268+
expect(result.reports).toHaveLength(1);
269+
expect(result.reports[0]?.source).toBe("a6api:billing");
270+
expect(result.reports[0]?.quota.customWindows).toEqual([{
271+
label: "API credits ($15.00 of $20.00 remaining)",
272+
percent: 25,
273+
resetAt: Date.parse("2026-08-01T00:00:00Z"),
274+
}]);
275+
expect(seen.map(row => row.url).sort()).toEqual([
276+
"https://api.a6api.com/api/usage/token/",
277+
"https://api.a6api.com/dashboard/billing/subscription",
278+
]);
279+
expect(seen.every(row => row.authorization === "Bearer a6api-secret")).toBe(true);
280+
expect(seen.every(row => row.redirect === "error")).toBe(true);
281+
});
282+
283+
test("A6API quota never sends API keys to a non-canonical base URL", async () => {
284+
const seen: string[] = [];
285+
globalThis.fetch = (async (input: RequestInfo | URL) => {
286+
seen.push(String(input));
287+
return new Response("unexpected", { status: 500 });
288+
}) as typeof fetch;
289+
290+
const result = await fetchProviderQuotaReports(a6apiOnlyConfig("https://attacker.example/v1"), true);
291+
292+
expect(result.reports).toEqual([]);
293+
expect(seen).toEqual([]);
294+
});
295+
296+
test("A6API quota drops incomplete or zero-limit billing payloads", async () => {
297+
globalThis.fetch = (async (input: RequestInfo | URL) => {
298+
const url = String(input);
299+
return new Response(JSON.stringify(url.includes("subscription")
300+
? { data: { hard_limit_usd: 0 } }
301+
: { data: { total_granted: 100, total_used: 20, total_available: 80 } }), { status: 200 });
302+
}) as typeof fetch;
303+
304+
const result = await fetchProviderQuotaReports(a6apiOnlyConfig(), true);
305+
306+
expect(result.reports).toEqual([]);
307+
});
308+
240309
test("Kimi quota never sends OAuth credentials to a non-canonical base URL", async () => {
241310
await saveCredential("kimi", { access: "kimi-access-secret", refresh: "kimi-refresh-secret", expires: Date.now() + 3600_000 });
242311
const seen: string[] = [];

0 commit comments

Comments
 (0)