Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Manager.ts

1,224 lines40.3 KB

1import { EventEmitter } from "node:events";
2import fs from "node:fs";
3import path from "node:path";
4​
5import {
6 DEFAULT_TERMINAL_ID,
7 TerminalClearInput,
8 TerminalCloseInput,
9 TerminalOpenInput,
10 TerminalResizeInput,
11 TerminalWriteInput,
12 type TerminalEvent,
13 type TerminalSessionSnapshot,
14} from "@t3tools/contracts";
15import { Effect, Encoding, Layer, Path, Schema } from "effect";
16​
17import { createLogger } from "../../logger";
18import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
19import { runProcess } from "../../processRunner";
20import { ServerConfig } from "../../config";
21import {
22 ShellCandidate,
23 TerminalError,
24 TerminalManager,
25 TerminalManagerShape,
26 TerminalSessionState,
27 TerminalStartInput,
28} from "../Services/Manager";
29​
30const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
31const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
32const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
33const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;
34const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
35const DEFAULT_OPEN_COLS = 120;
36const DEFAULT_OPEN_ROWS = 30;
37const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
38​
39const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
40const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
41const decodeTerminalResizeInput = Schema.decodeUnknownSync(TerminalResizeInput);
42const decodeTerminalClearInput = Schema.decodeUnknownSync(TerminalClearInput);
43const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
44​
45type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
46​
47function defaultShellResolver(): string {
48 if (process.platform === "win32") {
49 return process.env.ComSpec ?? "cmd.exe";
50 }
51 return process.env.SHELL ?? "bash";
53​
54function normalizeShellCommand(value: string | undefined): string | null {
55 if (!value) return null;
56 const trimmed = value.trim();
57 if (trimmed.length === 0) return null;
58​
59 if (process.platform === "win32") {
60 return trimmed;
61 }
62​
63 const firstToken = trimmed.split(/\s+/g)[0]?.trim();
64 if (!firstToken) return null;
65 return firstToken.replace(/^['"]|['"]$/g, "");
67​
68function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
69 if (!command || command.length === 0) return null;
70 const shellName = path.basename(command).toLowerCase();
71 if (process.platform !== "win32" && shellName === "zsh") {
72 return { shell: command, args: ["-o", "nopromptsp"] };
73 }
74 return { shell: command };
76​
77function formatShellCandidate(candidate: ShellCandidate): string {
78 if (!candidate.args || candidate.args.length === 0) return candidate.shell;
79 return `${candidate.shell} ${candidate.args.join(" ")}`;
81​
82function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
83 const seen = new Set<string>();
84 const ordered: ShellCandidate[] = [];
85 for (const candidate of candidates) {
86 if (!candidate) continue;
87 const key = formatShellCandidate(candidate);
88 if (seen.has(key)) continue;
89 seen.add(key);
90 ordered.push(candidate);
91 }
92 return ordered;
94​
95function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
96 const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
97​
98 if (process.platform === "win32") {
99 return uniqueShellCandidates([
100 requested,
101 shellCandidateFromCommand(process.env.ComSpec ?? null),
102 shellCandidateFromCommand("powershell.exe"),
103 shellCandidateFromCommand("cmd.exe"),
104 ]);
105 }
106​
107 return uniqueShellCandidates([
108 requested,
109 shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
110 shellCandidateFromCommand("/bin/zsh"),
111 shellCandidateFromCommand("/bin/bash"),
112 shellCandidateFromCommand("/bin/sh"),
113 shellCandidateFromCommand("zsh"),
114 shellCandidateFromCommand("bash"),
115 shellCandidateFromCommand("sh"),
116 ]);
118​
119function isRetryableShellSpawnError(error: unknown): boolean {
120 const queue: unknown[] = [error];
121 const seen = new Set<unknown>();
122 const messages: string[] = [];
123​
124 while (queue.length > 0) {
125 const current = queue.shift();
126 if (!current || seen.has(current)) {
127 continue;
128 }
129 seen.add(current);
130​
131 if (typeof current === "string") {
132 messages.push(current);
133 continue;
134 }
135​
136 if (current instanceof Error) {
137 messages.push(current.message);
138 const cause = (current as { cause?: unknown }).cause;
139 if (cause) {
140 queue.push(cause);
141 }
142 continue;
143 }
144​
145 if (typeof current === "object") {
146 const value = current as { message?: unknown; cause?: unknown };
147 if (typeof value.message === "string") {
148 messages.push(value.message);
149 }
150 if (value.cause) {
151 queue.push(value.cause);
152 }
153 }
154 }
155​
156 const message = messages.join(" ").toLowerCase();
157 return (
158 message.includes("posix_spawnp failed") ||
159 message.includes("enoent") ||
160 message.includes("not found") ||
161 message.includes("file not found") ||
162 message.includes("no such file")
163 );
165​
166async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
167 const command = [
168 `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
169 "if ($children) { exit 0 }",
170 "exit 1",
171 ].join("; ");
172 try {
173 const result = await runProcess(
174 "powershell.exe",
175 ["-NoProfile", "-NonInteractive", "-Command", command],
176 {
177 timeoutMs: 1_500,
178 allowNonZeroExit: true,
179 maxBufferBytes: 32_768,
180 outputMode: "truncate",
181 },
182 );
183 return result.code === 0;
184 } catch {
185 return false;
186 }
188​
189async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
190 try {
191 const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
192 timeoutMs: 1_000,
193 allowNonZeroExit: true,
194 maxBufferBytes: 32_768,
195 outputMode: "truncate",
196 });
197 if (pgrepResult.code === 0) {
198 return pgrepResult.stdout.trim().length > 0;
199 }
200 if (pgrepResult.code === 1) {
201 return false;
202 }
203 } catch {
204 // Fall back to ps when pgrep is unavailable.
205 }
206​
207 try {
208 const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
209 timeoutMs: 1_000,
210 allowNonZeroExit: true,
211 maxBufferBytes: 262_144,
212 outputMode: "truncate",
213 });
214 if (psResult.code !== 0) {
215 return false;
216 }
217​
218 for (const line of psResult.stdout.split(/\r?\n/g)) {
219 const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
220 const pid = Number(pidRaw);
221 const ppid = Number(ppidRaw);
222 if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
223 if (ppid === terminalPid) {
224 return true;
225 }
226 }
227 return false;
228 } catch {
229 return false;
230 }
232​
233async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
234 if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
235 return false;
236 }
237 if (process.platform === "win32") {
238 return checkWindowsSubprocessActivity(terminalPid);
239 }
240 return checkPosixSubprocessActivity(terminalPid);
242​
243function capHistory(history: string, maxLines: number): string {
244 if (history.length === 0) return history;
245 const hasTrailingNewline = history.endsWith("\n");
246 const lines = history.split("\n");
247 if (hasTrailingNewline) {
248 lines.pop();
249 }
250 if (lines.length <= maxLines) return history;
251 const capped = lines.slice(lines.length - maxLines).join("\n");
252 return hasTrailingNewline ? `${capped}\n` : capped;
254​
255function legacySafeThreadId(threadId: string): string {
256 return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
258​
259function toSafeThreadId(threadId: string): string {
260 return `terminal_${Encoding.encodeBase64Url(threadId)}`;
262​
263function toSafeTerminalId(terminalId: string): string {
264 return Encoding.encodeBase64Url(terminalId);
266​
267function toSessionKey(threadId: string, terminalId: string): string {
268 return `${threadId}\u0000${terminalId}`;
270​
271function shouldExcludeTerminalEnvKey(key: string): boolean {
272 const normalizedKey = key.toUpperCase();
273 if (normalizedKey.startsWith("T3CODE_")) {
274 return true;
275 }
276 if (normalizedKey.startsWith("VITE_")) {
277 return true;
278 }
279 return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
281​
282function createTerminalSpawnEnv(
283 baseEnv: NodeJS.ProcessEnv,
284 runtimeEnv?: Record<string, string> | null,
285): NodeJS.ProcessEnv {
286 const spawnEnv: NodeJS.ProcessEnv = {};
287 for (const [key, value] of Object.entries(baseEnv)) {
288 if (value === undefined) continue;
289 if (shouldExcludeTerminalEnvKey(key)) continue;
290 spawnEnv[key] = value;
291 }
292 if (runtimeEnv) {
293 for (const [key, value] of Object.entries(runtimeEnv)) {
294 spawnEnv[key] = value;
295 }
296 }
297 return spawnEnv;
299​
300function normalizedRuntimeEnv(
301 env: Record<string, string> | undefined,
302): Record<string, string> | null {
303 if (!env) return null;
304 const entries = Object.entries(env);
305 if (entries.length === 0) return null;
306 return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right)));
308​
309interface TerminalManagerEvents {
310 event: [event: TerminalEvent];
312​
313interface TerminalManagerOptions {
314 logsDir?: string;
315 historyLineLimit?: number;
316 ptyAdapter: PtyAdapterShape;
317 shellResolver?: () => string;
318 subprocessChecker?: TerminalSubprocessChecker;
319 subprocessPollIntervalMs?: number;
320 processKillGraceMs?: number;
321 maxRetainedInactiveSessions?: number;
323​
324export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents> {
325 private readonly sessions = new Map<string, TerminalSessionState>();
326 private readonly logsDir: string;
327 private readonly historyLineLimit: number;
328 private readonly ptyAdapter: PtyAdapterShape;
329 private readonly shellResolver: () => string;
330 private readonly persistQueues = new Map<string, Promise<void>>();
331 private readonly persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
332 private readonly pendingPersistHistory = new Map<string, string>();
333 private readonly threadLocks = new Map<string, Promise<void>>();
334 private readonly persistDebounceMs: number;
335 private readonly subprocessChecker: TerminalSubprocessChecker;
336 private readonly subprocessPollIntervalMs: number;
337 private readonly processKillGraceMs: number;
338 private readonly maxRetainedInactiveSessions: number;
339 private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
340 private subprocessPollInFlight = false;
341 private readonly killEscalationTimers = new Map<PtyProcess, ReturnType<typeof setTimeout>>();
342 private readonly logger = createLogger("terminal");
343​
344 constructor(options: TerminalManagerOptions) {
345 super();
346 this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
347 this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
348 this.ptyAdapter = options.ptyAdapter;
349 this.shellResolver = options.shellResolver ?? defaultShellResolver;
350 this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
351 this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
352 this.subprocessPollIntervalMs =
353 options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
354 this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
355 this.maxRetainedInactiveSessions =
356 options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
357 fs.mkdirSync(this.logsDir, { recursive: true });
358 }
359​
360 async open(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
361 const input = decodeTerminalOpenInput(raw);
362 return this.runWithThreadLock(input.threadId, async () => {
363 await this.assertValidCwd(input.cwd);
364​
365 const sessionKey = toSessionKey(input.threadId, input.terminalId);
366 const existing = this.sessions.get(sessionKey);
367 if (!existing) {
368 await this.flushPersistQueue(input.threadId, input.terminalId);
369 const history = await this.readHistory(input.threadId, input.terminalId);
370 const cols = input.cols ?? DEFAULT_OPEN_COLS;
371 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
372 const session: TerminalSessionState = {
373 threadId: input.threadId,
374 terminalId: input.terminalId,
375 cwd: input.cwd,
376 status: "starting",
377 pid: null,
378 history,
379 exitCode: null,
380 exitSignal: null,
381 updatedAt: new Date().toISOString(),
382 cols,
383 rows,
384 process: null,
385 unsubscribeData: null,
386 unsubscribeExit: null,
387 hasRunningSubprocess: false,
388 runtimeEnv: normalizedRuntimeEnv(input.env),
389 };
390 this.sessions.set(sessionKey, session);
391 this.evictInactiveSessionsIfNeeded();
392 await this.startSession(session, { ...input, cols, rows }, "started");
393 return this.snapshot(session);
394 }
395​
396 const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
397 const currentRuntimeEnv = existing.runtimeEnv;
398 const targetCols = input.cols ?? existing.cols;
399 const targetRows = input.rows ?? existing.rows;
400 const runtimeEnvChanged =
401 JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv);
402​
403 if (existing.cwd !== input.cwd || runtimeEnvChanged) {
404 this.stopProcess(existing);
405 existing.cwd = input.cwd;
406 existing.runtimeEnv = nextRuntimeEnv;
407 existing.history = "";
408 await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
409 } else if (existing.status === "exited" || existing.status === "error") {
410 existing.runtimeEnv = nextRuntimeEnv;
411 existing.history = "";
412 await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
413 } else if (currentRuntimeEnv !== nextRuntimeEnv) {
414 existing.runtimeEnv = nextRuntimeEnv;
415 }
416​
417 if (!existing.process) {
418 await this.startSession(
419 existing,
420 { ...input, cols: targetCols, rows: targetRows },
421 "started",
422 );
423 return this.snapshot(existing);
424 }
425​
426 if (existing.cols !== targetCols || existing.rows !== targetRows) {
427 existing.cols = targetCols;
428 existing.rows = targetRows;
429 existing.process.resize(targetCols, targetRows);
430 existing.updatedAt = new Date().toISOString();
431 }
432​
433 return this.snapshot(existing);
434 });
435 }
436​
437 async write(raw: TerminalWriteInput): Promise<void> {
438 const input = decodeTerminalWriteInput(raw);
439 const session = this.requireSession(input.threadId, input.terminalId);
440 if (!session.process || session.status !== "running") {
441 if (session.status === "exited") {
442 return;
443 }
444 throw new Error(
445 `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
446 );
447 }
448 session.process.write(input.data);
449 }
450​
451 async resize(raw: TerminalResizeInput): Promise<void> {
452 const input = decodeTerminalResizeInput(raw);
453 const session = this.requireSession(input.threadId, input.terminalId);
454 if (!session.process || session.status !== "running") {
455 throw new Error(
456 `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
457 );
458 }
459 session.cols = input.cols;
460 session.rows = input.rows;
461 session.updatedAt = new Date().toISOString();
462 session.process.resize(input.cols, input.rows);
463 }
464​
465 async clear(raw: TerminalClearInput): Promise<void> {
466 const input = decodeTerminalClearInput(raw);
467 await this.runWithThreadLock(input.threadId, async () => {
468 const session = this.requireSession(input.threadId, input.terminalId);
469 session.history = "";
470 session.updatedAt = new Date().toISOString();
471 await this.persistHistory(input.threadId, input.terminalId, session.history);
472 this.emitEvent({
473 type: "cleared",
474 threadId: input.threadId,
475 terminalId: input.terminalId,
476 createdAt: new Date().toISOString(),
477 });
478 });
479 }
480​
481 async restart(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
482 const input = decodeTerminalOpenInput(raw);
483 return this.runWithThreadLock(input.threadId, async () => {
484 await this.assertValidCwd(input.cwd);
485​
486 const sessionKey = toSessionKey(input.threadId, input.terminalId);
487 let session = this.sessions.get(sessionKey);
488 if (!session) {
489 const cols = input.cols ?? DEFAULT_OPEN_COLS;
490 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
491 session = {
492 threadId: input.threadId,
493 terminalId: input.terminalId,
494 cwd: input.cwd,
495 status: "starting",
496 pid: null,
497 history: "",
498 exitCode: null,
499 exitSignal: null,
500 updatedAt: new Date().toISOString(),
501 cols,
502 rows,
503 process: null,
504 unsubscribeData: null,
505 unsubscribeExit: null,
506 hasRunningSubprocess: false,
507 runtimeEnv: normalizedRuntimeEnv(input.env),
508 };
509 this.sessions.set(sessionKey, session);
510 this.evictInactiveSessionsIfNeeded();
511 } else {
512 this.stopProcess(session);
513 session.cwd = input.cwd;
514 session.runtimeEnv = normalizedRuntimeEnv(input.env);
515 }
516​
517 const cols = input.cols ?? session.cols;
518 const rows = input.rows ?? session.rows;
519​
520 session.history = "";
521 await this.persistHistory(input.threadId, input.terminalId, session.history);
522 await this.startSession(session, { ...input, cols, rows }, "restarted");
523 return this.snapshot(session);
524 });
525 }
526​
527 async close(raw: TerminalCloseInput): Promise<void> {
528 const input = decodeTerminalCloseInput(raw);
529 await this.runWithThreadLock(input.threadId, async () => {
530 if (input.terminalId) {
531 await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
532 return;
533 }
534​
535 const threadSessions = this.sessionsForThread(input.threadId);
536 for (const session of threadSessions) {
537 this.stopProcess(session);
538 this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
539 }
540 await Promise.all(
541 threadSessions.map((session) =>
542 this.flushPersistQueue(session.threadId, session.terminalId),
543 ),
544 );
545​
546 if (input.deleteHistory) {
547 await this.deleteAllHistoryForThread(input.threadId);
548 }
549 this.updateSubprocessPollingState();
550 });
551 }
552​
553 dispose(): void {
554 this.stopSubprocessPolling();
555 const sessions = [...this.sessions.values()];
556 this.sessions.clear();
557 for (const session of sessions) {
558 this.stopProcess(session);
559 }
560 for (const timer of this.persistTimers.values()) {
561 clearTimeout(timer);
562 }
563 this.persistTimers.clear();
564 for (const timer of this.killEscalationTimers.values()) {
565 clearTimeout(timer);
566 }
567 this.killEscalationTimers.clear();
568 this.pendingPersistHistory.clear();
569 this.threadLocks.clear();
570 this.persistQueues.clear();
571 }
572​
573 private async startSession(
574 session: TerminalSessionState,
575 input: TerminalStartInput,
576 eventType: "started" | "restarted",
577 ): Promise<void> {
578 this.stopProcess(session);
579​
580 session.status = "starting";
581 session.cwd = input.cwd;
582 session.cols = input.cols;
583 session.rows = input.rows;
584 session.exitCode = null;
585 session.exitSignal = null;
586 session.hasRunningSubprocess = false;
587 session.updatedAt = new Date().toISOString();
588​
589 let ptyProcess: PtyProcess | null = null;
590 let startedShell: string | null = null;
591 try {
592 const shellCandidates = resolveShellCandidates(this.shellResolver);
593 const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
594 let lastSpawnError: unknown = null;
595​
596 const spawnWithCandidate = (candidate: ShellCandidate) =>
597 Effect.runPromise(
598 this.ptyAdapter.spawn({
599 shell: candidate.shell,
600 ...(candidate.args ? { args: candidate.args } : {}),
601 cwd: session.cwd,
602 cols: session.cols,
603 rows: session.rows,
604 env: terminalEnv,
605 }),
606 );
607​
608 const trySpawn = async (
609 candidates: ShellCandidate[],
610 index = 0,
611 ): Promise<{ process: PtyProcess; shellLabel: string } | null> => {
612 if (index >= candidates.length) {
613 return null;
614 }
615 const candidate = candidates[index];
616 if (!candidate) {
617 return null;
618 }
619​
620 try {
621 const process = await spawnWithCandidate(candidate);
622 return { process, shellLabel: formatShellCandidate(candidate) };
623 } catch (error) {
624 lastSpawnError = error;
625 if (!isRetryableShellSpawnError(error)) {
626 throw error;
627 }
628 return trySpawn(candidates, index + 1);
629 }
630 };
631​
632 const spawnResult = await trySpawn(shellCandidates);
633 if (spawnResult) {
634 ptyProcess = spawnResult.process;
635 startedShell = spawnResult.shellLabel;
636 }
637​
638 if (!ptyProcess) {
639 const detail =
640 lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
641 const tried =
642 shellCandidates.length > 0
643 ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
644 : "";
645 throw new Error(`${detail}.${tried}`.trim());
646 }
647​
648 session.process = ptyProcess;
649 session.pid = ptyProcess.pid;
650 session.status = "running";
651 session.updatedAt = new Date().toISOString();
652 session.unsubscribeData = ptyProcess.onData((data) => {
653 this.onProcessData(session, data);
654 });
655 session.unsubscribeExit = ptyProcess.onExit((event) => {
656 this.onProcessExit(session, event);
657 });
658 this.updateSubprocessPollingState();
659 this.emitEvent({
660 type: eventType,
661 threadId: session.threadId,
662 terminalId: session.terminalId,
663 createdAt: new Date().toISOString(),
664 snapshot: this.snapshot(session),
665 });
666 } catch (error) {
667 if (ptyProcess) {
668 this.killProcessWithEscalation(ptyProcess, session.threadId, session.terminalId);
669 }
670 session.status = "error";
671 session.pid = null;
672 session.process = null;
673 session.hasRunningSubprocess = false;
674 session.updatedAt = new Date().toISOString();
675 this.evictInactiveSessionsIfNeeded();
676 this.updateSubprocessPollingState();
677 const message = error instanceof Error ? error.message : "Terminal start failed";
678 this.emitEvent({
679 type: "error",
680 threadId: session.threadId,
681 terminalId: session.terminalId,
682 createdAt: new Date().toISOString(),
683 message,
684 });
685 this.logger.error("failed to start terminal", {
686 threadId: session.threadId,
687 terminalId: session.terminalId,
688 error: message,
689 ...(startedShell ? { shell: startedShell } : {}),
690 });
691 }
692 }
693​
694 private onProcessData(session: TerminalSessionState, data: string): void {
695 session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
696 session.updatedAt = new Date().toISOString();
697 this.queuePersist(session.threadId, session.terminalId, session.history);
698 this.emitEvent({
699 type: "output",
700 threadId: session.threadId,
701 terminalId: session.terminalId,
702 createdAt: new Date().toISOString(),
703 data,
704 });
705 }
706​
707 private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void {
708 this.clearKillEscalationTimer(session.process);
709 this.cleanupProcessHandles(session);
710 session.process = null;
711 session.pid = null;
712 session.hasRunningSubprocess = false;
713 session.status = "exited";
714 session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
715 session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
716 session.updatedAt = new Date().toISOString();
717 this.emitEvent({
718 type: "exited",
719 threadId: session.threadId,
720 terminalId: session.terminalId,
721 createdAt: new Date().toISOString(),
722 exitCode: session.exitCode,
723 exitSignal: session.exitSignal,
724 });
725 this.evictInactiveSessionsIfNeeded();
726 this.updateSubprocessPollingState();
727 }
728​
729 private stopProcess(session: TerminalSessionState): void {
730 const process = session.process;
731 if (!process) return;
732 this.cleanupProcessHandles(session);
733 session.process = null;
734 session.pid = null;
735 session.hasRunningSubprocess = false;
736 session.status = "exited";
737 session.updatedAt = new Date().toISOString();
738 this.killProcessWithEscalation(process, session.threadId, session.terminalId);
739 this.evictInactiveSessionsIfNeeded();
740 this.updateSubprocessPollingState();
741 }
742​
743 private cleanupProcessHandles(session: TerminalSessionState): void {
744 session.unsubscribeData?.();
745 session.unsubscribeData = null;
746 session.unsubscribeExit?.();
747 session.unsubscribeExit = null;
748 }
749​
750 private clearKillEscalationTimer(process: PtyProcess | null): void {
751 if (!process) return;
752 const timer = this.killEscalationTimers.get(process);
753 if (!timer) return;
754 clearTimeout(timer);
755 this.killEscalationTimers.delete(process);
756 }
757​
758 private killProcessWithEscalation(
759 process: PtyProcess,
760 threadId: string,
761 terminalId: string,
762 ): void {
763 this.clearKillEscalationTimer(process);
764 try {
765 process.kill("SIGTERM");
766 } catch (error) {
767 const message = error instanceof Error ? error.message : String(error);
768 this.logger.warn("failed to kill terminal process", {
769 threadId,
770 terminalId,
771 signal: "SIGTERM",
772 error: message,
773 });
774 return;
775 }
776​
777 const timer = setTimeout(() => {
778 this.killEscalationTimers.delete(process);
779 try {
780 process.kill("SIGKILL");
781 } catch (error) {
782 const message = error instanceof Error ? error.message : String(error);
783 this.logger.warn("failed to force-kill terminal process", {
784 threadId,
785 terminalId,
786 signal: "SIGKILL",
787 error: message,
788 });
789 }
790 }, this.processKillGraceMs);
791 timer.unref?.();
792 this.killEscalationTimers.set(process, timer);
793 }
794​
795 private evictInactiveSessionsIfNeeded(): void {
796 const inactiveSessions = [...this.sessions.values()].filter(
797 (session) => session.status !== "running",
798 );
799 if (inactiveSessions.length <= this.maxRetainedInactiveSessions) {
800 return;
801 }
802​
803 inactiveSessions.sort(
804 (left, right) =>
805 left.updatedAt.localeCompare(right.updatedAt) ||
806 left.threadId.localeCompare(right.threadId) ||
807 left.terminalId.localeCompare(right.terminalId),
808 );
809 const toEvict = inactiveSessions.length - this.maxRetainedInactiveSessions;
810 for (const session of inactiveSessions.slice(0, toEvict)) {
811 const key = toSessionKey(session.threadId, session.terminalId);
812 this.sessions.delete(key);
813 this.clearPersistTimer(session.threadId, session.terminalId);
814 this.pendingPersistHistory.delete(key);
815 this.persistQueues.delete(key);
816 this.clearKillEscalationTimer(session.process);
817 }
818 }
819​
820 private queuePersist(threadId: string, terminalId: string, history: string): void {
821 const persistenceKey = toSessionKey(threadId, terminalId);
822 this.pendingPersistHistory.set(persistenceKey, history);
823 this.schedulePersist(threadId, terminalId);
824 }
825​
826 private async persistHistory(
827 threadId: string,
828 terminalId: string,
829 history: string,
830 ): Promise<void> {
831 const persistenceKey = toSessionKey(threadId, terminalId);
832 this.clearPersistTimer(threadId, terminalId);
833 this.pendingPersistHistory.delete(persistenceKey);
834 await this.enqueuePersistWrite(threadId, terminalId, history);
835 }
836​
837 private enqueuePersistWrite(
838 threadId: string,
839 terminalId: string,
840 history: string,
841 ): Promise<void> {
842 const persistenceKey = toSessionKey(threadId, terminalId);
843 const task = async () => {
844 await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
845 };
846 const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
847 const next = previous
848 .catch(() => undefined)
849 .then(task)
850 .catch((error) => {
851 this.logger.warn("failed to persist terminal history", {
852 threadId,
853 terminalId,
854 error: error instanceof Error ? error.message : String(error),
855 });
856 });
857 this.persistQueues.set(persistenceKey, next);
858 const finalized = next.finally(() => {
859 if (this.persistQueues.get(persistenceKey) === next) {
860 this.persistQueues.delete(persistenceKey);
861 }
862 if (
863 this.pendingPersistHistory.has(persistenceKey) &&
864 !this.persistTimers.has(persistenceKey)
865 ) {
866 this.schedulePersist(threadId, terminalId);
867 }
868 });
869 void finalized.catch(() => undefined);
870 return finalized;
871 }
872​
873 private schedulePersist(threadId: string, terminalId: string): void {
874 const persistenceKey = toSessionKey(threadId, terminalId);
875 if (this.persistTimers.has(persistenceKey)) return;
876 const timer = setTimeout(() => {
877 this.persistTimers.delete(persistenceKey);
878 const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
879 if (pendingHistory === undefined) return;
880 this.pendingPersistHistory.delete(persistenceKey);
881 void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
882 }, this.persistDebounceMs);
883 this.persistTimers.set(persistenceKey, timer);
884 }
885​
886 private clearPersistTimer(threadId: string, terminalId: string): void {
887 const persistenceKey = toSessionKey(threadId, terminalId);
888 const timer = this.persistTimers.get(persistenceKey);
889 if (!timer) return;
890 clearTimeout(timer);
891 this.persistTimers.delete(persistenceKey);
892 }
893​
894 private async readHistory(threadId: string, terminalId: string): Promise<string> {
895 const nextPath = this.historyPath(threadId, terminalId);
896 try {
897 const raw = await fs.promises.readFile(nextPath, "utf8");
898 const capped = capHistory(raw, this.historyLineLimit);
899 if (capped !== raw) {
900 await fs.promises.writeFile(nextPath, capped, "utf8");
901 }
902 return capped;
903 } catch (error) {
904 if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
905 throw error;
906 }
907 }
908​
909 if (terminalId !== DEFAULT_TERMINAL_ID) {
910 return "";
911 }
912​
913 const legacyPath = this.legacyHistoryPath(threadId);
914 try {
915 const raw = await fs.promises.readFile(legacyPath, "utf8");
916 const capped = capHistory(raw, this.historyLineLimit);
917​
918 // Migrate legacy transcript filename to the terminal-scoped path.
919 await fs.promises.writeFile(nextPath, capped, "utf8");
920 try {
921 await fs.promises.rm(legacyPath, { force: true });
922 } catch (cleanupError) {
923 this.logger.warn("failed to remove legacy terminal history", {
924 threadId,
925 error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
926 });
927 }
928​
929 return capped;
930 } catch (error) {
931 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
932 return "";
933 }
934 throw error;
935 }
936 }
937​
938 private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
939 const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
940 if (terminalId === DEFAULT_TERMINAL_ID) {
941 deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
942 }
943 try {
944 await Promise.all(deletions);
945 } catch (error) {
946 this.logger.warn("failed to delete terminal history", {
947 threadId,
948 terminalId,
949 error: error instanceof Error ? error.message : String(error),
950 });
951 }
952 }
953​
954 private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
955 const persistenceKey = toSessionKey(threadId, terminalId);
956 this.clearPersistTimer(threadId, terminalId);
957​
958 while (true) {
959 const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
960 if (pendingHistory !== undefined) {
961 this.pendingPersistHistory.delete(persistenceKey);
962 await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
963 }
964​
965 const pending = this.persistQueues.get(persistenceKey);
966 if (!pending) {
967 return;
968 }
969 await pending.catch(() => undefined);
970 }
971 }
972​
973 private updateSubprocessPollingState(): void {
974 const hasRunningSessions = [...this.sessions.values()].some(
975 (session) => session.status === "running" && session.pid !== null,
976 );
977 if (hasRunningSessions) {
978 this.ensureSubprocessPolling();
979 return;
980 }
981 this.stopSubprocessPolling();
982 }
983​
984 private ensureSubprocessPolling(): void {
985 if (this.subprocessPollTimer) return;
986 this.subprocessPollTimer = setInterval(() => {
987 void this.pollSubprocessActivity();
988 }, this.subprocessPollIntervalMs);
989 this.subprocessPollTimer.unref?.();
990 void this.pollSubprocessActivity();
991 }
992​
993 private stopSubprocessPolling(): void {
994 if (!this.subprocessPollTimer) return;
995 clearInterval(this.subprocessPollTimer);
996 this.subprocessPollTimer = null;
997 }
998​
999 private async pollSubprocessActivity(): Promise<void> {
1000 if (this.subprocessPollInFlight) return;
1001​
1002 const runningSessions = [...this.sessions.values()].filter(
1003 (session): session is TerminalSessionState & { pid: number } =>
1004 session.status === "running" && Number.isInteger(session.pid),
1005 );
1006 if (runningSessions.length === 0) {
1007 this.stopSubprocessPolling();
1008 return;
1010​
1011 this.subprocessPollInFlight = true;
1012 try {
1013 await Promise.all(
1014 runningSessions.map(async (session) => {
1015 const terminalPid = session.pid;
1016 let hasRunningSubprocess = false;
1017 try {
1018 hasRunningSubprocess = await this.subprocessChecker(terminalPid);
1019 } catch (error) {
1020 this.logger.warn("failed to check terminal subprocess activity", {
1021 threadId: session.threadId,
1022 terminalId: session.terminalId,
1023 terminalPid,
1024 error: error instanceof Error ? error.message : String(error),
1025 });
1026 return;
1028​
1029 const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
1030 if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
1031 return;
1033 if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
1034 return;
1036​
1037 liveSession.hasRunningSubprocess = hasRunningSubprocess;
1038 liveSession.updatedAt = new Date().toISOString();
1039 this.emitEvent({
1040 type: "activity",
1041 threadId: liveSession.threadId,
1042 terminalId: liveSession.terminalId,
1043 createdAt: new Date().toISOString(),
1044 hasRunningSubprocess,
1045 });
1046 }),
1047 );
1048 } finally {
1049 this.subprocessPollInFlight = false;
1052​
1053 private async assertValidCwd(cwd: string): Promise<void> {
1054 let stats: fs.Stats;
1055 try {
1056 stats = await fs.promises.stat(cwd);
1057 } catch (error) {
1058 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
1059 throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error });
1061 throw error;
1063 if (!stats.isDirectory()) {
1064 throw new Error(`Terminal cwd is not a directory: ${cwd}`);
1067​
1068 private async closeSession(
1069 threadId: string,
1070 terminalId: string,
1071 deleteHistory: boolean,
1072 ): Promise<void> {
1073 const key = toSessionKey(threadId, terminalId);
1074 const session = this.sessions.get(key);
1075 if (session) {
1076 this.stopProcess(session);
1077 this.sessions.delete(key);
1079 this.updateSubprocessPollingState();
1080 await this.flushPersistQueue(threadId, terminalId);
1081 if (deleteHistory) {
1082 await this.deleteHistory(threadId, terminalId);
1085​
1086 private sessionsForThread(threadId: string): TerminalSessionState[] {
1087 return [...this.sessions.values()].filter((session) => session.threadId === threadId);
1089​
1090 private async deleteAllHistoryForThread(threadId: string): Promise<void> {
1091 const threadPrefix = `${toSafeThreadId(threadId)}_`;
1092 try {
1093 const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
1094 const removals = entries
1095 .filter((entry) => entry.isFile())
1096 .map((entry) => entry.name)
1097 .filter(
1098 (name) =>
1099 name === `${toSafeThreadId(threadId)}.log` ||
1100 name === `${legacySafeThreadId(threadId)}.log` ||
1101 name.startsWith(threadPrefix),
1103 .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
1104 await Promise.all(removals);
1105 } catch (error) {
1106 this.logger.warn("failed to delete terminal histories for thread", {
1107 threadId,
1108 error: error instanceof Error ? error.message : String(error),
1109 });
1112​
1113 private requireSession(threadId: string, terminalId: string): TerminalSessionState {
1114 const session = this.sessions.get(toSessionKey(threadId, terminalId));
1115 if (!session) {
1116 throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
1118 return session;
1120​
1121 private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
1122 return {
1123 threadId: session.threadId,
1124 terminalId: session.terminalId,
1125 cwd: session.cwd,
1126 status: session.status,
1127 pid: session.pid,
1128 history: session.history,
1129 exitCode: session.exitCode,
1130 exitSignal: session.exitSignal,
1131 updatedAt: session.updatedAt,
1132 };
1134​
1135 private emitEvent(event: TerminalEvent): void {
1136 this.emit("event", event);
1138​
1139 private historyPath(threadId: string, terminalId: string): string {
1140 const threadPart = toSafeThreadId(threadId);
1141 if (terminalId === DEFAULT_TERMINAL_ID) {
1142 return path.join(this.logsDir, `${threadPart}.log`);
1144 return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
1146​
1147 private legacyHistoryPath(threadId: string): string {
1148 return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
1150​
1151 private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
1152 const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
1153 let release!: () => void;
1154 const current = new Promise<void>((resolve) => {
1155 release = resolve;
1156 });
1157 this.threadLocks.set(threadId, current);
1158 await previous.catch(() => undefined);
1159 try {
1160 return await task();
1161 } finally {
1162 release();
1163 if (this.threadLocks.get(threadId) === current) {
1164 this.threadLocks.delete(threadId);
1169​
1170export const TerminalManagerLive = Layer.effect(
1171 TerminalManager,
1172 Effect.gen(function* () {
1173 const { stateDir } = yield* ServerConfig;
1174 const { join } = yield* Path.Path;
1175 const logsDir = join(stateDir, "logs", "terminals");
1176​
1177 const ptyAdapter = yield* PtyAdapter;
1178 const runtime = yield* Effect.acquireRelease(
1179 Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
1180 (r) => Effect.sync(() => r.dispose()),
1181 );
1182​
1183 return {
1184 open: (input) =>
1185 Effect.tryPromise({
1186 try: () => runtime.open(input),
1187 catch: (cause) => new TerminalError({ message: "Failed to open terminal", cause }),
1188 }),
1189 write: (input) =>
1190 Effect.tryPromise({
1191 try: () => runtime.write(input),
1192 catch: (cause) => new TerminalError({ message: "Failed to write to terminal", cause }),
1193 }),
1194 resize: (input) =>
1195 Effect.tryPromise({
1196 try: () => runtime.resize(input),
1197 catch: (cause) => new TerminalError({ message: "Failed to resize terminal", cause }),
1198 }),
1199 clear: (input) =>
1200 Effect.tryPromise({
1201 try: () => runtime.clear(input),
1202 catch: (cause) => new TerminalError({ message: "Failed to clear terminal", cause }),
1203 }),
1204 restart: (input) =>
1205 Effect.tryPromise({
1206 try: () => runtime.restart(input),
1207 catch: (cause) => new TerminalError({ message: "Failed to restart terminal", cause }),
1208 }),
1209 close: (input) =>
1210 Effect.tryPromise({
1211 try: () => runtime.close(input),
1212 catch: (cause) => new TerminalError({ message: "Failed to close terminal", cause }),
1213 }),
1214 subscribe: (listener) =>
1215 Effect.sync(() => {
1216 runtime.on("event", listener);
1217 return () => {
1218 runtime.off("event", listener);
1219 };
1220 }),
1221 dispose: Effect.sync(() => runtime.dispose()),
1222 } satisfies TerminalManagerShape;
1223 }),