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