@seflless/ghosttown 1.3.0 → 1.3.2

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,1275 @@
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, spawnSync } 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
+ * Check if currently inside a tmux session
79
+ */
80
+ function isInsideTmux() {
81
+ return !!process.env.TMUX;
82
+ }
83
+
84
+ /**
85
+ * Get the name of the current tmux session
86
+ * Returns null if not inside tmux
87
+ */
88
+ function getCurrentTmuxSessionName() {
89
+ if (!isInsideTmux()) return null;
90
+ try {
91
+ return execSync('tmux display-message -p "#{session_name}"', {
92
+ encoding: 'utf8',
93
+ stdio: ['pipe', 'pipe', 'pipe'],
94
+ }).trim();
95
+ } catch (err) {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Check if currently inside a ghosttown session (named ghosttown-<N>)
102
+ */
103
+ function isInsideGhosttownSession() {
104
+ const sessionName = getCurrentTmuxSessionName();
105
+ return sessionName && sessionName.startsWith('ghosttown-');
106
+ }
107
+
108
+ /**
109
+ * Get the next available ghosttown session ID
110
+ * Scans existing tmux sessions named ghosttown-<N> and returns max(N) + 1
111
+ */
112
+ function getNextSessionId() {
113
+ try {
114
+ // List all tmux sessions
115
+ const output = execSync('tmux list-sessions -F "#{session_name}"', {
116
+ encoding: 'utf8',
117
+ stdio: ['pipe', 'pipe', 'pipe'],
118
+ });
119
+
120
+ // Find all ghosttown-<N> sessions and extract IDs
121
+ const sessionIds = output
122
+ .split('\n')
123
+ .filter((name) => name.startsWith('ghosttown-'))
124
+ .map((name) => {
125
+ const id = Number.parseInt(name.replace('ghosttown-', ''), 10);
126
+ return Number.isNaN(id) ? 0 : id;
127
+ });
128
+
129
+ // Return max + 1, or 1 if no sessions exist
130
+ return sessionIds.length > 0 ? Math.max(...sessionIds) + 1 : 1;
131
+ } catch (err) {
132
+ // tmux not running or no sessions - start with 1
133
+ return 1;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * List all ghosttown tmux sessions
139
+ */
140
+ function listSessions() {
141
+ // Check if tmux is installed
142
+ if (!checkTmuxInstalled()) {
143
+ printTmuxInstallHelp();
144
+ }
145
+
146
+ const RESET = '\x1b[0m';
147
+ const CYAN = '\x1b[36m';
148
+ const BEIGE = '\x1b[38;2;255;220;150m';
149
+
150
+ try {
151
+ // Get detailed session information
152
+ const output = execSync(
153
+ 'tmux list-sessions -F "#{session_name}|#{session_created}|#{session_attached}|#{session_windows}"',
154
+ {
155
+ encoding: 'utf8',
156
+ stdio: ['pipe', 'pipe', 'pipe'],
157
+ }
158
+ );
159
+
160
+ const sessions = output
161
+ .split('\n')
162
+ .filter((line) => line.startsWith('ghosttown-'))
163
+ .map((line) => {
164
+ const [name, created, attached, windows] = line.split('|');
165
+ return {
166
+ name,
167
+ created: new Date(Number.parseInt(created, 10) * 1000),
168
+ attached: attached === '1',
169
+ windows: Number.parseInt(windows, 10),
170
+ };
171
+ });
172
+
173
+ if (sessions.length === 0) {
174
+ console.log('');
175
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
176
+ console.log('');
177
+ process.exit(0);
178
+ }
179
+
180
+ // Print header
181
+ console.log('\n\x1b[1mGhosttown Sessions\x1b[0m\n');
182
+ console.log(
183
+ `${CYAN}${'Name'.padEnd(15)} ${'Created'.padEnd(22)} ${'Status'.padEnd(10)} Windows${RESET}`
184
+ );
185
+
186
+ // Print sessions
187
+ for (const session of sessions) {
188
+ const createdStr = session.created.toLocaleString();
189
+ // Status has ANSI codes so we need to pad the visible text differently
190
+ const statusPadded = session.attached
191
+ ? `\x1b[32m${'attached'.padEnd(10)}${RESET}`
192
+ : `\x1b[33m${'detached'.padEnd(10)}${RESET}`;
193
+ console.log(
194
+ `${session.name.padEnd(15)} ${createdStr.padEnd(22)} ${statusPadded} ${session.windows}`
195
+ );
196
+ }
197
+
198
+ console.log('');
199
+ const sessionWord = sessions.length === 1 ? 'session' : 'sessions';
200
+ console.log(`Total: ${sessions.length} ${sessionWord}`);
201
+ console.log('');
202
+ } catch (err) {
203
+ // tmux not running or no sessions
204
+ console.log('');
205
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
206
+ console.log('');
207
+ }
208
+
209
+ process.exit(0);
210
+ }
211
+
212
+ /**
213
+ * Create a new tmux session and run the command
214
+ */
215
+ function createTmuxSession(command) {
216
+ // Check if tmux is installed
217
+ if (!checkTmuxInstalled()) {
218
+ printTmuxInstallHelp();
219
+ }
220
+
221
+ const sessionId = getNextSessionId();
222
+ const sessionName = `ghosttown-${sessionId}`;
223
+
224
+ try {
225
+ // Create tmux session and attach directly (not detached)
226
+ // Use -x and -y to set initial size, avoiding "terminal too small" issues
227
+ // The command runs in the session, and we attach immediately
228
+ const attach = spawn(
229
+ 'tmux',
230
+ [
231
+ 'new-session',
232
+ '-s',
233
+ sessionName,
234
+ '-x',
235
+ '200',
236
+ '-y',
237
+ '50',
238
+ // Set status off (no HUD), run the command, then start a shell
239
+ // so the session stays open and interactive after command completes
240
+ 'tmux set-option status off; ' + command + '; exec $SHELL',
241
+ ],
242
+ {
243
+ stdio: 'inherit',
244
+ }
245
+ );
246
+
247
+ attach.on('exit', (code) => {
248
+ process.exit(code || 0);
249
+ });
250
+ } catch (err) {
251
+ console.error(`Error creating tmux session: ${err.message}`);
252
+ process.exit(1);
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Print styled detach success message
258
+ */
259
+ function printDetachMessage(sessionName) {
260
+ const RESET = '\x1b[0m';
261
+ const CYAN = '\x1b[36m';
262
+ const BEIGE = '\x1b[38;2;255;220;150m';
263
+ const DIM = '\x1b[2m';
264
+ const BOLD_YELLOW = '\x1b[1;93m';
265
+ const labelWidth = Math.max('To reattach:'.length, 'To list all sessions:'.length);
266
+ const formatHint = (label, command) =>
267
+ ` ${CYAN}${label.padStart(labelWidth)}${RESET} ${BEIGE}${command}${RESET}`;
268
+
269
+ return [
270
+ '',
271
+ ` ${BOLD_YELLOW}You've detached from your ghosttown session.${RESET}`,
272
+ ` ${DIM}It's now running in the background.${RESET}`,
273
+ '',
274
+ formatHint('To reattach:', `ghosttown attach ${sessionName}`),
275
+ '',
276
+ formatHint('To list all sessions:', 'ghosttown list'),
277
+ '',
278
+ '',
279
+ ].join('\n');
280
+ }
281
+
282
+ /**
283
+ * Detach from the current ghosttown tmux session
284
+ */
285
+ function detachFromTmux() {
286
+ const RESET = '\x1b[0m';
287
+ const RED = '\x1b[31m';
288
+ const DIM = '\x1b[2m';
289
+ const BEIGE = '\x1b[38;2;255;220;150m';
290
+
291
+ // Check if we're inside tmux at all
292
+ if (!isInsideTmux()) {
293
+ console.log('');
294
+ console.log(` ${RED}Error:${RESET} Not inside a tmux session.`);
295
+ console.log('');
296
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
297
+ console.log('');
298
+ process.exit(1);
299
+ }
300
+
301
+ // Check if we're inside a ghosttown session specifically
302
+ if (!isInsideGhosttownSession()) {
303
+ console.log('');
304
+ console.log(` ${RED}Error:${RESET} Not inside a ghosttown session.`);
305
+ console.log('');
306
+ console.log(` ${DIM}You're in a tmux session, but not one created by ghosttown.${RESET}`);
307
+ console.log(
308
+ ` ${DIM}To detach from this tmux session, use: tmux detach (or ctrl+b d)${RESET}`
309
+ );
310
+ console.log('');
311
+ process.exit(1);
312
+ }
313
+
314
+ // Get the session name for the message
315
+ const sessionName = getCurrentTmuxSessionName();
316
+ const message = printDetachMessage(sessionName);
317
+ const messageForShell = message.replace(/'/g, "'\\''");
318
+
319
+ // Detach only the current client (not all attached clients).
320
+ // Use client_tty so multiple attached windows aren't all detached.
321
+ let result = null;
322
+ let clientTty = null;
323
+ try {
324
+ clientTty = execSync('tmux display-message -p "#{client_tty}"', {
325
+ encoding: 'utf8',
326
+ stdio: ['pipe', 'pipe', 'pipe'],
327
+ }).trim();
328
+
329
+ if (clientTty) {
330
+ result = spawnSync(
331
+ 'tmux',
332
+ [
333
+ 'detach-client',
334
+ '-t',
335
+ clientTty,
336
+ '-E',
337
+ `printf %s '${messageForShell}'`,
338
+ ],
339
+ {
340
+ stdio: 'inherit',
341
+ }
342
+ );
343
+ }
344
+ } catch (err) {
345
+ // Fall back to generic detach below.
346
+ }
347
+
348
+ if (!result) {
349
+ // Detach using shell execution to avoid nesting warnings
350
+ result = spawnSync(process.env.SHELL || '/bin/sh', ['-c', 'exec tmux detach'], {
351
+ stdio: 'inherit',
352
+ });
353
+ }
354
+
355
+ // If we couldn't target a client tty, fall back to stdout.
356
+ if (!clientTty) {
357
+ process.stdout.write(message);
358
+ }
359
+
360
+ process.exit(result.status || 0);
361
+ }
362
+
363
+ /**
364
+ * Attach to a ghosttown session
365
+ */
366
+ function attachToSession(sessionName) {
367
+ // Check if tmux is installed
368
+ if (!checkTmuxInstalled()) {
369
+ printTmuxInstallHelp();
370
+ }
371
+
372
+ const RESET = '\x1b[0m';
373
+ const RED = '\x1b[31m';
374
+ const BEIGE = '\x1b[38;2;255;220;150m';
375
+
376
+ // Add ghosttown- prefix if not present
377
+ if (!sessionName.startsWith('ghosttown-')) {
378
+ sessionName = `ghosttown-${sessionName}`;
379
+ }
380
+
381
+ // Check if session exists
382
+ try {
383
+ const output = execSync('tmux list-sessions -F "#{session_name}"', {
384
+ encoding: 'utf8',
385
+ stdio: ['pipe', 'pipe', 'pipe'],
386
+ });
387
+
388
+ const sessions = output.split('\n').filter((s) => s.trim());
389
+ if (!sessions.includes(sessionName)) {
390
+ console.log('');
391
+ console.log(` ${RED}Error:${RESET} Session '${sessionName}' not found.`);
392
+ console.log('');
393
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
394
+ console.log('');
395
+ process.exit(1);
396
+ }
397
+ } catch (err) {
398
+ console.log('');
399
+ console.log(` ${RED}Error:${RESET} No tmux sessions found.`);
400
+ console.log('');
401
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
402
+ console.log('');
403
+ process.exit(1);
404
+ }
405
+
406
+ // Attach to the session using spawn with shell
407
+ // Use the same pattern as detachFromTmux which works
408
+ const result = spawnSync(
409
+ process.env.SHELL || '/bin/sh',
410
+ ['-c', `tmux attach-session -t ${sessionName}`],
411
+ {
412
+ stdio: 'inherit',
413
+ }
414
+ );
415
+
416
+ process.exit(result.status || 0);
417
+ }
418
+
419
+ /**
420
+ * Kill a ghosttown session
421
+ * If sessionName is null, kills the current session (if inside one)
422
+ */
423
+ function killSession(sessionName) {
424
+ // Check if tmux is installed
425
+ if (!checkTmuxInstalled()) {
426
+ printTmuxInstallHelp();
427
+ }
428
+
429
+ const RESET = '\x1b[0m';
430
+ const RED = '\x1b[31m';
431
+ const CYAN = '\x1b[36m';
432
+ const BEIGE = '\x1b[38;2;255;220;150m';
433
+ const DIM = '\x1b[2m';
434
+ const BOLD_YELLOW = '\x1b[1;93m';
435
+
436
+ // If no session specified, try to kill current session
437
+ if (!sessionName) {
438
+ if (!isInsideTmux()) {
439
+ console.log('');
440
+ console.log(` ${RED}Error:${RESET} No session specified and not inside a tmux session.`);
441
+ console.log('');
442
+ console.log(` ${DIM}Usage:${RESET}`);
443
+ console.log(` ${DIM} ghosttown -k <session> Kill a specific session${RESET}`);
444
+ console.log(
445
+ ` ${DIM} ghosttown -k Kill current session (when inside one)${RESET}`
446
+ );
447
+ console.log('');
448
+ process.exit(1);
449
+ }
450
+
451
+ if (!isInsideGhosttownSession()) {
452
+ console.log('');
453
+ console.log(` ${RED}Error:${RESET} Not inside a ghosttown session.`);
454
+ console.log('');
455
+ console.log(` ${DIM}You're in a tmux session, but not one created by ghosttown.${RESET}`);
456
+ console.log(` ${DIM}To kill this tmux session, use: tmux kill-session${RESET}`);
457
+ console.log('');
458
+ process.exit(1);
459
+ }
460
+
461
+ sessionName = getCurrentTmuxSessionName();
462
+ }
463
+
464
+ // Add ghosttown- prefix if not present
465
+ if (!sessionName.startsWith('ghosttown-')) {
466
+ sessionName = `ghosttown-${sessionName}`;
467
+ }
468
+
469
+ // Check if session exists
470
+ try {
471
+ const output = execSync('tmux list-sessions -F "#{session_name}"', {
472
+ encoding: 'utf8',
473
+ stdio: ['pipe', 'pipe', 'pipe'],
474
+ });
475
+
476
+ const sessions = output.split('\n').filter((s) => s.trim());
477
+ if (!sessions.includes(sessionName)) {
478
+ console.log('');
479
+ console.log(` ${RED}Error:${RESET} Session '${sessionName}' not found.`);
480
+ console.log('');
481
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
482
+ console.log('');
483
+ process.exit(1);
484
+ }
485
+ } catch (err) {
486
+ console.log('');
487
+ console.log(` ${RED}Error:${RESET} No tmux sessions found.`);
488
+ console.log('');
489
+ console.log(` ${BEIGE}No ghosttown sessions are currently running.${RESET}`);
490
+ console.log('');
491
+ process.exit(1);
492
+ }
493
+
494
+ // Kill the session
495
+ try {
496
+ execSync(`tmux kill-session -t ${sessionName}`, {
497
+ stdio: 'pipe',
498
+ });
499
+
500
+ console.log('');
501
+ console.log(` ${BOLD_YELLOW}Session '${sessionName}' has been killed.${RESET}`);
502
+ console.log('');
503
+ console.log(` ${CYAN}To list remaining:${RESET} ${BEIGE}ghosttown list${RESET}`);
504
+ console.log('');
505
+ process.exit(0);
506
+ } catch (err) {
507
+ console.log('');
508
+ console.log(` ${RED}Error:${RESET} Failed to kill session '${sessionName}'.`);
509
+ console.log('');
510
+ process.exit(1);
511
+ }
512
+ }
513
+
514
+ // ============================================================================
515
+ // Parse CLI arguments
516
+ // ============================================================================
517
+
518
+ function parseArgs(argv) {
519
+ const args = argv.slice(2);
520
+ let port = null;
521
+ let command = null;
522
+ let handled = false;
523
+
524
+ for (let i = 0; i < args.length; i++) {
525
+ const arg = args[i];
526
+
527
+ if (arg === '-h' || arg === '--help') {
528
+ console.log(`
529
+ Usage: ghosttown [options] [command]
530
+
531
+ Options:
532
+ -p, --port <port> Port to listen on (default: 8080, or PORT env var)
533
+ -k, --kill [session] Kill a session (current if inside one, or specify)
534
+ -h, --help Show this help message
535
+
536
+ Commands:
537
+ list List all ghosttown tmux sessions
538
+ attach <session> Attach to a ghosttown session
539
+ detach Detach from current ghosttown session
540
+ <command> Run command in a new tmux session (ghosttown-<id>)
541
+
542
+ Examples:
543
+ ghosttown Start the web terminal server
544
+ ghosttown -p 3000 Start the server on port 3000
545
+ ghosttown list List all ghosttown sessions
546
+ ghosttown attach ghosttown-1 Attach to session ghosttown-1
547
+ ghosttown detach Detach from current session
548
+ ghosttown -k Kill current session (when inside one)
549
+ ghosttown -k ghosttown-1 Kill a specific session
550
+ ghosttown vim Run vim in a new tmux session
551
+ ghosttown "npm run dev" Run npm in a new tmux session
552
+
553
+ Aliases:
554
+ This CLI can also be invoked as 'gt' or 'ght'.
555
+ `);
556
+ handled = true;
557
+ break;
558
+ }
559
+
560
+ // Handle list command
561
+ if (arg === 'list') {
562
+ handled = true;
563
+ listSessions();
564
+ // listSessions exits, so this won't be reached
565
+ }
566
+
567
+ // Handle detach command
568
+ else if (arg === 'detach') {
569
+ handled = true;
570
+ detachFromTmux();
571
+ // detachFromTmux exits, so this won't be reached
572
+ }
573
+
574
+ // Handle attach command
575
+ else if (arg === 'attach') {
576
+ const sessionArg = args[i + 1];
577
+ if (!sessionArg) {
578
+ console.error('Error: attach requires a session name');
579
+ console.error('Usage: ghosttown attach <session>');
580
+ handled = true;
581
+ break;
582
+ }
583
+ handled = true;
584
+ attachToSession(sessionArg);
585
+ // attachToSession exits, so this won't be reached
586
+ }
587
+
588
+ // Handle kill command
589
+ else if (arg === '-k' || arg === '--kill') {
590
+ const nextArg = args[i + 1];
591
+ // Session name is optional - if not provided or is another flag, pass null
592
+ const sessionArg = nextArg && !nextArg.startsWith('-') ? nextArg : null;
593
+ handled = true;
594
+ killSession(sessionArg);
595
+ // killSession exits, so this won't be reached
596
+ } else if (arg === '-p' || arg === '--port') {
597
+ const nextArg = args[i + 1];
598
+ if (!nextArg || nextArg.startsWith('-')) {
599
+ console.error(`Error: ${arg} requires a port number`);
600
+ process.exit(1);
601
+ }
602
+ port = Number.parseInt(nextArg, 10);
603
+ if (Number.isNaN(port) || port < 1 || port > 65535) {
604
+ console.error(`Error: Invalid port number: ${nextArg}`);
605
+ process.exit(1);
606
+ }
607
+ i++; // Skip the next argument since we consumed it
608
+ }
609
+
610
+ // First non-flag argument starts the command
611
+ // Capture it and all remaining arguments as the command
612
+ else if (!arg.startsWith('-')) {
613
+ command = args.slice(i).join(' ');
614
+ break;
615
+ }
616
+ }
617
+
618
+ return { port, command, handled };
619
+ }
620
+
621
+ // ============================================================================
622
+ // Web Server
623
+ // ============================================================================
624
+
625
+ function startWebServer(cliArgs) {
626
+ const HTTP_PORT = cliArgs.port || process.env.PORT || 8080;
627
+
628
+ // ============================================================================
629
+ // Locate ghosttown assets
630
+ // ============================================================================
631
+
632
+ function findAssets() {
633
+ // Assets are in the package root (one level up from src/)
634
+ const packageRoot = path.join(__dirname, '..');
635
+ const distPath = path.join(packageRoot, 'dist');
636
+ const wasmPath = path.join(packageRoot, 'ghostty-vt.wasm');
637
+
638
+ if (!fs.existsSync(path.join(distPath, 'ghostty-web.js'))) {
639
+ console.error('Error: dist/ghostty-web.js not found.');
640
+ console.error('The package may not have been built correctly.');
641
+ process.exit(1);
642
+ }
643
+
644
+ if (!fs.existsSync(wasmPath)) {
645
+ console.error('Error: ghostty-vt.wasm not found.');
646
+ console.error('The package may not have been built correctly.');
647
+ process.exit(1);
648
+ }
649
+
650
+ return { distPath, wasmPath };
651
+ }
652
+
653
+ const { distPath, wasmPath } = findAssets();
654
+
655
+ // ============================================================================
656
+ // HTML Template
657
+ // ============================================================================
658
+
659
+ const HTML_TEMPLATE = `<!doctype html>
660
+ <html lang="en">
661
+ <head>
662
+ <meta charset="UTF-8" />
663
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
664
+ <title>ghosttown</title>
665
+ <style>
666
+ :root {
667
+ --vvh: 100vh;
668
+ --vv-offset-top: 0px;
669
+ }
670
+
671
+ * {
672
+ margin: 0;
673
+ padding: 0;
674
+ box-sizing: border-box;
675
+ }
676
+
677
+ html, body {
678
+ margin: 0;
679
+ padding: 0;
680
+ height: var(--vvh);
681
+ overflow: hidden;
682
+ overscroll-behavior: none;
683
+ touch-action: none;
684
+ transition: none;
685
+ }
686
+
687
+ body {
688
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
689
+ background: #292c34;
690
+ padding: 8px 8px 14px 8px;
691
+ box-sizing: border-box;
692
+ position: fixed;
693
+ inset: 0;
694
+ height: var(--vvh);
695
+ }
696
+
697
+ .terminal-window {
698
+ width: 100%;
699
+ height: 100%;
700
+ background: #ededed;
701
+ display: flex;
702
+ flex-direction: column;
703
+ overflow: hidden;
704
+ box-shadow:
705
+ 0 0 0 0.5px #65686e,
706
+ 0 0 0 1px #74777c,
707
+ 0 0 0 1.5px #020203,
708
+ 0px 4px 10px 0px rgba(0, 0, 0, 0.5);
709
+ border-radius: 8px;
710
+ box-sizing: border-box;
711
+ transform: translateY(calc(var(--vv-offset-top) * -1));
712
+ transition: none;
713
+ }
714
+
715
+ .title-bar {
716
+ background: #292c34;
717
+ padding: 8px 16px 6px 10px;
718
+ display: flex;
719
+ align-items: center;
720
+ gap: 12px;
721
+ }
722
+
723
+ .traffic-lights {
724
+ display: flex;
725
+ gap: 8px;
726
+ }
727
+
728
+ .light {
729
+ width: 12px;
730
+ height: 12px;
731
+ border-radius: 50%;
732
+ }
733
+
734
+ .light.red { background: #ff5f56; }
735
+ .light.yellow { background: #ffbd2e; }
736
+ .light.green { background: #27c93f; }
737
+
738
+ .title {
739
+ color: #e5e5e5;
740
+ font-size: 13px;
741
+ font-weight: 500;
742
+ letter-spacing: 0.3px;
743
+ display: flex;
744
+ align-items: center;
745
+ gap: 8px;
746
+ }
747
+
748
+ .title-separator { color: #666; }
749
+ .current-directory {
750
+ color: #888;
751
+ font-size: 12px;
752
+ font-weight: 400;
753
+ max-width: 400px;
754
+ overflow: hidden;
755
+ text-overflow: ellipsis;
756
+ white-space: nowrap;
757
+ }
758
+
759
+ .connection-status {
760
+ margin-left: auto;
761
+ font-size: 11px;
762
+ color: #888;
763
+ display: flex;
764
+ align-items: center;
765
+ gap: 6px;
766
+ }
767
+
768
+ .connection-dot {
769
+ width: 6px;
770
+ height: 6px;
771
+ border-radius: 50%;
772
+ background: #666;
773
+ }
774
+
775
+ .connection-dot.connected { background: #27c93f; }
776
+
777
+ #terminal-container {
778
+ flex: 1;
779
+ padding: 2px 0 2px 2px;
780
+ background: #292c34;
781
+ position: relative;
782
+ overflow: hidden;
783
+ min-height: 0;
784
+ touch-action: none;
785
+ }
786
+
787
+ #terminal-container canvas {
788
+ display: block;
789
+ touch-action: none;
790
+ }
791
+ </style>
792
+ </head>
793
+ <body>
794
+ <div class="terminal-window">
795
+ <div class="title-bar">
796
+ <div class="traffic-lights">
797
+ <span class="light red"></span>
798
+ <span class="light yellow"></span>
799
+ <span class="light green"></span>
800
+ </div>
801
+ <div class="title">
802
+ <span>ghosttown</span>
803
+ <span class="title-separator" id="title-separator" style="display: none">•</span>
804
+ <span class="current-directory" id="current-directory"></span>
805
+ </div>
806
+ <div class="connection-status">
807
+ <span class="connection-dot" id="connection-dot"></span>
808
+ <span id="connection-text">Disconnected</span>
809
+ </div>
810
+ </div>
811
+ <div id="terminal-container"></div>
812
+ </div>
813
+
814
+ <script type="module">
815
+ import { init, Terminal, FitAddon } from '/dist/ghostty-web.js';
816
+
817
+ let term;
818
+ let ws;
819
+ let fitAddon;
820
+
821
+ async function initTerminal() {
822
+ await init();
823
+
824
+ term = new Terminal({
825
+ cursorBlink: true,
826
+ fontSize: 12,
827
+ fontFamily: 'Monaco, Menlo, "Courier New", monospace',
828
+ theme: {
829
+ background: '#292c34',
830
+ foreground: '#d4d4d4',
831
+ },
832
+ smoothScrollDuration: 0,
833
+ scrollback: 10000,
834
+ scrollbarVisible: false,
835
+ });
836
+
837
+ fitAddon = new FitAddon();
838
+ term.loadAddon(fitAddon);
839
+
840
+ term.open(document.getElementById('terminal-container'));
841
+ fitAddon.fit();
842
+ fitAddon.observeResize();
843
+
844
+ // Desktop: auto-focus. Mobile: focus only on tap.
845
+ const isCoarsePointer = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
846
+ if (!isCoarsePointer) {
847
+ term.focus();
848
+ }
849
+
850
+ // Prevent page scroll on iOS
851
+ document.addEventListener('touchmove', (e) => {
852
+ const container = document.getElementById('terminal-container');
853
+ if (container && !container.contains(e.target)) {
854
+ e.preventDefault();
855
+ }
856
+ }, { passive: false });
857
+
858
+ // Mobile keyboard handling via visualViewport
859
+ {
860
+ const root = document.documentElement;
861
+ let watchRafId = null;
862
+ let vvhCurrent = 0;
863
+ let vvhTarget = 0;
864
+ let offsetCurrent = 0;
865
+ let offsetTarget = 0;
866
+ let lastTick = 0;
867
+
868
+ const readViewport = () => ({
869
+ height: window.visualViewport?.height ?? window.innerHeight,
870
+ offsetTop: window.visualViewport?.offsetTop ?? 0,
871
+ });
872
+
873
+ const applyVars = () => {
874
+ root.style.setProperty('--vvh', vvhCurrent + 'px');
875
+ root.style.setProperty('--vv-offset-top', offsetCurrent + 'px');
876
+ };
877
+
878
+ const startKeyboardWatch = () => {
879
+ if (watchRafId !== null) return;
880
+ lastTick = performance.now();
881
+
882
+ const tick = () => {
883
+ const now = performance.now();
884
+ const dtMs = Math.max(1, now - lastTick);
885
+ lastTick = now;
886
+
887
+ const { height, offsetTop } = readViewport();
888
+ vvhTarget = height;
889
+ offsetTarget = offsetTop;
890
+
891
+ if (vvhCurrent === 0) vvhCurrent = vvhTarget;
892
+
893
+ const tauMs = 100;
894
+ const alpha = 1 - Math.exp(-dtMs / tauMs);
895
+ const deltaH = vvhTarget - vvhCurrent;
896
+ const deltaO = offsetTarget - offsetCurrent;
897
+
898
+ if (Math.abs(deltaH) > 1) vvhCurrent += deltaH * alpha;
899
+ else vvhCurrent = vvhTarget;
900
+
901
+ if (Math.abs(deltaO) > 0.5) offsetCurrent += deltaO * alpha;
902
+ else offsetCurrent = offsetTarget;
903
+
904
+ applyVars();
905
+ fitAddon.fit();
906
+
907
+ const stillAnimating = Math.abs(vvhTarget - vvhCurrent) > 0.5 || Math.abs(offsetTarget - offsetCurrent) > 0.5;
908
+ if (stillAnimating) {
909
+ watchRafId = requestAnimationFrame(tick);
910
+ } else {
911
+ watchRafId = null;
912
+ }
913
+ };
914
+
915
+ watchRafId = requestAnimationFrame(tick);
916
+ };
917
+
918
+ // Initial setup
919
+ const { height, offsetTop } = readViewport();
920
+ vvhCurrent = height;
921
+ vvhTarget = height;
922
+ offsetCurrent = offsetTop;
923
+ offsetTarget = offsetTop;
924
+ applyVars();
925
+
926
+ window.addEventListener('resize', startKeyboardWatch);
927
+ window.addEventListener('focusin', startKeyboardWatch);
928
+ window.addEventListener('focusout', startKeyboardWatch);
929
+ window.visualViewport?.addEventListener('resize', startKeyboardWatch);
930
+ }
931
+
932
+ // Handle terminal resize
933
+ term.onResize((size) => {
934
+ if (ws && ws.readyState === WebSocket.OPEN) {
935
+ ws.send(JSON.stringify({ type: 'resize', cols: size.cols, rows: size.rows }));
936
+ }
937
+ });
938
+
939
+ // Handle user input
940
+ term.onData((data) => {
941
+ if (ws && ws.readyState === WebSocket.OPEN) {
942
+ ws.send(data);
943
+ }
944
+ });
945
+
946
+ // Handle directory changes
947
+ const directoryElement = document.getElementById('current-directory');
948
+ const separatorElement = document.getElementById('title-separator');
949
+ term.onDirectoryChange((directory) => {
950
+ if (directoryElement && separatorElement) {
951
+ if (directory) {
952
+ directoryElement.textContent = directory;
953
+ separatorElement.style.display = 'inline';
954
+ } else {
955
+ directoryElement.textContent = '';
956
+ separatorElement.style.display = 'none';
957
+ }
958
+ }
959
+ });
960
+
961
+ connectWebSocket();
962
+ }
963
+
964
+ function connectWebSocket() {
965
+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
966
+ const wsUrl = protocol + '//' + window.location.host + '/ws?cols=' + term.cols + '&rows=' + term.rows;
967
+
968
+ ws = new WebSocket(wsUrl);
969
+
970
+ ws.onopen = () => {
971
+ updateConnectionStatus(true);
972
+ };
973
+
974
+ ws.onmessage = (event) => {
975
+ term.write(event.data);
976
+ };
977
+
978
+ ws.onerror = () => {
979
+ updateConnectionStatus(false);
980
+ };
981
+
982
+ ws.onclose = () => {
983
+ updateConnectionStatus(false);
984
+ setTimeout(() => {
985
+ if (!ws || ws.readyState === WebSocket.CLOSED) {
986
+ connectWebSocket();
987
+ }
988
+ }, 3000);
989
+ };
990
+ }
991
+
992
+ function updateConnectionStatus(connected) {
993
+ const dot = document.getElementById('connection-dot');
994
+ const text = document.getElementById('connection-text');
995
+ if (connected) {
996
+ dot.classList.add('connected');
997
+ text.textContent = 'Connected';
998
+ } else {
999
+ dot.classList.remove('connected');
1000
+ text.textContent = 'Disconnected';
1001
+ }
1002
+ }
1003
+
1004
+ initTerminal();
1005
+ </script>
1006
+ </body>
1007
+ </html>`;
1008
+
1009
+ // ============================================================================
1010
+ // MIME Types
1011
+ // ============================================================================
1012
+
1013
+ const MIME_TYPES = {
1014
+ '.html': 'text/html',
1015
+ '.js': 'application/javascript',
1016
+ '.mjs': 'application/javascript',
1017
+ '.css': 'text/css',
1018
+ '.json': 'application/json',
1019
+ '.wasm': 'application/wasm',
1020
+ '.png': 'image/png',
1021
+ '.svg': 'image/svg+xml',
1022
+ '.ico': 'image/x-icon',
1023
+ };
1024
+
1025
+ // ============================================================================
1026
+ // HTTP Server
1027
+ // ============================================================================
1028
+
1029
+ const httpServer = http.createServer((req, res) => {
1030
+ const url = new URL(req.url, `http://${req.headers.host}`);
1031
+ const pathname = url.pathname;
1032
+
1033
+ // Serve index page
1034
+ if (pathname === '/' || pathname === '/index.html') {
1035
+ res.writeHead(200, { 'Content-Type': 'text/html' });
1036
+ res.end(HTML_TEMPLATE);
1037
+ return;
1038
+ }
1039
+
1040
+ // Serve dist files
1041
+ if (pathname.startsWith('/dist/')) {
1042
+ const filePath = path.join(distPath, pathname.slice(6));
1043
+ serveFile(filePath, res);
1044
+ return;
1045
+ }
1046
+
1047
+ // Serve WASM file
1048
+ if (pathname === '/ghostty-vt.wasm') {
1049
+ serveFile(wasmPath, res);
1050
+ return;
1051
+ }
1052
+
1053
+ // 404
1054
+ res.writeHead(404);
1055
+ res.end('Not Found');
1056
+ });
1057
+
1058
+ function serveFile(filePath, res) {
1059
+ const ext = path.extname(filePath);
1060
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
1061
+
1062
+ fs.readFile(filePath, (err, data) => {
1063
+ if (err) {
1064
+ res.writeHead(404);
1065
+ res.end('Not Found');
1066
+ return;
1067
+ }
1068
+ res.writeHead(200, { 'Content-Type': contentType });
1069
+ res.end(data);
1070
+ });
1071
+ }
1072
+
1073
+ // ============================================================================
1074
+ // WebSocket Server
1075
+ // ============================================================================
1076
+
1077
+ const sessions = new Map();
1078
+
1079
+ function getShell() {
1080
+ if (process.platform === 'win32') {
1081
+ return process.env.COMSPEC || 'cmd.exe';
1082
+ }
1083
+ return process.env.SHELL || '/bin/bash';
1084
+ }
1085
+
1086
+ function createPtySession(cols, rows) {
1087
+ const shell = getShell();
1088
+
1089
+ const ptyProcess = pty.spawn(shell, [], {
1090
+ name: 'xterm-256color',
1091
+ cols: cols,
1092
+ rows: rows,
1093
+ cwd: homedir(),
1094
+ env: {
1095
+ ...process.env,
1096
+ TERM: 'xterm-256color',
1097
+ COLORTERM: 'truecolor',
1098
+ },
1099
+ });
1100
+
1101
+ return ptyProcess;
1102
+ }
1103
+
1104
+ const wss = new WebSocketServer({ noServer: true });
1105
+
1106
+ httpServer.on('upgrade', (req, socket, head) => {
1107
+ const url = new URL(req.url, `http://${req.headers.host}`);
1108
+
1109
+ if (url.pathname === '/ws') {
1110
+ wss.handleUpgrade(req, socket, head, (ws) => {
1111
+ wss.emit('connection', ws, req);
1112
+ });
1113
+ } else {
1114
+ socket.destroy();
1115
+ }
1116
+ });
1117
+
1118
+ wss.on('connection', (ws, req) => {
1119
+ const url = new URL(req.url, `http://${req.headers.host}`);
1120
+ const cols = Number.parseInt(url.searchParams.get('cols') || '80');
1121
+ const rows = Number.parseInt(url.searchParams.get('rows') || '24');
1122
+
1123
+ const ptyProcess = createPtySession(cols, rows);
1124
+ sessions.set(ws, { pty: ptyProcess });
1125
+
1126
+ ptyProcess.onData((data) => {
1127
+ if (ws.readyState === ws.OPEN) {
1128
+ ws.send(data);
1129
+ }
1130
+ });
1131
+
1132
+ ptyProcess.onExit(({ exitCode }) => {
1133
+ if (ws.readyState === ws.OPEN) {
1134
+ ws.send(`\r\n\x1b[33mShell exited (code: ${exitCode})\x1b[0m\r\n`);
1135
+ ws.close();
1136
+ }
1137
+ });
1138
+
1139
+ ws.on('message', (data) => {
1140
+ const message = data.toString('utf8');
1141
+
1142
+ if (message.startsWith('{')) {
1143
+ try {
1144
+ const msg = JSON.parse(message);
1145
+ if (msg.type === 'resize') {
1146
+ ptyProcess.resize(msg.cols, msg.rows);
1147
+ return;
1148
+ }
1149
+ } catch (e) {
1150
+ // Not JSON, treat as input
1151
+ }
1152
+ }
1153
+
1154
+ ptyProcess.write(message);
1155
+ });
1156
+
1157
+ ws.on('close', () => {
1158
+ const session = sessions.get(ws);
1159
+ if (session) {
1160
+ session.pty.kill();
1161
+ sessions.delete(ws);
1162
+ }
1163
+ });
1164
+
1165
+ ws.on('error', () => {
1166
+ // Ignore socket errors
1167
+ });
1168
+ });
1169
+
1170
+ // ============================================================================
1171
+ // Startup
1172
+ // ============================================================================
1173
+
1174
+ function getLocalIPs() {
1175
+ const interfaces = networkInterfaces();
1176
+ const ips = [];
1177
+ for (const name of Object.keys(interfaces)) {
1178
+ for (const iface of interfaces[name] || []) {
1179
+ if (iface.family === 'IPv4' && !iface.internal) {
1180
+ ips.push(iface.address);
1181
+ }
1182
+ }
1183
+ }
1184
+ return ips;
1185
+ }
1186
+
1187
+ function printBanner(url) {
1188
+ const localIPs = getLocalIPs();
1189
+ // ANSI color codes
1190
+ const RESET = '\x1b[0m';
1191
+ const CYAN = '\x1b[36m'; // Labels
1192
+ const BEIGE = '\x1b[38;2;255;220;150m'; // Warm yellow/beige for values (RGB: 255,220,150)
1193
+ const DIM = '\x1b[2m'; // Dimmed text
1194
+
1195
+ // console.log('');
1196
+
1197
+ // Open: URL
1198
+ console.log(` ${CYAN}Open:${RESET} ${BEIGE}${url}${RESET}`);
1199
+
1200
+ // Network: URLs
1201
+ const network = [` ${CYAN}Network: ${RESET}`];
1202
+ if (localIPs.length > 0) {
1203
+ let networkCount = 0;
1204
+ for (const ip of localIPs) {
1205
+ networkCount++;
1206
+ const spaces = networkCount !== 1 ? ' ' : '';
1207
+ network.push(`${spaces}${BEIGE}http://${ip}:${HTTP_PORT}${RESET}\n`);
1208
+ }
1209
+ }
1210
+ console.log(`\n${network.join('')} `);
1211
+
1212
+ // Shell: path
1213
+ console.log(` ${CYAN}Shell:${RESET} ${BEIGE}${getShell()}${RESET}`);
1214
+
1215
+ console.log('');
1216
+
1217
+ // Home: path
1218
+ console.log(` ${CYAN}Home:${RESET} ${BEIGE}${homedir()}${RESET}`);
1219
+
1220
+ console.log('');
1221
+ console.log(` ${DIM}Press ctrl+c to stop.${RESET}\n`);
1222
+ }
1223
+
1224
+ process.on('SIGINT', () => {
1225
+ console.log('\n\nShutting down...');
1226
+ for (const [ws, session] of sessions.entries()) {
1227
+ session.pty.kill();
1228
+ ws.close();
1229
+ }
1230
+ wss.close();
1231
+ process.exit(0);
1232
+ });
1233
+
1234
+ httpServer.listen(HTTP_PORT, '0.0.0.0', async () => {
1235
+ // Display ASCII art banner
1236
+ try {
1237
+ const imagePath = path.join(__dirname, '..', 'bin', 'assets', 'ghosts.png');
1238
+ if (fs.existsSync(imagePath)) {
1239
+ // Welcome text with orange/yellow color (bright yellow, bold)
1240
+ console.log('\n \x1b[1;93mWelcome to Ghosttown!\x1b[0m\n');
1241
+ const art = await asciiArt(imagePath, { maxWidth: 80, maxHeight: 20 });
1242
+ console.log(art);
1243
+ console.log('');
1244
+ }
1245
+ } catch (err) {
1246
+ // Silently fail if ASCII art can't be displayed
1247
+ // This allows the server to start even if the image is missing
1248
+ }
1249
+
1250
+ printBanner(`http://localhost:${HTTP_PORT}`);
1251
+ });
1252
+ }
1253
+
1254
+ // ============================================================================
1255
+ // Main entry point
1256
+ // ============================================================================
1257
+
1258
+ export function run(argv) {
1259
+ const cliArgs = parseArgs(argv);
1260
+
1261
+ if (cliArgs.handled) {
1262
+ return;
1263
+ }
1264
+
1265
+ // If a command is provided, create a tmux session instead of starting server
1266
+ if (cliArgs.command) {
1267
+ createTmuxSession(cliArgs.command);
1268
+ // createTmuxSession spawns tmux attach and waits for it to exit
1269
+ // The script will exit when tmux attach exits (via the exit handler)
1270
+ // We must not continue to server code, so we stop here
1271
+ } else {
1272
+ // Server mode (no command provided)
1273
+ startWebServer(cliArgs);
1274
+ }
1275
+ }