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
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
#!/usr/bin/env node

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { readFileSync, writeFileSync, existsSync, unlinkSync, mkdirSync } from 'fs';
import { spawn, exec } from 'child_process';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Read package.json for version
const packageJson = JSON.parse(
  readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')
);

// PID file location for background process management
const CONFIG_DIR = join(process.env.HOME || process.env.USERPROFILE || '', '.config', 'antigravity-proxy');
const PID_FILE = join(CONFIG_DIR, 'server.pid');

const args = process.argv.slice(2);
const command = args[0];

// Ensure config directory exists
function ensureConfigDir() {
  if (!existsSync(CONFIG_DIR)) {
    mkdirSync(CONFIG_DIR, { recursive: true });
  }
}

/**
 * Check if the service is running by reading PID file and verifying process
 */
function isServiceRunning() {
  if (!existsSync(PID_FILE)) {
    return false;
  }

  try {
    const pidStr = readFileSync(PID_FILE, 'utf-8');
    const pid = parseInt(pidStr, 10);
    if (isNaN(pid)) {
      cleanupPidFile();
      return false;
    }

    // Check if process is running (signal 0 doesn't kill, just checks)
    process.kill(pid, 0);
    return true;
  } catch (e) {
    // Process doesn't exist
    cleanupPidFile();
    return false;
  }
}

/**
 * Get the PID of the running service
 */
function getServicePid() {
  if (!existsSync(PID_FILE)) {
    return null;
  }
  try {
    const pid = parseInt(readFileSync(PID_FILE, 'utf-8'), 10);
    return isNaN(pid) ? null : pid;
  } catch (e) {
    return null;
  }
}

/**
 * Save PID to file
 */
function savePid(pid) {
  if (!existsSync(CONFIG_DIR)) {
    mkdirSync(CONFIG_DIR, { recursive: true });
  }
  writeFileSync(PID_FILE, pid.toString());
}

/**
 * Clean up PID file
 */
function cleanupPidFile() {
  if (existsSync(PID_FILE)) {
    try {
      unlinkSync(PID_FILE);
    } catch (e) {
      // Ignore cleanup errors
    }
  }
}

/**
 * Get current port from environment or default
 */
function getPort() {
  return process.env.PORT || 8080;
}

/**
 * Wait for service to be ready
 */
