initial commit

This commit is contained in:
Badri Narayanan S
2025-12-19 19:20:28 +05:30
parent 52d72b7bff
commit 5ae29947b1
18 changed files with 3925 additions and 494 deletions

514
src/account-manager.js Normal file
View File

@@ -0,0 +1,514 @@
/**
* Account Manager
* Manages multiple Antigravity accounts with round-robin selection,
* automatic failover, and smart cooldown for rate-limited accounts.
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { dirname } from 'path';
import { execSync } from 'child_process';
import { homedir } from 'os';
import { join } from 'path';
import {
ACCOUNT_CONFIG_PATH,
DEFAULT_COOLDOWN_MS,
TOKEN_REFRESH_INTERVAL_MS,
ANTIGRAVITY_ENDPOINT_FALLBACKS,
ANTIGRAVITY_HEADERS,
DEFAULT_PROJECT_ID
} from './constants.js';
import { refreshAccessToken } from './oauth.js';
// Default Antigravity database path
const ANTIGRAVITY_DB_PATH = join(
homedir(),
'Library/Application Support/Antigravity/User/globalStorage/state.vscdb'
);
/**
* Format duration in milliseconds to human-readable string (e.g., "1h23m45s")
*/
function formatDuration(ms) {
const seconds = Math.floor(ms / 1000);
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}h${minutes}m${secs}s`;
} else if (minutes > 0) {
return `${minutes}m${secs}s`;
}
return `${secs}s`;
}
/**
* Sleep for specified milliseconds
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export class AccountManager {
#accounts = [];
#currentIndex = 0;
#configPath;
#settings = {};
#initialized = false;
// Per-account caches
#tokenCache = new Map(); // email -> { token, extractedAt }
#projectCache = new Map(); // email -> projectId
constructor(configPath = ACCOUNT_CONFIG_PATH) {
this.#configPath = configPath;
}
/**
* Initialize the account manager by loading config
*/
async initialize() {
if (this.#initialized) return;
try {
if (existsSync(this.#configPath)) {
const configData = readFileSync(this.#configPath, 'utf-8');
const config = JSON.parse(configData);
this.#accounts = (config.accounts || []).map(acc => ({
...acc,
isRateLimited: acc.isRateLimited || false,
rateLimitResetTime: acc.rateLimitResetTime || null,
lastUsed: acc.lastUsed || null
}));
this.#settings = config.settings || {};
this.#currentIndex = config.activeIndex || 0;
// Clamp currentIndex to valid range
if (this.#currentIndex >= this.#accounts.length) {
this.#currentIndex = 0;
}
console.log(`[AccountManager] Loaded ${this.#accounts.length} account(s) from config`);
} else {
// No config file - use single account from Antigravity database
console.log('[AccountManager] No config file found. Using Antigravity database (single account mode)');
await this.#loadDefaultAccount();
}
} catch (error) {
console.error('[AccountManager] Failed to load config:', error.message);
// Fall back to default account
await this.#loadDefaultAccount();
}
// Clear any expired rate limits
this.clearExpiredLimits();
this.#initialized = true;
}
/**
* Load the default account from Antigravity's database
*/
async #loadDefaultAccount() {
try {
const authData = this.#extractTokenFromDB();
if (authData?.apiKey) {
this.#accounts = [{
email: authData.email || 'default@antigravity',
source: 'database',
isRateLimited: false,
rateLimitResetTime: null,
lastUsed: null
}];
// Pre-cache the token
this.#tokenCache.set(this.#accounts[0].email, {
token: authData.apiKey,
extractedAt: Date.now()
});
console.log(`[AccountManager] Loaded default account: ${this.#accounts[0].email}`);
}
} catch (error) {
console.error('[AccountManager] Failed to load default account:', error.message);
// Create empty account list - will fail on first request
this.#accounts = [];
}
}
/**
* Extract token from Antigravity's SQLite database
*/
#extractTokenFromDB(dbPath = ANTIGRAVITY_DB_PATH) {
const result = execSync(
`sqlite3 "${dbPath}" "SELECT value FROM ItemTable WHERE key = 'antigravityAuthStatus';"`,
{ encoding: 'utf-8', timeout: 5000 }
);
if (!result || !result.trim()) {
throw new Error('No auth status found in database');
}
return JSON.parse(result.trim());
}
/**
* Get the number of accounts
*/
getAccountCount() {
return this.#accounts.length;
}
/**
* Check if all accounts are rate-limited
*/
isAllRateLimited() {
if (this.#accounts.length === 0) return true;
return this.#accounts.every(acc => acc.isRateLimited);
}
/**
* Get list of available (non-rate-limited, non-invalid) accounts
*/
getAvailableAccounts() {
return this.#accounts.filter(acc => !acc.isRateLimited && !acc.isInvalid);
}
/**
* Get list of invalid accounts
*/
getInvalidAccounts() {
return this.#accounts.filter(acc => acc.isInvalid);
}
/**
* Clear expired rate limits
*/
clearExpiredLimits() {
const now = Date.now();
let cleared = 0;
for (const account of this.#accounts) {
if (account.isRateLimited && account.rateLimitResetTime && account.rateLimitResetTime <= now) {
account.isRateLimited = false;
account.rateLimitResetTime = null;
cleared++;
console.log(`[AccountManager] Rate limit expired for: ${account.email}`);
}
}
if (cleared > 0) {
this.saveToDisk();
}
return cleared;
}
/**
* Pick the next available account (round-robin)
*/
pickNext() {
this.clearExpiredLimits();
const available = this.getAvailableAccounts();
if (available.length === 0) {
return null;
}
// Find next available account starting from current index
for (let i = 0; i < this.#accounts.length; i++) {
const idx = (this.#currentIndex + i) % this.#accounts.length;
const account = this.#accounts[idx];
if (!account.isRateLimited && !account.isInvalid) {
this.#currentIndex = (idx + 1) % this.#accounts.length;
account.lastUsed = Date.now();
const position = this.#accounts.indexOf(account) + 1;
const total = this.#accounts.length;
console.log(`[AccountManager] Using account: ${account.email} (${position}/${total})`);
return account;
}
}
return null;
}
/**
* Mark an account as rate-limited
*/
markRateLimited(email, resetMs = null) {
const account = this.#accounts.find(a => a.email === email);
if (!account) return;
account.isRateLimited = true;
const cooldownMs = resetMs || this.#settings.cooldownDurationMs || DEFAULT_COOLDOWN_MS;
account.rateLimitResetTime = Date.now() + cooldownMs;
console.log(
`[AccountManager] Rate limited: ${email}. Available in ${formatDuration(cooldownMs)}`
);
this.saveToDisk();
}
/**
* Mark an account as invalid (credentials need re-authentication)
*/
markInvalid(email, reason = 'Unknown error') {
const account = this.#accounts.find(a => a.email === email);
if (!account) return;
account.isInvalid = true;
account.invalidReason = reason;
account.invalidAt = Date.now();
console.log(
`[AccountManager] ⚠ Account INVALID: ${email}`
);
console.log(
`[AccountManager] Reason: ${reason}`
);
console.log(
`[AccountManager] Run 'npm run accounts' to re-authenticate this account`
);
this.saveToDisk();
}
/**
* Get the minimum wait time until any account becomes available
*/
getMinWaitTimeMs() {
if (!this.isAllRateLimited()) return 0;
const now = Date.now();
let minWait = Infinity;
let soonestAccount = null;
for (const account of this.#accounts) {
if (account.rateLimitResetTime) {
const wait = account.rateLimitResetTime - now;
if (wait > 0 && wait < minWait) {
minWait = wait;
soonestAccount = account;
}
}
}
if (soonestAccount) {
console.log(`[AccountManager] Shortest wait: ${formatDuration(minWait)} (account: ${soonestAccount.email})`);
}
return minWait === Infinity ? DEFAULT_COOLDOWN_MS : minWait;
}
/**
* Get OAuth token for an account
*/
async getTokenForAccount(account) {
// Check cache first
const cached = this.#tokenCache.get(account.email);
if (cached && (Date.now() - cached.extractedAt) < TOKEN_REFRESH_INTERVAL_MS) {
return cached.token;
}
// Get fresh token based on source
let token;
if (account.source === 'oauth' && account.refreshToken) {
// OAuth account - use refresh token to get new access token
try {
const tokens = await refreshAccessToken(account.refreshToken);
token = tokens.accessToken;
// Clear invalid flag on success
if (account.isInvalid) {
account.isInvalid = false;
account.invalidReason = null;
this.saveToDisk();
}
console.log(`[AccountManager] Refreshed OAuth token for: ${account.email}`);
} catch (error) {
console.error(`[AccountManager] Failed to refresh token for ${account.email}:`, error.message);
// Mark account as invalid (credentials need re-auth)
this.markInvalid(account.email, error.message);
throw new Error(`AUTH_INVALID: ${account.email}: ${error.message}`);
}
} else if (account.source === 'manual' && account.apiKey) {
token = account.apiKey;
} else {
// Extract from database
const dbPath = account.dbPath || ANTIGRAVITY_DB_PATH;
const authData = this.#extractTokenFromDB(dbPath);
token = authData.apiKey;
}
// Cache the token
this.#tokenCache.set(account.email, {
token,
extractedAt: Date.now()
});
return token;
}
/**
* Get project ID for an account
*/
async getProjectForAccount(account, token) {
// Check cache first
const cached = this.#projectCache.get(account.email);
if (cached) {
return cached;
}
// OAuth or manual accounts may have projectId specified
if (account.projectId) {
this.#projectCache.set(account.email, account.projectId);
return account.projectId;
}
// Discover project via loadCodeAssist API
const project = await this.#discoverProject(token);
this.#projectCache.set(account.email, project);
return project;
}
/**
* Discover project ID via Cloud Code API
*/
async #discoverProject(token) {
for (const endpoint of ANTIGRAVITY_ENDPOINT_FALLBACKS) {
try {
const response = await fetch(`${endpoint}/v1internal:loadCodeAssist`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
...ANTIGRAVITY_HEADERS
},
body: JSON.stringify({
metadata: {
ideType: 'IDE_UNSPECIFIED',
platform: 'PLATFORM_UNSPECIFIED',
pluginType: 'GEMINI'
}
})
});
if (!response.ok) continue;
const data = await response.json();
if (typeof data.cloudaicompanionProject === 'string') {
return data.cloudaicompanionProject;
}
if (data.cloudaicompanionProject?.id) {
return data.cloudaicompanionProject.id;
}
} catch (error) {
console.log(`[AccountManager] Project discovery failed at ${endpoint}:`, error.message);
}
}
console.log(`[AccountManager] Using default project: ${DEFAULT_PROJECT_ID}`);
return DEFAULT_PROJECT_ID;
}
/**
* Clear project cache for an account (useful on auth errors)
*/
clearProjectCache(email = null) {
if (email) {
this.#projectCache.delete(email);
} else {
this.#projectCache.clear();
}
}
/**
* Clear token cache for an account (useful on auth errors)
*/
clearTokenCache(email = null) {
if (email) {
this.#tokenCache.delete(email);
} else {
this.#tokenCache.clear();
}
}
/**
* Save current state to disk
*/
saveToDisk() {
try {
// Ensure directory exists
const dir = dirname(this.#configPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
const config = {
accounts: this.#accounts.map(acc => ({
email: acc.email,
source: acc.source,
dbPath: acc.dbPath || null,
refreshToken: acc.source === 'oauth' ? acc.refreshToken : undefined,
apiKey: acc.source === 'manual' ? acc.apiKey : undefined,
projectId: acc.projectId || undefined,
addedAt: acc.addedAt || undefined,
isRateLimited: acc.isRateLimited,
rateLimitResetTime: acc.rateLimitResetTime,
isInvalid: acc.isInvalid || false,
invalidReason: acc.invalidReason || null,
lastUsed: acc.lastUsed
})),
settings: this.#settings,
activeIndex: this.#currentIndex
};
writeFileSync(this.#configPath, JSON.stringify(config, null, 2));
} catch (error) {
console.error('[AccountManager] Failed to save config:', error.message);
}
}
/**
* Get status object for logging/API
*/
getStatus() {
const available = this.getAvailableAccounts();
const rateLimited = this.#accounts.filter(a => a.isRateLimited);
const invalid = this.getInvalidAccounts();
return {
total: this.#accounts.length,
available: available.length,
rateLimited: rateLimited.length,
invalid: invalid.length,
summary: `${this.#accounts.length} total, ${available.length} available, ${rateLimited.length} rate-limited, ${invalid.length} invalid`,
accounts: this.#accounts.map(a => ({
email: a.email,
source: a.source,
isRateLimited: a.isRateLimited,
rateLimitResetTime: a.rateLimitResetTime,
isInvalid: a.isInvalid || false,
invalidReason: a.invalidReason || null,
lastUsed: a.lastUsed
}))
};
}
/**
* Get settings
*/
getSettings() {
return { ...this.#settings };
}
}
// Export helper functions
export { formatDuration, sleep };
export default AccountManager;

