Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

antigravityUsageLimits.ts

318 lines11.7 KB

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