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 Digest from "effect/crypto/Digest";
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 DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
19const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
20// The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod.
21// The sign-in method stands in for the tier.
22const ENDPOINTS = {
23 "oauth-personal": [DAILY_ENDPOINT, PROD_ENDPOINT],
24 "oauth-business": [PROD_ENDPOINT, DAILY_ENDPOINT],
25};
26const SUMMARY_WINDOW_MINS = new Map([
27 ["5h", 5 * 60],
28 ["weekly", 7 * 24 * 60],
29]);
30const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
31const TokenFile = Schema.Struct({
32 client_id: Schema.NonEmptyString,
33 client_secret: Schema.NonEmptyString,
34 refresh_token: Schema.NonEmptyString,
35 project_id: Schema.optional(Schema.String),
36});
37const TokenResponse = Schema.Struct({
38 access_token: Schema.NonEmptyString,
39 expires_in: Schema.Number.check(Schema.isGreaterThan(0)),
40});
41const UserInfo = Schema.Struct({ id: Schema.NonEmptyString });
42const Quota = Schema.Struct({
43 remainingFraction: Schema.optional(Schema.Number),
44 resetTime: Schema.optional(Schema.String),
45});
46const Bucket = Schema.Struct({
47 ...Quota.fields,
48 bucketId: Schema.NonEmptyString,
49 window: Schema.optional(Schema.String),
50 displayName: Schema.optional(Schema.String),
51 description: Schema.optional(Schema.String),
52 disabled: Schema.optional(Schema.Boolean),
53});
54const Summary = Schema.Struct({
55 groups: Schema.optional(
56 Schema.Array(
57 Schema.Struct({
58 displayName: Schema.optional(Schema.String),
59 buckets: Schema.optional(Schema.Array(Bucket)),
60 }),
61 ),
62 ),
63 buckets: Schema.optional(Schema.Array(Bucket)),
64});
65const Models = Schema.Struct({
66 models: Schema.Record(
67 Schema.String,
68 Schema.Struct({
69 modelProvider: Schema.optional(Schema.String),
70 quotaInfo: Schema.optional(Quota),
71 weeklyQuotaInfo: Schema.optional(Quota),
72 }),
73 ),
74});
75
76const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile));
77const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);
78const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo);
79const decodeSummary = Schema.decodeUnknownEffect(Summary);
80const decodeModels = Schema.decodeUnknownEffect(Models);
81
82function iso(value: string | undefined): string | undefined {
83 const parsed = value ? DateTime.make(value) : Option.none();
84 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : undefined;
85}
86
87function quotaWindow(
88 id: string,
89 label: string,
90 quota: typeof Quota.Type,
91 kind: ServerProviderUsageWindow["kind"] = "other",
92 windowDurationMins?: number,
93): ServerProviderUsageWindow | undefined {
94 if (quota.remainingFraction === undefined || !Number.isFinite(quota.remainingFraction)) {
95 return undefined;
96 }
97 const resetsAt = iso(quota.resetTime);
98 return {
99 id,
100 label,
101 kind,
102 usedPercent: (1 - Math.max(0, Math.min(1, quota.remainingFraction))) * 100,
103 ...(resetsAt ? { resetsAt } : {}),
104 ...(windowDurationMins === undefined ? {} : { windowDurationMins }),
105 };
106}
107
108function summaryResetTime(
109 bucket: typeof Bucket.Type,
110 windowDurationMins: number | undefined,
111 requestedAt: number,
112): string | undefined {
113 // Untouched summary buckets report a rolling full-window reset.
114 const untouched =
115 bucket.remainingFraction === 1 &&
116 bucket.description === undefined &&
117 windowDurationMins !== undefined &&
118 Math.abs(Date.parse(bucket.resetTime ?? "") - requestedAt - windowDurationMins * 60_000) <=
119 60_000;
120 return untouched ? undefined : bucket.resetTime;
121}
122
123function summaryWindows(summary: typeof Summary.Type, requestedAt: number) {
124 const windows = new Map<string, ServerProviderUsageWindow>();
125 const groups = summary.groups?.some((group) => group.buckets?.length)
126 ? summary.groups
127 : [{ buckets: summary.buckets }];
128 for (const group of groups ?? []) {
129 for (const bucket of group.buckets ?? []) {
130 if (bucket.disabled) continue;
131 // Argon and Carbon are metered separately from the default Gemini buckets.
132 const family = bucket.bucketId.startsWith("gemini-argon-")
133 ? group.displayName?.trim() || "Gemini Argon"
134 : bucket.bucketId.startsWith("gemini-carbon-")
135 ? group.displayName?.trim() || "Gemini Carbon"
136 : bucket.bucketId.startsWith("gemini-")
137 ? "Gemini"
138 : bucket.bucketId.startsWith("3p-")
139 ? "Claude & GPT (shared)"
140 : group.displayName?.trim() || bucket.bucketId;
141 const weekly = bucket.window === "weekly";
142 const session = bucket.window === "5h";
143 const windowDurationMins = SUMMARY_WINDOW_MINS.get(bucket.window ?? "");
144 const window = quotaWindow(
145 bucket.bucketId,
146 `${family} · ${weekly ? "Weekly" : session ? "5-hour" : bucket.displayName?.trim() || "Quota"}`,
147 { ...bucket, resetTime: summaryResetTime(bucket, windowDurationMins, requestedAt) },
148 weekly ? "weekly" : session ? "session" : "other",
149 windowDurationMins,
150 );
151 if (window) windows.set(window.id, window);
152 }
153 }
154 return [...windows.values()];
155}
156
157/** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */
158function modelWindows(models: typeof Models.Type) {
159 const windows = new Map<string, ServerProviderUsageWindow>();
160 for (const [modelId, model] of Object.entries(models.models)) {
161 const family =
162 model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-")
163 ? "Gemini"
164 : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-")
165 ? "Claude"
166 : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-")
167 ? "GPT"
168 : undefined;
169 if (!family) continue;
170 for (const [suffix, quota] of [
171 ["quota", model.quotaInfo],
172 ["weekly", model.weeklyQuotaInfo],
173 ] as const) {
174 if (!quota) continue;
175 const window = quotaWindow(
176 `${family.toLowerCase()}-${suffix}`,
177 `${family} · ${suffix === "weekly" ? "Weekly" : "Reported quota"}`,
178 quota,
179 suffix === "weekly" ? "weekly" : "other",
180 suffix === "weekly" ? 7 * 24 * 60 : undefined,
181 );
182 if (!window) continue;
183 const previous = windows.get(window.id);
184 if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window);
185 }
186 }
187 return [...windows.values()];
188}
189
190export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
191 readonly profileDirectory: string;
192 readonly authMethod: AntigravitySettings["authMethod"];
193}) {
194 const fs = yield* FileSystem.FileSystem;
195 const path = yield* Path.Path;
196 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
197 const crypto = yield* Digest.Digest;
198 const platform = yield* HostProcess.Platform;
199 const architecture = yield* HostProcess.Architecture;
200 const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json");
201 let cached:
202 | { fingerprint: string; account: string; accessToken: string; expiresAt: number }
203 | undefined;
204 let generation = 0;
205
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
215 const request = (request: HttpClientRequest.HttpClientRequest) =>
216 client.execute(request).pipe(
217 Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
218 Effect.flatMap(HttpClientResponse.filterStatusOk),
219 Effect.flatMap((response) => response.json),
220 Effect.timeout("10 seconds"),
221 );
222 const read = Effect.gen(function* () {
223 const startedGeneration = generation;
224 const checkedAt = DateTime.formatIso(yield* DateTime.now);
225 if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
226 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
227 }
228 if (!(yield* fs.exists(tokenPath))) {
229 cached = undefined;
230 return makeUnavailableUsageLimits({
231 checkedAt,
232 reason: "unsupported",
233 message: "Sign in with Google to see Antigravity limits.",
234 });
235 }
236 const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
237 const fingerprint = yield* sha256(
238 `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
239 );
240 const now = yield* Clock.currentTimeMillis;
241 let accessToken: string;
242 let account: string;
243 if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
244 cached = undefined;
245 const refreshed = yield* request(
246 HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
247 HttpClientRequest.bodyUrlParams({
248 client_id: token.client_id,
249 client_secret: token.client_secret,
250 refresh_token: token.refresh_token,
251 grant_type: "refresh_token",
252 }),
253 ),
254 ).pipe(Effect.flatMap(decodeTokenResponse));
255 accessToken = refreshed.access_token;
256 // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine.
257 account = yield* request(
258 HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
259 HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
260 ),
261 ).pipe(
262 Effect.flatMap(decodeUserInfo),
263 Effect.flatMap((info) => sha256(`google-account\0${info.id}`)),
264 Effect.orElseSucceed(() => fingerprint),
265 );
266 if (generation === startedGeneration) {
267 cached = {
268 fingerprint,
269 account,
270 accessToken,
271 expiresAt: now + refreshed.expires_in * 1000,
272 };
273 }
274 } else {
275 accessToken = cached.accessToken;
276 account = cached.account;
277 }
278 const endpoints = ENDPOINTS[input.authMethod];
279 // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins.
280 const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* <E>(
281 operation: string,
282 parse: (
283 response: unknown,
284 requestedAt: number,
285 ) => Effect.Effect<ServerProviderUsageWindow[], E>,
286 ) {
287 const responses = yield* Effect.forEach(
288 endpoints,
289 (endpoint) =>
290 Effect.gen(function* () {
291 // Capture each request after auth, so refresh latency does not widen the tolerance.
292 const requestedAt = yield* Clock.currentTimeMillis;
293 return yield* request(
294 HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
295 HttpClientRequest.setHeaders({
296 Authorization: `Bearer ${accessToken}`,
297 "User-Agent": `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`,
298 }),
299 HttpClientRequest.bodyJsonUnsafe(
300 token.project_id ? { project: token.project_id } : {},
301 ),
302 ),
303 ).pipe(
304 Effect.flatMap((response) => parse(response, requestedAt)),
305 Effect.orElseSucceed(() => []),
306 );
307 }),
308 { concurrency: "unbounded" },
309 );
310 const windows = new Map<string, ServerProviderUsageWindow>();
311 for (const window of responses.flat()) {
312 if (!windows.has(window.id)) windows.set(window.id, window);
313 }
314 return [...windows.values()];
315 });
316 const summary = yield* fetchWindows("retrieveUserQuotaSummary", (response, requestedAt) =>
317 decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))),
318 );
319 const windows = summary.length
320 ? summary
321 : yield* fetchWindows("fetchAvailableModels", (response) =>
322 decodeModels(response).pipe(Effect.map(modelWindows)),
323 );
324 if (windows.length === 0) {
325 return makeUnavailableUsageLimits({
326 checkedAt,
327 reason: "probeFailed",
328 message: "Antigravity did not return usable quota information.",
329 });
330 }
331 return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account };
332 });
333 const probe = read.pipe(
334 Effect.timeout("30 seconds"),
335 Effect.catch(() =>
336 Effect.gen(function* () {
337 return makeUnavailableUsageLimits({
338 checkedAt: DateTime.formatIso(yield* DateTime.now),
339 reason: "probeFailed",
340 message: "Could not read Antigravity limits. Refresh provider status to retry.",
341 });
342 }),
343 ),
344 );
345 return {
346 probe,
347 clear: Effect.sync(() => {
348 cached = undefined;
349 generation++;
350 }),
351 };
352});