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

antigravityUsageLimits.ts

229 lines8.1 KB

1import type {
2 AntigravitySettings,
3 ServerProviderUsageLimits,
4 ServerProviderUsageWindow,
5} from "@t3tools/contracts";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { compareSemverVersions } from "@t3tools/shared/semver";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import type * as Scope from "effect/Scope";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17​
18import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
19import {
20 clampPercent,
21 makeUnavailableUsageLimits,
22 makeUsageLimits,
23} from "@t3tools/provider-core/server/usageLimits";
24​
25import {
26 antigravityUsageEnvironment,
27 resolveAntigravityCaBundle,
28} from "./antigravityAuthSupport.ts";
29import type { AntigravityInstallationError } from "./AntigravityInstallation.ts";
30​
31/** The first release with `agy usage`. */
32const ANTIGRAVITY_USAGE_MIN_VERSION = "1.5.22";
33​
34const UPDATE_MESSAGE = `Update Antigravity to ${ANTIGRAVITY_USAGE_MIN_VERSION} or newer to see limits.`;
35const SIGN_IN_MESSAGE = "Sign in with Google to see Antigravity limits.";
36const FAILED_MESSAGE = "Could not read Antigravity limits. Refresh provider status to retry.";
37​
38const UsageBucket = Schema.Struct({
39 id: Schema.String,
40 name: Schema.optional(Schema.String),
41 window: Schema.optional(Schema.String),
42 remaining_fraction: Schema.optional(Schema.Number),
43 reset_time: Schema.optional(Schema.String),
44});
45​
46const UsageOutput = Schema.Struct({
47 status: Schema.String,
48 command: Schema.Struct({
49 name: Schema.Literal("usage"),
50 data: Schema.Struct({
51 groups: Schema.Array(
52 Schema.Struct({
53 name: Schema.optional(Schema.String),
54 buckets: Schema.optional(Schema.Array(UsageBucket)),
55 }),
56 ),
57 }),
58 }),
59});
60const decodeUsageOutput = Schema.decodeUnknownOption(Schema.fromJsonString(UsageOutput));
61​
62const WINDOWS: Record<
63 string,
64 { kind: ServerProviderUsageWindow["kind"]; label: string; mins: number }
65> = {
66 "5h": { kind: "session", label: "5-hour", mins: 5 * 60 },
67 weekly: { kind: "weekly", label: "Weekly", mins: 7 * 24 * 60 },
68};
69​
70/** Maps `agy usage --json` output; groups such as Gemini and Claude/GPT are metered apart. */
71function antigravityUsageOutputToLimits(
72 stdout: string,
73 checkedAt: string,
74): ServerProviderUsageLimits {
75 const decoded = decodeUsageOutput(stdout.trim());
76 if (Option.isNone(decoded) || decoded.value.status !== "SUCCESS") {
77 return makeUnavailableUsageLimits({
78 checkedAt,
79 reason: "probeFailed",
80 message: FAILED_MESSAGE,
81 });
82 }
83 const windows: ServerProviderUsageWindow[] = [];
84 for (const group of decoded.value.command.data.groups) {
85 for (const bucket of group.buckets ?? []) {
86 const fraction = bucket.remaining_fraction;
87 if (fraction === undefined || !Number.isFinite(fraction)) continue;
88 const window = WINDOWS[bucket.window ?? ""];
89 const reset = DateTime.make(bucket.reset_time ?? "");
90 // An untouched bucket reports the Unix epoch: its window has not started.
91 const resetsAt =
92 Option.isSome(reset) && DateTime.toEpochMillis(reset.value) > 0
93 ? DateTime.formatIso(reset.value)
94 : undefined;
95 windows.push({
96 id: bucket.id,
97 kind: window?.kind ?? "other",
98 label: `${group.name?.trim() || "Antigravity"} · ${window?.label ?? (bucket.name?.trim() || "Quota")}`,
99 usedPercent: clampPercent((1 - fraction) * 100),
100 ...(resetsAt ? { resetsAt } : {}),
101 ...(window ? { windowDurationMins: window.mins } : {}),
102 });
103 }
104 }
105 return windows.length > 0
106 ? makeUsageLimits({ checkedAt, windows })
107 : makeUnavailableUsageLimits({
108 checkedAt,
109 reason: "probeFailed",
110 message: "Antigravity did not return usable quota information.",
111 });
113​
114export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
115 readonly profileDirectory: string;
116 readonly authMethod: AntigravitySettings["authMethod"];
117 readonly environment: NodeJS.ProcessEnv;
118 /** The executable sessions use, held for the duration of the read. */
119 readonly executable: Effect.Effect<
120 { readonly executablePath: string; readonly version: string | null },
121 AntigravityInstallationError,
122 Scope.Scope
123 >;
124}) {
125 const fs = yield* FileSystem.FileSystem;
126 const path = yield* Path.Path;
127 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
128 const caBundlePath = yield* resolveAntigravityCaBundle(
129 yield* HostProcess.Platform,
130 input.environment,
131 );
132 const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "antigravity-oauth-token");
133 const usageHome = path.join(input.profileDirectory, "usage-home");
134 const usageTokenPath = path.join(
135 usageHome,
136 ".gemini",
137 "antigravity-cli",
138 "antigravity-oauth-token",
139 );
140​
141 const read = Effect.gen(function* () {
142 const checkedAt = DateTime.formatIso(yield* DateTime.now);
143 // API-key and Agent Platform sign-ins have no account quota.
144 if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
145 return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
146 }
147 if (!(yield* fs.exists(tokenPath))) {
148 yield* fs.remove(usageTokenPath, { force: true });
149 return makeUnavailableUsageLimits({
150 checkedAt,
151 reason: "unsupported",
152 message: SIGN_IN_MESSAGE,
153 });
154 }
155 const executable = yield* input.executable;
156 if (
157 executable.version !== null &&
158 compareSemverVersions(executable.version, ANTIGRAVITY_USAGE_MIN_VERSION) < 0
159 ) {
160 return makeUnavailableUsageLimits({
161 checkedAt,
162 reason: "unsupported",
163 message: UPDATE_MESSAGE,
164 });
165 }
166 // Copy each time so the read follows the instance's current sign-in, not an older account.
167 yield* fs.makeDirectory(path.dirname(usageTokenPath), { recursive: true, mode: 0o700 });
168 yield* fs.copyFile(tokenPath, usageTokenPath);
169 yield* fs.chmod(usageTokenPath, 0o600);
170 const child = yield* spawner.spawn(
171 ChildProcess.make(executable.executablePath, ["usage", "--json"], {
172 cwd: usageHome,
173 env: antigravityUsageEnvironment(input.environment, usageHome, caBundlePath),
174 extendEnv: false,
175 shell: false,
176 stdin: "ignore",
177 }),
178 );
179 const [stdout, stderr, exitCode] = yield* Effect.all(
180 [
181 collectUint8StreamText({ stream: child.stdout, maxBytes: 256 * 1024 }),
182 collectUint8StreamText({ stream: child.stderr, maxBytes: 16 * 1024 }),
183 child.exitCode,
184 ],
185 { concurrency: "unbounded" },
186 );
187 if (Number(exitCode) === 0) return antigravityUsageOutputToLimits(stdout.text, checkedAt);
188 if (/please sign in/i.test(stderr.text)) {
189 return makeUnavailableUsageLimits({
190 checkedAt,
191 reason: "unsupported",
192 message: SIGN_IN_MESSAGE,
193 });
194 }
195 // A PATH or custom executable has no known version until it rejects the subcommand.
196 if (/unexpected argument "usage"/.test(stderr.text)) {
197 return makeUnavailableUsageLimits({
198 checkedAt,
199 reason: "unsupported",
200 message: UPDATE_MESSAGE,
201 });
202 }
203 return yield* Effect.logWarning("Antigravity usage read failed.", {
204 exitCode: Number(exitCode),
205 }).pipe(
206 Effect.as(
207 makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", message: FAILED_MESSAGE }),
208 ),
209 );
210 });
211​
212 return {
213 probe: read.pipe(
214 Effect.scoped,
215 Effect.timeout("30 seconds"),
216 Effect.catch(() =>
217 Effect.map(DateTime.now, (now) =>
218 makeUnavailableUsageLimits({
219 checkedAt: DateTime.formatIso(now),
220 reason: "probeFailed",
221 message: FAILED_MESSAGE,
222 }),
223 ),
224 ),
225 ),
226 // Sign-out removes the copied credential with the instance's own.
227 clear: fs.remove(usageTokenPath, { force: true }).pipe(Effect.ignore),
228 };
229});