@markmayandi/bridge 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bridge.js ADDED
@@ -0,0 +1,897 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * =========================================================================
5
+ * BRIDGE — Universal Local-to-Web AI Coding Harness
6
+ * LN4 Volt Edition (Fluorescent Volt Green #D2FF00 + Charcoal Grays)
7
+ * Connects Local Projects to Google Gemini, Claude, ChatGPT & DeepSeek
8
+ * =========================================================================
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const http = require('http');
14
+ const https = require('https');
15
+ const os = require('os');
16
+ const readline = require('readline');
17
+ const { spawn, execSync } = require('child_process');
18
+
19
+ // Lando Norris Signature LN4 Palette (#D2FF00 + Charcoal Grays)
20
+ const C = {
21
+ reset: '\x1b[0m',
22
+ bold: '\x1b[1m',
23
+ dim: '\x1b[2m',
24
+
25
+ // Volt Green (Lando Norris Signature #D2FF00 - RGB 210, 255, 0)
26
+ volt: '\x1b[38;2;210;255;0m',
27
+ voltBold: '\x1b[1;38;2;210;255;0m',
28
+ bgVolt: '\x1b[48;2;210;255;0m\x1b[38;2;0;0;0m', // High-contrast black on volt green
29
+ bgVoltDark: '\x1b[48;2;28;34;0m',
30
+
31
+ // Sleek Charcoal & Asphalt Grays
32
+ steel: '\x1b[38;2;65;68;82m',
33
+ slate: '\x1b[38;2;142;146;164m',
34
+ lightSlate: '\x1b[38;2;180;185;200m',
35
+ white: '\x1b[38;2;240;242;248m',
36
+ whiteBold: '\x1b[1;38;2;255;255;255m',
37
+ darkDivider: '\x1b[38;2;44;47;58m',
38
+
39
+ // Accents
40
+ cyan: '\x1b[38;2;80;200;255m',
41
+ cyanBold: '\x1b[1;38;2;80;200;255m',
42
+ red: '\x1b[38;2;239;68;68m',
43
+ redBold: '\x1b[1;38;2;239;68;68m',
44
+
45
+ // Fallback compatibility
46
+ neon: '\x1b[38;2;210;255;0m',
47
+ neonBold: '\x1b[1;38;2;210;255;0m',
48
+ bgNeon: '\x1b[48;2;210;255;0m\x1b[38;2;0;0;0m',
49
+ coral: '\x1b[38;2;210;255;0m',
50
+ coralBold: '\x1b[1;38;2;210;255;0m',
51
+ bgCoral: '\x1b[48;2;210;255;0m\x1b[38;2;0;0;0m',
52
+ bgCyan: '\x1b[48;2;12;35;60m',
53
+ divider: '\x1b[38;2;44;47;58m',
54
+ yellow: '\x1b[38;2;210;255;0m',
55
+ gray: '\x1b[38;2;142;146;164m',
56
+ brightCyan: '\x1b[38;2;80;200;255m',
57
+ brightGreen: '\x1b[38;2;210;255;0m',
58
+ green: '\x1b[38;2;210;255;0m'
59
+ };
60
+
61
+ const scriptDir = __dirname;
62
+ const serverScript = path.join(scriptDir, 'secure-folder-mcp', 'server.js');
63
+
64
+ function getCloudflaredDownloadUrl() {
65
+ const platform = process.platform;
66
+ const arch = process.arch;
67
+
68
+ if (platform === 'win32') {
69
+ return 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe';
70
+ } else if (platform === 'darwin') {
71
+ return arch === 'arm64'
72
+ ? 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-arm64'
73
+ : 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-amd64';
74
+ } else if (platform === 'linux') {
75
+ return arch === 'arm64'
76
+ ? 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64'
77
+ : 'https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64';
78
+ }
79
+ return null;
80
+ }
81
+
82
+ function downloadBinaryWithRedirects(url, destPath) {
83
+ return new Promise((resolve, reject) => {
84
+ function get(currentUrl) {
85
+ https.get(currentUrl, (res) => {
86
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
87
+ get(res.headers.location);
88
+ return;
89
+ }
90
+ if (res.statusCode !== 200) {
91
+ reject(new Error(`Failed to download binary: HTTP ${res.statusCode}`));
92
+ return;
93
+ }
94
+ const fileStream = fs.createWriteStream(destPath);
95
+ res.pipe(fileStream);
96
+ fileStream.on('finish', () => {
97
+ fileStream.close(() => resolve(destPath));
98
+ });
99
+ fileStream.on('error', reject);
100
+ }).on('error', reject);
101
+ }
102
+ get(url);
103
+ });
104
+ }
105
+
106
+ async function ensureCloudflaredBinary() {
107
+ const exeName = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
108
+ // 1. Local directory check
109
+ const localPath = path.join(scriptDir, exeName);
110
+ if (fs.existsSync(localPath)) return localPath;
111
+
112
+ // 2. System PATH check
113
+ try {
114
+ const cmd = process.platform === 'win32' ? 'where.exe cloudflared' : 'which cloudflared';
115
+ const found = execSync(cmd, { stdio: 'pipe' }).toString().trim().split(/\r?\n/)[0].trim();
116
+ if (found && fs.existsSync(found)) return found;
117
+ } catch (e) {}
118
+
119
+ // 3. User cache directory (~/.bridge/bin/)
120
+ const userBridgeDir = path.join(os.homedir(), '.bridge', 'bin');
121
+ const cachedPath = path.join(userBridgeDir, exeName);
122
+ if (fs.existsSync(cachedPath)) return cachedPath;
123
+
124
+ // 4. Download on-demand (one-time setup for new machines)
125
+ if (!fs.existsSync(userBridgeDir)) {
126
+ fs.mkdirSync(userBridgeDir, { recursive: true });
127
+ }
128
+
129
+ const downloadUrl = getCloudflaredDownloadUrl();
130
+ if (!downloadUrl) {
131
+ throw new Error(`Unsupported platform: ${process.platform} (${process.arch})`);
132
+ }
133
+
134
+ process.stdout.write(`\n ${C.voltBold}● [FIRST RUN]${C.reset} ${C.white}Installing Cloudflare tunnel binary for ${process.platform}-${process.arch}...${C.reset}\n`);
135
+ await downloadBinaryWithRedirects(downloadUrl, cachedPath);
136
+ if (process.platform !== 'win32') {
137
+ fs.chmodSync(cachedPath, 0o755);
138
+ }
139
+ process.stdout.write(` ${C.voltBold}✓ [READY]${C.reset} ${C.white}Tunnel binary installed successfully!${C.reset}\n\n`);
140
+ return cachedPath;
141
+ }
142
+
143
+ const UI_WIDTH = 80;
144
+ const THIN_BAR = '─'.repeat(UI_WIDTH);
145
+ const THICK_BAR = '━'.repeat(UI_WIDTH);
146
+ const bar = THIN_BAR;
147
+ const thickBar = THICK_BAR;
148
+
149
+ const isLaunchFromBat = process.argv.includes('--launch');
150
+ const rawCliArgs = process.argv.slice(2).filter(a => a !== '--launch');
151
+ let activeProjectDir = rawCliArgs[0] ? path.resolve(rawCliArgs[0]) : null;
152
+ let mcpTunnelUrl = '';
153
+ let serverProcess = null;
154
+ let tunnelProcess = null;
155
+ let showLiveLogs = false;
156
+ let flashNotification = '';
157
+ let flashTimer = null;
158
+ let isNavigatingFolders = false;
159
+ let isEstablishingTunnel = false;
160
+ const recentLogs = [];
161
+
162
+ function setFlash(msg, durationMs = 3000) {
163
+ flashNotification = msg;
164
+ if (flashTimer) clearTimeout(flashTimer);
165
+ flashTimer = setTimeout(() => {
166
+ flashNotification = '';
167
+ if (!isNavigatingFolders && !isEstablishingTunnel) renderDashboard();
168
+ }, durationMs);
169
+ if (!isNavigatingFolders && !isEstablishingTunnel) renderDashboard();
170
+ }
171
+
172
+ function copyToClipboard(text) {
173
+ try {
174
+ if (process.platform === 'win32') {
175
+ const proc = spawn('clip');
176
+ proc.stdin.write(text);
177
+ proc.stdin.end();
178
+ return true;
179
+ }
180
+ } catch (e) {}
181
+ return false;
182
+ }
183
+
184
+ function freePort(port) {
185
+ try {
186
+ if (process.platform === 'win32') {
187
+ const psCmd = `Get-NetTCPConnection -LocalPort ${port} -ErrorAction SilentlyContinue | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }`;
188
+ execSync(`powershell -NoProfile -Command "${psCmd}"`, { stdio: 'ignore' });
189
+ execSync(`powershell -NoProfile -Command "Stop-Process -Name 'cloudflared' -Force -ErrorAction SilentlyContinue"`, { stdio: 'ignore' });
190
+ }
191
+ } catch (e) {}
192
+ }
193
+
194
+ function switchProjectDirectory(newPath) {
195
+ if (!newPath || !fs.existsSync(newPath)) {
196
+ setFlash(` ${C.redBold}● [ERROR]${C.reset} ${C.white}Invalid directory path.${C.reset}`);
197
+ return;
198
+ }
199
+
200
+ const resolved = fs.realpathSync(path.resolve(newPath));
201
+ activeProjectDir = resolved;
202
+
203
+ // Notify running server
204
+ const req = http.request({
205
+ hostname: '127.0.0.1',
206
+ port: 3000,
207
+ path: '/api/set-directory',
208
+ method: 'POST',
209
+ headers: { 'Content-Type': 'application/json' }
210
+ }, (res) => {
211
+ let data = '';
212
+ res.on('data', c => { data += c; });
213
+ res.on('end', () => {
214
+ setFlash(` ${C.voltBold}● [SWITCHED]${C.reset} ${C.white}Sandboxed project switched to: ${C.voltBold}${path.basename(resolved)}${C.reset}`);
215
+ });
216
+ });
217
+
218
+ req.on('error', () => {
219
+ setFlash(` ${C.voltBold}● [SWITCHED]${C.reset} ${C.white}Project folder switched: ${C.voltBold}${path.basename(resolved)}${C.reset}`);
220
+ });
221
+
222
+ req.write(JSON.stringify({ path: resolved }));
223
+ req.end();
224
+ }
225
+
226
+ function renderAsciiHeader(badgeText = '') {
227
+ console.log(`${C.voltBold}${THICK_BAR}${C.reset}`);
228
+ console.log(
229
+ ` ${C.voltBold}██████╗ ██████╗ ██╗██████╗ ██████╗ ███████╗${C.reset}` +
230
+ ` ${C.steel}╔══════╗${C.reset} ${C.cyan}╔══╗ ╔══╗ ${C.reset}`
231
+ );
232
+ console.log(
233
+ ` ${C.voltBold}██╔══██╗██╔══██╗██║██╔══██╗██╔════╝ ██╔════╝${C.reset}` +
234
+ ` ${C.steel}║ ${C.white}>_ ${C.voltBold}█${C.steel} ║${C.reset} ${C.cyan}╔═╝ ╚══╝ ╚═╗${C.reset}`
235
+ );
236
+ console.log(
237
+ ` ${C.voltBold}██████╔╝██████╔╝██║██║ ██║██║ ███╗█████╗ ${C.reset}` +
238
+ ` ${C.voltBold}╔╩══════╩═╗${C.reset} ${C.cyan}╔╝ ${C.voltBold}✦${C.cyanBold} LLM${C.cyan} ╚╗${C.reset}`
239
+ );
240
+ console.log(
241
+ ` ${C.voltBold}██╔══██╗██╔══██╗██║██║ ██║██║ ██║██╔══╝ ${C.reset}` +
242
+ ` ${C.voltBold}║ ╚════╬═════╬════╝ ║${C.reset}`
243
+ );
244
+ console.log(
245
+ ` ${C.voltBold}██████╔╝██║ ██║██║██████╔╝╚██████╔╝███████╗${C.reset}` +
246
+ ` ${C.voltBold}╚╗ ╔═══╩═════╩═══╗ ╔╝${C.reset}`
247
+ );
248
+ console.log(
249
+ ` ${C.voltBold}╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚══════╝${C.reset}` +
250
+ ` ${C.voltBold}╚════╝ ╚═════════╝ ${C.reset}`
251
+ );
252
+ console.log(`${C.voltBold}${THICK_BAR}${C.reset}`);
253
+
254
+ if (badgeText) {
255
+ console.log(` ${badgeText}`);
256
+ console.log(`${C.darkDivider}${THIN_BAR}${C.reset}`);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * =========================================================================
262
+ * CENTERED BRIDGE CROSSING ANIMATION (Athletic Sprinter Crossing Bridge)
263
+ * A high-energy runner sprints across the architectural span in < 2 seconds!
264
+ * =========================================================================
265
+ */
266
+ async function playInitialLoadingAnimation(durationMs = 1800) {
267
+ process.stdout.write('\x1b[?25l');
268
+ const startTime = Date.now();
269
+ let frame = 0;
270
+
271
+ const bridgeWidth = 66;
272
+ const sprinterSprites = [
273
+ [
274
+ " __o ✦",
275
+ " / /\\_ ",
276
+ " _\\__\\/_"
277
+ ],
278
+ [
279
+ " _o »",
280
+ " / /\\ ",
281
+ " < \\ >"
282
+ ],
283
+ [
284
+ " __o ✦",
285
+ " / /\\_ ",
286
+ " / /\\"
287
+ ],
288
+ [
289
+ " _o »",
290
+ " / /\\ ",
291
+ " / / \\"
292
+ ]
293
+ ];
294
+
295
+ const trails = [" = = >", " = = ", "= = > ", " = = "];
296
+ const startX = 6;
297
+ const endX = 52;
298
+
299
+ while (true) {
300
+ const elapsed = Date.now() - startTime;
301
+ const progress = Math.min(1.0, elapsed / durationMs);
302
+
303
+ const termCols = process.stdout.columns || 80;
304
+ const termRows = process.stdout.rows || 25;
305
+
306
+ const padLeft = ' '.repeat(Math.max(0, Math.floor((termCols - bridgeWidth) / 2)));
307
+ const topPad = '\n'.repeat(Math.max(1, Math.floor((termRows - 16) / 2) - 1));
308
+
309
+ const runner = sprinterSprites[frame % 4];
310
+ const runnerX = Math.floor(startX + progress * (endX - startX));
311
+
312
+ const out = [];
313
+ out.push(topPad);
314
+
315
+ // Centered Title
316
+ const title = `${C.voltBold}B R I D G E${C.reset}`;
317
+ const titlePad = ' '.repeat(Math.max(0, Math.floor((termCols - 15) / 2)));
318
+ out.push(`${titlePad}${title}\n`);
319
+
320
+ // Golden Gate Twin Vertical Steel Towers (Pure rectangular vertical towers - NO triangles, NO trees!)
321
+ out.push(`${padLeft}${C.slate} [LOCAL PC] [CLOUD AI] ${C.reset}`);
322
+ out.push(`${padLeft}${C.steel} ┌─┐ ┌─┐ ${C.reset}`);
323
+ out.push(`${padLeft}${C.steel} │ │ '. .' │ │ ${C.reset}`);
324
+ out.push(`${padLeft}${C.steel} ┌┴─┴┐ '. .' ┌┴─┴┐ ${C.reset}`);
325
+ out.push(`${padLeft}${C.steel} │ █ │ '. .' │ █ │ ${C.reset}`);
326
+ out.push(`${padLeft}${C.steel} └┬─┬┘ '--.........................--' └┬─┬┘ ${C.reset}`);
327
+
328
+ // 3 lines for runner deck level (vertical tower columns on sides, runner in middle)
329
+ for (let r = 0; r < 3; r++) {
330
+ let lineChars = Array(bridgeWidth).fill(' ');
331
+ lineChars[7] = '│';
332
+ lineChars[9] = '│';
333
+ lineChars[55] = '│';
334
+ lineChars[57] = '│';
335
+
336
+ // Trail effect behind runner
337
+ if (r === 1 && runnerX > 14) {
338
+ const trailStr = trails[frame % trails.length];
339
+ for (let t = 0; t < trailStr.length; t++) {
340
+ const pos = runnerX - 6 + t;
341
+ if (pos > 10 && pos < 54) {
342
+ lineChars[pos] = trailStr[t];
343
+ }
344
+ }
345
+ }
346
+
347
+ // Place runner sprite
348
+ const spriteLine = runner[r];
349
+ for (let c = 0; c < 8; c++) {
350
+ if (c < spriteLine.length) {
351
+ lineChars[runnerX + c] = spriteLine[c];
352
+ }
353
+ }
354
+
355
+ // Colorize
356
+ let formatted = '';
357
+ for (let i = 0; i < lineChars.length; i++) {
358
+ const ch = lineChars[i];
359
+ if (i >= runnerX && i < runnerX + 8 && ch !== ' ') {
360
+ if (ch === '✦' || ch === '»') {
361
+ formatted += C.cyanBold + ch + C.reset;
362
+ } else {
363
+ formatted += C.voltBold + ch + C.reset;
364
+ }
365
+ } else if (i < runnerX && (ch === '=' || ch === '>')) {
366
+ formatted += C.slate + ch + C.reset;
367
+ } else if (ch === '│' || ch === '┌' || ch === '┐' || ch === '└' || ch === '┘' || ch === '┴' || ch === '┬' || ch === '█') {
368
+ formatted += C.steel + ch + C.reset;
369
+ } else {
370
+ formatted += ch;
371
+ }
372
+ }
373
+ out.push(padLeft + formatted);
374
+ }
375
+
376
+ // Heavy Highway Deck with steel portal frames at tower bases
377
+ out.push(`${padLeft}${C.whiteBold}═════${C.voltBold}[═══]${C.whiteBold}═════════════════════════════════════════════${C.voltBold}[═══]${C.whiteBold}═════${C.reset}`);
378
+
379
+ // Foundation caissons beneath towers
380
+ out.push(`${padLeft}${C.steel} │ │ │ │ ${C.reset}`);
381
+ out.push(`${padLeft}${C.steel} [█████] ~ ~ ~ ~ ~ ~ [█████] ${C.reset}`);
382
+
383
+ // Clean water reflections
384
+ const waves = [
385
+ '≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈',
386
+ ' ≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈ '
387
+ ];
388
+ out.push(`${padLeft}${C.cyan}${waves[frame % 2]}${C.reset}\n`);
389
+
390
+ // Clean status & percentage
391
+ const pct = Math.min(100, Math.round(progress * 100));
392
+ const statusMsg = progress >= 1.0 ? 'BRIDGE CONNECTED!' : 'CROSSING THE BRIDGE...';
393
+ const subText = `${C.whiteBold}${statusMsg}${C.reset} ${C.voltBold}${pct}%${C.reset}`;
394
+ const subPad = ' '.repeat(Math.max(0, Math.floor((termCols - 28) / 2)));
395
+ out.push(`${subPad}${subText}`);
396
+
397
+ // Progress bar
398
+ const barLen = 30;
399
+ const filled = Math.min(barLen, Math.round(progress * barLen));
400
+ const empty = barLen - filled;
401
+ const barStr = C.voltBold + '█'.repeat(filled) + C.steel + '░'.repeat(empty) + C.reset;
402
+ const barPad = ' '.repeat(Math.max(0, Math.floor((termCols - (barLen + 2)) / 2)));
403
+ out.push(`${barPad}[${barStr}]`);
404
+
405
+ process.stdout.write('\x1b[2J\x1b[0f');
406
+ process.stdout.write(out.join('\n'));
407
+
408
+ if (progress >= 1.0) {
409
+ break;
410
+ }
411
+
412
+ frame++;
413
+ await new Promise(r => setTimeout(r, 55));
414
+ }
415
+
416
+ await new Promise(r => setTimeout(r, 150));
417
+ process.stdout.write('\x1b[?25h');
418
+ process.stdout.write('\x1b[2J\x1b[0f');
419
+ }
420
+
421
+ /**
422
+ * =========================================================================
423
+ * QUANTUM TUNNEL CREATION ANIMATION (Replaces Cloudflare tunnel wait time)
424
+ * Displays full ASCII header, traveling packet beam, and live progress bar
425
+ * =========================================================================
426
+ */
427
+ async function playTunnelCreationAnimation(getTunnelUrlFn, minDurationMs = 2500, maxDurationMs = 20000) {
428
+ process.stdout.write('\x1b[?25l');
429
+
430
+ const startTime = Date.now();
431
+ let frame = 0;
432
+
433
+ const packetTracks = [
434
+ ' [LOCAL PC] ═══▶═════════════════ ( ∞ ) ══════════════════════ [CLOUD AI]',
435
+ ' [LOCAL PC] ══════▶══════════════ ( ∞ ) ══════════════════════ [CLOUD AI]',
436
+ ' [LOCAL PC] ═════════▶═══════════ ( ∞ ) ══════════════════════ [CLOUD AI]',
437
+ ' [LOCAL PC] ════════════▶════════ ( ∞ ) ══════════════════════ [CLOUD AI]',
438
+ ' [LOCAL PC] ═══════════════▶═════ ( ∞ ) ══════════════════════ [CLOUD AI]',
439
+ ' [LOCAL PC] ══════════════════▶══ ( ∞ ) ══════════════════════ [CLOUD AI]',
440
+ ' [LOCAL PC] ═════════════════════ ( ✦ ) ═══▶══════════════════ [CLOUD AI]',
441
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ══════▶═══════════════ [CLOUD AI]',
442
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ═════════▶════════════ [CLOUD AI]',
443
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ════════════▶═════════ [CLOUD AI]',
444
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ═══════════════▶══════ [CLOUD AI] ✦',
445
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ══════════════════▶═══ [CLOUD AI] ✦',
446
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ═══════════════◀══════ [CLOUD AI]',
447
+ ' [LOCAL PC] ═════════════════════ ( ∞ ) ════════════◀═════════ [CLOUD AI]',
448
+ ' [LOCAL PC] ═════════════════════ ( ✦ ) ═══◀══════════════════ [CLOUD AI]',
449
+ ' [LOCAL PC] ══════════════════◀══ ( ∞ ) ══════════════════════ [CLOUD AI]',
450
+ ' [LOCAL PC] ═══════════════◀═════ ( ∞ ) ══════════════════════ [CLOUD AI]',
451
+ ' [LOCAL PC] ════════════◀════════ ( ∞ ) ══════════════════════ [CLOUD AI]',
452
+ ' [LOCAL PC] ═════════◀═══════════ ( ∞ ) ══════════════════════ [CLOUD AI]',
453
+ ' [LOCAL PC] ══════◀══════════════ ( ∞ ) ══════════════════════ [CLOUD AI]'
454
+ ];
455
+
456
+ const spinners = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
457
+ const stages = [
458
+ 'Mounting DeepSeek Harness & Local Project Sandbox...',
459
+ 'Connecting to Cloudflare Global Anycast Edge...',
460
+ 'Allocating Public HTTPS Quantum Tunnel for MCP...',
461
+ 'Finalizing Secure WebSocket & SSE Streaming...'
462
+ ];
463
+
464
+ while (true) {
465
+ const elapsed = Date.now() - startTime;
466
+ const url = getTunnelUrlFn();
467
+
468
+ // Finish when we have the URL and met minimum duration (or hit max timeout)
469
+ if ((url && elapsed >= minDurationMs) || elapsed >= maxDurationMs) {
470
+ break;
471
+ }
472
+
473
+ let progress = Math.min(0.92, (elapsed / (minDurationMs + 800)));
474
+ if (url) progress = 0.98;
475
+ const pct = Math.round(progress * 100);
476
+
477
+ const barLen = 46;
478
+ const filled = Math.round(progress * barLen);
479
+ const empty = barLen - filled;
480
+ const bar = C.voltBold + '█'.repeat(filled) + C.steel + '░'.repeat(empty) + C.reset;
481
+
482
+ const spinner = spinners[frame % spinners.length];
483
+ const track = packetTracks[frame % packetTracks.length];
484
+ const stageIdx = Math.min(stages.length - 1, Math.floor((frame / 6) % stages.length));
485
+ const stageText = stages[stageIdx];
486
+
487
+ process.stdout.write('\x1b[2J\x1b[0f');
488
+ renderAsciiHeader(`${C.bgVolt} ESTABLISHING TUNNEL ${C.reset}`);
489
+
490
+ console.log(` ${C.cyanBold}${track.trim()}${C.reset}`);
491
+ console.log(`${C.darkDivider}${THIN_BAR}${C.reset}`);
492
+ console.log(` ${C.voltBold}${spinner}${C.reset} ${C.whiteBold}CREATING CLOUDFLARE SECURE TUNNEL${C.reset} ${C.voltBold}${String(pct).padStart(3, ' ')}%${C.reset}`);
493
+ console.log(` [${bar}]`);
494
+ console.log(` ${C.slate}● ${stageText}${C.reset}`);
495
+ console.log(`${C.voltBold}${THICK_BAR}${C.reset}`);
496
+
497
+ frame++;
498
+ await new Promise(r => setTimeout(r, 70));
499
+ }
500
+
501
+ // Final confirmation frame
502
+ const finalUrl = getTunnelUrlFn() || 'https://trycloudflare.com';
503
+ process.stdout.write('\x1b[2J\x1b[0f');
504
+ renderAsciiHeader(`${C.bgVolt} TUNNEL ACTIVE ${C.reset}`);
505
+ console.log(` ${C.cyanBold} [LOCAL PC] ═════════════════════ ( ✦ ) ══════════════════════ [CLOUD AI] ✦${C.reset}`);
506
+ console.log(`${C.darkDivider}${THIN_BAR}${C.reset}`);
507
+ console.log(` ${C.voltBold}✓${C.reset} ${C.whiteBold}CLOUDFLARE TUNNEL CONNECTED${C.reset} ${C.voltBold}100%${C.reset}`);
508
+ console.log(` [${C.voltBold}${'█'.repeat(46)}${C.reset}]`);
509
+ console.log(` ${C.voltBold}● MCP URL: ${C.cyanBold}${finalUrl}/mcp${C.reset} ${C.slate}(Copied to Clipboard!)${C.reset}`);
510
+ console.log(`${C.voltBold}${THICK_BAR}${C.reset}`);
511
+
512
+ await new Promise(r => setTimeout(r, 400));
513
+
514
+ process.stdout.write('\x1b[?25h');
515
+ process.stdout.write('\x1b[2J\x1b[0f');
516
+ }
517
+
518
+ /**
519
+ * =========================================================================
520
+ * IN-CLI INTERACTIVE DIRECTORY NAVIGATOR
521
+ * Browse, explore, and pick folders purely inside the terminal window!
522
+ * =========================================================================
523
+ */
524
+ function selectDirectoryInteractive(startDir) {
525
+ return new Promise((resolve) => {
526
+ isNavigatingFolders = true;
527
+ let currentDir = startDir && fs.existsSync(startDir) ? path.resolve(startDir) : process.cwd();
528
+ let selectedIndex = 0;
529
+ let isTypingPath = false;
530
+ let typedPath = '';
531
+ let errorMessage = '';
532
+
533
+ function getItems() {
534
+ const items = [
535
+ { type: 'select_current', name: `[USE CURRENT FOLDER: ${path.basename(currentDir) || currentDir}]`, fullPath: currentDir }
536
+ ];
537
+
538
+ const parentDir = path.dirname(currentDir);
539
+ if (parentDir && parentDir !== currentDir) {
540
+ items.push({ type: 'parent', name: '.. (Parent Directory)', fullPath: parentDir });
541
+ }
542
+
543
+ try {
544
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
545
+ const dirs = entries
546
+ .filter(e => {
547
+ try {
548
+ return e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules';
549
+ } catch (err) {
550
+ return false;
551
+ }
552
+ })
553
+ .map(e => ({ type: 'dir', name: `${e.name}/`, fullPath: path.join(currentDir, e.name) }))
554
+ .sort((a, b) => a.name.localeCompare(b.name));
555
+
556
+ items.push(...dirs);
557
+ } catch (err) {
558
+ errorMessage = 'Access denied or unable to read directory.';
559
+ }
560
+
561
+ return items;
562
+ }
563
+
564
+ let items = getItems();
565
+
566
+ function renderNav() {
567
+ process.stdout.write('\x1b[2J\x1b[0f');
568
+ const w = UI_WIDTH;
569
+ const thinBar = '─'.repeat(w);
570
+ const thickBar = '━'.repeat(w);
571
+
572
+ // 1. First load Bridge ASCII Logo at top
573
+ renderAsciiHeader(`${C.bgVolt} DIRECTORY NAVIGATOR ${C.reset}`);
574
+
575
+ // 2. Down select the project
576
+ console.log(` ${C.slate}Current Folder:${C.reset} ${C.voltBold}${currentDir}${C.reset}`);
577
+ console.log(`${C.darkDivider}${thinBar}${C.reset}`);
578
+
579
+ if (errorMessage) {
580
+ console.log(` ${C.redBold}● [NOTE] ${errorMessage}${C.reset}`);
581
+ errorMessage = '';
582
+ console.log(`${C.darkDivider}${thinBar}${C.reset}`);
583
+ }
584
+
585
+ if (isTypingPath) {
586
+ console.log(`\n ${C.voltBold}Type or Paste Directory Path:${C.reset}`);
587
+ console.log(` > ${C.whiteBold}${typedPath}${C.reset}_\n`);
588
+ console.log(` ${C.slate}[Enter] Confirm | [Esc] Back to Directory Browser${C.reset}`);
589
+ console.log(`${C.voltBold}${thickBar}${C.reset}`);
590
+ return;
591
+ }
592
+
593
+ // Scrolling window of items
594
+ const maxVisible = 10;
595
+ let startIdx = 0;
596
+ if (selectedIndex >= maxVisible) {
597
+ startIdx = selectedIndex - maxVisible + 1;
598
+ }
599
+ const visibleItems = items.slice(startIdx, startIdx + maxVisible);
600
+
601
+ visibleItems.forEach((item, relIdx) => {
602
+ const actualIdx = startIdx + relIdx;
603
+ const isSelected = actualIdx === selectedIndex;
604
+ if (isSelected) {
605
+ console.log(` ${C.bgVolt} ► ${item.name.padEnd(70)} ${C.reset}`);
606
+ } else {
607
+ const color = item.type === 'select_current' ? C.voltBold : (item.type === 'parent' ? C.slate : C.white);
608
+ console.log(` ${color}${item.name}${C.reset}`);
609
+ }
610
+ });
611
+
612
+ console.log(`${C.darkDivider}${thinBar}${C.reset}`);
613
+ console.log(` ${C.voltBold}[↑/↓]${C.reset} ${C.white}Navigate${C.reset} ${C.voltBold}[Enter]${C.reset} ${C.white}Open Folder${C.reset} ${C.voltBold}[Space]${C.reset} ${C.white}Select This Folder${C.reset}`);
614
+ console.log(` ${C.voltBold}[T]${C.reset} ${C.white}Type Path${C.reset} ${C.voltBold}[Backspace]${C.reset} ${C.white}Up${C.reset} ${C.voltBold}[Esc]${C.reset} ${C.white}Cancel${C.reset}`);
615
+ console.log(`${C.voltBold}${thickBar}${C.reset}`);
616
+ }
617
+
618
+ renderNav();
619
+
620
+ function onNavKey(str, key) {
621
+ try {
622
+ if (!key) return;
623
+
624
+ if (isTypingPath) {
625
+ if (key.name === 'return') {
626
+ isTypingPath = false;
627
+ if (typedPath && fs.existsSync(typedPath) && fs.statSync(typedPath).isDirectory()) {
628
+ cleanup();
629
+ resolve(fs.realpathSync(path.resolve(typedPath)));
630
+ return;
631
+ } else {
632
+ errorMessage = `Directory "${typedPath}" does not exist.`;
633
+ typedPath = '';
634
+ renderNav();
635
+ return;
636
+ }
637
+ } else if (key.name === 'escape') {
638
+ isTypingPath = false;
639
+ typedPath = '';
640
+ renderNav();
641
+ return;
642
+ } else if (key.name === 'backspace') {
643
+ typedPath = typedPath.slice(0, -1);
644
+ renderNav();
645
+ return;
646
+ } else if (str && !key.ctrl && !key.meta) {
647
+ typedPath += str;
648
+ renderNav();
649
+ return;
650
+ }
651
+ return;
652
+ }
653
+
654
+ if (key.name === 'up') {
655
+ if (items.length > 0) {
656
+ selectedIndex = (selectedIndex - 1 + items.length) % items.length;
657
+ renderNav();
658
+ }
659
+ } else if (key.name === 'down') {
660
+ if (items.length > 0) {
661
+ selectedIndex = (selectedIndex + 1) % items.length;
662
+ renderNav();
663
+ }
664
+ } else if (key.name === 'return') {
665
+ if (items.length === 0) return;
666
+ const item = items[selectedIndex];
667
+ if (!item) return;
668
+ if (item.type === 'select_current') {
669
+ cleanup();
670
+ resolve(item.fullPath);
671
+ return;
672
+ } else if (item.type === 'parent' || item.type === 'dir') {
673
+ currentDir = item.fullPath;
674
+ items = getItems();
675
+ selectedIndex = 0;
676
+ renderNav();
677
+ }
678
+ } else if (key.name === 'space' || key.name === 's') {
679
+ cleanup();
680
+ resolve(currentDir);
681
+ return;
682
+ } else if (key.name === 'backspace' || key.name === 'left') {
683
+ const parentDir = path.dirname(currentDir);
684
+ if (parentDir && parentDir !== currentDir) {
685
+ currentDir = parentDir;
686
+ items = getItems();
687
+ selectedIndex = 0;
688
+ renderNav();
689
+ }
690
+ } else if (key.name === 't') {
691
+ isTypingPath = true;
692
+ typedPath = '';
693
+ renderNav();
694
+ } else if (key.name === 'escape' || (key.ctrl && key.name === 'c')) {
695
+ cleanup();
696
+ resolve(null);
697
+ }
698
+ } catch (e) {
699
+ errorMessage = e.message;
700
+ renderNav();
701
+ }
702
+ }
703
+
704
+ function cleanup() {
705
+ process.stdin.removeListener('keypress', onNavKey);
706
+ isNavigatingFolders = false;
707
+ }
708
+
709
+ process.stdin.on('keypress', onNavKey);
710
+ });
711
+ }
712
+
713
+ function renderDashboard() {
714
+ if (isNavigatingFolders || isEstablishingTunnel) return;
715
+
716
+ // Clear terminal
717
+ process.stdout.write('\x1b[2J\x1b[0f');
718
+
719
+ const width = 72;
720
+ const bar = '─'.repeat(width);
721
+
722
+ // 1. Full Bridge ASCII Emblem at top
723
+ renderAsciiHeader(`${C.voltBold}● STATUS: ONLINE${C.reset}`);
724
+
725
+ // 2. Complete Live Screen Details
726
+ console.log(` ${C.bgVolt} PROJECT ${C.reset} ${C.whiteBold}${activeProjectDir || '(None selected)'}${C.reset}`);
727
+ console.log(` ${C.bgVolt} JAILED ${C.reset} ${C.voltBold}STRICTLY ENFORCED${C.reset} ${C.slate}(Zero access outside folder)${C.reset}`);
728
+
729
+ if (mcpTunnelUrl) {
730
+ console.log(` ${C.bgVolt} MCP URL ${C.reset} ${C.cyanBold}${mcpTunnelUrl}/mcp${C.reset}`);
731
+ } else {
732
+ console.log(` ${C.bgVolt} MCP URL ${C.reset} ${C.slate}Establishing secure tunnel...${C.reset}`);
733
+ }
734
+
735
+ console.log(`${C.darkDivider}${bar}${C.reset}`);
736
+
737
+ if (flashNotification) {
738
+ console.log(` ${flashNotification}`);
739
+ console.log(`${C.darkDivider}${bar}${C.reset}`);
740
+ }
741
+
742
+ // Keyboard Shortcuts
743
+ console.log(` ${C.voltBold}KEYBOARD ACTIONS:${C.reset}`);
744
+ console.log(` ${C.voltBold}[C]${C.reset} ${C.white}Copy MCP URL${C.reset} ${C.voltBold}[D]${C.reset} ${C.white}Browse & Switch Project Folder${C.reset}`);
745
+ console.log(` ${C.voltBold}[L]${C.reset} ${C.white}Live Activity Logs (${showLiveLogs ? C.voltBold + 'ON' : C.slate + 'OFF'}${C.white})${C.reset} ${C.voltBold}[Q]${C.reset} ${C.white}Stop Server & Exit${C.reset}`);
746
+
747
+ console.log(`${C.voltBold}${thickBar}${C.reset}`);
748
+
749
+ if (showLiveLogs) {
750
+ console.log(` ${C.voltBold}LIVE HARNESS TRAFFIC & ACTIVITY LOGS:${C.reset}`);
751
+ const logsToShow = recentLogs.slice(-6);
752
+ if (logsToShow.length === 0) {
753
+ console.log(` ${C.slate}(Waiting for AI requests from Gemini, Claude, or ChatGPT...)${C.reset}`);
754
+ } else {
755
+ logsToShow.forEach(log => console.log(` ${log}`));
756
+ }
757
+ console.log(`${C.darkDivider}${bar}${C.reset}`);
758
+ } else {
759
+ console.log(` ${C.slate}Supported:${C.reset} ${C.white}Google Gemini${C.reset} ${C.darkDivider}•${C.reset} ${C.white}Claude Web / Desktop${C.reset} ${C.darkDivider}•${C.reset} ${C.white}ChatGPT Custom Tools${C.reset}`);
760
+ }
761
+ }
762
+
763
+ async function startBridge() {
764
+ // Ensure readline keypress setup
765
+ readline.emitKeypressEvents(process.stdin);
766
+ if (process.stdin.isTTY) {
767
+ process.stdin.setRawMode(true);
768
+ }
769
+
770
+ // Step 1: Initial Centered Bridge Crossing Animation (when launching via .bat)
771
+ if (isLaunchFromBat) {
772
+ await playInitialLoadingAnimation(1800);
773
+ }
774
+
775
+ // Step 2: In-CLI Directory Navigator (if no folder was passed)
776
+ if (!activeProjectDir || !fs.existsSync(activeProjectDir)) {
777
+ const picked = await selectDirectoryInteractive(process.cwd());
778
+ if (picked && fs.existsSync(picked)) {
779
+ activeProjectDir = fs.realpathSync(path.resolve(picked));
780
+ } else {
781
+ activeProjectDir = fs.realpathSync(process.cwd());
782
+ setFlash(` ${C.voltBold}● [DEFAULT]${C.reset} ${C.white}Using current folder. Press ${C.voltBold}[D]${C.white} anytime to browse.${C.reset}`, 5000);
783
+ }
784
+ }
785
+
786
+ // Step 3: Free Port 3000
787
+ freePort(3000);
788
+
789
+ // Step 4: Start MCP Server in background
790
+ serverProcess = spawn('node', [serverScript, activeProjectDir, '--http', '3000'], {
791
+ stdio: ['ignore', 'pipe', 'pipe'],
792
+ windowsHide: true
793
+ });
794
+
795
+ serverProcess.stderr.on('data', (chunk) => {
796
+ const text = chunk.toString();
797
+ const lines = text.split('\n').filter(l => l.trim());
798
+ lines.forEach(l => {
799
+ recentLogs.push(`${C.slate}[${new Date().toLocaleTimeString()}]${C.reset} ${l}`);
800
+ if (recentLogs.length > 50) recentLogs.shift();
801
+ });
802
+ if (showLiveLogs && !isNavigatingFolders && !isEstablishingTunnel) renderDashboard();
803
+ });
804
+
805
+ // Step 5: Start Cloudflare Tunnel
806
+ isEstablishingTunnel = true;
807
+ const activeCloudflaredBin = await ensureCloudflaredBinary();
808
+ tunnelProcess = spawn(activeCloudflaredBin, ['tunnel', '--url', 'http://localhost:3000'], {
809
+ stdio: ['ignore', 'pipe', 'pipe'],
810
+ windowsHide: true
811
+ });
812
+
813
+ const extractUrl = (text) => {
814
+ const match = text.match(/https:\/\/[a-zA-Z0-9-]+\.trycloudflare\.com/);
815
+ if (match && !mcpTunnelUrl) {
816
+ mcpTunnelUrl = match[0];
817
+ const fullUrl = `${mcpTunnelUrl}/mcp`;
818
+ copyToClipboard(fullUrl);
819
+ setFlash(` ${C.voltBold}● [COPIED]${C.reset} ${C.white}MCP URL loaded into your clipboard! (Ctrl + V to paste)${C.reset}`);
820
+ if (!isNavigatingFolders && !isEstablishingTunnel) renderDashboard();
821
+ }
822
+ };
823
+
824
+ tunnelProcess.stdout.on('data', chunk => extractUrl(chunk.toString()));
825
+ tunnelProcess.stderr.on('data', chunk => extractUrl(chunk.toString()));
826
+
827
+ // Step 6: Full Quantum Tunnel Creation Animation (directly replaces the tunnel creation wait time!)
828
+ await playTunnelCreationAnimation(() => mcpTunnelUrl, 2500, 20000);
829
+ isEstablishingTunnel = false;
830
+
831
+ // Step 7: Smooth Load of Live Dashboard
832
+ renderDashboard();
833
+
834
+ // Step 8: Dashboard Keypress Listener
835
+ process.stdin.on('keypress', async (str, key) => {
836
+ try {
837
+ if (isNavigatingFolders || isEstablishingTunnel || !key) return;
838
+
839
+ const keyName = (key.name || str || '').toLowerCase();
840
+
841
+ if ((key.ctrl && key.name === 'c') || keyName === 'q') {
842
+ cleanupAndExit();
843
+ return;
844
+ }
845
+
846
+ if (keyName === 'c') {
847
+ if (mcpTunnelUrl) {
848
+ copyToClipboard(`${mcpTunnelUrl}/mcp`);
849
+ setFlash(` ${C.voltBold}● [COPIED]${C.reset} ${C.white}MCP URL copied to clipboard: ${C.cyanBold}${mcpTunnelUrl}/mcp${C.reset}`);
850
+ } else {
851
+ setFlash(` ${C.slate}● [WAIT]${C.reset} ${C.white}Tunnel is still establishing... please wait.${C.reset}`);
852
+ }
853
+ } else if (keyName === 'd') {
854
+ // Launch In-CLI Directory Navigator
855
+ const picked = await selectDirectoryInteractive(activeProjectDir);
856
+ if (picked) {
857
+ switchProjectDirectory(picked);
858
+ }
859
+ renderDashboard();
860
+ } else if (keyName === 'l') {
861
+ showLiveLogs = !showLiveLogs;
862
+ renderDashboard();
863
+ }
864
+ } catch (err) {
865
+ // Prevent any crash from closing the CLI
866
+ setFlash(` ${C.redBold}● [NOTE]${C.reset} ${C.white}${err.message}${C.reset}`);
867
+ }
868
+ });
869
+
870
+ renderDashboard();
871
+ }
872
+
873
+ function cleanupAndExit() {
874
+ process.stdout.write('\n\n' + C.voltBold + 'Stopping Bridge and releasing ports...' + C.reset + '\n');
875
+ if (serverProcess) {
876
+ try { serverProcess.kill(); } catch (e) {}
877
+ }
878
+ if (tunnelProcess) {
879
+ try { tunnelProcess.kill(); } catch (e) {}
880
+ }
881
+ freePort(3000);
882
+ console.log(C.voltBold + '● [STOPPED] Bridge stopped cleanly. Goodbye!\n' + C.reset);
883
+ process.exit(0);
884
+ }
885
+
886
+ process.on('SIGINT', cleanupAndExit);
887
+ process.on('SIGTERM', cleanupAndExit);
888
+
889
+ process.on('uncaughtException', (err) => {
890
+ console.error('\n' + C.redBold + '● [UNCAUGHT ERROR] ' + C.reset + err.message + '\n' + (err.stack || ''));
891
+ });
892
+
893
+ process.on('unhandledRejection', (reason) => {
894
+ console.error('\n' + C.redBold + '● [UNHANDLED REJECTION] ' + C.reset + reason);
895
+ });
896
+
897
+ startBridge();