forked from f/agentlytics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·309 lines (272 loc) · 11.7 KB
/
index.js
File metadata and controls
executable file
·309 lines (272 loc) · 11.7 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
#!/usr/bin/env node
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');
const HOME = os.homedir();
const PORT = process.env.PORT || 4637;
const RELAY_PORT = process.env.RELAY_PORT || 4638;
const noCache = process.argv.includes('--no-cache');
const collectOnly = process.argv.includes('--collect');
const isRelay = process.argv.includes('--relay');
const joinIndex = process.argv.indexOf('--join');
const isJoin = joinIndex !== -1;
// ── Relay mode ───────────────────────────────────────────────
if (isRelay) {
const { initRelayDb, getRelayDb, createRelayApp } = require('./relay-server');
const { wireMcpToExpress } = require('./mcp-server');
console.log('');
console.log(chalk.bold(' ⚡ Agentlytics Relay'));
console.log(chalk.dim(' Multi-user context sharing server'));
console.log('');
initRelayDb();
console.log(chalk.green(' ✓ Relay database initialized'));
const app = createRelayApp();
wireMcpToExpress(app, getRelayDb);
console.log(chalk.green(' ✓ MCP server registered'));
if (process.env.RELAY_PASSWORD) {
console.log(chalk.green(' ✓ Password protection enabled'));
} else {
console.log(chalk.yellow(' ⚠ No password set (set RELAY_PASSWORD env to protect)'));
}
app.listen(RELAY_PORT, () => {
const localIp = getLocalIp();
const relayUrl = `http://${localIp}:${RELAY_PORT}`;
console.log('');
console.log(chalk.green(` ✓ Relay server running on port ${RELAY_PORT}`));
console.log('');
console.log(chalk.bold(' Share this command with your team:'));
console.log('');
console.log(chalk.cyan(` npx agentlytics --join ${localIp}:${RELAY_PORT} --username <name>`));
console.log('');
console.log(chalk.bold(' MCP server endpoint (add to your AI client):'));
console.log('');
console.log(chalk.cyan(` ${relayUrl}/mcp`));
console.log('');
console.log(chalk.dim(' REST endpoints:'));
console.log(chalk.dim(` GET ${relayUrl}/relay/health`));
console.log(chalk.dim(` GET ${relayUrl}/relay/users`));
console.log(chalk.dim(` GET ${relayUrl}/relay/search?q=<query>`));
console.log(chalk.dim(` GET ${relayUrl}/relay/activity/<username>`));
console.log(chalk.dim(` GET ${relayUrl}/relay/session/<chatId>`));
console.log('');
console.log(chalk.dim(' Press Ctrl+C to stop'));
console.log('');
});
// Skip the rest of the normal flow
return;
}
// ── Join mode ────────────────────────────────────────────────
if (isJoin) {
(async () => {
const relayAddress = process.argv[joinIndex + 1];
const usernameIndex = process.argv.indexOf('--username');
let username = usernameIndex !== -1 ? process.argv[usernameIndex + 1] : null;
if (!relayAddress) {
console.error(chalk.red('\n ✗ Missing relay address. Usage: npx agentlytics --join <host:port> --username <name>\n'));
process.exit(1);
}
// Auto-detect username from git config if not provided
if (!username) {
try {
const gitEmail = execSync('git config user.email', { encoding: 'utf-8' }).trim();
if (gitEmail) username = gitEmail;
} catch {}
}
// If still no username, ask interactively
if (!username) {
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
username = await new Promise(r => {
rl.question(chalk.bold('\n Enter your username: '), (answer) => {
rl.close();
r(answer.trim());
});
});
if (!username) {
console.error(chalk.red('\n ✗ Username is required.\n'));
process.exit(1);
}
}
const { startJoinClient } = require('./relay-client');
startJoinClient(relayAddress, username);
})();
// Skip the rest of the normal flow
return;
}
// ── Helper: get local IP for relay ───────────────────────────
function getLocalIp() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) return iface.address;
}
}
return 'localhost';
}
// ── ASCII banner ─────────────────────────────────────────
const c1 = chalk.hex('#818cf8'), c2 = chalk.hex('#f472b6'), c3 = chalk.hex('#34d399'), c4 = chalk.hex('#fbbf24');
console.log('');
console.log(` ${c1('(● ●)')} ${c2('[● ●]')} ${chalk.bold('Agentlytics')}`);
console.log(` ${c3('{● ●}')} ${c4('<● ●>')} ${chalk.dim('Unified analytics for your AI coding agents')}`);
if (collectOnly) console.log(chalk.cyan(' ⟳ Collect-only mode (no server)'));
console.log('');
// ── Build UI if not already built ──────────────────────────
const publicIndex = path.join(__dirname, 'public', 'index.html');
const uiDir = path.join(__dirname, 'ui');
if (!collectOnly && !fs.existsSync(publicIndex) && fs.existsSync(uiDir)) {
console.log(chalk.cyan(' ⟳ Building dashboard UI (first run)...'));
try {
const uiModules = path.join(uiDir, 'node_modules');
if (!fs.existsSync(uiModules)) {
console.log(chalk.dim(' Installing UI dependencies...'));
execSync('npm install --no-audit --no-fund', { cwd: uiDir, stdio: 'pipe' });
}
console.log(chalk.dim(' Compiling frontend...'));
execSync('npm run build', { cwd: uiDir, stdio: 'pipe' });
console.log(chalk.green(' ✓ UI built successfully'));
} catch (err) {
console.error(chalk.red(' ✗ UI build failed:'), err.message);
process.exit(1);
}
console.log('');
}
if (!collectOnly && !fs.existsSync(publicIndex)) {
console.error(chalk.red(' ✗ No built UI found at public/index.html'));
console.error(chalk.dim(' Run: cd ui && npm install && npm run build'));
process.exit(1);
}
const cache = require('./cache');
// Wipe cache if --no-cache flag is passed
if (noCache) {
const cacheDb = path.join(os.homedir(), '.agentlytics', 'cache.db');
if (fs.existsSync(cacheDb)) {
fs.unlinkSync(cacheDb);
// Remove WAL/SHM journal files to avoid SQLITE_IOERR_SHORT_READ
for (const suffix of ['-wal', '-shm']) {
if (fs.existsSync(cacheDb + suffix)) fs.unlinkSync(cacheDb + suffix);
}
console.log(chalk.yellow(' ⟳ Cache cleared (--no-cache)'));
}
}
// ── Warn about installed-but-not-running Windsurf variants (macOS only) ─
if (process.platform === 'darwin') {
const WINDSURF_VARIANTS = [
{ name: 'Windsurf', app: '/Applications/Windsurf.app', dataDir: path.join(HOME, '.codeium', 'windsurf'), ide: 'windsurf' },
{ name: 'Windsurf Next', app: '/Applications/Windsurf Next.app', dataDir: path.join(HOME, '.codeium', 'windsurf-next'), ide: 'windsurf-next' },
{ name: 'Antigravity', app: '/Applications/Antigravity.app', dataDir: path.join(HOME, '.codeium', 'antigravity'), ide: 'antigravity' },
];
(() => {
// Check which language servers are running
let runningIdes = [];
try {
const ps = execSync('ps aux', { encoding: 'utf-8', maxBuffer: 1024 * 1024 });
for (const line of ps.split('\n')) {
if (!line.includes('language_server_macos') || !line.includes('--csrf_token')) continue;
const ideMatch = line.match(/--ide_name\s+(\S+)/);
const appDirMatch = line.match(/--app_data_dir\s+(\S+)/);
if (ideMatch) runningIdes.push(ideMatch[1]);
if (appDirMatch) runningIdes.push(appDirMatch[1]);
}
} catch {}
const installedNotRunning = WINDSURF_VARIANTS.filter(v => {
const installed = fs.existsSync(v.app) || fs.existsSync(v.dataDir);
const running = runningIdes.some(r => r === v.ide || r.includes(v.ide));
return installed && !running;
});
if (installedNotRunning.length > 0) {
const names = installedNotRunning.map(v => chalk.bold(v.name)).join(', ');
console.log(chalk.yellow(` ⚠ ${names} installed but not running`));
console.log(chalk.dim(' These editors must be open for their sessions to be detected.'));
console.log('');
}
})();
}
// Initialize cache DB
cache.initDb();
// ── Detect editors & collect sessions ───────────────────────
const { editors: editorModules } = require('./editors');
const EDITOR_DISPLAY = [
['cursor', 'Cursor'],
['windsurf', 'Windsurf'],
['windsurf-next', 'Windsurf Next'],
['antigravity', 'Antigravity'],
['claude-code', 'Claude Code'],
['vscode', 'VS Code'],
['vscode-insiders', 'VS Code Insiders'],
['zed', 'Zed'],
['opencode', 'OpenCode'],
['codex', 'Codex'],
['gemini-cli', 'Gemini CLI'],
['kimi-cli', 'Kimi CLI'],
['copilot-cli', 'Copilot CLI'],
['cursor-agent', 'Cursor Agent'],
['commandcode', 'Command Code'],
];
console.log(chalk.dim(' Looking for AI coding agents...'));
const allChats = [];
for (const editor of editorModules) {
try {
const chats = editor.getChats();
allChats.push(...chats);
} catch { /* skip broken adapters */ }
}
allChats.sort((a, b) => (b.lastUpdatedAt || b.createdAt || 0) - (a.lastUpdatedAt || a.createdAt || 0));
// Count per source
const bySource = {};
for (const chat of allChats) bySource[chat.source] = (bySource[chat.source] || 0) + 1;
for (const [src, label] of EDITOR_DISPLAY) {
const count = bySource[src] || 0;
if (count > 0) {
console.log(` ${chalk.green('✓')} ${chalk.bold(label.padEnd(18))} ${chalk.dim(`${count} session${count === 1 ? '' : 's'}`)}`);
} else {
console.log(` ${chalk.dim('–')} ${chalk.dim(label.padEnd(18) + '–')}`);
}
}
console.log('');
// ── Analyze sessions with robot animation ──────────────────
const logUpdate = require('log-update');
const BOT_STYLES = [
{ l: '(', r: ')', color: '#818cf8' },
{ l: '[', r: ']', color: '#f472b6' },
{ l: '{', r: '}', color: '#34d399' },
{ l: '<', r: '>', color: '#fbbf24' },
];
let tick = 0;
const startTime = Date.now();
const result = cache.scanAll((p) => {
tick++;
if (tick % 5 !== 0) return;
const frame = Math.floor(tick / 40);
const b = BOT_STYLES[frame % 4];
const dots = '.'.repeat((Math.floor(tick / 10) % 3) + 1).padEnd(3);
logUpdate(` ${chalk.hex(b.color)(`${b.l}● ●${b.r}`)} ${chalk.dim(`Analyzing${dots} ${p.scanned}/${p.total}`)}`);
}, { chats: allChats });
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
const allFaces = BOT_STYLES.map(b => chalk.hex(b.color)(`${b.l}● ●${b.r}`)).join(' ');
logUpdate(` ${allFaces} ${chalk.green(`✓ ${result.analyzed} analyzed, ${result.skipped} cached (${elapsed}s)`)}`);
logUpdate.done();
console.log('');
// In collect-only mode, exit after cache is built
if (collectOnly) {
const cacheDbPath = path.join(os.homedir(), '.agentlytics', 'cache.db');
console.log(chalk.dim(` Cache file: ${cacheDbPath}`));
console.log('');
process.exit(0);
}
// Start server
const app = require('./server');
app.listen(PORT, () => {
const url = `http://localhost:${PORT}`;
console.log(chalk.green(` ✓ Dashboard ready at ${chalk.bold.white(url)}`));
console.log('');
console.log(chalk.dim(' 💡 Share sessions with your team:'));
console.log(chalk.dim(` npx agentlytics --relay Start a relay server`));
console.log(chalk.dim(` npx agentlytics --join <host:port> --username Join a relay server`));
console.log('');
console.log(chalk.dim(' Press Ctrl+C to stop\n'));
// Auto-open browser
const open = require('open');
open(url).catch(() => {});
});