Skip to content

Commit 16e9b75

Browse files
byongshintvcodex
andcommitted
fix(quota): reconcile A6API billing totals
Co-authored-by: OpenAI Codex <[email protected]>
1 parent 93d994f commit 16e9b75

7 files changed

Lines changed: 56 additions & 5 deletions

File tree

‎docs-site/src/content/docs/guides/providers.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ not shown as a quota reset because expiration does not imply that credit repleni
243243
}
244244
```
245245

246-
Quota probes send the active key only to the canonical A6API host and reject redirects. Malformed,
246+
Quota probes send only the active key to the canonical A6API host and reject redirects. Malformed,
247247
negative, or internally inconsistent billing totals produce no report rather than a misleading bar.
248248

249249
> **Tencent Cloud Coding Plan usage restriction:** Tencent documents this subscription for

‎docs-site/src/content/docs/ja/guides/providers.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,15 @@ opencodex v2.7.1 には組み込みプリセットが 50 個含まれていま
152152
大半は bearer キーと共に `openai-chat` アダプターを使い、Anthropic 互換エンドポイントのみを公開する一部
153153
(例: **Xiaomi MiMo**)は `anthropic` アダプター(`x-api-key`)を使います。
154154

155+
### A6API クレジットクォータ
156+
157+
`openai-chat`、`authMode: "key"`、正規の `https://api.a6api.com` または
158+
`https://api.a6api.com/v1` を使うカスタムプロバイダーでは、ダッシュボードと
159+
`ocx account refresh <provider>` に A6API クレジット使用量が表示されます。プロバイダー名は任意です。
160+
トークン単位を USD に換算し、使用率と残高を表示します。トークン期限は補充を意味しないため、クォータの
161+
リセットとしては表示しません。アクティブキーだけを正規ホストへ送信し、リダイレクトを拒否します。負数や
162+
整合しない請求合計からはレポートを生成しません。
163+
155164
> **Tencent Cloud Coding Plan の利用制限:** Tencent はこのサブスクリプションを対話型
156165
> コーディングツール専用としています。一般的な API 自動化、カスタムアプリのバックエンド、
157166
> 非対話型バッチ利用は禁止されており、プランキーが停止される場合があります。

‎docs-site/src/content/docs/ko/guides/providers.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,15 @@ opencodex v2.7.1에는 빌트인 프리셋이 50개 들어 있습니다. 키 방
152152
대부분은 bearer 키와 함께 `openai-chat` 어댑터를 사용하며, Anthropic 호환 엔드포인트만 노출하는 일부
153153
(예: **Xiaomi MiMo**)는 `anthropic` 어댑터(`x-api-key`)를 사용합니다.
154154

155+
### A6API 크레딧 쿼터
156+
157+
`openai-chat`, `authMode: "key"`, 공식 `https://api.a6api.com` 또는
158+
`https://api.a6api.com/v1` 주소를 사용하는 사용자 지정 프로바이더는 대시보드와
159+
`ocx account refresh <provider>`에서 A6API 크레딧 사용량을 표시합니다. 프로바이더 이름은 자유롭게 정할 수
160+
있습니다. 토큰 단위를 USD로 환산해 사용률과 남은 크레딧을 표시하며, 토큰 만료는 충전을 뜻하지 않으므로 쿼터
161+
리셋으로 표시하지 않습니다. 활성 키만 공식 호스트로 전송하고 리디렉션을 거부하며, 음수이거나 서로 일치하지
162+
않는 결제 합계에는 보고서를 만들지 않습니다.
163+
155164
> **Tencent Cloud Coding Plan 사용 제한:** Tencent는 이 구독을 대화형 코딩 도구 전용으로
156165
> 안내합니다. 일반 API 자동화, 사용자 애플리케이션 백엔드 및 비대화형 일괄 호출은 금지되며
157166
> 플랜 키가 정지될 수 있습니다.

‎docs-site/src/content/docs/ru/guides/providers.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,16 @@ opencodex поставляется с 53 встроенными пресетам
163163
только Anthropic-совместимую конечную точку (например, **Xiaomi MiMo**), используют адаптер
164164
`anthropic` (`x-api-key`).
165165

166+
### Квота кредитов A6API
167+
168+
Пользовательский провайдер с `openai-chat`, `authMode: "key"` и каноническим адресом
169+
`https://api.a6api.com` или `https://api.a6api.com/v1` показывает расход кредитов A6API в
170+
дашборде и в `ocx account refresh <provider>`. Имя провайдера может быть любым. Единицы токенов
171+
пересчитываются в USD; отображаются процент расхода и остаток. Срок действия токена не считается
172+
сбросом квоты, поскольку он не означает пополнение. Только активный ключ отправляется на
173+
канонический хост, перенаправления отклоняются, а отрицательные или несогласованные итоги биллинга
174+
не создают отчёт.
175+
166176
> **Ограничение Tencent Cloud Coding Plan:** Tencent разрешает использовать эту подписку только
167177
> в интерактивных инструментах программирования. Автоматизация общего API, серверы пользовательских
168178
> приложений и неинтерактивные пакетные вызовы запрещены и могут привести к блокировке ключа плана.