async function waitForService(timeout = 10000, initialDelay = 1000) {
  await new Promise(resolve => setTimeout(resolve, initialDelay));

  const startTime = Date.now();
  while (Date.now() - startTime < timeout) {
    if (isServiceRunning()) {
      // Additional wait to ensure service is fully ready
      await new Promise(resolve => setTimeout(resolve, 500));
      return true;
    }
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  return false;
}

/**
 * Start the server as a background process (or foreground with --log)
 */
async function startServer() {
  // Check for --log flag
  const logMode = args.includes('--log');

  if (isServiceRunning() && !logMode) {
    console.log('');
    console.log('โ•ญ' + 'โ”€'.repeat(48) + 'โ•ฎ');
    console.log('โ”‚  ๐Ÿ›ธ Antigravity Proxy is already in orbit      โ”‚');
    console.log('โ•ฐ' + 'โ”€'.repeat(48) + 'โ•ฏ');
    console.log('');

    const pid = getServicePid();
    const port = getPort();
    console.log(`   โ”Œโ”€ PID: ${pid}`);
    console.log(`   โ”œโ”€ Local: http://localhost:${port}`);
    console.log(`   โ””โ”€ Dashboard: http://localhost:${port}`);
    console.log('');
    return;
  }

  console.log('');
  if (logMode) {
    console.log('๐ŸŒŒ Launching Antigravity Proxy (foreground mode)...');
    console.log('   Press Ctrl+C to stop');
    console.log('');
  } else {
    console.log('๐ŸŒŒ Launching Antigravity Proxy...');
  }

  const serverScript = join(__dirname, '..', 'src', 'index.js');
  const port = getPort();

  // Filter out --log from args passed to server
  const serverArgs = args.slice(1).filter(arg => arg !== '--log');

  if (logMode) {
    // Foreground mode - show logs directly
    const serverProcess = spawn('node', [serverScript, ...serverArgs], {
      stdio: 'inherit', // Show output in current terminal
      env: { ...process.env, PORT: port.toString() }
    });

    serverProcess.on('error', (error) => {
      console.error('');
      console.error('โš ๏ธ  Launch failed:', error.message);
      console.error('');
      process.exit(1);
    });

    serverProcess.on('exit', (code) => {
      console.log('');
      console.log('๐ŸŒ™ Proxy has exited');
      console.log('');
      process.exit(code || 0);
    });

    // Keep process running
    return;
  }

  // Background mode - detached process
  const serverProcess = spawn('node', [serverScript, ...serverArgs], {
    detached: true,
    stdio: 'ignore',
    env: { ...process.env, PORT: port.toString() }
  });

  serverProcess.on('error', (error) => {
    console.error('');
    console.error('โš ๏ธ  Launch failed:', error.message);
    console.error('');
    process.exit(1);
  });

  // Save PID and detach
  savePid(serverProcess.pid);
  serverProcess.unref();

  // Wait for service to be ready
  if (await waitForService()) {
    console.log('โ•ญ' + 'โ”€'.repeat(48) + 'โ•ฎ');
    console.log('โ”‚ โšก Proxy is now in orbit!                      โ”‚');
    console.log('โ•ฐ' + 'โ”€'.repeat(48) + 'โ•ฏ');

    console.log('');
    console.log('   โ”Œโ”€ Process ID:', serverProcess.pid);
    console.log('   โ”œโ”€ Local:', `http://localhost:${port}`);
    console.log('   โ””โ”€ Dashboard:', `http://localhost:${port}/`);
    console.log('');
    console.log('   Next steps:');
    console.log('   โ€ข acc ui       โ†’ Open dashboard');
    console.log('   โ€ข acc status   โ†’ View proxy health');
    console.log('   โ€ข acc stop     โ†’ Shut down proxy');
    console.log('');
  } else {
    console.error('');
    console.error('โš ๏ธ  Proxy launched but health check timed out');
    console.log(`   Try: curl http://localhost:${port}/health`);
    console.error('');
  }
}

/**
 * Stop the running server
 */
function stopServer() {
  if (!isServiceRunning()) {
    console.log('');
    console.log('๐ŸŒ‘ Proxy is not running');
    console.log('');
    cleanupPidFile();
    return;
  }

  const pid = getServicePid();
  try {
    process.kill(pid, 'SIGTERM');
    cleanupPidFile();
    console.log('');
    console.log('๐ŸŒ™ Proxy has been taken offline');
    console.log('');
  } catch (e) {
    console.error('');
    console.error('โš ๏ธ  Shutdown failed:', e.message);
    console.error('');
    cleanupPidFile();
  }
}

/**
 * Restart the server
 */
async function restartServer() {
  console.log('');
  console.log('โ™ป๏ธ  Restarting proxy...');
  console.log('');

  // Stop if running
  if (isServiceRunning()) {
    const pid = getServicePid();
    try {
      process.kill(pid, 'SIGTERM');
      cleanupPidFile();
      console.log('   โ””โ”€ Existing instance stopped');
      console.log('');
      // Wait for process to fully terminate
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (e) {
      console.log('   โ””โ”€ No previous instance found');
      console.log('');
      cleanupPidFile();
    }
  }

  // Start fresh
  await startServer();
}

/**
 * Show server status
 */
function showStatus() {
  console.log('');
  console.log('โ•ญ' + 'โ”€'.repeat(48) + 'โ•ฎ');
  console.log('โ”‚  ๐Ÿ›ธ Antigravity Claude Proxy                   โ”‚');
  console.log('โ•ฐ' + 'โ”€'.repeat(48) + 'โ•ฏ');
  console.log('');

  if (isServiceRunning()) {
    const pid = getServicePid();
    const port = getPort();
    console.log('  STATUS');
    console.log('  โšก Proxy is active');
    console.log('');
    console.log('  DETAILS');
    console.log(`  โ”œโ”€ PID: ${pid}`);
    console.log(`  โ”œโ”€ Port: ${port}`);
    console.log(`  โ”œโ”€ API: http://localhost:${port}`);
    console.log(`  โ””โ”€ Dashboard: http://localhost:${port}/`);
    console.log('');
    console.log('  AVAILABLE COMMANDS');
    console.log('  โ€ข acc ui         Open dashboard');
    console.log('  โ€ข acc restart    Relaunch proxy');
    console.log('  โ€ข acc stop       Take offline');
  } else {
    console.log('  STATUS');
    console.log('  ๐ŸŒ‘ Proxy is offline');
    console.log('');
    console.log('  TO LAUNCH');
    console.log('  โ€ข acc start      Bring proxy online');
  }
  console.log('');
}

/**
 * Open WebUI in browser
 */
async function openUI() {
  // Start server if not running
  if (!isServiceRunning()) {
    console.log('');
    console.log('๐ŸŒŒ Proxy offline - launching now...');
    await startServer();
    // Wait for it to be fully ready
    await new Promise(resolve => setTimeout(resolve, 1000));
  }

  const port = getPort();
  const uiUrl = `http://localhost:${port}/`;

  console.log('');
  console.log(`๐Ÿ–ฅ๏ธ  Opening dashboard โ†’ ${uiUrl}`);
  console.log('');

  // Open URL in browser based on platform
  const platform = process.platform;
  let openCommand = '';

  if (platform === 'win32') {
    openCommand = `start ${uiUrl}`;
  } else if (platform === 'darwin') {
    openCommand = `open ${uiUrl}`;
  } else if (platform === 'linux') {
    openCommand = `xdg-open ${uiUrl}`;
  } else {
    console.error('โš ๏ธ  Cannot auto-open browser on this platform');
    console.log(`   Manual URL: ${uiUrl}`);
    console.log('');
    return;
  }

  exec(openCommand, (error) => {
    if (error) {
      console.error('โš ๏ธ  Browser launch failed:', error.message);
      console.log(`   Manual URL: ${uiUrl}`);
      console.log('');
    }
  });
}

function showHelp() {
  console.log(`
โ•ญ${'โ”€'.repeat(58)}โ•ฎ
โ”‚  ๐Ÿ›ธ Antigravity Claude Proxy v${packageJson.version.padEnd(27)}โ”‚
โ•ฐ${'โ”€'.repeat(58)}โ•ฏ

Route Claude Code CLI through Antigravity's multi-model API
with intelligent load balancing across Google accounts.

USAGE
  antigravity-claude-proxy <command> [options]
  acc <command> [options]                 โ† shorthand

โ”โ”โ” PROXY CONTROL โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  start              Launch proxy as background service
  stop               Shut down the proxy
  restart            Relaunch the proxy
  status             View proxy health and details
  ui                 Open dashboard in browser

โ”โ”โ” ACCOUNT MANAGEMENT โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  accounts           Interactive account menu
  accounts add       Add Google account via OAuth
  accounts list      Show all linked accounts
  accounts remove    Unlink accounts
  accounts verify    Check account health
  accounts clear     Remove all accounts

โ”โ”โ” OPTIONS โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  --help, -h         Show this help
  --version, -v      Show version
  --log              Run in foreground with visible logs
  --strategy=NAME    Load balancing: hybrid (default),
                     sticky (cache-optimized), round-robin
  --fallback         Enable model fallback on errors

โ”โ”โ” ENVIRONMENT โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  PORT              Custom port (default: 8080)

โ”โ”โ” EXAMPLES โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  acc start                    Launch proxy
  acc start --log              Launch with visible logs
  acc ui                       Open dashboard
  PORT=3000 acc start          Use custom port
  acc start --strategy=sticky  Optimize for prompt caching
  acc accounts add             Link new Google account

โ”โ”โ” CLAUDE CODE SETUP โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”
  Edit ~/.claude/settings.json:
  {
    "env": {
      "ANTHROPIC_BASE_URL": "http://localhost:8080"
    }
  }

Docs: https://github.com/badrisnarayanan/antigravity-claude-proxy
`);
}

function showVersion() {
  console.log(packageJson.version);
}

async function main() {
  // Handle flags
  if (args.includes('--help') || args.includes('-h')) {
    showHelp();
    process.exit(0);
  }

  if (args.includes('--version') || args.includes('-v')) {
    showVersion();
    process.exit(0);
  }

  // Handle commands
  switch (command) {
    case 'start':
      await startServer();
      break;

    case 'stop':
      stopServer();
      break;

    case 'restart':
      await restartServer();
      break;

    case 'status':
      showStatus();
      break;

    case 'ui':
      await openUI();
      break;

    case 'accounts': {
      // Pass remaining args to accounts CLI
      const subCommand = args[1] || 'add';
      process.argv = ['node', 'accounts-cli.js', subCommand, ...args.slice(2)];
      await import('../src/cli/accounts.js');
      break;
    }

    case 'help':
      showHelp();
      break;

    case 'version':
      showVersion();
      break;

    case undefined:
      // No command - show help
      showHelp();
      break;

    default:
      console.error(`Unknown command: ${command}`);
      console.error('Run "acc --help" for usage information.');
      process.exit(1);
  }
}

main().catch((err) => {
  console.error('Error:', err.message);
  process.exit(1);
});