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

Manager.ts

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