336
src/accounts-cli.js Normal file
View File

@@ -0,0 +1,336 @@
#!/usr/bin/env node
/**
* Account Management CLI
*
* Interactive CLI for adding and managing Google accounts
* for the Antigravity Claude Proxy.
*
* Usage:
* node src/accounts-cli.js # Interactive mode
* node src/accounts-cli.js add # Add new account(s)
* node src/accounts-cli.js list # List all accounts
* node src/accounts-cli.js clear # Remove all accounts
*/
import { createInterface } from 'readline/promises';
import { stdin, stdout } from 'process';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { dirname } from 'path';
import { exec } from 'child_process';
import { ACCOUNT_CONFIG_PATH } from './constants.js';
import {
getAuthorizationUrl,
startCallbackServer,
completeOAuthFlow,
refreshAccessToken,
getUserEmail
} from './oauth.js';
const MAX_ACCOUNTS = 10;
/**
* Create readline interface
*/
function createRL() {
return createInterface({ input: stdin, output: stdout });
}
/**
* Open URL in default browser
*/
function openBrowser(url) {
const platform = process.platform;
let command;
if (platform === 'darwin') {
command = `open "${url}"`;
} else if (platform === 'win32') {
command = `start "" "${url}"`;
} else {
command = `xdg-open "${url}"`;
}
exec(command, (error) => {
if (error) {
console.log('\n⚠ Could not open browser automatically.');
console.log('Please open this URL manually:', url);
}
});
}
/**
* Load existing accounts from config
*/
function loadAccounts() {
try {
if (existsSync(ACCOUNT_CONFIG_PATH)) {
const data = readFileSync(ACCOUNT_CONFIG_PATH, 'utf-8');
const config = JSON.parse(data);
return config.accounts || [];
}
} catch (error) {
console.error('Error loading accounts:', error.message);
}
return [];
}
/**
* Save accounts to config
*/
function saveAccounts(accounts, settings = {}) {
try {
const dir = dirname(ACCOUNT_CONFIG_PATH);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
const config = {
accounts: accounts.map(acc => ({
email: acc.email,
source: 'oauth',
refreshToken: acc.refreshToken,
projectId: acc.projectId,
addedAt: acc.addedAt || new Date().toISOString(),
lastUsed: acc.lastUsed || null,
isRateLimited: acc.isRateLimited || false,
rateLimitResetTime: acc.rateLimitResetTime || null
})),
settings: {
cooldownDurationMs: 60000,
maxRetries: 5,
...settings
},
activeIndex: 0
};
writeFileSync(ACCOUNT_CONFIG_PATH, JSON.stringify(config, null, 2));
console.log(`\n✓ Saved ${accounts.length} account(s) to ${ACCOUNT_CONFIG_PATH}`);
} catch (error) {
console.error('Error saving accounts:', error.message);
throw error;
}
}
/**
* Display current accounts
*/
function displayAccounts(accounts) {
if (accounts.length === 0) {
console.log('\nNo accounts configured.');
return;
}
console.log(`\n${accounts.length} account(s) saved:`);
accounts.forEach((acc, i) => {
const status = acc.isRateLimited ? ' (rate-limited)' : '';
console.log(` ${i + 1}. ${acc.email}${status}`);
});
}
/**
* Add a new account via OAuth with automatic callback
*/
async function addAccount(existingAccounts) {
console.log('\n=== Add Google Account ===\n');
// Generate authorization URL
const { url, verifier, state } = getAuthorizationUrl();
console.log('Opening browser for Google sign-in...');
console.log('(If browser does not open, copy this URL manually)\n');
console.log(` ${url}\n`);
// Open browser
openBrowser(url);
// Start callback server and wait for code
console.log('Waiting for authentication (timeout: 2 minutes)...\n');
try {
const code = await startCallbackServer(state);
console.log('Received authorization code. Exchanging for tokens...');
const result = await completeOAuthFlow(code, verifier);
// Check if account already exists
const existing = existingAccounts.find(a => a.email === result.email);
if (existing) {
console.log(`\n⚠ Account ${result.email} already exists. Updating tokens.`);
existing.refreshToken = result.refreshToken;
existing.projectId = result.projectId;
existing.addedAt = new Date().toISOString();
return null; // Don't add duplicate
}
console.log(`\n✓ Successfully authenticated: ${result.email}`);
if (result.projectId) {
console.log(` Project ID: ${result.projectId}`);
}
return {
email: result.email,
refreshToken: result.refreshToken,
projectId: result.projectId,
addedAt: new Date().toISOString(),
isRateLimited: false,
rateLimitResetTime: null
};
} catch (error) {
console.error(`\n✗ Authentication failed: ${error.message}`);
return null;
}
}
/**
* Interactive add accounts flow
*/
async function interactiveAdd(rl) {
const accounts = loadAccounts();
if (accounts.length > 0) {
displayAccounts(accounts);
const choice = await rl.question('\n(a)dd new account(s) or (f)resh start? [a/f]: ');
if (choice.toLowerCase() === 'f') {
console.log('\nStarting fresh - existing accounts will be replaced.');
accounts.length = 0;
} else {
console.log('\nAdding to existing accounts.');
}
}
// Add accounts loop
while (accounts.length < MAX_ACCOUNTS) {
const newAccount = await addAccount(accounts);
if (newAccount) {
accounts.push(newAccount);
// Auto-save after each successful add to prevent data loss
saveAccounts(accounts);
} else if (accounts.length > 0) {
// Even if newAccount is null (duplicate update), save the updated accounts
saveAccounts(accounts);
}
if (accounts.length >= MAX_ACCOUNTS) {
console.log(`\nMaximum of ${MAX_ACCOUNTS} accounts reached.`);
break;
}
const addMore = await rl.question('\nAdd another account? [y/N]: ');
if (addMore.toLowerCase() !== 'y') {
break;
}
}
if (accounts.length > 0) {
displayAccounts(accounts);
} else {
console.log('\nNo accounts to save.');
}
}
/**
* List accounts
*/
async function listAccounts() {
const accounts = loadAccounts();
displayAccounts(accounts);
if (accounts.length > 0) {
console.log(`\nConfig file: ${ACCOUNT_CONFIG_PATH}`);
}
}
/**
* Clear all accounts
*/
async function clearAccounts(rl) {
const accounts = loadAccounts();
if (accounts.length === 0) {
console.log('No accounts to clear.');
return;
}
displayAccounts(accounts);
const confirm = await rl.question('\nAre you sure you want to remove all accounts? [y/N]: ');
if (confirm.toLowerCase() === 'y') {
saveAccounts([]);
console.log('All accounts removed.');
} else {
console.log('Cancelled.');
}
}
/**
* Verify accounts (test refresh tokens)
*/
async function verifyAccounts() {
const accounts = loadAccounts();
if (accounts.length === 0) {
console.log('No accounts to verify.');
return;
}
console.log('\nVerifying accounts...\n');
for (const account of accounts) {
try {
const tokens = await refreshAccessToken(account.refreshToken);
const email = await getUserEmail(tokens.accessToken);
console.log(`${email} - OK`);
} catch (error) {
console.log(`${account.email} - ${error.message}`);
}
}
}
/**
* Main CLI
*/
async function main() {
const args = process.argv.slice(2);
const command = args[0] || 'add';
console.log('╔════════════════════════════════════════╗');
console.log('║ Antigravity Proxy Account Manager ║');
console.log('╚════════════════════════════════════════╝');
const rl = createRL();
try {
switch (command) {
case 'add':
await interactiveAdd(rl);
break;
case 'list':
await listAccounts();
break;
case 'clear':
await clearAccounts(rl);
break;
case 'verify':
await verifyAccounts();
break;
case 'help':
console.log('\nUsage:');
console.log(' node src/accounts-cli.js add Add new account(s)');
console.log(' node src/accounts-cli.js list List all accounts');
console.log(' node src/accounts-cli.js verify Verify account tokens');
console.log(' node src/accounts-cli.js clear Remove all accounts');
console.log(' node src/accounts-cli.js help Show this help');
break;
default:
console.log(`Unknown command: ${command}`);
console.log('Run with "help" for usage information.');
}
} finally {
rl.close();
}
}
main().catch(console.error);

