Skip to content
TypeScript

fix(usage): read and redeem hub reset credits through CLIProxyAPI (#10395)

Julius Marminge0a89364f153f
diff --git a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx
index bcd76722c8e..31d3a0e3f27 100644
--- a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx
+++ b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx
@@ -42,6 +42,9 @@ export function ComposerUsageLimits({
style={{ maxHeight: Math.round(height * 0.4) }}
>
{report.accounts.map((account, index) => {
+ const resetCreditInput =
+ account.resetCreditInput ??
+ (account.instanceId ? { instanceId: account.instanceId } : undefined);
const driverLabel = DRIVER_LABEL[account.driver] ?? String(account.driver);
return (
<AccountLimits
@@ -65,11 +68,11 @@ export function ComposerUsageLimits({
now={now}
trailing={index === 0 ? close : undefined}
footer={
- account.instanceId && account.limits.resetCredits ? (
+ resetCreditInput && account.limits.resetCredits ? (
<ResetCredits
dense
environmentId={environmentId}
- instanceId={account.instanceId}
+ input={resetCreditInput}
credits={account.limits.resetCredits}
now={now}
/>
diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx
index 61828ad90ee..dd62f4952d1 100644
--- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx
+++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx
@@ -140,7 +140,7 @@ function PoolWindowCard({
</View>
<View>
{pool.members.map(({ account, window }, index) => {
- const credits = account.redeem ? (account.limits.resetCredits?.availableCount ?? 0) : 0;
+ const credits = account.limits.resetCredits?.availableCount ?? 0;
const resetsIn = formatResetsIn(window, now);
return (
<Pressable
@@ -358,9 +358,9 @@ export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
<View className="gap-3 rounded-[24px] border-continuous bg-card p-4">
<Text className="text-sm font-t3-medium text-foreground">Reset credits</Text>
<ResetCredits
- key={`${account.redeem.environmentId}:${account.redeem.instanceId}`}
+ key={account.key}
environmentId={account.redeem.environmentId}
- instanceId={account.redeem.instanceId}
+ input={account.redeem.input}
credits={account.limits.resetCredits}
now={now}
/>
diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsx
index a923e903ef1..5b0e673505f 100644
--- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx
+++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx
@@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import type {
EnvironmentId,
ProviderConsumeResetCreditOutcome,
- ProviderInstanceId,
+ ProviderConsumeResetCreditInput,
ServerProvider,
ServerProviderResetCredits,
ServerProviderUsageWindow,
@@ -168,13 +168,13 @@ const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
*/
export function ResetCredits(props: {
readonly environmentId: EnvironmentId;
- readonly instanceId: ProviderInstanceId;
+ readonly input: ProviderConsumeResetCreditInput;
readonly credits: ServerProviderResetCredits;
readonly now: number;
/** A smaller pill for the composer card. */
readonly dense?: boolean;
}) {
- const { environmentId, instanceId, credits, now, dense = false } = props;
+ const { environmentId, input, credits, now, dense = false } = props;
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, {
reportFailure: false,
});
@@ -195,10 +195,10 @@ export function ResetCredits(props: {
const redeem = async () => {
setBusy(true);
setStatus(null);
- const result = await consume({ environmentId, input: { instanceId } });
+ const result = await consume({ environmentId, input });
setBusy(false);
if (result._tag === "Success") {
- setStatus(OUTCOME_TEXT[result.value.outcome]);
+ setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
return;
}
setStatus(
diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts
index abe7f8e6499..a63651f93c2 100644
--- a/apps/server/src/usage/UsageLimitSources.ts
+++ b/apps/server/src/usage/UsageLimitSources.ts
@@ -13,15 +13,16 @@
*/
import {
DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,
+ UsageLimitSourceError,
+ type UsageLimitSourceConsumeResetCreditInput,
+ type ProviderConsumeResetCreditResult,
type ServerSettings,
type UsageLimitSourceConfig,
type UsageLimitSourceId,
type UsageLimitSourceSnapshot,
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
-import type * as Cause from "effect/Cause";
import * as Context from "effect/Context";
-import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -30,16 +31,11 @@ import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Semaphore from "effect/Semaphore";
-import type * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
-import { HttpClient, type HttpClientError, HttpClientResponse } from "effect/unstable/http";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import { ServerSettingsService } from "../serverSettings.ts";
-import { cliproxyStatusToAccounts, decodeCliproxyQuotaStatus } from "./cliproxyUsageLimits.ts";
-
-const FETCH_TIMEOUT = "10 seconds";
-const QUOTA_STATUS_PATH = "/v0/management/quota-scheduler/status";
+import { makeCliproxyApi } from "./cliproxyApi.ts";
export class UsageLimitSources extends Context.Service<
UsageLimitSources,
@@ -49,35 +45,12 @@ export class UsageLimitSources extends Context.Service<
readonly streamChanges: Stream.Stream<ReadonlyArray<UsageLimitSourceSnapshot>>;
/** Re-read every source now. Never fails; failures land on the snapshot. */
readonly refresh: Effect.Effect<void>;
+ readonly consumeResetCredit: (
+ input: UsageLimitSourceConsumeResetCreditInput,
+ ) => Effect.Effect<ProviderConsumeResetCreditResult, UsageLimitSourceError>;
}
>()("t3/usage/UsageLimitSources") {}
-/**
- * A bounded, client-safe reason for a failed hub read. The exact failure
- * (which can carry the request URL and response body) goes to the log.
- */
-function readFailureMessage(
- error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError | InvalidUrl,
-): string {
- switch (error._tag) {
- case "InvalidUrl":
- return "The hub URL is not valid.";
- case "TimeoutError":
- return "The hub did not answer in time.";
- case "SchemaError":
- return "The hub answered with an unexpected shape.";
- case "HttpClientError":
- return error.reason._tag === "StatusCodeError"
- ? `The hub refused the request (HTTP ${error.reason.response.status}).`
- : "The hub could not be reached.";
- }
-}
-
-class InvalidUrl extends Data.TaggedError("InvalidUrl")<{
- readonly url: string;
- readonly cause: unknown;
-}> {}
-
function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
if (config.label) return config.label;
try {
@@ -88,7 +61,7 @@ function sourceLabel(id: string, config: UsageLimitSourceConfig): string {
}
export const make = Effect.gen(function* () {
- const httpClient = yield* HttpClient.HttpClient;
+ const api = yield* makeCliproxyApi;
const settingsService = yield* ServerSettingsService;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const stateRef = yield* Ref.make<ReadonlyArray<UsageLimitSourceSnapshot>>([]);
@@ -106,23 +79,10 @@ export const make = Effect.gen(function* () {
if (config.managementKey.length === 0) {
return { ...base, accounts: [], error: "No management key configured." };
}
- const accounts = yield* Effect.try({
- try: () => new URL(QUOTA_STATUS_PATH, config.url).toString(),
- catch: (cause) => new InvalidUrl({ url: config.url, cause }),
- }).pipe(
- Effect.flatMap((url) =>
- httpClient.get(url, { headers: { Authorization: `Bearer ${config.managementKey}` } }),
- ),
- Effect.flatMap(HttpClientResponse.filterStatusOk),
- Effect.flatMap((response) => response.json),
- Effect.flatMap(decodeCliproxyQuotaStatus),
- Effect.map((status) => cliproxyStatusToAccounts(status, checkedAt)),
- Effect.timeout(FETCH_TIMEOUT),
- Effect.result,
- );
+ const accounts = yield* api.readAccounts(config).pipe(Effect.result);
if (accounts._tag === "Failure") {
yield* Effect.logDebug("usage limit source read failed", { id, cause: accounts.failure });
- return { ...base, accounts: [], error: readFailureMessage(accounts.failure) };
+ return { ...base, accounts: [], error: accounts.failure.detail };
}
return { ...base, accounts: accounts.success };
});
@@ -154,6 +114,27 @@ export const make = Effect.gen(function* () {
yield* publish(snapshots);
}).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true }));
+ // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption.
+ const consumeResetCredit = (input: UsageLimitSourceConsumeResetCreditInput) =>
+ Effect.gen(function* () {
+ const settings = yield* settingsService.getSettings.pipe(
+ Effect.mapError(
+ () => new UsageLimitSourceError({ detail: "Could not read hub settings." }),
+ ),
+ );
+ const config = settings.usageLimitSources[input.sourceId];
+ if (!config?.enabled || !config.managementKey) {
+ return yield* new UsageLimitSourceError({
+ detail: "The usage limit source is missing or disabled.",
+ });
+ }
+ const result = yield* api.consume(config, input.accountId, input.creditId);
+ const snapshot = yield* readSource(input.sourceId, config);
+ const previous = yield* Ref.get(stateRef);
+ yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source)));
+ return result;
+ }).pipe(refreshLock.withPermits(1));
+
// Settings edits re-read straight away so a new hub shows up without
// waiting for the interval, and a removed one leaves the list.
yield* settingsService.streamChanges.pipe(
@@ -184,6 +165,7 @@ export const make = Effect.gen(function* () {
return {
current: Ref.get(stateRef),
+ consumeResetCredit,
refresh,
get streamChanges() {
return Stream.unwrap(
diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts
new file mode 100644
index 00000000000..b0fee363828
--- /dev/null
+++ b/apps/server/src/usage/cliproxyApi.test.ts
@@ -0,0 +1,310 @@
+import { describe, expect, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as TestClock from "effect/testing/TestClock";
+import { HttpClient, HttpClientResponse } from "effect/unstable/http";
+
+import { creditRedeemRequestId, makeCliproxyApi } from "./cliproxyApi.ts";
+
+const config = {
+ kind: "cliproxy",
+ url: "http://hub.test:8317",
+ managementKey: "management-secret",
+ enabled: true,
+} as const;
+const accounts = [
+ {
+ id: "first.json",
+ auth_index: "a",
+ provider: "codex",
+ email: "[email protected]",
+ id_token: { chatgpt_account_id: "account-a" },
+ },
+ {
+ id: "second.json",
+ auth_index: "b",
+ provider: "codex",
+ email: "[email protected]",
+ id_token: { chatgpt_account_id: "account-b" },
+ },
+];
+const credit = (id: string, expires_at = "2099-01-01T00:00:00Z") => ({
+ id,
+ expires_at,
+ status: "available",
+ reset_type: "codex_rate_limits",
+});
+const RequestBody = Schema.Struct({
+ auth_index: Schema.String,
+ method: Schema.optional(Schema.String),
+ url: Schema.optional(Schema.String),
+ header: Schema.optional(Schema.Record(Schema.String, Schema.String)),
+ data: Schema.optional(Schema.String),
+});
+type RequestBody = typeof RequestBody.Type;
+const decodeRequest = Schema.decodeUnknownSync(Schema.fromJsonString(RequestBody));
+const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+
+function fixture(
+ options: {
+ accounts?: Array<(typeof accounts)[number] & { disabled?: boolean }>;
+ upstream?: (request: RequestBody) => { status: number; body: unknown };
+ cooldownStatus?: number;
+ } = {},
+) {
+ const requests: Array<{ path: string; body?: RequestBody }> = [];
+ const http = HttpClient.make((request) =>
+ Effect.sync(() => {
+ expect(request.headers.authorization).toBe("Bearer management-secret");
+ const path = new URL(request.url).pathname;
+ const body =
+ request.body._tag === "Uint8Array"
+ ? decodeRequest(new TextDecoder().decode(request.body.body))
+ : undefined;
+ requests.push({ path, ...(body ? { body } : {}) });
+ if (path.endsWith("/auth-files"))
+ return HttpClientResponse.fromWeb(
+ request,
+ Response.json({ files: options.accounts ?? accounts }),
+ );
+ if (path.endsWith("/reset-quota"))
+ return HttpClientResponse.fromWeb(
+ request,
+ Response.json({}, { status: options.cooldownStatus ?? 200 }),
+ );
+ expect(path).toBe("/v0/management/api-call");
+ expect(body?.header?.Authorization).toBe("Bearer $TOKEN$");
+ const upstream = options.upstream?.(body!) ?? {
+ status: 200,
+ body: body?.url?.endsWith("/consume")
+ ? { code: "reset" }
+ : body?.url?.endsWith("/rate-limit-reset-credits")
+ ? {
+ credits: [
+ credit("later", "2099-02-01T00:00:00Z"),
+ credit("first"),
+ credit("expired", "2000-01-01T00:00:00Z"),
+ { ...credit("used"), status: "redeemed" },
+ ],
+ }
+ : {
+ plan_type: "pro",
+ rate_limit: {
+ secondary_window: {
+ used_percent: 78,
+ reset_at: 4070908800,
+ limit_window_seconds: 604800,
+ },
+ },
+ },
+ };
+ return HttpClientResponse.fromWeb(
+ request,
+ Response.json({ status_code: upstream.status, body: encodeJson(upstream.body) }),
+ );
+ }),
+ );
+ return {
+ requests,
+ api: makeCliproxyApi.pipe(Effect.provideService(HttpClient.HttpClient, http)),
+ };
+}
+
+describe("CLIProxyAPI built-in management API", () => {
+ it.effect(
+ "reads both accounts and their earliest unexpired credits without plugin endpoints",
+ () =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(1788710400000);
+ const test = fixture();
+ const api = yield* test.api;
+ const result = yield* api.readAccounts(config);
+ expect(result.map((account) => account.usageLimits.resetCredits)).toEqual([
+ { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
+ { availableCount: 2, nextCreditId: "first", nextExpiresAt: "2099-01-01T00:00:00.000Z" },
+ ]);
+ expect(result[0]?.usageLimits.windows).toMatchObject([
+ { id: "secondary", usedPercent: 78, kind: "weekly" },
+ ]);
+ const calls = test.requests.filter((request) => request.body?.url);
+ expect(calls.map((request) => request.body?.auth_index).sort()).toEqual([
+ "a",
+ "a",
+ "b",
+ "b",
+ ]);
+ expect(
+ calls.find((request) => request.body?.auth_index === "b")?.body?.header?.[
+ "Chatgpt-Account-Id"
+ ],
+ ).toBe("account-b");
+ }),
+ );
+
+ it.effect("keeps usage when the credits endpoint fails", () =>
+ Effect.gen(function* () {
+ const test = fixture({
+ upstream: (request) =>
+ request.url?.endsWith("rate-limit-reset-credits")
+ ? { status: 503, body: { token: "do-not-publish" } }
+ : { status: 200, body: { rate_limit: { primary_window: { used_percent: 12 } } } },
+ });
+ const api = yield* test.api;
+ const result = yield* api.readAccounts(config);
+ expect(result[0]?.usageLimits.windows[0]?.usedPercent).toBe(12);
+ expect(result[0]?.usageLimits.resetCredits).toBeUndefined();
+ }),
+ );
+
+ it.effect("isolates a failed account and never publishes upstream error bodies", () =>
+ Effect.gen(function* () {
+ const test = fixture({
+ upstream: (request) =>
+ request.auth_index === "a"
+ ? { status: 401, body: { token: "do-not-publish" } }
+ : {
+ status: 200,
+ body: request.url?.endsWith("rate-limit-reset-credits")
+ ? { credits: [] }
+ : { rate_limit: { primary_window: { used_percent: 12 } } },
+ },
+ });
+ const api = yield* test.api;
+ const result = yield* api.readAccounts(config);
+ expect(result[0]?.usageLimits.unavailable?.reason).toBe("probeFailed");
+ expect(result[1]?.usageLimits.windows[0]?.usedPercent).toBe(12);
+ expect(encodeJson(result)).not.toContain("do-not-publish");
+ }),
+ );
+
+ it.effect("maps Claude scoped windows without a scheduler plugin", () =>
+ Effect.gen(function* () {
+ const test = fixture({
+ accounts: [{ ...accounts[0]!, provider: "claude" }],
+ upstream: () => ({
+ status: 200,
+ body: {
+ five_hour: { utilization: 10, resets_at: null },
+ seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" },
+ limits: [
+ {
+ kind: "weekly_scoped",
+ percent: 80,
+ resets_at: null,
+ scope: { model: { display_name: "Fable" } },
+ },
+ ],
+ },
+ }),
+ });
+ const api = yield* test.api;
+ const result = yield* api.readAccounts(config);
+ expect(
+ result[0]?.usageLimits.windows.map((window) => [window.id, window.usedPercent]),
+ ).toEqual([
+ ["five_hour", 10],
+ ["seven_day", 50],
+ ["seven_day_fable", 80],
+ ]);
+ }),
+ );
+
+ it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
+ Effect.gen(function* () {
+ const test = fixture();
+ const api = yield* test.api;
+ expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
+ expect(yield* api.consume(config, "second.json", "credit-b")).toEqual({ outcome: "reset" });
+ const redemptions = test.requests.filter((request) =>
+ request.body?.url?.endsWith("/consume"),
+ );
+ expect(redemptions).toHaveLength(2);
+ expect(redemptions[0]?.body?.data).toBe(redemptions[1]?.body?.data);
+ expect(redemptions[0]?.body?.data).toBe(
+ encodeJson({
+ redeem_request_id: creditRedeemRequestId("account-b", "credit-b"),
+ credit_id: "credit-b",
+ }),
+ );
+ expect(
+ test.requests
+ .filter((request) => request.path.endsWith("/reset-quota"))
+ .map((request) => request.body?.auth_index),
+ ).toEqual(["b", "b"]);
+ }),
+ );
+
+ for (const [code, outcome] of [
+ ["nothing_to_reset", "nothingToReset"],
+ ["no_credit", "noCredit"],
+ ["already_redeemed", "alreadyRedeemed"],
+ ] as const) {
+ it.effect(`reports ${code} accurately`, () =>
+ Effect.gen(function* () {
+ const test = fixture({ upstream: () => ({ status: 200, body: { code } }) });
+ const api = yield* test.api;
+ expect(yield* api.consume(config, "first.json", "credit")).toEqual({ outcome });
+ expect(test.requests.some((request) => request.path.endsWith("/reset-quota"))).toBe(
+ code === "already_redeemed",
+ );
+ }),
+ );
+ }
+
+ it.effect("reports redemption success even if cooldown clearing fails", () =>
+ Effect.gen(function* () {
+ const api = yield* fixture({ cooldownStatus: 404 }).api;
+ const result = yield* api.consume(config, "first.json", "credit");
+ expect(result.outcome).toBe("reset");
+ expect(result.warning).toContain("cooldown");
+ }),
+ );
+
+ it.effect("skips disabled accounts and rejects redemption on them", () =>
+ Effect.gen(function* () {
+ const test = fixture({ accounts: [{ ...accounts[0]!, disabled: true }] });
+ const api = yield* test.api;
+ expect(yield* api.readAccounts(config)).toEqual([]);
+ expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
+ "Failure",
+ );
+ expect(test.requests.every((request) => request.path.endsWith("/auth-files"))).toBe(true);
+ }),
+ );
+
+ it.effect("keeps the same redemption id after an uncertain upstream failure", () =>
+ Effect.gen(function* () {
+ let attempts = 0;
+ const test = fixture({
+ upstream: () =>
+ ++attempts === 1
+ ? { status: 503, body: {} }
+ : { status: 200, body: { code: "already_redeemed" } },
+ });
+ const api = yield* test.api;
+ expect((yield* api.consume(config, "first.json", "credit").pipe(Effect.result))._tag).toBe(
+ "Failure",
+ );
+ expect(yield* api.consume(config, "first.json", "credit")).toEqual({
+ outcome: "alreadyRedeemed",
+ });
+ const data = test.requests
+ .filter((request) => request.body?.url?.endsWith("/consume"))
+ .map((request) => request.body?.data);
+ expect(data[0]).toBe(data[1]);
+ expect(test.requests.filter((request) => request.path.endsWith("/reset-quota"))).toHaveLength(
+ 1,
+ );
+ }),
+ );
+
+ it.effect("rejects unknown accounts without forwarding a redemption", () =>
+ Effect.gen(function* () {
+ const test = fixture();
+ const api = yield* test.api;
+ const result = yield* api.consume(config, "missing.json", "credit").pipe(Effect.result);
+ expect(result._tag).toBe("Failure");
+ expect(test.requests).toHaveLength(1);
+ }),
+ );
+});
diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts
new file mode 100644
index 00000000000..6bfd3fe4772
--- /dev/null
+++ b/apps/server/src/usage/cliproxyApi.ts
@@ -0,0 +1,366 @@
+import * as NodeCrypto from "node:crypto";
+
+import {
+ ProviderDriverKind,
+ UsageLimitSourceError,
+ type ProviderConsumeResetCreditResult,
+ type UsageLimitSourceAccount,
+ type UsageLimitSourceConfig,
+} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
+
+import { codexPlanLabel } from "../provider/Layers/CodexProvider.ts";
+import { codexRateLimitsToLimits } from "../provider/Layers/codexUsageLimits.ts";
+import { claudeUsageResponseToLimits } from "../provider/Layers/claudeUsageLimits.ts";
+import { makeUnavailableUsageLimits } from "../provider/providerUsageLimits.ts";
+
+const AuthFile = Schema.Struct({
+ id: Schema.String,
+ auth_index: Schema.String,
+ provider: Schema.String,
+ email: Schema.optional(Schema.String),
+ disabled: Schema.optional(Schema.Boolean),
+ id_token: Schema.optional(
+ Schema.Struct({
+ chatgpt_account_id: Schema.optional(Schema.String),
+ chatgpt_plan_type: Schema.optional(Schema.String),
+ }),
+ ),
+});
+const AuthFiles = Schema.Struct({ files: Schema.Array(AuthFile) });
+const ApiResponse = Schema.Struct({ status_code: Schema.Number, body: Schema.String });
+const CodexWindow = Schema.Struct({
+ used_percent: Schema.Number,
+ reset_at: Schema.optional(Schema.NullOr(Schema.Number)),
+ limit_window_seconds: Schema.optional(Schema.Number),
+});
+const CodexUsage = Schema.Struct({
+ plan_type: Schema.optional(Schema.String),
+ rate_limit: Schema.NullOr(
+ Schema.Struct({
+ primary_window: Schema.optional(Schema.NullOr(CodexWindow)),
+ secondary_window: Schema.optional(Schema.NullOr(CodexWindow)),
+ }),
+ ),
+});
+const ClaudeWindow = Schema.Struct({
+ utilization: Schema.Number,
+ resets_at: Schema.NullOr(Schema.String),
+});
+const ClaudeUsage = Schema.Struct({
+ five_hour: Schema.optional(Schema.NullOr(ClaudeWindow)),
+ seven_day: Schema.optional(Schema.NullOr(ClaudeWindow)),
+ limits: Schema.optional(
+ Schema.Array(
+ Schema.Struct({
+ kind: Schema.String,
+ percent: Schema.optional(Schema.NullOr(Schema.Number)),
+ resets_at: Schema.optional(Schema.NullOr(Schema.String)),
+ scope: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ model: Schema.optional(Schema.NullOr(Schema.Struct({ display_name: Schema.String }))),
+ }),
+ ),
+ ),
+ }),
+ ),
+ ),
+});
+const CreditList = Schema.Struct({
+ credits: Schema.Array(
+ Schema.Struct({
+ id: Schema.String,
+ status: Schema.String,
+ reset_type: Schema.String,
+ expires_at: Schema.String,
+ }),
+ ),
+});
+
+const decodeAuthFiles = Schema.decodeUnknownEffect(AuthFiles);
+const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
+const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse);
+const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList));
+const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
+const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
+const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
+const decodeConsumeResponse = Schema.decodeUnknownEffect(
+ Schema.fromJsonString(
+ Schema.Struct({
+ code: Schema.Literals(["reset", "nothing_to_reset", "no_credit", "already_redeemed"]),
+ }),
+ ),
+);
+
+const CODEX_BASE = "https://chatgpt.com/backend-api/wham";
+const CREDIT_URL = `${CODEX_BASE}/rate-limit-reset-credits`;
+
+// UUIDv5 per account and credit also deduplicates retries across T3 environments.
+export function creditRedeemRequestId(accountId: string, creditId: string): string {
+ const bytes = NodeCrypto.createHash("sha1")
+ .update(Buffer.from("6f1c2a9e2d4b4c1e9a7f3b8d5e0c1a42", "hex"))
+ .update(`${accountId}:${creditId}`)
+ .digest()
+ .subarray(0, 16);
+ bytes[6] = (bytes[6]! & 0x0f) | 0x50;
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
+ const hex = bytes.toString("hex");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+export const makeCliproxyApi = Effect.gen(function* () {
+ const client = yield* HttpClient.HttpClient;
+
+ const management = Effect.fn("CliproxyApi.management")(function* (
+ config: UsageLimitSourceConfig,
+ path: string,
+ body?: unknown,
+ ) {
+ const url = yield* Effect.try({
+ try: () => new URL(`/v0/management/${path}`, config.url).toString(),
+ catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }),
+ });
+ const request = (
+ body === undefined ? HttpClientRequest.get(url) : HttpClientRequest.post(url)
+ ).pipe(HttpClientRequest.setHeader("Authorization", `Bearer ${config.managementKey}`));
+ const response = yield* client
+ .execute(body === undefined ? request : request.pipe(HttpClientRequest.bodyJsonUnsafe(body)))
+ .pipe(
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
+ Effect.flatMap((response) => response.json),
+ Effect.timeout("15 seconds"),
+ Effect.mapError(
+ () => new UsageLimitSourceError({ detail: "The hub management request failed." }),
+ ),
+ );
+ return response;
+ });
+
+ const authFiles = Effect.fn("CliproxyApi.authFiles")(function* (config: UsageLimitSourceConfig) {
+ const response = yield* management(config, "auth-files");
+ return (yield* decodeAuthFiles(response)).files;
+ });
+
+ const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
+ config: UsageLimitSourceConfig,
+ account: typeof AuthFile.Type,
+ url: string,
+ data?: unknown,
+ ) {
+ const header =
+ account.provider === "codex"
+ ? {
+ Authorization: "Bearer $TOKEN$",
+ "Content-Type": "application/json",
+ "OpenAI-Beta": "codex-1",
+ Originator: "Codex Desktop",
+ ...(account.id_token?.chatgpt_account_id
+ ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
+ : {}),
+ }
+ : { Authorization: "Bearer $TOKEN$", "anthropic-beta": "oauth-2025-04-20" };
+ const raw = yield* management(config, "api-call", {
+ auth_index: account.auth_index,
+ method: data === undefined ? "GET" : "POST",
+ url,
+ header,
+ ...(data === undefined ? {} : { data: yield* encodeJson(data) }),
+ });
+ const response = yield* decodeApiResponse(raw);
+ if (response.status_code < 200 || response.status_code >= 300) {
+ return yield* new UsageLimitSourceError({
+ detail: `The provider refused the hub request (HTTP ${response.status_code}).`,
+ });
+ }
+ return response.body;
+ });
+
+ const credits = Effect.fn("CliproxyApi.credits")(function* (
+ config: UsageLimitSourceConfig,
+ account: typeof AuthFile.Type,
+ ) {
+ const body = yield* apiCall(config, account, CREDIT_URL);
+ const response = yield* decodeCreditList(body);
+ const now = DateTime.toEpochMillis(yield* DateTime.now);
+ return response.credits
+ .filter(
+ (credit) =>
+ credit.reset_type === "codex_rate_limits" &&
+ credit.status === "available" &&
+ Date.parse(credit.expires_at) > now,
+ )
+ .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
+ });
+
+ const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
+ config: UsageLimitSourceConfig,
+ account: typeof AuthFile.Type,
+ ) {
+ const checkedAt = DateTime.formatIso(yield* DateTime.now);
+ const base = {
+ id: account.id,
+ driver: ProviderDriverKind.make(account.provider === "codex" ? "codex" : "claudeAgent"),
+ ...(account.email ? { email: account.email } : {}),
+ };
+ const read = Effect.gen(function* () {
+ if (account.provider === "claude") {
+ const body = yield* apiCall(config, account, "https://api.anthropic.com/api/oauth/usage");
+ const usage = yield* decodeClaudeUsage(body);
+ const model_scoped = (usage.limits ?? []).flatMap((limit) =>
+ limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
+ ? [
+ {
+ display_name: limit.scope.model.display_name,
+ utilization: limit.percent,
+ resets_at: limit.resets_at ?? null,
+ },
+ ]
+ : [],
+ );
+ return {
+ ...base,
+ plan: "Claude Subscription",
+ usageLimits: claudeUsageResponseToLimits({
+ checkedAt,
+ response: {
+ rate_limits_available: true,
+ rate_limits: {
+ five_hour: usage.five_hour ?? null,
+ seven_day: usage.seven_day ?? null,
+ model_scoped,
+ },
+ },
+ }).limits,
+ };
+ }
+ const body = yield* apiCall(config, account, `${CODEX_BASE}/usage`);
+ const usage = yield* decodeCodexUsage(body);
+ const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
+ window
+ ? {
+ usedPercent: window.used_percent,
+ resetsAt: window.reset_at ?? null,
+ ...(window.limit_window_seconds === undefined
+ ? {}
+ : { windowDurationMins: window.limit_window_seconds / 60 }),
+ }
+ : null;
+ // A credits outage must not hide successfully fetched quota windows.
+ const available = yield* credits(config, account).pipe(Effect.orElseSucceed(() => undefined));
+ const next = available?.[0];
+ return {
+ ...base,
+ plan: codexPlanLabel(usage.plan_type ?? account.id_token?.chatgpt_plan_type),
+ usageLimits: {
+ ...codexRateLimitsToLimits({
+ checkedAt,
+ snapshot: {
+ planType: usage.plan_type ?? null,
+ primary: toWindow(usage.rate_limit?.primary_window),
+ secondary: toWindow(usage.rate_limit?.secondary_window),
+ },
+ }),
+ ...(available
+ ? {
+ resetCredits: {
+ availableCount: available.length,
+ ...(next
+ ? {
+ nextCreditId: next.id,
+ nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
+ }
+ : {}),
+ },
+ }
+ : {}),
+ },
+ };
+ });
+ return yield* read.pipe(
+ Effect.orElseSucceed(() => ({
+ ...base,
+ usageLimits: makeUnavailableUsageLimits({
+ checkedAt,
+ reason: "probeFailed",
+ message: "The hub could not read this account's usage.",
+ }),
+ })),
+ );
+ });
+
+ const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
+ config: UsageLimitSourceConfig,
+ ): Effect.fn.Return<ReadonlyArray<UsageLimitSourceAccount>, UsageLimitSourceError> {
+ const accounts = yield* authFiles(config).pipe(
+ Effect.mapError(
+ () => new UsageLimitSourceError({ detail: "The hub could not list accounts." }),
+ ),
+ );
+ return yield* Effect.forEach(
+ accounts.filter(
+ (account) =>
+ !account.disabled && (account.provider === "codex" || account.provider === "claude"),
+ ),
+ (account) => readAccount(config, account),
+ { concurrency: 4 },
+ );
+ });
+
+ const consume = Effect.fn("CliproxyApi.consume")(function* (
+ config: UsageLimitSourceConfig,
+ accountId: string,
+ creditId: string,
+ ): Effect.fn.Return<ProviderConsumeResetCreditResult, UsageLimitSourceError> {
+ const operation = Effect.gen(function* () {
+ const account = (yield* authFiles(config)).find((account) => account.id === accountId);
+ if (!account || account.disabled || account.provider !== "codex") {
+ return yield* new UsageLimitSourceError({
+ detail: "The Codex hub account is missing or disabled.",
+ });
+ }
+ const body = yield* apiCall(config, account, `${CREDIT_URL}/consume`, {
+ redeem_request_id: creditRedeemRequestId(
+ account.id_token?.chatgpt_account_id ?? account.id,
+ creditId,
+ ),
+ credit_id: creditId,
+ });
+ const response = yield* decodeConsumeResponse(body);
+ const outcome = (
+ {
+ reset: "reset",
+ nothing_to_reset: "nothingToReset",
+ no_credit: "noCredit",
+ already_redeemed: "alreadyRedeemed",
+ } as const
+ )[response.code];
+ if (outcome !== "reset" && outcome !== "alreadyRedeemed") return { outcome };
+ const cleared = yield* management(config, "reset-quota", {
+ auth_index: account.auth_index,
+ }).pipe(Effect.result);
+ return {
+ outcome,
+ ...(cleared._tag === "Failure"
+ ? {
+ warning:
+ "Credit redeemed, but the hub cooldown could not be cleared. Routing may resume after its cooldown expires.",
+ }
+ : {}),
+ } as const;
+ });
+ return yield* operation.pipe(
+ Effect.mapError((error) =>
+ isUsageLimitSourceError(error)
+ ? error
+ : new UsageLimitSourceError({
+ detail: "The hub returned an unexpected reset-credit response.",
+ }),
+ ),
+ );
+ });
+ return { readAccounts, consume };
+});
diff --git a/apps/server/src/usage/cliproxyUsageLimits.test.ts b/apps/server/src/usage/cliproxyUsageLimits.test.ts
deleted file mode 100644
index 5e8d1b1fff7..00000000000
--- a/apps/server/src/usage/cliproxyUsageLimits.test.ts
+++ /dev/null
@@ -1,134 +0,0 @@
-import { describe, expect, it } from "vite-plus/test";
-
-import { accountEmailFromAuthFile, cliproxyStatusToAccounts } from "./cliproxyUsageLimits.ts";
-
-const checkedAt = "2026-09-03T22:00:00.000Z";
-
-describe("cliproxyStatusToAccounts", () => {
- // Trimmed from a live `quota-scheduler/status`: one Claude account with a
- // hard-limited Fable bucket, one Codex account whose 5h window is unknown.
- it("maps each pooled account onto the windows the provider drivers use", () => {
- const accounts = cliproxyStatusToAccounts(
- {
- accounts: {
- provider: "claude",
- fetched_at: "2026-09-03T15:06:07-07:00",
- five_hour: { hard_limited: false, known: true, used_percent: 0 },
- seven_day: {
- hard_limited: false,
- known: true,
- reset_at: "2026-09-07T07:59:59Z",
- used_percent: 51,
- },
- fable: {
- hard_limited: true,
- known: true,
- reset_at: "2026-09-07T07:59:59Z",
- used_percent: 100,
- },
- },
- provider: "codex",
- plan: "pro",
- fetched_at: "2026-09-03T15:07:07-07:00",
- five_hour: { hard_limited: false, known: false, used_percent: 0 },
- weekly: {
- hard_limited: false,
- known: true,
- reset_at: "2026-09-06T19:52:53-07:00",
- used_percent: 12,
- },
- },
- "[email protected]": { provider: "xai" },
- },
- },
- checkedAt,
- );
-
- expect(accounts).toEqual([
- {
- driver: "claudeAgent",
- email: "[email protected]",
- plan: "Claude Subscription",
- usageLimits: {
- checkedAt: "2026-09-03T22:06:07.000Z",
- windows: [
- {
- id: "five_hour",
- kind: "session",
- label: "Session",
- usedPercent: 0,
- windowDurationMins: 300,
- },
- {
- id: "seven_day",
- kind: "weekly",
- label: "Weekly",
- usedPercent: 51,
- windowDurationMins: 10080,
- resetsAt: "2026-09-07T07:59:59.000Z",
- },
- {
- id: "seven_day_fable",
- kind: "weekly",
- label: "Weekly · Fable",
- usedPercent: 100,
- windowDurationMins: 10080,
- resetsAt: "2026-09-07T07:59:59.000Z",
- },
- ],
- },
- },
- {
- driver: "codex",
- email: "[email protected]",
- plan: "ChatGPT Pro 20x Subscription",
- usageLimits: {
- checkedAt: "2026-09-03T22:07:07.000Z",
- windows: [
- {
- id: "secondary",
- kind: "weekly",
- label: "Weekly",
- usedPercent: 12,
- windowDurationMins: 10080,
- resetsAt: "2026-09-07T02:52:53.000Z",
- },
- ],
- },
- },
- ]);
- });
-
- it("names a Codex five-hour window `primary`, as the Codex driver does", () => {
- const accounts = cliproxyStatusToAccounts(
- {
- accounts: {
- provider: "codex",
- plan: "pro",
- five_hour: { hard_limited: false, known: true, used_percent: 40 },
- },
- },
- },
- checkedAt,
- );
- expect(accounts[0]?.usageLimits.windows.map((window) => window.id)).toEqual(["primary"]);
- });
-});
-
-describe("accountEmailFromAuthFile", () => {
- it("pulls the email out of the hub's auth file names", () => {
- expect(accountEmailFromAuthFile("[email protected]")).toBe("[email protected]");
- expect(accountEmailFromAuthFile("[email protected]")).toBe(
- );
- expect(accountEmailFromAuthFile("[email protected]")).toBe(
- );
- expect(accountEmailFromAuthFile("mystery.json")).toBeUndefined();
- });
-});
diff --git a/apps/server/src/usage/cliproxyUsageLimits.ts b/apps/server/src/usage/cliproxyUsageLimits.ts
deleted file mode 100644
index 47ed200c3f2..00000000000
--- a/apps/server/src/usage/cliproxyUsageLimits.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-/**
- * Maps a CLIProxyAPI hub's `quota-scheduler/status` response onto the usage
- * limit windows the Limits view renders, one account per pooled auth file.
- *
- * The hub already normalises each upstream: Claude accounts carry
- * `five_hour` / `seven_day` / `fable`, Codex accounts `five_hour` / `weekly`.
- * Every window is `{ used_percent, reset_at?, known, hard_limited }`.
- *
- * @module usage/cliproxyUsageLimits
- */
-import {
- ProviderDriverKind,
- type ServerProviderUsageLimits,
- type ServerProviderUsageWindow,
- type UsageLimitSourceAccount,
-} from "@t3tools/contracts";
-import * as DateTime from "effect/DateTime";
-import * as Option from "effect/Option";
-import * as Schema from "effect/Schema";
-
-import { codexPlanLabel } from "../provider/Layers/CodexProvider.ts";
-import { clampPercent, makeUsageLimits } from "../provider/providerUsageLimits.ts";
-
-const QuotaWindow = Schema.Struct({
- used_percent: Schema.Number,
- reset_at: Schema.optional(Schema.String),
- known: Schema.optional(Schema.Boolean),
- hard_limited: Schema.optional(Schema.Boolean),
-});
-
-const QuotaAccount = Schema.Struct({
- provider: Schema.String,
- plan: Schema.optional(Schema.String),
- fetched_at: Schema.optional(Schema.String),
- five_hour: Schema.optional(QuotaWindow),
- seven_day: Schema.optional(QuotaWindow),
- weekly: Schema.optional(QuotaWindow),
- fable: Schema.optional(QuotaWindow),
-});
-
-export const CliproxyQuotaStatus = Schema.Struct({
- accounts: Schema.Record(Schema.String, QuotaAccount),
-});
-export type CliproxyQuotaStatus = typeof CliproxyQuotaStatus.Type;
-export const decodeCliproxyQuotaStatus = Schema.decodeUnknownEffect(CliproxyQuotaStatus);
-
-const SESSION_MINS = 5 * 60;
-const WEEK_MINS = 7 * 24 * 60;
-
-/** Window ids match what the provider drivers emit, so rows read the same across sources. */
-const WINDOWS: ReadonlyArray<{
- readonly key: keyof Omit<typeof QuotaAccount.Type, "provider" | "plan" | "fetched_at">;
- readonly id: string;
- readonly kind: ServerProviderUsageWindow["kind"];
- readonly label: string;
- readonly windowDurationMins: number;
-}> = [
- {
- key: "five_hour",
- id: "five_hour",
- kind: "session",
- label: "Session",
- windowDurationMins: SESSION_MINS,
- },
- {
- key: "seven_day",
- id: "seven_day",
- kind: "weekly",
- label: "Weekly",
- windowDurationMins: WEEK_MINS,
- },
- {
- key: "weekly",
- id: "secondary",
- kind: "weekly",
- label: "Weekly",
- windowDurationMins: WEEK_MINS,
- },
- {
- key: "fable",
- id: "seven_day_fable",
- kind: "weekly",
- label: "Weekly · Fable",
- windowDurationMins: WEEK_MINS,
- },
-];
-
-const DRIVER_BY_HUB_PROVIDER: Readonly<Record<string, ProviderDriverKind>> = {
- claude: ProviderDriverKind.make("claudeAgent"),
- codex: ProviderDriverKind.make("codex"),
-};
-
-function isoFromHub(value: string | undefined): string | undefined {
- if (!value) return undefined;
- const dt = DateTime.make(value);
- return Option.isSome(dt) ? DateTime.formatIso(dt.value) : undefined;
-}
-
-/** `[email protected]` → `[email protected]`; `codex-<hash>[email protected]` → `x@y`. */
-export function accountEmailFromAuthFile(fileName: string): string | undefined {
- const stem = fileName.replace(/\.json$/i, "");
- // Strip the provider prefix (and Codex's hash) rather than splitting on
- // `-`, so a hyphenated local part such as `first-last@` survives.
- return stem.match(/^(?:claude-|codex-[a-z0-9]+-)?([^\s/]+@[^\s/]+?)(?:-[a-z0-9]+)?$/i)?.[1];
-}
-
-/**
- * The hub only reports a plan slug for Codex. Claude accounts carry no tier
- * in the scheduler status, so the row says what it is: a Claude subscription.
- */
-function planLabel(account: typeof QuotaAccount.Type): string | undefined {
- if (account.provider === "codex") return codexPlanLabel(account.plan);
- if (account.provider === "claude") return "Claude Subscription";
- return undefined;
-}
-
-export function cliproxyAccountToUsageLimits(
- account: typeof QuotaAccount.Type,
- checkedAt: string,
-): ServerProviderUsageLimits {
- const windows: ServerProviderUsageWindow[] = [];
- for (const spec of WINDOWS) {
- const window = account[spec.key];
- if (!window || window.known === false) continue;
- const resetsAt = isoFromHub(window.reset_at);
- windows.push({
- // Codex names its five-hour window by position, so a hub row and a
- // native row for the same account pool together.
- id: spec.key === "five_hour" && account.provider === "codex" ? "primary" : spec.id,
- kind: spec.kind,
- label: spec.label,
- windowDurationMins: spec.windowDurationMins,
- // The hub flags a window it has seen a 429 on; the percent may lag.
- usedPercent: window.hard_limited ? 100 : clampPercent(window.used_percent),
- ...(resetsAt ? { resetsAt } : {}),
- });
- }
- return makeUsageLimits({ checkedAt: isoFromHub(account.fetched_at) ?? checkedAt, windows });
-}
-
-export function cliproxyStatusToAccounts(
- status: CliproxyQuotaStatus,
- checkedAt: string,
-): ReadonlyArray<UsageLimitSourceAccount> {
- const accounts: UsageLimitSourceAccount[] = [];
- for (const [fileName, account] of Object.entries(status.accounts)) {
- const driver = DRIVER_BY_HUB_PROVIDER[account.provider];
- if (!driver) continue;
- const email = accountEmailFromAuthFile(fileName);
- const plan = planLabel(account);
- accounts.push({
- id: fileName,
- driver,
- ...(email ? { email } : {}),
- ...(plan ? { plan } : {}),
- usageLimits: cliproxyAccountToUsageLimits(account, checkedAt),
- });
- }
- return accounts.toSorted(
- (left, right) => left.driver.localeCompare(right.driver) || left.id.localeCompare(right.id),
- );
-}
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index b4255c64781..46396bf1e4a 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1847,6 +1847,7 @@ const makeWsRpcLayer = (
observeRpcEffect(
WS_METHODS.providerConsumeResetCredit,
Effect.gen(function* () {
+ if ("sourceId" in input) return yield* usageLimitSources.consumeResetCredit(input);
const instance = yield* providerInstances.getInstance(input.instanceId);
// A disabled instance must not spend anything on its account.
if (instance === undefined || !instance.enabled) {
diff --git a/apps/web/src/components/chat/ComposerUsageLimits.tsx b/apps/web/src/components/chat/ComposerUsageLimits.tsx
index 384492b5789..3171582298b 100644
--- a/apps/web/src/components/chat/ComposerUsageLimits.tsx
+++ b/apps/web/src/components/chat/ComposerUsageLimits.tsx
@@ -57,6 +57,9 @@ function UsageLimitsBannerBody({
<ComposerBanner.Scroll>
<ComposerBanner.Body className="flex flex-col gap-2 pt-1 pb-1.5 pe-2">
{report.accounts.map((account) => {
+ const resetCreditInput =
+ account.resetCreditInput ??
+ (account.instanceId ? { instanceId: account.instanceId } : undefined);
const notice = limitsNotice(account.limits);
return (
<div key={account.id} className="flex min-w-0 flex-col gap-1">
@@ -75,10 +78,10 @@ function UsageLimitsBannerBody({
now={now}
/>
)}
- {account.instanceId && account.limits.resetCredits ? (
+ {resetCreditInput && account.limits.resetCredits ? (
<ResetCredits
environmentId={environmentId}
- instanceId={account.instanceId}
+ input={resetCreditInput}
credits={account.limits.resetCredits}
now={now}
/>
diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx
index 3f7168ad32f..e50547b6600 100644
--- a/apps/web/src/components/usage/UsageLimits.tsx
+++ b/apps/web/src/components/usage/UsageLimits.tsx
@@ -1,7 +1,7 @@
import {
type EnvironmentId,
type ProviderConsumeResetCreditOutcome,
- ProviderInstanceId,
+ ProviderConsumeResetCreditInput,
ServerProvider,
ServerProviderResetCredits,
ServerProviderUsageWindow,
@@ -202,7 +202,10 @@ const OUTCOME_TEXT: Record<ProviderConsumeResetCreditOutcome, string> = {
};
/** Everything a redeem needs: where to send it and what to say afterwards. */
-export function useResetCredit(environmentId: EnvironmentId, instanceId: ProviderInstanceId) {
+export function useResetCredit(
+ environmentId: EnvironmentId,
+ input: ProviderConsumeResetCreditInput,
+) {
const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false });
const [confirming, setConfirming] = useState(false);
const [busy, setBusy] = useState(false);
@@ -212,10 +215,10 @@ export function useResetCredit(environmentId: EnvironmentId, instanceId: Provide
setConfirming(false);
setBusy(true);
setStatus(null);
- const result = await consume({ environmentId, input: { instanceId } });
+ const result = await consume({ environmentId, input });
setBusy(false);
if (result._tag === "Success") {
- setStatus(OUTCOME_TEXT[result.value.outcome]);
+ setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]);
return;
}
setStatus(
@@ -282,19 +285,16 @@ export function resetCreditsSummary(
/** Banked reset credits with the redeem button and its confirm, self-contained. */
export function ResetCredits({
environmentId,
- instanceId,
+ input,
credits,
now,
}: {
readonly environmentId: EnvironmentId;
- readonly instanceId: ProviderInstanceId;
+ readonly input: ProviderConsumeResetCreditInput;
readonly credits: ServerProviderResetCredits;
readonly now: number;
}) {
- const { confirming, setConfirming, busy, status, redeem } = useResetCredit(
- environmentId,
- instanceId,
- );
+ const { confirming, setConfirming, busy, status, redeem } = useResetCredit(environmentId, input);
if (credits.availableCount === 0 && status === null) return null;
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx
index 1d57cdb9634..0c17779daa3 100644
--- a/apps/web/src/components/usage/UsageLimitsPooled.tsx
+++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx
@@ -235,7 +235,7 @@ function PoolSegment({
const [open, setOpen] = useState(false);
const remaining = remainingPercent(window);
const resetsIn = formatResetsIn(window, now);
- const credits = account.redeem ? (account.limits.resetCredits?.availableCount ?? 0) : 0;
+ const credits = account.limits.resetCredits?.availableCount ?? 0;
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
@@ -340,7 +340,7 @@ function LegendRow({
}) {
const remaining = remainingPercent(window);
const resetsIn = formatResetsIn(window, now);
- const credits = account.redeem ? (account.limits.resetCredits?.availableCount ?? 0) : 0;
+ const credits = account.limits.resetCredits?.availableCount ?? 0;
return (
<PopoverTrigger
style={{ gridColumn: "1 / -1", gridRow: index + 1 }}
@@ -395,7 +395,7 @@ function RedeemableSegmentPopup({
readonly redeemAt: NonNullable<LimitAccount["redeem"]>;
readonly closePopover: () => void;
}) {
- const redeem = useResetCredit(redeemAt.environmentId, redeemAt.instanceId);
+ const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input);
return (
<>
<PopoverPopup side="top" sideOffset={6}>
diff --git a/docs/user/usage.md b/docs/user/usage.md
index 4c4af3299ac..4be084ea299 100644
--- a/docs/user/usage.md
+++ b/docs/user/usage.md
@@ -67,6 +67,9 @@ using a proxy through `ANTHROPIC_AUTH_TOKEN`.
To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the
environment that will connect to the hub and enter its URL and management key.
-The accounts appear under **Usage → Limits**. This connection supplies usage information; configure
+The accounts appear under **Usage → Limits**. Codex accounts show banked reset credits; select an
+account and choose **Use reset** to redeem one. No hub plugin is required.
+
+This connection supplies usage information; configure
the provider separately to send agent requests through the hub. Remove the hub from the same
settings section when you no longer need it.
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 7cd1cf019be..91073a6354d 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -975,7 +975,7 @@ export function createServerEnvironmentAtoms<R, E>(
tag: WS_METHODS.providerAuthStart,
concurrency: {
mode: "singleFlight",
- key: ({ environmentId, input }) => JSON.stringify([environmentId, input.instanceId]),
+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
},
}),
completeProviderAuth: createEnvironmentRpcCommand(runtime, {
@@ -1056,7 +1056,7 @@ export function createServerEnvironmentAtoms<R, E>(
concurrency: {
mode: "singleFlight",
// Both ids are free-form strings; a delimiter could collide.
- key: ({ environmentId, input }) => JSON.stringify([environmentId, input.instanceId]),
+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
},
}),
refreshProviders: createEnvironmentRpcCommand(runtime, {
diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts
index 554e68c1b20..d460d53f8b4 100644
--- a/packages/contracts/src/providerUsageLimits.ts
+++ b/packages/contracts/src/providerUsageLimits.ts
@@ -35,6 +35,8 @@ export type ServerProviderUsageWindow = typeof ServerProviderUsageWindow.Type;
export const ServerProviderResetCredits = Schema.Struct({
availableCount: NonNegativeInt,
nextExpiresAt: Schema.optional(IsoDateTime),
+ /** Pins hub redemption to the displayed credit, including retries from another client. */
+ nextCreditId: Schema.optional(TrimmedNonEmptyString),
});
export type ServerProviderResetCredits = typeof ServerProviderResetCredits.Type;
@@ -103,11 +105,29 @@ export type UsageLimitSourceSnapshot = typeof UsageLimitSourceSnapshot.Type;
export const UsageLimitSourceSnapshots = ForwardCompatibleArray(UsageLimitSourceSnapshot);
export type UsageLimitSourceSnapshots = typeof UsageLimitSourceSnapshots.Type;
-export const ProviderConsumeResetCreditInput = Schema.Struct({
- instanceId: ProviderInstanceId,
+export const UsageLimitSourceConsumeResetCreditInput = Schema.Struct({
+ sourceId: UsageLimitSourceId,
+ accountId: TrimmedNonEmptyString,
+ creditId: TrimmedNonEmptyString,
});
+export type UsageLimitSourceConsumeResetCreditInput =
+ typeof UsageLimitSourceConsumeResetCreditInput.Type;
+
+export const ProviderConsumeResetCreditInput = Schema.Union([
+ Schema.Struct({ instanceId: ProviderInstanceId }),
+ UsageLimitSourceConsumeResetCreditInput,
+]);
export type ProviderConsumeResetCreditInput = typeof ProviderConsumeResetCreditInput.Type;
+export class UsageLimitSourceError extends Schema.TaggedErrorClass<UsageLimitSourceError>()(
+ "UsageLimitSourceError",
+ { detail: Schema.String },
+) {
+ override get message(): string {
+ return this.detail;
+ }
+}
+
/** Mirrors Codex's own outcome set; other providers map onto it. */
export const ProviderConsumeResetCreditOutcome = Schema.Literals([
"reset",
@@ -119,6 +139,8 @@ export type ProviderConsumeResetCreditOutcome = typeof ProviderConsumeResetCredi
export const ProviderConsumeResetCreditResult = Schema.Struct({
outcome: ProviderConsumeResetCreditOutcome,
+ /** Redemption succeeded, but a follow-up such as clearing the hub cooldown failed. */
+ warning: Schema.optional(TrimmedNonEmptyString),
});
export type ProviderConsumeResetCreditResult = typeof ProviderConsumeResetCreditResult.Type;
@@ -134,6 +156,7 @@ export const UsageLimitsReport = Schema.Struct({
email: Schema.optional(TrimmedNonEmptyString),
sourceLabel: Schema.optional(TrimmedNonEmptyString),
instanceId: Schema.optional(ProviderInstanceId),
+ resetCreditInput: Schema.optional(ProviderConsumeResetCreditInput),
displayName: Schema.optional(Schema.String),
accentColor: Schema.optional(Schema.String),
limits: ServerProviderUsageLimits,
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index fb077193c20..9dbcaa9f416 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -217,6 +217,7 @@ import {
ResourceTelemetrySnapshot,
} from "./resourceTelemetry.ts";
import {
+ UsageLimitSourceError,
ProviderConsumeResetCreditInput,
ProviderConsumeResetCreditResult,
} from "./providerUsageLimits.ts";
@@ -432,7 +433,7 @@ const ProviderSetupRpcError = Schema.Union([ProviderSetupError, EnvironmentAutho
const WsProviderConsumeResetCreditRpc = Rpc.make(WS_METHODS.providerConsumeResetCredit, {
payload: ProviderConsumeResetCreditInput,
success: ProviderConsumeResetCreditResult,
- error: ProviderSetupRpcError,
+ error: Schema.Union([ProviderSetupError, UsageLimitSourceError, EnvironmentAuthorizationError]),
});
const WsProviderAuthStartRpc = Rpc.make(WS_METHODS.providerAuthStart, {
diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts
index 32fb4eaa950..4f217f66c78 100644
--- a/packages/shared/src/usageLimits.test.ts
+++ b/packages/shared/src/usageLimits.test.ts
@@ -378,7 +378,7 @@ describe("pools", () => {
key: "env-a:claude",
sourceLabel: null,
// Desktop's read is fresher, so its credits and its redeem are the ones on show.
- redeem: { environmentId: "env-b", instanceId: "claude" },
+ redeem: { environmentId: "env-b", input: { instanceId: "claude" } },
environments: [
{ environmentId: "env-a", label: "Laptop" },
{ environmentId: "env-b", label: "Desktop" },
@@ -429,7 +429,7 @@ describe("pools", () => {
const [account] = collectLimitAccounts(input);
expect(account?.limits.windows[0]?.usedPercent).toBe(55);
expect(account?.limits.resetCredits?.availableCount).toBe(2);
- expect(account?.redeem).toEqual({ environmentId: "env-a", instanceId: "claude" });
+ expect(account?.redeem).toEqual({ environmentId: "env-a", input: { instanceId: "claude" } });
expect(account?.environments).toEqual([{ environmentId: "env-a", label: "Laptop" }]);
});
@@ -459,7 +459,108 @@ describe("pools", () => {
]);
const [account] = collectLimitAccounts(input);
expect(account?.limits.resetCredits?.availableCount).toBe(2);
- expect(account?.redeem).toEqual({ environmentId: "env-b", instanceId: "codex" });
+ expect(account?.redeem).toEqual({ environmentId: "env-b", input: { instanceId: "codex" } });
+ });
+
+ it("uses the freshest hub credit and its environment even when the account is also native", () => {
+ const native = provider({
+ auth: { status: "authenticated", email: "[email protected]" },
+ usageLimits: { checkedAt, windows: [window], resetCredits: { availableCount: 1 } },
+ });
+ const hubAccount = {
+ id: "codex-same.json",
+ driver: native.driver,
+ email: "[email protected]",
+ usageLimits: {
+ checkedAt: "2026-09-03T11:30:00.000Z",
+ windows: [window],
+ resetCredits: { availableCount: 2, nextCreditId: "credit-2" },
+ },
+ };
+ const input = new Map([
+ [EnvironmentId.make("env-a"), { ...laptop, serverConfig: { providers: [native] } }],
+ [
+ EnvironmentId.make("env-b"),
+ {
+ ...laptop,
+ serverConfig: {
+ providers: [],
+ usageLimitSources: [{ ...source, accounts: [hubAccount] }],
+ },
+ },
+ ],
+ ]);
+ const [account] = collectLimitAccounts(input);
+ expect(account?.limits.resetCredits?.availableCount).toBe(2);
+ expect(account?.redeem).toEqual({
+ environmentId: "env-b",
+ input: { sourceId: "hub", accountId: "codex-same.json", creditId: "credit-2" },
+ });
+ hubAccount.usageLimits.resetCredits.availableCount = 0;
+ expect(collectLimitAccounts(input)[0]?.limits.resetCredits?.availableCount).toBe(0);
+ });
+
+ it("keeps distinct hub accounts redeemable through their own source", () => {
+ const hubAccounts = ["first", "second"].map((id) => ({
+ id,
+ driver: ProviderDriverKind.make("codex"),
+ email: `${id}@example.com`,
+ usageLimits: {
+ checkedAt,
+ windows: [window],
+ resetCredits: { availableCount: 2, nextCreditId: `${id}-credit` },
+ },
+ }));
+ const input = new Map([
+ [
+ EnvironmentId.make("env-a"),
+ {
+ ...laptop,
+ serverConfig: {
+ providers: [],
+ usageLimitSources: [{ ...source, accounts: hubAccounts }],
+ },
+ },
+ ],
+ ]);
+ expect(collectLimitAccounts(input).map((account) => account.redeem)).toEqual(
+ hubAccounts.map((account) => ({
+ environmentId: "env-a",
+ input: { sourceId: "hub", accountId: account.id, creditId: `${account.id}-credit` },
+ })),
+ );
+ });
+
+ it("does not give old credits the timestamp of a newer window-only read", () => {
+ const snapshots = [
+ { checkedAt, windows: [window], resetCredits: { availableCount: 2 } },
+ { checkedAt: "2026-09-03T12:00:00.000Z", windows: [window] },
+ {
+ checkedAt: "2026-09-03T11:30:00.000Z",
+ windows: [window],
+ resetCredits: { availableCount: 1 },
+ },
+ ];
+ const input = new Map(
+ snapshots.map((usageLimits, i) => [
+ EnvironmentId.make(`env-${i}`),
+ {
+ ...laptop,
+ serverConfig: {
+ providers: [
+ provider({
+ auth: { status: "authenticated", email: "[email protected]" },
+ usageLimits,
+ }),
+ ],
+ },
+ },
+ ]),
+ );
+ const [account] = collectLimitAccounts(input);
+ expect(account?.limits.checkedAt).toBe("2026-09-03T12:00:00.000Z");
+ expect(account?.limits.resetCredits?.availableCount).toBe(1);
+ expect(account?.redeem?.environmentId).toBe("env-2");
});
it("names an environment once however many of its instances share the account", () => {
@@ -713,6 +814,31 @@ describe("/usage-limits", () => {
},
];
+ it("uses hub credit balances and redemption targets in the composer, including native duplicates", () => {
+ const hubs = sources.map((source) => ({
+ ...source,
+ accounts: source.accounts.map((account) => ({
+ ...account,
+ usageLimits: {
+ ...account.usageLimits,
+ resetCredits: { availableCount: 2, nextCreditId: `${account.id}-credit` },
+ },
+ })),
+ }));
+ const report = collectProviderUsageLimits(selected.instanceId, [selected], hubs, now);
+ expect(report?.accounts[0]?.limits.resetCredits?.availableCount).toBe(2);
+ expect(report?.accounts[0]?.resetCreditInput).toEqual({
+ sourceId: "hub",
+ accountId: "duplicate",
+ creditId: "duplicate-credit",
+ });
+ expect(report?.accounts.find((account) => account.id === "hub:oss")?.resetCreditInput).toEqual({
+ sourceId: "hub",
+ accountId: "oss",
+ creditId: "oss-credit",
+ });
+ });
+
it("keeps accounts and custom instances separate, filtering by driver", () => {
const report = collectProviderUsageLimits(
selected.instanceId,
diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts
index d3b295bf42f..532060d3872 100644
--- a/packages/shared/src/usageLimits.ts
+++ b/packages/shared/src/usageLimits.ts
@@ -9,6 +9,7 @@ import {
type EnvironmentId,
type UsageLimitsReport,
type ProviderInstanceId,
+ type ProviderConsumeResetCreditInput,
type ServerProviderSlashCommand,
isProviderAvailable,
type ServerProvider,
@@ -170,24 +171,33 @@ export interface LimitAccount {
}>;
/** The hub that reported it, when no environment has it natively. */
readonly sourceLabel: string | null;
- /** Where a reset credit can be redeemed; only native instances can. */
+ /** Where the displayed reset credit can be redeemed. */
readonly redeem: {
readonly environmentId: EnvironmentId;
- readonly instanceId: ProviderInstanceId;
+ readonly input: ProviderConsumeResetCreditInput;
} | null;
readonly limits: ServerProviderUsageLimits;
}
/**
* Every account with usable windows across the connected environments, one
- * entry per distinct account. Native instances win over hub reports, and the
- * freshest snapshot wins when the same account is reported twice.
+ * entry per distinct account. The freshest reads supply windows and credits;
+ * native instances supply names and environment labels.
*/
export function collectLimitAccounts(
presentations: Parameters<typeof collectLimitSources>[0],
): readonly LimitAccount[] {
const accounts = new Map<string, LimitAccount>();
+ const creditSources = new Map<string, LimitAccount>();
const merge = (key: string, next: LimitAccount) => {
+ const previousCredit = creditSources.get(key);
+ if (
+ next.limits.resetCredits &&
+ (!previousCredit ||
+ Date.parse(next.limits.checkedAt) > Date.parse(previousCredit.limits.checkedAt))
+ ) {
+ creditSources.set(key, next);
+ }
const previous = accounts.get(key);
if (!previous) {
accounts.set(key, next);
@@ -203,13 +213,9 @@ export function collectLimitAccounts(
),
];
const winner = fresher ? next : previous;
- // Windows come from the freshest snapshot, wherever it was read. Reset
- // credits only ever come from a native instance, and the redeem must go
- // to the instance whose credits are on show, so the two travel together:
- // the freshest native snapshot supplies both, or neither.
- const native = [previous, next]
- .filter((candidate) => candidate.redeem !== null)
- .sort((a, b) => Date.parse(b.limits.checkedAt) - Date.parse(a.limits.checkedAt))[0];
+ // Credits and their redemption target travel together. A failed credit
+ // probe must not erase a successful read from another environment.
+ const creditSource = creditSources.get(key);
accounts.set(key, {
...previous,
displayName: previous.displayName ?? next.displayName,
@@ -218,11 +224,13 @@ export function collectLimitAccounts(
environments,
// A hub only names the account when no environment has it natively.
sourceLabel: environments.length > 0 ? null : (previous.sourceLabel ?? next.sourceLabel),
- redeem: native?.redeem ?? null,
+ redeem: creditSource
+ ? creditSource.redeem
+ : (winner.redeem ?? previous.redeem ?? next.redeem),
limits: {
...winner.limits,
- ...(native?.limits.resetCredits
- ? { resetCredits: native.limits.resetCredits }
+ ...(creditSource?.limits.resetCredits
+ ? { resetCredits: creditSource.limits.resetCredits }
: { resetCredits: undefined }),
},
});
@@ -243,7 +251,7 @@ export function collectLimitAccounts(
accentColor: provider.accentColor,
environments: [{ environmentId, label }],
sourceLabel: null,
- redeem: { environmentId, instanceId: provider.instanceId },
+ redeem: { environmentId, input: { instanceId: provider.instanceId } },
limits: provider.usageLimits,
},
);
@@ -253,7 +261,7 @@ export function collectLimitAccounts(
// may hold a fresher read of the same subscription, and the merge above
// keeps the redeem target consistent with whichever snapshot wins.
const labelEnvironment = presentations.size > 1;
- for (const presentation of presentations.values()) {
+ for (const [environmentId, presentation] of presentations) {
for (const source of presentation.serverConfig?.usageLimitSources ?? []) {
const sourceLabel = labelEnvironment
? `${presentation.entry.target.label} · ${source.label}`
@@ -269,7 +277,16 @@ export function collectLimitAccounts(
accentColor: undefined,
environments: [],
sourceLabel,
- redeem: null,
+ redeem: account.usageLimits.resetCredits?.nextCreditId
+ ? {
+ environmentId,
+ input: {
+ sourceId: source.id,
+ accountId: account.id,
+ creditId: account.usageLimits.resetCredits.nextCreditId,
+ },
+ }
+ : null,
limits: account.usageLimits,
});
}
@@ -614,16 +631,48 @@ export function collectProviderUsageLimits(
const notices: string[] = [];
for (const provider of native) {
if (!provider.usageLimits) continue;
+ const key = accountKey(provider.driver, provider.auth.email);
+ const hubCredits = sources
+ .flatMap((source) => source.accounts.map((account) => ({ source, account })))
+ .filter(
+ ({ account }) =>
+ key !== null &&
+ accountKey(account.driver, account.email) === key &&
+ account.usageLimits.resetCredits &&
+ !limitsNotice(account.usageLimits),
+ )
+ .sort(
+ (a, b) =>
+ Date.parse(b.account.usageLimits.checkedAt) - Date.parse(a.account.usageLimits.checkedAt),
+ )[0];
+ const useHubCredits =
+ hubCredits &&
+ (!provider.usageLimits.resetCredits ||
+ Date.parse(hubCredits.account.usageLimits.checkedAt) >
+ Date.parse(provider.usageLimits.checkedAt));
+ const hubCreditId = useHubCredits
+ ? hubCredits.account.usageLimits.resetCredits?.nextCreditId
+ : undefined;
accounts.push({
id: provider.instanceId,
driver: provider.driver,
label: `${provider.displayName?.trim() || String(provider.driver)} [${provider.instanceId}]`,
...(provider.auth.label ? { plan: provider.auth.label } : {}),
instanceId: provider.instanceId,
+ resetCreditInput:
+ hubCreditId && hubCredits
+ ? {
+ sourceId: hubCredits.source.id,
+ accountId: hubCredits.account.id,
+ creditId: hubCreditId,
+ }
+ : { instanceId: provider.instanceId },
...(provider.displayName ? { displayName: provider.displayName } : {}),
...(provider.accentColor ? { accentColor: provider.accentColor } : {}),
...(provider.auth.email ? { email: provider.auth.email } : {}),
- limits: provider.usageLimits,
+ limits: useHubCredits
+ ? { ...provider.usageLimits, resetCredits: hubCredits.account.usageLimits.resetCredits }
+ : provider.usageLimits,
});
}
for (const source of sources) {
@@ -636,6 +685,15 @@ export function collectProviderUsageLimits(
driver: account.driver,
label: `${source.label} · ${account.id}`,
sourceLabel: "CLI Proxy",
+ ...(account.usageLimits.resetCredits?.nextCreditId
+ ? {
+ resetCreditInput: {
+ sourceId: source.id,
+ accountId: account.id,
+ creditId: account.usageLimits.resetCredits.nextCreditId,
+ },
+ }
+ : {}),
...(account.plan ? { plan: account.plan } : {}),
...(account.email ? { email: account.email } : {}),
limits: account.usageLimits,