@seflless/ghosttown 1.3.0 → 1.3.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/src/cli.js ADDED
@@ -0,0 +1,944 @@
1
+ /**
2
+ * ghosttown CLI - Web-based terminal emulator
3
+ *
4
+ * Starts a local HTTP server with WebSocket PTY support,
5
+ * or runs a command in a new tmux session.
6
+ *
7
+ * Usage:
8
+ * ghosttown [options] [command]
9
+ *
10
+ * Options:
11
+ * -p, --port <port> Port to listen on (default: 8080, or PORT env var)
12
+ * -h, --help Show this help message
13
+ *
14
+ * Examples:
15
+ * ghosttown Start the web terminal server
16
+ * ghosttown -p 3000 Start the server on port 3000
17
+ * ghosttown vim Run vim in a new tmux session
18
+ * ghosttown "npm run dev" Run npm in a new tmux session
19
+ */
20
+
21
+ import { execSync, spawn } from 'child_process';
22
+ import fs from 'fs';
23
+ import http from 'http';
24
+ import { homedir, networkInterfaces } from 'os';
25
+ import path from 'path';
26
+ import { fileURLToPath } from 'url';
27
+
28
+ // Node-pty for cross-platform PTY support
29
+ import pty from '@lydell/node-pty';
30
+ // WebSocket server
31
+ import { WebSocketServer } from 'ws';
32
+ // ASCII art generator
33
+ import { asciiArt } from '../bin/ascii.js';
34
+
35
+ const __filename = fileURLToPath(import.meta.url);
36
+ const __dirname = path.dirname(__filename);
37
+
38
+ // ============================================================================
39
+ // Tmux Session Management
40
+ // ============================================================================
41
+
42
+ /**
43
+ * Check if tmux is installed
44
+ */
45
+ function checkTmuxInstalled() {
46
+ try {
47
+ execSync('which tmux', { stdio: 'pipe' });
48
+ return true;
49
+ } catch (err) {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Print tmux installation instructions and exit
56
+ */
57
+ function printTmuxInstallHelp() {
58
+ console.error('\x1b[31mError: tmux is not installed.\x1b[0m\n');
59
+ console.error('tmux is required to run commands in ghosttown sessions.\n');
60
+ console.error('To install tmux:\n');
61
+
62
+ if (process.platform === 'darwin') {
63
+ console.error(' \x1b[36mmacOS (Homebrew):\x1b[0m brew install tmux');
64
+ console.error(' \x1b[36mmacOS (MacPorts):\x1b[0m sudo port install tmux');
65
+ } else if (process.platform === 'linux') {
66
+ console.error(' \x1b[36mDebian/Ubuntu:\x1b[0m sudo apt install tmux');
67
+ console.error(' \x1b[36mFedora:\x1b[0m sudo dnf install tmux');
68
+ console.error(' \x1b[36mArch:\x1b[0m sudo pacman -S tmux');
69
+ } else {
70
+ console.error(' Please install tmux using your system package manager.');
71
+ }
72
+
73
+ console.error('');
74
+ process.exit(1);
75
+ }
76
+
77
+ /**
78
+ * Get the next available ghosttown session ID
79
+ * Scans existing tmux sessions named ghosttown-<N> and returns max(N) + 1
80
+ */
81
+ function getNextSessionId() {
82
+ try {
83
+ // List all tmux sessions
84
+ const output = execSync('tmux list-sessions -F "#{session_name}"', {
85
+ encoding: 'utf8',
86
+ stdio: ['pipe', 'pipe', 'pipe'],
87
+ });
88
+
89
+ // Find all ghosttown-<N> sessions and extract IDs
90
+ const sessionIds = output
91
+ .split('\n')
92
+ .filter((name) => name.startsWith('ghosttown-'))
93
+ .map((name) => {
94
+ const id = Number.parseInt(name.replace('ghosttown-', ''), 10);
95
+ return Number.isNaN(id) ? 0 : id;
96
+ });
97
+
98
+ // Return max + 1, or 1 if no sessions exist
99
+ return sessionIds.length > 0 ? Math.max(...sessionIds) + 1 : 1;
100
+ } catch (err) {
101
+ // tmux not running or no sessions - start with 1
102
+ return 1;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * List all ghosttown tmux sessions
108
+ */
109
+ function listSessions() {
110
+ // Check if tmux is installed
111
+ if (!checkTmuxInstalled()) {
112
+ printTmuxInstallHelp();
113
+ }
114
+
115
+ try {
116
+ // Get detailed session information
117
+ const output = execSync(
118
+ 'tmux list-sessions -F "#{session_name}|#{session_created}|#{session_attached}|#{session_windows}"',
119
+ {
120
+ encoding: 'utf8',
121
+ stdio: ['pipe', 'pipe', 'pipe'],
122
+ }
123
+ );
124
+
125
+ const sessions = output
126
+ .split('\n')
127
+ .filter((line) => line.startsWith('ghosttown-'))
128
+ .map((line) => {
129
+ const [name, created, attached, windows] = line.split('|');
130
+ return {
131
+ name,
132
+ created: new Date(Number.parseInt(created, 10) * 1000),
133
+ attached: attached === '1',
134
+ windows: Number.parseInt(windows, 10),
135
+ };
136
+ });
137
+
138
+ if (sessions.length === 0) {
139
+ console.log('No ghosttown sessions running.');
140
+ console.log('\nTo create a session, run:');
141
+ console.log(' ghosttown <command>');
142
+ console.log('\nExample:');
143
+ console.log(' ghosttown vim');
144
+ process.exit(0);
145
+ }
146
+
147
+ // Print header
148
+ console.log('\n\x1b[1mGhosttown Sessions\x1b[0m\n');
149
+ console.log(
150
+ `\x1b[36m${'Name'.padEnd(15)} ${'Created'.padEnd(22)} ${'Status'.padEnd(10)} Windows\x1b[0m`
151
+ );
152
+ console.log('-'.repeat(65));
153
+
154
+ // Print sessions
155
+ for (const session of sessions) {
156
+ const createdStr = session.created.toLocaleString();
157
+ // Status has ANSI codes so we need to pad the visible text differently
158
+ const statusPadded = session.attached
159
+ ? `\x1b[32m${'attached'.padEnd(10)}\x1b[0m`
160
+ : `\x1b[33m${'detached'.padEnd(10)}\x1b[0m`;
161
+ console.log(
162
+ `${session.name.padEnd(15)} ${createdStr.padEnd(22)} ${statusPadded} ${session.windows}`
163
+ );
164
+ }
165
+
166
+ console.log('');
167
+ console.log(`Total: ${sessions.length} session(s)`);
168
+ console.log('');
169
+ } catch (err) {
170
+ // tmux not running or no sessions
171
+ console.log('No ghosttown sessions running.');
172
+ console.log('\nTo create a session, run:');
173
+ console.log(' ghosttown <command>');
174
+ console.log('\nExample:');
175
+ console.log(' ghosttown vim');
176
+ }
177
+
178
+ process.exit(0);
179
+ }
180
+
181
+ /**
182
+ * Create a new tmux session and run the command
183
+ */
184
+ function createTmuxSession(command) {
185
+ // Check if tmux is installed
186
+ if (!checkTmuxInstalled()) {
187
+ printTmuxInstallHelp();
188
+ }
189
+
190
+ const sessionId = getNextSessionId();
191
+ const sessionName = `ghosttown-${sessionId}`;
192
+
193
+ try {
194
+ // Create tmux session and attach directly (not detached)
195
+ // Use -x and -y to set initial size, avoiding "terminal too small" issues
196
+ // The command runs in the session, and we attach immediately
197
+ const attach = spawn(
198
+ 'tmux',
199
+ [
200
+ 'new-session',
201
+ '-s',
202
+ sessionName,
203
+ '-x',
204
+ '200',
205
+ '-y',
206
+ '50',
207
+ // Set status off (no HUD), run the command, then start a shell
208
+ // so the session stays open and interactive after command completes
209
+ 'tmux set-option status off; ' + command + '; exec $SHELL',
210
+ ],
211
+ {
212
+ stdio: 'inherit',
213
+ }
214
+ );
215
+
216
+ attach.on('exit', (code) => {
217
+ process.exit(code || 0);
218
+ });
219
+ } catch (err) {
220
+ console.error(`Error creating tmux session: ${err.message}`);
221
+ process.exit(1);
222
+ }
223
+ }
224
+
225
+ // ============================================================================
226
+ // Parse CLI arguments
227
+ // ============================================================================
228
+
229
+ function parseArgs(argv) {
230
+ const args = argv.slice(2);
231
+ let port = null;
232
+ let command = null;
233
+
234
+ for (let i = 0; i < args.length; i++) {
235
+ const arg = args[i];
236
+
237
+ if (arg === '-h' || arg === '--help') {
238
+ console.log(`
239
+ Usage: ghosttown [options] [command]
240
+
241
+ Options:
242
+ -p, --port <port> Port to listen on (default: 8080, or PORT env var)
243
+ -h, --help Show this help message
244
+
245
+ Commands:
246
+ list List all ghosttown tmux sessions
247
+ <command> Run command in a new tmux session (ghosttown-<id>)
248
+
249
+ Examples:
250
+ ghosttown Start the web terminal server
251
+ ghosttown -p 3000 Start the server on port 3000
252
+ ghosttown list List all ghosttown sessions
253
+ ghosttown vim Run vim in a new tmux session
254
+ ghosttown "npm run dev" Run npm in a new tmux session
255
+
256
+ Aliases:
257
+ This CLI can also be invoked as 'gt' or 'ght'.
258
+ `);
259
+ process.exit(0);
260
+ }
261
+
262
+ // Handle list command
263
+ if (arg === 'list') {
264
+ listSessions();
265
+ // listSessions exits, so this won't be reached
266
+ }
267
+
268
+ if (arg === '-p' || arg === '--port') {
269
+ const nextArg = args[i + 1];
270
+ if (!nextArg || nextArg.startsWith('-')) {
271
+ console.error(`Error: ${arg} requires a port number`);
272
+ process.exit(1);
273
+ }
274
+ port = Number.parseInt(nextArg, 10);
275
+ if (Number.isNaN(port) || port < 1 || port > 65535) {
276
+ console.error(`Error: Invalid port number: ${nextArg}`);
277
+ process.exit(1);
278
+ }
279
+ i++; // Skip the next argument since we consumed it
280
+ continue;
281
+ }
282
+
283
+ // First non-flag argument starts the command
284
+ // Capture it and all remaining arguments as the command
285
+ if (!arg.startsWith('-')) {
286
+ command = args.slice(i).join(' ');
287
+ break;
288
+ }
289
+ }
290
+
291
+ return { port, command };
292
+ }
293
+
294
+ // ============================================================================
295
+ // Web Server
296
+ // ============================================================================
297
+
298
+ function startWebServer(cliArgs) {
299
+ const HTTP_PORT = cliArgs.port || process.env.PORT || 8080;
300
+
301
+ // ============================================================================
302
+ // Locate ghosttown assets
303
+ // ============================================================================
304
+
305
+ function findAssets() {
306
+ // Assets are in the package root (one level up from src/)
307
+ const packageRoot = path.join(__dirname, '..');
308
+ const distPath = path.join(packageRoot, 'dist');
309
+ const wasmPath = path.join(packageRoot, 'ghostty-vt.wasm');
310
+
311
+ if (!fs.existsSync(path.join(distPath, 'ghostty-web.js'))) {
312
+ console.error('Error: dist/ghostty-web.js not found.');
313
+ console.error('The package may not have been built correctly.');
314
+ process.exit(1);
315
+ }
316
+
317
+ if (!fs.existsSync(wasmPath)) {
318
+ console.error('Error: ghostty-vt.wasm not found.');
319
+ console.error('The package may not have been built correctly.');
320
+ process.exit(1);
321
+ }
322
+
323
+ return { distPath, wasmPath };
324
+ }
325
+
326
+ const { distPath, wasmPath } = findAssets();
327
+
328
+ // ============================================================================
329
+ // HTML Template
330
+ // ============================================================================
331
+
332
+ const HTML_TEMPLATE = `<!doctype html>
333
+ <html lang="en">
334
+ <head>
335
+ <meta charset="UTF-8" />
336
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
337
+ <title>ghosttown</title>
338
+ <style>
339
+ :root {
340
+ --vvh: 100vh;
341
+ --vv-offset-top: 0px;
342
+ }
343
+
344
+ * {
345
+ margin: 0;
346
+ padding: 0;
347
+ box-sizing: border-box;
348
+ }
349
+
350
+ html, body {
351
+ margin: 0;
352
+ padding: 0;
353
+ height: var(--vvh);
354
+ overflow: hidden;
355
+ overscroll-behavior: none;
356
+ touch-action: none;
357
+ transition: none;
358
+ }
359
+
360
+ body {
361
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
362
+ background: #292c34;
363
+ padding: 8px 8px 14px 8px;
364
+ box-sizing: border-box;
365
+ position: fixed;
366
+ inset: 0;
367
+ height: var(--vvh);
368
+ }
369
+
370
+ .terminal-window {
371
+ width: 100%;
372
+ height: 100%;
373
+ background: #ededed;
374
+ display: flex;
375
+ flex-direction: column;
376
+ overflow: hidden;
377
+ box-shadow:
378
+ 0 0 0 0.5px #65686e,
379
+ 0 0 0 1px #74777c,
380
+ 0 0 0 1.5px #020203,
381
+ 0px 4px 10px 0px rgba(0, 0, 0, 0.5);
382
+ border-radius: 8px;
383
+ box-sizing: border-box;
384
+ transform: translateY(calc(var(--vv-offset-top) * -1));
385
+ transition: none;
386
+ }
387
+
388
+ .title-bar {
389
+ background: #292c34;
390
+ padding: 8px 16px 6px 10px;
391
+ display: flex;
392
+ align-items: center;
393
+ gap: 12px;
394
+ }
395
+
396
+ .traffic-lights {
397
+ display: flex;
398
+ gap: 8px;
399
+ }
400
+
401
+ .light {
402
+ width: 12px;
403
+ height: 12px;
404
+ border-radius: 50%;
405
+ }
406
+
407
+ .light.red { background: #ff5f56; }
408
+ .light.yellow { background: #ffbd2e; }
409
+ .light.green { background: #27c93f; }
410
+
411
+ .title {
412
+ color: #e5e5e5;
413
+ font-size: 13px;
414
+ font-weight: 500;
415
+ letter-spacing: 0.3px;
416
+ display: flex;
417
+ align-items: center;
418
+ gap: 8px;
419
+ }
420
+
421
+ .title-separator { color: #666; }
422
+ .current-directory {
423
+ color: #888;
424
+ font-size: 12px;
425
+ font-weight: 400;
426
+ max-width: 400px;
427
+ overflow: hidden;
428
+ text-overflow: ellipsis;
429
+ white-space: nowrap;
430
+ }
431
+
432
+ .connection-status {
433
+ margin-left: auto;
434
+ font-size: 11px;
435
+ color: #888;
436
+ display: flex;
437
+ align-items: center;
438
+ gap: 6px;
439
+ }
440
+
441
+ .connection-dot {
442
+ width: 6px;
443
+ height: 6px;
444
+ border-radius: 50%;
445
+ background: #666;
446
+ }
447
+
448
+ .connection-dot.connected { background: #27c93f; }
449
+
450
+ #terminal-container {
451
+ flex: 1;
452
+ padding: 2px 0 2px 2px;
453
+ background: #292c34;
454
+ position: relative;
455
+ overflow: hidden;
456
+ min-height: 0;
457
+ touch-action: none;
458
+ }
459
+
460
+ #terminal-container canvas {
461
+ display: block;
462
+ touch-action: none;
463
+ }
464
+ </style>
465
+ </head>
466
+ <body>
467
+ <div class="terminal-window">
468
+ <div class="title-bar">
469
+ <div class="traffic-lights">
470
+ <span class="light red"></span>
471
+ <span class="light yellow"></span>
472
+ <span class="light green"></span>
473
+ </div>
474
+ <div class="title">
475
+ <span>ghosttown</span>
476
+ <span class="title-separator" id="title-separator" style="display: none">•</span>
477
+ <span class="current-directory" id="current-directory"></span>
478
+ </div>
479
+ <div class="connection-status">
480
+ <span class="connection-dot" id="connection-dot"></span>
481
+ <span id="connection-text">Disconnected</span>
482
+ </div>
483
+ </div>
484
+ <div id="terminal-container"></div>
485
+ </div>
486
+
487
+ <script type="module">
488
+ import { init, Terminal, FitAddon } from '/dist/ghostty-web.js';
489
+
490
+ let term;
491
+ let ws;
492
+ let fitAddon;
493
+
494
+ async function initTerminal() {
495
+ await init();
496
+
497
+ term = new Terminal({
498
+ cursorBlink: true,
499
+ fontSize: 12,
500
+ fontFamily: 'Monaco, Menlo, "Courier New", monospace',
501
+ theme: {
502
+ background: '#292c34',
503
+ foreground: '#d4d4d4',
504
+ },
505
+ smoothScrollDuration: 0,
506
+ scrollback: 10000,
507
+ scrollbarVisible: false,
508
+ });
509
+
510
+ fitAddon = new FitAddon();
511
+ term.loadAddon(fitAddon);
512
+
513
+ term.open(document.getElementById('terminal-container'));
514
+ fitAddon.fit();
515
+ fitAddon.observeResize();
516
+
517
+ // Desktop: auto-focus. Mobile: focus only on tap.
518
+ const isCoarsePointer = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
519
+ if (!isCoarsePointer) {
520
+ term.focus();
521
+ }
522
+
523
+ // Prevent page scroll on iOS
524
+ document.addEventListener('touchmove', (e) => {
525
+ const container = document.getElementById('terminal-container');
526
+ if (container && !container.contains(e.target)) {
527
+ e.preventDefault();
528
+ }
529
+ }, { passive: false });
530
+
531
+ // Mobile keyboard handling via visualViewport
532
+ {
533
+ const root = document.documentElement;
534
+ let watchRafId = null;
535
+ let vvhCurrent = 0;
536
+ let vvhTarget = 0;
537
+ let offsetCurrent = 0;
538
+ let offsetTarget = 0;
539
+ let lastTick = 0;
540
+
541
+ const readViewport = () => ({
542
+ height: window.visualViewport?.height ?? window.innerHeight,
543
+ offsetTop: window.visualViewport?.offsetTop ?? 0,
544
+ });
545
+
546
+ const applyVars = () => {
547
+ root.style.setProperty('--vvh', vvhCurrent + 'px');
548
+ root.style.setProperty('--vv-offset-top', offsetCurrent + 'px');
549
+ };
550
+
551
+ const startKeyboardWatch = () => {
552
+ if (watchRafId !== null) return;
553
+ lastTick = performance.now();
554
+
555
+ const tick = () => {
556
+ const now = performance.now();
557
+ const dtMs = Math.max(1, now - lastTick);
558
+ lastTick = now;
559
+
560
+ const { height, offsetTop } = readViewport();
561
+ vvhTarget = height;
562
+ offsetTarget = offsetTop;
563
+
564
+ if (vvhCurrent === 0) vvhCurrent = vvhTarget;
565
+
566
+ const tauMs = 100;
567
+ const alpha = 1 - Math.exp(-dtMs / tauMs);
568
+ const deltaH = vvhTarget - vvhCurrent;
569
+ const deltaO = offsetTarget - offsetCurrent;
570
+
571
+ if (Math.abs(deltaH) > 1) vvhCurrent += deltaH * alpha;
572
+ else vvhCurrent = vvhTarget;
573
+
574
+ if (Math.abs(deltaO) > 0.5) offsetCurrent += deltaO * alpha;
575
+ else offsetCurrent = offsetTarget;
576
+
577
+ applyVars();
578
+ fitAddon.fit();
579
+
580
+ const stillAnimating = Math.abs(vvhTarget - vvhCurrent) > 0.5 || Math.abs(offsetTarget - offsetCurrent) > 0.5;
581
+ if (stillAnimating) {
582
+ watchRafId = requestAnimationFrame(tick);
583
+ } else {
584
+ watchRafId = null;
585
+ }
586
+ };
587
+
588
+ watchRafId = requestAnimationFrame(tick);
589
+ };
590
+
591
+ // Initial setup
592
+ const { height, offsetTop } = readViewport();
593
+ vvhCurrent = height;
594
+ vvhTarget = height;
595
+ offsetCurrent = offsetTop;
596
+ offsetTarget = offsetTop;
597
+ applyVars();
598
+
599
+ window.addEventListener('resize', startKeyboardWatch);
600
+ window.addEventListener('focusin', startKeyboardWatch);
601
+ window.addEventListener('focusout', startKeyboardWatch);
602
+ window.visualViewport?.addEventListener('resize', startKeyboardWatch);
603
+ }
604
+
605
+ // Handle terminal resize
606
+ term.onResize((size) => {
607
+ if (ws && ws.readyState === WebSocket.OPEN) {
608
+ ws.send(JSON.stringify({ type: 'resize', cols: size.cols, rows: size.rows }));
609
+ }
610
+ });
611
+
612
+ // Handle user input
613
+ term.onData((data) => {
614
+ if (ws && ws.readyState === WebSocket.OPEN) {
615
+ ws.send(data);
616
+ }
617
+ });
618
+
619
+ // Handle directory changes
620
+ const directoryElement = document.getElementById('current-directory');
621
+ const separatorElement = document.getElementById('title-separator');
622
+ term.onDirectoryChange((directory) => {
623
+ if (directoryElement && separatorElement) {
624
+ if (directory) {
625
+ directoryElement.textContent = directory;
626
+ separatorElement.style.display = 'inline';
627
+ } else {
628
+ directoryElement.textContent = '';
629
+ separatorElement.style.display = 'none';
630
+ }
631
+ }
632
+ });
633
+
634
+ connectWebSocket();
635
+ }
636
+
637
+ function connectWebSocket() {
638
+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
639
+ const wsUrl = protocol + '//' + window.location.host + '/ws?cols=' + term.cols + '&rows=' + term.rows;
640
+
641
+ ws = new WebSocket(wsUrl);
642
+
643
+ ws.onopen = () => {
644
+ updateConnectionStatus(true);
645
+ };
646
+
647
+ ws.onmessage = (event) => {
648
+ term.write(event.data);
649
+ };
650
+
651
+ ws.onerror = () => {
652
+ updateConnectionStatus(false);
653
+ };
654
+
655
+ ws.onclose = () => {
656
+ updateConnectionStatus(false);
657
+ setTimeout(() => {
658
+ if (!ws || ws.readyState === WebSocket.CLOSED) {
659
+ connectWebSocket();
660
+ }
661
+ }, 3000);
662
+ };
663
+ }
664
+
665
+ function updateConnectionStatus(connected) {
666
+ const dot = document.getElementById('connection-dot');
667
+ const text = document.getElementById('connection-text');
668
+ if (connected) {
669
+ dot.classList.add('connected');
670
+ text.textContent = 'Connected';
671
+ } else {
672
+ dot.classList.remove('connected');
673
+ text.textContent = 'Disconnected';
674
+ }
675
+ }
676
+
677
+ initTerminal();
678
+ </script>
679
+ </body>
680
+ </html>`;
681
+
682
+ // ============================================================================
683
+ // MIME Types
684
+ // ============================================================================
685
+
686
+ const MIME_TYPES = {
687
+ '.html': 'text/html',
688
+ '.js': 'application/javascript',
689
+ '.mjs': 'application/javascript',
690
+ '.css': 'text/css',
691
+ '.json': 'application/json',
692
+ '.wasm': 'application/wasm',
693
+ '.png': 'image/png',
694
+ '.svg': 'image/svg+xml',
695
+ '.ico': 'image/x-icon',
696
+ };
697
+
698
+ // ============================================================================
699
+ // HTTP Server
700
+ // ============================================================================
701
+
702
+ const httpServer = http.createServer((req, res) => {
703
+ const url = new URL(req.url, `http://${req.headers.host}`);
704
+ const pathname = url.pathname;
705
+
706
+ // Serve index page
707
+ if (pathname === '/' || pathname === '/index.html') {
708
+ res.writeHead(200, { 'Content-Type': 'text/html' });
709
+ res.end(HTML_TEMPLATE);
710
+ return;
711
+ }
712
+
713
+ // Serve dist files
714
+ if (pathname.startsWith('/dist/')) {
715
+ const filePath = path.join(distPath, pathname.slice(6));
716
+ serveFile(filePath, res);
717
+ return;
718
+ }
719
+
720
+ // Serve WASM file
721
+ if (pathname === '/ghostty-vt.wasm') {
722
+ serveFile(wasmPath, res);
723
+ return;
724
+ }
725
+
726
+ // 404
727
+ res.writeHead(404);
728
+ res.end('Not Found');
729
+ });
730
+
731
+ function serveFile(filePath, res) {
732
+ const ext = path.extname(filePath);
733
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
734
+
735
+ fs.readFile(filePath, (err, data) => {
736
+ if (err) {
737
+ res.writeHead(404);
738
+ res.end('Not Found');
739
+ return;
740
+ }
741
+ res.writeHead(200, { 'Content-Type': contentType });
742
+ res.end(data);
743
+ });
744
+ }
745
+
746
+ // ============================================================================
747
+ // WebSocket Server
748
+ // ============================================================================
749
+
750
+ const sessions = new Map();
751
+
752
+ function getShell() {
753
+ if (process.platform === 'win32') {
754
+ return process.env.COMSPEC || 'cmd.exe';
755
+ }
756
+ return process.env.SHELL || '/bin/bash';
757
+ }
758
+
759
+ function createPtySession(cols, rows) {
760
+ const shell = getShell();
761
+
762
+ const ptyProcess = pty.spawn(shell, [], {
763
+ name: 'xterm-256color',
764
+ cols: cols,
765
+ rows: rows,
766
+ cwd: homedir(),
767
+ env: {
768
+ ...process.env,
769
+ TERM: 'xterm-256color',
770
+ COLORTERM: 'truecolor',
771
+ },
772
+ });
773
+
774
+ return ptyProcess;
775
+ }
776
+
777
+ const wss = new WebSocketServer({ noServer: true });
778
+
779
+ httpServer.on('upgrade', (req, socket, head) => {
780
+ const url = new URL(req.url, `http://${req.headers.host}`);
781
+
782
+ if (url.pathname === '/ws') {
783
+ wss.handleUpgrade(req, socket, head, (ws) => {
784
+ wss.emit('connection', ws, req);
785
+ });
786
+ } else {
787
+ socket.destroy();
788
+ }
789
+ });
790
+
791
+ wss.on('connection', (ws, req) => {
792
+ const url = new URL(req.url, `http://${req.headers.host}`);
793
+ const cols = Number.parseInt(url.searchParams.get('cols') || '80');
794
+ const rows = Number.parseInt(url.searchParams.get('rows') || '24');
795
+
796
+ const ptyProcess = createPtySession(cols, rows);
797
+ sessions.set(ws, { pty: ptyProcess });
798
+
799
+ ptyProcess.onData((data) => {
800
+ if (ws.readyState === ws.OPEN) {
801
+ ws.send(data);
802
+ }
803
+ });
804
+
805
+ ptyProcess.onExit(({ exitCode }) => {
806
+ if (ws.readyState === ws.OPEN) {
807
+ ws.send(`\r\n\x1b[33mShell exited (code: ${exitCode})\x1b[0m\r\n`);
808
+ ws.close();
809
+ }
810
+ });
811
+
812
+ ws.on('message', (data) => {
813
+ const message = data.toString('utf8');
814
+
815
+ if (message.startsWith('{')) {
816
+ try {
817
+ const msg = JSON.parse(message);
818
+ if (msg.type === 'resize') {
819
+ ptyProcess.resize(msg.cols, msg.rows);
820
+ return;
821
+ }
822
+ } catch (e) {
823
+ // Not JSON, treat as input
824
+ }
825
+ }
826
+
827
+ ptyProcess.write(message);
828
+ });
829
+
830
+ ws.on('close', () => {
831
+ const session = sessions.get(ws);
832
+ if (session) {
833
+ session.pty.kill();
834
+ sessions.delete(ws);
835
+ }
836
+ });
837
+
838
+ ws.on('error', () => {
839
+ // Ignore socket errors
840
+ });
841
+ });
842
+
843
+ // ============================================================================
844
+ // Startup
845
+ // ============================================================================
846
+
847
+ function getLocalIPs() {
848
+ const interfaces = networkInterfaces();
849
+ const ips = [];
850
+ for (const name of Object.keys(interfaces)) {
851
+ for (const iface of interfaces[name] || []) {
852
+ if (iface.family === 'IPv4' && !iface.internal) {
853
+ ips.push(iface.address);
854
+ }
855
+ }
856
+ }
857
+ return ips;
858
+ }
859
+
860
+ function printBanner(url) {
861
+ const localIPs = getLocalIPs();
862
+ // ANSI color codes
863
+ const RESET = '\x1b[0m';
864
+ const CYAN = '\x1b[36m'; // Labels
865
+ const BEIGE = '\x1b[38;2;255;220;150m'; // Warm yellow/beige for values (RGB: 255,220,150)
866
+ const DIM = '\x1b[2m'; // Dimmed text
867
+
868
+ // console.log('');
869
+
870
+ // Open: URL
871
+ console.log(` ${CYAN}Open:${RESET} ${BEIGE}${url}${RESET}`);
872
+
873
+ // Network: URLs
874
+ const network = [` ${CYAN}Network: ${RESET}`];
875
+ if (localIPs.length > 0) {
876
+ let networkCount = 0;
877
+ for (const ip of localIPs) {
878
+ networkCount++;
879
+ const spaces = networkCount !== 1 ? ' ' : '';
880
+ network.push(`${spaces}${BEIGE}http://${ip}:${HTTP_PORT}${RESET}\n`);
881
+ }
882
+ }
883
+ console.log(`\n${network.join('')} `);
884
+
885
+ // Shell: path
886
+ console.log(` ${CYAN}Shell:${RESET} ${BEIGE}${getShell()}${RESET}`);
887
+
888
+ console.log('');
889
+
890
+ // Home: path
891
+ console.log(` ${CYAN}Home:${RESET} ${BEIGE}${homedir()}${RESET}`);
892
+
893
+ console.log('');
894
+ console.log(` ${DIM}Press Ctrl+C to stop.${RESET}\n`);
895
+ }
896
+
897
+ process.on('SIGINT', () => {
898
+ console.log('\n\nShutting down...');
899
+ for (const [ws, session] of sessions.entries()) {
900
+ session.pty.kill();
901
+ ws.close();
902
+ }
903
+ wss.close();
904
+ process.exit(0);
905
+ });
906
+
907
+ httpServer.listen(HTTP_PORT, '0.0.0.0', async () => {
908
+ // Display ASCII art banner
909
+ try {
910
+ const imagePath = path.join(__dirname, '..', 'bin', 'assets', 'ghosts.png');
911
+ if (fs.existsSync(imagePath)) {
912
+ // Welcome text with orange/yellow color (bright yellow, bold)
913
+ console.log('\n \x1b[1;93mWelcome to Ghosttown!\x1b[0m\n');
914
+ const art = await asciiArt(imagePath, { maxWidth: 80, maxHeight: 20 });
915
+ console.log(art);
916
+ console.log('');
917
+ }
918
+ } catch (err) {
919
+ // Silently fail if ASCII art can't be displayed
920
+ // This allows the server to start even if the image is missing
921
+ }
922
+
923
+ printBanner(`http://localhost:${HTTP_PORT}`);
924
+ });
925
+ }
926
+
927
+ // ============================================================================
928
+ // Main entry point
929
+ // ============================================================================
930
+
931
+ export function run(argv) {
932
+ const cliArgs = parseArgs(argv);
933
+
934
+ // If a command is provided, create a tmux session instead of starting server
935
+ if (cliArgs.command) {
936
+ createTmuxSession(cliArgs.command);
937
+ // createTmuxSession spawns tmux attach and waits for it to exit
938
+ // The script will exit when tmux attach exits (via the exit handler)
939
+ // We must not continue to server code, so we stop here
940
+ } else {
941
+ // Server mode (no command provided)
942
+ startWebServer(cliArgs);
943
+ }
944
+ }