File diff suppressed because it is too large Load Diff

View File

@@ -3,21 +3,19 @@
* Based on: https://github.com/NoeFabris/opencode-antigravity-auth
*/
// Cloud Code API endpoints (in fallback order)
export const ANTIGRAVITY_ENDPOINT_DAILY = 'https://daily-cloudcode-pa.sandbox.googleapis.com';
export const ANTIGRAVITY_ENDPOINT_AUTOPUSH = 'https://autopush-cloudcode-pa.sandbox.googleapis.com';
export const ANTIGRAVITY_ENDPOINT_PROD = 'https://cloudcode-pa.googleapis.com';
import { homedir } from 'os';
import { join } from 'path';
// Endpoint fallback order (daily → autopush → prod)
// Cloud Code API endpoints (in fallback order)
const ANTIGRAVITY_ENDPOINT_DAILY = 'https://daily-cloudcode-pa.sandbox.googleapis.com';
const ANTIGRAVITY_ENDPOINT_PROD = 'https://cloudcode-pa.googleapis.com';
// Endpoint fallback order (daily → prod)
export const ANTIGRAVITY_ENDPOINT_FALLBACKS = [
ANTIGRAVITY_ENDPOINT_DAILY,
ANTIGRAVITY_ENDPOINT_AUTOPUSH,
ANTIGRAVITY_ENDPOINT_PROD
];
// Primary endpoint
export const ANTIGRAVITY_ENDPOINT = ANTIGRAVITY_ENDPOINT_DAILY;
// Required headers for Antigravity API requests
export const ANTIGRAVITY_HEADERS = {
'User-Agent': 'antigravity/1.11.5 darwin/arm64',
@@ -70,23 +68,30 @@ export const AVAILABLE_MODELS = [
// Default project ID if none can be discovered
export const DEFAULT_PROJECT_ID = 'rising-fact-p41fc';
// Centralized configuration constants
export const STREAMING_CHUNK_SIZE = 20;
export const TOKEN_REFRESH_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
export const REQUEST_BODY_LIMIT = '50mb';
export const ANTIGRAVITY_AUTH_PORT = 9092;
export const DEFAULT_PORT = 8080;
// Multi-account configuration
export const ACCOUNT_CONFIG_PATH = join(
homedir(),
'.config/antigravity-proxy/accounts.json'
);
export const DEFAULT_COOLDOWN_MS = 60 * 1000; // 1 minute default cooldown
export const MAX_RETRIES = 5; // Max retry attempts across accounts
export default {
ANTIGRAVITY_ENDPOINT,
ANTIGRAVITY_ENDPOINT_FALLBACKS,
ANTIGRAVITY_HEADERS,
MODEL_MAPPINGS,
AVAILABLE_MODELS,
DEFAULT_PROJECT_ID,
STREAMING_CHUNK_SIZE,
TOKEN_REFRESH_INTERVAL_MS,
REQUEST_BODY_LIMIT,
ANTIGRAVITY_AUTH_PORT,
DEFAULT_PORT
DEFAULT_PORT,
ACCOUNT_CONFIG_PATH,
DEFAULT_COOLDOWN_MS,
MAX_RETRIES
};

View File

@@ -10,6 +10,11 @@
import crypto from 'crypto';
import { MODEL_MAPPINGS } from './constants.js';
// Default thinking budget (16K tokens)
const DEFAULT_THINKING_BUDGET = 16000;
// Claude thinking models need larger max output tokens
const CLAUDE_THINKING_MAX_OUTPUT_TOKENS = 64000;
/**
* Map Anthropic model name to Antigravity model name
*/
@@ -17,6 +22,208 @@ export function mapModelName(anthropicModel) {
return MODEL_MAPPINGS[anthropicModel] || anthropicModel;
}
/**
* Check if a part is a thinking block
*/
function isThinkingPart(part) {
return part.type === 'thinking' ||
part.type === 'redacted_thinking' ||
part.thinking !== undefined ||
part.thought === true;
}
/**
* Check if a thinking part has a valid signature (>= 50 chars)
*/
function hasValidSignature(part) {
const signature = part.thought === true ? part.thoughtSignature : part.signature;
return typeof signature === 'string' && signature.length >= 50;
}
/**
* Sanitize a thinking part by keeping only allowed fields
*/
function sanitizeThinkingPart(part) {
// Gemini-style thought blocks: { thought: true, text, thoughtSignature }
if (part.thought === true) {
const sanitized = { thought: true };
if (part.text !== undefined) sanitized.text = part.text;
if (part.thoughtSignature !== undefined) sanitized.thoughtSignature = part.thoughtSignature;
return sanitized;
}
// Anthropic-style thinking blocks: { type: "thinking", thinking, signature }
if (part.type === 'thinking' || part.thinking !== undefined) {
const sanitized = { type: 'thinking' };
if (part.thinking !== undefined) sanitized.thinking = part.thinking;
if (part.signature !== undefined) sanitized.signature = part.signature;
return sanitized;
}
return part;
}
/**
* Filter content array, keeping only thinking blocks with valid signatures.
* Since signature_delta transmits signatures properly, cache is no longer needed.
*/
function filterContentArray(contentArray) {
const filtered = [];
for (const item of contentArray) {
if (!item || typeof item !== 'object') {
filtered.push(item);
continue;
}
if (!isThinkingPart(item)) {
filtered.push(item);
continue;
}
// Keep items with valid signatures
if (hasValidSignature(item)) {
filtered.push(sanitizeThinkingPart(item));
continue;
}
// Drop unsigned thinking blocks
console.log('[FormatConverter] Dropping unsigned thinking block');
}
return filtered;
}
/**
* Filter unsigned thinking blocks from contents (Gemini format)
*/
export function filterUnsignedThinkingBlocks(contents) {
return contents.map(content => {
if (!content || typeof content !== 'object') return content;
if (Array.isArray(content.parts)) {
return { ...content, parts: filterContentArray(content.parts) };
}
return content;
});
}
/**
* Remove trailing unsigned thinking blocks from assistant messages.
* Claude/Gemini APIs require that assistant messages don't end with unsigned thinking blocks.
* This function removes thinking blocks from the end of content arrays.
*/
export function removeTrailingThinkingBlocks(content) {
if (!Array.isArray(content)) return content;
if (content.length === 0) return content;
// Work backwards from the end, removing thinking blocks
let endIndex = content.length;
for (let i = content.length - 1; i >= 0; i--) {
const block = content[i];
if (!block || typeof block !== 'object') break;
// Check if it's a thinking block (any format)
const isThinking = isThinkingPart(block);
if (isThinking) {
// Check if it has a valid signature
if (!hasValidSignature(block)) {
endIndex = i;
} else {
break; // Stop at signed thinking block
}
} else {
break; // Stop at first non-thinking block
}
}
if (endIndex < content.length) {
console.log('[FormatConverter] Removed', content.length - endIndex, 'trailing unsigned thinking blocks');
return content.slice(0, endIndex);
}
return content;
}
/**
* Filter thinking blocks: keep only those with valid signatures.
* Blocks without signatures are dropped (API requires signatures).
*/
export function restoreThinkingSignatures(content) {
if (!Array.isArray(content)) return content;
const originalLength = content.length;
const filtered = content.filter(block => {
if (!block || block.type !== 'thinking') return true;
// Keep blocks with valid signatures (>= 50 chars)
return block.signature && block.signature.length >= 50;
});
if (filtered.length < originalLength) {
console.log(`[FormatConverter] Dropped ${originalLength - filtered.length} unsigned thinking block(s)`);
}
return filtered;
}
/**
* Reorder content so that:
* 1. Thinking blocks come first (required when thinking is enabled)
* 2. Text blocks come in the middle (filtering out empty/useless ones)
* 3. Tool_use blocks come at the end (required before tool_result)
*
* Claude API requires that when thinking is enabled, assistant messages must start with thinking.
*/
export function reorderAssistantContent(content) {
if (!Array.isArray(content)) return content;
if (content.length <= 1) return content;
const thinkingBlocks = [];
const textBlocks = [];
const toolUseBlocks = [];
let droppedEmptyBlocks = 0;
for (const block of content) {
if (!block) continue;
if (block.type === 'thinking') {
thinkingBlocks.push(block);
} else if (block.type === 'tool_use') {
toolUseBlocks.push(block);
} else if (block.type === 'text') {
// Only keep text blocks with meaningful content
if (block.text && block.text.trim().length > 0) {
textBlocks.push(block);
} else {
droppedEmptyBlocks++;
}
} else {
// Other block types go in the text position
textBlocks.push(block);
}
}
if (droppedEmptyBlocks > 0) {
console.log(`[FormatConverter] Dropped ${droppedEmptyBlocks} empty text block(s)`);
}
const reordered = [...thinkingBlocks, ...textBlocks, ...toolUseBlocks];
// Log only if actual reordering happened (not just filtering)
if (reordered.length === content.length) {
const originalOrder = content.map(b => b?.type || 'unknown').join(',');
const newOrder = reordered.map(b => b?.type || 'unknown').join(',');
if (originalOrder !== newOrder) {
console.log('[FormatConverter] Reordered assistant content');
}
}
return reordered;
}
/**
* Convert Anthropic message content to Google Generative AI parts
*/
@@ -33,7 +240,10 @@ function convertContentToParts(content, isClaudeModel = false) {
for (const block of content) {
if (block.type === 'text') {
parts.push({ text: block.text });
// Skip empty text blocks - they cause API errors
if (block.text && block.text.trim()) {
parts.push({ text: block.text });
}
} else if (block.type === 'image') {
// Handle image content
if (block.source?.type === 'base64') {
@@ -107,19 +317,21 @@ function convertContentToParts(content, isClaudeModel = false) {
}
parts.push({ functionResponse });
} else if (block.type === 'thinking' || block.type === 'redacted_thinking') {
// Skip thinking blocks for Claude models - thinking is handled by the model itself
// For non-Claude models, convert to Google's thought format
if (!isClaudeModel && block.type === 'thinking') {
} else if (block.type === 'thinking') {
// Handle thinking blocks - only those with valid signatures
if (block.signature && block.signature.length >= 50) {
// Convert to Gemini format with signature
parts.push({
text: block.thinking,
thought: true
thought: true,
thoughtSignature: block.signature
});
}
// Unsigned thinking blocks are dropped upstream
}
}
return parts.length > 0 ? parts : [{ text: '' }];
return parts;
}
/**
@@ -142,7 +354,10 @@ function convertRole(role) {
*/
export function convertAnthropicToGoogle(anthropicRequest) {
const { messages, system, max_tokens, temperature, top_p, top_k, stop_sequences, tools, tool_choice, thinking } = anthropicRequest;
const isClaudeModel = (anthropicRequest.model || '').toLowerCase().includes('claude');
const modelName = anthropicRequest.model || '';
const isClaudeModel = modelName.toLowerCase().includes('claude');
const isClaudeThinkingModel = isClaudeModel && modelName.toLowerCase().includes('thinking');
const googleRequest = {
contents: [],
@@ -169,9 +384,36 @@ export function convertAnthropicToGoogle(anthropicRequest) {
}
}
// Convert messages to contents
// Add interleaved thinking hint for Claude thinking models with tools
if (isClaudeThinkingModel && tools && tools.length > 0) {
const hint = 'Interleaved thinking is enabled. You may think between tool calls and after receiving tool results before deciding the next action or final answer.';
if (!googleRequest.systemInstruction) {
googleRequest.systemInstruction = { parts: [{ text: hint }] };
} else {
const lastPart = googleRequest.systemInstruction.parts[googleRequest.systemInstruction.parts.length - 1];
if (lastPart && lastPart.text) {
lastPart.text = `${lastPart.text}\n\n${hint}`;
} else {
googleRequest.systemInstruction.parts.push({ text: hint });
}
}
}
// Convert messages to contents, then filter unsigned thinking blocks
for (const msg of messages) {
const parts = convertContentToParts(msg.content, isClaudeModel);
let msgContent = msg.content;
// For assistant messages, process thinking blocks and reorder content
if ((msg.role === 'assistant' || msg.role === 'model') && Array.isArray(msgContent)) {
// First, try to restore signatures for unsigned thinking blocks from cache
msgContent = restoreThinkingSignatures(msgContent);
// Remove trailing unsigned thinking blocks
msgContent = removeTrailingThinkingBlocks(msgContent);
// Reorder: thinking first, then text, then tool_use
msgContent = reorderAssistantContent(msgContent);
}
const parts = convertContentToParts(msgContent, isClaudeModel);
const content = {
role: convertRole(msg.role),
parts: parts
@@ -179,6 +421,11 @@ export function convertAnthropicToGoogle(anthropicRequest) {
googleRequest.contents.push(content);
}
// Filter unsigned thinking blocks for Claude models
if (isClaudeModel) {
googleRequest.contents = filterUnsignedThinkingBlocks(googleRequest.contents);
}
// Generation config
if (max_tokens) {
googleRequest.generationConfig.maxOutputTokens = max_tokens;
@@ -196,9 +443,24 @@ export function convertAnthropicToGoogle(anthropicRequest) {
googleRequest.generationConfig.stopSequences = stop_sequences;
}
// Extended thinking is disabled for Claude models
// The model itself (e.g., claude-opus-4-5-thinking) handles thinking internally
// Enabling thinkingConfig causes signature issues in multi-turn conversations
// Enable thinking for Claude thinking models
if (isClaudeThinkingModel) {
// Get budget from request or use default
const thinkingBudget = thinking?.budget_tokens || DEFAULT_THINKING_BUDGET;
googleRequest.generationConfig.thinkingConfig = {
include_thoughts: true,
thinking_budget: thinkingBudget
};
// Ensure maxOutputTokens is large enough for thinking models
if (!googleRequest.generationConfig.maxOutputTokens ||
googleRequest.generationConfig.maxOutputTokens <= thinkingBudget) {
googleRequest.generationConfig.maxOutputTokens = CLAUDE_THINKING_MAX_OUTPUT_TOKENS;
}
console.log('[FormatConverter] Thinking enabled with budget:', thinkingBudget);
}
// Convert tools to Google format
if (tools && tools.length > 0) {
@@ -232,54 +494,48 @@ export function convertAnthropicToGoogle(anthropicRequest) {
}
/**
* Sanitize JSON schema for Google API compatibility
* Removes unsupported fields like additionalProperties
* Sanitize JSON Schema for Antigravity API compatibility.
* Uses allowlist approach - only permit known-safe JSON Schema features.
* Converts "const" to equivalent "enum" for compatibility.
* Generates placeholder schema for empty tool schemas.
*/
function sanitizeSchema(schema) {
if (!schema || typeof schema !== 'object') {
return schema;
// Empty/missing schema - generate placeholder with reason property
return {
type: 'object',
properties: {
reason: {
type: 'string',
description: 'Reason for calling this tool'
}
},
required: ['reason']
};
}
// Fields to skip entirely - not compatible with Claude's JSON Schema 2020-12
const UNSUPPORTED_FIELDS = new Set([
'$schema',
'additionalProperties',
'default',
'anyOf',
'allOf',
'oneOf',
'minLength',
'maxLength',
'pattern',
'format',
'minimum',
'maximum',
'exclusiveMinimum',
'exclusiveMaximum',
'minItems',
'maxItems',
'uniqueItems',
'minProperties',
'maxProperties',
'$id',
'$ref',
'$defs',
'definitions',
'patternProperties',
'unevaluatedProperties',
'unevaluatedItems',
'if',
'then',
'else',
'not',
'contentEncoding',
'contentMediaType'
// Allowlist of permitted JSON Schema fields
const ALLOWED_FIELDS = new Set([
'type',
'description',
'properties',
'required',
'items',
'enum',
'title'
]);
const sanitized = {};
for (const [key, value] of Object.entries(schema)) {
// Skip unsupported fields
if (UNSUPPORTED_FIELDS.has(key)) {
// Convert "const" to "enum" for compatibility
if (key === 'const') {
sanitized.enum = [value];
continue;
}
// Skip fields not in allowlist
if (!ALLOWED_FIELDS.has(key)) {
continue;
}
@@ -289,38 +545,49 @@ function sanitizeSchema(schema) {
sanitized.properties[propKey] = sanitizeSchema(propValue);
}
} else if (key === 'items' && value && typeof value === 'object') {
// Handle items - could be object or array
if (Array.isArray(value)) {
sanitized.items = value.map(item => sanitizeSchema(item));
} else if (value.anyOf || value.allOf || value.oneOf) {
// Replace complex items with permissive type
sanitized.items = {};
} else {
sanitized.items = sanitizeSchema(value);
}
} else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
// Recursively sanitize nested objects that aren't properties/items
sanitized[key] = sanitizeSchema(value);
} else {
sanitized[key] = value;
}
}
// Ensure we have at least a type
if (!sanitized.type) {
sanitized.type = 'object';
}
// If object type with no properties, add placeholder
if (sanitized.type === 'object' && (!sanitized.properties || Object.keys(sanitized.properties).length === 0)) {
sanitized.properties = {
reason: {
type: 'string',
description: 'Reason for calling this tool'
}
};
sanitized.required = ['reason'];
}
return sanitized;
}
/**
* Convert Google Generative AI response to Anthropic Messages API format
*
*
* @param {Object} googleResponse - Google format response (the inner response object)
* @param {string} model - The model name used
* @param {boolean} isStreaming - Whether this is a streaming response
* @returns {Object} Anthropic format response
*/
export function convertGoogleToAnthropic(googleResponse, model, isStreaming = false) {
export function convertGoogleToAnthropic(googleResponse, model) {
// Handle the response wrapper
const response = googleResponse.response || googleResponse;
const candidates = response.candidates || [];
const firstCandidate = candidates[0] || {};
const content = firstCandidate.content || {};
@@ -328,18 +595,26 @@ export function convertGoogleToAnthropic(googleResponse, model, isStreaming = fa
// Convert parts to Anthropic content blocks
const anthropicContent = [];
let toolCallCounter = 0;
let hasToolCalls = false;
for (const part of parts) {
if (part.text !== undefined) {
// Skip thinking blocks (thought: true) - the model handles thinking internally
// Handle thinking blocks
if (part.thought === true) {
continue;
const signature = part.thoughtSignature || '';
// Include thinking blocks in the response for Claude Code
anthropicContent.push({
type: 'thinking',
thinking: part.text,
signature: signature
});
} else {
anthropicContent.push({
type: 'text',
text: part.text
});
}
anthropicContent.push({
type: 'text',
text: part.text
});
} else if (part.functionCall) {
// Convert functionCall to tool_use
// Use the id from the response if available, otherwise generate one
@@ -349,7 +624,7 @@ export function convertGoogleToAnthropic(googleResponse, model, isStreaming = fa
name: part.functionCall.name,
input: part.functionCall.args || {}
});
toolCallCounter++;
hasToolCalls = true;
}
}
@@ -360,7 +635,7 @@ export function convertGoogleToAnthropic(googleResponse, model, isStreaming = fa
stopReason = 'end_turn';
} else if (finishReason === 'MAX_TOKENS') {
stopReason = 'max_tokens';
} else if (finishReason === 'TOOL_USE' || toolCallCounter > 0) {
} else if (finishReason === 'TOOL_USE' || hasToolCalls) {
stopReason = 'tool_use';
}
@@ -382,108 +657,8 @@ export function convertGoogleToAnthropic(googleResponse, model, isStreaming = fa
};
}
/**
* Parse SSE data and extract the response object
*/
export function parseSSEResponse(data) {
if (!data || !data.startsWith('data:')) {
return null;
}
const jsonStr = data.slice(5).trim();
if (!jsonStr) {
return null;
}
try {
return JSON.parse(jsonStr);
} catch (e) {
console.error('[FormatConverter] Failed to parse SSE data:', e.message);
return null;
}
}
/**
* Convert a streaming chunk to Anthropic SSE format
*/
export function convertStreamingChunk(googleChunk, model, index, isFirst, isLast) {
const events = [];
const response = googleChunk.response || googleChunk;
const candidates = response.candidates || [];
const firstCandidate = candidates[0] || {};
const content = firstCandidate.content || {};
const parts = content.parts || [];
if (isFirst) {
// message_start event
events.push({
type: 'message_start',
message: {
id: `msg_${crypto.randomBytes(16).toString('hex')}`,
type: 'message',
role: 'assistant',
content: [],
model: model,
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: 0, output_tokens: 0 }
}
});
// content_block_start event
events.push({
type: 'content_block_start',
index: 0,
content_block: { type: 'text', text: '' }
});
}
// Extract text from parts and emit as delta
for (const part of parts) {
if (part.text !== undefined) {
events.push({
type: 'content_block_delta',
index: 0,
delta: { type: 'text_delta', text: part.text }
});
}
}
if (isLast) {
// content_block_stop event
events.push({
type: 'content_block_stop',
index: 0
});
// Determine stop reason
const finishReason = firstCandidate.finishReason;
let stopReason = 'end_turn';
if (finishReason === 'MAX_TOKENS') {
stopReason = 'max_tokens';
}
// Extract usage
const usageMetadata = response.usageMetadata || {};
// message_delta event
events.push({
type: 'message_delta',
delta: { stop_reason: stopReason, stop_sequence: null },
usage: { output_tokens: usageMetadata.candidatesTokenCount || 0 }
});
// message_stop event
events.push({ type: 'message_stop' });
}
return events;
}
export default {
mapModelName,
convertAnthropicToGoogle,
convertGoogleToAnthropic,
parseSSEResponse,
convertStreamingChunk
convertGoogleToAnthropic
};

View File

@@ -20,6 +20,7 @@ app.listen(PORT, () => {
║ POST /v1/messages - Anthropic Messages API ║
║ GET /v1/models - List available models ║
║ GET /health - Health check ║
║ GET /accounts - Account pool status ║
║ POST /refresh-token - Force token refresh ║
║ ║
║ Usage with Claude Code: ║
@@ -27,7 +28,10 @@ app.listen(PORT, () => {
║ export ANTHROPIC_API_KEY=dummy ║
║ claude ║
║ ║
Prerequisites:
Add Google accounts:
║ npm run accounts ║
║ ║
║ Prerequisites (if no accounts configured): ║
║ - Antigravity must be running ║
║ - Have a chat panel open in Antigravity ║
║ ║

338
src/oauth.js Normal file
View File

@@ -0,0 +1,338 @@
/**
* Google OAuth with PKCE for Antigravity
*
* Implements the same OAuth flow as opencode-antigravity-auth
* to obtain refresh tokens for multiple Google accounts.
* Uses a local callback server to automatically capture the auth code.
*/
import crypto from 'crypto';
import http from 'http';
import { ANTIGRAVITY_ENDPOINT_FALLBACKS, ANTIGRAVITY_HEADERS } from './constants.js';
// Google OAuth configuration (from opencode-antigravity-auth)
const GOOGLE_CLIENT_ID = '1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com';
const GOOGLE_CLIENT_SECRET = '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';
const GOOGLE_AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
const GOOGLE_USERINFO_URL = 'https://www.googleapis.com/oauth2/v1/userinfo';
// Local callback server configuration
const CALLBACK_PORT = 51121;
const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}/oauth-callback`;
// Scopes needed for Cloud Code access (matching Antigravity)
const SCOPES = [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/cclog',
'https://www.googleapis.com/auth/experimentsandconfigs'
].join(' ');
/**
* Generate PKCE code verifier and challenge
*/
function generatePKCE() {
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto
.createHash('sha256')
.update(verifier)
.digest('base64url');
return { verifier, challenge };
}
/**
* Generate authorization URL for Google OAuth
* Returns the URL and the PKCE verifier (needed for token exchange)
*/
export function getAuthorizationUrl() {
const { verifier, challenge } = generatePKCE();
const state = crypto.randomBytes(16).toString('hex');
const params = new URLSearchParams({
client_id: GOOGLE_CLIENT_ID,
redirect_uri: REDIRECT_URI,
response_type: 'code',
scope: SCOPES,
access_type: 'offline',
prompt: 'consent',
code_challenge: challenge,
code_challenge_method: 'S256',
state: state
});
return {
url: `${GOOGLE_AUTH_URL}?${params.toString()}`,
verifier,
state
};
}
/**
* Start a local server to receive the OAuth callback
* Returns a promise that resolves with the authorization code
*/
export function startCallbackServer(expectedState, timeoutMs = 120000) {
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://localhost:${CALLBACK_PORT}`);
if (url.pathname !== '/oauth-callback') {
res.writeHead(404);
res.end('Not found');
return;
}
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
const error = url.searchParams.get('error');
if (error) {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<head><title>Authentication Failed</title></head>
<body style="font-family: system-ui; padding: 40px; text-align: center;">
<h1 style="color: #dc3545;">❌ Authentication Failed</h1>
<p>Error: ${error}</p>
<p>You can close this window.</p>
</body>
</html>
`);
server.close();
reject(new Error(`OAuth error: ${error}`));
return;
}
if (state !== expectedState) {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<head><title>Authentication Failed</title></head>
<body style="font-family: system-ui; padding: 40px; text-align: center;">
<h1 style="color: #dc3545;">❌ Authentication Failed</h1>
<p>State mismatch - possible CSRF attack.</p>
<p>You can close this window.</p>
</body>
</html>
`);
server.close();
reject(new Error('State mismatch'));
return;
}
if (!code) {
res.writeHead(400, { 'Content-Type': 'text/html' });
res.end(`
<html>
<head><title>Authentication Failed</title></head>
<body style="font-family: system-ui; padding: 40px; text-align: center;">
<h1 style="color: #dc3545;">❌ Authentication Failed</h1>
<p>No authorization code received.</p>
<p>You can close this window.</p>
</body>
</html>
`);
server.close();
reject(new Error('No authorization code'));
return;
}
// Success!
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<html>
<head><title>Authentication Successful</title></head>
<body style="font-family: system-ui; padding: 40px; text-align: center;">
<h1 style="color: #28a745;">✅ Authentication Successful!</h1>
<p>You can close this window and return to the terminal.</p>
<script>setTimeout(() => window.close(), 2000);</script>
</body>
</html>
`);
server.close();
resolve(code);
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
reject(new Error(`Port ${CALLBACK_PORT} is already in use. Close any other OAuth flows and try again.`));
} else {
reject(err);
}
});
server.listen(CALLBACK_PORT, () => {
console.log(`[OAuth] Callback server listening on port ${CALLBACK_PORT}`);
});
// Timeout after specified duration
setTimeout(() => {
server.close();
reject(new Error('OAuth callback timeout - no response received'));
}, timeoutMs);
});
}
/**
* Exchange authorization code for tokens
*/
export async function exchangeCode(code, verifier) {
const response = await fetch(GOOGLE_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
code: code,
code_verifier: verifier,
grant_type: 'authorization_code',
redirect_uri: REDIRECT_URI
})
});
if (!response.ok) {
const error = await response.text();
console.error('[OAuth] Token exchange failed:', response.status, error);
throw new Error(`Token exchange failed: ${error}`);
}
const tokens = await response.json();
if (!tokens.access_token) {
console.error('[OAuth] No access token in response:', tokens);
throw new Error('No access token received');
}
console.log('[OAuth] Token exchange successful, access_token length:', tokens.access_token?.length);
return {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
expiresIn: tokens.expires_in
};
}
/**
* Refresh access token using refresh token
*/
export async function refreshAccessToken(refreshToken) {
const response = await fetch(GOOGLE_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
refresh_token: refreshToken,
grant_type: 'refresh_token'
})
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Token refresh failed: ${error}`);
}
const tokens = await response.json();
return {
accessToken: tokens.access_token,
expiresIn: tokens.expires_in
};
}
/**
* Get user email from access token
*/
export async function getUserEmail(accessToken) {
const response = await fetch(GOOGLE_USERINFO_URL, {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (!response.ok) {
const errorText = await response.text();
console.error('[OAuth] getUserEmail failed:', response.status, errorText);
throw new Error(`Failed to get user info: ${response.status}`);
}
const userInfo = await response.json();
return userInfo.email;
}
/**
* Discover project ID for the authenticated user
*/
export async function discoverProjectId(accessToken) {
for (const endpoint of ANTIGRAVITY_ENDPOINT_FALLBACKS) {
try {
const response = await fetch(`${endpoint}/v1internal:loadCodeAssist`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
...ANTIGRAVITY_HEADERS
},
body: JSON.stringify({
metadata: {
ideType: 'IDE_UNSPECIFIED',
platform: 'PLATFORM_UNSPECIFIED',
pluginType: 'GEMINI'
}
})
});
if (!response.ok) continue;
const data = await response.json();
if (typeof data.cloudaicompanionProject === 'string') {
return data.cloudaicompanionProject;
}
if (data.cloudaicompanionProject?.id) {
return data.cloudaicompanionProject.id;
}
} catch (error) {
console.log(`[OAuth] Project discovery failed at ${endpoint}:`, error.message);
}
}
return null;
}
/**
* Complete OAuth flow: exchange code and get all account info
*/
export async function completeOAuthFlow(code, verifier) {
// Exchange code for tokens
const tokens = await exchangeCode(code, verifier);
// Get user email
const email = await getUserEmail(tokens.accessToken);
// Discover project ID
const projectId = await discoverProjectId(tokens.accessToken);
return {
email,
refreshToken: tokens.refreshToken,
accessToken: tokens.accessToken,
projectId
};
}
export default {
getAuthorizationUrl,
startCallbackServer,
exchangeCode,
refreshAccessToken,
getUserEmail,
discoverProjectId,
completeOAuthFlow
};

View File

@@ -1,16 +1,43 @@
/**
* Express Server - Anthropic-compatible API
* Proxies to Google Cloud Code via Antigravity
* Supports multi-account load balancing
*/
import express from 'express';
import cors from 'cors';
import { sendMessage, sendMessageStream, listModels, clearProjectCache, getProject } from './cloudcode-client.js';
import { getToken, forceRefresh } from './token-extractor.js';
import { AVAILABLE_MODELS, REQUEST_BODY_LIMIT } from './constants.js';
import { sendMessage, sendMessageStream, listModels } from './cloudcode-client.js';
import { forceRefresh } from './token-extractor.js';
import { REQUEST_BODY_LIMIT } from './constants.js';
import { AccountManager } from './account-manager.js';
const app = express();
// Initialize account manager (will be fully initialized on first request or startup)
const accountManager = new AccountManager();
// Track initialization status
let isInitialized = false;
let initError = null;
/**
* Ensure account manager is initialized
*/
async function ensureInitialized() {
if (isInitialized) return;
try {
await accountManager.initialize();
isInitialized = true;
const status = accountManager.getStatus();
console.log(`[Server] Account pool initialized: ${status.summary}`);
} catch (error) {
initError = error;
console.error('[Server] Failed to initialize account manager:', error.message);
throw error;
}
}
// Middleware
app.use(cors());
app.use(express.json({ limit: REQUEST_BODY_LIMIT }));
@@ -27,13 +54,20 @@ function parseError(error) {
errorType = 'authentication_error';
statusCode = 401;
errorMessage = 'Authentication failed. Make sure Antigravity is running with a valid token.';
} else if (error.message.includes('429') || error.message.includes('RESOURCE_EXHAUSTED')) {
errorType = 'rate_limit_error';
statusCode = 429;
const resetMatch = error.message.match(/quota will reset after (\d+h\d+m\d+s|\d+s)/i);
errorMessage = resetMatch
? `Rate limited. Quota will reset after ${resetMatch[1]}.`
: 'Rate limited. Please wait and try again.';
} else if (error.message.includes('429') || error.message.includes('RESOURCE_EXHAUSTED') || error.message.includes('QUOTA_EXHAUSTED')) {
errorType = 'overloaded_error'; // Claude Code recognizes this type
statusCode = 529; // Use 529 for overloaded (Claude API convention)
// Try to extract the quota reset time from the error
const resetMatch = error.message.match(/quota will reset after (\d+h\d+m\d+s|\d+m\d+s|\d+s)/i);
const modelMatch = error.message.match(/"model":\s*"([^"]+)"/);
const model = modelMatch ? modelMatch[1] : 'the model';
if (resetMatch) {
errorMessage = `You have exhausted your capacity on ${model}. Quota will reset after ${resetMatch[1]}.`;
} else {
errorMessage = `You have exhausted your capacity on ${model}. Please wait for your quota to reset.`;
}
} else if (error.message.includes('invalid_request_error') || error.message.includes('INVALID_ARGUMENT')) {
errorType = 'invalid_request_error';
statusCode = 400;
@@ -63,19 +97,15 @@ app.use((req, res, next) => {
*/
app.get('/health', async (req, res) => {
try {
const token = await getToken();
let project = null;
try {
project = await getProject(token);
} catch (e) {
// Project fetch might fail if token just refreshed
}
await ensureInitialized();
const status = accountManager.getStatus();
res.json({
status: 'ok',
hasToken: !!token,
tokenPrefix: token ? token.substring(0, 10) + '...' : null,
project: project || 'unknown',
accounts: status.summary,
available: status.available,
rateLimited: status.rateLimited,
invalid: status.invalid,
timestamp: new Date().toISOString()
});
} catch (error) {
@@ -87,16 +117,55 @@ app.get('/health', async (req, res) => {
}
});
/**
* Account pool status endpoint
*/
app.get('/accounts', async (req, res) => {
try {
await ensureInitialized();
const status = accountManager.getStatus();
res.json({
total: status.total,
available: status.available,
rateLimited: status.rateLimited,
invalid: status.invalid,
accounts: status.accounts.map(a => ({
email: a.email,
source: a.source,
isRateLimited: a.isRateLimited,
rateLimitResetTime: a.rateLimitResetTime
? new Date(a.rateLimitResetTime).toISOString()
: null,
isInvalid: a.isInvalid,
invalidReason: a.invalidReason,
lastUsed: a.lastUsed
? new Date(a.lastUsed).toISOString()
: null
}))
});
} catch (error) {
res.status(500).json({
status: 'error',
error: error.message
});
}
});
/**
* Force token refresh endpoint
*/
app.post('/refresh-token', async (req, res) => {
try {
clearProjectCache();
await ensureInitialized();
// Clear all caches
accountManager.clearTokenCache();
accountManager.clearProjectCache();
// Force refresh default token
const token = await forceRefresh();
res.json({
status: 'ok',
message: 'Token refreshed successfully',
message: 'Token caches cleared and refreshed',
tokenPrefix: token.substring(0, 10) + '...'
});
} catch (error) {
@@ -119,6 +188,9 @@ app.get('/v1/models', (req, res) => {
*/
app.post('/v1/messages', async (req, res) => {
try {
// Ensure account manager is initialized
await ensureInitialized();
const {
model,
messages,
@@ -161,6 +233,15 @@ app.post('/v1/messages', async (req, res) => {
console.log(`[API] Request for model: ${request.model}, stream: ${!!stream}`);
// Debug: Log message structure to diagnose tool_use/tool_result ordering
console.log('[API] Message structure:');
messages.forEach((msg, i) => {
const contentTypes = Array.isArray(msg.content)
? msg.content.map(c => c.type || 'text').join(', ')
: (typeof msg.content === 'string' ? 'text' : 'unknown');
console.log(` [${i}] ${msg.role}: ${contentTypes}`);
});
if (stream) {
// Handle streaming response
res.setHeader('Content-Type', 'text/event-stream');
@@ -168,10 +249,15 @@ app.post('/v1/messages', async (req, res) => {
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
// Flush headers immediately to start the stream
res.flushHeaders();
try {
// Use the streaming generator
for await (const event of sendMessageStream(request)) {
// Use the streaming generator with account manager
for await (const event of sendMessageStream(request, accountManager)) {
res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
// Flush after each event for real-time streaming
if (res.flush) res.flush();
}
res.end();
@@ -189,7 +275,7 @@ app.post('/v1/messages', async (req, res) => {
} else {
// Handle non-streaming response
const response = await sendMessage(request);
const response = await sendMessage(request, accountManager);
res.json(response);
}
@@ -202,7 +288,8 @@ app.post('/v1/messages', async (req, res) => {
if (errorType === 'authentication_error') {
console.log('[API] Token might be expired, attempting refresh...');
try {
clearProjectCache();
accountManager.clearProjectCache();
accountManager.clearTokenCache();
await forceRefresh();
errorMessage = 'Token was expired and has been refreshed. Please retry your request.';
} catch (refreshError) {
@@ -210,13 +297,25 @@ app.post('/v1/messages', async (req, res) => {
}
}
res.status(statusCode).json({
type: 'error',
error: {
type: errorType,
message: errorMessage
}
});
console.log(`[API] Returning error response: ${statusCode} ${errorType} - ${errorMessage}`);
// Check if headers have already been sent (for streaming that failed mid-way)
if (res.headersSent) {
console.log('[API] Headers already sent, writing error as SSE event');
res.write(`event: error\ndata: ${JSON.stringify({
type: 'error',
error: { type: errorType, message: errorMessage }
})}\n\n`);
res.end();
} else {
res.status(statusCode).json({
type: 'error',
error: {
type: errorType,
message: errorMessage
}
});
}
}
});

View File

@@ -9,7 +9,6 @@
import { execSync } from 'child_process';
import { homedir } from 'os';
import { join } from 'path';
import fetch from 'node-fetch';
import { TOKEN_REFRESH_INTERVAL_MS, ANTIGRAVITY_AUTH_PORT } from './constants.js';
// Cache for the extracted token
@@ -138,27 +137,6 @@ export async function getToken() {
return cachedToken;
}
/**
* Get the full configuration from Antigravity
*/
export async function getConfig() {
if (needsRefresh()) {
await getToken(); // This will refresh the cache
}
return cachedConfig;
}
/**
* Get available models from the cached config
*/
export async function getAvailableModels() {
const config = await getConfig();
if (!config?.initialUserStatus?.cascadeModelConfigData?.clientModelConfigs) {
return [];
}
return config.initialUserStatus.cascadeModelConfigData.clientModelConfigs;
}
/**
* Force refresh the token (useful if requests start failing)
*/
@@ -169,13 +147,7 @@ export async function forceRefresh() {
return getToken();
}
// Alias for forceRefresh
export const refreshToken = forceRefresh;
export default {
getToken,
getConfig,
getAvailableModels,
forceRefresh,
refreshToken
forceRefresh
};