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

Manager.ts

1,221 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 throw new Error(
442 `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
443 );
444 }
445 session.process.write(input.data);
446 }
447​
448 async resize(raw: TerminalResizeInput): Promise<void> {
449 const input = decodeTerminalResizeInput(raw);
450 const session = this.requireSession(input.threadId, input.terminalId);
451 if (!session.process || session.status !== "running") {
452 throw new Error(
453 `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
454 );
455 }
456 session.cols = input.cols;
457 session.rows = input.rows;
458 session.updatedAt = new Date().toISOString();
459 session.process.resize(input.cols, input.rows);
460 }
461​
462 async clear(raw: TerminalClearInput): Promise<void> {
463 const input = decodeTerminalClearInput(raw);
464 await this.runWithThreadLock(input.threadId, async () => {
465 const session = this.requireSession(input.threadId, input.terminalId);
466 session.history = "";
467 session.updatedAt = new Date().toISOString();
468 await this.persistHistory(input.threadId, input.terminalId, session.history);
469 this.emitEvent({
470 type: "cleared",
471 threadId: input.threadId,
472 terminalId: input.terminalId,
473 createdAt: new Date().toISOString(),
474 });
475 });
476 }
477​
478 async restart(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
479 const input = decodeTerminalOpenInput(raw);
480 return this.runWithThreadLock(input.threadId, async () => {
481 await this.assertValidCwd(input.cwd);
482​
483 const sessionKey = toSessionKey(input.threadId, input.terminalId);
484 let session = this.sessions.get(sessionKey);
485 if (!session) {
486 const cols = input.cols ?? DEFAULT_OPEN_COLS;
487 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
488 session = {
489 threadId: input.threadId,
490 terminalId: input.terminalId,
491 cwd: input.cwd,
492 status: "starting",
493 pid: null,
494 history: "",
495 exitCode: null,
496 exitSignal: null,
497 updatedAt: new Date().toISOString(),
498 cols,
499 rows,
500 process: null,
501 unsubscribeData: null,
502 unsubscribeExit: null,
503 hasRunningSubprocess: false,
504 runtimeEnv: normalizedRuntimeEnv(input.env),
505 };
506 this.sessions.set(sessionKey, session);
507 this.evictInactiveSessionsIfNeeded();
508 } else {
509 this.stopProcess(session);
510 session.cwd = input.cwd;
511 session.runtimeEnv = normalizedRuntimeEnv(input.env);
512 }
513​
514 const cols = input.cols ?? session.cols;
515 const rows = input.rows ?? session.rows;
516​
517 session.history = "";
518 await this.persistHistory(input.threadId, input.terminalId, session.history);
519 await this.startSession(session, { ...input, cols, rows }, "restarted");
520 return this.snapshot(session);
521 });
522 }
523​
524 async close(raw: TerminalCloseInput): Promise<void> {
525 const input = decodeTerminalCloseInput(raw);
526 await this.runWithThreadLock(input.threadId, async () => {
527 if (input.terminalId) {
528 await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
529 return;
530 }
531​
532 const threadSessions = this.sessionsForThread(input.threadId);
533 for (const session of threadSessions) {
534 this.stopProcess(session);
535 this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
536 }
537 await Promise.all(
538 threadSessions.map((session) =>
539 this.flushPersistQueue(session.threadId, session.terminalId),
540 ),
541 );
542​
543 if (input.deleteHistory) {
544 await this.deleteAllHistoryForThread(input.threadId);
545 }
546 this.updateSubprocessPollingState();
547 });
548 }
549​
550 dispose(): void {
551 this.stopSubprocessPolling();
552 const sessions = [...this.sessions.values()];
553 this.sessions.clear();
554 for (const session of sessions) {
555 this.stopProcess(session);
556 }
557 for (const timer of this.persistTimers.values()) {
558 clearTimeout(timer);
559 }
560 this.persistTimers.clear();
561 for (const timer of this.killEscalationTimers.values()) {
562 clearTimeout(timer);
563 }
564 this.killEscalationTimers.clear();
565 this.pendingPersistHistory.clear();
566 this.threadLocks.clear();
567 this.persistQueues.clear();
568 }
569​
570 private async startSession(
571 session: TerminalSessionState,
572 input: TerminalStartInput,
573 eventType: "started" | "restarted",
574 ): Promise<void> {
575 this.stopProcess(session);
576​
577 session.status = "starting";
578 session.cwd = input.cwd;
579 session.cols = input.cols;
580 session.rows = input.rows;
581 session.exitCode = null;
582 session.exitSignal = null;
583 session.hasRunningSubprocess = false;
584 session.updatedAt = new Date().toISOString();
585​
586 let ptyProcess: PtyProcess | null = null;
587 let startedShell: string | null = null;
588 try {
589 const shellCandidates = resolveShellCandidates(this.shellResolver);
590 const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
591 let lastSpawnError: unknown = null;
592​
593 const spawnWithCandidate = (candidate: ShellCandidate) =>
594 Effect.runPromise(
595 this.ptyAdapter.spawn({
596 shell: candidate.shell,
597 ...(candidate.args ? { args: candidate.args } : {}),
598 cwd: session.cwd,
599 cols: session.cols,
600 rows: session.rows,
601 env: terminalEnv,
602 }),
603 );
604​
605 const trySpawn = async (
606 candidates: ShellCandidate[],
607 index = 0,
608 ): Promise<{ process: PtyProcess; shellLabel: string } | null> => {
609 if (index >= candidates.length) {
610 return null;
611 }
612 const candidate = candidates[index];
613 if (!candidate) {
614 return null;
615 }
616​
617 try {
618 const process = await spawnWithCandidate(candidate);
619 return { process, shellLabel: formatShellCandidate(candidate) };
620 } catch (error) {
621 lastSpawnError = error;
622 if (!isRetryableShellSpawnError(error)) {
623 throw error;
624 }
625 return trySpawn(candidates, index + 1);
626 }
627 };
628​
629 const spawnResult = await trySpawn(shellCandidates);
630 if (spawnResult) {
631 ptyProcess = spawnResult.process;
632 startedShell = spawnResult.shellLabel;
633 }
634​
635 if (!ptyProcess) {
636 const detail =
637 lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
638 const tried =
639 shellCandidates.length > 0
640 ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
641 : "";
642 throw new Error(`${detail}.${tried}`.trim());
643 }
644​
645 session.process = ptyProcess;
646 session.pid = ptyProcess.pid;
647 session.status = "running";
648 session.updatedAt = new Date().toISOString();
649 session.unsubscribeData = ptyProcess.onData((data) => {
650 this.onProcessData(session, data);
651 });
652 session.unsubscribeExit = ptyProcess.onExit((event) => {
653 this.onProcessExit(session, event);
654 });
655 this.updateSubprocessPollingState();
656 this.emitEvent({
657 type: eventType,
658 threadId: session.threadId,
659 terminalId: session.terminalId,
660 createdAt: new Date().toISOString(),
661 snapshot: this.snapshot(session),
662 });
663 } catch (error) {
664 if (ptyProcess) {
665 this.killProcessWithEscalation(ptyProcess, session.threadId, session.terminalId);
666 }
667 session.status = "error";
668 session.pid = null;
669 session.process = null;
670 session.hasRunningSubprocess = false;
671 session.updatedAt = new Date().toISOString();
672 this.evictInactiveSessionsIfNeeded();
673 this.updateSubprocessPollingState();
674 const message = error instanceof Error ? error.message : "Terminal start failed";
675 this.emitEvent({
676 type: "error",
677 threadId: session.threadId,
678 terminalId: session.terminalId,
679 createdAt: new Date().toISOString(),
680 message,
681 });
682 this.logger.error("failed to start terminal", {
683 threadId: session.threadId,
684 terminalId: session.terminalId,
685 error: message,
686 ...(startedShell ? { shell: startedShell } : {}),
687 });
688 }
689 }
690​
691 private onProcessData(session: TerminalSessionState, data: string): void {
692 session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
693 session.updatedAt = new Date().toISOString();
694 this.queuePersist(session.threadId, session.terminalId, session.history);
695 this.emitEvent({
696 type: "output",
697 threadId: session.threadId,
698 terminalId: session.terminalId,
699 createdAt: new Date().toISOString(),
700 data,
701 });
702 }
703​
704 private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void {
705 this.clearKillEscalationTimer(session.process);
706 this.cleanupProcessHandles(session);
707 session.process = null;
708 session.pid = null;
709 session.hasRunningSubprocess = false;
710 session.status = "exited";
711 session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
712 session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
713 session.updatedAt = new Date().toISOString();
714 this.emitEvent({
715 type: "exited",
716 threadId: session.threadId,
717 terminalId: session.terminalId,
718 createdAt: new Date().toISOString(),
719 exitCode: session.exitCode,
720 exitSignal: session.exitSignal,
721 });
722 this.evictInactiveSessionsIfNeeded();
723 this.updateSubprocessPollingState();
724 }
725​
726 private stopProcess(session: TerminalSessionState): void {
727 const process = session.process;
728 if (!process) return;
729 this.cleanupProcessHandles(session);
730 session.process = null;
731 session.pid = null;
732 session.hasRunningSubprocess = false;
733 session.status = "exited";
734 session.updatedAt = new Date().toISOString();
735 this.killProcessWithEscalation(process, session.threadId, session.terminalId);
736 this.evictInactiveSessionsIfNeeded();
737 this.updateSubprocessPollingState();
738 }
739​
740 private cleanupProcessHandles(session: TerminalSessionState): void {
741 session.unsubscribeData?.();
742 session.unsubscribeData = null;
743 session.unsubscribeExit?.();
744 session.unsubscribeExit = null;
745 }
746​
747 private clearKillEscalationTimer(process: PtyProcess | null): void {
748 if (!process) return;
749 const timer = this.killEscalationTimers.get(process);
750 if (!timer) return;
751 clearTimeout(timer);
752 this.killEscalationTimers.delete(process);
753 }
754​
755 private killProcessWithEscalation(
756 process: PtyProcess,
757 threadId: string,
758 terminalId: string,
759 ): void {
760 this.clearKillEscalationTimer(process);
761 try {
762 process.kill("SIGTERM");
763 } catch (error) {
764 const message = error instanceof Error ? error.message : String(error);
765 this.logger.warn("failed to kill terminal process", {
766 threadId,
767 terminalId,
768 signal: "SIGTERM",
769 error: message,
770 });
771 return;
772 }
773​
774 const timer = setTimeout(() => {
775 this.killEscalationTimers.delete(process);
776 try {
777 process.kill("SIGKILL");
778 } catch (error) {
779 const message = error instanceof Error ? error.message : String(error);
780 this.logger.warn("failed to force-kill terminal process", {
781 threadId,
782 terminalId,
783 signal: "SIGKILL",
784 error: message,
785 });
786 }
787 }, this.processKillGraceMs);
788 timer.unref?.();
789 this.killEscalationTimers.set(process, timer);
790 }
791​
792 private evictInactiveSessionsIfNeeded(): void {
793 const inactiveSessions = [...this.sessions.values()].filter(
794 (session) => session.status !== "running",
795 );
796 if (inactiveSessions.length <= this.maxRetainedInactiveSessions) {
797 return;
798 }
799​
800 inactiveSessions.sort(
801 (left, right) =>
802 left.updatedAt.localeCompare(right.updatedAt) ||
803 left.threadId.localeCompare(right.threadId) ||
804 left.terminalId.localeCompare(right.terminalId),
805 );
806 const toEvict = inactiveSessions.length - this.maxRetainedInactiveSessions;
807 for (const session of inactiveSessions.slice(0, toEvict)) {
808 const key = toSessionKey(session.threadId, session.terminalId);
809 this.sessions.delete(key);
810 this.clearPersistTimer(session.threadId, session.terminalId);
811 this.pendingPersistHistory.delete(key);
812 this.persistQueues.delete(key);
813 this.clearKillEscalationTimer(session.process);
814 }
815 }
816​
817 private queuePersist(threadId: string, terminalId: string, history: string): void {
818 const persistenceKey = toSessionKey(threadId, terminalId);
819 this.pendingPersistHistory.set(persistenceKey, history);
820 this.schedulePersist(threadId, terminalId);
821 }
822​
823 private async persistHistory(
824 threadId: string,
825 terminalId: string,
826 history: string,
827 ): Promise<void> {
828 const persistenceKey = toSessionKey(threadId, terminalId);
829 this.clearPersistTimer(threadId, terminalId);
830 this.pendingPersistHistory.delete(persistenceKey);
831 await this.enqueuePersistWrite(threadId, terminalId, history);
832 }
833​
834 private enqueuePersistWrite(
835 threadId: string,
836 terminalId: string,
837 history: string,
838 ): Promise<void> {
839 const persistenceKey = toSessionKey(threadId, terminalId);
840 const task = async () => {
841 await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
842 };
843 const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
844 const next = previous
845 .catch(() => undefined)
846 .then(task)
847 .catch((error) => {
848 this.logger.warn("failed to persist terminal history", {
849 threadId,
850 terminalId,
851 error: error instanceof Error ? error.message : String(error),
852 });
853 });
854 this.persistQueues.set(persistenceKey, next);
855 const finalized = next.finally(() => {
856 if (this.persistQueues.get(persistenceKey) === next) {
857 this.persistQueues.delete(persistenceKey);
858 }
859 if (
860 this.pendingPersistHistory.has(persistenceKey) &&
861 !this.persistTimers.has(persistenceKey)
862 ) {
863 this.schedulePersist(threadId, terminalId);
864 }
865 });
866 void finalized.catch(() => undefined);
867 return finalized;
868 }
869​
870 private schedulePersist(threadId: string, terminalId: string): void {
871 const persistenceKey = toSessionKey(threadId, terminalId);
872 if (this.persistTimers.has(persistenceKey)) return;
873 const timer = setTimeout(() => {
874 this.persistTimers.delete(persistenceKey);
875 const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
876 if (pendingHistory === undefined) return;
877 this.pendingPersistHistory.delete(persistenceKey);
878 void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
879 }, this.persistDebounceMs);
880 this.persistTimers.set(persistenceKey, timer);
881 }
882​
883 private clearPersistTimer(threadId: string, terminalId: string): void {
884 const persistenceKey = toSessionKey(threadId, terminalId);
885 const timer = this.persistTimers.get(persistenceKey);
886 if (!timer) return;
887 clearTimeout(timer);
888 this.persistTimers.delete(persistenceKey);
889 }
890​
891 private async readHistory(threadId: string, terminalId: string): Promise<string> {
892 const nextPath = this.historyPath(threadId, terminalId);
893 try {
894 const raw = await fs.promises.readFile(nextPath, "utf8");
895 const capped = capHistory(raw, this.historyLineLimit);
896 if (capped !== raw) {
897 await fs.promises.writeFile(nextPath, capped, "utf8");
898 }
899 return capped;
900 } catch (error) {
901 if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
902 throw error;
903 }
904 }
905​
906 if (terminalId !== DEFAULT_TERMINAL_ID) {
907 return "";
908 }
909​
910 const legacyPath = this.legacyHistoryPath(threadId);
911 try {
912 const raw = await fs.promises.readFile(legacyPath, "utf8");
913 const capped = capHistory(raw, this.historyLineLimit);
914​
915 // Migrate legacy transcript filename to the terminal-scoped path.
916 await fs.promises.writeFile(nextPath, capped, "utf8");
917 try {
918 await fs.promises.rm(legacyPath, { force: true });
919 } catch (cleanupError) {
920 this.logger.warn("failed to remove legacy terminal history", {
921 threadId,
922 error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
923 });
924 }
925​
926 return capped;
927 } catch (error) {
928 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
929 return "";
930 }
931 throw error;
932 }
933 }
934​
935 private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
936 const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
937 if (terminalId === DEFAULT_TERMINAL_ID) {
938 deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
939 }
940 try {
941 await Promise.all(deletions);
942 } catch (error) {
943 this.logger.warn("failed to delete terminal history", {
944 threadId,
945 terminalId,
946 error: error instanceof Error ? error.message : String(error),
947 });
948 }
949 }
950​
951 private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
952 const persistenceKey = toSessionKey(threadId, terminalId);
953 this.clearPersistTimer(threadId, terminalId);
954​
955 while (true) {
956 const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
957 if (pendingHistory !== undefined) {
958 this.pendingPersistHistory.delete(persistenceKey);
959 await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
960 }
961​
962 const pending = this.persistQueues.get(persistenceKey);
963 if (!pending) {
964 return;
965 }
966 await pending.catch(() => undefined);
967 }
968 }
969​
970 private updateSubprocessPollingState(): void {
971 const hasRunningSessions = [...this.sessions.values()].some(
972 (session) => session.status === "running" && session.pid !== null,
973 );
974 if (hasRunningSessions) {
975 this.ensureSubprocessPolling();
976 return;
977 }
978 this.stopSubprocessPolling();
979 }
980​
981 private ensureSubprocessPolling(): void {
982 if (this.subprocessPollTimer) return;
983 this.subprocessPollTimer = setInterval(() => {
984 void this.pollSubprocessActivity();
985 }, this.subprocessPollIntervalMs);
986 this.subprocessPollTimer.unref?.();
987 void this.pollSubprocessActivity();
988 }
989​
990 private stopSubprocessPolling(): void {
991 if (!this.subprocessPollTimer) return;
992 clearInterval(this.subprocessPollTimer);
993 this.subprocessPollTimer = null;
994 }
995​
996 private async pollSubprocessActivity(): Promise<void> {
997 if (this.subprocessPollInFlight) return;
998​
999 const runningSessions = [...this.sessions.values()].filter(
1000 (session): session is TerminalSessionState & { pid: number } =>
1001 session.status === "running" && Number.isInteger(session.pid),
1002 );
1003 if (runningSessions.length === 0) {
1004 this.stopSubprocessPolling();
1005 return;
1007​
1008 this.subprocessPollInFlight = true;
1009 try {
1010 await Promise.all(
1011 runningSessions.map(async (session) => {
1012 const terminalPid = session.pid;
1013 let hasRunningSubprocess = false;
1014 try {
1015 hasRunningSubprocess = await this.subprocessChecker(terminalPid);
1016 } catch (error) {
1017 this.logger.warn("failed to check terminal subprocess activity", {
1018 threadId: session.threadId,
1019 terminalId: session.terminalId,
1020 terminalPid,
1021 error: error instanceof Error ? error.message : String(error),
1022 });
1023 return;
1025​
1026 const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
1027 if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
1028 return;
1030 if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
1031 return;
1033​
1034 liveSession.hasRunningSubprocess = hasRunningSubprocess;
1035 liveSession.updatedAt = new Date().toISOString();
1036 this.emitEvent({
1037 type: "activity",
1038 threadId: liveSession.threadId,
1039 terminalId: liveSession.terminalId,
1040 createdAt: new Date().toISOString(),
1041 hasRunningSubprocess,
1042 });
1043 }),
1044 );
1045 } finally {
1046 this.subprocessPollInFlight = false;
1049​
1050 private async assertValidCwd(cwd: string): Promise<void> {
1051 let stats: fs.Stats;
1052 try {
1053 stats = await fs.promises.stat(cwd);
1054 } catch (error) {
1055 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
1056 throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error });
1058 throw error;
1060 if (!stats.isDirectory()) {
1061 throw new Error(`Terminal cwd is not a directory: ${cwd}`);
1064​
1065 private async closeSession(
1066 threadId: string,
1067 terminalId: string,
1068 deleteHistory: boolean,
1069 ): Promise<void> {
1070 const key = toSessionKey(threadId, terminalId);
1071 const session = this.sessions.get(key);
1072 if (session) {
1073 this.stopProcess(session);
1074 this.sessions.delete(key);
1076 this.updateSubprocessPollingState();
1077 await this.flushPersistQueue(threadId, terminalId);
1078 if (deleteHistory) {
1079 await this.deleteHistory(threadId, terminalId);
1082​
1083 private sessionsForThread(threadId: string): TerminalSessionState[] {
1084 return [...this.sessions.values()].filter((session) => session.threadId === threadId);
1086​
1087 private async deleteAllHistoryForThread(threadId: string): Promise<void> {
1088 const threadPrefix = `${toSafeThreadId(threadId)}_`;
1089 try {
1090 const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
1091 const removals = entries
1092 .filter((entry) => entry.isFile())
1093 .map((entry) => entry.name)
1094 .filter(
1095 (name) =>
1096 name === `${toSafeThreadId(threadId)}.log` ||
1097 name === `${legacySafeThreadId(threadId)}.log` ||
1098 name.startsWith(threadPrefix),
1100 .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
1101 await Promise.all(removals);
1102 } catch (error) {
1103 this.logger.warn("failed to delete terminal histories for thread", {
1104 threadId,
1105 error: error instanceof Error ? error.message : String(error),
1106 });
1109​
1110 private requireSession(threadId: string, terminalId: string): TerminalSessionState {
1111 const session = this.sessions.get(toSessionKey(threadId, terminalId));
1112 if (!session) {
1113 throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
1115 return session;
1117​
1118 private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
1119 return {
1120 threadId: session.threadId,
1121 terminalId: session.terminalId,
1122 cwd: session.cwd,
1123 status: session.status,
1124 pid: session.pid,
1125 history: session.history,
1126 exitCode: session.exitCode,
1127 exitSignal: session.exitSignal,
1128 updatedAt: session.updatedAt,
1129 };
1131​
1132 private emitEvent(event: TerminalEvent): void {
1133 this.emit("event", event);
1135​
1136 private historyPath(threadId: string, terminalId: string): string {
1137 const threadPart = toSafeThreadId(threadId);
1138 if (terminalId === DEFAULT_TERMINAL_ID) {
1139 return path.join(this.logsDir, `${threadPart}.log`);
1141 return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
1143​
1144 private legacyHistoryPath(threadId: string): string {
1145 return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
1147​
1148 private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
1149 const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
1150 let release: () => void = () => {};
1151 const current = new Promise<void>((resolve) => {
1152 release = resolve;
1153 });
1154 this.threadLocks.set(threadId, current);
1155 await previous.catch(() => undefined);
1156 try {
1157 return await task();
1158 } finally {
1159 release();
1160 if (this.threadLocks.get(threadId) === current) {
1161 this.threadLocks.delete(threadId);
1166​
1167export const TerminalManagerLive = Layer.effect(
1168 TerminalManager,
1169 Effect.gen(function* () {
1170 const { stateDir } = yield* ServerConfig;
1171 const { join } = yield* Path.Path;
1172 const logsDir = join(stateDir, "logs", "terminals");
1173​
1174 const ptyAdapter = yield* PtyAdapter;
1175 const runtime = yield* Effect.acquireRelease(
1176 Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
1177 (r) => Effect.sync(() => r.dispose()),
1178 );
1179​
1180 return {
1181 open: (input) =>
1182 Effect.tryPromise({
1183 try: () => runtime.open(input),
1184 catch: (cause) => new TerminalError({ message: "Failed to open terminal", cause }),
1185 }),
1186 write: (input) =>
1187 Effect.tryPromise({
1188 try: () => runtime.write(input),
1189 catch: (cause) => new TerminalError({ message: "Failed to write to terminal", cause }),
1190 }),
1191 resize: (input) =>
1192 Effect.tryPromise({
1193 try: () => runtime.resize(input),
1194 catch: (cause) => new TerminalError({ message: "Failed to resize terminal", cause }),
1195 }),
1196 clear: (input) =>
1197 Effect.tryPromise({
1198 try: () => runtime.clear(input),
1199 catch: (cause) => new TerminalError({ message: "Failed to clear terminal", cause }),
1200 }),
1201 restart: (input) =>
1202 Effect.tryPromise({
1203 try: () => runtime.restart(input),
1204 catch: (cause) => new TerminalError({ message: "Failed to restart terminal", cause }),
1205 }),
1206 close: (input) =>
1207 Effect.tryPromise({
1208 try: () => runtime.close(input),
1209 catch: (cause) => new TerminalError({ message: "Failed to close terminal", cause }),
1210 }),
1211 subscribe: (listener) =>
1212 Effect.sync(() => {
1213 runtime.on("event", listener);
1214 return () => {
1215 runtime.off("event", listener);
1216 };
1217 }),
1218 dispose: Effect.sync(() => runtime.dispose()),
1219 } satisfies TerminalManagerShape;
1220 }),