@devries-cameron20 / t3code Mirror · read-only / commits / 44ebb2fe57
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 00:45 UTC

feat(usage): show Muse Code limits, and xAI and Antigravity accounts from a CLIProxyAPI hub (#33800)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 10, 2026 at 22:36 UTC 44ebb2fe57465d32f2bd07c5eb3d8e871bdf5ed5
21 files changed +1201 -217
apps/mobile/src/features/threads/ComposerUsageLimits.tsx
+2 -3
@@ -1,3 +1,4 @@
1 +import { providerClients } from "@t3tools/client-runtime/provider-clients";
2 import type { EnvironmentId, UsageLimitsReport } from "@t3tools/contracts";
3 import { Pressable, ScrollView, View } from "react-native";
4
@@ -5,8 +6,6 @@ import { SymbolView } from "../../components/ui/AppSymbol";
6 import { AppText as Text } from "../../components/ui/AppText";
7 import { AccountLimits, ResetCredits } from "../usage/UsageLimitsSection";
8
8 -const DRIVER_LABEL: Partial<Record<string, string>> = { codex: "Codex", claudeAgent: "Claude" };
9 -
9 export function ComposerUsageLimits({
10 report,
11 environmentId,
@@ -37,7 +36,7 @@ export function ComposerUsageLimits({
36 const resetCreditInput =
37 account.resetCreditInput ??
38 (account.instanceId ? { instanceId: account.instanceId } : undefined);
40 - const driverLabel = DRIVER_LABEL[account.driver] ?? String(account.driver);
39 + const driverLabel = providerClients.get(account.driver)?.label ?? account.driver;
40 return (
41 <AccountLimits
42 key={account.id}
apps/mobile/src/features/usage/UsageLimitsPooled.tsx
+6 -9
@@ -1,6 +1,7 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3 import { EnvironmentId } from "@t3tools/contracts";
4 +import { providerClients } from "@t3tools/client-runtime/provider-clients";
5 import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display";
6 import {
7 collectLimitAccounts,
@@ -29,17 +30,11 @@ import { environmentPresentations } from "../../state/presentation";
30 import { ResetCredits } from "./UsageLimitsSection";
31 import { usageProviderKind, useProviderColors } from "./usageProviders";
32
32 -const DRIVER_LABEL: Partial<Record<string, string>> = {
33 - codex: "Codex",
34 - claudeAgent: "Claude",
35 - grok: "Grok",
36 - antigravity: "Antigravity",
37 -};
33 const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const;
34
35 function accountName(account: LimitAccount) {
36 if (account.displayName) return account.displayName;
42 - if (!account.email) return DRIVER_LABEL[account.driver] ?? String(account.driver);
37 + if (!account.email) return providerClients.get(account.driver)?.label ?? account.driver;
38 return emailInitials(account.email) || "Account";
39 }
40
@@ -444,7 +439,7 @@ export function UsageLimitsSection({
439 <View className="flex-row items-center gap-2 px-1">
440 <ProviderIcon provider={pool.driver} size={18} />
441 <Text className="text-base font-t3-medium text-foreground">
447 - {DRIVER_LABEL[pool.driver] ?? pool.driver}
442 + {providerClients.get(pool.driver)?.label ?? pool.driver}
443 </Text>
444 </View>
445 {windows.map((window) => {
@@ -559,7 +554,9 @@ export function UsageLimitAccountScreen({ route }: AccountScreenProps) {
554 <View className="flex-row items-center gap-2">
555 <ProviderIcon provider={account.driver} size={24} />
556 <Text className="flex-1 text-xl font-t3-bold text-foreground">
562 - {account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver}
557 + {account.displayName ??
558 + providerClients.get(account.driver)?.label ??
559 + account.driver}
560 </Text>
561 </View>
562 {account.email ? (
apps/server/src/provider/antigravityUsageLimits.ts
+24 -15
@@ -15,6 +15,10 @@ import {
15 makeUsageLimits,
16 } from "@t3tools/provider-core/server/usageLimits";
17
18 +export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) {
19 + return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;
20 +}
21 +
22 const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
23 const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
24 // The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod.
@@ -120,6 +124,22 @@ function summaryResetTime(
124 return untouched ? undefined : bucket.resetTime;
125 }
126
127 +const sha256 = Effect.fnUntraced(function* (text: string) {
128 + const digest = yield* (yield* Digest.Digest).digest(
129 + Digest.sha256,
130 + new TextEncoder().encode(text),
131 + );
132 + return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
133 +});
134 +
135 +/** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */
136 +export const antigravityAccountFingerprint = (userInfo: unknown) =>
137 + decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`)));
138 +
139 +/** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */
140 +export const antigravitySummaryWindows = (response: unknown, requestedAt: number) =>
141 + decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt)));
142 +
143 function summaryWindows(summary: typeof Summary.Type, requestedAt: number) {
144 const windows = new Map<string, ServerProviderUsageWindow>();
145 const groups = summary.groups?.some((group) => group.buckets?.length)
@@ -203,15 +223,6 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
223 | undefined;
224 let generation = 0;
225
206 - const sha256 = (text: string) =>
207 - crypto
208 - .digest(Digest.sha256, new TextEncoder().encode(text))
209 - .pipe(
210 - Effect.map((digest) =>
211 - Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""),
212 - ),
213 - );
214 -
226 const request = (request: HttpClientRequest.HttpClientRequest) =>
227 client.execute(request).pipe(
228 Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
@@ -259,8 +270,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
270 HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
271 ),
272 ).pipe(
262 - Effect.flatMap(decodeUserInfo),
263 - Effect.flatMap((info) => sha256(`google-account\0${info.id}`)),
273 + Effect.flatMap(antigravityAccountFingerprint),
274 Effect.orElseSucceed(() => fingerprint),
275 );
276 if (generation === startedGeneration) {
@@ -294,7 +304,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
304 HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
305 HttpClientRequest.setHeaders({
306 Authorization: `Bearer ${accessToken}`,
297 - "User-Agent": `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`,
307 + "User-Agent": antigravityUserAgent(platform, architecture),
308 }),
309 HttpClientRequest.bodyJsonUnsafe(
310 token.project_id ? { project: token.project_id } : {},
@@ -313,9 +323,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
323 }
324 return [...windows.values()];
325 });
316 - const summary = yield* fetchWindows("retrieveUserQuotaSummary", (response, requestedAt) =>
317 - decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))),
318 - );
326 + const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows);
327 const windows = summary.length
328 ? summary
329 : yield* fetchWindows("fetchAvailableModels", (response) =>
@@ -331,6 +339,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(
339 return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account };
340 });
341 const probe = read.pipe(
342 + Effect.provideService(Digest.Digest, crypto),
343 Effect.timeout("30 seconds"),
344 Effect.catch(() =>
345 Effect.gen(function* () {
apps/server/src/usage/cliproxyApi.test.ts
+192 -6
@@ -1,4 +1,5 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 +import * as HostProcess from "@t3tools/shared/HostProcess";
3 import { describe, expect, it } from "@effect/vitest";
4 import * as Effect from "effect/Effect";
5 import * as Schema from "effect/Schema";
@@ -48,12 +49,15 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
49
50 function fixture(
51 options: {
51 - accounts?: Array<
52 - (typeof accounts)[number] & {
53 - disabled?: boolean;
54 - id_token: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
55 - }
56 - >;
52 + accounts?: Array<{
53 + id: string;
54 + auth_index: string;
55 + provider: string;
56 + email?: string;
57 + disabled?: boolean;
58 + project_id?: string;
59 + id_token?: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string };
60 + }>;
61 upstream?: (request: RequestBody) => { status: number; body: unknown };
62 cooldownStatus?: number;
63 } = {},
@@ -433,6 +437,188 @@ describe("CLIProxyAPI built-in management API", () => {
437 }),
438 );
439
440 + const antigravitySummary = {
441 + buckets: [
442 + {
443 + bucketId: "gemini-weekly",
444 + window: "weekly",
445 + remainingFraction: 0.75,
446 + resetTime: "2099-01-01T00:00:00Z",
447 + },
448 + ],
449 + };
450 +
451 + it.effect("reads an xAI account as Grok with Grok CLI headers", () =>
452 + Effect.gen(function* () {
453 + const test = fixture({
454 + accounts: [{ id: "xai.json", auth_index: "x", provider: "xai", email: "x@example.com" }],
455 + upstream: () => ({
456 + status: 200,
457 + body: {
458 + config: {
459 + creditUsagePercent: 40,
460 + currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: "2099-01-01T00:00:00Z" },
461 + },
462 + },
463 + }),
464 + });
465 + const [account] = yield* (yield* test.api).readAccounts(config);
466 + expect(account).toMatchObject({ driver: "grok", email: "x@example.com" });
467 + expect(account?.usageLimits.windows).toMatchObject([
468 + { id: "subscription", kind: "weekly", usedPercent: 40 },
469 + ]);
470 + const call = test.requests.find((request) => request.body?.url)?.body;
471 + expect(call?.method).toBe("GET");
472 + expect(call?.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits");
473 + expect(call?.header).toMatchObject({
474 + "x-xai-token-auth": "xai-grok-cli",
475 + "x-grok-client-version": expect.any(String),
476 + "User-Agent": expect.stringMatching(/^grok-cli\//),
477 + });
478 + }),
479 + );
480 +
481 + it.effect("reads an Antigravity summary and keys the account by its Google ID", () =>
482 + Effect.gen(function* () {
483 + const test = fixture({
484 + accounts: [
485 + {
486 + id: "antigravity-g@example.com.json",
487 + auth_index: "g",
488 + provider: "antigravity",
489 + email: "g@example.com",
490 + project_id: "project-7",
491 + },
492 + ],
493 + upstream: (request) => ({
494 + status: 200,
495 + body: request.url?.endsWith("/userinfo") ? { id: "google-42" } : antigravitySummary,
496 + }),
497 + });
498 + const [account] = yield* (yield* test.api).readAccounts(config);
499 + expect(account?.driver).toBe("antigravity");
500 + expect(account?.email).toBeUndefined();
501 + expect(account?.usageLimits.credentialFingerprint).toBe(
502 + // sha256("google-account\0google-42"), as a local Antigravity probe reports it.
503 + "136d4952771fd67a3600053f37492cbd05828712e0b1c89ebab03d4c22ab6554",
504 + );
505 + expect(account?.usageLimits.windows).toMatchObject([
506 + { id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
507 + ]);
508 + const summary = test.requests.find((request) => request.body?.method === "POST")?.body;
509 + expect(summary?.url).toBe(
510 + "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
511 + );
512 + expect(summary?.data).toBe(encodeJson({ project: "project-7" }));
513 + expect(summary).toMatchObject({
514 + auth_index: "g",
515 + method: "POST",
516 + header: {
517 + Authorization: "Bearer $TOKEN$",
518 + "Content-Type": "application/json",
519 + "User-Agent":
520 + "antigravity/hub/2.24.0 (aidev_client; os_type=linux; arch=x64; cl=963137146)",
521 + },
522 + });
523 + const identityCalls = test.requests.filter((request) =>
524 + request.body?.url?.endsWith("/userinfo"),
525 + );
526 + expect(identityCalls).toHaveLength(1);
527 + expect(identityCalls[0]?.body).toMatchObject({
528 + method: "GET",
529 + url: "https://www.googleapis.com/oauth2/v2/userinfo",
530 + header: { Authorization: "Bearer $TOKEN$" },
531 + });
532 + }).pipe(
533 + Effect.provideService(HostProcess.Platform, "linux"),
534 + Effect.provideService(HostProcess.Architecture, "x64"),
535 + ),
536 + );
537 +
538 + it.effect("keeps Antigravity limits and listing email when its identity read fails", () =>
539 + Effect.gen(function* () {
540 + const test = fixture({
541 + accounts: [
542 + {
543 + id: "antigravity.json",
544 + auth_index: "g",
545 + provider: "antigravity",
546 + email: "g@example.com",
547 + project_id: "project-7",
548 + },
549 + ],
550 + upstream: (request) =>
551 + request.url?.endsWith("/userinfo")
552 + ? { status: 403, body: { error: "denied" } }
553 + : {
554 + status: 200,
555 + body: antigravitySummary,
556 + },
557 + });
558 + const result = yield* (yield* test.api).readAccounts(config);
559 + expect(result).toHaveLength(1);
560 + const [account] = result;
561 + expect(account).toMatchObject({ driver: "antigravity", email: "g@example.com" });
562 + expect(account?.usageLimits.credentialFingerprint).toBeUndefined();
563 + expect(account?.usageLimits.unavailable).toBeUndefined();
564 + expect(account?.usageLimits.windows).toMatchObject([
565 + { id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
566 + ]);
567 + }),
568 + );
569 +
570 + it.effect.each([
571 + { name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } },
572 + { name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } },
573 + { name: "a refused Antigravity call", provider: "antigravity", status: 401, body: {} },
574 + { name: "a malformed Antigravity answer", provider: "antigravity", status: 200, body: [] },
575 + { name: "an empty Antigravity summary", provider: "antigravity", status: 200, body: {} },
576 + ])("reports $name as unreadable", ({ provider, status, body }) =>
577 + Effect.gen(function* () {
578 + const test = fixture({
579 + accounts: [{ id: `${provider}.json`, auth_index: "a", provider, project_id: "project-7" }],
580 + upstream: () => ({ status, body }),
581 + });
582 + const [account] = yield* (yield* test.api).readAccounts(config);
583 + expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
584 + }),
585 + );
586 +
587 + it.effect.each([undefined, "", " "])(
588 + "rejects a missing or blank Antigravity project (%s) before upstream calls",
589 + (project_id) =>
590 + Effect.gen(function* () {
591 + const test = fixture({
592 + accounts: [
593 + {
594 + id: "antigravity.json",
595 + auth_index: "a",
596 + provider: "antigravity",
597 + ...(project_id === undefined ? {} : { project_id }),
598 + },
599 + ],
600 + });
601 + const [account] = yield* (yield* test.api).readAccounts(config);
602 + expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
603 + expect(test.requests.map((request) => request.path)).toEqual(["/v0/management/auth-files"]);
604 + }),
605 + );
606 +
607 + it.effect("skips accounts of providers the hub table does not know", () =>
608 + Effect.gen(function* () {
609 + const test = fixture({
610 + accounts: [
611 + { id: "kiro.json", auth_index: "k", provider: "kiro", email: "k@example.com" },
612 + { ...accounts[0]!, provider: "claude" },
613 + ],
614 + upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }),
615 + });
616 + const result = yield* (yield* test.api).readAccounts(config);
617 + expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]);
618 + expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k");
619 + }),
620 + );
621 +
622 it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () =>
623 Effect.gen(function* () {
624 const test = fixture();
apps/server/src/usage/cliproxyApi.ts
+254 -137
@@ -5,18 +5,33 @@ import {
5 type UsageLimitSourceAccount,
6 type UsageLimitSourceConfig,
7 } from "@t3tools/contracts";
8 +import * as HostProcess from "@t3tools/shared/HostProcess";
9 import * as Cause from "effect/Cause";
10 import * as Digest from "effect/crypto/Digest";
11 import * as DateTime from "effect/DateTime";
12 import * as Effect from "effect/Effect";
13 import * as Hex from "effect/encoding/Hex";
14 +import * as Option from "effect/Option";
15 import * as Schema from "effect/Schema";
16 import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
17
18 +import {
19 + GROK_USAGE_URL,
20 + GrokUsageResponse,
21 + grokUsageResponseToLimits,
22 +} from "@t3tools/provider-grok/server";
23 import { codexPlanLabel } from "../provider/CodexProvider.ts";
24 import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
25 import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts";
19 -import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
26 +import {
27 + antigravityAccountFingerprint,
28 + antigravitySummaryWindows,
29 + antigravityUserAgent,
30 +} from "../provider/antigravityUsageLimits.ts";
31 +import {
32 + makeUnavailableUsageLimits,
33 + makeUsageLimits,
34 +} from "@t3tools/provider-core/server/usageLimits";
35
36 /** A hub with its management key already read from wherever the setting keeps it. */
37 export interface CliproxyHub {
@@ -30,6 +45,7 @@ const AuthFile = Schema.Struct({
45 provider: Schema.String,
46 email: Schema.optional(Schema.String),
47 disabled: Schema.optional(Schema.Boolean),
48 + project_id: Schema.optional(Schema.String),
49 id_token: Schema.optional(
50 Schema.Struct({
51 chatgpt_account_id: Schema.optional(Schema.String),
@@ -106,6 +122,8 @@ const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse);
122 const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList));
123 const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
124 const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
125 +const decodeGrokUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(GrokUsageResponse));
126 +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
127 const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
128
129 // Extra CAs can fix untrusted chains; expiry/hostname failures report codes only.
@@ -174,9 +192,216 @@ const creditRedeemRequestId = Effect.fn("CliproxyApi.creditRedeemRequestId")(fun
192 return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
193 });
194
195 +type AuthFile = typeof AuthFile.Type;
196 +/** Sends one upstream request with the account's token, as GET or as a JSON POST of `data`. */
197 +type HubCall = (
198 + url: string,
199 + data?: unknown,
200 +) => Effect.Effect<string, UsageLimitSourceError | Schema.SchemaError>;
201 +type HubReading = Omit<UsageLimitSourceAccount, "id" | "driver">;
202 +interface HubProvider {
203 + readonly driver: ProviderDriverKind;
204 + readonly header: (
205 + account: AuthFile,
206 + platform: NodeJS.Platform,
207 + architecture: NodeJS.Architecture,
208 + ) => Record<string, string>;
209 + readonly read: (input: {
210 + readonly account: AuthFile;
211 + readonly call: HubCall;
212 + readonly checkedAt: string;
213 + }) => Effect.Effect<HubReading, UsageLimitSourceError | Schema.SchemaError, Digest.Digest>;
214 +}
215 +
216 +const listedIdentity = (account: AuthFile) => ({
217 + ...(account.email ? { email: account.email } : {}),
218 + ...(account.id_token?.chatgpt_account_id?.trim()
219 + ? { workspaceId: account.id_token.chatgpt_account_id.trim() }
220 + : {}),
221 +});
222 +
223 +const credits = Effect.fn("CliproxyApi.credits")(function* (call: HubCall) {
224 + const response = yield* decodeCreditList(yield* call(CREDIT_URL));
225 + const now = DateTime.toEpochMillis(yield* DateTime.now);
226 + return response.credits
227 + .filter(
228 + (credit) =>
229 + credit.reset_type === "codex_rate_limits" &&
230 + credit.status === "available" &&
231 + Date.parse(credit.expires_at) > now,
232 + )
233 + .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
234 +});
235 +
236 +const CODEX_HUB: HubProvider = {
237 + driver: ProviderDriverKind.make("codex"),
238 + header: (account) => ({
239 + Authorization: "Bearer $TOKEN$",
240 + "Content-Type": "application/json",
241 + "OpenAI-Beta": "codex-1",
242 + Originator: "Codex Desktop",
243 + ...(account.id_token?.chatgpt_account_id
244 + ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
245 + : {}),
246 + }),
247 + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
248 + const usage = yield* decodeCodexUsage(yield* call(`${CODEX_BASE}/usage`));
249 + const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
250 + window
251 + ? {
252 + usedPercent: window.used_percent,
253 + resetsAt: window.reset_at ?? null,
254 + ...(window.limit_window_seconds === undefined
255 + ? {}
256 + : { windowDurationMins: window.limit_window_seconds / 60 }),
257 + }
258 + : null;
259 + const available = yield* credits(call).pipe(Effect.orElseSucceed(() => undefined));
260 + const next = available?.[0];
261 + const planType =
262 + usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type;
263 + return {
264 + ...listedIdentity(account),
265 + plan: codexPlanLabel(planType),
266 + usageLimits: {
267 + ...codexRateLimitsToLimits({
268 + checkedAt,
269 + snapshot: {
270 + planType: planType ?? null,
271 + primary: toWindow(usage.rate_limit?.primary_window),
272 + secondary: toWindow(usage.rate_limit?.secondary_window),
273 + },
274 + }),
275 + ...(available
276 + ? {
277 + resetCredits: {
278 + availableCount: available.length,
279 + ...(next
280 + ? {
281 + nextCreditId: next.id,
282 + nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
283 + }
284 + : {}),
285 + },
286 + }
287 + : {}),
288 + },
289 + };
290 + }),
291 +};
292 +
293 +const GROK_CLI_VERSION = "1.0.77";
294 +const ANTIGRAVITY_SUMMARY_URL =
295 + "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary";
296 +
297 +// Keyed by the auth-files `provider`; accounts of any other provider are skipped.
298 +const HUB_PROVIDERS = new Map<string, HubProvider>([
299 + ["codex", CODEX_HUB],
300 + [
301 + "claude",
302 + {
303 + driver: ProviderDriverKind.make("claudeAgent"),
304 + header: () => ({
305 + Authorization: "Bearer $TOKEN$",
306 + "anthropic-beta": "oauth-2025-04-20",
307 + // The OAuth usage endpoint can return 429 without a Claude Code user agent.
308 + "User-Agent": "claude-code/2.1.273",
309 + }),
310 + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
311 + const usage = yield* decodeClaudeUsage(
312 + yield* call("https://api.anthropic.com/api/oauth/usage"),
313 + );
314 + const model_scoped = (usage.limits ?? []).flatMap((limit) =>
315 + limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
316 + ? [
317 + {
318 + display_name: limit.scope.model.display_name,
319 + utilization: limit.percent,
320 + resets_at: limit.resets_at ?? null,
321 + },
322 + ]
323 + : [],
324 + );
325 + const rateLimits = {
326 + five_hour: usage.five_hour ?? null,
327 + seven_day: usage.seven_day ?? null,
328 + model_scoped,
329 + spend: usage.spend,
330 + extra_usage: usage.extra_usage ?? null,
331 + };
332 + return {
333 + ...listedIdentity(account),
334 + plan: "Claude Subscription",
335 + usageLimits: claudeUsageResponseToLimits({
336 + checkedAt,
337 + response: { rate_limits_available: true, rate_limits: rateLimits },
338 + }).limits,
339 + };
340 + }),
341 + },
342 + ],
343 + [
344 + "xai",
345 + {
346 + driver: ProviderDriverKind.make("grok"),
347 + header: () => ({
348 + Authorization: "Bearer $TOKEN$",
349 + "x-xai-token-auth": "xai-grok-cli",
350 + "x-grok-client-version": GROK_CLI_VERSION,
351 + "User-Agent": `grok-cli/${GROK_CLI_VERSION}`,
352 + }),
353 + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
354 + const usage = yield* decodeGrokUsage(yield* call(GROK_USAGE_URL));
355 + return {
356 + ...listedIdentity(account),
357 + usageLimits: grokUsageResponseToLimits(usage, checkedAt),
358 + };
359 + }),
360 + },
361 + ],
362 + [
363 + "antigravity",
364 + {
365 + driver: ProviderDriverKind.make("antigravity"),
366 + header: (_account, platform, architecture) => ({
367 + Authorization: "Bearer $TOKEN$",
368 + "Content-Type": "application/json",
369 + "User-Agent": antigravityUserAgent(platform, architecture),
370 + }),
371 + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
372 + const project = account.project_id?.trim();
373 + if (!project) {
374 + return yield* new UsageLimitSourceError({ detail: "No Antigravity project reported." });
375 + }
376 + const requestedAt = DateTime.toEpochMillis(yield* DateTime.now);
377 + const summary = yield* call(ANTIGRAVITY_SUMMARY_URL, { project });
378 + const windows = yield* antigravitySummaryWindows(yield* decodeJson(summary), requestedAt);
379 + if (windows.length === 0) {
380 + return yield* new UsageLimitSourceError({ detail: "No Antigravity quota reported." });
381 + }
382 + // Local Antigravity reports no e-mail, so the Google account fingerprint is what pools the two.
383 + const fingerprint = yield* call("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
384 + Effect.flatMap(decodeJson),
385 + Effect.flatMap(antigravityAccountFingerprint),
386 + Effect.option,
387 + );
388 + const usageLimits = makeUsageLimits({ checkedAt, windows });
389 + return Option.match(fingerprint, {
390 + onNone: () => ({ ...listedIdentity(account), usageLimits }),
391 + onSome: (credentialFingerprint) => ({
392 + usageLimits: { ...usageLimits, credentialFingerprint },
393 + }),
394 + });
395 + }),
396 + },
397 + ],
398 +]);
399 +
400 export const makeCliproxyApi = Effect.gen(function* () {
401 const client = yield* HttpClient.HttpClient;
402 const digest = yield* Digest.Digest;
403 + const platform = yield* HostProcess.Platform;
404 + const architecture = yield* HostProcess.Architecture;
405
406 const management = Effect.fn("CliproxyApi.management")(function* (
407 hub: CliproxyHub,
@@ -215,27 +440,11 @@ export const makeCliproxyApi = Effect.gen(function* () {
440
441 const apiCall = Effect.fn("CliproxyApi.apiCall")(function* (
442 hub: CliproxyHub,
218 - account: typeof AuthFile.Type,
443 + account: AuthFile,
444 + header: Record<string, string>,
445 url: string,
446 data?: unknown,
447 ) {
222 - const header =
223 - account.provider === "codex"
224 - ? {
225 - Authorization: "Bearer $TOKEN$",
226 - "Content-Type": "application/json",
227 - "OpenAI-Beta": "codex-1",
228 - Originator: "Codex Desktop",
229 - ...(account.id_token?.chatgpt_account_id
230 - ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id }
231 - : {}),
232 - }
233 - : {
234 - Authorization: "Bearer $TOKEN$",
235 - "anthropic-beta": "oauth-2025-04-20",
236 - // The OAuth usage endpoint can return 429 without a Claude Code user agent.
237 - "User-Agent": "claude-code/2.1.273",
238 - };
448 const raw = yield* management(hub, "api-call", {
449 auth_index: account.auth_index,
450 method: data === undefined ? "GET" : "POST",
@@ -252,117 +461,18 @@ export const makeCliproxyApi = Effect.gen(function* () {
461 return response.body;
462 });
463
255 - const credits = Effect.fn("CliproxyApi.credits")(function* (
256 - hub: CliproxyHub,
257 - account: typeof AuthFile.Type,
258 - ) {
259 - const body = yield* apiCall(hub, account, CREDIT_URL);
260 - const response = yield* decodeCreditList(body);
261 - const now = DateTime.toEpochMillis(yield* DateTime.now);
262 - return response.credits
263 - .filter(
264 - (credit) =>
265 - credit.reset_type === "codex_rate_limits" &&
266 - credit.status === "available" &&
267 - Date.parse(credit.expires_at) > now,
268 - )
269 - .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));
270 - });
271 -
464 const readAccount = Effect.fn("CliproxyApi.readAccount")(function* (
465 hub: CliproxyHub,
274 - account: typeof AuthFile.Type,
466 + account: AuthFile,
467 + provider: HubProvider,
468 ) {
469 const checkedAt = DateTime.formatIso(yield* DateTime.now);
277 - const base = {
278 - id: account.id,
279 - driver: ProviderDriverKind.make(account.provider === "codex" ? "codex" : "claudeAgent"),
280 - ...(account.email ? { email: account.email } : {}),
281 - ...(account.id_token?.chatgpt_account_id?.trim()
282 - ? { workspaceId: account.id_token.chatgpt_account_id.trim() }
283 - : {}),
284 - };
285 - const read = Effect.gen(function* () {
286 - if (account.provider === "claude") {
287 - const body = yield* apiCall(hub, account, "https://api.anthropic.com/api/oauth/usage");
288 - const usage = yield* decodeClaudeUsage(body);
289 - const model_scoped = (usage.limits ?? []).flatMap((limit) =>
290 - limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number"
291 - ? [
292 - {
293 - display_name: limit.scope.model.display_name,
294 - utilization: limit.percent,
295 - resets_at: limit.resets_at ?? null,
296 - },
297 - ]
298 - : [],
299 - );
300 - const rateLimits = {
301 - five_hour: usage.five_hour ?? null,
302 - seven_day: usage.seven_day ?? null,
303 - model_scoped,
304 - spend: usage.spend,
305 - extra_usage: usage.extra_usage ?? null,
306 - };
307 - return {
308 - ...base,
309 - plan: "Claude Subscription",
310 - usageLimits: claudeUsageResponseToLimits({
311 - checkedAt,
312 - response: {
313 - rate_limits_available: true,
314 - rate_limits: rateLimits,
315 - },
316 - }).limits,
317 - };
318 - }
319 - const body = yield* apiCall(hub, account, `${CODEX_BASE}/usage`);
320 - const usage = yield* decodeCodexUsage(body);
321 - const toWindow = (window: typeof CodexWindow.Type | null | undefined) =>
322 - window
323 - ? {
324 - usedPercent: window.used_percent,
325 - resetsAt: window.reset_at ?? null,
326 - ...(window.limit_window_seconds === undefined
327 - ? {}
328 - : { windowDurationMins: window.limit_window_seconds / 60 }),
329 - }
330 - : null;
331 - const available = yield* credits(hub, account).pipe(Effect.orElseSucceed(() => undefined));
332 - const next = available?.[0];
333 - const planType =
334 - usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type;
335 - return {
336 - ...base,
337 - plan: codexPlanLabel(planType),
338 - usageLimits: {
339 - ...codexRateLimitsToLimits({
340 - checkedAt,
341 - snapshot: {
342 - planType: planType ?? null,
343 - primary: toWindow(usage.rate_limit?.primary_window),
344 - secondary: toWindow(usage.rate_limit?.secondary_window),
345 - },
346 - }),
347 - ...(available
348 - ? {
349 - resetCredits: {
350 - availableCount: available.length,
351 - ...(next
352 - ? {
353 - nextCreditId: next.id,
354 - nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)),
355 - }
356 - : {}),
357 - },
358 - }
359 - : {}),
360 - },
361 - };
362 - });
363 - return yield* read.pipe(
470 + const call: HubCall = (url, data) =>
471 + apiCall(hub, account, provider.header(account, platform, architecture), url, data);
472 + const reading = yield* provider.read({ account, call, checkedAt }).pipe(
473 + Effect.provideService(Digest.Digest, digest),
474 Effect.orElseSucceed(() => ({
365 - ...base,
475 + ...listedIdentity(account),
476 usageLimits: makeUnavailableUsageLimits({
477 checkedAt,
478 reason: "probeFailed",
@@ -370,6 +480,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
480 }),
481 })),
482 );
483 + return { id: account.id, driver: provider.driver, ...reading };
484 });
485
486 const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
@@ -383,11 +494,11 @@ export const makeCliproxyApi = Effect.gen(function* () {
494 ),
495 );
496 return yield* Effect.forEach(
386 - accounts.filter(
387 - (account) =>
388 - !account.disabled && (account.provider === "codex" || account.provider === "claude"),
389 - ),
390 - (account) => readAccount(hub, account),
497 + accounts.flatMap((account) => {
498 + const provider = HUB_PROVIDERS.get(account.provider);
499 + return provider && !account.disabled ? [{ account, provider }] : [];
500 + }),
501 + ({ account, provider }) => readAccount(hub, account, provider),
502 { concurrency: 4 },
503 );
504 });
@@ -404,13 +515,19 @@ export const makeCliproxyApi = Effect.gen(function* () {
515 detail: "The Codex hub account is missing or disabled.",
516 });
517 }
407 - const body = yield* apiCall(hub, account, `${CREDIT_URL}/consume`, {
408 - redeem_request_id: yield* creditRedeemRequestId(
409 - account.id_token?.chatgpt_account_id ?? account.id,
410 - creditId,
411 - ).pipe(Effect.provideService(Digest.Digest, digest)),
412 - credit_id: creditId,
413 - });
518 + const body = yield* apiCall(
519 + hub,
520 + account,
521 + CODEX_HUB.header(account, platform, architecture),
522 + `${CREDIT_URL}/consume`,
523 + {
524 + redeem_request_id: yield* creditRedeemRequestId(
525 + account.id_token?.chatgpt_account_id ?? account.id,
526 + creditId,
527 + ).pipe(Effect.provideService(Digest.Digest, digest)),
528 + credit_id: creditId,
529 + },
530 + );
531 const response = yield* decodeConsumeResponse(body);
532 const outcome = (
533 {
apps/web/test/fixtures/usage-limits-hub/README.md
+12 -9
@@ -2,15 +2,18 @@
2
3 A fake CLIProxyAPI hub that serves the Limits evidence scenarios in `scenarios.json`:
4
5 -| Scenario | Accounts |
6 -| -------- | -------------------------------------------------------------- |
7 -| A | mixed Codex and Claude accounts |
8 -| B | one account per provider |
9 -| C | six long-email Codex accounts |
10 -| L | named accounts (no email, so segments show the auth-file name) |
11 -| T | forty accounts, so pooled segments are 4px wide at 390px |
12 -
13 -Reset times are minute offsets from `n0`.
5 +| Scenario | Accounts |
6 +| -------- | ------------------------------------------------------------------------ |
7 +| A | mixed Codex and Claude accounts |
8 +| B | one account per provider |
9 +| C | six long-email Codex accounts |
10 +| F | xAI and Antigravity accounts that read, answer malformed, or are refused |
11 +| L | named accounts (no email, so segments show the auth-file name) |
12 +| P | one account per read hub provider, plus an unread Kiro account |
13 +| T | forty accounts, so pooled segments are 4px wide at 390px |
14 +
15 +Reset times are minute offsets from `n0`. An account's `state` of `malformed` or `refused` makes
16 +its usage unreadable, so Limits leaves it out.
17
18 ## Rebuild a capture
19
apps/web/test/fixtures/usage-limits-hub/hub.mjs
+34 -1
@@ -13,8 +13,29 @@ const MINUTE = 60_000;
13
14 // A window is [usedPercent, minutesFromN0 | null]; null is unknown reset timing.
15 const at = (n0, minutes) => (minutes === null ? null : n0 + minutes * MINUTE);
16 +const iso = (n0, minutes) =>
17 + minutes === null ? undefined : new Date(at(n0, minutes)).toISOString();
18 const usage = (account, n0) => {
19 const [session, weekly, fable] = account.windows;
20 + if (account.provider === "xai") {
21 + return {
22 + config: {
23 + creditUsagePercent: session[0],
24 + currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: iso(n0, session[1]) },
25 + },
26 + };
27 + }
28 + if (account.provider === "antigravity") {
29 + const bucket = (bucketId, window, [used, minutes]) => ({
30 + bucketId,
31 + window,
32 + remainingFraction: 1 - used / 100,
33 + resetTime: iso(n0, minutes),
34 + });
35 + return {
36 + buckets: [bucket("gemini-5h", "5h", session), bucket("gemini-weekly", "weekly", weekly)],
37 + };
38 + }
39 if (account.provider === "codex") {
40 const window = ([used, minutes], seconds) => ({
41 used_percent: used,
@@ -68,6 +89,7 @@ NodeHttp.createServer((request, response) => {
89 auth_index: id,
90 provider: account.provider,
91 ...(account.email ? { email: account.email } : {}),
92 + ...(account.project_id ? { project_id: account.project_id } : {}),
93 })),
94 });
95 }
@@ -75,6 +97,13 @@ NodeHttp.createServer((request, response) => {
97 const call = JSON.parse(raw);
98 const account = accounts[call.auth_index];
99 if (!account) return json(response, { status_code: 404, body: "{}" });
100 + // "refused" fails every upstream call; "malformed" answers the usage call with the wrong shape.
101 + if (account.state === "refused") {
102 + return json(response, { status_code: 403, body: JSON.stringify({ error: "refused" }) });
103 + }
104 + if (call.url.endsWith("/userinfo")) {
105 + return json(response, { status_code: 200, body: JSON.stringify({ id: call.auth_index }) });
106 + }
107 if (call.url.endsWith("/rate-limit-reset-credits")) {
108 const credits = Array.from({ length: account.credits ?? 0 }, (_, index) => ({
109 id: `${call.auth_index}-credit-${index}`,
@@ -84,7 +113,11 @@ NodeHttp.createServer((request, response) => {
113 }));
114 return json(response, { status_code: 200, body: JSON.stringify({ credits }) });
115 }
87 - return json(response, { status_code: 200, body: JSON.stringify(usage(account, n0)) });
116 + const body =
117 + account.state === "malformed"
118 + ? { config: "malformed", buckets: "malformed" }
119 + : usage(account, n0);
120 + return json(response, { status_code: 200, body: JSON.stringify(body) });
121 }
122 response.writeHead(404).end();
123 });
apps/web/test/fixtures/usage-limits-hub/scenarios.json
+86
@@ -512,5 +512,91 @@
512 [20, 4480]
513 ]
514 }
515 + },
516 + "P": {
517 + "c1": {
518 + "provider": "codex",
519 + "email": "c1.codex.owner@example.com",
520 + "windows": [
521 + [30, 120],
522 + [60, 7560.0]
523 + ]
524 + },
525 + "a1": {
526 + "provider": "claude",
527 + "email": "a1.claude.owner@example.com",
528 + "windows": [
529 + [50, 150.0],
530 + [10, 9273.6],
531 + [0, 10140]
532 + ]
533 + },
534 + "x1": {
535 + "provider": "xai",
536 + "email": "x1.grok.owner@example.com",
537 + "windows": [[35, 4320]]
538 + },
539 + "g1": {
540 + "provider": "antigravity",
541 + "project_id": "fixture-project",
542 + "email": "g1.antigravity.owner@example.com",
543 + "windows": [
544 + [60, 200],
545 + [25, 6000]
546 + ]
547 + },
548 + "k1": {
549 + "provider": "kiro",
550 + "email": "k1.kiro.owner@example.com",
551 + "windows": [[10, 60]]
552 + }
553 + },
554 + "F": {
555 + "x1": {
556 + "provider": "xai",
557 + "email": "x1.grok.owner@example.com",
558 + "windows": [[35, 4320]]
559 + },
560 + "x2": {
561 + "provider": "xai",
562 + "email": "x2.grok.owner@example.com",
563 + "windows": [[35, 4320]],
564 + "state": "malformed"
565 + },
566 + "x3": {
567 + "provider": "xai",
568 + "email": "x3.grok.owner@example.com",
569 + "windows": [[35, 4320]],
570 + "state": "refused"
571 + },
572 + "g1": {
573 + "provider": "antigravity",
574 + "project_id": "fixture-project",
575 + "email": "g1.antigravity.owner@example.com",
576 + "windows": [
577 + [60, 200],
578 + [25, 6000]
579 + ]
580 + },
581 + "g2": {
582 + "provider": "antigravity",
583 + "project_id": "fixture-project",
584 + "email": "g2.antigravity.owner@example.com",
585 + "windows": [
586 + [60, 200],
587 + [25, 6000]
588 + ],
589 + "state": "malformed"
590 + },
591 + "g3": {
592 + "provider": "antigravity",
593 + "project_id": "fixture-project",
594 + "email": "g3.antigravity.owner@example.com",
595 + "windows": [
596 + [60, 200],
597 + [25, 6000]
598 + ],
599 + "state": "refused"
600 + }
601 }
602 }
docs/user/usage.md
+5 -1
@@ -165,6 +165,9 @@ Grok reports the remaining subscription allowance and reset time for its current
165 after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication
166 or endpoint configurations do not report subscription limits.
167
168 +Muse Code reports its session and weekly windows and its tier once the Muse CLI has run in a thread.
169 +Until then it shows no limits. Readings are not kept across a server restart.
170 +
171 API-key accounts may not report subscription limits. This also applies to Claude connections
172 using a proxy through `ANTHROPIC_AUTH_TOKEN`.
173
@@ -173,7 +176,8 @@ using a proxy through `ANTHROPIC_AUTH_TOKEN`.
176 To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the
177 environment that will connect to the hub and enter its URL and management key.
178
176 -The accounts appear under **Usage → Limits**. Codex accounts show banked reset credits; select an
179 +The hub's Codex, Claude, xAI (shown as Grok) and Antigravity accounts appear under **Usage → Limits**;
180 +accounts for other providers are not read. Codex accounts show banked reset credits; select an
181 account and choose **Use reset** to redeem one. No hub plugin is required.
182
183 This connection supplies usage information; configure
packages/provider-core/src/server/managedProvider.test.ts
+108 -3
@@ -609,10 +609,16 @@ describe("makeManagedServerProvider", () => {
609 yield* provider.applyUsageLimits({
610 checkedAt: "2026-04-10T00:05:00.000Z",
611 windows: [{ id: "seven_day", kind: "weekly", label: "Weekly", usedPercent: 25 }],
612 + authLabel: "tier-1",
613 + });
614 + yield* provider.applyUsageLimits({
615 + checkedAt: "2026-04-10T00:06:00.000Z",
616 + windows: [],
617 + authLabel: "tier-2",
618 });
613 - yield* provider.applyUsageLimits({ checkedAt: "2026-04-10T00:06:00.000Z", windows: [] });
619
620 const [update] = Array.from(yield* Fiber.join(updatesFiber));
621 + assert.strictEqual(update?.auth.label, "tier-1");
622 assert.deepStrictEqual(update?.usageLimits, {
623 checkedAt: "2026-04-10T00:05:00.000Z",
624 windows: [
@@ -631,7 +637,10 @@ describe("makeManagedServerProvider", () => {
637 ).pipe(Effect.provide(layerAlwaysRunTest)),
638 );
639
634 - it.effect("keeps live usage windows across a failed probe and a stale enrichment", () =>
640 + it.effect.each([
641 + { name: "a live plan", clearPlan: false },
642 + { name: "a cleared plan", clearPlan: true },
643 + ])("keeps $name and usage across a failed probe and stale enrichment", ({ clearPlan }) =>
644 Effect.scoped(
645 Effect.gen(function* () {
646 const releaseEnrichment = yield* Deferred.make<void>();
@@ -651,7 +660,7 @@ describe("makeManagedServerProvider", () => {
660 count === 1
661 ? {
662 ...refreshedSnapshot,
654 - auth: { ...refreshedSnapshot.auth, workspaceId: "ws-a" },
663 + auth: { ...refreshedSnapshot.auth, workspaceId: "ws-a", label: "tier-1" },
664 usageLimits: probedLimits,
665 }
666 : {
@@ -689,9 +698,18 @@ describe("makeManagedServerProvider", () => {
698 } as const;
699 yield* provider.applyUsageLimits({
700 checkedAt: "2026-04-10T00:00:02.000Z",
701 + authLabel: "tier-2",
702 windows: [liveWindow],
703 });
704
705 + if (clearPlan) {
706 + yield* provider.applyUsageLimits({
707 + checkedAt: "2026-04-10T00:00:02.000Z",
708 + complete: true,
709 + windows: [liveWindow],
710 + });
711 + }
712 +
713 yield* Deferred.succeed(releaseEnrichment, undefined);
714 const enriched = yield* Stream.take(provider.streamChanges, 1).pipe(
715 Stream.runCollect,
@@ -699,11 +717,13 @@ describe("makeManagedServerProvider", () => {
717 );
718 assert.deepStrictEqual(enriched.models, enrichedSnapshot.models);
719 assert.deepStrictEqual(enriched.usageLimits?.windows, [liveWindow]);
720 + assert.strictEqual(enriched.auth.label, clearPlan ? undefined : "tier-2");
721
722 const refreshed = yield* provider.refresh;
723 assert.strictEqual(refreshed.message, refreshedSnapshotSecond.message);
724 assert.deepStrictEqual(refreshed.usageLimits?.windows, [liveWindow]);
725 assert.strictEqual(refreshed.auth.workspaceId, "ws-a");
726 + assert.strictEqual(refreshed.auth.label, clearPlan ? undefined : "tier-2");
727
728 const switched = yield* provider.refresh;
729 assert.strictEqual(switched.auth.workspaceId, "ws-b");
@@ -712,6 +732,91 @@ describe("makeManagedServerProvider", () => {
732 ).pipe(Effect.provide(layerAlwaysRunTest)),
733 );
734
735 + it.effect.each([
736 + { name: "an empty reading", hasUsage: true, clearPlan: false },
737 + { name: "no reading", hasUsage: false, clearPlan: false },
738 + { name: "an empty reading after clearing the plan", hasUsage: true, clearPlan: true },
739 + { name: "no reading after clearing the plan", hasUsage: false, clearPlan: true },
740 + ])("keeps the live plan and limits after $name", ({ hasUsage, clearPlan }) =>
741 + Effect.scoped(
742 + Effect.gen(function* () {
743 + const started = yield* Deferred.make<void>();
744 + const release = yield* Deferred.make<void>();
745 + const count = yield* Ref.make(0);
746 + const provider = yield* makeManagedServerProvider<TestSettings>({
747 + resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
748 + getSettings: Effect.succeed({ enabled: true }),
749 + streamSettings: Stream.empty,
750 + haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
751 + initialSnapshot: () => Effect.succeed(initialSnapshot),
752 + checkProvider: Effect.gen(function* () {
753 + if ((yield* Ref.updateAndGet(count, (n) => n + 1)) > 1) {
754 + yield* Deferred.succeed(started, undefined);
755 + yield* Deferred.await(release);
756 + }
757 + return {
758 + ...refreshedSnapshot,
759 + auth: { status: "authenticated", label: "tier-1" },
760 + ...(hasUsage
761 + ? { usageLimits: { checkedAt: refreshedSnapshot.checkedAt, windows: [] } }
762 + : {}),
763 + } satisfies ServerProvider;
764 + }),
765 + });
766 + yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain);
767 + const refresh = yield* provider.refresh.pipe(Effect.forkChild);
768 + yield* Deferred.await(started);
769 + yield* provider.applyUsageLimits({
770 + checkedAt: "2026-04-10T00:00:04.000Z",
771 + authLabel: "tier-2",
772 + complete: true,
773 + windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 70 }],
774 + });
775 + if (clearPlan) {
776 + yield* provider.applyUsageLimits({
777 + checkedAt: "2026-04-10T00:00:04.000Z",
778 + complete: true,
779 + windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 70 }],
780 + });
781 + }
782 + yield* Deferred.succeed(release, undefined);
783 + const refreshed = yield* Fiber.join(refresh);
784 + assert.strictEqual(refreshed.auth.label, clearPlan ? undefined : "tier-2");
785 + assert.strictEqual(refreshed.usageLimits?.windows[0]?.usedPercent, 70);
786 + assert.strictEqual(refreshed.usageLimits?.unavailable, undefined);
787 + }),
788 + ).pipe(Effect.provide(layerAlwaysRunTest)),
789 + );
790 +
791 + it.effect("drops an earlier plan override after a complete reading without a label", () =>
792 + Effect.scoped(
793 + Effect.gen(function* () {
794 + const usageLimits = {
795 + checkedAt: "2026-04-10T00:00:04.000Z",
796 + windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 70 }],
797 + } as const;
798 + const provider = yield* makeManagedServerProvider<TestSettings>({
799 + resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
800 + getSettings: Effect.succeed({ enabled: true }),
801 + streamSettings: Stream.empty,
802 + haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
803 + initialSnapshot: () => Effect.succeed(initialSnapshot),
804 + checkProvider: Effect.succeed({ ...refreshedSnapshot, usageLimits }),
805 + refreshOnInterval: false,
806 + });
807 + yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain);
808 + yield* provider.applyUsageLimits({ ...usageLimits, complete: true, authLabel: "tier-2" });
809 + assert.strictEqual((yield* provider.refresh).auth.label, "tier-2");
810 +
811 + yield* provider.applyUsageLimits({ ...usageLimits, complete: true });
812 + assert.strictEqual((yield* provider.getSnapshot).auth.label, undefined);
813 + const refreshed = yield* provider.refresh;
814 + assert.strictEqual(refreshed.auth.label, undefined);
815 + assert.deepStrictEqual(refreshed.usageLimits, usageLimits);
816 + }),
817 + ).pipe(Effect.provide(layerAlwaysRunTest)),
818 + );
819 +
820 it.effect("keeps sparse usage unavailable after probe failure until a full probe recovers", () =>
821 Effect.scoped(
822 Effect.gen(function* () {
packages/provider-core/src/server/managedProvider.ts
+66 -17
@@ -16,12 +16,18 @@ import * as Stream from "effect/Stream";
16 import * as Semaphore from "effect/Semaphore";
17
18 import * as ProviderHost from "./ProviderHost.ts";
19 -import { applyUsageLimitsUpdate, resolveUsageLimitsAfterProbe } from "./usageLimits.ts";
19 +import {
20 + applyUsageLimitsUpdate,
21 + makeUsageLimits,
22 + resolveUsageLimitsAfterProbe,
23 +} from "./usageLimits.ts";
24 import type { ManagedServerProvider } from "./snapshot.ts";
25
26 interface ProviderSnapshotState {
27 readonly snapshot: ServerProvider;
28 readonly enrichmentGeneration: number;
29 + // null preserves an explicitly cleared plan across probes and enrichment.
30 + readonly usageAuthLabel: string | null | undefined;
31 }
32
33 function withUsageLimits(
@@ -72,6 +78,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
78 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
79 snapshot: initialSnapshot,
80 enrichmentGeneration: 0,
81 + usageAuthLabel: undefined,
82 });
83 const settingsRef = yield* Ref.make(initialSettings);
84 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
@@ -86,7 +93,15 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
93 return [null, state] as const;
94 }
95 // Enrichment must not revert usage updates newer than its input snapshot.
89 - const merged = withUsageLimits(nextSnapshot, state.snapshot.usageLimits);
96 + const merged = withUsageLimits(
97 + state.usageAuthLabel === undefined
98 + ? nextSnapshot
99 + : {
100 + ...nextSnapshot,
101 + auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined },
102 + },
103 + state.snapshot.usageLimits,
104 + );
105 if (Equal.equals(state.snapshot, merged)) {
106 return [null, state] as const;
107 }
@@ -150,6 +165,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
165 return state.snapshot;
166 }
167
168 + // A probe without usage must not erase a report published while its I/O was in flight.
169 + const usageBeforeProbe = (yield* Ref.get(snapshotStateRef)).snapshot.usageLimits;
170 const probedSnapshot = yield* input.checkProvider;
171 const { snapshot: nextSnapshot, generation: nextGeneration } = yield* Ref.modify(
172 snapshotStateRef,
@@ -167,21 +184,35 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
184 probedSnapshot.auth.workspaceId !== previous.workspaceId);
185 const usageLimits = switchedAccount
186 ? probedSnapshot.usageLimits
170 - : resolveUsageLimitsAfterProbe({
171 - published: state.snapshot.usageLimits,
172 - probed: probedSnapshot.usageLimits,
173 - });
187 + : probedSnapshot.usageLimits === undefined &&
188 + state.snapshot.usageLimits !== usageBeforeProbe
189 + ? state.snapshot.usageLimits
190 + : resolveUsageLimitsAfterProbe({
191 + published: state.snapshot.usageLimits,
192 + probed: probedSnapshot.usageLimits,
193 + });
194 const workspaceId =
195 usageLimits === probedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId;
196 + const usageAuthLabel =
197 + !switchedAccount && usageLimits?.checkedAt === state.snapshot.usageLimits?.checkedAt
198 + ? state.usageAuthLabel
199 + : undefined;
200 + const labeledProbe =
201 + usageAuthLabel === undefined
202 + ? probedSnapshot
203 + : {
204 + ...probedSnapshot,
205 + auth: { ...probedSnapshot.auth, label: usageAuthLabel ?? undefined },
206 + };
207 const snapshot = withUsageLimits(
208 workspaceId && !probedSnapshot.auth.workspaceId
178 - ? { ...probedSnapshot, auth: { ...probedSnapshot.auth, workspaceId } }
179 - : probedSnapshot,
209 + ? { ...labeledProbe, auth: { ...labeledProbe.auth, workspaceId } }
210 + : labeledProbe,
211 usageLimits,
212 );
213 return [
214 { snapshot, generation },
184 - { snapshot, enrichmentGeneration: generation },
215 + { snapshot, enrichmentGeneration: generation, usageAuthLabel },
216 ] as const;
217 },
218 );
@@ -197,16 +228,34 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
228 const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = Effect.fnUntraced(
229 function* (update) {
230 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
200 - const usageLimits = applyUsageLimitsUpdate({
201 - previous: state.snapshot.usageLimits,
202 - update,
203 - checkedAt: update.checkedAt,
204 - });
205 - if (usageLimits === state.snapshot.usageLimits) {
231 + const complete = update.complete && update.windows.length > 0;
232 + const usageLimits = complete
233 + ? makeUsageLimits(update)
234 + : applyUsageLimitsUpdate({
235 + previous: state.snapshot.usageLimits,
236 + update,
237 + checkedAt: update.checkedAt,
238 + });
239 + const { auth } = state.snapshot;
240 + const label = update.windows.length > 0 ? update.authLabel : undefined;
241 + const relabel =
242 + (label !== undefined || (complete && state.usageAuthLabel !== undefined)) &&
243 + label !== auth.label;
244 + if (usageLimits === state.snapshot.usageLimits && !relabel) {
245 return [null, state] as const;
246 }
208 - const snapshot = withUsageLimits(state.snapshot, usageLimits);
209 - return [snapshot, { ...state, snapshot }] as const;
247 + const snapshot = withUsageLimits(
248 + relabel ? { ...state.snapshot, auth: { ...auth, label } } : state.snapshot,
249 + usageLimits,
250 + );
251 + return [
252 + snapshot,
253 + {
254 + ...state,
255 + snapshot,
256 + usageAuthLabel: label ?? (complete ? null : state.usageAuthLabel),
257 + },
258 + ] as const;
259 });
260 if (snapshotToPublish !== null) {
261 yield* PubSub.publish(changesPubSub, snapshotToPublish);
packages/provider-core/src/server/snapshot.ts
+10 -4
@@ -7,6 +7,14 @@ import type * as Effect from "effect/Effect";
7 import type * as Stream from "effect/Stream";
8 import type { ProviderMaintenanceCapabilities } from "./maintenance.ts";
9
10 +/** authLabel names the plan, for drivers whose usage report carries it. */
11 +export type ProviderUsageLimitsReport = ProviderUsageLimitsUpdate & {
12 + readonly checkedAt: string;
13 + readonly authLabel?: string;
14 + /** A full reading replaces sparse windows and clears a previous probe failure. */
15 + readonly complete?: boolean;
16 +};
17 +
18 export interface ManagedServerProvider {
19 /** Cached; pass { fresh: true } before executing updates. */
20 readonly resolveMaintenance: (options?: {
@@ -16,8 +24,6 @@ export interface ManagedServerProvider {
24 readonly refresh: Effect.Effect<ServerProvider>;
25 readonly refreshUsage?: Effect.Effect<void, ServerSettingsError>;
26 readonly streamChanges: Stream.Stream<ServerProvider>;
19 - /** Merge windows by ID; updates with no usable window leave the snapshot untouched. */
20 - readonly applyUsageLimits: (
21 - update: ProviderUsageLimitsUpdate & { readonly checkedAt: string },
22 - ) => Effect.Effect<void>;
27 + /** Merge windows by ID and set any authLabel; an update with no window leaves the snapshot untouched. */
28 + readonly applyUsageLimits: (update: ProviderUsageLimitsReport) => Effect.Effect<void>;
29 }
packages/provider-grok/src/server.ts
+5
@@ -1,2 +1,7 @@
1 export { GrokDriver, type GrokDriverEnv } from "./server/driver.ts";
2 export { type GrokAdapterV2DriverEnv } from "./server/adapter.ts";
3 +export {
4 + GROK_USAGE_URL,
5 + GrokUsageResponse,
6 + grokUsageResponseToLimits,
7 +} from "./server/usageLimits.ts";
packages/provider-grok/src/server/usageLimits.ts
+3 -4
@@ -24,7 +24,8 @@ const GrokCredentials = Schema.Record(
24 }),
25 );
26 const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(GrokCredentials));
27 -const GrokUsageResponse = Schema.Struct({
27 +export const GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
28 +export const GrokUsageResponse = Schema.Struct({
29 config: Schema.optional(
30 Schema.Struct({
31 creditUsagePercent: Schema.optional(Schema.Number),
@@ -179,9 +180,7 @@ export const readGrokAccount = Effect.fn("readGrokAccount")(function* (
180 const usageLimits = yield* Effect.gen(function* () {
181 const client = yield* HttpClient.HttpClient;
182 const response = yield* client.execute(
182 - HttpClientRequest.get("https://cli-chat-proxy.grok.com/v1/billing?format=credits").pipe(
183 - HttpClientRequest.bearerToken(token),
184 - ),
183 + HttpClientRequest.get(GROK_USAGE_URL).pipe(HttpClientRequest.bearerToken(token)),
184 );
185 if (response.status === 403) {
186 const { error } = yield* HttpClientResponse.schemaBodyJson(GrokErrorResponse)(response);
packages/provider-muse/src/server/adapter.test.ts
+27 -3
@@ -42,6 +42,7 @@ import type { MuseItem, MuseSubscriptionUsage } from "./protocol.ts";
42 import type { MuseSdkHost, MuseSdkHostOptions } from "./sdk.ts";
43 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
44 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
45 +import type { ProviderUsageLimitsReport } from "@t3tools/provider-core/server/snapshot";
46 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
47 import { makeMuseAdapterV2, type MuseAdapterV2Options } from "./adapter.ts";
48
@@ -208,7 +209,7 @@ const makeHarness = Effect.fnUntraced(function* (
209 policy = runtimePolicy,
210 overrides: Pick<
211 MuseAdapterV2Options,
211 - "createHost" | "nativeEventLogger" | "modelCatalog" | "continuationRequests"
212 + "createHost" | "nativeEventLogger" | "modelCatalog" | "continuationRequests" | "onUsageLimits"
213 > = {},
214 ) {
215 let hostCount = 0;
@@ -607,7 +608,16 @@ describe("MuseAdapterV2", () => {
608 it.effect("stops at a Meta usage limit until every exhausted window resets", () =>
609 Effect.gen(function* () {
610 const fake = yield* makeFakeMuse();
610 - const harness = yield* makeHarness(fake);
611 + const reports: Array<ProviderUsageLimitsReport> = [];
612 + const harness = yield* makeHarness(
613 + fake,
614 + INSTANCE_ID,
615 + undefined,
616 + undefined,
617 + undefined,
618 + runtimePolicy,
619 + { onUsageLimits: (report) => Effect.sync(() => void reports.push(report)) },
620 + );
621 yield* fake.emitHostWide("usage/changed", {
622 ...SUBSCRIPTION_USAGE,
623 window: { ...SUBSCRIPTION_USAGE.window, usedPercent: 103 },
@@ -624,6 +634,10 @@ describe("MuseAdapterV2", () => {
634 assert.strictEqual(terminal.threadDisposition, "reusable");
635 assert.strictEqual(terminal.failure?.class, "usage_limit");
636 assert.strictEqual(terminal.failure?.resetAt, "2026-10-08T13:19:17.000Z");
637 + assert.deepStrictEqual(
638 + reports.map((report) => [report.authLabel, report.windows[0]?.usedPercent]),
639 + [["tier-1", 100]],
640 + );
641 assert.isTrue(
642 harness.allEvents.some(
643 (event) =>
@@ -685,7 +699,16 @@ describe("MuseAdapterV2", () => {
699 it.effect("skips an unreadable usage report without ending the session", () =>
700 Effect.gen(function* () {
701 const fake = yield* makeFakeMuse();
688 - const harness = yield* makeHarness(fake);
702 + const reports: Array<ProviderUsageLimitsReport> = [];
703 + const harness = yield* makeHarness(
704 + fake,
705 + INSTANCE_ID,
706 + undefined,
707 + undefined,
708 + undefined,
709 + runtimePolicy,
710 + { onUsageLimits: (report) => Effect.sync(() => void reports.push(report)) },
711 + );
712 yield* fake.emitHostWide("usage/changed", { window: "not usage" });
713 yield* fake.emitHostWide("usage/changed", {
714 ...SUBSCRIPTION_USAGE,
@@ -700,6 +723,7 @@ describe("MuseAdapterV2", () => {
723 const terminal = yield* harness.takeEvent("turn.terminal");
724 assert.strictEqual(terminal.failure?.class, "usage_limit");
725 assert.isUndefined(terminal.failure?.resetAt);
726 + assert.deepStrictEqual(reports, []);
727 assert.strictEqual(fake.closeCount(), 0);
728 }).pipe(Effect.scoped, Effect.provide(testLayer)),
729 );
packages/provider-muse/src/server/adapter.ts
+11 -1
@@ -63,7 +63,11 @@ import {
63 museApprovalOptions,
64 type MuseItem,
65 } from "./protocol.ts";
66 -import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts";
66 +import {
67 + isMuseUsageLimitFailure,
68 + museUsageLimitResetAt,
69 + museUsageToLimits,
70 +} from "./usageLimits.ts";
71 import {
72 createMuseSdkHostEffect,
73 MuseSdkError,
@@ -75,6 +79,7 @@ import {
79 type MuseSdkHost,
80 } from "./sdk.ts";
81 import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
82 +import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
83 import {
84 providerMessageTextWithAttachmentPaths,
85 isProviderNativeImageAttachment,
@@ -202,6 +207,8 @@ export interface MuseAdapterV2Options {
207 readonly createHost?: typeof createMuseSdkHost;
208 readonly requestTimeoutMs?: number;
209 readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger;
210 + /** Receives every account-wide usage report, whichever session's host sent it. */
211 + readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"];
212 readonly continuationRequests?: {
213 readonly offer: (
214 request: ProviderContinuationRequests.ProviderContinuationRequest,
@@ -1378,6 +1385,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1385 // usage/changed is account-wide and carries no session ID.
1386 if (method === "usage/changed") {
1387 latestSubscriptionUsage = yield* decode(MuseSubscriptionUsage, params);
1388 + if (options.onUsageLimits) {
1389 + yield* options.onUsageLimits(museUsageToLimits(latestSubscriptionUsage));
1390 + }
1391 return;
1392 }
1393 if (params.sessionId !== nativeSessionId) return;
packages/provider-muse/src/server/driver.test.ts new
+216
@@ -0,0 +1,216 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { expect, it } from "@effect/vitest";
3 +import {
4 + DEFAULT_SERVER_SETTINGS,
5 + ProviderInstanceId,
6 + ProviderSessionId,
7 + ThreadId,
8 +} from "@t3tools/contracts";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Queue from "effect/Queue";
12 +import * as Stream from "effect/Stream";
13 +import * as Sink from "effect/Sink";
14 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15 +import * as HttpClient from "effect/http/HttpClient";
16 +import { vi } from "vite-plus/test";
17 +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
18 +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
19 +import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
20 +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
21 +import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
22 +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
23 +import * as sdk from "./sdk.ts";
24 +import { MuseDriver } from "./driver.ts";
25 +
26 +vi.mock("./sdk.ts", { spy: true });
27 +
28 +const layerTest = TestProviderHost.layer({
29 + runBackgroundWork: false,
30 + settings: { ...DEFAULT_SERVER_SETTINGS, enableProviderUpdateChecks: false },
31 +}).pipe(
32 + Layer.provideMerge(NodeServices.layer),
33 + Layer.provideMerge(IdAllocator.layer),
34 + Layer.provideMerge(McpProviderSessions.layer),
35 + Layer.provideMerge(ProviderLatestVersions.layer),
36 + Layer.provideMerge(
37 + Layer.succeed(
38 + ProviderEventLoggers.ProviderEventLoggers,
39 + ProviderEventLoggers.NoOpProviderEventLoggers,
40 + ),
41 + ),
42 + Layer.provideMerge(
43 + Layer.succeed(
44 + HttpClient.HttpClient,
45 + HttpClient.make(() => Effect.die("Unexpected HTTP request")),
46 + ),
47 + ),
48 +);
49 +
50 +function nativeHost() {
51 + let notify: Parameters<sdk.MuseSdkHost["connection"]["onNotification"]>[0] = () => {};
52 + let close!: () => void;
53 + const closed = new Promise<void>((resolve) => {
54 + close = resolve;
55 + });
56 + const host: sdk.MuseSdkHost = {
57 + connection: {
58 + mintCommandId: () => "command",
59 + request: async (method) =>
60 + method.startsWith("session/")
61 + ? {
62 + session: { sessionId: "command", modelId: "muse-wonder-1.0", activeTurnId: null },
63 + history: { items: [] },
64 + }
65 + : method === "model/list"
66 + ? {
67 + providerId: "meta",
68 + models: [
69 + {
70 + modelId: "muse-wonder-1.0",
71 + displayLabel: "Muse",
72 + providerId: "meta",
73 + isDefault: true,
74 + },
75 + ],
76 + }
77 + : {},
78 + command: async (_method, params) => ({
79 + session: { sessionId: params.sessionId, modelId: "muse-wonder-1.0", activeTurnId: null },
80 + history: { items: [] },
81 + }),
82 + onNotification: (handler) => {
83 + notify = handler;
84 + },
85 + onProtocolError: () => {},
86 + onServerRequest: () => {},
87 + closed,
88 + },
89 + initializeResult: { grantedCapabilities: [] },
90 + exited: closed.then(() => ({ code: 0, signal: null })),
91 + close: async () => {
92 + close();
93 + },
94 + };
95 + return {
96 + host,
97 + emit: (method: string, params: Record<string, unknown>) =>
98 + notify({ jsonrpc: "2.0", method, params }),
99 + };
100 +}
101 +
102 +it.layer(layerTest)("MuseDriver usage", (it) => {
103 + it.effect(
104 + "keeps the newest complete account report across late reports and refresh without probing for usage",
105 + () =>
106 + Effect.gen(function* () {
107 + const hosts: ReturnType<typeof nativeHost>[] = [];
108 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
109 + using spawn = vi.spyOn(spawner, "spawn").mockImplementation(() =>
110 + Effect.succeed(
111 + ChildProcessSpawner.makeHandle({
112 + pid: ChildProcessSpawner.ProcessId(1),
113 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
114 + isRunning: Effect.succeed(false),
115 + kill: () => Effect.void,
116 + unref: Effect.succeed(Effect.void),
117 + stdin: Sink.drain,
118 + stdout: Stream.encodeText(Stream.make("muse 1.0.3-R2198.1")),
119 + stderr: Stream.empty,
120 + all: Stream.empty,
121 + getInputFd: () => Sink.drain,
122 + getOutputFd: () => Stream.empty,
123 + }),
124 + ),
125 + );
126 + const createHost: typeof sdk.createMuseSdkHost = async () => {
127 + const fake = nativeHost();
128 + hosts.push(fake);
129 + return fake.host;
130 + };
131 + const original = (yield* Effect.promise(() => vi.importActual<typeof sdk>("./sdk.ts")))
132 + .createMuseSdkHostEffect;
133 + using _hostEffect = vi
134 + .spyOn(sdk, "createMuseSdkHostEffect")
135 + .mockImplementation((options) => original(options, createHost));
136 + using _host = vi.spyOn(sdk, "createMuseSdkHost").mockImplementation(createHost);
137 + const instanceId = ProviderInstanceId.make("muse-test");
138 + const instance = yield* MuseDriver.create({
139 + instanceId,
140 + displayName: "Muse test",
141 + enabled: true,
142 + environment: [],
143 + config: { ...MuseDriver.defaultConfig(), binaryPath: process.execPath },
144 + });
145 + yield* Stream.take(instance.snapshot.streamChanges, 1).pipe(Stream.runDrain);
146 + expect((yield* instance.snapshot.getSnapshot).status).toBe("ready");
147 + expect((yield* instance.snapshot.getSnapshot).usageLimits).toBeUndefined();
148 + const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
149 + runtimeMode: "full-access",
150 + interactionMode: "default",
151 + cwd: null,
152 + });
153 + const sessions = yield* Effect.forEach(
154 + ["one", "two"],
155 + Effect.fnUntraced(function* (id) {
156 + const runtime = yield* instance.orchestrationAdapter.openSession({
157 + threadId: ThreadId.make(id),
158 + providerSessionId: ProviderSessionId.make(id),
159 + modelSelection: { instanceId, model: "muse-wonder-1.0", options: [] },
160 + runtimePolicy: policy,
161 + });
162 + const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
163 + yield* runtime.events.pipe(
164 + Stream.runForEach((event) => Queue.offer(events, event)),
165 + Effect.forkScoped,
166 + );
167 + yield* runtime.ensureThread({
168 + threadId: ThreadId.make(id),
169 + modelSelection: { instanceId, model: "muse-wonder-1.0", options: [] },
170 + runtimePolicy: policy,
171 + });
172 + return { fake: hosts.at(-1)!, events };
173 + }),
174 + );
175 + const reading = (observedAtMs: number, usedPercent: number, tier: string) => ({
176 + window: { usedPercent, windowDurationMins: 300, resetsAtMs: 1791465557000 },
177 + weekly: { usedPercent: 50, resetsAtMs: 1791763200000 },
178 + observedAtMs,
179 + tier,
180 + });
181 + const publish = Effect.fnUntraced(function* (
182 + index: number,
183 + report: ReturnType<typeof reading>,
184 + ) {
185 + const session = sessions[index]!;
186 + session.fake.emit("usage/changed", report);
187 + // The following context event acknowledges that this host has processed the report.
188 + session.fake.emit("session/contextUsage", {
189 + sessionId: "command",
190 + usedTokens: report.observedAtMs,
191 + });
192 + yield* Queue.take(session.events).pipe(
193 + Effect.repeat({
194 + until: (event) =>
195 + event.type === "provider_thread.updated" &&
196 + event.providerThread.contextUsage?.usedTokens === report.observedAtMs,
197 + }),
198 + );
199 + });
200 + yield* publish(1, reading(1791447762610, 70, "tier-2"));
201 + const latest = yield* instance.snapshot.getSnapshot;
202 + expect(latest.usageLimits?.unavailable).toBeUndefined();
203 + expect(latest.usageLimits?.windows.map((window) => window.usedPercent)).toEqual([70, 50]);
204 + expect(latest.auth.label).toBe("tier-2");
205 + yield* publish(0, reading(1791447761610, 10, "tier-1"));
206 + expect((yield* instance.snapshot.getSnapshot).usageLimits).toEqual(latest.usageLimits);
207 + expect((yield* instance.snapshot.getSnapshot).auth.label).toBe("tier-2");
208 + const callsBeforeUsageRefresh = spawn.mock.calls.length;
209 + yield* instance.snapshot.refreshUsage!;
210 + expect(spawn.mock.calls.length).toBe(callsBeforeUsageRefresh);
211 + const refreshed = yield* instance.snapshot.refresh;
212 + expect(refreshed.usageLimits).toEqual(latest.usageLimits);
213 + expect(refreshed.auth.label).toBe("tier-2");
214 + }).pipe(Effect.scoped),
215 + );
216 +});
packages/provider-muse/src/server/driver.ts
+36 -2
@@ -1,8 +1,10 @@
1 -import { ProviderDriverKind } from "@t3tools/contracts";
1 +import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
2 import { MuseSettings } from "../settings.ts";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 +import * as Ref from "effect/Ref";
7 +import * as Semaphore from "effect/Semaphore";
8 import * as Path from "effect/Path";
9 import * as Schema from "effect/Schema";
10 import * as HttpClient from "effect/http/HttpClient";
@@ -20,6 +22,8 @@ import * as ProviderContinuationRequests from "@t3tools/provider-core/server/Pro
22 import { checkMuseProviderStatus, makePendingMuseProvider } from "./status.ts";
23 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
24 import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
25 +import type { ProviderUsageLimitsReport } from "@t3tools/provider-core/server/snapshot";
26 +import { makeUsageLimits } from "@t3tools/provider-core/server/usageLimits";
27 import { enrichMuseSnapshot, latestMuseVersion, museMaintenance } from "./maintenance.ts";
28 import { makeMuseEnvironment } from "./sdk.ts";
29 import { museUsageReader } from "./usage.ts";
@@ -104,6 +108,26 @@ export const MuseDriver: ProviderDriver<
108 accentColor,
109 continuationGroupKey: continuationIdentity.continuationKey,
110 });
111 + // Only a running CLI reports usage; status probes cannot fetch it.
112 + const latestUsage = yield* Ref.make<ProviderUsageLimitsReport | undefined>(undefined);
113 + const usagePermit = yield* Semaphore.make(1);
114 + const withLatestUsage = (provider: ServerProvider) =>
115 + Ref.get(latestUsage).pipe(
116 + Effect.map((report): ServerProvider =>
117 + report
118 + ? {
119 + ...provider,
120 + ...(report.authLabel
121 + ? { auth: { ...provider.auth, label: report.authLabel } }
122 + : {}),
123 + usageLimits: makeUsageLimits({
124 + checkedAt: report.checkedAt,
125 + windows: report.windows,
126 + }),
127 + }
128 + : provider,
129 + ),
130 + );
131 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
132 const resolveInstallation = yield* makeCachedProviderMaintenanceResolution(
133 resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, {
@@ -148,6 +172,7 @@ export const MuseDriver: ProviderDriver<
172 makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)),
173 checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe(
174 Effect.map(stampIdentity),
175 + Effect.flatMap(withLatestUsage),
176 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
177 Effect.provideService(FileSystem.FileSystem, fileSystem),
178 Effect.provideService(Path.Path, path),
@@ -185,6 +210,15 @@ export const MuseDriver: ProviderDriver<
210 modelCatalog,
211 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
212 continuationRequests,
213 + onUsageLimits: (report) =>
214 + usagePermit.withPermits(1)(
215 + Effect.gen(function* () {
216 + const previous = yield* Ref.get(latestUsage);
217 + if (previous && Date.parse(report.checkedAt) < Date.parse(previous.checkedAt)) return;
218 + yield* Ref.set(latestUsage, report);
219 + yield* snapshot.applyUsageLimits({ ...report, complete: true });
220 + }),
221 + ),
222 });
223 const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, {
224 environment: processEnvironment,
@@ -197,7 +231,7 @@ export const MuseDriver: ProviderDriver<
231 displayName,
232 accentColor,
233 enabled,
200 - snapshot: { ...snapshot, resolveMaintenance },
234 + snapshot: { ...snapshot, resolveMaintenance, refreshUsage: Effect.void },
235 orchestrationAdapter,
236 textGeneration,
237 } satisfies ProviderInstance;
packages/provider-muse/src/server/usageLimits.test.ts
+33 -1
@@ -1,7 +1,11 @@
1 import { describe, expect, it } from "@effect/vitest";
2
3 import type { MuseSubscriptionUsage } from "./protocol.ts";
4 -import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts";
4 +import {
5 + isMuseUsageLimitFailure,
6 + museUsageLimitResetAt,
7 + museUsageToLimits,
8 +} from "./usageLimits.ts";
9
10 const usage = {
11 observedAtMs: 1791447762610,
@@ -54,3 +58,31 @@ describe("Muse usage limit failures", () => {
58 expect(museUsageLimitResetAt(undefined, afterNamedReset, { message: realRefusal })).toBeNull();
59 });
60 });
61 +
62 +describe("Muse account usage", () => {
63 + it("reports the session and weekly windows, capped at 100, with the tier as plan", () => {
64 + expect(museUsageToLimits({ ...usage, window: { ...usage.window, usedPercent: 103 } })).toEqual({
65 + checkedAt: "2026-10-08T08:22:42.610Z",
66 + authLabel: "tier-1",
67 + windows: [
68 + {
69 + id: "session",
70 + kind: "session",
71 + label: "Session",
72 + usedPercent: 100,
73 + resetsAt: "2026-10-08T13:19:17.000Z",
74 + windowDurationMins: 300,
75 + },
76 + {
77 + id: "weekly",
78 + kind: "weekly",
79 + label: "Weekly",
80 + usedPercent: 5,
81 + resetsAt: "2026-10-12T00:00:00.000Z",
82 + windowDurationMins: 10080,
83 + },
84 + ],
85 + });
86 + expect(museUsageToLimits({ ...usage, tier: " " })).not.toHaveProperty("authLabel");
87 + });
88 +});
packages/provider-muse/src/server/usageLimits.ts
+32 -1
@@ -1,7 +1,38 @@
1 import * as DateTime from "effect/DateTime";
2 +import { clampPercent } from "@t3tools/provider-core/server/usageLimits";
3 +import type { ProviderUsageLimitsReport } from "@t3tools/provider-core/server/snapshot";
4
5 import { LATEST_DATE_MS, type MuseSubscriptionUsage } from "./protocol.ts";
6
7 +const isoMillis = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));
8 +
9 +/** Muse's account-wide report as Limits windows, with its tier as the plan. */
10 +export function museUsageToLimits(usage: MuseSubscriptionUsage): ProviderUsageLimitsReport {
11 + const tier = usage.tier.trim();
12 + return {
13 + checkedAt: isoMillis(usage.observedAtMs),
14 + windows: [
15 + {
16 + id: "session",
17 + kind: "session",
18 + label: "Session",
19 + usedPercent: clampPercent(usage.window.usedPercent),
20 + resetsAt: isoMillis(usage.window.resetsAtMs),
21 + windowDurationMins: usage.window.windowDurationMins,
22 + },
23 + {
24 + id: "weekly",
25 + kind: "weekly",
26 + label: "Weekly",
27 + usedPercent: clampPercent(usage.weekly.usedPercent),
28 + resetsAt: isoMillis(usage.weekly.resetsAtMs),
29 + windowDurationMins: 7 * 24 * 60,
30 + },
31 + ],
32 + ...(tier ? { authLabel: tier } : {}),
33 + };
34 +}
35 +
36 /** Credential proxies may omit error.quota from 429 refusals; inspect text too. */
37 export function isMuseUsageLimitFailure(message: string | undefined): boolean {
38 return message !== undefined && /\b429\b/.test(message) && /quota|usage limit/i.test(message);
@@ -30,5 +61,5 @@ export function museUsageLimitResetAt(
61 (ms): ms is number =>
62 ms !== undefined && Number.isFinite(ms) && ms > nowMs && ms <= LATEST_DATE_MS,
63 );
33 - return resets.length > 0 ? DateTime.formatIso(DateTime.makeUnsafe(Math.max(...resets))) : null;
64 + return resets.length > 0 ? isoMillis(Math.max(...resets)) : null;
65 }
packages/shared/src/usageLimits.test.ts
+39
@@ -344,6 +344,45 @@ describe("pools", () => {
344 expect(collectLimitAccounts(input)).toHaveLength(1);
345 });
346
347 + it("merges a local Antigravity login with its hub account by Google account fingerprint", () => {
348 + const antigravity = ProviderDriverKind.make("antigravity");
349 + const local = provider({
350 + driver: antigravity,
351 + instanceId: ProviderInstanceId.make("antigravity"),
352 + auth: { status: "authenticated" },
353 + usageLimits: {
354 + checkedAt,
355 + credentialFingerprint: "google-key",
356 + windows: [{ ...window, id: "gemini-weekly", usedPercent: 20 }],
357 + },
358 + });
359 + const hubAccount = {
360 + id: "antigravity-g@example.com.json",
361 + driver: antigravity,
362 + usageLimits: {
363 + checkedAt: "2026-09-03T11:30:00.000Z",
364 + credentialFingerprint: "google-key",
365 + windows: [{ ...window, id: "gemini-weekly", usedPercent: 30 }],
366 + },
367 + };
368 + const accounts = collectLimitAccounts(
369 + new Map([
370 + [
371 + EnvironmentId.make("env-a"),
372 + {
373 + ...laptop,
374 + serverConfig: {
375 + providers: [local],
376 + usageLimitSources: [{ ...source, accounts: [hubAccount] }],
377 + },
378 + },
379 + ],
380 + ]),
381 + );
382 + expect(accounts).toHaveLength(1);
383 + expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(30);
384 + });
385 +
386 it("takes windows from a fresher hub read but credits and redeem from the native instance", () => {
387 const native = provider({
388 driver: claude,