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

antigravityUsageLimits.ts

350 lines13.1 KB

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;
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 };
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;
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 is metered apart from the default Gemini buckets; keep its group name.
132 const family = bucket.bucketId.startsWith("gemini-argon-")
133 ? group.displayName?.trim() || "Gemini Argon"
134 : bucket.bucketId.startsWith("gemini-")
135 ? "Gemini"
136 : bucket.bucketId.startsWith("3p-")
137 ? "Claude & GPT (shared)"
138 : group.displayName?.trim() || bucket.bucketId;
139 const weekly = bucket.window === "weekly";
140 const session = bucket.window === "5h";
141 const windowDurationMins = SUMMARY_WINDOW_MINS.get(bucket.window ?? "");
142 const window = quotaWindow(
143 bucket.bucketId,
144 `${family} · ${weekly ? "Weekly" : session ? "5-hour" : bucket.displayName?.trim() || "Quota"}`,
145 { ...bucket, resetTime: summaryResetTime(bucket, windowDurationMins, requestedAt) },
146 weekly ? "weekly" : session ? "session" : "other",
147 windowDurationMins,
148 );
149 if (window) windows.set(window.id, window);
150 }
151 }
152 return [...windows.values()];
154​
155/** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */
156function modelWindows(models: typeof Models.Type) {
157 const windows = new Map<string, ServerProviderUsageWindow>();
158 for (const [modelId, model] of Object.entries(models.models)) {
159 const family =
160 model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-")
161 ? "Gemini"
162 : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-")
163 ? "Claude"
164 : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-")
165 ? "GPT"
166 : undefined;
167 if (!family) continue;
168 for (const [suffix, quota] of [
169 ["quota", model.quotaInfo],
170 ["weekly", model.weeklyQuotaInfo],
171 ] as const) {
172 if (!quota) continue;
173 const window = quotaWindow(
174 `${family.toLowerCase()}-${suffix}`,
175 `${family} · ${suffix === "weekly" ? "Weekly" : "Reported quota"}`,
176 quota,
177 suffix === "weekly" ? "weekly" : "other",
178 suffix === "weekly" ? 7 * 24 * 60 : undefined,
179 );
180 if (!window) continue;
181 const previous = windows.get(window.id);
182 if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window);
183 }
184 }
185 return [...windows.values()];
187​
188export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
189 readonly profileDirectory: string;
190 readonly authMethod: AntigravitySettings["authMethod"];
191}) {
192 const fs = yield* FileSystem.FileSystem;
193 const path = yield* Path.Path;
194 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
195 const crypto = yield* Digest.Digest;
196 const platform = yield* HostProcess.Platform;
197 const architecture = yield* HostProcess.Architecture;
198 const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json");
199 let cached:
200 | { fingerprint: string; account: string; accessToken: string; expiresAt: number }
201 | undefined;
202 let generation = 0;
203​
204 const sha256 = (text: string) =>
205 crypto
206 .digest(Digest.sha256, new TextEncoder().encode(text))
207 .pipe(
208 Effect.map((digest) =>
209 Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""),
210 ),
211 );
212​
213 const request = (request: HttpClientRequest.HttpClientRequest) =>
214 client.execute(request).pipe(
215 Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
216 Effect.flatMap(HttpClientResponse.filterStatusOk),
217 Effect.flatMap((response) => response.json),
218 Effect.timeout("10 seconds"),
219 );
220 const read = Effect.gen(function* () {
221 const startedGeneration = generation;
222 const checkedAt = DateTime.formatIso(yield* DateTime.now);
223 if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
224 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
225 }
226 if (!(yield* fs.exists(tokenPath))) {
227 cached = undefined;
228 return makeUnavailableUsageLimits({
229 checkedAt,
230 reason: "unsupported",
231 message: "Sign in with Google to see Antigravity limits.",
232 });
233 }
234 const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
235 const fingerprint = yield* sha256(
236 `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
237 );
238 const now = yield* Clock.currentTimeMillis;
239 let accessToken: string;
240 let account: string;
241 if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
242 cached = undefined;
243 const refreshed = yield* request(
244 HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
245 HttpClientRequest.bodyUrlParams({
246 client_id: token.client_id,
247 client_secret: token.client_secret,
248 refresh_token: token.refresh_token,
249 grant_type: "refresh_token",
250 }),
251 ),
252 ).pipe(Effect.flatMap(decodeTokenResponse));
253 accessToken = refreshed.access_token;
254 // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine.
255 account = yield* request(
256 HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
257 HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
258 ),
259 ).pipe(
260 Effect.flatMap(decodeUserInfo),
261 Effect.flatMap((info) => sha256(`google-account\0${info.id}`)),
262 Effect.orElseSucceed(() => fingerprint),
263 );
264 if (generation === startedGeneration) {
265 cached = {
266 fingerprint,
267 account,
268 accessToken,
269 expiresAt: now + refreshed.expires_in * 1000,
270 };
271 }
272 } else {
273 accessToken = cached.accessToken;
274 account = cached.account;
275 }
276 const endpoints = ENDPOINTS[input.authMethod];
277 // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins.
278 const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* <E>(
279 operation: string,
280 parse: (
281 response: unknown,
282 requestedAt: number,
283 ) => Effect.Effect<ServerProviderUsageWindow[], E>,
284 ) {
285 const responses = yield* Effect.forEach(
286 endpoints,
287 (endpoint) =>
288 Effect.gen(function* () {
289 // Capture each request after auth, so refresh latency does not widen the tolerance.
290 const requestedAt = yield* Clock.currentTimeMillis;
291 return yield* request(
292 HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
293 HttpClientRequest.setHeaders({
294 Authorization: `Bearer ${accessToken}`,
295 "User-Agent": `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`,
296 }),
297 HttpClientRequest.bodyJsonUnsafe(
298 token.project_id ? { project: token.project_id } : {},
299 ),
300 ),
301 ).pipe(
302 Effect.flatMap((response) => parse(response, requestedAt)),
303 Effect.orElseSucceed(() => []),
304 );
305 }),
306 { concurrency: "unbounded" },
307 );
308 const windows = new Map<string, ServerProviderUsageWindow>();
309 for (const window of responses.flat()) {
310 if (!windows.has(window.id)) windows.set(window.id, window);
311 }
312 return [...windows.values()];
313 });
314 const summary = yield* fetchWindows("retrieveUserQuotaSummary", (response, requestedAt) =>
315 decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))),
316 );
317 const windows = summary.length
318 ? summary
319 : yield* fetchWindows("fetchAvailableModels", (response) =>
320 decodeModels(response).pipe(Effect.map(modelWindows)),
321 );
322 if (windows.length === 0) {
323 return makeUnavailableUsageLimits({
324 checkedAt,
325 reason: "probeFailed",
326 message: "Antigravity did not return usable quota information.",
327 });
328 }
329 return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account };
330 });
331 const probe = read.pipe(
332 Effect.timeout("30 seconds"),
333 Effect.catch(() =>
334 Effect.gen(function* () {
335 return makeUnavailableUsageLimits({
336 checkedAt: DateTime.formatIso(yield* DateTime.now),
337 reason: "probeFailed",
338 message: "Could not read Antigravity limits. Refresh provider status to retry.",
339 });
340 }),
341 ),
342 );
343 return {
344 probe,
345 clear: Effect.sync(() => {
346 cached = undefined;
347 generation++;
348 }),
349 };
350});