‎docs-site/src/content/docs/zh-cn/guides/providers.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,14 @@ ChatGPT 转发预设。仪表盘的 **Add provider** 选择器会打开密钥提
143143

144144
大多数使用带 bearer 密钥的 `openai-chat` adapter;少数仅暴露 Anthropic 兼容端点的提供商(例如 **Xiaomi MiMo**)使用 `anthropic` adapter(`x-api-key`)。
145145

146+
### A6API 信用额度
147+
148+
使用 `openai-chat`、`authMode: "key"` 以及规范地址 `https://api.a6api.com` 或
149+
`https://api.a6api.com/v1` 的自定义提供商,会在仪表板和 `ocx account refresh <provider>`
150+
中显示 A6API 信用使用情况;提供商名称可以自定义。系统将令牌单位换算为 USD,并显示已用百分比和剩余额度。
151+
令牌到期不代表额度补充,因此不会显示为配额重置。只有当前活动密钥会发送到规范主机,重定向会被拒绝;负数
152+
或内部不一致的计费总数不会生成报告。
153+
146154
> **腾讯云 Coding Plan 使用限制:**腾讯将此订阅限定为交互式编程工具使用。禁止通用 API
147155
> 自动化、自定义应用后端和非交互式批量调用;违规使用可能导致套餐密钥被停用。
148156

‎src/providers/quota.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,17 @@ async function fetchA6apiQuota(provider: string, config: OcxProviderConfig): Pro
166166
const grantedUnits = firstFinite(token, ["total_granted"]);
167167
const usedUnits = firstFinite(token, ["total_used"]);
168168
const availableUnits = firstFinite(token, ["total_available"]);
169+
const reconciledUnits = usedUnits !== undefined && availableUnits !== undefined
170+
? usedUnits + availableUnits
171+
: undefined;
172+
const reconciliationTolerance = grantedUnits !== undefined
173+
? Math.max(1, Math.abs(grantedUnits)) * 1e-9
174+
: 0;
169175
if (limitUsd === undefined || grantedUnits === undefined || usedUnits === undefined
170176
|| availableUnits === undefined || limitUsd <= 0 || grantedUnits <= 0
171177
|| usedUnits < 0 || availableUnits < 0
172-
|| usedUnits + availableUnits > grantedUnits) return null;
178+
|| reconciledUnits === undefined
179+
|| Math.abs(reconciledUnits - grantedUnits) > reconciliationTolerance) return null;
173180
const usdPerUnit = limitUsd / grantedUnits;
174181
const usedUsd = usedUnits * usdPerUnit;
175182
const remainingUsd = Math.max(0, availableUnits * usdPerUnit);

‎tests/provider-quota.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ describe("fetchProviderQuotaReports", () => {
309309
{ total_used: -1, total_available: 101 },
310310
{ total_used: 1, total_available: -1 },
311311
{ total_used: 80, total_available: 80 },
312+
{ total_used: 20, total_available: 70 },
312313
])("A6API quota drops malformed usage totals", async usage => {
313314
globalThis.fetch = (async (input: RequestInfo | URL) => {
314315
const url = String(input);
@@ -331,13 +332,20 @@ describe("fetchProviderQuotaReports", () => {
331332
: { data: { total_granted: 100, total_used: 25, total_available: 75 } }), { status: 200 });
332333
}) as typeof fetch;
333334

334-
const equivalent = await fetchProviderQuotaReports(a6apiOnlyConfig("https://API.A6API.COM:443/v1/"), true);
335+
const canonicalUrls = [
336+
"https://api.a6api.com",
337+
"https://api.a6api.com/v1",
338+
"https://API.A6API.COM:443/v1/",
339+
];
340+
for (const baseUrl of canonicalUrls) {
341+
const result = await fetchProviderQuotaReports(a6apiOnlyConfig(baseUrl), true);
342+
expect(result.reports).toHaveLength(1);
343+
}
335344
const credentialedUrl = "https://user" + "@api.a6api.com/v1";
336345
const credentialed = await fetchProviderQuotaReports(a6apiOnlyConfig(credentialedUrl), true);
337346

338-
expect(equivalent.reports).toHaveLength(1);
339347
expect(credentialed.reports).toEqual([]);
340-
expect(seen).toHaveLength(2);
348+
expect(seen).toHaveLength(canonicalUrls.length * 2);
341349
});
342350

343351
test("malformed API-key fields do not break unrelated quota reports", async () => {

0 commit comments

Comments
 (0)