The best way to control Claude Code, Codex and more from any computer or phone

main
ts 505 lines 19.5 KB
Raw
1 import * as NodeModule from "node:module";
2
3 import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Clock from "effect/Clock";
6 import * as Digest from "effect/crypto/Digest";
7 import * as DateTime from "effect/DateTime";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Option from "effect/Option";
11 import * as Path from "effect/Path";
12 import * as Schema from "effect/Schema";
13 import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14
15 import {
16 makeUnavailableUsageLimits,
17 makeUsageLimits,
18 } from "@t3tools/provider-core/server/usageLimits";
19
20 export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) {
21 return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;
22 }
23
24 const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
25 const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
26 // The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod.
27 // The sign-in method stands in for the tier.
28 const ENDPOINTS = {
29 "oauth-personal": [DAILY_ENDPOINT, PROD_ENDPOINT],
30 "oauth-business": [PROD_ENDPOINT, DAILY_ENDPOINT],
31 };
32 const SUMMARY_WINDOW_MINS = new Map([
33 ["5h", 5 * 60],
34 ["weekly", 7 * 24 * 60],
35 ]);
36 const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
37 const TokenFile = Schema.Struct({
38 client_id: Schema.NonEmptyString,
39 client_secret: Schema.NonEmptyString,
40 refresh_token: Schema.NonEmptyString,
41 project_id: Schema.optional(Schema.String),
42 });
43 // The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in
44 // antigravity-oauth-token without one or when T3 bypasses the keyring. It stores no OAuth client, so T3 cannot refresh it.
45 const CliToken = Schema.Struct({
46 token: Schema.Struct({
47 access_token: Schema.NonEmptyString,
48 refresh_token: Schema.optional(Schema.String),
49 expiry: Schema.optional(Schema.String),
50 }),
51 });
52 const TokenResponse = Schema.Struct({
53 access_token: Schema.NonEmptyString,
54 expires_in: Schema.Number.check(Schema.isGreaterThan(0)),
55 });
56 const UserInfo = Schema.Struct({ id: Schema.NonEmptyString });
57 const Quota = Schema.Struct({
58 remainingFraction: Schema.optional(Schema.Number),
59 resetTime: Schema.optional(Schema.String),
60 });
61 const Bucket = Schema.Struct({
62 ...Quota.fields,
63 bucketId: Schema.NonEmptyString,
64 window: Schema.optional(Schema.String),
65 displayName: Schema.optional(Schema.String),
66 description: Schema.optional(Schema.String),
67 disabled: Schema.optional(Schema.Boolean),
68 });
69 const Summary = Schema.Struct({
70 groups: Schema.optional(
71 Schema.Array(
72 Schema.Struct({
73 displayName: Schema.optional(Schema.String),
74 buckets: Schema.optional(Schema.Array(Bucket)),
75 }),
76 ),
77 ),
78 buckets: Schema.optional(Schema.Array(Bucket)),
79 });
80 const Models = Schema.Struct({
81 models: Schema.Record(
82 Schema.String,
83 Schema.Struct({
84 modelProvider: Schema.optional(Schema.String),
85 quotaInfo: Schema.optional(Quota),
86 weeklyQuotaInfo: Schema.optional(Quota),
87 }),
88 ),
89 });
90
91 const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile));
92 const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken));
93 const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);
94 const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo);
95 const decodeSummary = Schema.decodeUnknownEffect(Summary);
96 const decodeModels = Schema.decodeUnknownEffect(Models);
97
98 function iso(value: string | undefined): string | undefined {
99 const parsed = value ? DateTime.make(value) : Option.none();
100 return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : undefined;
101 }
102
103 function quotaWindow(
104 id: string,
105 label: string,
106 quota: typeof Quota.Type,
107 kind: ServerProviderUsageWindow["kind"] = "other",
108 windowDurationMins?: number,
109 ): ServerProviderUsageWindow | undefined {
110 if (quota.remainingFraction === undefined || !Number.isFinite(quota.remainingFraction)) {
111 return undefined;
112 }
113 const resetsAt = iso(quota.resetTime);
114 return {
115 id,
116 label,
117 kind,
118 usedPercent: (1 - Math.max(0, Math.min(1, quota.remainingFraction))) * 100,
119 ...(resetsAt ? { resetsAt } : {}),
120 ...(windowDurationMins === undefined ? {} : { windowDurationMins }),
121 };
122 }
123
124 function summaryResetTime(
125 bucket: typeof Bucket.Type,
126 windowDurationMins: number | undefined,
127 requestedAt: number,
128 ): string | undefined {
129 // Untouched summary buckets report a rolling full-window reset.
130 const untouched =
131 bucket.remainingFraction === 1 &&
132 bucket.description === undefined &&
133 windowDurationMins !== undefined &&
134 Math.abs(Date.parse(bucket.resetTime ?? "") - requestedAt - windowDurationMins * 60_000) <=
135 60_000;
136 return untouched ? undefined : bucket.resetTime;
137 }
138
139 const sha256 = Effect.fnUntraced(function* (text: string) {
140 const digest = yield* (yield* Digest.Digest).digest(
141 Digest.sha256,
142 new TextEncoder().encode(text),
143 );
144 return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
145 });
146
147 /** go-keyring stores UTF-8, which it prefixes and encodes on macOS. */
148 export function decodeGoKeyringSecret(secret: ArrayLike<number>): string {
149 // The binding resolves a plain number array at runtime despite its Uint8Array type.
150 const text = new TextDecoder().decode(Uint8Array.from(secret));
151 if (text.startsWith("go-keyring-base64:")) {
152 return Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8");
153 }
154 if (text.startsWith("go-keyring-encoded:")) {
155 return Buffer.from(text.slice("go-keyring-encoded:".length), "hex").toString("utf8");
156 }
157 return text;
158 }
159
160 class AntigravityKeyringError extends Schema.TaggedError<AntigravityKeyringError>()(
161 "AntigravityKeyringError",
162 { cause: Schema.Defect() },
163 ) {
164 override get message(): string {
165 return "Could not read the Antigravity sign-in from the system keyring.";
166 }
167 }
168
169 // A single-executable server resolves packages on disk only through `require`.
170 const requireExternal = NodeModule.createRequire(import.meta.url);
171
172 /**
173 * go-keyring's Windows target is `gemini:antigravity`; @napi-rs/keyring reads `antigravity.gemini`,
174 * and its `withTarget` overwrites the target with an empty secret before reading.
175 */
176 export function readWindowsCliCredential(
177 architecture: NodeJS.Architecture,
178 ): Uint8Array | undefined {
179 // CREDENTIALW offsets and the pointers below are 64-bit.
180 if (architecture !== "x64" && architecture !== "arm64") {
181 throw new Error(`no credential access on ${architecture}`);
182 }
183 const { DataType, load, open } = requireExternal("ffi-rs") as typeof import("ffi-rs");
184 open({ library: "t3-advapi32", path: "advapi32.dll" });
185 open({ library: "t3-kernel32", path: "kernel32.dll" });
186 const copy = (into: Buffer, from: bigint) =>
187 load({
188 library: "t3-kernel32",
189 funcName: "RtlMoveMemory",
190 retType: DataType.Void,
191 paramsType: [DataType.U8Array, DataType.BigInt, DataType.BigInt],
192 paramsValue: [into, from, BigInt(into.length)],
193 });
194 const out = Buffer.alloc(8);
195 const read = load({
196 library: "t3-advapi32",
197 funcName: "CredReadW",
198 retType: DataType.I32,
199 // CRED_TYPE_GENERIC
200 paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array],
201 paramsValue: ["gemini:antigravity", 1, 0, out],
202 errno: true as const,
203 });
204 if (read.value === 0) {
205 // ERROR_NOT_FOUND
206 if (read.errnoCode === 1168) return undefined;
207 throw new Error(`CredReadW failed with Windows error ${read.errnoCode}`);
208 }
209 const credential = out.readBigUInt64LE();
210 try {
211 // CredentialBlobSize is a DWORD at 32 and CredentialBlob a pointer at 40.
212 const header = Buffer.alloc(48);
213 copy(header, credential);
214 const size = header.readUInt32LE(32);
215 if (size === 0) return undefined;
216 const blob = Buffer.alloc(size);
217 copy(blob, header.readBigUInt64LE(40));
218 return blob;
219 } finally {
220 load({
221 library: "t3-advapi32",
222 funcName: "CredFree",
223 retType: DataType.Void,
224 paramsType: [DataType.BigInt],
225 paramsValue: [credential],
226 });
227 }
228 }
229
230 // Loaded lazily: a native binding that fails to load must not take the provider down.
231 const readCliKeyringSecret = (platform: NodeJS.Platform, architecture: NodeJS.Architecture) =>
232 Effect.tryPromise({
233 try: async () => {
234 const secret =
235 platform === "win32"
236 ? readWindowsCliCredential(architecture)
237 : await new (
238 requireExternal("@napi-rs/keyring") as typeof import("@napi-rs/keyring")
239 ).AsyncEntry("gemini", "antigravity").getSecret();
240 return secret ? decodeGoKeyringSecret(secret) : undefined;
241 },
242 catch: (cause) => new AntigravityKeyringError({ cause }),
243 });
244
245 /** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */
246 export const antigravityAccountFingerprint = (userInfo: unknown) =>
247 decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`)));
248
249 /** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */
250 export const antigravitySummaryWindows = (response: unknown, requestedAt: number) =>
251 decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt)));
252
253 function summaryWindows(summary: typeof Summary.Type, requestedAt: number) {
254 const windows = new Map<string, ServerProviderUsageWindow>();
255 const groups = summary.groups?.some((group) => group.buckets?.length)
256 ? summary.groups
257 : [{ buckets: summary.buckets }];
258 for (const group of groups ?? []) {
259 for (const bucket of group.buckets ?? []) {
260 if (bucket.disabled) continue;
261 // Argon and Carbon are metered separately from the default Gemini buckets.
262 const family = bucket.bucketId.startsWith("gemini-argon-")
263 ? group.displayName?.trim() || "Gemini Argon"
264 : bucket.bucketId.startsWith("gemini-carbon-")
265 ? group.displayName?.trim() || "Gemini Carbon"
266 : bucket.bucketId.startsWith("gemini-")
267 ? "Gemini"
268 : bucket.bucketId.startsWith("3p-")
269 ? "Claude & GPT (shared)"
270 : group.displayName?.trim() || bucket.bucketId;
271 const weekly = bucket.window === "weekly";
272 const session = bucket.window === "5h";
273 const windowDurationMins = SUMMARY_WINDOW_MINS.get(bucket.window ?? "");
274 const window = quotaWindow(
275 bucket.bucketId,
276 `${family} · ${weekly ? "Weekly" : session ? "5-hour" : bucket.displayName?.trim() || "Quota"}`,
277 { ...bucket, resetTime: summaryResetTime(bucket, windowDurationMins, requestedAt) },
278 weekly ? "weekly" : session ? "session" : "other",
279 windowDurationMins,
280 );
281 if (window) windows.set(window.id, window);
282 }
283 }
284 return [...windows.values()];
285 }
286
287 /** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */
288 function modelWindows(models: typeof Models.Type) {
289 const windows = new Map<string, ServerProviderUsageWindow>();
290 for (const [modelId, model] of Object.entries(models.models)) {
291 const family =
292 model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-")
293 ? "Gemini"
294 : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-")
295 ? "Claude"
296 : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-")
297 ? "GPT"
298 : undefined;
299 if (!family) continue;
300 for (const [suffix, quota] of [
301 ["quota", model.quotaInfo],
302 ["weekly", model.weeklyQuotaInfo],
303 ] as const) {
304 if (!quota) continue;
305 const window = quotaWindow(
306 `${family.toLowerCase()}-${suffix}`,
307 `${family} · ${suffix === "weekly" ? "Weekly" : "Reported quota"}`,
308 quota,
309 suffix === "weekly" ? "weekly" : "other",
310 suffix === "weekly" ? 7 * 24 * 60 : undefined,
311 );
312 if (!window) continue;
313 const previous = windows.get(window.id);
314 if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window);
315 }
316 }
317 return [...windows.values()];
318 }
319
320 export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
321 readonly profileDirectory: string;
322 readonly authMethod: AntigravitySettings["authMethod"];
323 readonly readKeyringSecret?: Effect.Effect<string | undefined, AntigravityKeyringError>;
324 }) {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
328 const crypto = yield* Digest.Digest;
329 const platform = yield* HostProcess.Platform;
330 const architecture = yield* HostProcess.Architecture;
331 const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json");
332 const cliTokenPath = path.join(
333 input.profileDirectory,
334 "antigravity-acp",
335 "antigravity-oauth-token",
336 );
337 const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture);
338 let cached:
339 | { fingerprint: string; account: string; accessToken: string; expiresAt: number }
340 | undefined;
341 let generation = 0;
342
343 const request = (request: HttpClientRequest.HttpClientRequest) =>
344 client.execute(request).pipe(
345 Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
346 Effect.flatMap(HttpClientResponse.filterStatusOk),
347 Effect.flatMap((response) => response.json),
348 Effect.timeout("10 seconds"),
349 );
350 const read = Effect.gen(function* () {
351 const startedGeneration = generation;
352 const checkedAt = DateTime.formatIso(yield* DateTime.now);
353 if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
354 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
355 }
356 const now = yield* Clock.currentTimeMillis;
357 let accessToken: string;
358 let account: string;
359 let projectId: string | undefined;
360 if (!(yield* fs.exists(tokenPath))) {
361 cached = undefined;
362 // Google account instances bypass the keyring, whose one entry every profile shares.
363 const stored = (yield* fs.exists(cliTokenPath))
364 ? yield* fs.readFileString(cliTokenPath)
365 : input.authMethod === "oauth-business"
366 ? yield* readKeyringSecret
367 : undefined;
368 if (stored === undefined) {
369 return makeUnavailableUsageLimits({
370 checkedAt,
371 reason: "unsupported",
372 message: "Sign in with Google to see Antigravity limits.",
373 });
374 }
375 const { token } = yield* decodeCliToken(stored);
376 if (!(Date.parse(token.expiry ?? "") > now + 60_000)) {
377 return makeUnavailableUsageLimits({
378 checkedAt,
379 reason: "probeFailed",
380 message:
381 "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.",
382 });
383 }
384 accessToken = token.access_token;
385 account = yield* request(
386 HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
387 HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
388 ),
389 ).pipe(
390 Effect.flatMap(antigravityAccountFingerprint),
391 Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)),
392 );
393 } else {
394 const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
395 projectId = token.project_id;
396 const fingerprint = yield* sha256(
397 `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
398 );
399 if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
400 cached = undefined;
401 const refreshed = yield* request(
402 HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
403 HttpClientRequest.bodyUrlParams({
404 client_id: token.client_id,
405 client_secret: token.client_secret,
406 refresh_token: token.refresh_token,
407 grant_type: "refresh_token",
408 }),
409 ),
410 ).pipe(Effect.flatMap(decodeTokenResponse));
411 accessToken = refreshed.access_token;
412 // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine.
413 account = yield* request(
414 HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
415 HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
416 ),
417 ).pipe(
418 Effect.flatMap(antigravityAccountFingerprint),
419 Effect.orElseSucceed(() => fingerprint),
420 );
421 if (generation === startedGeneration) {
422 cached = {
423 fingerprint,
424 account,
425 accessToken,
426 expiresAt: now + refreshed.expires_in * 1000,
427 };
428 }
429 } else {
430 accessToken = cached.accessToken;
431 account = cached.account;
432 }
433 }
434 const endpoints = ENDPOINTS[input.authMethod];
435 // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins.
436 const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* <E>(
437 operation: string,
438 parse: (
439 response: unknown,
440 requestedAt: number,
441 ) => Effect.Effect<ServerProviderUsageWindow[], E>,
442 ) {
443 const responses = yield* Effect.forEach(
444 endpoints,
445 (endpoint) =>
446 Effect.gen(function* () {
447 // Capture each request after auth, so refresh latency does not widen the tolerance.
448 const requestedAt = yield* Clock.currentTimeMillis;
449 return yield* request(
450 HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
451 HttpClientRequest.setHeaders({
452 Authorization: `Bearer ${accessToken}`,
453 "User-Agent": antigravityUserAgent(platform, architecture),
454 }),
455 HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}),
456 ),
457 ).pipe(
458 Effect.flatMap((response) => parse(response, requestedAt)),
459 Effect.orElseSucceed(() => []),
460 );
461 }),
462 { concurrency: "unbounded" },
463 );
464 const windows = new Map<string, ServerProviderUsageWindow>();
465 for (const window of responses.flat()) {
466 if (!windows.has(window.id)) windows.set(window.id, window);
467 }
468 return [...windows.values()];
469 });
470 const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows);
471 const windows = summary.length
472 ? summary
473 : yield* fetchWindows("fetchAvailableModels", (response) =>
474 decodeModels(response).pipe(Effect.map(modelWindows)),
475 );
476 if (windows.length === 0) {
477 return makeUnavailableUsageLimits({
478 checkedAt,
479 reason: "probeFailed",
480 message: "Antigravity did not return usable quota information.",
481 });
482 }
483 return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account };
484 });
485 const probe = read.pipe(
486 Effect.provideService(Digest.Digest, crypto),
487 Effect.timeout("30 seconds"),
488 Effect.catch(() =>
489 Effect.gen(function* () {
490 return makeUnavailableUsageLimits({
491 checkedAt: DateTime.formatIso(yield* DateTime.now),
492 reason: "probeFailed",
493 message: "Could not read Antigravity limits. Refresh provider status to retry.",
494 });
495 }),
496 ),
497 );
498 return {
499 probe,
500 clear: Effect.sync(() => {
501 cached = undefined;
502 generation++;
503 }),
504 };
505 });