272 lines
11 KiB
JavaScript
272 lines
11 KiB
JavaScript
const http = require('http');
|
|
const https = require('https');
|
|
const os = require('os');
|
|
const { exec } = require('child_process');
|
|
const fs = require('fs');
|
|
|
|
const COMMAND_TIMEOUT_MS = 5000;
|
|
const MAX_BUFFER_BYTES = 10 * 1024 * 1024;
|
|
|
|
function runCommand(command, timeout = COMMAND_TIMEOUT_MS) {
|
|
return new Promise((resolve) => {
|
|
exec(command, { timeout, maxBuffer: MAX_BUFFER_BYTES }, (error, stdout, stderr) => {
|
|
resolve({ error, stdout: stdout || '', stderr: stderr || '' });
|
|
});
|
|
});
|
|
}
|
|
|
|
function parseWindowsProcessJson(stdout) {
|
|
if (!stdout.trim()) return [];
|
|
const parsed = JSON.parse(stdout);
|
|
const rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
return rows
|
|
.filter(row => row && row.ProcessId)
|
|
.map(row => ({
|
|
pid: Number(row.ProcessId),
|
|
ppid: Number(row.ParentProcessId || 0),
|
|
commandLine: row.CommandLine || row.ExecutablePath || '',
|
|
}));
|
|
}
|
|
|
|
async function listLanguageServerProcesses() {
|
|
const command = [
|
|
'powershell -NoProfile -Command',
|
|
'"Get-CimInstance Win32_Process -Filter \\"name like \'language_server%\'\\"',
|
|
'| Select-Object ProcessId,ParentProcessId,CommandLine,ExecutablePath',
|
|
'| ConvertTo-Json -Depth 2"',
|
|
].join(' ');
|
|
const result = await runCommand(command);
|
|
if (result.error && !result.stdout.trim()) {
|
|
throw new Error(result.stderr.trim() || result.error.message);
|
|
}
|
|
return parseWindowsProcessJson(result.stdout);
|
|
}
|
|
|
|
function extractArgument(commandLine, argumentName) {
|
|
const escapedName = argumentName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
const pattern = new RegExp(`--${escapedName}(?:=|\\s+)(?:"([^"]*)"|'([^']*)'|([^\\s]+))`, 'i');
|
|
const match = commandLine.match(pattern);
|
|
return match ? (match[1] ?? match[2] ?? match[3] ?? null) : null;
|
|
}
|
|
|
|
const API_PATH = '/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary';
|
|
const requestBody = JSON.stringify({ metadata: { ideName: 'antigravity', extensionName: 'ag-usage', locale: 'en' } });
|
|
|
|
function tryPort(port, csrfToken, protocol) {
|
|
return new Promise(resolve => {
|
|
const client = protocol === 'https' ? https : http;
|
|
const req = client.request({
|
|
hostname: '127.0.0.1', port, path: API_PATH, method: 'POST',
|
|
...(protocol === 'https' ? { rejectUnauthorized: false } : {}),
|
|
headers: {
|
|
'X-Codeium-Csrf-Token': csrfToken,
|
|
'Connect-Protocol-Version': '1',
|
|
'Content-Type': 'application/json',
|
|
'Content-Length': Buffer.byteLength(requestBody),
|
|
},
|
|
timeout: 3000,
|
|
}, res => {
|
|
let body = '';
|
|
res.setEncoding('utf8');
|
|
res.on('data', chunk => body += chunk);
|
|
res.on('end', () => resolve({ port, statusCode: res.statusCode, body }));
|
|
});
|
|
req.on('error', () => resolve(null));
|
|
req.on('timeout', () => { req.destroy(); resolve(null); });
|
|
req.end(requestBody);
|
|
});
|
|
}
|
|
|
|
function parseResponse(body) {
|
|
const trimmed = body.trim();
|
|
if (!trimmed) return null;
|
|
try { return JSON.parse(trimmed); } catch {}
|
|
|
|
// Fallback for NDJSON or streamed lines
|
|
for (const line of trimmed.split(/\r?\n/).filter(Boolean)) {
|
|
try { return JSON.parse(line); } catch {}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
async function discoverWindowsListeningPorts(pid) {
|
|
const command = [
|
|
'powershell -NoProfile -Command',
|
|
`"Get-NetTCPConnection -OwningProcess ${pid} -ErrorAction SilentlyContinue`,
|
|
'| Select-Object LocalAddress,LocalPort,RemotePort,State',
|
|
'| ConvertTo-Json"',
|
|
].join(' ');
|
|
const result = await runCommand(command);
|
|
const ports = [];
|
|
if (result.stdout.trim()) {
|
|
try {
|
|
const parsed = JSON.parse(result.stdout);
|
|
const rows = Array.isArray(parsed) ? parsed : [parsed];
|
|
for (const row of rows) {
|
|
if (!row) continue;
|
|
const isLoopback = row.LocalAddress === '127.0.0.1' || row.LocalAddress === '::1';
|
|
const isListeningState = row.State === null || row.State === 2 || row.State === 'Listen';
|
|
const port = Number(row.LocalPort);
|
|
if (isLoopback && Number(row.RemotePort) === 0 && isListeningState && port > 0 && port < 65536) {
|
|
ports.push(port);
|
|
}
|
|
}
|
|
} catch {
|
|
// Fall back to netstat below if PowerShell JSON parsing fails.
|
|
}
|
|
}
|
|
if (ports.length > 0) return ports;
|
|
|
|
const netstatResult = await runCommand('netstat -ano');
|
|
for (const line of netstatResult.stdout.split(/\r?\n/)) {
|
|
if (!new RegExp(`\\s${pid}\\s*$`).test(line)) continue;
|
|
if (!/(LISTEN|ABH|HERGESTELLT|ESTABLISHED)/i.test(line)) continue;
|
|
const match = line.match(/^\s*TCP\s+(?:127\.0\.0\.1|\[?::1\]?):(\d{2,5})\s/i);
|
|
if (!match) continue;
|
|
const port = Number(match[1]);
|
|
if (port > 0 && port < 65536) ports.push(port);
|
|
}
|
|
return ports;
|
|
}
|
|
|
|
async function syncToTokenWatch(quotaData) {
|
|
const postData = JSON.stringify(quotaData);
|
|
// Ersetze diese URL durch die echte von TokenWatch auf der Jannik-Cloud, sobald sie läuft.
|
|
const url = 'https://tokenwatch.orfel.de/api/webhook/antigravity';
|
|
const isHttps = url.startsWith('https');
|
|
const client = isHttps ? https : http;
|
|
|
|
return new Promise((resolve) => {
|
|
const req = client.request(url, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) },
|
|
timeout: 10000,
|
|
}, (res) => {
|
|
let body = '';
|
|
res.on('data', chunk => body += chunk);
|
|
res.on('end', () => {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
resolve(true);
|
|
} else {
|
|
console.error(`Webhook HTTP ${res.statusCode}:`, body);
|
|
resolve(false);
|
|
}
|
|
});
|
|
});
|
|
req.on('timeout', () => {
|
|
console.error('Webhook error: Request timed out');
|
|
req.destroy();
|
|
resolve(false);
|
|
});
|
|
req.on('error', (err) => {
|
|
console.error('Webhook error:', err.message);
|
|
resolve(false);
|
|
});
|
|
req.write(postData);
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
function extractQuotaBuckets(groups) {
|
|
let gemini5h = null, geminiWeekly = null, gemini5hReset = null, geminiWeeklyReset = null;
|
|
let claude5h = null, claudeWeekly = null, claude5hReset = null, claudeWeeklyReset = null;
|
|
|
|
for (const group of groups) {
|
|
const displayName = (group.displayName || '').toLowerCase();
|
|
const isMainGeminiGroup = displayName === 'gemini models' || (displayName.includes('gemini') && !displayName.includes('argon'));
|
|
const isClaudeGroup = displayName.includes('claude') || displayName.includes('3p');
|
|
|
|
for (const bucket of group.buckets || []) {
|
|
const id = bucket.bucketId;
|
|
if (id === 'gemini-5h' || (gemini5h === null && isMainGeminiGroup && bucket.window === '5h')) {
|
|
gemini5h = bucket.remainingFraction ?? 1;
|
|
gemini5hReset = bucket.resetTime || null;
|
|
} else if (id === 'gemini-weekly' || (geminiWeekly === null && isMainGeminiGroup && bucket.window === 'weekly')) {
|
|
geminiWeekly = bucket.remainingFraction ?? 1;
|
|
geminiWeeklyReset = bucket.resetTime || null;
|
|
} else if (id === '3p-5h' || (claude5h === null && isClaudeGroup && bucket.window === '5h')) {
|
|
claude5h = bucket.remainingFraction ?? 1;
|
|
claude5hReset = bucket.resetTime || null;
|
|
} else if (id === '3p-weekly' || (claudeWeekly === null && isClaudeGroup && bucket.window === 'weekly')) {
|
|
claudeWeekly = bucket.remainingFraction ?? 1;
|
|
claudeWeeklyReset = bucket.resetTime || null;
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
gemini_5h_remaining: Math.round((gemini5h ?? 1) * 100),
|
|
gemini_weekly_remaining: Math.round((geminiWeekly ?? 1) * 100),
|
|
claude_5h_remaining: Math.round((claude5h ?? 1) * 100),
|
|
claude_weekly_remaining: Math.round((claudeWeekly ?? 1) * 100),
|
|
gemini_5h_reset: gemini5hReset,
|
|
gemini_weekly_reset: geminiWeeklyReset,
|
|
claude_5h_reset: claude5hReset,
|
|
claude_weekly_reset: claudeWeeklyReset,
|
|
};
|
|
}
|
|
|
|
async function main() {
|
|
console.log('Suche Antigravity Language Server...');
|
|
const processes = await listLanguageServerProcesses();
|
|
const candidatesProcs = processes
|
|
.filter(item => extractArgument(item.commandLine, 'csrf_token'))
|
|
.sort((a, b) => {
|
|
const aHub = extractArgument(a.commandLine, 'subclient_type') === 'hub' ? 0 : 1;
|
|
const bHub = extractArgument(b.commandLine, 'subclient_type') === 'hub' ? 0 : 1;
|
|
return aHub - bHub;
|
|
});
|
|
|
|
if (candidatesProcs.length === 0) {
|
|
console.error('Fehler: Kein Antigravity language_server Prozess gefunden.');
|
|
process.exitCode = 1;
|
|
return;
|
|
}
|
|
|
|
let actualData = null;
|
|
for (const processInfo of candidatesProcs) {
|
|
const csrfToken = extractArgument(processInfo.commandLine, 'csrf_token');
|
|
const extensionPort = Number(extractArgument(processInfo.commandLine, 'extension_server_port')) || null;
|
|
const listeningPorts = await discoverWindowsListeningPorts(processInfo.pid);
|
|
const candidates = [...new Set(listeningPorts)].filter(port => port !== extensionPort).sort((a, b) => a - b);
|
|
|
|
for (const port of candidates) {
|
|
for (const protocol of ['https', 'http']) {
|
|
const result = await tryPort(port, csrfToken, protocol);
|
|
if (result && result.statusCode === 200) {
|
|
const parsed = parseResponse(result.body);
|
|
const candidateData = Array.isArray(parsed) ? parsed[0] : parsed;
|
|
if (candidateData?.response?.groups) {
|
|
actualData = candidateData;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (actualData) break;
|
|
}
|
|
if (actualData) break;
|
|
}
|
|
|
|
const groups = actualData?.response?.groups;
|
|
if (!groups) {
|
|
console.error('Fehler: Konnte keine JSON-Antwort mit Quota auslesen.', actualData);
|
|
process.exitCode = 1;
|
|
return;
|
|
}
|
|
|
|
const payload = extractQuotaBuckets(groups);
|
|
console.log('Gefundene Live-Daten:', payload);
|
|
const ok = await syncToTokenWatch(payload);
|
|
if (ok) {
|
|
console.log('Erfolgreich an TokenWatch gesendet!');
|
|
} else {
|
|
console.error('Fehler beim Senden an TokenWatch.');
|
|
process.exitCode = 1;
|
|
}
|
|
}
|
|
|
|
main().catch(err => {
|
|
console.error(err);
|
|
process.exitCode = 1;
|
|
});
|