forked from krmslmz/antigravity-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
713 lines (626 loc) · 29 KB
/
index.js
File metadata and controls
713 lines (626 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
#!/usr/bin/env node
import { Command } from 'commander';
import { GoogleGenerativeAI } from '@google/generative-ai';
import { OAuth2Client } from 'google-auth-library';
import fs from 'fs/promises';
import chalk from 'chalk';
import path from 'path';
import open from 'open';
import express from 'express';
import promptsLib from 'prompts';
import { ANTIGRAVITY_SYSTEM_INSTRUCTION, getAntigravityHeaders, setAntigravityVersion } from 'opencode-antigravity-auth/dist/src/constants.js';
import { startApiServer } from './api-server.js';
import { getValidAccounts, getInstalledAntigravityVersion, getAntigravityProjectFromSettings, getKeysPath, getConfigPath, ensureDataDir } from './auth.js';
const AUTH_ENDPOINT = 'https://cloudcode-pa.googleapis.com';
const INFERENCE_ENDPOINT = 'https://daily-cloudcode-pa.sandbox.googleapis.com';
const detectedIdeVersion = await getInstalledAntigravityVersion();
if (detectedIdeVersion) setAntigravityVersion(detectedIdeVersion);
async function resolveAndOnboardProject(accessToken) {
const version = await getInstalledAntigravityVersion();
if (version) setAntigravityVersion(version);
let projectId = null;
let source = null;
try {
const res = await fetch(`${AUTH_ENDPOINT}/v1internal:loadCodeAssist`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
...getAntigravityHeaders()
},
body: JSON.stringify({ metadata: {} })
});
if (res.ok) {
const data = await res.json();
projectId = data.cloudaicompanionProject || data.response?.cloudaicompanionProject || null;
if (projectId) source = 'Google managed project';
}
} catch (e) {
console.log(chalk.yellow(`[Auto-detect] loadCodeAssist failed: ${e.message}`));
}
if (!projectId) {
projectId = await getAntigravityProjectFromSettings();
if (projectId) source = 'Antigravity IDE settings.json';
}
if (!projectId) {
console.log(chalk.yellow('\n[!] Could not auto-detect a GCP project for this account.'));
console.log(chalk.gray(' This is expected for Workspace accounts that need their own project.'));
console.log(chalk.gray(' Create one at: https://console.cloud.google.com/projectcreate'));
console.log(chalk.gray(' Then enable "Cloud AI Companion API" on it.\n'));
const ans = await promptsLib({
type: 'text',
name: 'project',
message: 'Enter your GCP project_id (or leave empty to skip):',
initial: ''
});
projectId = (ans.project || '').trim() || null;
if (projectId) source = 'manual input';
}
if (!projectId) {
console.log(chalk.yellow('[!] No project_id set. Account saved but inference will fail until you add one.'));
return null;
}
console.log(chalk.green(`[Project] Using ${projectId} (source: ${source})`));
try {
const res = await fetch(`${AUTH_ENDPOINT}/v1internal:onboardUser`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
...getAntigravityHeaders()
},
body: JSON.stringify({
cloudaicompanionProject: projectId,
tierId: 'standard-tier',
metadata: {}
})
});
if (res.ok) {
console.log(chalk.green(`[Onboard] Account registered to ${projectId}`));
} else {
console.log(chalk.yellow(`[Onboard] Failed (${res.status}), inference may still work if project was previously onboarded.`));
}
} catch (e) {
console.log(chalk.yellow(`[Onboard] Error: ${e.message}`));
}
return projectId;
}
const program = new Command();
// Embedded client info (obfuscated to bypass basic secret scanning)
const _0x1a = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
const _0x1b1 = 'GOCSPX-';
const _0x1b2 = 'K58FWR486LdLJ1mLB8sXC4z6qDAf';
const _0x1c = 'http://localhost:57936/oauth-callback';
async function getOAuthClient() {
try {
await ensureDataDir();
const configPath = getConfigPath();
const data = await fs.readFile(configPath, 'utf8');
const config = JSON.parse(data);
return new OAuth2Client(config.CLIENT_ID, config.CLIENT_SECRET, config.REDIRECT_URI);
} catch (e) {
// Fallback to embedded
return new OAuth2Client(_0x1a, _0x1b1 + _0x1b2, _0x1c);
}
}
program
.name('antigravity-cli')
.description('Access premium AI models (Claude Opus, Gemini Pro) via Google One AI Premium subscription.');
// ---------------------------------------------------------
// 0. SETUP COMMAND (Configure Client ID / Secret)
// ---------------------------------------------------------
program
.command('setup')
.description('Configure your Google OAuth credentials (CLIENT_ID, CLIENT_SECRET).')
.action(async () => {
const questions = [
{
type: 'text',
name: 'CLIENT_ID',
message: 'Enter your Google OAuth Client ID:',
validate: value => value.length > 5 ? true : 'Please enter a valid Client ID'
},
{
type: 'password',
name: 'CLIENT_SECRET',
message: 'Enter your Google OAuth Client Secret:',
validate: value => value.length > 5 ? true : 'Please enter a valid Client Secret'
},
{
type: 'text',
name: 'REDIRECT_URI',
message: 'Enter Redirect URI:',
initial: 'http://localhost:57936/oauth-callback'
}
];
const response = await promptsLib(questions);
if (response.CLIENT_ID && response.CLIENT_SECRET) {
await ensureDataDir();
await fs.writeFile(
getConfigPath(),
JSON.stringify(response, null, 2)
);
console.log(chalk.green('\n✅ config.json created successfully! Now you can run "node index.js login".\n'));
}
});
// ---------------------------------------------------------
// 1. LOGIN COMMAND (Google OAuth2 Browser Login)
// ---------------------------------------------------------
program
.command('login')
.description('Sign in with your Google account via browser (Google One AI Premium).')
.action(async () => {
const oauth2Client = await getOAuthClient();
const app = express();
const port = 57936;
const server = app.listen(port, async () => {
console.log(chalk.yellow('\n⌛ Starting Google OAuth authentication...'));
console.log(chalk.magenta('Opening Google sign-in page in your browser.\n'));
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/cclog',
'https://www.googleapis.com/auth/experimentsandconfigs'
],
prompt: 'consent'
});
console.log(chalk.gray(`\nIf the browser doesn't open automatically, click the link below (Ctrl+Click):\n`));
console.log(chalk.cyan.underline(authorizeUrl) + '\n');
try {
await open(authorizeUrl);
} catch (e) {
console.log(chalk.red("Could not open browser automatically. Please visit the link above."));
}
});
app.get('/oauth-callback', async (req, res) => {
try {
const code = req.query.code;
if (!code) throw new Error('Authorization code not received.');
const { tokens } = await oauth2Client.getToken(code);
console.log(chalk.cyan('\n[Auth] Tokens received. Resolving project...'));
const projectId = await resolveAndOnboardProject(tokens.access_token);
await ensureDataDir();
const keysPath = getKeysPath();
let existingKeys = [];
try {
const raw = await fs.readFile(keysPath, 'utf8');
const parsed = JSON.parse(raw);
// Backward compatibility: convert plain string tokens to objects
existingKeys = parsed.map(k => {
if (typeof k === 'string') return { access_token: k, refresh_token: null, expiry_date: null };
return k;
}).filter(k => k && k.access_token);
} catch (e) {
// File doesn't exist yet, start with empty array
}
// Update existing account or add new one
const existingIndex = existingKeys.findIndex(k => k.refresh_token === tokens.refresh_token && tokens.refresh_token != null);
if (existingIndex > -1) {
existingKeys[existingIndex] = { ...existingKeys[existingIndex], ...tokens };
if (projectId) existingKeys[existingIndex].project_id = projectId;
} else {
existingKeys.push({
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
expiry_date: tokens.expiry_date,
...(projectId ? { project_id: projectId } : {})
});
}
await fs.writeFile(keysPath, JSON.stringify(existingKeys, null, 2));
res.send(`
<html><body style="background: #1a1a2e; color: #fff; font-family: sans-serif; text-align:center; padding-top: 100px;">
<h1 style="color:#4CAF50;">✅ Google Account Connected!</h1>
<p style="color:#aaa;">Your access token has been saved securely.</p>
<p><strong>You can close this tab now.</strong></p>
</body></html>
`);
console.log(chalk.green(`\n✓ Google account successfully connected to Antigravity CLI.`));
console.log(chalk.cyan(`Try an AI query now:`));
console.log(chalk.bold.white(`node index.js ask "What is the temperature at the sun's core?"\n`));
server.close();
process.exit(0);
} catch (err) {
res.status(500).send('<h1>Error</h1><p>' + err.message + '</p>');
console.error(chalk.red('\n[Error] Failed to obtain token: '), err.message);
server.close();
process.exit(1);
}
});
});
// ---------------------------------------------------------
// 1b. LOGOUT COMMAND (Remove a stored account)
// ---------------------------------------------------------
program
.command('logout')
.description('Remove a Google account from the stored credentials.')
.action(async () => {
await ensureDataDir();
const keysPath = getKeysPath();
let accounts = [];
try {
accounts = JSON.parse(await fs.readFile(keysPath, 'utf8'));
} catch (e) {
console.log(chalk.yellow('No accounts found.'));
return;
}
if (accounts.length === 0) {
console.log(chalk.yellow('No accounts found.'));
return;
}
console.log(chalk.cyan(`\nFound ${accounts.length} account(s):\n`));
for (let i = 0; i < accounts.length; i++) {
const a = accounts[i];
const proj = a.project_id || '(no project)';
const tok = a.access_token ? a.access_token.substring(0, 25) + '...' : '(no token)';
console.log(` ${i + 1}. [project: ${proj}] token: ${tok}`);
}
console.log();
const ans = await promptsLib({
type: 'number',
name: 'idx',
message: `Remove which account? (1-${accounts.length}, or 0 to cancel)`,
validate: v => (v >= 0 && v <= accounts.length) ? true : `Enter 1-${accounts.length} or 0`
});
if (!ans.idx) {
console.log(chalk.gray('Cancelled.'));
return;
}
const removed = accounts.splice(ans.idx - 1, 1)[0];
await fs.writeFile(keysPath, JSON.stringify(accounts, null, 2));
console.log(chalk.green(`\n✓ Removed account ${ans.idx} [project: ${removed.project_id || '?'}]`));
console.log(chalk.gray(`${accounts.length} account(s) remaining.\n`));
});
// ---------------------------------------------------------
// 2. ASK COMMAND (Direct terminal queries)
// ---------------------------------------------------------
program
.command('ask [directPrompts...]')
.description('Send questions to AI models using your stored credentials.')
.option('-p, --prompts <path>', 'JSON file containing multiple prompts')
.option('-m, --model <name>', 'Model name to use (interactive selection if omitted)')
.action(async (directPrompts, options) => {
try {
// 1. Load auth accounts
const accounts = await getValidAccounts();
const keys = accounts.map(a => a.access_token);
if (keys.length === 0) {
console.error(chalk.red(`\n[Auth Error] No valid tokens found.`));
console.error(chalk.yellow(`Please sign in with your Google One account:`));
console.error(chalk.white(`node index.js login\n`));
process.exit(1);
}
// 2. Collect prompts
let prompts = [];
if (options.prompts) {
try {
const promptsPath = path.resolve(process.cwd(), options.prompts);
const promptsRaw = await fs.readFile(promptsPath, 'utf8');
const parsed = JSON.parse(promptsRaw);
if (Array.isArray(parsed)) prompts = prompts.concat(parsed);
} catch (e) {
console.warn(chalk.yellow(`Warning: Could not read ${options.prompts} or invalid JSON.`));
}
}
if (directPrompts && directPrompts.length > 0) {
prompts = prompts.concat(directPrompts);
}
if (prompts.length === 0) {
console.log(chalk.gray('No prompts provided. Example:'));
console.log(chalk.bold.white(' node index.js ask "Hello"'));
process.exit(0);
}
const CLOUD_CODE_BASE = INFERENCE_ENDPOINT;
let currentKeyIndex = 0;
let projectId = accounts[currentKeyIndex].project_id;
console.log(chalk.green(`[✓] Account-${currentKeyIndex + 1} project: ${projectId}`));
// Step 2: Fetch available models (if no model specified)
if (!options.model) {
console.log(chalk.cyan('🔍 Fetching available AI models...'));
let modelChoices = [];
try {
const modelHeaders = {
'Authorization': `Bearer ${keys[currentKeyIndex]}`,
'Content-Type': 'application/json'
};
if (projectId) modelHeaders['x-goog-user-project'] = projectId;
const modelsRes = await fetch(`${CLOUD_CODE_BASE}/v1internal:fetchAvailableModels`, {
method: 'POST',
headers: modelHeaders,
body: JSON.stringify({})
});
if (modelsRes.ok) {
const modelsData = await modelsRes.json();
const models = modelsData.models || modelsData.modelDetails || [];
if (models.length > 0) {
modelChoices = models
.filter(m => !m.disabled)
.map(m => ({
title: `${m.displayName || m.model || 'Unknown'} ${m.beta ? '(BETA)' : ''}`,
value: m.model || m.displayName || m.name
}));
console.log(chalk.green(`[✓] ${modelChoices.length} models found!`));
}
} else {
const errText = await modelsRes.text();
console.warn(chalk.yellow(`⚠ fetchAvailableModels error: ${modelsRes.status} - ${errText}`));
}
} catch (e) {
console.warn(chalk.yellow(`⚠ fetchAvailableModels failed: ${e.message}`));
}
if (modelChoices.length === 0) {
modelChoices = [
{ title: 'Gemini 3.1 Pro (High)', value: 'gemini-3.1-pro-high' },
{ title: 'Gemini 3.1 Pro (Low)', value: 'gemini-3.1-pro-low' },
{ title: 'Gemini 3 Flash', value: 'gemini-3-flash-agent' },
{ title: 'Claude Sonnet 4.6 (Thinking)', value: 'claude-sonnet-4-6' },
{ title: 'Claude Opus 4.6 (Thinking)', value: 'claude-opus-4-6-thinking' },
{ title: 'GPT-OSS 120B (Medium)', value: 'gpt-oss-120b-medium' }
];
}
const response = await promptsLib({
type: 'select',
name: 'selectedModel',
message: '🤖 Select an AI model:',
choices: modelChoices,
initial: 0
});
if (!response.selectedModel) {
console.log(chalk.yellow('\n[!] Cancelled.\n'));
process.exit(0);
}
options.model = response.selectedModel;
console.log(chalk.green(`\n[✓] Selected model: ${options.model}\n`));
}
// Step 3: Process queries (with multi-account fallback)
console.log(chalk.blue(`Queued ${prompts.length} prompt(s) for processing.`));
console.log(chalk.gray('----------------------------------------------------'));
for (let i = 0; i < prompts.length; i++) {
const prompt = prompts[i];
console.log(chalk.cyan(`\n[Prompt ${i + 1}/${prompts.length}]: `) + chalk.white(prompt));
let success = false;
while (!success) {
try {
const isApiKey = keys[currentKeyIndex] && keys[currentKeyIndex].startsWith('AIza');
let url, headers, requestBody;
if (isApiKey) {
url = `https://generativelanguage.googleapis.com/v1beta/models/${options.model}:streamGenerateContent?alt=sse&key=${keys[currentKeyIndex]}`;
headers = { 'Content-Type': 'application/json' };
requestBody = {
contents: [{ role: 'user', parts: [{ text: prompt }] }],
generationConfig: { temperature: 0.7, maxOutputTokens: 4096 }
};
console.log(chalk.dim(`(→ API Key-${currentKeyIndex + 1} via Generative Language API...)`));
} else {
const agentHeaders = getAntigravityHeaders();
const finalProjectId = accounts[currentKeyIndex].project_id;
url = `${INFERENCE_ENDPOINT}/v1internal:streamGenerateContent?alt=sse`;
headers = {
'Authorization': `Bearer ${keys[currentKeyIndex]}`,
'Content-Type': 'application/json',
...agentHeaders
};
let apiModel = options.model.replace(/^antigravity-/i, '');
requestBody = {
project: finalProjectId,
model: apiModel,
request: {
contents: [{ role: 'user', parts: [{ text: prompt }] }],
systemInstruction: { parts: [{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION }] },
generationConfig: {
temperature: 0.7,
maxOutputTokens: 8192
}
}
};
// Thinking configuration
if (apiModel.includes('thinking') || apiModel.includes('gemini-3')) {
if (apiModel.includes('claude') || apiModel.includes('sonnet')) {
requestBody.request.generationConfig.thinkingConfig = {
includeThoughts: true,
thinkingBudget: 1024
};
} else {
let level = 'medium';
if (apiModel.includes('low')) level = 'low';
if (apiModel.includes('high')) level = 'high';
requestBody.request.generationConfig.thinkingConfig = {
includeThoughts: true,
thinkingLevel: level
};
}
}
// --- SOFT QUOTA CHECK (95% threshold) ---
if (keys.length > 1) {
try {
const qRes = await fetch(`${CLOUD_CODE_BASE}/v1internal:fetchAvailableModels`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${keys[currentKeyIndex]}`,
'Content-Type': 'application/json',
...getAntigravityHeaders()
},
body: JSON.stringify({ project: finalProjectId })
});
if (qRes.ok) {
const qData = await qRes.json();
const modelsObj = qData.models || {};
let targetEntry = null;
for (const [mName, entry] of Object.entries(modelsObj)) {
if (mName.includes(apiModel) || apiModel.includes(mName)) {
targetEntry = entry;
break;
}
}
if (targetEntry?.quotaInfo) {
const rf = Number(targetEntry.quotaInfo.remainingFraction || 0);
if (rf <= 0.05) {
throw new Error(`Soft Quota Exceeded: Only ${Math.round(rf*100)}% remaining. Auto-switching to protect account.`);
}
}
}
} catch (qErr) {
if (qErr.message.includes('Soft Quota')) throw qErr;
}
}
// --- END SOFT QUOTA CHECK ---
console.log(chalk.dim(`(→ Account-${currentKeyIndex + 1} via Antigravity [Model: ${apiModel}] [Project: ${finalProjectId}]...)`));
}
const fetchRes = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(requestBody)
});
if (!fetchRes.ok) {
const errData = await fetchRes.text();
throw new Error(`${fetchRes.status} - ${errData}`);
}
const reader = fetchRes.body.getReader();
const decoder = new TextDecoder();
let text = "";
let buffer = "";
process.stdout.write(chalk.green(`\n[Response]:\n`));
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const blocks = buffer.split('data: ');
buffer = blocks.pop();
for (let block of blocks) {
block = block.trim();
if (!block || block === '[DONE]') continue;
try {
const jsonStr = block.split('\n')[0];
const parsed = JSON.parse(jsonStr);
if (parsed.error) {
const errMsg = parsed.error.message || JSON.stringify(parsed.error);
throw new Error(`API Error: ${errMsg}`);
}
const candidate = parsed.response?.candidates?.[0] || parsed.candidates?.[0] || parsed[0]?.candidates?.[0];
if (candidate?.content?.parts) {
for (const part of candidate.content.parts) {
if (part.text) {
process.stdout.write(chalk.whiteBright(part.text));
text += part.text;
}
if (part.thought) {
process.stdout.write(chalk.gray(`\n[Thought]: ${part.text}\n`));
}
}
} else if (candidate?.finishReason && candidate.finishReason !== "STOP") {
text += `\n[Warning: Finish Reason -> ${candidate.finishReason}]\n`;
}
} catch (e) {
if (e.message.includes('API Error')) {
throw e;
}
}
}
}
console.log("\n");
console.log(chalk.gray('----------------------------------------------------'));
if (!text.trim()) {
throw new Error("Empty response received. Model or quota may be blocked.");
}
success = true;
} catch (error) {
const errStr = error.message || error.toString();
console.error(chalk.yellow(`\n[Error]: Account-${currentKeyIndex + 1} rejected: `) + chalk.gray(errStr));
currentKeyIndex++;
if (currentKeyIndex < keys.length) {
console.log(chalk.magenta(`=> ⚡ Auto-switching to Account-${currentKeyIndex + 1}...`));
} else {
console.error(chalk.bgRed.white('\n All tokens exhausted. Please run "node index.js login" to add new accounts. '));
process.exit(1);
}
}
}
}
} catch (err) {
console.error(chalk.bgRed.white('\nFatal Error:\n'), err);
process.exit(1);
}
});
// ---------------------------------------------------------
// 3. SERVE COMMAND (OpenAI-Compatible API Server)
// ---------------------------------------------------------
program
.command('serve')
.description('Start a local OpenAI-compatible API server.')
.option('-p, --port <number>', 'Server port', '6012')
.action((options) => {
startApiServer(parseInt(options.port, 10));
});
// ---------------------------------------------------------
// 4. STATUS COMMAND (Token & Quota Monitoring)
// ---------------------------------------------------------
program
.command('status')
.description('Check token expiry and AI quota for all accounts.')
.action(async () => {
const accounts = await getValidAccounts();
if (accounts.length === 0) {
console.log(chalk.yellow('[!] No valid tokens found. Please run "node index.js login" first.'));
return;
}
console.log(chalk.cyan(`\n🔍 Checking ${accounts.length} account(s)...\n`));
for (let i = 0; i < accounts.length; i++) {
const token = accounts[i].access_token;
const projectId = accounts[i].project_id;
console.log(chalk.gray(`----------------------------------------------------`));
try {
const res = await fetch(`https://oauth2.googleapis.com/tokeninfo?access_token=${token}`);
if (res.ok) {
const data = await res.json();
const remainingMin = Math.floor(parseInt(data.expires_in, 10) / 60);
console.log(chalk.green(`[✓] Account-${i + 1}: Active! Auth expires in `) + chalk.white.bold(`${remainingMin} minutes`) + chalk.green('.') + chalk.gray(` [project: ${projectId}]`));
// AI Quota check
try {
const quotaRes = await fetch(`${AUTH_ENDPOINT}/v1internal:fetchAvailableModels`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
...getAntigravityHeaders()
},
body: JSON.stringify({ project: projectId })
});
if (quotaRes.ok) {
const quotaData = await quotaRes.json();
const models = quotaData.models || {};
let claudeQuota = "Unknown";
let geminiQuota = "Unknown";
let claudeReset = "";
let geminiReset = "";
for (const [mName, entry] of Object.entries(models)) {
if (!entry.quotaInfo) continue;
const perc = Math.round(Number(entry.quotaInfo.remainingFraction || 0) * 100);
const rt = entry.quotaInfo.resetTime ? new Date(entry.quotaInfo.resetTime).toLocaleTimeString('en-US') : "";
if (mName.includes('claude-opus')) {
claudeQuota = `${perc}%`;
claudeReset = rt;
}
if (mName.includes('gemini-3.1-pro-high')) {
geminiQuota = `${perc}%`;
geminiReset = rt;
}
}
console.log(chalk.cyan(` ‣ Claude Opus Quota : `) + chalk.white(`${claudeQuota} remaining `) + chalk.gray(claudeReset ? `(Reset: ${claudeReset})` : ''));
console.log(chalk.cyan(` ‣ Gemini Pro Quota : `) + chalk.white(`${geminiQuota} remaining `) + chalk.gray(geminiReset ? `(Reset: ${geminiReset})` : ''));
} else {
console.log(chalk.yellow(` ‣ Could not read AI quota: API access may be restricted.`));
}
} catch (e) {
console.log(chalk.yellow(` ‣ Failed to fetch AI quota (${e.message})`));
}
} else {
console.log(chalk.red(`[X] Account-${i + 1}: Expired or invalid (OAuth token expired after 1 hour)`));
}
} catch (e) {
console.log(chalk.red(`[!] Account-${i + 1}: Connection error while checking.`));
}
}
console.log(chalk.gray(`----------------------------------------------------`));
});
program.parse(process.argv);