Repository navigation
Expand file tree
/
Copy pathterminal-server.ts
More file actions
442 lines (379 loc) · 11.2 KB
/
Copy pathterminal-server.ts
File metadata and controls
442 lines (379 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#!/usr/bin/env node
import { spawn } from "node:child_process";
import * as fs from "node:fs";
import * as net from "node:net";
import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import type { ServerEvent, ServerMessage, ServerRequest, ServerResponse } from "./messages.js";
import { TerminalManager } from "./terminal-manager.js";
// Read version from package.json
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const packageJsonPath = path.join(__dirname, "..", "package.json");
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
const SERVER_VERSION = packageJson.version;
export class TerminalServer {
private processManager = new TerminalManager();
private server?: net.Server;
private clients = new Map<string, net.Socket>();
private sessionSubscribers = new Map<string, Set<string>>(); // sessionId -> Set<clientId>
public readonly serverSocketPath = path.join(os.homedir(), ".terminalcp", "server.sock");
private clientCounter = 0;
constructor() {
// Ensure directory exists
const dir = path.dirname(this.serverSocketPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
/**
* Start the server
*/
async start(): Promise<void> {
// Remove existing socket file if it exists
if (fs.existsSync(this.serverSocketPath)) {
try {
fs.unlinkSync(this.serverSocketPath);
} catch (err) {
console.error("Failed to remove existing socket:", err);
}
}
return new Promise((resolve, reject) => {
this.server = net.createServer((socket) => {
this.handleClient(socket);
});
this.server.on("error", (err) => {
console.error("Server error:", err);
reject(err);
});
this.server.listen(this.serverSocketPath, () => {
console.error(`Terminal server listening at ${this.serverSocketPath}`);
// Set socket permissions to be user-only
fs.chmodSync(this.serverSocketPath, 0o600);
resolve();
});
});
}
/**
* Handle a new client connection
*/
private handleClient(socket: net.Socket): void {
const clientId = `client-${++this.clientCounter}`;
this.clients.set(clientId, socket);
let buffer = "";
socket.on("data", (data) => {
buffer += data.toString();
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (line.trim()) {
try {
const message: ServerRequest = JSON.parse(line);
this.handleMessage(clientId, message);
} catch (err) {
console.error(`Failed to parse message from ${clientId}:`, err);
this.sendError(clientId, "invalid-request", "Invalid JSON");
}
}
}
});
socket.on("close", () => {
this.clients.delete(clientId);
// Remove client from all session subscriptions
for (const subscribers of this.sessionSubscribers.values()) {
subscribers.delete(clientId);
}
});
socket.on("error", (err) => {
console.error(`Client ${clientId} error:`, err);
});
}
/**
* Handle a message from a client
*/
private async handleMessage(clientId: string, message: ServerRequest): Promise<void> {
const { id: requestId, args } = message;
if (!requestId || !args.action) {
this.sendError(clientId, requestId || "unknown", "Missing required fields");
return;
}
try {
let result: string | { rows: number; cols: number; rawOutput: string } = "";
switch (args.action) {
case "start": {
const { command, cwd, name } = args || {};
if (!command) {
throw new Error("Missing required field: command");
}
const sessionId = await this.processManager.start(command, { cwd, name });
// Register output handler for this session
this.processManager.onOutput(sessionId, (id, data) => {
this.broadcastEvent({
type: "event",
event: "output",
sessionId: id,
data,
});
});
// Auto-subscribe the creator to this session
if (!this.sessionSubscribers.has(sessionId)) {
this.sessionSubscribers.set(sessionId, new Set());
}
this.sessionSubscribers.get(sessionId)?.add(clientId);
result = sessionId;
break;
}
case "stop": {
const { id } = args || {};
if (!id) {
// Stop all
const processes = this.processManager.listProcesses();
let count = 0;
for (const proc of processes) {
this.processManager.offOutput(proc.id);
await this.processManager.stop(proc.id);
count++;
}
result = `stopped ${count} processes`;
} else {
this.processManager.offOutput(id);
await this.processManager.stop(id);
result = `stopped ${id}`;
}
break;
}
case "stdin": {
const { id, data } = args || {};
if (!id || data === undefined) {
throw new Error("Missing required fields: id, data");
}
await this.processManager.sendInput(id, data);
result = ""; // Return empty string for stdin
break;
}
case "stdout": {
const { id, lines } = args || {};
if (!id) {
throw new Error("Missing required field: id");
}
result = await this.processManager.getOutput(id, { lines });
break;
}
case "stream": {
const { id, since_last, strip_ansi } = args || {};
if (!id) {
throw new Error("Missing required field: id");
}
result = await this.processManager.getStream(id, { since_last, strip_ansi });
break;
}
case "list": {
const list = this.processManager.listProcesses();
const lines = list.map((p) => `${p.id} ${p.running ? "running" : "stopped"} ${p.cwd} ${p.command}`);
result = lines.join("\n");
break;
}
case "term-size": {
const { id } = args || {};
if (!id) {
throw new Error("Missing required field: id");
}
const size = this.processManager.getTerminalSize(id);
result = `${size.rows} ${size.cols} ${size.scrollback_lines}`;
break;
}
case "attach": {
const { id } = args || {};
if (!id) {
throw new Error("Missing required field: id");
}
const proc = this.processManager.getProcess(id);
if (!proc) {
throw new Error(`Process not found: ${id}`);
}
// Subscribe client to this session
if (!this.sessionSubscribers.has(id)) {
this.sessionSubscribers.set(id, new Set());
}
this.sessionSubscribers.get(id)?.add(clientId);
// Send initial terminal state
result = {
cols: proc.terminal.cols,
rows: proc.terminal.rows,
rawOutput: proc.rawOutput,
};
break;
}
case "resize": {
const { id, cols, rows } = args || {};
if (!id) {
throw new Error("Missing required field: id");
}
this.processManager.resizeTerminal(id, cols, rows);
// Broadcast resize to other clients
this.broadcastEvent({
type: "event",
event: "resize",
sessionId: id,
cols,
rows,
});
result = ""; // Return empty string for resize
break;
}
case "detach": {
const { id } = args || {};
if (!id) {
throw new Error("Missing required field: id");
}
// Unsubscribe client from session
const subscribers = this.sessionSubscribers.get(id);
if (subscribers) {
subscribers.delete(clientId);
}
result = "detached";
break;
}
case "kill-server": {
result = "shutting down";
// Send response before shutting down
this.sendResponse(clientId, requestId, result);
await this.shutdown();
return;
}
case "version": {
result = SERVER_VERSION;
break;
}
}
// Send response
this.sendResponse(clientId, requestId, result);
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
this.sendError(clientId, requestId, error);
}
}
/**
* Send a response to a client
*/
private sendResponse(clientId: string, requestId: string, result: ServerResponse["result"]): void {
const socket = this.clients.get(clientId);
if (!socket || socket.destroyed) return;
const response: ServerMessage = {
id: requestId,
type: "response",
result,
};
socket.write(`${JSON.stringify(response)}\n`);
}
/**
* Send an error response to a client
*/
private sendError(clientId: string, requestId: string, error: string): void {
const socket = this.clients.get(clientId);
if (!socket || socket.destroyed) return;
const response: ServerMessage = {
id: requestId,
type: "response",
error,
};
socket.write(`${JSON.stringify(response)}\n`);
}
private broadcastEvent(event: ServerEvent): void {
const subscribers = this.sessionSubscribers.get(event.sessionId);
if (!subscribers) return;
const messageStr = `${JSON.stringify(event)}\n`;
for (const clientId of subscribers) {
const socket = this.clients.get(clientId);
if (socket && !socket.destroyed) {
socket.write(messageStr);
}
}
}
/**
* Shutdown the server
*/
async shutdown(): Promise<void> {
console.error("Shutting down terminal server...");
// Stop all processes
await this.processManager.stopAll();
// Close all client connections
for (const socket of this.clients.values()) {
socket.end();
}
// Close the server
if (this.server) {
this.server.close();
}
// Remove the socket file
if (fs.existsSync(this.serverSocketPath)) {
try {
fs.unlinkSync(this.serverSocketPath);
} catch (_err) {
// Ignore if already removed
}
}
process.exit(0);
}
}
export async function startServer(): Promise<void> {
// Determine how to start the server
let command: string;
let args: string[];
// Check if we're running via tsx (development) or from dist
const scriptPath = new URL(import.meta.url).pathname;
const isTypescript = scriptPath.includes("/src/");
if (isTypescript) {
// Development mode: compile and run with node
// Use tsx directly as the command
const tsxPath = path.join(process.cwd(), "node_modules", ".bin", "tsx");
if (fs.existsSync(tsxPath)) {
command = tsxPath;
args = [path.join(path.dirname(scriptPath), "index.ts"), "--server"];
} else {
// Fallback to npx tsx
command = "npx";
args = ["tsx", path.join(path.dirname(scriptPath), "index.ts"), "--server"];
}
} else {
// Production mode: run the compiled JavaScript
command = process.execPath;
args = [path.join(path.dirname(scriptPath), "index.js"), "--server"];
}
const serverProcess = spawn(command, args, {
detached: true,
stdio: "ignore",
cwd: process.cwd(),
});
serverProcess.unref(); // Allow parent to exit independently
// Give the server a moment to start
await new Promise((resolve) => setTimeout(resolve, 100));
}
// If run directly, start the server
if (import.meta.url === `file://${process.argv[1]}`) {
const server = new TerminalServer();
server.start().catch((err) => {
console.error("Failed to start server:", err);
process.exit(1);
});
// Handle shutdown signals
process.on("SIGINT", async () => {
await server.shutdown();
});
process.on("SIGTERM", async () => {
await server.shutdown();
});
process.on("SIGQUIT", async () => {
await server.shutdown();
});
process.on("exit", () => {
// Last-ditch cleanup on any exit
if (fs.existsSync(server.serverSocketPath)) {
try {
fs.unlinkSync(server.serverSocketPath);
} catch (_err) {
// Ignore
}
}
});
}