@caio2a7/opencode-antigravity-quota 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tui.js ADDED
@@ -0,0 +1,1605 @@
1
+ // src/tui.tsx
2
+ import { createComponent as _$createComponent2 } from "opentui:runtime-module:%40opentui%2Fsolid";
3
+ import { homedir as homedir4 } from "node:os";
4
+ import { createSignal } from "opentui:runtime-module:solid-js";
5
+
6
+ // src/command.tsx
7
+ function RefreshCommand(props) {
8
+ props.keymap.layer(() => ({
9
+ mode: "global",
10
+ commands: [{
11
+ id: `${props.id}.refresh`,
12
+ title: "Refresh Antigravity quota",
13
+ group: "Antigravity Quota",
14
+ palette: true,
15
+ slash: {
16
+ name: "antigravity-quota",
17
+ aliases: ["ag-quota"]
18
+ },
19
+ run: props.run
20
+ }]
21
+ }));
22
+ return null;
23
+ }
24
+
25
+ // src/shared-state.ts
26
+ import { join } from "node:path";
27
+
28
+ // src/snapshot-codec.ts
29
+ var BUCKET_IDS = ["gemini_5h", "gemini_weekly", "gemini_argon"];
30
+ var SOURCES = ["antigravity", "gemini-cli", "cached"];
31
+ function isObject(value) {
32
+ return typeof value === "object" && value !== null && !Array.isArray(value);
33
+ }
34
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
35
+ var isNonNegInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
36
+ var isBucketId = (value) => typeof value === "string" && BUCKET_IDS.includes(value);
37
+ var isSource = (value) => typeof value === "string" && SOURCES.includes(value);
38
+ function dateOrNull(value) {
39
+ if (value === null)
40
+ return null;
41
+ if (typeof value !== "string")
42
+ return;
43
+ const date = new Date(value);
44
+ return Number.isNaN(date.getTime()) ? undefined : date;
45
+ }
46
+ var stringOrNull = (value) => value === null ? null : typeof value === "string" ? value : undefined;
47
+ function reviveBucket(value) {
48
+ if (!isObject(value) || !isBucketId(value.id) || typeof value.label !== "string")
49
+ return null;
50
+ const resetsAt = dateOrNull(value.resetsAt);
51
+ if (!isFiniteNumber(value.utilization) || !isFiniteNumber(value.remaining) || !isNonNegInt(value.modelCount) || resetsAt === undefined) {
52
+ return null;
53
+ }
54
+ return { id: value.id, label: value.label, utilization: value.utilization, remaining: value.remaining, resetsAt, modelCount: value.modelCount };
55
+ }
56
+ function revivePool(value) {
57
+ if (value === null)
58
+ return null;
59
+ if (!isObject(value))
60
+ return;
61
+ const { total, enabled, geminiReady } = value;
62
+ if (!isNonNegInt(total) || !isNonNegInt(enabled) || !isNonNegInt(geminiReady)) {
63
+ return;
64
+ }
65
+ return { total, enabled, geminiReady };
66
+ }
67
+ function reviveList(value, revive) {
68
+ if (!Array.isArray(value))
69
+ return null;
70
+ const items = value.map(revive);
71
+ return items.every((item) => item !== null) ? items : null;
72
+ }
73
+ function reviveSnapshot(value) {
74
+ if (!isObject(value) || !isSource(value.source))
75
+ return null;
76
+ const accountEmail = stringOrNull(value.accountEmail);
77
+ const buckets = reviveList(value.buckets, reviveBucket);
78
+ const pool = revivePool(value.pool);
79
+ const fetchedAt = dateOrNull(value.fetchedAt);
80
+ if (accountEmail === undefined || !buckets || pool === undefined || !fetchedAt)
81
+ return null;
82
+ return { accountEmail, source: value.source, buckets, pool, fetchedAt };
83
+ }
84
+
85
+ // src/shared-state.ts
86
+ var STATE_VERSION = 3;
87
+ var LOCK_STALE_MS = 30000;
88
+ var ERROR_KINDS = ["network", "unauthorized", "rate_limited", "http", "parse"];
89
+ function emptyState() {
90
+ return { version: STATE_VERSION, snapshot: null, fetchedAt: null, blockedUntil: 0, consecutiveFailures: 0, lastError: null };
91
+ }
92
+ function reviveError(value) {
93
+ if (!isObject(value) || typeof value.message !== "string")
94
+ return null;
95
+ const kind = value.kind;
96
+ return typeof kind === "string" && ERROR_KINDS.includes(kind) ? { kind, message: value.message } : null;
97
+ }
98
+ function reviveState(raw) {
99
+ if (!isObject(raw) || raw.version !== STATE_VERSION)
100
+ return emptyState();
101
+ const snapshot = reviveSnapshot(raw.snapshot);
102
+ const failures = raw.consecutiveFailures;
103
+ return {
104
+ version: STATE_VERSION,
105
+ snapshot,
106
+ fetchedAt: snapshot && isFiniteNumber(raw.fetchedAt) ? raw.fetchedAt : null,
107
+ blockedUntil: isFiniteNumber(raw.blockedUntil) ? raw.blockedUntil : 0,
108
+ consecutiveFailures: isFiniteNumber(failures) && failures > 0 ? Math.floor(failures) : 0,
109
+ lastError: reviveError(raw.lastError)
110
+ };
111
+ }
112
+ function atomicWrite(fs, dir, statePath, state) {
113
+ const tmp = `${statePath}.${process.pid}-${Math.random().toString(36).slice(2)}.tmp`;
114
+ try {
115
+ fs.mkdirp(dir);
116
+ fs.writeText(tmp, JSON.stringify(state));
117
+ fs.rename(tmp, statePath);
118
+ return true;
119
+ } catch {
120
+ try {
121
+ fs.remove(tmp);
122
+ } catch {}
123
+ return false;
124
+ }
125
+ }
126
+ function acquireLock(fs, dir, lockPath, now) {
127
+ try {
128
+ fs.mkdirp(dir);
129
+ const acquire = () => fs.createExclusive(lockPath, String(now()));
130
+ const clearStale = () => {
131
+ const modified = fs.mtimeMs(lockPath);
132
+ if (modified !== null && now() - modified <= LOCK_STALE_MS)
133
+ return false;
134
+ fs.remove(lockPath);
135
+ return true;
136
+ };
137
+ if (!acquire() && !(clearStale() && acquire()))
138
+ return null;
139
+ return () => {
140
+ try {
141
+ fs.remove(lockPath);
142
+ } catch {}
143
+ };
144
+ } catch {
145
+ return () => {};
146
+ }
147
+ }
148
+ function createSharedStore({ dir, fs, now }) {
149
+ const statePath = join(dir, "state.json");
150
+ const lockPath = join(dir, "fetch.lock");
151
+ return {
152
+ read() {
153
+ try {
154
+ return reviveState(JSON.parse(fs.readText(statePath)));
155
+ } catch {
156
+ return emptyState();
157
+ }
158
+ },
159
+ write: (state) => atomicWrite(fs, dir, statePath, state),
160
+ tryLock: () => acquireLock(fs, dir, lockPath, now)
161
+ };
162
+ }
163
+
164
+ // src/coordinator.ts
165
+ var BACKOFF_BASE_MS = 2 * 60000;
166
+ var BACKOFF_MAX_MS = 30 * 60000;
167
+ var LOCK_RETRY_MS = 3000;
168
+ var MIN_ADOPT_DELAY_MS = 5000;
169
+ var LOCAL_BACKOFF_MAX_MS = 10 * 60000;
170
+ var SHARED_KINDS = new Set(["network", "http", "rate_limited"]);
171
+ var backoffMs = (failures) => Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, failures - 1));
172
+ function matchesExpectedAccount(snapshot, expected) {
173
+ if (!snapshot)
174
+ return false;
175
+ if (expected === null)
176
+ return true;
177
+ return snapshot.accountEmail !== null && snapshot.accountEmail.toLowerCase() === expected.toLowerCase();
178
+ }
179
+ function resolveExpected(o) {
180
+ try {
181
+ return o.expectedAccountEmail ? o.expectedAccountEmail() : null;
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+ function blocked(state, remainingMs, expected) {
187
+ const base = {
188
+ ok: false,
189
+ kind: state.lastError?.kind ?? "rate_limited",
190
+ message: state.lastError?.message ?? "Antigravity quota endpoint rate limited (HTTP 429)",
191
+ retryAfterMs: remainingMs,
192
+ nextInMs: remainingMs
193
+ };
194
+ return matchesExpectedAccount(state.snapshot, expected) && state.snapshot ? { ...base, snapshot: state.snapshot } : base;
195
+ }
196
+ function fromShared(o, state, req) {
197
+ const now = o.now();
198
+ const expected = resolveExpected(o);
199
+ const accountMismatch = state.snapshot !== null && !matchesExpectedAccount(state.snapshot, expected);
200
+ if (state.blockedUntil > now && !accountMismatch)
201
+ return blocked(state, state.blockedUntil - now, expected);
202
+ if (!state.snapshot || state.fetchedAt === null || accountMismatch)
203
+ return null;
204
+ const age = now - state.fetchedAt;
205
+ if (age >= req.maxAgeMs)
206
+ return null;
207
+ return { ok: true, snapshot: state.snapshot, nextInMs: Math.max(MIN_ADOPT_DELAY_MS, o.intervalMs - age) };
208
+ }
209
+ function waiting(state, expected) {
210
+ if (matchesExpectedAccount(state.snapshot, expected) && state.snapshot) {
211
+ return { ok: true, snapshot: state.snapshot, nextInMs: LOCK_RETRY_MS };
212
+ }
213
+ return { ok: false, kind: "internal", message: "Waiting for another OpenCode window…", nextInMs: LOCK_RETRY_MS };
214
+ }
215
+ function keepSnapshot(result, snapshot, expected) {
216
+ return matchesExpectedAccount(snapshot, expected) && snapshot && !result.ok ? { ...result, snapshot } : result;
217
+ }
218
+ function createCoordinator(o) {
219
+ let localFailures = 0;
220
+ async function fetchAndPersist(prior) {
221
+ const result = await o.fetchOnce();
222
+ const expected = resolveExpected(o);
223
+ if (result.ok) {
224
+ localFailures = 0;
225
+ const fetchedAt = result.snapshot.fetchedAt.getTime();
226
+ o.store.write({ version: STATE_VERSION, snapshot: result.snapshot, fetchedAt, blockedUntil: 0, consecutiveFailures: 0, lastError: null });
227
+ return { ...result, nextInMs: o.intervalMs };
228
+ }
229
+ if (SHARED_KINDS.has(result.kind)) {
230
+ const failures = prior.consecutiveFailures + 1;
231
+ const delay2 = result.kind === "rate_limited" && result.retryAfterMs ? result.retryAfterMs : backoffMs(failures);
232
+ const lastError = { kind: result.kind, message: result.message };
233
+ o.store.write({ ...prior, consecutiveFailures: failures, blockedUntil: o.now() + delay2, lastError });
234
+ return keepSnapshot({ ...result, retryAfterMs: delay2, nextInMs: delay2 }, prior.snapshot, expected);
235
+ }
236
+ localFailures = result.kind === "unauthorized" ? localFailures + 1 : 0;
237
+ const delay = Math.min(LOCAL_BACKOFF_MAX_MS, o.intervalMs * 2 ** Math.max(0, localFailures - 1));
238
+ return keepSnapshot({ ...result, nextInMs: delay }, prior.snapshot, expected);
239
+ }
240
+ return async (req) => {
241
+ const early = fromShared(o, o.store.read(), req);
242
+ if (early)
243
+ return early;
244
+ const release = o.store.tryLock();
245
+ if (!release)
246
+ return waiting(o.store.read(), resolveExpected(o));
247
+ try {
248
+ const current = o.store.read();
249
+ return fromShared(o, current, req) ?? await fetchAndPersist(current);
250
+ } finally {
251
+ release();
252
+ }
253
+ };
254
+ }
255
+
256
+ // src/loader.ts
257
+ import { readFileSync } from "node:fs";
258
+ import { homedir as homedir3 } from "node:os";
259
+
260
+ // src/api.ts
261
+ import { createHash } from "node:crypto";
262
+
263
+ // src/parse.ts
264
+ class QuotaParseError extends Error {
265
+ constructor(message) {
266
+ super(message);
267
+ this.name = "QuotaParseError";
268
+ }
269
+ }
270
+ var DAY_MS = 24 * 60 * 60000;
271
+ var BUCKET_ORDER = [
272
+ ["gemini_5h", "Gemini-5h"],
273
+ ["gemini_weekly", "Gemini-Week"],
274
+ ["gemini_argon", "Argon"]
275
+ ];
276
+ var CACHED_KEY_MAP = {
277
+ "gemini-5h": "gemini_5h",
278
+ gemini_5h: "gemini_5h",
279
+ gemini: "gemini_5h",
280
+ "gemini-pro": "gemini_5h",
281
+ gemini_pro: "gemini_5h",
282
+ "gemini-flash": "gemini_5h",
283
+ gemini_flash: "gemini_5h",
284
+ "gemini-weekly": "gemini_weekly",
285
+ gemini_weekly: "gemini_weekly",
286
+ "gemini-argon": "gemini_argon",
287
+ gemini_argon: "gemini_argon",
288
+ argon: "gemini_argon"
289
+ };
290
+ function isObj(v) {
291
+ return typeof v === "object" && v !== null && !Array.isArray(v);
292
+ }
293
+ function normalizeRemainingFraction(value) {
294
+ if (typeof value !== "number" || !Number.isFinite(value))
295
+ return 0;
296
+ if (value <= 0)
297
+ return 0;
298
+ if (value >= 1)
299
+ return 1;
300
+ return value;
301
+ }
302
+ function parseIsoDate(value) {
303
+ if (typeof value !== "string" || value.trim() === "")
304
+ return null;
305
+ const date = new Date(value);
306
+ return Number.isNaN(date.getTime()) ? null : date;
307
+ }
308
+ function classifyBucket(modelId, displayName) {
309
+ const idLower = modelId.toLowerCase();
310
+ if (idLower.startsWith("tab_"))
311
+ return null;
312
+ const combined = `${idLower} ${(displayName ?? "").toLowerCase()}`;
313
+ if (combined.includes("claude") || combined.includes("gpt"))
314
+ return null;
315
+ if (!combined.includes("gemini"))
316
+ return null;
317
+ return combined.includes("argon") ? "gemini_argon" : "gemini_5h";
318
+ }
319
+ function classifySummaryBucket(bucketId, window) {
320
+ if (typeof bucketId !== "string" || bucketId.trim() === "")
321
+ return null;
322
+ const id = bucketId.trim().toLowerCase();
323
+ if (id.startsWith("3p-") || id.includes("claude") || id.includes("gpt"))
324
+ return null;
325
+ if (id.includes("argon"))
326
+ return "gemini_argon";
327
+ const win = typeof window === "string" ? window.trim().toLowerCase() : "";
328
+ if (id === "gemini-5h" || id.startsWith("gemini-") && win === "5h")
329
+ return "gemini_5h";
330
+ if (id === "gemini-weekly" || id.startsWith("gemini-") && win === "weekly")
331
+ return "gemini_weekly";
332
+ return null;
333
+ }
334
+ function resolveModelWindowBucket(bucketId, resetsAt, now) {
335
+ if (bucketId === "gemini_argon")
336
+ return "gemini_argon";
337
+ return resetsAt !== null && resetsAt.getTime() - now.getTime() > DAY_MS ? "gemini_weekly" : "gemini_5h";
338
+ }
339
+ function accumulate(map, id, remainingFraction, resetsAt, count = 1) {
340
+ const prev = map.get(id);
341
+ if (!prev) {
342
+ map.set(id, { remainingFraction, resetsAt, modelCount: count });
343
+ return;
344
+ }
345
+ prev.modelCount += count;
346
+ if (remainingFraction < prev.remainingFraction) {
347
+ prev.remainingFraction = remainingFraction;
348
+ prev.resetsAt = resetsAt;
349
+ } else if (remainingFraction === prev.remainingFraction && resetsAt !== null) {
350
+ if (prev.resetsAt === null || resetsAt.getTime() < prev.resetsAt.getTime()) {
351
+ prev.resetsAt = resetsAt;
352
+ }
353
+ }
354
+ }
355
+ function toOrderedBuckets(map) {
356
+ const out = [];
357
+ for (const [id, label] of BUCKET_ORDER) {
358
+ const acc = map.get(id);
359
+ if (!acc)
360
+ continue;
361
+ const remaining = Math.min(100, Math.max(0, Math.round(acc.remainingFraction * 1000) / 10));
362
+ const utilization = Math.min(100, Math.max(0, Math.round((100 - remaining) * 10) / 10));
363
+ out.push({ id, label, utilization, remaining, resetsAt: acc.resetsAt, modelCount: acc.modelCount });
364
+ }
365
+ return out;
366
+ }
367
+ function parseQuotaSummaryResponse(payload, meta, now = meta.fetchedAt ?? new Date) {
368
+ if (!isObj(payload) || !Array.isArray(payload.groups)) {
369
+ throw new QuotaParseError("Quota summary response is missing `groups` array");
370
+ }
371
+ const acc = new Map;
372
+ for (const group of payload.groups) {
373
+ if (!isObj(group) || !Array.isArray(group.buckets))
374
+ continue;
375
+ for (const bucket of group.buckets) {
376
+ if (!isObj(bucket) || bucket.disabled === true)
377
+ continue;
378
+ const bucketId = classifySummaryBucket(bucket.bucketId, bucket.window);
379
+ if (!bucketId)
380
+ continue;
381
+ accumulate(acc, bucketId, normalizeRemainingFraction(bucket.remainingFraction), parseIsoDate(bucket.resetTime));
382
+ }
383
+ }
384
+ return {
385
+ accountEmail: meta.accountEmail,
386
+ source: meta.source ?? "antigravity",
387
+ buckets: toOrderedBuckets(acc),
388
+ pool: meta.pool,
389
+ fetchedAt: now
390
+ };
391
+ }
392
+ function parseAvailableModelsResponse(raw, meta, now = meta.fetchedAt ?? new Date) {
393
+ if (!isObj(raw))
394
+ throw new QuotaParseError("Available models response is not a JSON object");
395
+ if (raw.models !== undefined && !isObj(raw.models))
396
+ throw new QuotaParseError("Response field `models` is not an object");
397
+ const models = isObj(raw.models) ? raw.models : {};
398
+ const acc = new Map;
399
+ for (const [modelId, entry] of Object.entries(models)) {
400
+ if (!isObj(entry) || entry.disabled === true || !isObj(entry.quotaInfo))
401
+ continue;
402
+ const labelHint = typeof entry.displayName === "string" ? entry.displayName : typeof entry.modelName === "string" ? entry.modelName : undefined;
403
+ const baseBucket = classifyBucket(modelId, labelHint);
404
+ if (!baseBucket)
405
+ continue;
406
+ const resetsAt = parseIsoDate(entry.quotaInfo.resetTime);
407
+ const bucketId = resolveModelWindowBucket(baseBucket, resetsAt, now);
408
+ accumulate(acc, bucketId, normalizeRemainingFraction(entry.quotaInfo.remainingFraction), resetsAt);
409
+ }
410
+ return {
411
+ accountEmail: meta.accountEmail,
412
+ source: meta.source ?? "antigravity",
413
+ buckets: toOrderedBuckets(acc),
414
+ pool: meta.pool,
415
+ fetchedAt: now
416
+ };
417
+ }
418
+ function parseRetrieveUserQuotaResponse(raw, meta, now = meta.fetchedAt ?? new Date) {
419
+ if (!isObj(raw))
420
+ throw new QuotaParseError("Retrieve user quota response is not a JSON object");
421
+ if (raw.buckets !== undefined && !Array.isArray(raw.buckets))
422
+ throw new QuotaParseError("Response field `buckets` is not an array");
423
+ const items = Array.isArray(raw.buckets) ? raw.buckets : [];
424
+ const acc = new Map;
425
+ for (const item of items) {
426
+ if (!isObj(item) || typeof item.modelId !== "string" || item.modelId.trim() === "")
427
+ continue;
428
+ const baseBucket = classifyBucket(item.modelId);
429
+ if (!baseBucket)
430
+ continue;
431
+ const resetsAt = parseIsoDate(item.resetTime);
432
+ const bucketId = resolveModelWindowBucket(baseBucket, resetsAt, now);
433
+ accumulate(acc, bucketId, normalizeRemainingFraction(item.remainingFraction), resetsAt);
434
+ }
435
+ return {
436
+ accountEmail: meta.accountEmail,
437
+ source: meta.source ?? "gemini-cli",
438
+ buckets: toOrderedBuckets(acc),
439
+ pool: meta.pool,
440
+ fetchedAt: now
441
+ };
442
+ }
443
+ function parseCachedQuota(cachedQuota, meta, updatedAt) {
444
+ if (!isObj(cachedQuota))
445
+ return null;
446
+ const acc = new Map;
447
+ for (const [key, entry] of Object.entries(cachedQuota)) {
448
+ const bucketId = CACHED_KEY_MAP[key.toLowerCase()];
449
+ if (!bucketId || !isObj(entry))
450
+ continue;
451
+ const remainingFraction = normalizeRemainingFraction(entry.remainingFraction);
452
+ const resetsAt = parseIsoDate(entry.remainingFractionResetTime) ?? parseIsoDate(entry.resetTime);
453
+ const count = typeof entry.modelCount === "number" && Number.isInteger(entry.modelCount) && entry.modelCount > 0 ? entry.modelCount : 1;
454
+ accumulate(acc, bucketId, remainingFraction, resetsAt, count);
455
+ }
456
+ const buckets = toOrderedBuckets(acc);
457
+ if (buckets.length === 0)
458
+ return null;
459
+ return {
460
+ accountEmail: meta.accountEmail,
461
+ source: "cached",
462
+ buckets,
463
+ pool: meta.pool,
464
+ fetchedAt: updatedAt
465
+ };
466
+ }
467
+
468
+ // src/api.ts
469
+ var ANTIGRAVITY_BASE_URL = "https://daily-cloudcode-pa.googleapis.com";
470
+ var ANTIGRAVITY_QUOTA_SUMMARY_URL = `${ANTIGRAVITY_BASE_URL}/v1internal:retrieveUserQuotaSummary`;
471
+ var ANTIGRAVITY_MODELS_URL = `${ANTIGRAVITY_BASE_URL}/v1internal:fetchAvailableModels`;
472
+ var ANTIGRAVITY_LOAD_CODE_ASSIST_URL = `${ANTIGRAVITY_BASE_URL}/v1internal:loadCodeAssist`;
473
+ var ANTIGRAVITY_RETRIEVE_QUOTA_URL = `${ANTIGRAVITY_BASE_URL}/v1internal:retrieveUserQuota`;
474
+ var GEMINI_CLI_QUOTA_URL = "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota";
475
+ var DEFAULT_ANTIGRAVITY_USER_AGENT = "antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64)";
476
+ var GEMINI_CLI_HEADERS = {
477
+ "User-Agent": "google-api-nodejs-client/9.15.1",
478
+ "X-Goog-Api-Client": "gl-node/22.17.0",
479
+ "Client-Metadata": "ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI"
480
+ };
481
+ var DEFAULT_TIMEOUT_MS = 1e4;
482
+ var MAX_RETRY_MS = 60 * 60000;
483
+ var MAX_PROJECT_CACHE = 64;
484
+ var defaultProjectCache = new Map;
485
+ function retryAfterMs(header) {
486
+ const seconds = header === null ? NaN : Number(header.trim());
487
+ return header !== null && header.trim() !== "" && Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds * 1000, MAX_RETRY_MS) : undefined;
488
+ }
489
+ function failure(kind, message, retryMs) {
490
+ return retryMs === undefined ? { ok: false, kind, message } : { ok: false, kind, message, retryAfterMs: retryMs };
491
+ }
492
+ function statusFailure(res, label) {
493
+ if (res.status === 401 || res.status === 403) {
494
+ return failure("unauthorized", `${label} rejected the token (HTTP ${res.status}) — re-authenticate your account`);
495
+ }
496
+ if (res.status === 429) {
497
+ return failure("rate_limited", `${label} endpoint rate limited (HTTP 429)`, retryAfterMs(res.headers.get("retry-after")));
498
+ }
499
+ return failure("http", `${label} endpoint returned HTTP ${res.status}`);
500
+ }
501
+ function networkFailure(err) {
502
+ const reason = err instanceof Error && err.name === "AbortError" ? "request timed out" : "request failed";
503
+ return failure("network", `Network error: ${reason}`);
504
+ }
505
+ async function postJson(url, headers, body, opts) {
506
+ const controller = new AbortController;
507
+ const timer = setTimeout(() => controller.abort(), opts.timeoutMs);
508
+ try {
509
+ const res = await opts.fetchFn(url, {
510
+ method: "POST",
511
+ headers,
512
+ body: JSON.stringify(body),
513
+ signal: controller.signal
514
+ });
515
+ return res.ok ? await res.text() : res;
516
+ } finally {
517
+ clearTimeout(timer);
518
+ }
519
+ }
520
+ function extractProjectId(payload) {
521
+ if (typeof payload !== "object" || payload === null)
522
+ return null;
523
+ const value = payload.cloudaicompanionProject;
524
+ const raw = typeof value === "string" ? value : typeof value === "object" && value !== null ? value.id : null;
525
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
526
+ }
527
+ function projectCacheKey(accessToken, email) {
528
+ if (email && email.trim() !== "")
529
+ return `email:${email.trim().toLowerCase()}`;
530
+ return `tok:${createHash("sha256").update(accessToken).digest("hex").slice(0, 24)}`;
531
+ }
532
+ async function discoverProjectId(accessToken, opts = {}) {
533
+ const cache = opts.projectCache ?? defaultProjectCache;
534
+ const key = projectCacheKey(accessToken, opts.accountEmail);
535
+ const cached = cache.get(key);
536
+ if (cached)
537
+ return cached;
538
+ const headers = {
539
+ Authorization: `Bearer ${accessToken}`,
540
+ "Content-Type": "application/json",
541
+ "User-Agent": opts.userAgent?.trim() || DEFAULT_ANTIGRAVITY_USER_AGENT
542
+ };
543
+ try {
544
+ const outcome = await postJson(ANTIGRAVITY_LOAD_CODE_ASSIST_URL, headers, { metadata: { ideType: "ANTIGRAVITY" } }, { fetchFn: opts.fetch ?? fetch, timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS });
545
+ if (typeof outcome !== "string")
546
+ return null;
547
+ const id = extractProjectId(JSON.parse(outcome));
548
+ if (id) {
549
+ cache.set(key, id);
550
+ if (cache.size > MAX_PROJECT_CACHE) {
551
+ const oldest = cache.keys().next().value;
552
+ if (oldest !== undefined)
553
+ cache.delete(oldest);
554
+ }
555
+ }
556
+ return id;
557
+ } catch {
558
+ return null;
559
+ }
560
+ }
561
+ async function callAndParse(url, headers, body, label, parse, opts) {
562
+ let outcome;
563
+ try {
564
+ outcome = await postJson(url, headers, body, opts);
565
+ } catch (err) {
566
+ return networkFailure(err);
567
+ }
568
+ if (typeof outcome !== "string")
569
+ return statusFailure(outcome, label);
570
+ try {
571
+ return parse(JSON.parse(outcome));
572
+ } catch {
573
+ return failure("parse", `Unexpected response from the ${label} endpoint`);
574
+ }
575
+ }
576
+ var TERMINAL_SUMMARY_ERRORS = new Set(["unauthorized", "rate_limited", "network"]);
577
+ async function fetchAntigravityLegacy(headers, body, meta, now, reqOpts) {
578
+ const models = await callAndParse(ANTIGRAVITY_MODELS_URL, headers, body, "Antigravity quota", (raw) => ({ ok: true, snapshot: parseAvailableModelsResponse(raw, meta, now()) }), reqOpts);
579
+ if (!models.ok || models.snapshot.buckets.length > 0)
580
+ return models;
581
+ const fallback = await callAndParse(ANTIGRAVITY_RETRIEVE_QUOTA_URL, headers, body, "Antigravity quota", (raw) => ({ ok: true, snapshot: parseRetrieveUserQuotaResponse(raw, meta, now()) }), reqOpts);
582
+ return fallback.ok ? fallback : models;
583
+ }
584
+ async function fetchAntigravityQuota(accessToken, opts = {}) {
585
+ const fetchFn = opts.fetch ?? fetch;
586
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
587
+ const now = opts.now ?? (() => new Date);
588
+ const userAgent = opts.userAgent?.trim() || DEFAULT_ANTIGRAVITY_USER_AGENT;
589
+ const headers = {
590
+ Authorization: `Bearer ${accessToken}`,
591
+ "Content-Type": "application/json",
592
+ "User-Agent": userAgent
593
+ };
594
+ const projectId = opts.projectId?.trim() || await discoverProjectId(accessToken, {
595
+ fetch: fetchFn,
596
+ timeoutMs,
597
+ userAgent,
598
+ accountEmail: opts.accountEmail,
599
+ projectCache: opts.projectCache
600
+ });
601
+ const body = projectId ? { project: projectId } : {};
602
+ const meta = { accountEmail: opts.accountEmail ?? null, pool: opts.pool ?? null, source: "antigravity" };
603
+ const reqOpts = { fetchFn, timeoutMs };
604
+ const summary = await callAndParse(ANTIGRAVITY_QUOTA_SUMMARY_URL, headers, body, "Antigravity quota", (raw) => ({ ok: true, snapshot: parseQuotaSummaryResponse(raw, meta, now()) }), reqOpts);
605
+ if (summary.ok && summary.snapshot.buckets.length > 0)
606
+ return summary;
607
+ if (!summary.ok && TERMINAL_SUMMARY_ERRORS.has(summary.kind))
608
+ return summary;
609
+ return fetchAntigravityLegacy(headers, body, meta, now, reqOpts);
610
+ }
611
+ async function fetchGeminiCliQuota(accessToken, opts = {}) {
612
+ const fetchFn = opts.fetch ?? fetch;
613
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
614
+ const now = opts.now ?? (() => new Date);
615
+ const headers = {
616
+ ...GEMINI_CLI_HEADERS,
617
+ Authorization: `Bearer ${accessToken}`,
618
+ "Content-Type": "application/json"
619
+ };
620
+ const projectId = opts.projectId?.trim() || null;
621
+ const body = projectId ? { project: projectId } : {};
622
+ const meta = { accountEmail: opts.accountEmail ?? null, pool: opts.pool ?? null, source: "gemini-cli" };
623
+ return callAndParse(GEMINI_CLI_QUOTA_URL, headers, body, "Gemini CLI quota", (raw) => ({ ok: true, snapshot: parseRetrieveUserQuotaResponse(raw, meta, now()) }), { fetchFn, timeoutMs });
624
+ }
625
+
626
+ // src/credentials.ts
627
+ import { readFile as fsReadFile } from "node:fs/promises";
628
+ import { homedir } from "node:os";
629
+ import { join as join2 } from "node:path";
630
+ var EXPIRY_BUFFER_MS = 60000;
631
+ var MISSING_MSG = "Antigravity/Gemini credentials not found — log in via opencode-antigravity-auth or Gemini CLI";
632
+ var INVALID_MSG = "Antigravity/Gemini credentials file is unreadable or malformed";
633
+ var EXPIRED_GEMINI_MSG = "Gemini CLI token expired — run `gemini` once to refresh it";
634
+ var EXPIRED_CLI_MSG = "Antigravity CLI token expired and has no refresh token — log in again";
635
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
636
+ var nonEmpty = (v) => typeof v === "string" && v.trim() !== "" ? v.trim() : null;
637
+ function defaultCredentialDeps() {
638
+ return {
639
+ env: process.env,
640
+ homeDir: homedir(),
641
+ readFile: (p) => fsReadFile(p, "utf8"),
642
+ now: new Date,
643
+ platform: process.platform
644
+ };
645
+ }
646
+ function accountCandidatePaths(env, homeDir, platform) {
647
+ const override = nonEmpty(env.OPENCODE_CONFIG_DIR);
648
+ const xdg = nonEmpty(env.XDG_CONFIG_HOME) ?? join2(homeDir, ".config");
649
+ const primary = join2(override ?? join2(xdg, "opencode"), "antigravity-accounts.json");
650
+ if (platform !== "win32")
651
+ return [primary];
652
+ const appData = nonEmpty(env.APPDATA) ?? join2(homeDir, "AppData", "Roaming");
653
+ const legacy = join2(appData, "opencode", "antigravity-accounts.json");
654
+ return legacy === primary ? [primary] : [primary, legacy];
655
+ }
656
+ var antigravityCliTokenPath = (homeDir) => join2(homeDir, ".gemini", "antigravity-cli", "antigravity-oauth-token");
657
+ var geminiCliCredsPath = (homeDir) => join2(homeDir, ".gemini", "oauth_creds.json");
658
+ function parseExpiry(value) {
659
+ if (typeof value === "number" && Number.isFinite(value)) {
660
+ const date = new Date(value > 100000000000 ? value : value * 1000);
661
+ return Number.isNaN(date.getTime()) ? null : date;
662
+ }
663
+ return parseIsoDate(value);
664
+ }
665
+ var isTokenFresh = (expiry, now) => expiry !== null && expiry.getTime() > now.getTime() + EXPIRY_BUFFER_MS;
666
+ function parseRawAccount(item) {
667
+ if (!isObj2(item))
668
+ return null;
669
+ const refreshToken = nonEmpty(item.refreshToken);
670
+ if (!refreshToken)
671
+ return null;
672
+ const fp = isObj2(item.fingerprint) ? item.fingerprint : null;
673
+ const updatedAt = typeof item.cachedQuotaUpdatedAt === "number" && Number.isFinite(item.cachedQuotaUpdatedAt) ? item.cachedQuotaUpdatedAt : null;
674
+ return {
675
+ refreshToken,
676
+ email: nonEmpty(item.email),
677
+ projectId: nonEmpty(item.managedProjectId) ?? nonEmpty(item.projectId),
678
+ enabled: item.enabled !== false,
679
+ userAgent: fp ? nonEmpty(fp.userAgent) : null,
680
+ cachedQuota: isObj2(item.cachedQuota) ? item.cachedQuota : null,
681
+ cachedQuotaUpdatedAt: updatedAt,
682
+ rateLimitResetTimes: isObj2(item.rateLimitResetTimes) ? item.rateLimitResetTimes : null
683
+ };
684
+ }
685
+ function selectActiveAccount(raw, accounts) {
686
+ const byIdx = (idx) => {
687
+ if (typeof idx !== "number" || !Number.isInteger(idx) || idx < 0 || idx >= accounts.length)
688
+ return null;
689
+ const acc = accounts[idx];
690
+ return acc && acc.enabled ? acc : null;
691
+ };
692
+ const byFamily = isObj2(raw.activeIndexByFamily) ? raw.activeIndexByFamily : null;
693
+ return byIdx(raw.activeIndex) ?? byIdx(byFamily?.gemini) ?? accounts.find((a) => a.enabled) ?? accounts[0] ?? null;
694
+ }
695
+ function isGroupReady(group, nowMs) {
696
+ if (!isObj2(group))
697
+ return true;
698
+ if (normalizeRemainingFraction(group.remainingFraction) > 0)
699
+ return true;
700
+ const reset = parseIsoDate(group.remainingFractionResetTime) ?? parseIsoDate(group.resetTime);
701
+ return reset !== null && reset.getTime() <= nowMs;
702
+ }
703
+ function isGeminiReady(acc, nowMs) {
704
+ if (!acc.cachedQuota) {
705
+ const rl = acc.rateLimitResetTimes?.["gemini-antigravity"] ?? acc.rateLimitResetTimes?.gemini;
706
+ return !(typeof rl === "number" && Number.isFinite(rl) && rl > nowMs);
707
+ }
708
+ const keys = ["gemini", "gemini-pro", "gemini_pro", "gemini-flash", "gemini_flash", "gemini-argon", "gemini_argon", "argon"];
709
+ const entries = keys.map((k) => acc.cachedQuota?.[k]).filter(isObj2);
710
+ return entries.length === 0 ? true : entries.some((entry) => isGroupReady(entry, nowMs));
711
+ }
712
+ function computePool(accounts, nowMs) {
713
+ const enabledList = accounts.filter((a) => a.enabled);
714
+ if (enabledList.length <= 1)
715
+ return null;
716
+ let geminiReady = 0;
717
+ for (const acc of enabledList) {
718
+ if (isGeminiReady(acc, nowMs))
719
+ geminiReady += 1;
720
+ }
721
+ return { total: accounts.length, enabled: enabledList.length, geminiReady };
722
+ }
723
+ function extractActiveAccountEmailFromJson(parsed) {
724
+ if (!isObj2(parsed))
725
+ return null;
726
+ if (Array.isArray(parsed.accounts)) {
727
+ const accounts = parsed.accounts.map(parseRawAccount).filter((a) => a !== null);
728
+ return selectActiveAccount(parsed, accounts)?.email ?? null;
729
+ }
730
+ if (isObj2(parsed.token))
731
+ return nonEmpty(parsed.id_token_email);
732
+ return null;
733
+ }
734
+ async function tryReadJson(deps, path) {
735
+ let content;
736
+ try {
737
+ content = await deps.readFile(path);
738
+ } catch {
739
+ return { found: false, data: undefined };
740
+ }
741
+ try {
742
+ return { found: true, data: JSON.parse(content) };
743
+ } catch {
744
+ return { found: true, data: undefined };
745
+ }
746
+ }
747
+ async function lookupReusableCliToken(deps, email) {
748
+ if (!email)
749
+ return null;
750
+ const { data } = await tryReadJson(deps, antigravityCliTokenPath(deps.homeDir));
751
+ if (!isObj2(data) || !isObj2(data.token))
752
+ return null;
753
+ const cliEmail = nonEmpty(data.id_token_email);
754
+ if (!cliEmail || cliEmail.toLowerCase() !== email.toLowerCase())
755
+ return null;
756
+ const accessToken = nonEmpty(data.token.access_token);
757
+ const expiry = parseExpiry(data.token.expiry);
758
+ return accessToken && isTokenFresh(expiry, deps.now) && expiry ? { token: accessToken, expiresAt: expiry } : null;
759
+ }
760
+ function okCred(source, apiKind, fields) {
761
+ return {
762
+ ok: true,
763
+ source,
764
+ apiKind,
765
+ accessToken: fields.accessToken ?? null,
766
+ accessTokenExpiresAt: fields.accessTokenExpiresAt ?? null,
767
+ refreshToken: fields.refreshToken ?? null,
768
+ email: fields.email ?? null,
769
+ projectId: fields.projectId ?? null,
770
+ userAgent: fields.userAgent ?? null,
771
+ pool: fields.pool ?? null,
772
+ cachedFallback: fields.cachedFallback ?? null
773
+ };
774
+ }
775
+ async function interpretAccountsFile(parsed, deps) {
776
+ if (!Array.isArray(parsed.accounts))
777
+ return null;
778
+ const accounts = parsed.accounts.map(parseRawAccount).filter((a) => a !== null);
779
+ const active = selectActiveAccount(parsed, accounts);
780
+ if (!active)
781
+ return null;
782
+ const pool = computePool(accounts, deps.now.getTime());
783
+ const reusable = await lookupReusableCliToken(deps, active.email);
784
+ const updatedAt = active.cachedQuotaUpdatedAt !== null ? new Date(active.cachedQuotaUpdatedAt) : deps.now;
785
+ const cachedFallback = active.cachedQuota ? parseCachedQuota(active.cachedQuota, { accountEmail: active.email, pool }, updatedAt) : null;
786
+ return okCred("antigravity-accounts", "antigravity", {
787
+ accessToken: reusable?.token ?? null,
788
+ accessTokenExpiresAt: reusable?.expiresAt ?? null,
789
+ refreshToken: active.refreshToken,
790
+ email: active.email,
791
+ projectId: active.projectId,
792
+ userAgent: active.userAgent,
793
+ pool,
794
+ cachedFallback
795
+ });
796
+ }
797
+ function interpretAntigravityCli(parsed, now) {
798
+ if (!isObj2(parsed.token))
799
+ return { ok: false, reason: "invalid", message: INVALID_MSG };
800
+ const access = nonEmpty(parsed.token.access_token);
801
+ const refresh = nonEmpty(parsed.token.refresh_token);
802
+ const expiry = parseExpiry(parsed.token.expiry);
803
+ const freshAccess = access && isTokenFresh(expiry, now) ? access : null;
804
+ if (!freshAccess && !refresh)
805
+ return { ok: false, reason: access ? "expired" : "invalid", message: access ? EXPIRED_CLI_MSG : INVALID_MSG };
806
+ return okCred("antigravity-cli", "antigravity", {
807
+ accessToken: freshAccess,
808
+ accessTokenExpiresAt: freshAccess ? expiry : null,
809
+ refreshToken: refresh,
810
+ email: nonEmpty(parsed.id_token_email)
811
+ });
812
+ }
813
+ function interpretGeminiCli(parsed, now) {
814
+ const access = nonEmpty(parsed.access_token);
815
+ if (!access)
816
+ return { ok: false, reason: "invalid", message: INVALID_MSG };
817
+ const expiry = parseExpiry(parsed.expiry_date);
818
+ if (!isTokenFresh(expiry, now))
819
+ return { ok: false, reason: "expired", message: EXPIRED_GEMINI_MSG };
820
+ return okCred("gemini-cli", "gemini-cli", {
821
+ accessToken: access,
822
+ accessTokenExpiresAt: expiry,
823
+ refreshToken: nonEmpty(parsed.refresh_token),
824
+ projectId: nonEmpty(parsed.project_id)
825
+ });
826
+ }
827
+ async function resolveExplicitFile(path, deps) {
828
+ const { found, data } = await tryReadJson(deps, path);
829
+ if (!found)
830
+ return { ok: false, reason: "missing", message: `Credentials file not found at ${path}` };
831
+ if (!isObj2(data))
832
+ return { ok: false, reason: "invalid", message: INVALID_MSG };
833
+ if (Array.isArray(data.accounts)) {
834
+ return await interpretAccountsFile(data, deps) ?? { ok: false, reason: "invalid", message: INVALID_MSG };
835
+ }
836
+ if (isObj2(data.token))
837
+ return interpretAntigravityCli(data, deps.now);
838
+ if (typeof data.access_token === "string" || typeof data.refresh_token === "string") {
839
+ return interpretGeminiCli(data, deps.now);
840
+ }
841
+ return { ok: false, reason: "invalid", message: INVALID_MSG };
842
+ }
843
+ function envCredential(env) {
844
+ const accessToken = nonEmpty(env.ANTIGRAVITY_OAUTH_TOKEN);
845
+ return accessToken ? okCred("env", "antigravity", { accessToken, projectId: nonEmpty(env.ANTIGRAVITY_PROJECT_ID) }) : null;
846
+ }
847
+ async function resolveAccountsFromDefaultPaths(deps) {
848
+ for (const path of accountCandidatePaths(deps.env, deps.homeDir, deps.platform)) {
849
+ const { data } = await tryReadJson(deps, path);
850
+ if (isObj2(data)) {
851
+ const resolved = await interpretAccountsFile(data, deps);
852
+ if (resolved)
853
+ return resolved;
854
+ }
855
+ }
856
+ return null;
857
+ }
858
+ async function resolveCredentials(deps) {
859
+ const fromEnv = envCredential(deps.env);
860
+ if (fromEnv)
861
+ return fromEnv;
862
+ if (deps.credentialsPath)
863
+ return resolveExplicitFile(deps.credentialsPath, deps);
864
+ const fromAccounts = await resolveAccountsFromDefaultPaths(deps);
865
+ if (fromAccounts)
866
+ return fromAccounts;
867
+ const cli = await tryReadJson(deps, antigravityCliTokenPath(deps.homeDir));
868
+ if (isObj2(cli.data) && isObj2(cli.data.token)) {
869
+ const cliResult = interpretAntigravityCli(cli.data, deps.now);
870
+ if (cliResult.ok)
871
+ return cliResult;
872
+ }
873
+ const gemini = await tryReadJson(deps, geminiCliCredsPath(deps.homeDir));
874
+ if (isObj2(gemini.data))
875
+ return interpretGeminiCli(gemini.data, deps.now);
876
+ return { ok: false, reason: "missing", message: MISSING_MSG };
877
+ }
878
+
879
+ // src/oauth.ts
880
+ import { createHash as createHash2 } from "node:crypto";
881
+ import { readdir, readFile as fsReadFile2, stat } from "node:fs/promises";
882
+ import { homedir as homedir2 } from "node:os";
883
+ import { isAbsolute, join as join3 } from "node:path";
884
+ var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
885
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
886
+ var EXPIRY_BUFFER_MS2 = 60000;
887
+ var MAX_CACHE_ENTRIES = 64;
888
+ var MAX_RETRY_MS2 = 60 * 60000;
889
+ var CLIENT_ID_RE = /\bANTIGRAVITY_CLIENT_ID\s*=\s*["']([^"']+)["']/;
890
+ var CLIENT_SECRET_RE = /\bANTIGRAVITY_CLIENT_SECRET\s*=\s*["']([^"']+)["']/;
891
+ var nonEmpty2 = (v) => v && v.trim() !== "" ? v.trim() : null;
892
+ function defaultOAuthDiscoverDeps() {
893
+ return {
894
+ env: process.env,
895
+ homeDir: homedir2(),
896
+ readFile: (p) => fsReadFile2(p, "utf8"),
897
+ listDir: (d) => readdir(d),
898
+ statMtime: async (p) => {
899
+ try {
900
+ return (await stat(p)).mtimeMs;
901
+ } catch {
902
+ return null;
903
+ }
904
+ }
905
+ };
906
+ }
907
+ function extractClientFromConstants(text) {
908
+ const clientId = text.match(CLIENT_ID_RE)?.[1]?.trim();
909
+ const clientSecret = text.match(CLIENT_SECRET_RE)?.[1]?.trim();
910
+ return clientId && clientSecret ? { clientId, clientSecret } : null;
911
+ }
912
+ async function safeListDir(deps, dir) {
913
+ try {
914
+ return await deps.listDir(dir);
915
+ } catch {
916
+ return [];
917
+ }
918
+ }
919
+ async function sortByNewest(deps, parent, entries) {
920
+ const weighted = await Promise.all(entries.map(async (name) => ({ name, mtime: await deps.statMtime(join3(parent, name)) ?? 0 })));
921
+ weighted.sort((a, b) => b.mtime !== a.mtime ? b.mtime - a.mtime : b.name.localeCompare(a.name));
922
+ return weighted.map((entry) => entry.name);
923
+ }
924
+ async function candidateConstantsPaths(deps) {
925
+ const paths = [];
926
+ const xdgCache = nonEmpty2(deps.env.XDG_CACHE_HOME);
927
+ const cacheRoot = xdgCache && isAbsolute(xdgCache) ? xdgCache : join3(deps.homeDir, ".cache");
928
+ const npmCacheDir = join3(cacheRoot, "opencode", "npm");
929
+ const pkgEntries = (await safeListDir(deps, npmCacheDir)).filter((name) => name.startsWith("opencode-antigravity-auth@"));
930
+ for (const pkg of await sortByNewest(deps, npmCacheDir, pkgEntries)) {
931
+ const pkgDir = join3(npmCacheDir, pkg);
932
+ const revisions = await sortByNewest(deps, pkgDir, await safeListDir(deps, pkgDir));
933
+ for (const rev of revisions) {
934
+ paths.push(join3(pkgDir, rev, "node_modules", "opencode-antigravity-auth", "dist", "src", "constants.js"));
935
+ }
936
+ }
937
+ const configDir = nonEmpty2(deps.env.OPENCODE_CONFIG_DIR) ?? join3(nonEmpty2(deps.env.XDG_CONFIG_HOME) ?? join3(deps.homeDir, ".config"), "opencode");
938
+ paths.push(join3(configDir, "node_modules", "opencode-antigravity-auth", "dist", "src", "constants.js"));
939
+ return paths;
940
+ }
941
+ async function discoverOAuthClient(overrides) {
942
+ const deps = { ...defaultOAuthDiscoverDeps(), ...overrides };
943
+ const envId = nonEmpty2(deps.env.ANTIGRAVITY_CLIENT_ID);
944
+ const envSecret = nonEmpty2(deps.env.ANTIGRAVITY_CLIENT_SECRET);
945
+ if (envId && envSecret)
946
+ return { clientId: envId, clientSecret: envSecret };
947
+ for (const filePath of await candidateConstantsPaths(deps)) {
948
+ try {
949
+ const parsed = extractClientFromConstants(await deps.readFile(filePath));
950
+ if (parsed)
951
+ return parsed;
952
+ } catch {}
953
+ }
954
+ return null;
955
+ }
956
+ function tokenHash(refreshToken) {
957
+ return createHash2("sha256").update(refreshToken).digest("hex");
958
+ }
959
+ function retryAfterMs2(header) {
960
+ const seconds = header === null ? NaN : Number(header.trim());
961
+ return header !== null && header.trim() !== "" && Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds * 1000, MAX_RETRY_MS2) : undefined;
962
+ }
963
+ function parseErrorCode(body) {
964
+ try {
965
+ const parsed = JSON.parse(body);
966
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.error === "string") {
967
+ return parsed.error;
968
+ }
969
+ } catch {}
970
+ return null;
971
+ }
972
+ function interpretHttpFailure(status, body, retryAfter) {
973
+ const code = parseErrorCode(body);
974
+ if (status === 401 || status === 400 && code === "invalid_grant") {
975
+ return { ok: false, kind: "unauthorized", message: "Antigravity refresh token rejected or revoked — re-authenticate your account" };
976
+ }
977
+ if (status === 429) {
978
+ const retryMs = retryAfterMs2(retryAfter);
979
+ return retryMs === undefined ? { ok: false, kind: "rate_limited", message: "Google OAuth token endpoint rate limited (HTTP 429)" } : { ok: false, kind: "rate_limited", message: "Google OAuth token endpoint rate limited (HTTP 429)", retryAfterMs: retryMs };
980
+ }
981
+ return { ok: false, kind: "http", message: `Google OAuth token endpoint returned HTTP ${status}` };
982
+ }
983
+ async function requestToken(refreshToken, client, opts) {
984
+ const controller = new AbortController;
985
+ const timer = setTimeout(() => controller.abort(), opts.timeoutMs);
986
+ try {
987
+ const res = await opts.fetchFn(GOOGLE_TOKEN_URL, {
988
+ method: "POST",
989
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
990
+ body: new URLSearchParams({
991
+ grant_type: "refresh_token",
992
+ refresh_token: refreshToken,
993
+ client_id: client.clientId,
994
+ client_secret: client.clientSecret
995
+ }),
996
+ signal: controller.signal
997
+ });
998
+ const body = await res.text();
999
+ if (!res.ok)
1000
+ return interpretHttpFailure(res.status, body, res.headers.get("retry-after"));
1001
+ const parsed = JSON.parse(body);
1002
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.access_token !== "string") {
1003
+ return { ok: false, kind: "http", message: "Unexpected response from Google OAuth token endpoint" };
1004
+ }
1005
+ const token = parsed.access_token.trim();
1006
+ if (!token)
1007
+ return { ok: false, kind: "http", message: "Google OAuth returned an empty access token" };
1008
+ const rawExpires = parsed.expires_in;
1009
+ const expiresInSec = typeof rawExpires === "number" && Number.isFinite(rawExpires) && rawExpires > 0 ? rawExpires : 3600;
1010
+ return { ok: true, accessToken: token, expiresAt: new Date(opts.now().getTime() + expiresInSec * 1000) };
1011
+ } catch (err) {
1012
+ if (err instanceof SyntaxError)
1013
+ return { ok: false, kind: "http", message: "Unexpected response from Google OAuth token endpoint" };
1014
+ const reason = err instanceof Error && err.name === "AbortError" ? "request timed out" : "request failed";
1015
+ return { ok: false, kind: "network", message: `OAuth network error: ${reason}` };
1016
+ } finally {
1017
+ clearTimeout(timer);
1018
+ }
1019
+ }
1020
+ var NO_CLIENT_RESULT = {
1021
+ ok: false,
1022
+ kind: "no_client",
1023
+ message: "Antigravity OAuth client not found — set ANTIGRAVITY_CLIENT_ID/SECRET or install opencode-antigravity-auth"
1024
+ };
1025
+ function storeInCache(cache, key, entry) {
1026
+ cache.set(key, entry);
1027
+ if (cache.size <= MAX_CACHE_ENTRIES)
1028
+ return;
1029
+ const oldest = cache.keys().next().value;
1030
+ if (oldest !== undefined)
1031
+ cache.delete(oldest);
1032
+ }
1033
+ function createTokenExchanger(opts = {}) {
1034
+ const fetchFn = opts.fetch ?? fetch;
1035
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
1036
+ const now = opts.now ?? (() => new Date);
1037
+ const discoverClient = opts.discoverClient ?? (() => discoverOAuthClient());
1038
+ const cache = new Map;
1039
+ const inFlight = new Map;
1040
+ const runExchange = async (refreshToken, key) => {
1041
+ const client = await discoverClient();
1042
+ if (!client)
1043
+ return NO_CLIENT_RESULT;
1044
+ const result = await requestToken(refreshToken, client, { fetchFn, timeoutMs, now });
1045
+ if (result.ok)
1046
+ storeInCache(cache, key, { accessToken: result.accessToken, expiresAt: result.expiresAt });
1047
+ else if (result.kind === "unauthorized")
1048
+ cache.delete(key);
1049
+ return result;
1050
+ };
1051
+ return {
1052
+ async exchange(refreshToken) {
1053
+ const key = tokenHash(refreshToken);
1054
+ const cached = cache.get(key);
1055
+ if (cached && cached.expiresAt.getTime() > now().getTime() + EXPIRY_BUFFER_MS2) {
1056
+ return { ok: true, accessToken: cached.accessToken, expiresAt: cached.expiresAt };
1057
+ }
1058
+ const existing = inFlight.get(key);
1059
+ if (existing)
1060
+ return existing;
1061
+ const pending = runExchange(refreshToken, key).finally(() => {
1062
+ if (inFlight.get(key) === pending)
1063
+ inFlight.delete(key);
1064
+ });
1065
+ inFlight.set(key, pending);
1066
+ return pending;
1067
+ },
1068
+ invalidate: (refreshToken) => void cache.delete(tokenHash(refreshToken))
1069
+ };
1070
+ }
1071
+
1072
+ // src/loader.ts
1073
+ var EXPIRY_BUFFER_MS3 = 60000;
1074
+ function tryReadEmail(read, path) {
1075
+ try {
1076
+ return extractActiveAccountEmailFromJson(JSON.parse(read(path)));
1077
+ } catch {
1078
+ return null;
1079
+ }
1080
+ }
1081
+ function readActiveAccountEmail(credentialsPath, deps = {}) {
1082
+ const env = deps.env ?? process.env;
1083
+ if (env.ANTIGRAVITY_OAUTH_TOKEN?.trim())
1084
+ return null;
1085
+ const read = deps.readFileSync ?? ((p) => readFileSync(p, "utf8"));
1086
+ if (credentialsPath)
1087
+ return tryReadEmail(read, credentialsPath);
1088
+ const home = deps.homeDir ?? homedir3();
1089
+ const platform = deps.platform ?? process.platform;
1090
+ for (const path of accountCandidatePaths(env, home, platform)) {
1091
+ const email = tryReadEmail(read, path);
1092
+ if (email)
1093
+ return email;
1094
+ }
1095
+ return tryReadEmail(read, antigravityCliTokenPath(home));
1096
+ }
1097
+ function hasFreshToken(cred, now) {
1098
+ if (!cred.accessToken)
1099
+ return false;
1100
+ return cred.accessTokenExpiresAt === null || cred.accessTokenExpiresAt.getTime() > now.getTime() + EXPIRY_BUFFER_MS3;
1101
+ }
1102
+ async function fetchWithToken(cred, accessToken, deps) {
1103
+ if (cred.apiKind === "gemini-cli") {
1104
+ return deps.fetchGeminiCli(accessToken, {
1105
+ projectId: cred.projectId,
1106
+ accountEmail: cred.email,
1107
+ pool: cred.pool,
1108
+ now: deps.now
1109
+ });
1110
+ }
1111
+ return deps.fetchAntigravity(accessToken, {
1112
+ projectId: cred.projectId,
1113
+ userAgent: cred.userAgent,
1114
+ accountEmail: cred.email,
1115
+ pool: cred.pool,
1116
+ now: deps.now
1117
+ });
1118
+ }
1119
+ async function resolveAccessTokenForRequest(cred, exchanger, now) {
1120
+ if (hasFreshToken(cred, now))
1121
+ return { ok: true, token: cred.accessToken, fromRefresh: false };
1122
+ if (!cred.refreshToken) {
1123
+ return { ok: false, kind: "credentials", message: "Antigravity access token expired and no refresh token available" };
1124
+ }
1125
+ const exchanged = await exchanger.exchange(cred.refreshToken);
1126
+ if (exchanged.ok)
1127
+ return { ok: true, token: exchanged.accessToken, fromRefresh: true };
1128
+ if (exchanged.kind === "no_client" && cred.cachedFallback !== null) {
1129
+ return { ok: true, snapshot: cred.cachedFallback };
1130
+ }
1131
+ const kind = exchanged.kind === "no_client" ? "credentials" : exchanged.kind;
1132
+ return exchanged.retryAfterMs === undefined ? { ok: false, kind, message: exchanged.message } : { ok: false, kind, message: exchanged.message, retryAfterMs: exchanged.retryAfterMs };
1133
+ }
1134
+ function createLoader(credentialsPath, deps = {}) {
1135
+ const exchanger = deps.exchanger ?? createTokenExchanger();
1136
+ const fetchAntigravity = deps.fetchAntigravity ?? fetchAntigravityQuota;
1137
+ const fetchGeminiCli = deps.fetchGeminiCli ?? fetchGeminiCliQuota;
1138
+ const now = deps.now ?? (() => new Date);
1139
+ const makeCredDeps = deps.credentialDeps ?? (() => defaultCredentialDeps());
1140
+ return async () => {
1141
+ try {
1142
+ const cred = await resolveCredentials({ ...makeCredDeps(), now: now(), credentialsPath });
1143
+ if (!cred.ok)
1144
+ return { ok: false, kind: "credentials", message: cred.message };
1145
+ const resolved = await resolveAccessTokenForRequest(cred, exchanger, now());
1146
+ if (!("token" in resolved))
1147
+ return resolved;
1148
+ const result = await fetchWithToken(cred, resolved.token, { fetchAntigravity, fetchGeminiCli, now });
1149
+ if (!result.ok && result.kind === "unauthorized" && cred.refreshToken) {
1150
+ exchanger.invalidate(cred.refreshToken);
1151
+ if (!resolved.fromRefresh) {
1152
+ const refreshed = await exchanger.exchange(cred.refreshToken);
1153
+ if (refreshed.ok)
1154
+ return await fetchWithToken(cred, refreshed.accessToken, { fetchAntigravity, fetchGeminiCli, now });
1155
+ }
1156
+ }
1157
+ return result;
1158
+ } catch {
1159
+ return { ok: false, kind: "internal", message: "Unexpected error loading Antigravity quota" };
1160
+ }
1161
+ };
1162
+ }
1163
+
1164
+ // src/poller.ts
1165
+ var DEFAULT_INTERVAL_MS = 120000;
1166
+ var MIN_INTERVAL_MS = 60000;
1167
+ var POST_TURN_MAX_AGE_MS = 60000;
1168
+ var MANUAL_MAX_AGE_MS = 30000;
1169
+ var MIN_DELAY_MS = 1000;
1170
+ function clampInterval(ms) {
1171
+ if (ms === undefined || !Number.isFinite(ms))
1172
+ return DEFAULT_INTERVAL_MS;
1173
+ return Math.max(MIN_INTERVAL_MS, Math.floor(ms));
1174
+ }
1175
+ var realTimers = {
1176
+ set: (fn, ms) => setTimeout(fn, ms),
1177
+ clear: (handle) => clearTimeout(handle)
1178
+ };
1179
+ function createPoller(options) {
1180
+ return new PollerImpl(options);
1181
+ }
1182
+
1183
+ class PollerImpl {
1184
+ options;
1185
+ intervalMs;
1186
+ now;
1187
+ timers;
1188
+ listeners = new Set;
1189
+ state;
1190
+ handle = null;
1191
+ running = false;
1192
+ stopped = false;
1193
+ inFlight = null;
1194
+ constructor(options) {
1195
+ this.options = options;
1196
+ this.intervalMs = clampInterval(options.intervalMs);
1197
+ this.now = options.now ?? (() => new Date);
1198
+ this.timers = options.timers ?? realTimers;
1199
+ this.state = { snapshot: options.initial ?? null, error: null, lastAttemptAt: null, loading: false };
1200
+ }
1201
+ start() {
1202
+ if (this.running)
1203
+ return;
1204
+ this.running = true;
1205
+ this.stopped = false;
1206
+ this.run(this.intervalMs);
1207
+ }
1208
+ stop() {
1209
+ this.running = false;
1210
+ this.stopped = true;
1211
+ if (this.handle !== null)
1212
+ this.timers.clear(this.handle);
1213
+ this.handle = null;
1214
+ this.listeners.clear();
1215
+ }
1216
+ async refresh(maxAgeMs = MANUAL_MAX_AGE_MS) {
1217
+ if (this.inFlight)
1218
+ return false;
1219
+ await this.run(maxAgeMs);
1220
+ return true;
1221
+ }
1222
+ getState() {
1223
+ return this.state;
1224
+ }
1225
+ subscribe(listener) {
1226
+ this.listeners.add(listener);
1227
+ return () => this.listeners.delete(listener);
1228
+ }
1229
+ setState(patch) {
1230
+ this.state = { ...this.state, ...patch };
1231
+ for (const listener of this.listeners)
1232
+ listener(this.state);
1233
+ }
1234
+ schedule(delay) {
1235
+ if (this.handle !== null)
1236
+ this.timers.clear(this.handle);
1237
+ this.handle = this.running ? this.timers.set(() => void this.run(this.intervalMs), delay) : null;
1238
+ }
1239
+ run(maxAgeMs) {
1240
+ if (!this.inFlight) {
1241
+ this.inFlight = this.attempt(maxAgeMs).finally(() => {
1242
+ this.inFlight = null;
1243
+ });
1244
+ }
1245
+ return this.inFlight;
1246
+ }
1247
+ async attempt(maxAgeMs) {
1248
+ this.setState({ loading: true, lastAttemptAt: this.now() });
1249
+ const result = await this.options.load({ maxAgeMs });
1250
+ if (this.stopped)
1251
+ return;
1252
+ const retryAfter = result.ok ? undefined : result.retryAfterMs;
1253
+ const retryAt = retryAfter === undefined ? null : new Date(this.now().getTime() + retryAfter);
1254
+ const error = result.ok ? null : { kind: result.kind, message: result.message, retryAt };
1255
+ this.setState({ snapshot: result.snapshot ?? this.state.snapshot, error, loading: false });
1256
+ this.schedule(Math.max(MIN_DELAY_MS, result.nextInMs ?? this.intervalMs));
1257
+ }
1258
+ }
1259
+
1260
+ // src/options.ts
1261
+ function bool(value, fallback) {
1262
+ return typeof value === "boolean" ? value : fallback;
1263
+ }
1264
+ function displayMode(value) {
1265
+ return value === "remaining" || value === "used" ? value : "used";
1266
+ }
1267
+ function parseOptions(raw) {
1268
+ const input = raw ?? {};
1269
+ const seconds = typeof input.refreshInterval === "number" ? input.refreshInterval * 1000 : undefined;
1270
+ const path = typeof input.credentialsPath === "string" ? input.credentialsPath.trim() : "";
1271
+ return {
1272
+ refreshIntervalMs: clampInterval(seconds),
1273
+ showModels: bool(input.showModels, true),
1274
+ displayMode: displayMode(input.displayMode),
1275
+ credentialsPath: path === "" ? undefined : path
1276
+ };
1277
+ }
1278
+
1279
+ // src/format.ts
1280
+ var SECOND = 1000;
1281
+ var MINUTE = 60 * SECOND;
1282
+ var HOUR = 60 * MINUTE;
1283
+ var DAY = 24 * HOUR;
1284
+ function formatDuration(ms) {
1285
+ if (!(ms > 0))
1286
+ return "now";
1287
+ if (ms >= DAY) {
1288
+ const days = Math.floor(ms / DAY);
1289
+ return `${days}d ${Math.floor(ms % DAY / HOUR)}h`;
1290
+ }
1291
+ if (ms >= HOUR) {
1292
+ const hours = Math.floor(ms / HOUR);
1293
+ return `${hours}h ${Math.floor(ms % HOUR / MINUTE)}m`;
1294
+ }
1295
+ return `${Math.max(1, Math.floor(ms / MINUTE))}m`;
1296
+ }
1297
+ function severity(pct) {
1298
+ if (pct >= 100)
1299
+ return "critical";
1300
+ if (pct >= 75)
1301
+ return "high";
1302
+ if (pct >= 50)
1303
+ return "warn";
1304
+ return "ok";
1305
+ }
1306
+ function remainingSeverity(pct) {
1307
+ if (pct <= 0)
1308
+ return "critical";
1309
+ if (pct <= 25)
1310
+ return "high";
1311
+ if (pct <= 50)
1312
+ return "warn";
1313
+ return "ok";
1314
+ }
1315
+ function renderBar(pct, width) {
1316
+ if (!(width > 0))
1317
+ return { filled: "", empty: "" };
1318
+ const safe = Number.isNaN(pct) ? 0 : Math.min(100, Math.max(0, pct));
1319
+ const cells = Math.round(safe / 100 * width);
1320
+ return { filled: "━".repeat(cells), empty: "─".repeat(width - cells) };
1321
+ }
1322
+
1323
+ // src/rows.ts
1324
+ var BAR_WIDTH = 14;
1325
+ var LABEL_WIDTH = 12;
1326
+ var PRIMARY = new Set(["gemini_5h", "gemini_weekly"]);
1327
+ var SEVERITY_TONE = {
1328
+ ok: "success",
1329
+ warn: "warning",
1330
+ high: "error",
1331
+ critical: "error"
1332
+ };
1333
+ var indent = " ".repeat(LABEL_WIDTH);
1334
+ function bucketRows(b, now, mode) {
1335
+ const value = mode === "remaining" ? b.remaining : b.utilization;
1336
+ const pct = Math.round(value);
1337
+ const bar = renderBar(value, BAR_WIDTH);
1338
+ const tone = SEVERITY_TONE[mode === "remaining" ? remainingSeverity(b.remaining) : severity(b.utilization)];
1339
+ const rows = [
1340
+ {
1341
+ kind: "bar",
1342
+ label: b.label.padEnd(LABEL_WIDTH),
1343
+ ...bar,
1344
+ percent: `${String(pct).padStart(4)}%`,
1345
+ tone
1346
+ }
1347
+ ];
1348
+ if (b.resetsAt !== null && b.utilization > 0) {
1349
+ const left = b.resetsAt.getTime() - now.getTime();
1350
+ rows.push({ kind: "text", text: `${indent}resets in ${formatDuration(left)}`, tone: "muted" });
1351
+ }
1352
+ return rows;
1353
+ }
1354
+ function errorRows(state, now) {
1355
+ const { error, snapshot } = state;
1356
+ if (!error)
1357
+ return [];
1358
+ if (error.kind === "rate_limited") {
1359
+ const retry = error.retryAt ? ` · retry in ${formatDuration(error.retryAt.getTime() - now.getTime())}` : "";
1360
+ return [{ kind: "text", text: `rate limited${retry}`, tone: "muted" }];
1361
+ }
1362
+ return [{ kind: "text", text: `${error.message}${snapshot ? " (stale)" : ""}`, tone: "muted" }];
1363
+ }
1364
+ function buildRows(state, now, options) {
1365
+ const rows = [];
1366
+ const snap = state.snapshot;
1367
+ if (snap) {
1368
+ const buckets = snap.buckets.filter((b) => PRIMARY.has(b.id) || options.showModels);
1369
+ for (const b of buckets)
1370
+ rows.push(...bucketRows(b, now, options.displayMode));
1371
+ } else if (state.loading) {
1372
+ rows.push({ kind: "text", text: "Loading…", tone: "muted" });
1373
+ }
1374
+ rows.push(...errorRows(state, now));
1375
+ return rows;
1376
+ }
1377
+
1378
+ // src/shared-fs.ts
1379
+ import { mkdirSync, readFileSync as readFileSync2, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
1380
+ import { isAbsolute as isAbsolute2, join as join4 } from "node:path";
1381
+ var hasCode = (error, code) => typeof error === "object" && error !== null && error.code === code;
1382
+ var nodeFs = {
1383
+ readText: (path) => readFileSync2(path, "utf8"),
1384
+ writeText: (path, data) => writeFileSync(path, data, { mode: 384 }),
1385
+ rename: renameSync,
1386
+ mkdirp: (dir) => void mkdirSync(dir, { recursive: true, mode: 448 }),
1387
+ createExclusive(path, data) {
1388
+ try {
1389
+ writeFileSync(path, data, { flag: "wx", mode: 384 });
1390
+ return true;
1391
+ } catch (error) {
1392
+ if (hasCode(error, "EEXIST"))
1393
+ return false;
1394
+ throw error;
1395
+ }
1396
+ },
1397
+ mtimeMs(path) {
1398
+ try {
1399
+ return statSync(path).mtimeMs;
1400
+ } catch (error) {
1401
+ if (hasCode(error, "ENOENT"))
1402
+ return null;
1403
+ throw error;
1404
+ }
1405
+ },
1406
+ remove(path) {
1407
+ try {
1408
+ unlinkSync(path);
1409
+ } catch (error) {
1410
+ if (!hasCode(error, "ENOENT"))
1411
+ throw error;
1412
+ }
1413
+ }
1414
+ };
1415
+ function defaultCacheDir(env, home) {
1416
+ const xdg = env.XDG_CACHE_HOME?.trim();
1417
+ return join4(xdg && isAbsolute2(xdg) ? xdg : join4(home, ".cache"), "opencode-antigravity-quota");
1418
+ }
1419
+
1420
+ // src/toast.ts
1421
+ function createRefreshCommand(poller, toast) {
1422
+ return async () => {
1423
+ const ran = await poller.refresh();
1424
+ const { error } = poller.getState();
1425
+ if (error?.kind === "rate_limited") {
1426
+ const wait = error.retryAt ? ` — retrying in ${formatDuration(error.retryAt.getTime() - Date.now())}` : "";
1427
+ toast.show({ message: `Rate limited by Google${wait}`, variant: "warning" });
1428
+ } else if (error)
1429
+ toast.show({ message: error.message, variant: "error" });
1430
+ else if (ran)
1431
+ toast.show({ message: "Antigravity quota refreshed", variant: "success" });
1432
+ else
1433
+ toast.show({ message: "Antigravity quota is already fresh", variant: "info" });
1434
+ };
1435
+ }
1436
+
1437
+ // src/view.tsx
1438
+ import { createComponent as _$createComponent } from "opentui:runtime-module:%40opentui%2Fsolid";
1439
+ import { createTextNode as _$createTextNode } from "opentui:runtime-module:%40opentui%2Fsolid";
1440
+ import { insertNode as _$insertNode } from "opentui:runtime-module:%40opentui%2Fsolid";
1441
+ import { setProp as _$setProp } from "opentui:runtime-module:%40opentui%2Fsolid";
1442
+ import { effect as _$effect } from "opentui:runtime-module:%40opentui%2Fsolid";
1443
+ import { insert as _$insert } from "opentui:runtime-module:%40opentui%2Fsolid";
1444
+ import { createElement as _$createElement } from "opentui:runtime-module:%40opentui%2Fsolid";
1445
+ import { For, Show } from "opentui:runtime-module:solid-js";
1446
+ function toneColor(theme, tone) {
1447
+ switch (tone) {
1448
+ case "muted":
1449
+ return theme.text.muted;
1450
+ case "success":
1451
+ return theme.text.feedback.success.base;
1452
+ case "warning":
1453
+ return theme.text.feedback.warning.base;
1454
+ case "error":
1455
+ return theme.text.feedback.error.base;
1456
+ default:
1457
+ return theme.text.base;
1458
+ }
1459
+ }
1460
+ function RowView(props) {
1461
+ const row = props.row;
1462
+ if (row.kind === "text")
1463
+ return (() => {
1464
+ var _el$ = _$createElement("text");
1465
+ _$insert(_el$, () => row.text);
1466
+ _$effect((_$p) => _$setProp(_el$, "fg", toneColor(props.theme, row.tone), _$p));
1467
+ return _el$;
1468
+ })();
1469
+ return (() => {
1470
+ var _el$2 = _$createElement("text"), _el$3 = _$createElement("span"), _el$4 = _$createElement("span"), _el$5 = _$createElement("span"), _el$6 = _$createElement("span");
1471
+ _$insertNode(_el$2, _el$3);
1472
+ _$insertNode(_el$2, _el$4);
1473
+ _$insertNode(_el$2, _el$5);
1474
+ _$insertNode(_el$2, _el$6);
1475
+ _$insert(_el$3, () => row.label);
1476
+ _$insert(_el$4, () => row.filled);
1477
+ _$insert(_el$5, () => row.empty);
1478
+ _$insert(_el$6, () => row.percent);
1479
+ _$effect((_p$) => {
1480
+ var _v$ = {
1481
+ fg: props.theme.text.muted
1482
+ }, _v$2 = {
1483
+ fg: toneColor(props.theme, row.tone)
1484
+ }, _v$3 = {
1485
+ fg: props.theme.border.base
1486
+ }, _v$4 = {
1487
+ fg: props.theme.text.base
1488
+ };
1489
+ _v$ !== _p$.e && (_p$.e = _$setProp(_el$3, "style", _v$, _p$.e));
1490
+ _v$2 !== _p$.t && (_p$.t = _$setProp(_el$4, "style", _v$2, _p$.t));
1491
+ _v$3 !== _p$.a && (_p$.a = _$setProp(_el$5, "style", _v$3, _p$.a));
1492
+ _v$4 !== _p$.o && (_p$.o = _$setProp(_el$6, "style", _v$4, _p$.o));
1493
+ return _p$;
1494
+ }, {
1495
+ e: undefined,
1496
+ t: undefined,
1497
+ a: undefined,
1498
+ o: undefined
1499
+ });
1500
+ return _el$2;
1501
+ })();
1502
+ }
1503
+ function QuotaView(props) {
1504
+ return (() => {
1505
+ var _el$7 = _$createElement("box"), _el$8 = _$createElement("text"), _el$9 = _$createElement("b");
1506
+ _$insertNode(_el$7, _el$8);
1507
+ _$setProp(_el$7, "flexDirection", "column");
1508
+ _$setProp(_el$7, "paddingTop", 1);
1509
+ _$insertNode(_el$8, _el$9);
1510
+ _$insertNode(_el$9, _$createTextNode(`Antigravity Quota`));
1511
+ _$insert(_el$7, _$createComponent(Show, {
1512
+ get when() {
1513
+ return props.rows().length > 0;
1514
+ },
1515
+ get children() {
1516
+ return _$createComponent(For, {
1517
+ get each() {
1518
+ return props.rows();
1519
+ },
1520
+ children: (row) => _$createComponent(RowView, {
1521
+ get theme() {
1522
+ return props.theme;
1523
+ },
1524
+ row
1525
+ })
1526
+ });
1527
+ }
1528
+ }), null);
1529
+ _$effect((_$p) => _$setProp(_el$8, "fg", props.theme.text.base, _$p));
1530
+ return _el$7;
1531
+ })();
1532
+ }
1533
+
1534
+ // src/tui.tsx
1535
+ var TICK_MS = 30000;
1536
+ var ID = "opencode-antigravity-quota";
1537
+ function initialSnapshot(cached, expectedEmail) {
1538
+ if (!cached)
1539
+ return null;
1540
+ if (expectedEmail === null)
1541
+ return cached;
1542
+ return cached.accountEmail !== null && cached.accountEmail.toLowerCase() === expectedEmail.toLowerCase() ? cached : null;
1543
+ }
1544
+ var plugin = {
1545
+ id: ID,
1546
+ setup(context) {
1547
+ const options = parseOptions(context.options);
1548
+ const store = createSharedStore({
1549
+ dir: defaultCacheDir(process.env, homedir4()),
1550
+ fs: nodeFs,
1551
+ now: Date.now
1552
+ });
1553
+ const expectedAccountEmail = () => readActiveAccountEmail(options.credentialsPath);
1554
+ const poller = createPoller({
1555
+ intervalMs: options.refreshIntervalMs,
1556
+ initial: initialSnapshot(store.read().snapshot, expectedAccountEmail()),
1557
+ load: createCoordinator({
1558
+ store,
1559
+ fetchOnce: createLoader(options.credentialsPath),
1560
+ intervalMs: options.refreshIntervalMs,
1561
+ now: Date.now,
1562
+ expectedAccountEmail
1563
+ })
1564
+ });
1565
+ const [state, setState] = createSignal(poller.getState());
1566
+ const [now, setNow] = createSignal(new Date);
1567
+ const unsubscribe = poller.subscribe((next) => setState(next));
1568
+ const ticker = setInterval(() => setNow(new Date), TICK_MS);
1569
+ const rows = () => buildRows(state(), now(), options);
1570
+ const stopEvents = context.data.on("session.execution.succeeded", () => void poller.refresh(POST_TURN_MAX_AGE_MS));
1571
+ const forceRefresh = createRefreshCommand(poller, context.ui.toast);
1572
+ const removeSidebar = context.ui.slot({
1573
+ append: "sidebar.content",
1574
+ render: () => _$createComponent2(QuotaView, {
1575
+ get theme() {
1576
+ return context.theme;
1577
+ },
1578
+ rows
1579
+ })
1580
+ });
1581
+ const removeCommands = context.ui.slot({
1582
+ append: "app",
1583
+ render: () => _$createComponent2(RefreshCommand, {
1584
+ get keymap() {
1585
+ return context.keymap;
1586
+ },
1587
+ id: ID,
1588
+ run: forceRefresh
1589
+ })
1590
+ });
1591
+ poller.start();
1592
+ return () => {
1593
+ removeSidebar();
1594
+ removeCommands();
1595
+ stopEvents();
1596
+ unsubscribe();
1597
+ clearInterval(ticker);
1598
+ poller.stop();
1599
+ };
1600
+ }
1601
+ };
1602
+ var tui_default = plugin;
1603
+ export {
1604
+ tui_default as default
1605
+ };