Open History to see the last commit
1import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts";
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import * as Clock from "effect/Clock";
4import * as Crypto from "effect/Crypto";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
12
13import {
14 makeUnavailableUsageLimits,
15 makeUsageLimits,
16} from "@t3tools/provider-core/server/usageLimits";
17
18const ENDPOINTS = [
19 "https://daily-cloudcode-pa.googleapis.com",
20 "https://cloudcode-pa.googleapis.com",
21];
22const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
23const TokenFile = Schema.Struct({
24 client_id: Schema.NonEmptyString,
25 client_secret: Schema.NonEmptyString,
26 refresh_token: Schema.NonEmptyString,
27 project_id: Schema.optional(Schema.String),
28});
29const TokenResponse = Schema.Struct({
30 access_token: Schema.NonEmptyString,
31 expires_in: Schema.Number.check(Schema.isGreaterThan(0)),
32});
33const Quota = Schema.Struct({
34 remainingFraction: Schema.optional(Schema.Number),
35 resetTime: Schema.optional(Schema.String),
36});
37const Bucket = Schema.Struct({
38 ...Quota.fields,
39 bucketId: Schema.NonEmptyString,
40 window: Schema.optional(Schema.String),
41 displayName: Schema.optional(Schema.String),
42 disabled: Schema.optional(Schema.Boolean),
43});
44const Summary = Schema.Struct({
45 groups: Schema.optional(
46 Schema.Array(
47 Schema.Struct({
48 displayName: Schema.optional(Schema.String),
49 buckets: Schema.optional(Schema.Array(Bucket)),
50 }),
51 ),
52 ),
53 buckets: Schema.optional(Schema.Array(Bucket)),
54});
55const Models = Schema.Struct({
56 models: Schema.Record(
57 Schema.String,
58 Schema.Struct({
59 modelProvider: Schema.optional(Schema.String),
60 quotaInfo: Schema.optional(Quota),
61 weeklyQuotaInfo: Schema.optional(Quota),
62 }),
63 ),
64});
65
66const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile));
67const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);
68const decodeSummary = Schema.decodeUnknownEffect(Summary);
69const decodeModels = Schema.decodeUnknownEffect(Models);
70
71function iso(value: string | undefined): string | undefined {
72 const parsed = value ? DateTime.make(value) : Option.none();
73 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : undefined;
74}
75
76function quotaWindow(
77 id: string,
78 label: string,
79 quota: typeof Quota.Type,
80 kind: ServerProviderUsageWindow["kind"] = "other",
81 windowDurationMins?: number,
82): ServerProviderUsageWindow | undefined {
83 if (quota.remainingFraction === undefined || !Number.isFinite(quota.remainingFraction)) {
84 return undefined;
85 }
86 const resetsAt = iso(quota.resetTime);
87 return {
88 id,
89 label,
90 kind,
91 usedPercent: (1 - Math.max(0, Math.min(1, quota.remainingFraction))) * 100,
92 ...(resetsAt ? { resetsAt } : {}),
93 ...(windowDurationMins === undefined ? {} : { windowDurationMins }),
94 };
95}
96
97/** The summary names the actual shared buckets; Claude and GPT consume one allowance. */
98function summaryWindows(summary: typeof Summary.Type) {
99 const windows = new Map<string, ServerProviderUsageWindow>();
100 const groups = summary.groups?.some((group) => group.buckets?.length)
101 ? summary.groups
102 : [{ buckets: summary.buckets }];
103 for (const group of groups ?? []) {
104 for (const bucket of group.buckets ?? []) {
105 if (bucket.disabled) continue;
106 const family = bucket.bucketId.startsWith("gemini-")
107 ? "Gemini"
108 : bucket.bucketId.startsWith("3p-")
109 ? "Claude & GPT (shared)"
110 : group.displayName?.trim() || bucket.bucketId;
111 const weekly = bucket.window === "weekly";
112 const session = bucket.window === "5h";
113 const window = quotaWindow(
114 bucket.bucketId,
115 `${family} · ${weekly ? "Weekly" : session ? "5-hour" : bucket.displayName?.trim() || "Quota"}`,
116 bucket,
117 weekly ? "weekly" : session ? "session" : "other",
118 weekly ? 7 * 24 * 60 : session ? 5 * 60 : undefined,
119 );
120 if (window) windows.set(window.id, window);
121 }
122 }
123 return [...windows.values()];
124}
125
126/** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */
127function modelWindows(models: typeof Models.Type) {
128 const windows = new Map<string, ServerProviderUsageWindow>();
129 for (const [modelId, model] of Object.entries(models.models)) {
130 const family =
131 model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-")
132 ? "Gemini"
133 : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-")
134 ? "Claude"
135 : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-")
136 ? "GPT"
137 : undefined;
138 if (!family) continue;
139 for (const [suffix, quota] of [
140 ["quota", model.quotaInfo],
141 ["weekly", model.weeklyQuotaInfo],
142 ] as const) {
143 if (!quota) continue;
144 const window = quotaWindow(
145 `${family.toLowerCase()}-${suffix}`,
146 `${family} · ${suffix === "weekly" ? "Weekly" : "Reported quota"}`,
147 quota,
148 suffix === "weekly" ? "weekly" : "other",
149 suffix === "weekly" ? 7 * 24 * 60 : undefined,
150 );
151 if (!window) continue;
152 const previous = windows.get(window.id);
153 if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window);
154 }
155 }
156 return [...windows.values()];
157}
158
159/** Reads this instance's Google profile, with a memory-only access token and no credential writes. */
160export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
161 readonly profileDirectory: string;
162 readonly authMethod: AntigravitySettings["authMethod"];
163}) {
164 const fs = yield* FileSystem.FileSystem;
165 const path = yield* Path.Path;
166 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
167 const crypto = yield* Crypto.Crypto;
168 const platform = yield* HostProcess.Platform;
169 const architecture = yield* HostProcess.Architecture;
170 const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json");
171 let cached: { fingerprint: string; accessToken: string; expiresAt: number } | undefined;
172 let generation = 0;
173
174 const request = (request: HttpClientRequest.HttpClientRequest) =>
175 client.execute(request).pipe(
176 Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
177 Effect.flatMap(HttpClientResponse.filterStatusOk),
178 Effect.flatMap((response) => response.json),
179 Effect.timeout("10 seconds"),
180 );
181 const read = Effect.gen(function* () {
182 const startedGeneration = generation;
183 const checkedAt = DateTime.formatIso(yield* DateTime.now);
184 if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
185 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
186 }
187 if (!(yield* fs.exists(tokenPath))) {
188 cached = undefined;
189 return makeUnavailableUsageLimits({
190 checkedAt,
191 reason: "unsupported",
192 message: "Sign in with Google to see Antigravity limits.",
193 });
194 }
195 const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
196 const fingerprint = Array.from(
197 yield* crypto.digest(
198 "SHA-256",
199 new TextEncoder().encode(
200 `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
201 ),
202 ),
203 (byte) => byte.toString(16).padStart(2, "0"),
204 ).join("");
205 const now = yield* Clock.currentTimeMillis;
206 let accessToken: string;
207 if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
208 cached = undefined;
209 const refreshed = yield* request(
210 HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
211 HttpClientRequest.bodyUrlParams({
212 client_id: token.client_id,
213 client_secret: token.client_secret,
214 refresh_token: token.refresh_token,
215 grant_type: "refresh_token",
216 }),
217 ),
218 ).pipe(Effect.flatMap(decodeTokenResponse));
219 accessToken = refreshed.access_token;
220 if (generation === startedGeneration) {
221 cached = { fingerprint, accessToken, expiresAt: now + refreshed.expires_in * 1000 };
222 }
223 } else {
224 accessToken = cached.accessToken;
225 }
226 const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* <E>(
227 operation: string,
228 parse: (response: unknown) => Effect.Effect<ServerProviderUsageWindow[], E>,
229 ) {
230 for (const endpoint of ENDPOINTS) {
231 const windows = yield* request(
232 HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
233 HttpClientRequest.setHeaders({
234 Authorization: `Bearer ${accessToken}`,
235 "User-Agent": `antigravity/hub/1.0.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`,
236 }),
237 HttpClientRequest.bodyJsonUnsafe(token.project_id ? { project: token.project_id } : {}),
238 ),
239 ).pipe(
240 Effect.flatMap(parse),
241 Effect.orElseSucceed(() => []),
242 );
243 if (windows.length > 0) return windows;
244 }
245 return [];
246 });
247 const summary = yield* fetchWindows("retrieveUserQuotaSummary", (response) =>
248 decodeSummary(response).pipe(Effect.map(summaryWindows)),
249 );
250 const windows = summary.length
251 ? summary
252 : yield* fetchWindows("fetchAvailableModels", (response) =>
253 decodeModels(response).pipe(Effect.map(modelWindows)),
254 );
255 if (windows.length === 0) {
256 return makeUnavailableUsageLimits({
257 checkedAt,
258 reason: "probeFailed",
259 message: "Antigravity did not return usable quota information.",
260 });
261 }
262 return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: fingerprint };
263 });
264 const probe = read.pipe(
265 Effect.timeout("30 seconds"),
266 Effect.catch(() =>
267 Effect.gen(function* () {
268 return makeUnavailableUsageLimits({
269 checkedAt: DateTime.formatIso(yield* DateTime.now),
270 reason: "probeFailed",
271 message: "Could not read Antigravity limits. Refresh provider status to retry.",
272 });
273 }),
274 ),
275 );
276 return {
277 probe,
278 clear: Effect.sync(() => {
279 cached = undefined;
280 generation++;
281 }),
282 };
283});