@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 3,985 lines 136 KB
Raw
1 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto digest is effectful; a sync hash keeps historyPath a plain function.
2 import * as NodeCrypto from "node:crypto";
3
4 import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
5 import {
6 DEFAULT_TERMINAL_ID,
7 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
8 retainedTerminalHistory,
9 TERMINAL_SEQUENCE_GROUND,
10 terminalSequenceEnd,
11 terminalSequenceStateAfter,
12 TerminalCwdError,
13 TerminalCwdNotDirectoryError,
14 TerminalCwdNotFoundError,
15 TerminalCwdStatError,
16 TerminalError,
17 TerminalHistoryError,
18 TerminalNotRunningError,
19 TerminalProviderInstanceNotFoundError,
20 TerminalProviderEnvironmentError,
21 TerminalResizeError,
22 TerminalSessionLookupError,
23 TerminalWriteError,
24 type TerminalAttachInput,
25 type TerminalAttachStreamEvent,
26 type TerminalClearInput,
27 type TerminalCloseInput,
28 type TerminalEvent,
29 type TerminalMetadataStreamEvent,
30 type TerminalOpenInput,
31 type TerminalObserveInput,
32 type TerminalResizeInput,
33 type ResourceMonitorProcessTableEntry,
34 type TerminalSessionSnapshot,
35 type TerminalSessionStatus,
36 type TerminalSummary,
37 type TerminalWriteInput,
38 ClaudeSettings,
39 CodexSettings,
40 ProviderInstanceId,
41 } from "@t3tools/contracts";
42 import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
43 import * as KeyedLock from "@t3tools/shared/KeyedLock";
44 import { AgentScope } from "@t3tools/shared/AgentScope";
45 import * as HostProcess from "@t3tools/shared/HostProcess";
46 import { SpawnExecutableResolution, mergePathEntries } from "@t3tools/shared/shell";
47
48 import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server";
49 import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
50 import * as DateTime from "effect/DateTime";
51 import * as Deferred from "effect/Deferred";
52 import * as Context from "effect/Context";
53 import * as Duration from "effect/Duration";
54 import * as Effect from "effect/Effect";
55 import * as Base64Url from "effect/encoding/Base64Url";
56 import * as Equal from "effect/Equal";
57 import * as Exit from "effect/Exit";
58 import * as Fiber from "effect/Fiber";
59 import * as FileSystem from "effect/FileSystem";
60 import * as Layer from "effect/Layer";
61 import * as Option from "effect/Option";
62 import * as Path from "effect/Path";
63 import * as Result from "effect/Result";
64 import * as Schema from "effect/Schema";
65 import * as Scope from "effect/Scope";
66 import * as Stream from "effect/Stream";
67 import * as SynchronizedRef from "effect/SynchronizedRef";
68
69 import packageJson from "../../package.json" with { type: "json" };
70 import * as ServerConfig from "../config.ts";
71 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
72 import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
73 import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
74 import type { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts";
75 import * as ServerSettings from "../serverSettings.ts";
76 import { increment, terminalSessionsTotal } from "../observability/Metrics.ts";
77 import { expandHomeVariable } from "@t3tools/provider-core/server/pathExpansion";
78 import * as ProcessRunner from "../processRunner.ts";
79 import * as PortScanner from "../preview/PortScanner.ts";
80 import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
81 import { terminalOutputStream } from "./OutputProtocol.ts";
82 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
83
84 export {
85 TerminalCwdError,
86 TerminalCwdNotDirectoryError,
87 TerminalCwdNotFoundError,
88 TerminalCwdStatError,
89 TerminalError,
90 TerminalHistoryError,
91 TerminalNotRunningError,
92 TerminalProviderInstanceNotFoundError,
93 TerminalProviderEnvironmentError,
94 TerminalResizeError,
95 TerminalSessionLookupError,
96 TerminalWriteError,
97 };
98
99 const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
100 const DEFAULT_HISTORY_BYTE_LIMIT = 8 * 1024 * 1024;
101 // eCryptfs permits 143-byte names.
102 const MAX_HISTORY_FILENAME_BYTES = 143;
103 const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;
104 const DEFAULT_PERSIST_DEBOUNCE_MS = 250;
105 const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
106 const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000;
107 // `ps` and WMI can take seconds on a loaded host and their tables are still
108 // valid then; the timeout only ends a query that is truly stuck.
109 const PROCESS_TABLE_QUERY_TIMEOUT = "15 seconds";
110 // closeIdle queries while holding the thread lock, so it keeps a short budget
111 // rather than stalling other operations on that thread behind a slow table.
112 const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const;
113 // Discover children started without terminal input or output.
114 const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30;
115 const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;
116 const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
117 const DEFAULT_OPEN_COLS = 120;
118 const DEFAULT_OPEN_ROWS = 30;
119 // The tmux/screen/Zellij keys name the multiplexer pane that launched the server,
120 // so inheriting them points multiplexer-aware tools at that unrelated pane.
121 const TERMINAL_ENV_BLOCKLIST = new Set([
122 "PORT",
123 "ELECTRON_RENDERER_PORT",
124 "ELECTRON_RUN_AS_NODE",
125 "TMUX",
126 "TMUX_PANE",
127 "STY",
128 "WINDOW",
129 "ZELLIJ",
130 "ZELLIJ_SESSION_NAME",
131 "ZELLIJ_PANE_ID",
132 ]);
133 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
134 const MAX_TERMINAL_LABEL_LENGTH = 128;
135 const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
136 const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
137
138 class TerminalSubprocessCheckError extends Schema.TaggedError<TerminalSubprocessCheckError>()(
139 "TerminalSubprocessCheckError",
140 {
141 cause: Schema.optional(Schema.Defect()),
142 command: Schema.Literals(["powershell", "ps", "resource-monitor"]),
143 exitCode: Schema.optional(Schema.NullOr(Schema.Number)),
144 timedOut: Schema.optional(Schema.Boolean),
145 stdoutTruncated: Schema.optional(Schema.Boolean),
146 },
147 ) {
148 override get message(): string {
149 const details = [
150 this.exitCode !== undefined && this.exitCode !== null ? `exit code ${this.exitCode}` : null,
151 this.timedOut ? "timed out" : null,
152 this.stdoutTruncated ? "output truncated" : null,
153 ]
154 .filter((detail) => detail !== null)
155 .join(", ");
156 return `Failed to inspect terminal subprocesses with ${this.command}${details.length > 0 ? ` (${details})` : ""}`;
157 }
158 }
159
160 class TerminalProcessSignalError extends Schema.TaggedError<TerminalProcessSignalError>()(
161 "TerminalProcessSignalError",
162 {
163 cause: Schema.optional(Schema.Defect()),
164 signal: Schema.Literals(["SIGTERM", "SIGKILL"]),
165 terminalPid: Schema.Number,
166 },
167 ) {
168 override get message(): string {
169 return `Failed to send ${this.signal} to terminal process ${this.terminalPid}`;
170 }
171 }
172
173 export class TerminalCwdRecovery extends Context.Reference<
174 (error: TerminalCwdNotFoundError) => Effect.Effect<void, TerminalCwdNotFoundError>
175 >("t3/terminal/TerminalCwdRecovery", { defaultValue: () => (error) => Effect.fail(error) }) {}
176
177 export class TerminalManager extends Context.Service<
178 TerminalManager,
179 {
180 readonly open: (
181 input: TerminalOpenInput,
182 ) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
183
184 readonly getShell: (input: TerminalObserveInput) => Effect.Effect<string, TerminalError>;
185
186 /**
187 * Attached viewers share one PTY sized to the smallest of them, so a narrow client
188 * still sees the whole TUI. Streams and resizes with the same `viewerId` (one client
189 * connection) count as one viewer; streams without one are each their own viewer.
190 */
191 readonly attachStream: (
192 input: TerminalAttachInput,
193 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
194 registerCleanup?: (stop: () => void) => void,
195 viewerId?: string,
196 ) => Effect.Effect<() => void, TerminalError>;
197
198 /**
199 * The `terminal.attach` RPC stream. Overflow recovery swaps the inner subscription, so
200 * `viewerId` and the size it reported stay attached until the whole stream ends.
201 */
202 readonly attachOutputStream: (
203 input: TerminalAttachInput,
204 viewerId: string,
205 ) => Stream.Stream<TerminalAttachStreamEvent, TerminalError>;
206
207 readonly observeStream: (
208 input: TerminalObserveInput,
209 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
210 registerCleanup?: (stop: () => void) => void,
211 ) => Effect.Effect<() => void, TerminalError>;
212
213 readonly resyncStream: (
214 input: TerminalObserveInput,
215 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
216 registerCleanup?: (stop: () => void) => void,
217 ) => Effect.Effect<() => void, TerminalError>;
218
219 /**
220 * Attached viewers share one reply owner per PTY until it detaches. Marked replies
221 * from other or detached viewer IDs are dropped; identity-free writes do not claim ownership.
222 */
223 readonly write: (
224 input: TerminalWriteInput,
225 viewerId?: string,
226 ) => Effect.Effect<void, TerminalError>;
227
228 readonly resize: (
229 input: TerminalResizeInput,
230 viewerId?: string,
231 ) => Effect.Effect<void, TerminalError>;
232
233 readonly clear: (input: TerminalClearInput) => Effect.Effect<void, TerminalError>;
234
235 /** Omit terminalId to close all sessions for the thread. */
236 readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
237
238 readonly closeOnSettle: (input: { readonly threadId: string }) => Effect.Effect<void>;
239
240 readonly closeIdle: (input: {
241 readonly threadId: string;
242 readonly terminalId?: string;
243 }) => Effect.Effect<void>;
244
245 readonly hasActiveSubprocess: (input: { readonly threadId: string }) => Effect.Effect<boolean>;
246
247 readonly subscribe: (
248 listener: (event: TerminalEvent) => Effect.Effect<void>,
249 registerCleanup?: (stop: () => void) => void,
250 ) => Effect.Effect<() => void>;
251
252 readonly subscribeMetadata: (
253 listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,
254 ) => Effect.Effect<() => void>;
255 }
256 >()("t3/terminal/Manager/TerminalManager") {}
257
258 interface TerminalSubprocessInspectResult {
259 readonly hasRunningSubprocess: boolean;
260 readonly childCommand: string | null;
261 readonly processIds: ReadonlyArray<number>;
262 }
263
264 interface TerminalSubprocessInspector {
265 (
266 terminalPid: number,
267 shell: string | null,
268 ): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError>;
269 }
270
271 const resizePtyProcess = (
272 session: TerminalSessionState,
273 process: PtyAdapter.PtyProcess,
274 cols: number,
275 rows: number,
276 ) =>
277 Effect.try({
278 try: () => process.resize(cols, rows),
279 catch: (cause) =>
280 new TerminalResizeError({
281 threadId: session.threadId,
282 terminalId: session.terminalId,
283 terminalPid: process.pid,
284 cols,
285 rows,
286 cause,
287 }),
288 });
289
290 export interface ShellCandidate {
291 shell: string;
292 args?: string[];
293 }
294
295 interface TerminalStartInput {
296 readonly cwd: string;
297 readonly worktreePath?: string | null;
298 readonly cols: number;
299 readonly rows: number;
300 }
301
302 interface TerminalSessionState {
303 threadId: string;
304 terminalId: string;
305 cwd: string;
306 worktreePath: string | null;
307 status: TerminalSessionStatus;
308 pid: number | null;
309 history: BoundedTerminalHistory;
310 pendingHistoryControlSequence: string;
311 pendingProcessEvents: Array<PendingProcessEvent | undefined>;
312 pendingProcessEventIndex: number;
313 processEventDrainRunning: boolean;
314 exitCode: number | null;
315 exitSignal: number | null;
316 updatedAt: string;
317 eventSequence: number;
318 inputCount: number;
319 cols: number;
320 rows: number;
321 process: PtyAdapter.PtyProcess | null;
322 shell: string | null;
323 unsubscribeData: (() => void) | null;
324 unsubscribeExit: (() => void) | null;
325 hasRunningSubprocess: boolean;
326 childCommandLabel: string | null;
327 runtimeEnv: Record<string, string> | null;
328 stopOnSettle: boolean;
329 startupError: string | null;
330 }
331
332 interface TerminalGrid {
333 readonly cols: number;
334 readonly rows: number;
335 }
336
337 /** One client connection attached to a terminal, possibly through several streams. */
338 interface TerminalViewer {
339 streams: number;
340 grid: TerminalGrid | null;
341 answersQueries: boolean;
342 }
343
344 interface PersistHistoryRequest {
345 history: BoundedTerminalHistory;
346 immediate: boolean;
347 }
348
349 type PendingProcessEvent =
350 | { type: "output"; data: string }
351 | { type: "exit"; event: PtyAdapter.PtyExitEvent };
352
353 type DrainProcessEventAction =
354 | { type: "idle" }
355 | {
356 type: "output";
357 threadId: string;
358 terminalId: string;
359 sequence: number;
360 history: BoundedTerminalHistory | null;
361 data: string;
362 }
363 | {
364 type: "exit";
365 process: PtyAdapter.PtyProcess | null;
366 threadId: string;
367 terminalId: string;
368 sequence: number;
369 exitCode: number | null;
370 exitSignal: number | null;
371 };
372
373 interface TerminalManagerState {
374 sessions: Map<string, TerminalSessionState>;
375 killFibers: Map<PtyAdapter.PtyProcess, Fiber.Fiber<void, never>>;
376 }
377
378 function truncateTerminalWireLabel(value: string): string {
379 if (value.length <= MAX_TERMINAL_LABEL_LENGTH) return value;
380 return value.slice(0, MAX_TERMINAL_LABEL_LENGTH);
381 }
382
383 function normalizeChildCommandName(raw: string, platform: NodeJS.Platform): string | null {
384 let trimmed = raw.trim();
385 if (trimmed.length === 0) return null;
386 if (
387 (trimmed.startsWith("[") && trimmed.endsWith("]")) ||
388 (trimmed.startsWith("(") && trimmed.endsWith(")"))
389 ) {
390 trimmed = trimmed.slice(1, -1).trim();
391 }
392 // Process names and macOS `comm` paths can contain spaces ("Google Chrome").
393 const separators = platform === "win32" ? /[\\/]/ : /\//;
394 const base = (trimmed.split(separators).at(-1) ?? trimmed).trim();
395 const withoutExe =
396 platform === "win32" && base.toLowerCase().endsWith(".exe") ? base.slice(0, -4) : base;
397 return withoutExe.length > 0 ? withoutExe : null;
398 }
399
400 function terminalWireLabel(session: TerminalSessionState): string {
401 if (session.hasRunningSubprocess && session.childCommandLabel) {
402 const trimmed = session.childCommandLabel.trim();
403 if (trimmed.length > 0) {
404 return truncateTerminalWireLabel(trimmed);
405 }
406 }
407 return truncateTerminalWireLabel(getTerminalLabel(session.terminalId));
408 }
409
410 function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
411 return {
412 threadId: session.threadId,
413 terminalId: session.terminalId,
414 cwd: session.cwd,
415 worktreePath: session.worktreePath,
416 status: session.status,
417 pid: session.pid,
418 history: session.history.value(),
419 exitCode: session.exitCode,
420 exitSignal: session.exitSignal,
421 label: terminalWireLabel(session),
422 updatedAt: session.updatedAt,
423 sequence: session.eventSequence,
424 cols: session.cols,
425 rows: session.rows,
426 ...(session.startupError === null ? {} : { error: session.startupError }),
427 };
428 }
429
430 function summary(session: TerminalSessionState): TerminalSummary {
431 return {
432 threadId: session.threadId,
433 terminalId: session.terminalId,
434 cwd: session.cwd,
435 worktreePath: session.worktreePath,
436 status: session.status,
437 pid: session.pid,
438 exitCode: session.exitCode,
439 exitSignal: session.exitSignal,
440 hasRunningSubprocess: session.hasRunningSubprocess,
441 label: terminalWireLabel(session),
442 updatedAt: session.updatedAt,
443 };
444 }
445
446 function shouldPublishTerminalMetadataEvent(event: TerminalEvent): boolean {
447 switch (event.type) {
448 case "started":
449 case "restarted":
450 case "exited":
451 case "closed":
452 case "error":
453 case "activity":
454 return true;
455 case "output":
456 case "cleared":
457 return false;
458 }
459 }
460
461 function terminalEventToAttachEvent(event: TerminalEvent): TerminalAttachStreamEvent {
462 switch (event.type) {
463 case "started":
464 return {
465 type: "snapshot",
466 snapshot: event.snapshot,
467 };
468 case "output":
469 case "exited":
470 case "closed":
471 case "error":
472 case "cleared":
473 case "restarted":
474 case "activity":
475 return event;
476 }
477 }
478
479 function isDuplicateAttachSnapshotEvent(
480 event: TerminalEvent,
481 initialSnapshot: TerminalSessionSnapshot,
482 ) {
483 return typeof event.sequence === "number" && typeof initialSnapshot.sequence === "number"
484 ? event.sequence <= initialSnapshot.sequence
485 : event.type === "started" &&
486 event.snapshot.threadId === initialSnapshot.threadId &&
487 event.snapshot.terminalId === initialSnapshot.terminalId &&
488 event.snapshot.updatedAt <= initialSnapshot.updatedAt;
489 }
490
491 function advanceEventSequence(session: TerminalSessionState): {
492 readonly updatedAt: string;
493 readonly sequence: number;
494 } {
495 const updatedAt = DateTime.formatIso(DateTime.nowUnsafe());
496 session.eventSequence += 1;
497 session.updatedAt = updatedAt;
498 return { updatedAt, sequence: session.eventSequence };
499 }
500
501 function terminalActivityMark(session: TerminalSessionState): number {
502 return session.eventSequence + session.inputCount;
503 }
504
505 interface QuietTerminalSession {
506 readonly process: PtyAdapter.PtyProcess | null;
507 readonly mark: number;
508 readonly idleSnapshots: number;
509 }
510
511 function cleanupProcessHandles(session: TerminalSessionState): void {
512 session.unsubscribeData?.();
513 session.unsubscribeData = null;
514 session.unsubscribeExit?.();
515 session.unsubscribeExit = null;
516 }
517
518 function enqueueProcessEvent(
519 session: TerminalSessionState,
520 expectedPid: number,
521 event: PendingProcessEvent,
522 ): boolean {
523 if (!session.process || session.status !== "running" || session.pid !== expectedPid) {
524 return false;
525 }
526
527 session.pendingProcessEvents.push(event);
528 if (session.processEventDrainRunning) {
529 return false;
530 }
531
532 session.processEventDrainRunning = true;
533 return true;
534 }
535
536 function defaultShellResolver(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string {
537 if (platform === "win32") {
538 return "pwsh.exe";
539 }
540 return env.SHELL ?? "bash";
541 }
542
543 const normalizeShellCommand = Effect.fn("terminal.normalizeShellCommand")(function* (
544 value: string | undefined,
545 platform: NodeJS.Platform,
546 ) {
547 if (!value) return null;
548 const trimmed = value.trim();
549 if (trimmed.length === 0) return null;
550
551 if (platform === "win32") {
552 return trimmed;
553 }
554
555 const quoted = /^(['"])(.*?)\1(?:\s|$)/.exec(trimmed);
556 if (quoted) return quoted[2] || null;
557
558 if (trimmed.startsWith("/") && /\s/.test(trimmed)) {
559 const fs = yield* FileSystem.FileSystem;
560 const ends = [...trimmed.matchAll(/\s+/g)].map((match) => match.index);
561 // Unquoted paths are ambiguous; prefer the longest existing file over flag syntax.
562 for (const end of [trimmed.length, ...ends.reverse()]) {
563 const candidate = trimmed.slice(0, end);
564 const info = yield* fs
565 .stat(candidate)
566 .pipe(Effect.catchTags({ PlatformError: () => Effect.succeed(null) }));
567 if (info?.type === "File") return candidate;
568 }
569 }
570
571 return trimmed.split(/\s+(?=-)/)[0]?.replace(/^['"]|['"]$/g, "") || null;
572 });
573
574 function basenameForPlatform(command: string, platform: NodeJS.Platform): string {
575 const normalized =
576 platform === "win32" ? command.replaceAll("/", "\\") : command.replaceAll("\\", "/");
577 const parts = normalized
578 .split(platform === "win32" ? /\\+/ : /\/+/)
579 .filter((part) => part.length > 0);
580 return parts.at(-1) ?? normalized;
581 }
582
583 function joinWindowsPath(...parts: ReadonlyArray<string>): string {
584 return parts
585 .map((part, index) => {
586 if (index === 0) return part.replace(/[\\/]+$/g, "");
587 return part.replace(/^[\\/]+|[\\/]+$/g, "");
588 })
589 .filter((part) => part.length > 0)
590 .join("\\");
591 }
592
593 // PowerShell decodes native output with the console code page (often OEM 437), mangling UTF-8.
594 const POWERSHELL_UTF8_SETUP =
595 "[Console]::OutputEncoding = $OutputEncoding = [System.Text.UTF8Encoding]::new()";
596
597 function shellCandidateFromCommand(
598 command: string | null,
599 platform: NodeJS.Platform,
600 ): ShellCandidate | null {
601 if (!command || command.length === 0) return null;
602 const shellName = basenameForPlatform(command, platform).toLowerCase();
603 if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
604 return { shell: command, args: ["-NoLogo", "-NoExit", "-Command", POWERSHELL_UTF8_SETUP] };
605 }
606 if (platform === "win32" && (shellName === "bash.exe" || shellName === "bash")) {
607 return { shell: command, args: ["--login", "-i"] };
608 }
609 if (platform !== "win32" && shellName === "zsh") {
610 return { shell: command, args: ["-o", "nopromptsp"] };
611 }
612 // Login shells load ~/.bash_profile, matching macOS terminal startup.
613 if (platform === "darwin" && shellName === "bash") {
614 return { shell: command, args: ["-l"] };
615 }
616 return { shell: command };
617 }
618
619 function windowsSystemRoot(env: NodeJS.ProcessEnv): string {
620 return env.SystemRoot?.trim() || env.windir?.trim() || "C:\\Windows";
621 }
622
623 function windowsPowerShellPath(env: NodeJS.ProcessEnv): string {
624 return joinWindowsPath(
625 windowsSystemRoot(env),
626 "System32",
627 "WindowsPowerShell",
628 "v1.0",
629 "powershell.exe",
630 );
631 }
632
633 function windowsCmdPath(env: NodeJS.ProcessEnv): string {
634 return joinWindowsPath(windowsSystemRoot(env), "System32", "cmd.exe");
635 }
636
637 function formatShellCandidate(candidate: ShellCandidate): string {
638 if (!candidate.args || candidate.args.length === 0) return candidate.shell;
639 return `${candidate.shell} ${candidate.args.join(" ")}`;
640 }
641
642 function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
643 const seen = new Set<string>();
644 const ordered: ShellCandidate[] = [];
645 for (const candidate of candidates) {
646 if (!candidate) continue;
647 const key = formatShellCandidate(candidate);
648 if (seen.has(key)) continue;
649 seen.add(key);
650 ordered.push(candidate);
651 }
652 return ordered;
653 }
654
655 const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(function* (
656 shellResolver: () => string,
657 platform: NodeJS.Platform,
658 env: NodeJS.ProcessEnv,
659 terminalShell: string | undefined,
660 ) {
661 // This is an executable path, not a command line; spaces belong to the path.
662 const configured = shellCandidateFromCommand(terminalShell?.trim() || null, platform);
663 const requested = shellCandidateFromCommand(
664 yield* normalizeShellCommand(shellResolver(), platform),
665 platform,
666 );
667
668 if (platform === "win32") {
669 return uniqueShellCandidates([
670 configured,
671 requested,
672 shellCandidateFromCommand("pwsh.exe", platform),
673 shellCandidateFromCommand(windowsPowerShellPath(env), platform),
674 shellCandidateFromCommand("powershell.exe", platform),
675 shellCandidateFromCommand(env.ComSpec ?? null, platform),
676 shellCandidateFromCommand(windowsCmdPath(env), platform),
677 shellCandidateFromCommand("cmd.exe", platform),
678 ]);
679 }
680
681 return uniqueShellCandidates([
682 configured,
683 requested,
684 shellCandidateFromCommand(yield* normalizeShellCommand(env.SHELL, platform), platform),
685 shellCandidateFromCommand("/bin/zsh", platform),
686 shellCandidateFromCommand("/bin/bash", platform),
687 shellCandidateFromCommand("/bin/sh", platform),
688 shellCandidateFromCommand("zsh", platform),
689 shellCandidateFromCommand("bash", platform),
690 shellCandidateFromCommand("sh", platform),
691 ]);
692 });
693
694 function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
695 const queue: unknown[] = [error];
696 const seen = new Set<unknown>();
697 const messages: string[] = [];
698
699 while (queue.length > 0) {
700 const current = queue.shift();
701 if (!current || seen.has(current)) {
702 continue;
703 }
704 seen.add(current);
705
706 if (typeof current === "string") {
707 messages.push(current);
708 continue;
709 }
710
711 if (current instanceof Error) {
712 messages.push(current.message);
713 if (current.cause) {
714 queue.push(current.cause);
715 }
716 continue;
717 }
718
719 if (typeof current === "object") {
720 const value = current as { message?: unknown; cause?: unknown };
721 if (typeof value.message === "string") {
722 messages.push(value.message);
723 }
724 if (value.cause) {
725 queue.push(value.cause);
726 }
727 }
728 }
729
730 const message = messages.join(" ").toLowerCase();
731 return (
732 message.includes("posix_spawnp failed") ||
733 message.includes("enoent") ||
734 message.includes("not found") ||
735 message.includes("file not found") ||
736 message.includes("no such file")
737 );
738 }
739
740 interface TerminalProcessTableSnapshot {
741 readonly childrenByParent: ReadonlyMap<number, ReadonlyArray<number>>;
742 readonly commandById: ReadonlyMap<number, string>;
743 }
744
745 // Idles at least four times as long as the last fallback query took, so a slow
746 // process table never keeps the poll loop busy most of the time.
747 function subprocessSnapshotPollDelayMs(
748 pollIntervalMs: number,
749 failureCount: number,
750 queryElapsedMs: number,
751 ): number {
752 return Math.min(
753 Math.max(pollIntervalMs * 2 ** failureCount, queryElapsedMs * 4),
754 MAX_SUBPROCESS_POLL_INTERVAL_MS,
755 );
756 }
757
758 function parsePosixProcessTable(stdout: string): TerminalProcessTableSnapshot {
759 const childrenByParent = new Map<number, number[]>();
760 const commandById = new Map<number, string>();
761 for (const line of stdout.split(/\r?\n/g)) {
762 // The final comm column can contain spaces; only the first two tokens are structural.
763 const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
764 if (!match) continue;
765 const pid = Number(match[1]);
766 const ppid = Number(match[2]);
767 if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
768 commandById.set(pid, (match[3] ?? "").trim());
769 const children = childrenByParent.get(ppid) ?? [];
770 children.push(pid);
771 childrenByParent.set(ppid, children);
772 }
773 return { childrenByParent, commandById };
774 }
775
776 function processTableSnapshotFromProcesses(
777 processes: ReadonlyArray<ResourceMonitorProcessTableEntry>,
778 ): TerminalProcessTableSnapshot {
779 const childrenByParent = new Map<number, number[]>();
780 const commandById = new Map<number, string>();
781 for (const process of processes) {
782 const { pid, ppid: parentPid, name } = process;
783 if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
784 commandById.set(pid, name.trim());
785 const children = childrenByParent.get(parentPid) ?? [];
786 children.push(pid);
787 childrenByParent.set(parentPid, children);
788 }
789 return { childrenByParent, commandById };
790 }
791
792 // A root with one of these names is still an interactive shell, e.g. after `.bashrc` runs `exec zsh`.
793 const INTERACTIVE_SHELL_NAMES = new Set([
794 "bash",
795 "zsh",
796 "fish",
797 "sh",
798 "dash",
799 "ksh",
800 "mksh",
801 "tcsh",
802 "csh",
803 "nu",
804 ]);
805
806 function deriveSubprocessInspectResult(
807 snapshot: TerminalProcessTableSnapshot,
808 terminalPid: number,
809 shell: string | null,
810 platform: NodeJS.Platform,
811 foregroundProcessGroup?: number | null,
812 ): TerminalSubprocessInspectResult {
813 const commandName = (pid: number) =>
814 normalizeChildCommandName(snapshot.commandById.get(pid) ?? "", platform);
815 const shellName = commandName(terminalPid);
816 // `exec <command>` replaces the shell, leaving the command itself as the root.
817 const rootIsCommand =
818 platform !== "win32" &&
819 shell !== null &&
820 shellName !== null &&
821 shellName !== normalizeChildCommandName(shell, platform) &&
822 !INTERACTIVE_SHELL_NAMES.has(shellName.replace(/^-/, ""));
823 // Async prompt themes fork childless shell helpers that are not user commands;
824 // a foreground job owns the terminal's process group, and an unknown one counts as foreground.
825 const childPid = rootIsCommand
826 ? terminalPid
827 : (snapshot.childrenByParent.get(terminalPid) ?? []).find(
828 (pid) =>
829 shellName === null ||
830 commandName(pid) !== shellName ||
831 (snapshot.childrenByParent.get(pid)?.length ?? 0) > 0 ||
832 (foregroundProcessGroup !== undefined && foregroundProcessGroup !== terminalPid),
833 );
834 if (childPid === undefined) {
835 return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
836 }
837 const processIds = new Set<number>([terminalPid]);
838 const pending = [terminalPid];
839 while (pending.length > 0) {
840 const parentPid = pending.pop();
841 if (parentPid === undefined) continue;
842 for (const pid of snapshot.childrenByParent.get(parentPid) ?? []) {
843 if (processIds.has(pid)) continue;
844 processIds.add(pid);
845 pending.push(pid);
846 }
847 }
848 const normalized = commandName(childPid);
849 return {
850 hasRunningSubprocess: true,
851 childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
852 processIds: [...processIds],
853 };
854 }
855
856 // Field 8 of /proc/<pid>/stat is the tty's foreground process group; comm (field 2) may hold spaces or parens.
857 function parseProcStatForegroundProcessGroup(stat: string): number | null {
858 const tpgid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[5]);
859 return Number.isInteger(tpgid) ? tpgid : null;
860 }
861
862 const POSIX_PS_ABSOLUTE_PATHS = ["/bin/ps", "/usr/bin/ps"] as const;
863
864 // Resolve ps once; bare-name spawns repeatedly probe long PATHs during one-second polling.
865 const resolvePosixPsCommand = Effect.fn("terminal.resolvePosixPsCommand")(function* () {
866 const fileSystem = yield* FileSystem.FileSystem;
867 for (const candidate of POSIX_PS_ABSOLUTE_PATHS) {
868 const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
869 if (exists) return candidate;
870 }
871 return "ps";
872 });
873
874 const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot")(function* (
875 psCommand: string,
876 timeout: Duration.Input,
877 ): Effect.fn.Return<
878 TerminalProcessTableSnapshot,
879 TerminalSubprocessCheckError,
880 ProcessRunner.ProcessRunner
881 > {
882 const processRunner = yield* ProcessRunner.ProcessRunner;
883 const result = yield* processRunner
884 .run({
885 command: psCommand,
886 args: ["-eo", "pid=,ppid=,comm="],
887 timeout,
888 maxOutputBytes: 524_288,
889 outputMode: "truncate",
890 timeoutBehavior: "timedOutResult",
891 })
892 .pipe(
893 Effect.mapError(
894 (cause) =>
895 new TerminalSubprocessCheckError({
896 cause,
897 command: "ps",
898 }),
899 ),
900 );
901 if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
902 // Reject partial tables; treating them as authoritative would clear process ids and mark terminals idle.
903 return yield* new TerminalSubprocessCheckError({
904 command: "ps",
905 exitCode: result.code,
906 timedOut: result.timedOut,
907 stdoutTruncated: result.stdoutTruncated,
908 });
909 }
910 return parsePosixProcessTable(result.stdout);
911 });
912
913 const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")(function* (
914 timeout: Duration.Input,
915 ): Effect.fn.Return<
916 TerminalProcessTableSnapshot,
917 TerminalSubprocessCheckError,
918 ProcessRunner.ProcessRunner
919 > {
920 const processRunner = yield* ProcessRunner.ProcessRunner;
921 const command =
922 '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
923 const result = yield* processRunner
924 .run({
925 command: "powershell.exe",
926 args: ["-NoProfile", "-NonInteractive", "-Command", command],
927 timeout,
928 maxOutputBytes: 262_144,
929 outputMode: "truncate",
930 timeoutBehavior: "timedOutResult",
931 })
932 .pipe(
933 Effect.mapError(
934 (cause) => new TerminalSubprocessCheckError({ cause, command: "powershell" }),
935 ),
936 );
937 if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
938 return yield* new TerminalSubprocessCheckError({
939 command: "powershell",
940 exitCode: result.code,
941 timedOut: result.timedOut,
942 stdoutTruncated: result.stdoutTruncated,
943 });
944 }
945 const processes = result.stdout.split(/\r?\n/g).flatMap((line) => {
946 const [pidRaw, ppidRaw, name = ""] = line.trim().split("|", 3);
947 const pid = Number(pidRaw);
948 const ppid = Number(ppidRaw);
949 return Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) ? [{ pid, ppid, name }] : [];
950 });
951 return processTableSnapshotFromProcesses(processes);
952 });
953
954 interface TerminalHistoryChunk {
955 data: string;
956 byteLength: number;
957 lineBreaks: number;
958 }
959
960 interface TerminalHistoryPersistenceCursor {
961 readonly generation: number;
962 readonly offset: number;
963 readonly fileBytes: number;
964 }
965
966 function countLineBreaks(data: string): number {
967 let lineBreaks = 0;
968 for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) {
969 lineBreaks += 1;
970 }
971 return lineBreaks;
972 }
973
974 export class BoundedTerminalHistory {
975 private readonly maxLines: number;
976 private readonly maxBytes: number;
977 private chunks: Array<TerminalHistoryChunk | undefined> = [];
978 private start = 0;
979 private byteLength = 0;
980 private lineBreaks = 0;
981 // Reading the old string's tail on each append can force chunk concatenation.
982 private lastCodeUnit: number | undefined;
983 // The terminal parser's state at the first retained code unit, which is where a replay starts.
984 private sequenceState = TERMINAL_SEQUENCE_GROUND;
985 private cachedValue: string | null = "";
986 private generation = 0;
987 private appendedLength = 0;
988
989 constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) {
990 this.maxLines = maxLines;
991 this.maxBytes = maxBytes;
992 this.append(initial);
993 }
994
995 append(text: string): void {
996 if (text.length === 0) return;
997 this.appendedLength += text.length;
998 this.cachedValue = null;
999 if (this.maxBytes <= 0 || this.maxLines <= 0) {
1000 this.clear();
1001 if (this.maxBytes > 0 && text.endsWith("\n")) this.appendChunk("\n");
1002 return;
1003 }
1004
1005 let offset = 0;
1006 const previous = this.chunks.at(-1);
1007 const lastCode = this.lastCodeUnit;
1008 const firstCode = text.charCodeAt(0);
1009 if (
1010 previous &&
1011 lastCode !== undefined &&
1012 lastCode >= 0xd800 &&
1013 lastCode <= 0xdbff &&
1014 firstCode >= 0xdc00 &&
1015 firstCode <= 0xdfff
1016 ) {
1017 // Joining a split surrogate changes its UTF-8 size from 3 to 4 bytes.
1018 // The previous flush may have encoded the lone surrogate as a replacement character.
1019 this.generation += 1;
1020 previous.data += text[0];
1021 previous.byteLength += 1;
1022 this.byteLength += 1;
1023 this.lastCodeUnit = firstCode;
1024 offset = 1;
1025 this.trim();
1026 }
1027
1028 while (offset < text.length) {
1029 let end = Math.min(offset + MAX_HISTORY_CHUNK_LENGTH, text.length);
1030 const before = text.charCodeAt(end - 1);
1031 const after = text.charCodeAt(end);
1032 if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) {
1033 end -= 1;
1034 }
1035 const data = text.slice(offset, end);
1036 // Detach small chunks from large input strings so evicted prefixes can be collected.
1037 this.appendChunk(
1038 text.length > MAX_HISTORY_CHUNK_LENGTH
1039 ? Buffer.from(data, "utf16le").toString("utf16le")
1040 : data,
1041 );
1042 this.trim();
1043 offset = end;
1044 }
1045 }
1046
1047 private appendChunk(data: string): void {
1048 const byteLength = Buffer.byteLength(data);
1049 const lineBreaks = countLineBreaks(data);
1050 const previous = this.chunks.at(-1);
1051 if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) {
1052 previous.data += data;
1053 previous.byteLength += byteLength;
1054 previous.lineBreaks += lineBreaks;
1055 } else {
1056 this.chunks.push({ data, byteLength, lineBreaks });
1057 }
1058 this.byteLength += byteLength;
1059 this.lineBreaks += lineBreaks;
1060 this.lastCodeUnit = data.charCodeAt(data.length - 1);
1061 this.cachedValue = null;
1062 }
1063
1064 private discardChunk(): void {
1065 const first = this.chunks[this.start]!;
1066 this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data);
1067 this.byteLength -= first.byteLength;
1068 this.lineBreaks -= first.lineBreaks;
1069 this.chunks[this.start++] = undefined;
1070 }
1071
1072 private trimChunk(offset: number, byteLength: number, lineBreaks: number): void {
1073 const first = this.chunks[this.start]!;
1074 if (offset === first.data.length) {
1075 this.discardChunk();
1076 return;
1077 }
1078 this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data, 0, offset);
1079 first.data = first.data.slice(offset);
1080 first.byteLength -= byteLength;
1081 first.lineBreaks -= lineBreaks;
1082 this.byteLength -= byteLength;
1083 this.lineBreaks -= lineBreaks;
1084 }
1085
1086 private trim(): void {
1087 const trailingNewline = this.lastCodeUnit === 10;
1088 let linesToDrop = this.lineBreaks + (trailingNewline ? 0 : 1) - this.maxLines;
1089 while (linesToDrop > 0) {
1090 const first = this.chunks[this.start]!;
1091 if (first.lineBreaks < linesToDrop) {
1092 linesToDrop -= first.lineBreaks;
1093 this.discardChunk();
1094 continue;
1095 }
1096 let offset = 0;
1097 for (let line = 0; line < linesToDrop; line += 1) {
1098 offset = first.data.indexOf("\n", offset) + 1;
1099 }
1100 this.trimChunk(offset, Buffer.byteLength(first.data.slice(0, offset)), linesToDrop);
1101 linesToDrop = 0;
1102 }
1103
1104 while (this.byteLength > this.maxBytes) {
1105 const first = this.chunks[this.start]!;
1106 const bytesToDrop = this.byteLength - this.maxBytes;
1107 if (first.byteLength <= bytesToDrop) {
1108 this.discardChunk();
1109 continue;
1110 }
1111 if (first.byteLength === first.data.length && first.lineBreaks === 0) {
1112 this.trimChunk(bytesToDrop, bytesToDrop, 0);
1113 continue;
1114 }
1115 let offset = 0;
1116 let bytes = 0;
1117 let lineBreaks = 0;
1118 while (bytes < bytesToDrop) {
1119 const codePoint = first.data.codePointAt(offset)!;
1120 bytes += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;
1121 offset += codePoint <= 0xffff ? 1 : 2;
1122 if (codePoint === 10) lineBreaks += 1;
1123 }
1124 this.trimChunk(offset, bytes, lineBreaks);
1125 }
1126 // A cut inside a control sequence would replay the rest of it as text.
1127 while (this.sequenceState !== TERMINAL_SEQUENCE_GROUND && this.start < this.chunks.length) {
1128 const first = this.chunks[this.start]!;
1129 const dropped = first.data.slice(0, terminalSequenceEnd(this.sequenceState, first.data));
1130 this.trimChunk(dropped.length, Buffer.byteLength(dropped), countLineBreaks(dropped));
1131 }
1132 if (
1133 this.start === this.chunks.length ||
1134 (this.start > 2_048 && this.start * 2 >= this.chunks.length)
1135 ) {
1136 this.chunks = this.chunks.slice(this.start);
1137 this.start = 0;
1138 if (this.chunks.length === 0) this.lastCodeUnit = undefined;
1139 }
1140 }
1141
1142 clear(): void {
1143 this.generation += 1;
1144 this.appendedLength = 0;
1145 this.chunks = [];
1146 this.start = 0;
1147 this.byteLength = 0;
1148 this.lineBreaks = 0;
1149 this.lastCodeUnit = undefined;
1150 this.sequenceState = TERMINAL_SEQUENCE_GROUND;
1151 this.cachedValue = "";
1152 }
1153
1154 persistenceUpdate(previous?: TerminalHistoryPersistenceCursor) {
1155 const offset = this.appendedLength;
1156 let data: string | undefined;
1157 if (previous?.generation === this.generation) {
1158 let remaining = offset - previous.offset;
1159 const tail: string[] = [];
1160 for (let index = this.chunks.length - 1; remaining > 0 && index >= this.start; index -= 1) {
1161 const chunk = this.chunks[index]!.data;
1162 const suffix = chunk.slice(Math.max(0, chunk.length - remaining));
1163 tail.push(suffix);
1164 remaining -= suffix.length;
1165 }
1166 if (remaining === 0) data = tail.toReversed().join("");
1167 }
1168 // Keep the on-disk log bounded while amortizing compaction across new output.
1169 // Readers already cap the plain-text tail by bytes and lines.
1170 const append =
1171 data !== undefined &&
1172 previous !== undefined &&
1173 previous.fileBytes + Buffer.byteLength(data) <= this.maxBytes * 2;
1174 const output = append && data !== undefined ? data : this.value();
1175 return {
1176 data: output,
1177 append,
1178 cursor: {
1179 generation: this.generation,
1180 offset,
1181 fileBytes: (append ? previous.fileBytes : 0) + Buffer.byteLength(output),
1182 },
1183 };
1184 }
1185
1186 value(): string {
1187 if (this.cachedValue !== null) return this.cachedValue;
1188 this.cachedValue = this.chunks
1189 .slice(this.start)
1190 .map((chunk) => chunk!.data)
1191 .join("");
1192 return this.cachedValue;
1193 }
1194 }
1195
1196 // Pop beyond Ghostty's eight-entry Kitty stacks on both screens before clearing
1197 // flags. A 1049 round trip preserves the main cursor, text, and scrollback.
1198 const INHERITED_INPUT_RESET =
1199 "\u001b[?1049h\u001b[<100u\u001b[=0;1u\u001b[?1049l" +
1200 "\u001b[?1;9;66;67;1000;1002;1003;1004;1005;1006;1015;2004l" +
1201 "\u001b[?25;1035;1036h\u001b[<100u\u001b[=0;1u\u001b[>4m";
1202
1203 function neutralizeInheritedHistory(history: string, maxLines: number, maxBytes: number): string {
1204 // Scan exactly the cold replay window, reserving the entire longest reset so
1205 // neither the server nor the client can trim away the entry after we choose its exit.
1206 const resetBytes = history.includes("\u001b")
1207 ? Buffer.byteLength(INHERITED_INPUT_RESET + "\u001b7\u001b[?1049l")
1208 : 0;
1209 history = new BoundedTerminalHistory(
1210 // The suffix occupies the empty line after a trailing newline, too.
1211 resetBytes > 0 && history.endsWith("\n") ? maxLines - 1 : maxLines,
1212 history,
1213 Math.max(0, maxBytes - resetBytes),
1214 ).value();
1215 if (!history.includes("\u001b")) return history;
1216 // An unconditional 1049 reset restores a stale saved cursor on the main
1217 // screen. The exit must match the inherited screen's cursor-save behavior.
1218 let alternateScreen: number | undefined;
1219 for (const match of history.matchAll(/\u001b(?:\[\?([0-9;]+)([hl])|(c))/gu)) {
1220 if (match[3]) alternateScreen = undefined;
1221 for (const parameter of (match[1] ?? "").split(";")) {
1222 const mode = Number(parameter);
1223 if (mode === 47 || mode === 1047 || mode === 1049) {
1224 alternateScreen = match[2] === "h" ? (alternateScreen ?? mode) : undefined;
1225 }
1226 }
1227 }
1228 // A client may trim away the entry, leaving us on main: save its current
1229 // cursor before exiting. On alternate this saves only the alternate cursor.
1230 const leaveAlternateScreen =
1231 alternateScreen === undefined ? "" : `\u001b7\u001b[?${alternateScreen}l`;
1232 return history + leaveAlternateScreen + INHERITED_INPUT_RESET;
1233 }
1234
1235 function isCsiFinalByte(codePoint: number): boolean {
1236 return codePoint >= 0x40 && codePoint <= 0x7e;
1237 }
1238
1239 function isControlSequenceCancel(codePoint: number): boolean {
1240 return codePoint === 0x18 || codePoint === 0x1a;
1241 }
1242
1243 function shouldStripCsiSequence(body: string, finalByte: string): boolean {
1244 if (finalByte === "n") {
1245 return true;
1246 }
1247 if (finalByte === "R" && /^[0-9;?]*$/.test(body)) {
1248 return true;
1249 }
1250 if (finalByte === "c" && /^[>=0-9;?]*$/.test(body)) {
1251 return true;
1252 }
1253 // Strip DECRQM/DECRPM query traffic to prevent echoed replies during replay; $ guards preserve setters.
1254 if ((finalByte === "p" || finalByte === "y") && /^[0-9;?]*\$$/.test(body)) {
1255 return true;
1256 }
1257 // XTVERSION query (>q). DECSCUSR (space-intermediate q) stays.
1258 if (finalByte === "q" && /^>[0-9;]*$/.test(body)) {
1259 return true;
1260 }
1261 // Kitty keyboard protocol query/reply (?u). Restore-cursor (bare u) stays.
1262 if (finalByte === "u" && body.startsWith("?")) {
1263 return true;
1264 }
1265 return false;
1266 }
1267
1268 // Strip DECRQSS/XTGETTCAP query traffic; replaying queries triggers fresh replies without visual value.
1269 function shouldStripDcsSequence(content: string): boolean {
1270 return /^[01]?[$+][qr]/.test(content);
1271 }
1272
1273 function shouldStripOscSequence(content: string): boolean {
1274 return /^(10|11|12);(?:\?|rgb:)/.test(content);
1275 }
1276
1277 function stripStringTerminator(value: string): string {
1278 if (value.endsWith("\u001b\\")) {
1279 return value.slice(0, -2);
1280 }
1281 const lastCharacter = value.at(-1);
1282 if (lastCharacter === "\u0007" || lastCharacter === "\u009c") {
1283 return value.slice(0, -1);
1284 }
1285 return value;
1286 }
1287
1288 interface C1Effect {
1289 /** ESC form of the sequence the code point starts, or "" when it returns to ground. */
1290 readonly next: string;
1291 /** Its 0x9A byte ran DECID, which replies with device attributes. */
1292 readonly query: boolean;
1293 /** What replays its visible effect from ground. */
1294 readonly safe: string;
1295 }
1296
1297 // Outside ground and OSC, libghostty parses a code point's UTF-8 bytes one at a time: 0x80-0x9F
1298 // act as C1 controls, the rest are dropped. Bytes left over after a return to ground print U+FFFD.
1299 function c1Effect(codePoint: number): C1Effect | undefined {
1300 // A lone surrogate is encoded as U+FFFD, whose bytes are all dropped.
1301 if (codePoint >= 0xd800 && codePoint <= 0xdfff) return undefined;
1302 let next: string | undefined;
1303 let query = false;
1304 let safe = "";
1305 for (let shift = codePoint > 0xffff ? 12 : codePoint > 0x7ff ? 6 : 0; shift >= 0; shift -= 6) {
1306 const byte = 0x80 | ((codePoint >> shift) & 0x3f);
1307 if (next === "") {
1308 safe += "\ufffd";
1309 } else if (next?.startsWith("\u001b]")) {
1310 next += "\ufffd";
1311 } else if (byte === 0x9b) {
1312 next = "\u001b[";
1313 } else if (byte === 0x9d) {
1314 next = "\u001b]";
1315 } else if (byte === 0x90) {
1316 next = "\u001bP";
1317 } else if (byte === 0x98 || byte === 0x9e || byte === 0x9f) {
1318 next = "\u001b_";
1319 } else if (byte < 0xa0) {
1320 next = "";
1321 query = byte === 0x9a;
1322 // Any other C1 control but ST runs as ESC plus the byte less 0x40.
1323 safe = query || byte === 0x9c ? "" : `\u001b${String.fromCharCode(byte - 0x40)}`;
1324 }
1325 }
1326 return next === undefined ? undefined : { next, query, safe };
1327 }
1328
1329 // BEL ends only OSC; inside DCS, PM and APC it is payload. Non-ASCII is the reverse: libghostty
1330 // keeps it inside OSC, while a C1 byte in it ends the other strings.
1331 function findStringEnd(
1332 input: string,
1333 start: number,
1334 isOsc: boolean,
1335 ): { end: number; c1?: { effect: C1Effect; index: number } } | null {
1336 for (let index = start; index < input.length; index += 1) {
1337 const codePoint = input.charCodeAt(index);
1338 if ((isOsc && codePoint === 0x07) || isControlSequenceCancel(codePoint)) {
1339 return { end: index + 1 };
1340 }
1341 // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence.
1342 if (codePoint === 0x1b) {
1343 if (index + 1 >= input.length) return null;
1344 return { end: input.charCodeAt(index + 1) === 0x5c ? index + 2 : index };
1345 }
1346 if (codePoint >= 0x80 && !isOsc) {
1347 const fullCodePoint = input.codePointAt(index) ?? codePoint;
1348 const end = index + (fullCodePoint > 0xffff ? 2 : 1);
1349 const effect = c1Effect(fullCodePoint);
1350 if (effect) return { end, c1: { effect, index } };
1351 index = end - 1;
1352 }
1353 }
1354 return null;
1355 }
1356
1357 function isEscapeIntermediateByte(codePoint: number): boolean {
1358 return codePoint >= 0x20 && codePoint <= 0x2f;
1359 }
1360
1361 function isEscapeFinalByte(codePoint: number): boolean {
1362 return codePoint >= 0x30 && codePoint <= 0x7e;
1363 }
1364
1365 function findEscapeSequenceEndIndex(input: string, start: number): number | null {
1366 let cursor = start;
1367 while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) {
1368 cursor += 1;
1369 }
1370 if (cursor >= input.length) {
1371 return null;
1372 }
1373 // A second ESC restarts the sequence, so leave it for the next pass.
1374 if (input.charCodeAt(cursor) === 0x1b) {
1375 return cursor;
1376 }
1377 return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1;
1378 }
1379
1380 // libghostty prints UTF-8 C1 code points (U+0080-U+009F) as text, so only ESC starts a sequence.
1381 const HISTORY_SEQUENCE_START = /\u001b/;
1382 const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g");
1383
1384 function sanitizeTerminalHistoryChunk(
1385 pendingControlSequence: string,
1386 data: string,
1387 ): { visibleText: string; pendingControlSequence: string } {
1388 if (pendingControlSequence.length === 0 && !HISTORY_SEQUENCE_START.test(data)) {
1389 return { visibleText: data, pendingControlSequence: "" };
1390 }
1391
1392 const input = `${pendingControlSequence}${data}`;
1393 // Only the pending prefix's final ESC can begin a terminator split across chunks.
1394 const pendingScanStart = Math.max(0, pendingControlSequence.length - 1);
1395 let visibleText = "";
1396 let index = 0;
1397 // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it.
1398 let c1Introducer = "";
1399
1400 const append = (value: string) => {
1401 visibleText += value;
1402 };
1403
1404 while (index < input.length) {
1405 const codePoint = input.charCodeAt(index);
1406
1407 if (c1Introducer.length > 0 || codePoint === 0x1b) {
1408 // Empty for a sequence the input introduces itself, which starts with ESC at `index`.
1409 const prefix = c1Introducer;
1410 c1Introducer = "";
1411 const contentStart = prefix.length > 0 ? index : index + 2;
1412 const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1);
1413 if (Number.isNaN(nextCodePoint)) {
1414 return { visibleText, pendingControlSequence: input.slice(index) };
1415 }
1416
1417 if (nextCodePoint === 0x5b) {
1418 let cursor = contentStart;
1419 // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would
1420 // print in ground state. None join the parameters; only executed ones survive a strip.
1421 let body = "";
1422 let executedControls = "";
1423 while (cursor < input.length) {
1424 const cursorCodePoint = input.charCodeAt(cursor);
1425 const cancelled = isControlSequenceCancel(cursorCodePoint);
1426 if (cancelled || isCsiFinalByte(cursorCodePoint)) {
1427 if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) {
1428 append(prefix + input.slice(index, cursor + 1));
1429 } else {
1430 append(executedControls);
1431 }
1432 index = cursor + 1;
1433 break;
1434 }
1435 if (cursorCodePoint >= 0x80) {
1436 const fullCodePoint = input.codePointAt(cursor) ?? cursorCodePoint;
1437 const end = cursor + (fullCodePoint > 0xffff ? 2 : 1);
1438 const c1 = c1Effect(fullCodePoint);
1439 if (c1) {
1440 // The CSI ends here undispatched, so it is kept only when the terminal is back in
1441 // ground with nothing to answer.
1442 if (c1.next.length === 0 && !c1.query) {
1443 append(prefix + input.slice(index, end));
1444 } else {
1445 append(executedControls + c1.safe);
1446 }
1447 c1Introducer = c1.next;
1448 index = end;
1449 break;
1450 }
1451 cursor = end;
1452 continue;
1453 }
1454 // An ESC abandons the CSI and starts the next sequence, which may be stripped.
1455 if (cursorCodePoint === 0x1b) {
1456 append(executedControls);
1457 index = cursor;
1458 break;
1459 }
1460 if (cursorCodePoint < 0x10) {
1461 executedControls += input[cursor];
1462 } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) {
1463 body += input[cursor];
1464 }
1465 cursor += 1;
1466 }
1467 if (cursor >= input.length) {
1468 return { visibleText, pendingControlSequence: prefix + input.slice(index) };
1469 }
1470 continue;
1471 }
1472
1473 if (
1474 nextCodePoint === 0x5d ||
1475 nextCodePoint === 0x50 ||
1476 nextCodePoint === 0x5e ||
1477 nextCodePoint === 0x5f
1478 ) {
1479 const stringEnd = findStringEnd(
1480 input,
1481 Math.max(contentStart, pendingScanStart),
1482 nextCodePoint === 0x5d,
1483 );
1484 if (stringEnd === null) {
1485 return { visibleText, pendingControlSequence: prefix + input.slice(index) };
1486 }
1487 const { end, c1 } = stringEnd;
1488 const content = stripStringTerminator(
1489 prefix.slice(2) + input.slice(contentStart, c1?.index ?? end),
1490 );
1491 const strip =
1492 (nextCodePoint === 0x5d && shouldStripOscSequence(content)) ||
1493 (nextCodePoint === 0x50 && shouldStripDcsSequence(content));
1494 if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) {
1495 if (!strip) {
1496 append(prefix + input.slice(index, end));
1497 }
1498 } else {
1499 // ST stands in for a code point that cannot be replayed as it came.
1500 const closed = strip ? "" : `${prefix}${input.slice(index, c1.index)}\u009c`;
1501 append(closed + c1.effect.safe);
1502 c1Introducer = c1.effect.next;
1503 }
1504 index = end;
1505 continue;
1506 }
1507
1508 const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1);
1509 if (escapeSequenceEndIndex === null) {
1510 return { visibleText, pendingControlSequence: input.slice(index) };
1511 }
1512 // ESC Z (DECID) is the legacy primary device attributes query.
1513 if (nextCodePoint !== 0x5a) {
1514 append(input.slice(index, escapeSequenceEndIndex));
1515 }
1516 index = escapeSequenceEndIndex;
1517 continue;
1518 }
1519
1520 // One slice per printable run: every chunk of coloured output reaches this loop.
1521 NEXT_HISTORY_SEQUENCE_START.lastIndex = index + 1;
1522 const nextSequenceStart = NEXT_HISTORY_SEQUENCE_START.exec(input)?.index ?? input.length;
1523 append(input.slice(index, nextSequenceStart));
1524 index = nextSequenceStart;
1525 }
1526
1527 return { visibleText, pendingControlSequence: c1Introducer };
1528 }
1529
1530 function legacySafeThreadId(threadId: string): string {
1531 return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
1532 }
1533
1534 function encodedHistoryThreadPart(threadId: string): string {
1535 return `terminal_${Base64Url.encode(threadId)}`;
1536 }
1537
1538 function hashId(id: string): string {
1539 return NodeCrypto.createHash("sha256").update(id).digest("base64url");
1540 }
1541
1542 // "." is outside the base64url alphabet, so a hashed name can never collide with an encoded one.
1543 function hashedHistoryThreadPart(threadId: string): string {
1544 return `terminal_sha256.${hashId(threadId)}`;
1545 }
1546
1547 function joinHistoryFileName(threadPart: string, terminalPart: string | null): string {
1548 return terminalPart === null ? `${threadPart}.log` : `${threadPart}_${terminalPart}.log`;
1549 }
1550
1551 function toSessionKey(threadId: string, terminalId: string): string {
1552 return `${threadId}\u0000${terminalId}`;
1553 }
1554
1555 function shouldExcludeTerminalEnvKey(key: string): boolean {
1556 const normalizedKey = key.toUpperCase();
1557 if (normalizedKey.startsWith("T3CODE_")) {
1558 return true;
1559 }
1560 if (normalizedKey.startsWith("VITE_")) {
1561 return true;
1562 }
1563 return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
1564 }
1565
1566 const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const;
1567 const APPIMAGE_PATH_LIKE_ENV_KEYS = [
1568 "PATH",
1569 "LD_LIBRARY_PATH",
1570 "XDG_DATA_DIRS",
1571 "GSETTINGS_SCHEMA_DIR",
1572 ] as const;
1573
1574 function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean {
1575 return segment === appDir || segment.startsWith(`${appDir}/`);
1576 }
1577
1578 // AppImage mount paths would make PTY tools resolve against the mount instead of the user's system.
1579 function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
1580 if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env;
1581
1582 const scrubbed: NodeJS.ProcessEnv = { ...env };
1583 for (const key of APPIMAGE_RUNTIME_ENV_KEYS) {
1584 delete scrubbed[key];
1585 }
1586
1587 const appDir = env.APPDIR?.replace(/\/+$/, "");
1588 if (appDir) {
1589 for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) {
1590 const value = scrubbed[key];
1591 if (value === undefined) continue;
1592 const kept = value
1593 .split(":")
1594 .filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir));
1595 if (kept.length > 0) {
1596 scrubbed[key] = kept.join(":");
1597 } else {
1598 delete scrubbed[key];
1599 }
1600 }
1601 }
1602
1603 return scrubbed;
1604 }
1605
1606 function createTerminalSpawnEnv(
1607 baseEnv: NodeJS.ProcessEnv,
1608 runtimeEnv: Record<string, string> | null | undefined,
1609 platform: NodeJS.Platform,
1610 home: string,
1611 threadId: string,
1612 ): NodeJS.ProcessEnv {
1613 const spawnEnv: NodeJS.ProcessEnv = {};
1614 for (const [key, value] of Object.entries(baseEnv)) {
1615 if (value === undefined) continue;
1616 if (shouldExcludeTerminalEnvKey(key)) continue;
1617 if (platform === "win32") {
1618 const normalizedKey = key.toUpperCase();
1619 if (normalizedKey === "TERM_PROGRAM" || normalizedKey === "TERM_PROGRAM_VERSION") continue;
1620 }
1621 spawnEnv[key] = value;
1622 }
1623 // The server inherits its launcher's identity (e.g. Apple_Terminal); shells
1624 // and tools inside the integrated terminal should see T3 Code instead.
1625 spawnEnv.TERM_PROGRAM = "t3code";
1626 spawnEnv.TERM_PROGRAM_VERSION = packageJson.version;
1627 if (runtimeEnv) {
1628 for (const [key, value] of Object.entries(runtimeEnv)) {
1629 const existingKey =
1630 platform === "win32"
1631 ? Object.keys(spawnEnv).find((candidate) => candidate.toLowerCase() === key.toLowerCase())
1632 : undefined;
1633 spawnEnv[existingKey ?? key] = expandHomeVariable(
1634 platform === "win32" ? key.toUpperCase() : key,
1635 value,
1636 home,
1637 );
1638 }
1639 }
1640 spawnEnv[PortScanner.AGENT_THREAD_ENV] = threadId;
1641 if (!spawnEnv.COLORTERM && runtimeEnv?.COLORTERM === undefined) {
1642 spawnEnv.COLORTERM = "truecolor";
1643 }
1644 // fish 4.1+ can wait 10s at startup for a DA1 reply before a renderer can answer.
1645 // Skip the query unless the user or provider already chose `query-term` or `no-query-term`.
1646 const fishFeaturesKey =
1647 platform === "win32"
1648 ? (Object.keys(spawnEnv).find((candidate) => candidate.toLowerCase() === "fish_features") ??
1649 "fish_features")
1650 : "fish_features";
1651 const fishFeatures = spawnEnv[fishFeaturesKey];
1652 if (!fishFeatures?.includes("query-term")) {
1653 spawnEnv[fishFeaturesKey] = fishFeatures ? `${fishFeatures},no-query-term` : "no-query-term";
1654 }
1655 return stripAppImageRuntimeEnv(spawnEnv);
1656 }
1657
1658 function normalizedRuntimeEnv(
1659 env: Record<string, string> | undefined,
1660 ): Record<string, string> | null {
1661 if (!env) return null;
1662 const entries = Object.entries(env);
1663 if (entries.length === 0) return null;
1664 return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right)));
1665 }
1666
1667 interface TerminalManagerOptions {
1668 logsDir: string;
1669 historyLineLimit?: number;
1670 historyByteLimit?: number;
1671 ptyAdapter: PtyAdapter.PtyAdapter["Service"];
1672 shellResolver?: () => string;
1673 env?: NodeJS.ProcessEnv;
1674 managedBinaryCacheDir?: string;
1675 managedBinaryToolsDir?: string;
1676 subprocessInspector?: TerminalSubprocessInspector;
1677 processTable?: Effect.Effect<
1678 ReadonlyArray<ResourceMonitorProcessTableEntry>,
1679 TerminalSubprocessCheckError
1680 >;
1681 foregroundProcessGroup?: (terminalPid: number) => Effect.Effect<number | null>;
1682 subprocessPollIntervalMs?: number;
1683 processKillGraceMs?: number;
1684 maxRetainedInactiveSessions?: number;
1685 registerTerminalProcesses?: (input: {
1686 readonly threadId: string;
1687 readonly terminalId: string;
1688 readonly processIds: ReadonlyArray<number>;
1689 }) => Effect.Effect<void>;
1690 unregisterTerminal?: (input: {
1691 readonly threadId: string;
1692 readonly terminalId: string;
1693 }) => Effect.Effect<void>;
1694 resolveProviderInstanceEnvironment?: (
1695 providerInstanceId: string,
1696 env: Record<string, string> | undefined,
1697 ) => Effect.Effect<
1698 Record<string, string>,
1699 TerminalProviderInstanceNotFoundError | TerminalProviderEnvironmentError
1700 >;
1701 }
1702
1703 export const resolveProviderInstanceTerminalEnvironment = Effect.fn(
1704 "terminal.resolveProviderInstanceTerminalEnvironment",
1705 )(function* (input: {
1706 readonly deriveProviderInstanceConfigMap: typeof deriveProviderInstanceConfigMap;
1707 readonly serverSettings: ServerSettings.ServerSettingsService["Service"];
1708 readonly path: Path.Path;
1709 readonly rawProviderInstanceId: string;
1710 readonly env: Record<string, string> | undefined;
1711 }) {
1712 const providerInstanceId = ProviderInstanceId.make(input.rawProviderInstanceId);
1713 const settings = yield* input.serverSettings.getSettings.pipe(
1714 Effect.mapError((cause) => new TerminalProviderEnvironmentError({ providerInstanceId, cause })),
1715 );
1716 const instance = input.deriveProviderInstanceConfigMap(settings)[providerInstanceId];
1717 if (instance === undefined) {
1718 return yield* new TerminalProviderInstanceNotFoundError({ providerInstanceId });
1719 }
1720
1721 let resolved = yield* mergeProviderInstanceEnvironment(instance.environment, input.env ?? {});
1722 if (instance.driver === "codex") {
1723 const config = decodeCodexSettings(instance.config ?? {});
1724 if (Option.isSome(config)) {
1725 const layout = yield* resolveCodexHomeLayout(config.value).pipe(
1726 Effect.provideService(Path.Path, input.path),
1727 );
1728 if (layout.effectiveHomePath)
1729 resolved = { ...resolved, CODEX_HOME: layout.effectiveHomePath };
1730 }
1731 } else if (instance.driver === "claudeAgent") {
1732 const config = decodeClaudeSettings(instance.config ?? {});
1733 if (Option.isSome(config)) {
1734 resolved = yield* makeClaudeEnvironment(config.value, resolved).pipe(
1735 Effect.provideService(Path.Path, input.path),
1736 );
1737 }
1738 }
1739
1740 return Object.fromEntries(
1741 Object.entries(resolved).filter((entry): entry is [string, string] => entry[1] !== undefined),
1742 );
1743 });
1744
1745 /** @public */
1746 export const make = Effect.fn("TerminalManager.make")(function* (
1747 deriveConfigMap: typeof deriveProviderInstanceConfigMap,
1748 ) {
1749 const { terminalLogsDir, providerStatusCacheDir, baseDir } = yield* ServerConfig.ServerConfig;
1750 const ptyAdapter = yield* PtyAdapter.PtyAdapter;
1751 const portDiscovery = yield* PortScanner.PortDiscovery;
1752 const nativeTelemetry = yield* NativeTelemetryClient.NativeTelemetryClient;
1753 const serverSettings = yield* ServerSettings.ServerSettingsService;
1754 const path = yield* Path.Path;
1755 const resolveProviderInstanceEnvironment = Effect.fn(
1756 "terminal.resolveProviderInstanceEnvironment",
1757 )((rawProviderInstanceId: string, env: Record<string, string> | undefined) =>
1758 resolveProviderInstanceTerminalEnvironment({
1759 deriveProviderInstanceConfigMap: deriveConfigMap,
1760 serverSettings,
1761 path,
1762 rawProviderInstanceId,
1763 env,
1764 }),
1765 );
1766 return yield* makeWithOptions({
1767 logsDir: terminalLogsDir,
1768 ptyAdapter,
1769 processTable: nativeTelemetry.processTable.pipe(
1770 Effect.mapError(
1771 (cause) => new TerminalSubprocessCheckError({ cause, command: "resource-monitor" }),
1772 ),
1773 ),
1774 managedBinaryCacheDir: providerStatusCacheDir,
1775 managedBinaryToolsDir: path.join(baseDir, "tools"),
1776 registerTerminalProcesses: portDiscovery.registerTerminalProcesses,
1777 unregisterTerminal: portDiscovery.unregisterTerminal,
1778 resolveProviderInstanceEnvironment,
1779 });
1780 });
1781
1782 export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(function* (
1783 options: TerminalManagerOptions,
1784 ) {
1785 const fileSystem = yield* FileSystem.FileSystem;
1786 const path = yield* Path.Path;
1787 const context = yield* Effect.context<never>();
1788 const runFork = Effect.runForkWith(context);
1789
1790 const logsDir = options.logsDir;
1791 const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
1792 const historyByteLimit = options.historyByteLimit ?? DEFAULT_HISTORY_BYTE_LIMIT;
1793 const platform = yield* HostProcess.Platform;
1794 const architecture = yield* HostProcess.Architecture;
1795 const agentScope = yield* AgentScope;
1796 const resolveExecutable = yield* SpawnExecutableResolution;
1797 // Inherit the full environment minus createTerminalSpawnEnv's blocklist; allowlists silently drop user tooling variables.
1798 const baseEnv = options.env ?? process.env;
1799 const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
1800 const processRunner = yield* ProcessRunner.ProcessRunner;
1801 const resolveLaunchInputEnvironment = Effect.fn("terminal.resolveLaunchInputEnvironment")(
1802 function* <Input extends TerminalOpenInput | TerminalAttachInput>(
1803 input: Input,
1804 ): Effect.fn.Return<
1805 Input,
1806 TerminalProviderInstanceNotFoundError | TerminalProviderEnvironmentError
1807 > {
1808 if (input.providerInstanceId === undefined) return input;
1809 const resolver = options.resolveProviderInstanceEnvironment;
1810 if (resolver === undefined) {
1811 return yield* new TerminalProviderInstanceNotFoundError({
1812 providerInstanceId: ProviderInstanceId.make(input.providerInstanceId),
1813 });
1814 }
1815 const env = yield* resolver(input.providerInstanceId, input.env);
1816 return { ...input, env };
1817 },
1818 );
1819 // Share one process table per poll; per-terminal scans can exhaust PIDs on busy hosts.
1820 // Timed on success and failure so the poll loop can pace the next query.
1821 const posixPsCommand = platform === "win32" ? undefined : yield* resolvePosixPsCommand();
1822 const fallbackProcessTableSnapshot = (timeout: Duration.Input) =>
1823 (posixPsCommand === undefined
1824 ? windowsProcessTableSnapshot(timeout)
1825 : posixProcessTableSnapshot(posixPsCommand, timeout)
1826 ).pipe(
1827 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
1828 Effect.result,
1829 Effect.timed,
1830 Effect.map(([elapsed, snapshot]) => ({
1831 snapshot,
1832 queryElapsedMs: Duration.toMillis(elapsed),
1833 })),
1834 );
1835 // `fallbackTimeout` only bounds the ps/WMI fallback; a native process table
1836 // or custom inspector is unaffected.
1837 const fetchProcessTableSnapshot = (
1838 fallbackTimeout: Duration.Input,
1839 ): Effect.Effect<{
1840 readonly snapshot: Result.Result<TerminalProcessTableSnapshot, TerminalSubprocessCheckError>;
1841 readonly snapshotSucceeded: boolean;
1842 readonly queryElapsedMs: number;
1843 }> =>
1844 options.processTable
1845 ? options.processTable.pipe(
1846 Effect.map((entries) => ({
1847 snapshot: Result.succeed(processTableSnapshotFromProcesses(entries)),
1848 snapshotSucceeded: true,
1849 queryElapsedMs: 0,
1850 })),
1851 Effect.catch(() =>
1852 fallbackProcessTableSnapshot(fallbackTimeout).pipe(
1853 Effect.map((fallback) => ({ ...fallback, snapshotSucceeded: false })),
1854 ),
1855 ),
1856 )
1857 : fallbackProcessTableSnapshot(fallbackTimeout).pipe(
1858 Effect.map((fallback) => ({
1859 ...fallback,
1860 snapshotSucceeded: Result.isSuccess(fallback.snapshot),
1861 })),
1862 );
1863 const foregroundProcessGroup =
1864 options.foregroundProcessGroup ??
1865 ((terminalPid: number) =>
1866 platform === "linux"
1867 ? fileSystem.readFileString(`/proc/${terminalPid}/stat`).pipe(
1868 Effect.map(parseProcStatForegroundProcessGroup),
1869 Effect.orElseSucceed(() => null),
1870 )
1871 : processRunner
1872 .run({
1873 command: posixPsCommand ?? "ps",
1874 args: ["-o", "tpgid=", "-p", String(terminalPid)],
1875 timeout: CLOSE_IDLE_QUERY_TIMEOUT.posix,
1876 timeoutBehavior: "timedOutResult",
1877 })
1878 .pipe(
1879 Effect.map((result) => {
1880 const tpgid = Number(result.stdout.trim());
1881 return result.code === 0 && !result.timedOut && Number.isInteger(tpgid) && tpgid > 0
1882 ? tpgid
1883 : null;
1884 }),
1885 Effect.orElseSucceed(() => null),
1886 ));
1887 const customSubprocessInspector = options.subprocessInspector;
1888 const acquireSubprocessInspector = (
1889 fallbackTimeout: Duration.Input,
1890 ): Effect.Effect<{
1891 readonly inspector: Result.Result<TerminalSubprocessInspector, TerminalSubprocessCheckError>;
1892 readonly snapshotSucceeded: boolean;
1893 readonly queryElapsedMs: number;
1894 }> =>
1895 customSubprocessInspector !== undefined
1896 ? Effect.succeed({
1897 inspector: Result.succeed(customSubprocessInspector),
1898 snapshotSucceeded: true,
1899 queryElapsedMs: 0,
1900 })
1901 : Effect.map(
1902 fetchProcessTableSnapshot(fallbackTimeout),
1903 ({ snapshot, snapshotSucceeded, queryElapsedMs }) => ({
1904 inspector: Result.map(
1905 snapshot,
1906 (table): TerminalSubprocessInspector =>
1907 (terminalPid, shell) => {
1908 const result = deriveSubprocessInspectResult(table, terminalPid, shell, platform);
1909 // Only shell-named childless children are ambiguous; read the foreground group for those alone.
1910 if (
1911 result.hasRunningSubprocess ||
1912 platform === "win32" ||
1913 (table.childrenByParent.get(terminalPid)?.length ?? 0) === 0
1914 ) {
1915 return Effect.succeed(result);
1916 }
1917 return Effect.map(foregroundProcessGroup(terminalPid), (group) =>
1918 deriveSubprocessInspectResult(table, terminalPid, shell, platform, group),
1919 );
1920 },
1921 ),
1922 snapshotSucceeded,
1923 queryElapsedMs,
1924 }),
1925 );
1926 const subprocessPollIntervalMs =
1927 options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
1928 const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
1929 const maxRetainedInactiveSessions =
1930 options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
1931 const registerTerminalProcesses = options.registerTerminalProcesses ?? (() => Effect.void);
1932 const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void);
1933
1934 yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
1935
1936 const managerId = NodeCrypto.randomUUID();
1937 const managerStateRef = yield* SynchronizedRef.make<TerminalManagerState>({
1938 sessions: new Map(),
1939 killFibers: new Map(),
1940 });
1941 // Keep close markers in memory so unknown IDs recover after a server restart.
1942 const closedSessionKeys = new Set<string>();
1943 const threadLocks = yield* KeyedLock.make<string>();
1944 const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
1945 const workerScope = yield* Scope.make("sequential");
1946 yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void));
1947
1948 const publishEvent =
1949 /* Provider events include streaming deltas; avoid a span for each update. */
1950 Effect.fnUntraced(function* (event: TerminalEvent) {
1951 for (const listener of terminalEventListeners) {
1952 yield* listener(event).pipe(Effect.ignoreCause({ log: true }));
1953 }
1954 });
1955
1956 const encodedHistoryPath = (threadId: string, terminalId: string) =>
1957 path.join(
1958 logsDir,
1959 joinHistoryFileName(
1960 encodedHistoryThreadPart(threadId),
1961 terminalId === DEFAULT_TERMINAL_ID ? null : Base64Url.encode(terminalId),
1962 ),
1963 );
1964
1965 const historyPath = (threadId: string, terminalId: string) => {
1966 const encoded = encodedHistoryPath(threadId, terminalId);
1967 if (path.basename(encoded).length <= MAX_HISTORY_FILENAME_BYTES) return encoded;
1968 return path.join(
1969 logsDir,
1970 joinHistoryFileName(
1971 hashedHistoryThreadPart(threadId),
1972 terminalId === DEFAULT_TERMINAL_ID ? null : hashId(terminalId),
1973 ),
1974 );
1975 };
1976
1977 const legacyHistoryName = (threadId: string) => `${legacySafeThreadId(threadId)}.log`;
1978 // Legacy names in the current "terminal_" namespace would alias another thread's history,
1979 // case-insensitively on some filesystems.
1980 const hasLegacyHistoryName = (threadId: string) =>
1981 !legacySafeThreadId(threadId).toLowerCase().startsWith("terminal_");
1982
1983 const historyPaths = (threadId: string, terminalId: string) => [
1984 ...new Set([
1985 historyPath(threadId, terminalId),
1986 encodedHistoryPath(threadId, terminalId),
1987 ...(terminalId === DEFAULT_TERMINAL_ID && hasLegacyHistoryName(threadId)
1988 ? [path.join(logsDir, legacyHistoryName(threadId))]
1989 : []),
1990 ]),
1991 ];
1992
1993 const historyExists = (filePath: string) => {
1994 const name = path.basename(filePath);
1995 // An oversized old path can itself fail on access. Directory entries also
1996 // preserve migration of such histories on filesystems with a larger limit.
1997 return name.length <= MAX_HISTORY_FILENAME_BYTES
1998 ? fileSystem.exists(filePath)
1999 : fileSystem.readDirectory(logsDir).pipe(Effect.map((entries) => entries.includes(name)));
2000 };
2001
2002 const readManagerState = SynchronizedRef.get(managerStateRef);
2003
2004 const modifyManagerState = <A>(
2005 f: (state: TerminalManagerState) => readonly [A, TerminalManagerState],
2006 ) => SynchronizedRef.modify(managerStateRef, f);
2007
2008 const withThreadLock = <A, E, R>(
2009 threadId: string,
2010 effect: Effect.Effect<A, E, R>,
2011 ): Effect.Effect<A, E, R> => threadLocks.withLock(threadId, effect);
2012
2013 const terminalViewers = new Map<string, Map<string, TerminalViewer>>();
2014 let anonymousViewerCount = 0;
2015
2016 const retainViewer = (sessionKey: string, viewerId: string, grid: TerminalGrid | null) => {
2017 let viewers = terminalViewers.get(sessionKey);
2018 if (!viewers) {
2019 viewers = new Map();
2020 terminalViewers.set(sessionKey, viewers);
2021 }
2022 const viewer = viewers.get(viewerId);
2023 if (viewer) {
2024 viewer.streams += 1;
2025 // After a viewer's first size, resizes own it; attach retries resend the original size.
2026 viewer.grid ??= grid;
2027 } else {
2028 viewers.set(viewerId, { streams: 1, grid, answersQueries: false });
2029 }
2030 };
2031
2032 /** Returns whether the viewer left, which can grow the shared grid. */
2033 const releaseViewer = (sessionKey: string, viewerId: string) => {
2034 const viewers = terminalViewers.get(sessionKey);
2035 const viewer = viewers?.get(viewerId);
2036 if (!viewers || !viewer) return false;
2037 viewer.streams -= 1;
2038 if (viewer.streams > 0) return false;
2039 viewers.delete(viewerId);
2040 if (viewers.size === 0) terminalViewers.delete(sessionKey);
2041 return true;
2042 };
2043
2044 // The first attached viewer to answer a query keeps answering until it detaches.
2045 const acceptsQueryReply = (sessionKey: string, viewerId: string | undefined) => {
2046 const viewers = terminalViewers.get(sessionKey);
2047 const viewer = viewerId === undefined ? undefined : viewers?.get(viewerId);
2048 if (viewerId !== undefined && !viewer) return false;
2049 if (viewer?.answersQueries) return true;
2050 for (const other of viewers?.values() ?? []) {
2051 if (other.answersQueries) return false;
2052 }
2053 if (viewer) viewer.answersQueries = true;
2054 return true;
2055 };
2056
2057 // The smallest attached viewer bounds each axis, so every viewer can draw the whole grid.
2058 const sharedViewerGrid = (sessionKey: string): TerminalGrid | null => {
2059 let shared: TerminalGrid | null = null;
2060 for (const viewer of terminalViewers.get(sessionKey)?.values() ?? []) {
2061 if (!viewer.grid) continue;
2062 shared = shared
2063 ? {
2064 cols: Math.min(shared.cols, viewer.grid.cols),
2065 rows: Math.min(shared.rows, viewer.grid.rows),
2066 }
2067 : viewer.grid;
2068 }
2069 return shared;
2070 };
2071
2072 /** Attached viewers own the size; a caller's own size only applies when none has reported one. */
2073 const withSharedGrid = <
2074 A extends { readonly cols?: number | undefined; readonly rows?: number | undefined },
2075 >(
2076 sessionKey: string,
2077 input: A,
2078 ): A => {
2079 const shared = sharedViewerGrid(sessionKey);
2080 return shared ? { ...input, cols: shared.cols, rows: shared.rows } : input;
2081 };
2082
2083 // Renderers draw the PTY grid, so every size change reaches them. It rides on activity
2084 // because older clients reject unknown event types.
2085 const resizeSession = Effect.fnUntraced(function* (
2086 session: TerminalSessionState,
2087 process: PtyAdapter.PtyProcess,
2088 cols: number,
2089 rows: number,
2090 ) {
2091 yield* resizePtyProcess(session, process, cols, rows);
2092 session.cols = cols;
2093 session.rows = rows;
2094 session.updatedAt = yield* nowIso;
2095 const eventStamp = advanceEventSequence(session);
2096 yield* publishEvent({
2097 type: "activity",
2098 threadId: session.threadId,
2099 terminalId: session.terminalId,
2100 sequence: eventStamp.sequence,
2101 hasRunningSubprocess: session.hasRunningSubprocess,
2102 label: terminalWireLabel(session),
2103 cols,
2104 rows,
2105 });
2106 });
2107
2108 const applySharedGrid = Effect.fnUntraced(function* (threadId: string, terminalId: string) {
2109 const session = yield* getSession(threadId, terminalId);
2110 if (Option.isNone(session)) return;
2111 const process = session.value.process;
2112 const shared = sharedViewerGrid(toSessionKey(threadId, terminalId));
2113 if (
2114 !process ||
2115 session.value.status !== "running" ||
2116 !shared ||
2117 (shared.cols === session.value.cols && shared.rows === session.value.rows)
2118 ) {
2119 return;
2120 }
2121 yield* resizeSession(session.value, process, shared.cols, shared.rows);
2122 });
2123
2124 const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* (
2125 process: PtyAdapter.PtyProcess | null,
2126 ) {
2127 if (!process) return;
2128 const fiber: Option.Option<Fiber.Fiber<void, never>> = yield* modifyManagerState<
2129 Option.Option<Fiber.Fiber<void, never>>
2130 >((state) => {
2131 const existing: Option.Option<Fiber.Fiber<void, never>> = Option.fromNullishOr(
2132 state.killFibers.get(process),
2133 );
2134 if (Option.isNone(existing)) {
2135 return [Option.none<Fiber.Fiber<void, never>>(), state] as const;
2136 }
2137 const killFibers = new Map(state.killFibers);
2138 killFibers.delete(process);
2139 return [existing, { ...state, killFibers }] as const;
2140 });
2141 if (Option.isSome(fiber)) {
2142 yield* Fiber.interrupt(fiber.value).pipe(Effect.ignore);
2143 }
2144 });
2145
2146 const registerKillFiber = Effect.fn("terminal.registerKillFiber")(function* (
2147 process: PtyAdapter.PtyProcess,
2148 fiber: Fiber.Fiber<void, never>,
2149 ) {
2150 yield* modifyManagerState((state) => {
2151 // Children may finalize before registration; check inside the synchronized update to avoid retaining finished fibers.
2152 if (fiber.pollUnsafe() !== undefined) {
2153 return [undefined, state] as const;
2154 }
2155 const killFibers = new Map(state.killFibers);
2156 killFibers.set(process, fiber);
2157 return [undefined, { ...state, killFibers }] as const;
2158 });
2159 });
2160
2161 const runKillEscalation = Effect.fn("terminal.runKillEscalation")(function* (
2162 process: PtyAdapter.PtyProcess,
2163 threadId: string,
2164 terminalId: string,
2165 ) {
2166 // Subscribe before SIGTERM to catch immediate exits; Effect.ensuring releases even on interruption, unlike JS finally.
2167 const exited = Deferred.makeUnsafe<void>();
2168 const unsubscribeExit = process.onExit(() => {
2169 Deferred.doneUnsafe(exited, Effect.void);
2170 });
2171 yield* Effect.gen(function* () {
2172 // Interactive shells ignore SIGTERM but pass SIGHUP to their background jobs, skipping nohup'd and disowned ones.
2173 // Windows ignores the signal and node-pty kills the whole tree there.
2174 if (platform !== "win32") {
2175 yield* Effect.sync(() => {
2176 try {
2177 process.kill("SIGHUP");
2178 } catch {
2179 // The SIGTERM below reports a shell that can no longer be signalled.
2180 }
2181 });
2182 }
2183 const terminated = yield* Effect.try({
2184 try: () => process.kill("SIGTERM"),
2185 catch: (cause) =>
2186 new TerminalProcessSignalError({
2187 cause,
2188 signal: "SIGTERM",
2189 terminalPid: process.pid,
2190 }),
2191 }).pipe(
2192 Effect.as(true),
2193 Effect.catch((error) =>
2194 Effect.logWarning("failed to kill terminal process", {
2195 threadId,
2196 terminalId,
2197 signal: "SIGTERM",
2198 cause: error,
2199 }).pipe(Effect.as(false)),
2200 ),
2201 );
2202 if (!terminated) {
2203 return;
2204 }
2205
2206 const exitedBeforeGrace = yield* Deferred.await(exited).pipe(
2207 Effect.as(true),
2208 Effect.timeoutOrElse({
2209 duration: processKillGraceMs,
2210 orElse: () => Effect.succeed(false),
2211 }),
2212 );
2213 if (exitedBeforeGrace) {
2214 return;
2215 }
2216
2217 yield* Effect.try({
2218 try: () => process.kill("SIGKILL"),
2219 catch: (cause) =>
2220 new TerminalProcessSignalError({
2221 cause,
2222 signal: "SIGKILL",
2223 terminalPid: process.pid,
2224 }),
2225 }).pipe(
2226 Effect.catch((error) =>
2227 Effect.logWarning("failed to force-kill terminal process", {
2228 threadId,
2229 terminalId,
2230 signal: "SIGKILL",
2231 cause: error,
2232 }),
2233 ),
2234 );
2235 }).pipe(Effect.ensuring(Effect.sync(unsubscribeExit)));
2236 });
2237
2238 const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* (
2239 process: PtyAdapter.PtyProcess,
2240 threadId: string,
2241 terminalId: string,
2242 ) {
2243 const fiber = yield* runKillEscalation(process, threadId, terminalId).pipe(
2244 Effect.ensuring(
2245 modifyManagerState((state) => {
2246 if (!state.killFibers.has(process)) {
2247 return [undefined, state] as const;
2248 }
2249 const killFibers = new Map(state.killFibers);
2250 killFibers.delete(process);
2251 return [undefined, { ...state, killFibers }] as const;
2252 }),
2253 ),
2254 Effect.forkIn(workerScope),
2255 );
2256
2257 yield* registerKillFiber(process, fiber);
2258 });
2259
2260 const persistedHistory = new WeakMap<BoundedTerminalHistory, TerminalHistoryPersistenceCursor>();
2261 const persistWorker = yield* makeKeyedCoalescingWorker<
2262 string,
2263 PersistHistoryRequest,
2264 never,
2265 never
2266 >({
2267 merge: (current, next) => ({
2268 history: next.history,
2269 immediate: current.immediate || next.immediate,
2270 }),
2271 process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) {
2272 if (!request.immediate) {
2273 yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS);
2274 }
2275
2276 const [threadId, terminalId] = sessionKey.split("\u0000");
2277 if (!threadId || !terminalId) {
2278 return;
2279 }
2280
2281 const update = request.history.persistenceUpdate(
2282 request.immediate ? undefined : persistedHistory.get(request.history),
2283 );
2284 if (update.append && update.data.length === 0) return;
2285 // An append may partially succeed before failing. Retry from a full snapshot,
2286 // never from an uncertain file offset.
2287 persistedHistory.delete(request.history);
2288 yield* fileSystem
2289 .writeFileString(historyPath(threadId, terminalId), update.data, {
2290 flag: update.append ? "a" : "w",
2291 })
2292 .pipe(
2293 Effect.tap(() => Effect.sync(() => persistedHistory.set(request.history, update.cursor))),
2294 Effect.catch((error) =>
2295 Effect.logWarning("failed to persist terminal history", {
2296 threadId,
2297 terminalId,
2298 error,
2299 }),
2300 ),
2301 );
2302 }),
2303 });
2304
2305 const queuePersist = Effect.fn("terminal.queuePersist")(function* (
2306 threadId: string,
2307 terminalId: string,
2308 history: BoundedTerminalHistory,
2309 ) {
2310 yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), {
2311 history,
2312 immediate: false,
2313 });
2314 });
2315
2316 const flushPersist = Effect.fn("terminal.flushPersist")(function* (
2317 threadId: string,
2318 terminalId: string,
2319 ) {
2320 yield* persistWorker.drainKey(toSessionKey(threadId, terminalId));
2321 });
2322
2323 const persistHistory = Effect.fn("terminal.persistHistory")(function* (
2324 threadId: string,
2325 terminalId: string,
2326 history: BoundedTerminalHistory,
2327 ) {
2328 yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), {
2329 history,
2330 immediate: true,
2331 });
2332 yield* flushPersist(threadId, terminalId);
2333 });
2334
2335 const readHistoryTail = Effect.fn("terminal.readHistoryTail")(function* (filePath: string) {
2336 const file = yield* fileSystem.open(filePath, { flag: "r" });
2337 const info = yield* file.stat;
2338 const limit = BigInt(historyByteLimit);
2339 const offset = info.size > limit ? info.size - limit : 0n;
2340 // The tail can start inside a control sequence; only the bytes before it say which.
2341 const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
2342 let sequenceState = TERMINAL_SEQUENCE_GROUND;
2343 const skipped = new Uint8Array(Math.min(Number(offset), 64 * 1024));
2344 for (let remaining = Number(offset); remaining > 0;) {
2345 const read = Number(yield* file.read(skipped.subarray(0, remaining)));
2346 if (read === 0) break;
2347 remaining -= read;
2348 sequenceState = terminalSequenceStateAfter(
2349 sequenceState,
2350 decoder.decode(skipped.subarray(0, read), { stream: true }),
2351 );
2352 }
2353 yield* file.seek(offset, "start");
2354 const bytes = new Uint8Array(Number(info.size - offset));
2355 let length = 0;
2356 while (length < bytes.length) {
2357 const read = Number(yield* file.read(bytes.subarray(length)));
2358 if (read === 0) break;
2359 length += read;
2360 }
2361 let start = 0;
2362 if (offset > 0n) {
2363 // A tail read can start inside a UTF-8 code point. Skip its remaining bytes.
2364 while (start < length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start += 1;
2365 }
2366 sequenceState = terminalSequenceStateAfter(
2367 sequenceState,
2368 decoder.decode(bytes.subarray(0, start)),
2369 );
2370 const history = new TextDecoder("utf-8", { ignoreBOM: true }).decode(
2371 bytes.subarray(start, length),
2372 );
2373 return {
2374 history: history.slice(terminalSequenceEnd(sequenceState, history)),
2375 truncated: offset > 0n,
2376 };
2377 });
2378
2379 const readHistory = Effect.fn("terminal.readHistory")(function* (
2380 threadId: string,
2381 terminalId: string,
2382 ) {
2383 const nextPath = historyPath(threadId, terminalId);
2384 for (const sourcePath of historyPaths(threadId, terminalId)) {
2385 const migrating = sourcePath !== nextPath;
2386 const operation = migrating ? "migrate" : "read";
2387 if (
2388 !(yield* historyExists(sourcePath).pipe(
2389 Effect.mapError(
2390 (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }),
2391 ),
2392 ))
2393 )
2394 continue;
2395 const { history: raw, truncated } = yield* readHistoryTail(sourcePath).pipe(
2396 Effect.scoped,
2397 Effect.mapError(
2398 (cause) => new TerminalHistoryError({ operation, threadId, terminalId, cause }),
2399 ),
2400 );
2401 const history = new BoundedTerminalHistory(historyLineLimit, raw, historyByteLimit);
2402 const capped = history.value();
2403 if (migrating || truncated || capped !== raw) {
2404 const write = Effect.gen(function* () {
2405 const temporaryPath = yield* fileSystem.makeTempFileScoped({
2406 directory: logsDir,
2407 prefix: ".history-",
2408 });
2409 yield* fileSystem.writeFileString(temporaryPath, capped);
2410 yield* fileSystem.rename(temporaryPath, nextPath);
2411 }).pipe(
2412 Effect.scoped,
2413 Effect.mapError(
2414 (cause) =>
2415 new TerminalHistoryError({
2416 operation: migrating ? "migrate" : "truncate",
2417 threadId,
2418 terminalId,
2419 cause,
2420 }),
2421 ),
2422 );
2423 yield* migrating
2424 ? write
2425 : write.pipe(
2426 Effect.catch((error) =>
2427 Effect.logWarning("failed to compact terminal history", {
2428 threadId,
2429 terminalId,
2430 error,
2431 }),
2432 ),
2433 );
2434 }
2435 if (migrating) {
2436 yield* fileSystem.remove(sourcePath, { force: true }).pipe(
2437 Effect.catch((error) =>
2438 Effect.logWarning("failed to remove legacy terminal history", {
2439 threadId,
2440 terminalId,
2441 error,
2442 }),
2443 ),
2444 );
2445 }
2446 return history;
2447 }
2448 return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit);
2449 });
2450
2451 const deleteHistory = Effect.fn("terminal.deleteHistory")(function* (
2452 threadId: string,
2453 terminalId: string,
2454 ) {
2455 yield* Effect.forEach(
2456 historyPaths(threadId, terminalId),
2457 (filePath) =>
2458 Effect.gen(function* () {
2459 if (yield* historyExists(filePath)) {
2460 yield* fileSystem.remove(filePath, { force: true });
2461 }
2462 }).pipe(
2463 Effect.catch((error) =>
2464 Effect.logWarning("failed to delete terminal history", {
2465 threadId,
2466 terminalId,
2467 error,
2468 }),
2469 ),
2470 ),
2471 { discard: true },
2472 );
2473 });
2474
2475 const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* (
2476 threadId: string,
2477 ) {
2478 const threadParts = [encodedHistoryThreadPart(threadId), hashedHistoryThreadPart(threadId)];
2479 const entries = yield* fileSystem
2480 .readDirectory(logsDir, { recursive: false })
2481 .pipe(Effect.orElseSucceed(() => [] as Array<string>));
2482 yield* Effect.forEach(
2483 entries.filter(
2484 (name) =>
2485 (hasLegacyHistoryName(threadId) && name === legacyHistoryName(threadId)) ||
2486 threadParts.some((part) => name === `${part}.log` || name.startsWith(`${part}_`)),
2487 ),
2488 (name) =>
2489 fileSystem.remove(path.join(logsDir, name), { force: true }).pipe(
2490 Effect.catch((error) =>
2491 Effect.logWarning("failed to delete terminal histories for thread", {
2492 threadId,
2493 error,
2494 }),
2495 ),
2496 ),
2497 { discard: true },
2498 );
2499 });
2500
2501 const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) {
2502 const stat = fileSystem.stat(cwd).pipe(
2503 Effect.catchTags({
2504 PlatformError: (cause) =>
2505 cause.reason._tag === "NotFound"
2506 ? new TerminalCwdNotFoundError({ cwd })
2507 : new TerminalCwdStatError({ cwd, cause }),
2508 }),
2509 );
2510 const stats = yield* stat.pipe(
2511 Effect.catchTags({
2512 TerminalCwdNotFoundError: (error) =>
2513 Effect.flatMap(TerminalCwdRecovery, (recover) =>
2514 recover(error).pipe(Effect.andThen(stat)),
2515 ),
2516 }),
2517 );
2518 if (stats.type !== "Directory") {
2519 return yield* new TerminalCwdNotDirectoryError({ cwd });
2520 }
2521 });
2522
2523 const getSession = Effect.fn("terminal.getSession")(function* (
2524 threadId: string,
2525 terminalId: string,
2526 ): Effect.fn.Return<Option.Option<TerminalSessionState>> {
2527 return yield* Effect.map(readManagerState, (state) =>
2528 Option.fromNullishOr(state.sessions.get(toSessionKey(threadId, terminalId))),
2529 );
2530 });
2531
2532 const requireSession = Effect.fn("terminal.requireSession")(function* (
2533 threadId: string,
2534 terminalId: string,
2535 ): Effect.fn.Return<TerminalSessionState, TerminalSessionLookupError> {
2536 return yield* Effect.flatMap(getSession(threadId, terminalId), (session) =>
2537 Effect.fromOption(session, () => new TerminalSessionLookupError({ threadId, terminalId })),
2538 );
2539 });
2540
2541 const sessionsForThread = Effect.fn("terminal.sessionsForThread")(function* (threadId: string) {
2542 return yield* readManagerState.pipe(
2543 Effect.map((state) =>
2544 [...state.sessions.values()].filter((session) => session.threadId === threadId),
2545 ),
2546 );
2547 });
2548
2549 const evictInactiveSessionsIfNeeded = Effect.fn("terminal.evictInactiveSessionsIfNeeded")(
2550 function* () {
2551 yield* modifyManagerState((state) => {
2552 const inactiveSessions = [...state.sessions.values()].filter(
2553 (session) => session.status !== "running",
2554 );
2555 if (inactiveSessions.length <= maxRetainedInactiveSessions) {
2556 return [undefined, state] as const;
2557 }
2558
2559 inactiveSessions.sort(
2560 (left, right) =>
2561 left.updatedAt.localeCompare(right.updatedAt) ||
2562 left.threadId.localeCompare(right.threadId) ||
2563 left.terminalId.localeCompare(right.terminalId),
2564 );
2565
2566 const sessions = new Map(state.sessions);
2567
2568 const toEvict = inactiveSessions.length - maxRetainedInactiveSessions;
2569 for (const session of inactiveSessions.slice(0, toEvict)) {
2570 const key = toSessionKey(session.threadId, session.terminalId);
2571 sessions.delete(key);
2572 closedSessionKeys.add(key);
2573 }
2574
2575 return [undefined, { ...state, sessions }] as const;
2576 });
2577 },
2578 );
2579
2580 const drainProcessEvents = Effect.fn("terminal.drainProcessEvents")(function* (
2581 session: TerminalSessionState,
2582 expectedPid: number,
2583 ) {
2584 while (true) {
2585 const action: DrainProcessEventAction = yield* Effect.sync(() => {
2586 if (session.pid !== expectedPid || !session.process || session.status !== "running") {
2587 session.pendingProcessEvents = [];
2588 session.pendingProcessEventIndex = 0;
2589 session.processEventDrainRunning = false;
2590 return { type: "idle" } as const;
2591 }
2592
2593 const nextEvent = session.pendingProcessEvents[session.pendingProcessEventIndex];
2594 if (!nextEvent) {
2595 session.pendingProcessEvents = [];
2596 session.pendingProcessEventIndex = 0;
2597 session.processEventDrainRunning = false;
2598 return { type: "idle" } as const;
2599 }
2600
2601 session.pendingProcessEvents[session.pendingProcessEventIndex] = undefined;
2602 session.pendingProcessEventIndex += 1;
2603 if (session.pendingProcessEventIndex * 2 >= session.pendingProcessEvents.length) {
2604 session.pendingProcessEvents = session.pendingProcessEvents.slice(
2605 session.pendingProcessEventIndex,
2606 );
2607 session.pendingProcessEventIndex = 0;
2608 }
2609
2610 if (nextEvent.type === "output") {
2611 const sanitized = sanitizeTerminalHistoryChunk(
2612 session.pendingHistoryControlSequence,
2613 nextEvent.data,
2614 );
2615 session.pendingHistoryControlSequence = sanitized.pendingControlSequence;
2616 if (sanitized.visibleText.length > 0) {
2617 session.history.append(sanitized.visibleText);
2618 }
2619 const eventStamp = advanceEventSequence(session);
2620
2621 return {
2622 type: "output",
2623 threadId: session.threadId,
2624 terminalId: session.terminalId,
2625 sequence: eventStamp.sequence,
2626 history: sanitized.visibleText.length > 0 ? session.history : null,
2627 data: nextEvent.data,
2628 } as const;
2629 }
2630
2631 const process = session.process;
2632 cleanupProcessHandles(session);
2633 session.process = null;
2634 session.pid = null;
2635 session.hasRunningSubprocess = false;
2636 session.childCommandLabel = null;
2637 session.status = "exited";
2638 session.pendingHistoryControlSequence = "";
2639 session.pendingProcessEvents = [];
2640 session.pendingProcessEventIndex = 0;
2641 session.processEventDrainRunning = false;
2642 session.exitCode = Number.isInteger(nextEvent.event.exitCode)
2643 ? nextEvent.event.exitCode
2644 : null;
2645 session.exitSignal = Number.isInteger(nextEvent.event.signal)
2646 ? nextEvent.event.signal
2647 : null;
2648 const eventStamp = advanceEventSequence(session);
2649
2650 return {
2651 type: "exit",
2652 process,
2653 threadId: session.threadId,
2654 terminalId: session.terminalId,
2655 sequence: eventStamp.sequence,
2656 exitCode: session.exitCode,
2657 exitSignal: session.exitSignal,
2658 } as const;
2659 });
2660
2661 if (action.type === "idle") {
2662 return;
2663 }
2664
2665 if (action.type === "output") {
2666 if (action.history !== null) {
2667 yield* queuePersist(action.threadId, action.terminalId, action.history);
2668 }
2669
2670 yield* publishEvent({
2671 type: "output",
2672 threadId: action.threadId,
2673 terminalId: action.terminalId,
2674 sequence: action.sequence,
2675 data: action.data,
2676 });
2677 continue;
2678 }
2679
2680 yield* clearKillFiber(action.process);
2681 yield* unregisterTerminal({
2682 threadId: action.threadId,
2683 terminalId: action.terminalId,
2684 });
2685 yield* publishEvent({
2686 type: "exited",
2687 threadId: action.threadId,
2688 terminalId: action.terminalId,
2689 sequence: action.sequence,
2690 exitCode: action.exitCode,
2691 exitSignal: action.exitSignal,
2692 });
2693 yield* evictInactiveSessionsIfNeeded();
2694 return;
2695 }
2696 });
2697
2698 const stopProcess = Effect.fn("terminal.stopProcess")(function* (session: TerminalSessionState) {
2699 const process = session.process;
2700 if (!process) return;
2701
2702 const updatedAt = yield* nowIso;
2703 yield* modifyManagerState((state) => {
2704 cleanupProcessHandles(session);
2705 session.process = null;
2706 session.pid = null;
2707 session.hasRunningSubprocess = false;
2708 session.childCommandLabel = null;
2709 session.status = "exited";
2710 session.pendingHistoryControlSequence = "";
2711 session.pendingProcessEvents = [];
2712 session.pendingProcessEventIndex = 0;
2713 session.processEventDrainRunning = false;
2714 session.updatedAt = updatedAt;
2715 return [undefined, state] as const;
2716 });
2717
2718 yield* clearKillFiber(process);
2719 yield* unregisterTerminal({
2720 threadId: session.threadId,
2721 terminalId: session.terminalId,
2722 });
2723 yield* startKillEscalation(process, session.threadId, session.terminalId);
2724 yield* evictInactiveSessionsIfNeeded();
2725 });
2726
2727 const trySpawn = Effect.fn("terminal.trySpawn")(function* (
2728 shellCandidates: ReadonlyArray<ShellCandidate>,
2729 spawnEnv: NodeJS.ProcessEnv,
2730 session: TerminalSessionState,
2731 index = 0,
2732 lastError: PtyAdapter.PtySpawnError | null = null,
2733 ): Effect.fn.Return<
2734 { process: PtyAdapter.PtyProcess; shell: string; shellLabel: string },
2735 PtyAdapter.PtySpawnError
2736 > {
2737 if (index >= shellCandidates.length) {
2738 return yield* new PtyAdapter.PtySpawnError({
2739 adapter: "terminal-manager",
2740 attemptedShells: shellCandidates.map((candidate) => formatShellCandidate(candidate)),
2741 ...(lastError ? { cause: lastError } : {}),
2742 });
2743 }
2744
2745 const candidate = shellCandidates[index];
2746 if (!candidate) {
2747 return yield* (
2748 lastError ??
2749 new PtyAdapter.PtySpawnError({
2750 adapter: "terminal-manager",
2751 attemptedShells: [],
2752 })
2753 );
2754 }
2755
2756 // PATH lookup must use the child's working directory, not the server's.
2757 const lookupEnv =
2758 platform === "win32"
2759 ? spawnEnv
2760 : {
2761 ...spawnEnv,
2762 PATH: (spawnEnv.PATH ?? spawnEnv.Path ?? spawnEnv.path ?? "")
2763 .split(":")
2764 // An empty entry means the working directory, which resolve("") yields.
2765 .map((entry) => path.resolve(session.cwd, entry.replace(/^"+|"+$/g, "")))
2766 .join(":"),
2767 };
2768 // POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate.
2769 const executable =
2770 platform !== "win32"
2771 ? resolveExecutable(
2772 candidate.shell.includes("/")
2773 ? path.resolve(session.cwd, candidate.shell)
2774 : candidate.shell,
2775 platform,
2776 lookupEnv,
2777 )
2778 : candidate.shell;
2779 if (executable === undefined) {
2780 return yield* trySpawn(
2781 shellCandidates,
2782 spawnEnv,
2783 session,
2784 index + 1,
2785 new PtyAdapter.PtySpawnError({ adapter: "terminal-manager", shell: candidate.shell }),
2786 );
2787 }
2788
2789 const launch = yield* agentScope.wrap({
2790 command: executable,
2791 args: candidate.args ?? [],
2792 name: "terminal",
2793 env: spawnEnv,
2794 survivesRestart: true,
2795 });
2796 const attempt = yield* Effect.result(
2797 options.ptyAdapter.spawn({
2798 shell: launch.command,
2799 ...(launch.args.length > 0 ? { args: [...launch.args] } : {}),
2800 cwd: session.cwd,
2801 cols: session.cols,
2802 rows: session.rows,
2803 env: spawnEnv,
2804 }),
2805 );
2806
2807 if (attempt._tag === "Success") {
2808 return {
2809 process: attempt.success,
2810 shell: candidate.shell,
2811 shellLabel: formatShellCandidate(candidate),
2812 };
2813 }
2814
2815 const spawnError = attempt.failure;
2816 if (!isRetryableShellSpawnError(spawnError)) {
2817 return yield* spawnError;
2818 }
2819
2820 return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError);
2821 });
2822
2823 const startSession = Effect.fn("terminal.startSession")(function* (
2824 session: TerminalSessionState,
2825 input: TerminalStartInput,
2826 eventType: "started" | "restarted",
2827 ) {
2828 yield* stopProcess(session);
2829 yield* Effect.annotateCurrentSpan({
2830 "terminal.thread_id": session.threadId,
2831 "terminal.id": session.terminalId,
2832 "terminal.event_type": eventType,
2833 "terminal.cwd": input.cwd,
2834 });
2835
2836 const startingAt = yield* nowIso;
2837 yield* modifyManagerState((state) => {
2838 session.status = "starting";
2839 session.startupError = null;
2840 session.shell = null;
2841 session.cwd = input.cwd;
2842 session.worktreePath = input.worktreePath ?? null;
2843 session.cols = input.cols;
2844 session.rows = input.rows;
2845 session.exitCode = null;
2846 session.exitSignal = null;
2847 session.hasRunningSubprocess = false;
2848 session.childCommandLabel = null;
2849 session.pendingProcessEvents = [];
2850 session.pendingProcessEventIndex = 0;
2851 session.processEventDrainRunning = false;
2852 session.updatedAt = startingAt;
2853 return [undefined, state] as const;
2854 });
2855
2856 let ptyProcess: PtyAdapter.PtyProcess | null = null;
2857 let startedShell: string | null = null;
2858
2859 const startResult = yield* Effect.result(
2860 increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(
2861 Effect.andThen(
2862 Effect.gen(function* () {
2863 const shellCandidates = yield* resolveShellCandidates(
2864 shellResolver,
2865 platform,
2866 baseEnv,
2867 session.runtimeEnv?.T3CODE_TERMINAL_SHELL ?? baseEnv.T3CODE_TERMINAL_SHELL,
2868 ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
2869 const terminalEnv = createTerminalSpawnEnv(
2870 baseEnv,
2871 session.runtimeEnv,
2872 platform,
2873 yield* HostProcess.HomeDirectory,
2874 session.threadId,
2875 );
2876 // Append managed install directories so agent commands resolve without shadowing user/system tools.
2877 if (
2878 options.managedBinaryCacheDir !== undefined &&
2879 options.managedBinaryToolsDir !== undefined
2880 ) {
2881 const managedDirectories = yield* acpRegistryManagedBinaryDirectories({
2882 cacheDir: options.managedBinaryCacheDir,
2883 toolsDir: options.managedBinaryToolsDir,
2884 platform,
2885 architecture,
2886 }).pipe(
2887 Effect.provideService(FileSystem.FileSystem, fileSystem),
2888 Effect.provideService(Path.Path, path),
2889 );
2890 if (managedDirectories.length > 0) {
2891 const delimiter = platform === "win32" ? ";" : ":";
2892 const pathKey =
2893 platform === "win32"
2894 ? (Object.keys(terminalEnv).find(
2895 (candidate) => candidate.toLowerCase() === "path",
2896 ) ?? "PATH")
2897 : "PATH";
2898 const merged = mergePathEntries(
2899 terminalEnv[pathKey],
2900 managedDirectories.join(delimiter),
2901 platform,
2902 );
2903 if (merged !== undefined) {
2904 terminalEnv[pathKey] = merged;
2905 }
2906 }
2907 }
2908 const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
2909 ptyProcess = spawnResult.process;
2910 startedShell = spawnResult.shellLabel;
2911
2912 const processPid = ptyProcess.pid;
2913 let eventsActivated = false;
2914
2915 let eventStamp: ReturnType<typeof advanceEventSequence> = {
2916 updatedAt: session.updatedAt,
2917 sequence: session.eventSequence,
2918 };
2919 yield* modifyManagerState((state) => {
2920 session.process = ptyProcess;
2921 session.shell = spawnResult.shell;
2922 session.pid = processPid;
2923 session.status = "running";
2924 // onExit may replay an exit immediately; accept it before subscribing.
2925 session.unsubscribeData = spawnResult.process.onData((data) => {
2926 if (!enqueueProcessEvent(session, processPid, { type: "output", data })) {
2927 return;
2928 }
2929 if (eventsActivated) runFork(drainProcessEvents(session, processPid));
2930 });
2931 session.unsubscribeExit = spawnResult.process.onExit((event) => {
2932 if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) {
2933 return;
2934 }
2935 if (eventsActivated) runFork(drainProcessEvents(session, processPid));
2936 });
2937 eventStamp = advanceEventSequence(session);
2938 return [undefined, state] as const;
2939 });
2940
2941 yield* publishEvent({
2942 type: eventType,
2943 threadId: session.threadId,
2944 terminalId: session.terminalId,
2945 sequence: eventStamp.sequence,
2946 snapshot: snapshot(session),
2947 });
2948 // Publish startup before draining any events replayed during subscription.
2949 eventsActivated = true;
2950 if (session.processEventDrainRunning) runFork(drainProcessEvents(session, processPid));
2951 }),
2952 ),
2953 ),
2954 );
2955
2956 if (startResult._tag === "Success") {
2957 return;
2958 }
2959
2960 {
2961 const error = startResult.failure;
2962 const message = error.message;
2963 if (ptyProcess) {
2964 yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);
2965 }
2966
2967 yield* modifyManagerState((state) => {
2968 cleanupProcessHandles(session);
2969 session.status = "error";
2970 session.startupError = message;
2971 session.pid = null;
2972 session.process = null;
2973 session.hasRunningSubprocess = false;
2974 session.childCommandLabel = null;
2975 session.pendingProcessEvents = [];
2976 session.pendingProcessEventIndex = 0;
2977 session.processEventDrainRunning = false;
2978 advanceEventSequence(session);
2979 return [undefined, state] as const;
2980 });
2981 yield* unregisterTerminal({
2982 threadId: session.threadId,
2983 terminalId: session.terminalId,
2984 });
2985
2986 yield* evictInactiveSessionsIfNeeded();
2987
2988 yield* publishEvent({
2989 type: "error",
2990 threadId: session.threadId,
2991 terminalId: session.terminalId,
2992 sequence: session.eventSequence,
2993 message,
2994 });
2995 yield* Effect.logError("failed to start terminal", {
2996 threadId: session.threadId,
2997 terminalId: session.terminalId,
2998 cause: error,
2999 ...(startedShell ? { shell: startedShell } : {}),
3000 });
3001 }
3002 });
3003
3004 const closeSession = Effect.fn("terminal.closeSession")(function* (
3005 threadId: string,
3006 terminalId: string,
3007 deleteHistoryOnClose: boolean,
3008 ) {
3009 const key = toSessionKey(threadId, terminalId);
3010 const session = yield* getSession(threadId, terminalId);
3011 const closedEventSequence = Option.isSome(session) ? session.value.eventSequence + 1 : 0;
3012
3013 if (Option.isSome(session)) {
3014 yield* stopProcess(session.value);
3015 yield* unregisterTerminal({ threadId, terminalId });
3016 yield* persistHistory(threadId, terminalId, session.value.history);
3017 }
3018
3019 yield* flushPersist(threadId, terminalId);
3020
3021 const removed = yield* modifyManagerState((state) => {
3022 closedSessionKeys.add(key);
3023 if (!state.sessions.has(key)) {
3024 return [false, state] as const;
3025 }
3026 const sessions = new Map(state.sessions);
3027 sessions.delete(key);
3028 return [true, { ...state, sessions }] as const;
3029 });
3030
3031 if (removed) {
3032 yield* publishEvent({
3033 type: "closed",
3034 threadId,
3035 terminalId,
3036 sequence: closedEventSequence,
3037 });
3038 }
3039
3040 if (deleteHistoryOnClose) {
3041 yield* deleteHistory(threadId, terminalId);
3042 }
3043 });
3044
3045 // Two unchanged snapshots cover children forked just after the first snapshot.
3046 // Process identity prevents a restarted shell from inheriting quiet state.
3047 let quietSessions = new WeakMap<TerminalSessionState, QuietTerminalSession>();
3048 let skippedQuietTicks = 0;
3049 const isQuiet = (session: TerminalSessionState & { pid: number }) => {
3050 const quiet = quietSessions.get(session);
3051 return (
3052 quiet !== undefined &&
3053 quiet.idleSnapshots === 2 &&
3054 quiet.process === session.process &&
3055 quiet.mark === terminalActivityMark(session) &&
3056 !session.hasRunningSubprocess
3057 );
3058 };
3059
3060 const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () {
3061 const state = yield* readManagerState;
3062 const runningSessions = [...state.sessions.values()]
3063 .filter(
3064 (session): session is TerminalSessionState & { pid: number } =>
3065 session.status === "running" && Number.isInteger(session.pid),
3066 )
3067 .map((session) => ({
3068 session,
3069 terminalPid: session.pid,
3070 process: session.process,
3071 mark: terminalActivityMark(session),
3072 }));
3073
3074 if (runningSessions.length === 0) {
3075 return { snapshotSucceeded: true, queryElapsedMs: 0 };
3076 }
3077 if (
3078 runningSessions.every(({ session }) => isQuiet(session)) &&
3079 skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1
3080 ) {
3081 skippedQuietTicks += 1;
3082 return { snapshotSucceeded: true, queryElapsedMs: 0 };
3083 }
3084 skippedQuietTicks = 0;
3085
3086 const { inspector, snapshotSucceeded, queryElapsedMs } = yield* acquireSubprocessInspector(
3087 PROCESS_TABLE_QUERY_TIMEOUT,
3088 );
3089 if (Result.isFailure(inspector)) {
3090 yield* Effect.logWarning("failed to snapshot processes for terminal subprocess polling", {
3091 reason: inspector.failure,
3092 });
3093 quietSessions = new WeakMap();
3094 return { snapshotSucceeded: false, queryElapsedMs };
3095 }
3096
3097 const subprocessInspector = inspector.success;
3098 const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* (
3099 candidate: (typeof runningSessions)[number],
3100 ) {
3101 const { session, terminalPid, process } = candidate;
3102 let mark = candidate.mark;
3103 const previous = quietSessions.get(session);
3104 quietSessions.delete(session);
3105 const inspectResult = yield* subprocessInspector(terminalPid, session.shell).pipe(
3106 Effect.asSome,
3107 Effect.catch((reason) =>
3108 Effect.logWarning("failed to check terminal subprocess activity", {
3109 threadId: session.threadId,
3110 terminalId: session.terminalId,
3111 terminalPid,
3112 reason,
3113 }).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),
3114 ),
3115 );
3116
3117 if (
3118 Option.isNone(inspectResult) ||
3119 session.status !== "running" ||
3120 session.pid !== terminalPid ||
3121 session.process !== process
3122 ) {
3123 return;
3124 }
3125
3126 const next = inspectResult.value;
3127 yield* registerTerminalProcesses({
3128 threadId: session.threadId,
3129 terminalId: session.terminalId,
3130 processIds: next.processIds,
3131 });
3132 const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null;
3133 const event = yield* modifyManagerState((state) => {
3134 const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
3135 state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
3136 );
3137 if (
3138 Option.isNone(liveSession) ||
3139 liveSession.value !== session ||
3140 liveSession.value.status !== "running" ||
3141 liveSession.value.pid !== terminalPid ||
3142 liveSession.value.process !== process ||
3143 (liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&
3144 liveSession.value.childCommandLabel === nextChildLabel)
3145 ) {
3146 return [Option.none(), state] as const;
3147 }
3148
3149 liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess;
3150 liveSession.value.childCommandLabel = nextChildLabel;
3151 const eventStamp = advanceEventSequence(liveSession.value);
3152 // Only this poll's own event may advance the mark without waking it.
3153 mark += 1;
3154
3155 return [
3156 Option.some({
3157 type: "activity" as const,
3158 threadId: liveSession.value.threadId,
3159 terminalId: liveSession.value.terminalId,
3160 sequence: eventStamp.sequence,
3161 hasRunningSubprocess: next.hasRunningSubprocess,
3162 label: terminalWireLabel(liveSession.value),
3163 }),
3164 state,
3165 ] as const;
3166 });
3167
3168 if (Option.isSome(event)) {
3169 yield* publishEvent(event.value);
3170 }
3171
3172 if (
3173 snapshotSucceeded &&
3174 !next.hasRunningSubprocess &&
3175 session.status === "running" &&
3176 session.pid === terminalPid &&
3177 session.process === process &&
3178 terminalActivityMark(session) === mark
3179 ) {
3180 quietSessions.set(session, {
3181 process,
3182 mark,
3183 idleSnapshots: previous?.process === process && previous.mark === mark ? 2 : 1,
3184 });
3185 }
3186 });
3187
3188 yield* Effect.forEach(runningSessions, checkSubprocessActivity, {
3189 concurrency: "unbounded",
3190 discard: true,
3191 });
3192
3193 return { snapshotSucceeded, queryElapsedMs };
3194 });
3195
3196 const hasRunningSessions = readManagerState.pipe(
3197 Effect.map((state) =>
3198 [...state.sessions.values()].some((session) => session.status === "running"),
3199 ),
3200 );
3201
3202 let subprocessSnapshotFailureCount = 0;
3203 yield* Effect.forever(
3204 hasRunningSessions.pipe(
3205 Effect.flatMap((active) =>
3206 active
3207 ? pollSubprocessActivity().pipe(
3208 Effect.flatMap(({ snapshotSucceeded, queryElapsedMs }) => {
3209 subprocessSnapshotFailureCount = snapshotSucceeded
3210 ? 0
3211 : Math.min(subprocessSnapshotFailureCount + 1, 30);
3212 const delayMs = subprocessSnapshotPollDelayMs(
3213 subprocessPollIntervalMs,
3214 subprocessSnapshotFailureCount,
3215 queryElapsedMs,
3216 );
3217 return Effect.sleep(delayMs);
3218 }),
3219 )
3220 : Effect.sync(() => {
3221 subprocessSnapshotFailureCount = 0;
3222 }).pipe(Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs))),
3223 ),
3224 ),
3225 ).pipe(Effect.forkIn(workerScope));
3226
3227 yield* Effect.addFinalizer(() =>
3228 Effect.gen(function* () {
3229 const [sessions, pendingKills] = yield* modifyManagerState(
3230 (state) =>
3231 [
3232 [[...state.sessions.values()], [...state.killFibers.values()]],
3233 {
3234 ...state,
3235 sessions: new Map(),
3236 },
3237 ] as const,
3238 );
3239
3240 const cleanupSession = Effect.fn("terminal.cleanupSession")(function* (
3241 session: TerminalSessionState,
3242 ) {
3243 cleanupProcessHandles(session);
3244 if (!session.process) return;
3245 yield* clearKillFiber(session.process);
3246 yield* runKillEscalation(session.process, session.threadId, session.terminalId);
3247 });
3248
3249 // Closing workerScope next would interrupt escalations of already stopped terminals.
3250 yield* Effect.all(
3251 [
3252 Effect.forEach(sessions, cleanupSession, { concurrency: "unbounded", discard: true }),
3253 Fiber.awaitAll(pendingKills),
3254 ],
3255 { concurrency: "unbounded", discard: true },
3256 );
3257 }).pipe(Effect.ignoreCause({ log: true })),
3258 );
3259
3260 const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* (
3261 requestedInput: TerminalOpenInput,
3262 ) {
3263 const terminalId = requestedInput.terminalId;
3264 yield* assertValidCwd(requestedInput.cwd);
3265
3266 const sessionKey = toSessionKey(requestedInput.threadId, terminalId);
3267 const input = withSharedGrid(sessionKey, requestedInput);
3268 const existing = yield* getSession(input.threadId, terminalId);
3269 if (Option.isNone(existing)) {
3270 yield* flushPersist(input.threadId, terminalId);
3271 const inherited = yield* readHistory(input.threadId, terminalId);
3272 const history = new BoundedTerminalHistory(
3273 historyLineLimit,
3274 neutralizeInheritedHistory(
3275 inherited.value(),
3276 historyLineLimit,
3277 Math.min(historyByteLimit, DEFAULT_MAX_TERMINAL_BUFFER_BYTES),
3278 ),
3279 historyByteLimit,
3280 );
3281 const cols = input.cols ?? DEFAULT_OPEN_COLS;
3282 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
3283 const session: TerminalSessionState = {
3284 threadId: input.threadId,
3285 terminalId,
3286 cwd: input.cwd,
3287 worktreePath: input.worktreePath ?? null,
3288 status: "starting",
3289 pid: null,
3290 history,
3291 pendingHistoryControlSequence: "",
3292 pendingProcessEvents: [],
3293 pendingProcessEventIndex: 0,
3294 processEventDrainRunning: false,
3295 exitCode: null,
3296 exitSignal: null,
3297 updatedAt: yield* nowIso,
3298 eventSequence: 0,
3299 inputCount: 0,
3300 cols,
3301 rows,
3302 process: null,
3303 shell: null,
3304 unsubscribeData: null,
3305 unsubscribeExit: null,
3306 hasRunningSubprocess: false,
3307 childCommandLabel: null,
3308 runtimeEnv: normalizedRuntimeEnv(input.env),
3309 stopOnSettle: input.stopOnSettle ?? false,
3310 startupError: null,
3311 };
3312
3313 const createdSession = session;
3314 yield* modifyManagerState((state) => {
3315 const sessions = new Map(state.sessions);
3316 sessions.set(sessionKey, createdSession);
3317 closedSessionKeys.delete(sessionKey);
3318 return [undefined, { ...state, sessions }] as const;
3319 });
3320
3321 yield* evictInactiveSessionsIfNeeded();
3322 yield* startSession(
3323 session,
3324 {
3325 cwd: input.cwd,
3326 ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
3327 cols,
3328 rows,
3329 },
3330 "started",
3331 );
3332 return snapshot(session);
3333 }
3334
3335 const liveSession = existing.value;
3336 if (input.stopOnSettle !== undefined) liveSession.stopOnSettle = input.stopOnSettle;
3337 const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
3338 const currentRuntimeEnv = liveSession.runtimeEnv;
3339 const targetCols = input.cols ?? liveSession.cols;
3340 const targetRows = input.rows ?? liveSession.rows;
3341 const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv);
3342 const nextWorktreePath =
3343 input.worktreePath !== undefined ? (input.worktreePath ?? null) : liveSession.worktreePath;
3344 const launchContextChanged =
3345 liveSession.cwd !== input.cwd ||
3346 runtimeEnvChanged ||
3347 liveSession.worktreePath !== nextWorktreePath;
3348
3349 if (launchContextChanged) {
3350 yield* stopProcess(liveSession);
3351 liveSession.cwd = input.cwd;
3352 liveSession.worktreePath = nextWorktreePath;
3353 liveSession.runtimeEnv = nextRuntimeEnv;
3354 liveSession.history.clear();
3355 liveSession.pendingHistoryControlSequence = "";
3356 liveSession.pendingProcessEvents = [];
3357 liveSession.pendingProcessEventIndex = 0;
3358 liveSession.processEventDrainRunning = false;
3359 yield* persistHistory(liveSession.threadId, liveSession.terminalId, liveSession.history);
3360 } else if (liveSession.status === "exited" || liveSession.status === "error") {
3361 liveSession.runtimeEnv = nextRuntimeEnv;
3362 liveSession.worktreePath = nextWorktreePath;
3363 liveSession.history.clear();
3364 liveSession.pendingHistoryControlSequence = "";
3365 liveSession.pendingProcessEvents = [];
3366 liveSession.pendingProcessEventIndex = 0;
3367 liveSession.processEventDrainRunning = false;
3368 yield* persistHistory(liveSession.threadId, liveSession.terminalId, liveSession.history);
3369 }
3370
3371 if (!liveSession.process) {
3372 yield* startSession(
3373 liveSession,
3374 {
3375 cwd: input.cwd,
3376 worktreePath: liveSession.worktreePath,
3377 cols: targetCols,
3378 rows: targetRows,
3379 },
3380 "started",
3381 );
3382 return snapshot(liveSession);
3383 }
3384
3385 if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
3386 yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows);
3387 }
3388
3389 return snapshot(liveSession);
3390 });
3391
3392 const openLocked = (input: TerminalOpenInput) =>
3393 withWorkspaceLease(
3394 path.resolve(input.worktreePath ?? input.cwd),
3395 openWithWorkspaceLease(input),
3396 );
3397
3398 const open: TerminalManager["Service"]["open"] = (input) =>
3399 withThreadLock(
3400 input.threadId,
3401 resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),
3402 );
3403
3404 const getShell = Effect.fn("terminal.getShell")(function* (input: TerminalObserveInput) {
3405 const session = yield* requireSession(input.threadId, input.terminalId);
3406 if (session.status !== "running" || session.shell === null) {
3407 return yield* new TerminalNotRunningError(input);
3408 }
3409 return session.shell;
3410 });
3411
3412 const openOrAttachForStream = Effect.fnUntraced(function* (requestedInput: TerminalAttachInput) {
3413 const terminalId = requestedInput.terminalId;
3414 const input = withSharedGrid(toSessionKey(requestedInput.threadId, terminalId), requestedInput);
3415 const existing = yield* getSession(input.threadId, terminalId);
3416
3417 if (Option.isNone(existing)) {
3418 if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) {
3419 return null;
3420 }
3421 if (!input.cwd) {
3422 return yield* new TerminalSessionLookupError({
3423 threadId: input.threadId,
3424 terminalId,
3425 });
3426 }
3427
3428 const resolvedInput = yield* resolveLaunchInputEnvironment({
3429 ...input,
3430 terminalId,
3431 cwd: input.cwd,
3432 });
3433 return yield* Effect.uninterruptible(openLocked(resolvedInput));
3434 }
3435
3436 const session = existing.value;
3437 const targetCols = input.cols ?? session.cols;
3438 const targetRows = input.rows ?? session.rows;
3439
3440 if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) {
3441 const resolvedInput = yield* resolveLaunchInputEnvironment({
3442 ...input,
3443 terminalId,
3444 cwd: input.cwd,
3445 });
3446 return yield* Effect.uninterruptible(openLocked(resolvedInput));
3447 }
3448
3449 if (
3450 session.process &&
3451 session.status === "running" &&
3452 (session.cols !== targetCols || session.rows !== targetRows)
3453 ) {
3454 yield* resizeSession(session, session.process, targetCols, targetRows);
3455 }
3456
3457 return snapshot(session);
3458 });
3459
3460 const readAllTerminalMetadata = () =>
3461 readManagerState.pipe(
3462 Effect.map((state) =>
3463 [...state.sessions.values()]
3464 .map(summary)
3465 .sort(
3466 (left, right) =>
3467 right.updatedAt.localeCompare(left.updatedAt) ||
3468 left.threadId.localeCompare(right.threadId) ||
3469 left.terminalId.localeCompare(right.terminalId),
3470 ),
3471 ),
3472 );
3473
3474 const readTerminalMetadata = (input: {
3475 readonly threadId: string;
3476 readonly terminalId: string;
3477 }) =>
3478 getSession(input.threadId, input.terminalId).pipe(
3479 Effect.map((session) => (Option.isSome(session) ? summary(session.value) : null)),
3480 );
3481
3482 const subscribe: TerminalManager["Service"]["subscribe"] = (listener, registerCleanup) =>
3483 Effect.sync(() => {
3484 terminalEventListeners.add(listener);
3485 const stop = () => {
3486 terminalEventListeners.delete(listener);
3487 };
3488 // Transfer ownership before an interrupt can discard the returned handle.
3489 registerCleanup?.(stop);
3490 return stop;
3491 });
3492
3493 // Subscribe after taking the lock so contention cannot accumulate an unbounded replay.
3494 // Snapshot listeners run under that lock and must not block.
3495 const streamSession = (
3496 input: TerminalObserveInput,
3497 initial: Effect.Effect<TerminalSessionSnapshot | null, TerminalError>,
3498 listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
3499 registerCleanup?: (stop: () => void) => void,
3500 ) => {
3501 let unsubscribe: (() => void) | null = null;
3502 const stop = () => {
3503 unsubscribe?.();
3504 unsubscribe = null;
3505 };
3506
3507 return Effect.gen(function* () {
3508 const bufferedEvents: TerminalEvent[] = [];
3509 let deliverLive = false;
3510 let snapshotFloor: number | null = null;
3511
3512 yield* subscribe(
3513 (event) => {
3514 if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {
3515 return Effect.void;
3516 }
3517
3518 if (!deliverLive) {
3519 bufferedEvents.push(event);
3520 return Effect.void;
3521 }
3522
3523 // Fanout can finish after a snapshot that already includes the event.
3524 // Keep only its sequence, not its history, until the session changes.
3525 if (snapshotFloor !== null) {
3526 if (
3527 event.type === "started" ||
3528 event.type === "restarted" ||
3529 event.type === "error" ||
3530 event.type === "closed"
3531 ) {
3532 snapshotFloor = null;
3533 } else if (typeof event.sequence === "number" && event.sequence <= snapshotFloor) {
3534 return Effect.void;
3535 }
3536 }
3537
3538 const attachEvent = terminalEventToAttachEvent(event);
3539 return listener(attachEvent);
3540 },
3541 (cleanup) => {
3542 unsubscribe = cleanup;
3543 registerCleanup?.(stop);
3544 },
3545 );
3546
3547 const initialSnapshot = yield* initial;
3548
3549 yield* listener(
3550 initialSnapshot === null
3551 ? { type: "closed", threadId: input.threadId, terminalId: input.terminalId }
3552 : { type: "snapshot", snapshot: initialSnapshot },
3553 );
3554
3555 for (const event of bufferedEvents) {
3556 if (initialSnapshot !== null && isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {
3557 continue;
3558 }
3559
3560 const attachEvent = terminalEventToAttachEvent(event);
3561 yield* listener(attachEvent);
3562 }
3563 // The live listener keeps this closure, so release replayed output.
3564 bufferedEvents.length = 0;
3565
3566 snapshotFloor = initialSnapshot?.sequence ?? null;
3567 deliverLive = true;
3568 return stop;
3569 }).pipe(
3570 (effect) => withThreadLock(input.threadId, effect),
3571 Effect.onError(() => Effect.sync(stop)),
3572 );
3573 };
3574
3575 /** Retains `viewer` and returns its release, which runs at most once. */
3576 const retainViewerOnce = (
3577 input: TerminalObserveInput,
3578 viewer: string,
3579 grid: TerminalGrid | null,
3580 ) => {
3581 const sessionKey = toSessionKey(input.threadId, input.terminalId);
3582 retainViewer(sessionKey, viewer, grid);
3583 let retained = true;
3584 return () => {
3585 if (!retained) return;
3586 retained = false;
3587 if (releaseViewer(sessionKey, viewer)) {
3588 runFork(withThreadLock(input.threadId, applySharedGrid(input.threadId, input.terminalId)));
3589 }
3590 };
3591 };
3592
3593 const attachStream: TerminalManager["Service"]["attachStream"] = (
3594 input,
3595 listener,
3596 registerCleanup,
3597 viewerId,
3598 ) => {
3599 const viewer = viewerId ?? `stream:${++anonymousViewerCount}`;
3600 let detach = () => {};
3601 const initial = Effect.suspend(() => {
3602 detach = retainViewerOnce(
3603 input,
3604 viewer,
3605 input.cols !== undefined && input.rows !== undefined
3606 ? { cols: input.cols, rows: input.rows }
3607 : null,
3608 );
3609 return openOrAttachForStream(input);
3610 });
3611 return streamSession(
3612 input,
3613 initial,
3614 listener,
3615 registerCleanup &&
3616 ((stop) =>
3617 registerCleanup(() => {
3618 stop();
3619 detach();
3620 })),
3621 ).pipe(
3622 Effect.map((stop) => () => {
3623 stop();
3624 detach();
3625 }),
3626 Effect.onError(() => Effect.sync(detach)),
3627 );
3628 };
3629
3630 const observeStream: TerminalManager["Service"]["observeStream"] = (
3631 input,
3632 listener,
3633 registerCleanup,
3634 ) =>
3635 streamSession(
3636 input,
3637 requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)),
3638 listener,
3639 registerCleanup,
3640 );
3641
3642 const resyncStream: TerminalManager["Service"]["resyncStream"] = (
3643 input,
3644 listener,
3645 registerCleanup,
3646 ) =>
3647 streamSession(
3648 input,
3649 getSession(input.threadId, input.terminalId).pipe(
3650 Effect.map((session) => (Option.isSome(session) ? snapshot(session.value) : null)),
3651 ),
3652 listener,
3653 registerCleanup,
3654 );
3655
3656 const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = (
3657 input,
3658 viewerId,
3659 ) => {
3660 const { maxHistoryBytes } = input;
3661 const retained = (listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>) =>
3662 maxHistoryBytes === undefined
3663 ? listener
3664 : (event: TerminalAttachStreamEvent) =>
3665 listener(
3666 "snapshot" in event
3667 ? {
3668 ...event,
3669 snapshot: {
3670 ...event.snapshot,
3671 history: retainedTerminalHistory(event.snapshot.history, maxHistoryBytes),
3672 },
3673 }
3674 : event,
3675 );
3676 return Stream.unwrap(
3677 Effect.acquireRelease(
3678 Effect.sync(() => retainViewerOnce(input, viewerId, null)),
3679 (release) => Effect.sync(release),
3680 ).pipe(
3681 Effect.as(
3682 terminalOutputStream(
3683 (listener, registerCleanup) =>
3684 attachStream(input, retained(listener), registerCleanup, viewerId),
3685 (listener, registerCleanup) => resyncStream(input, retained(listener), registerCleanup),
3686 ),
3687 ),
3688 ),
3689 );
3690 };
3691
3692 const metadataEventFromTerminalEvent = (
3693 event: TerminalEvent,
3694 ): Effect.Effect<TerminalMetadataStreamEvent | null> => {
3695 if (!shouldPublishTerminalMetadataEvent(event)) {
3696 return Effect.succeed(null);
3697 }
3698
3699 if (event.type === "closed") {
3700 return Effect.succeed({
3701 type: "remove" as const,
3702 threadId: event.threadId,
3703 terminalId: event.terminalId,
3704 });
3705 }
3706
3707 return readTerminalMetadata({
3708 threadId: event.threadId,
3709 terminalId: event.terminalId,
3710 }).pipe(
3711 Effect.map((terminal) =>
3712 terminal
3713 ? {
3714 type: "upsert" as const,
3715 terminal,
3716 }
3717 : null,
3718 ),
3719 );
3720 };
3721
3722 const offerMetadataEvent = (
3723 listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,
3724 event: TerminalEvent,
3725 ) =>
3726 metadataEventFromTerminalEvent(event).pipe(
3727 Effect.flatMap((metadataEvent) => (metadataEvent ? listener(metadataEvent) : Effect.void)),
3728 );
3729
3730 const subscribeMetadata: TerminalManager["Service"]["subscribeMetadata"] = (listener) => {
3731 let unsubscribe: (() => void) | null = null;
3732
3733 return Effect.gen(function* () {
3734 const bufferedEvents: TerminalEvent[] = [];
3735 let deliverLive = false;
3736
3737 unsubscribe = yield* subscribe((event) => {
3738 if (!deliverLive) {
3739 bufferedEvents.push(event);
3740 return Effect.void;
3741 }
3742
3743 return offerMetadataEvent(listener, event);
3744 });
3745
3746 const terminals = yield* readAllTerminalMetadata();
3747 yield* listener({
3748 type: "snapshot",
3749 terminals,
3750 managerId,
3751 });
3752
3753 for (const event of bufferedEvents) {
3754 yield* offerMetadataEvent(listener, event);
3755 }
3756
3757 deliverLive = true;
3758 return () => {
3759 unsubscribe?.();
3760 unsubscribe = null;
3761 };
3762 }).pipe(
3763 Effect.catchCause((cause) =>
3764 Effect.flatMap(
3765 Effect.sync(() => {
3766 unsubscribe?.();
3767 unsubscribe = null;
3768 }),
3769 () => Effect.failCause(cause),
3770 ),
3771 ),
3772 );
3773 };
3774
3775 const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")(
3776 function* (input, viewerId) {
3777 const terminalId = input.terminalId;
3778 const session = yield* requireSession(input.threadId, terminalId);
3779 const process = session.process;
3780 if (!process || session.status !== "running") {
3781 if (session.status === "exited") return;
3782 return yield* new TerminalNotRunningError({
3783 threadId: input.threadId,
3784 terminalId,
3785 });
3786 }
3787 if (input.reply && !acceptsQueryReply(toSessionKey(input.threadId, terminalId), viewerId)) {
3788 return;
3789 }
3790 session.inputCount += 1;
3791 yield* Effect.try({
3792 try: () => process.write(PtyAdapter.ptyInput(input.data, input.binary)),
3793 catch: (cause) =>
3794 new TerminalWriteError({
3795 threadId: input.threadId,
3796 terminalId,
3797 terminalPid: process.pid,
3798 cause,
3799 }),
3800 });
3801 },
3802 );
3803
3804 const resizeLocked = Effect.fn("terminal.resize")(function* (
3805 input: TerminalResizeInput,
3806 viewerId: string | undefined,
3807 ) {
3808 const sessionKey = toSessionKey(input.threadId, input.terminalId);
3809 const viewer =
3810 viewerId === undefined ? undefined : terminalViewers.get(sessionKey)?.get(viewerId);
3811 if (viewer) {
3812 viewer.grid = { cols: input.cols, rows: input.rows };
3813 return yield* applySharedGrid(input.threadId, input.terminalId);
3814 }
3815 // A caller that is not attached cannot override the viewers that are.
3816 if (sharedViewerGrid(sessionKey)) return;
3817 const session = yield* getSession(input.threadId, input.terminalId);
3818 if (Option.isNone(session)) {
3819 return;
3820 }
3821 const process = session.value.process;
3822 if (
3823 !process ||
3824 session.value.status !== "running" ||
3825 (session.value.cols === input.cols && session.value.rows === input.rows)
3826 ) {
3827 return;
3828 }
3829 yield* resizeSession(session.value, process, input.cols, input.rows);
3830 });
3831
3832 const resize: TerminalManager["Service"]["resize"] = (input, viewerId) =>
3833 withThreadLock(input.threadId, resizeLocked(input, viewerId));
3834
3835 const clear: TerminalManager["Service"]["clear"] = (input) =>
3836 withThreadLock(
3837 input.threadId,
3838 Effect.gen(function* () {
3839 const terminalId = input.terminalId;
3840 const session = yield* requireSession(input.threadId, terminalId);
3841 session.history.clear();
3842 session.pendingHistoryControlSequence = "";
3843 session.pendingProcessEvents = [];
3844 session.pendingProcessEventIndex = 0;
3845 session.processEventDrainRunning = false;
3846 const eventStamp = advanceEventSequence(session);
3847 // A drain waits for the key to go idle, which never happens while the shell keeps
3848 // printing; every reader of the file flushes it first.
3849 yield* persistWorker.enqueue(toSessionKey(input.threadId, terminalId), {
3850 history: session.history,
3851 immediate: true,
3852 });
3853 yield* publishEvent({
3854 type: "cleared",
3855 threadId: input.threadId,
3856 terminalId,
3857 sequence: eventStamp.sequence,
3858 });
3859 }),
3860 );
3861
3862 const close: TerminalManager["Service"]["close"] = (input) =>
3863 withThreadLock(
3864 input.threadId,
3865 Effect.gen(function* () {
3866 if (input.terminalId) {
3867 yield* closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
3868 return;
3869 }
3870
3871 const threadSessions = yield* sessionsForThread(input.threadId);
3872 yield* Effect.forEach(
3873 threadSessions,
3874 (session) => closeSession(input.threadId, session.terminalId, false),
3875 { discard: true },
3876 );
3877
3878 if (input.deleteHistory) {
3879 yield* deleteAllHistoryForThread(input.threadId);
3880 }
3881 }),
3882 );
3883
3884 const closeIdle: TerminalManager["Service"]["closeIdle"] = (input) =>
3885 withThreadLock(
3886 input.threadId,
3887 Effect.gen(function* () {
3888 const running = (yield* sessionsForThread(input.threadId)).filter(
3889 (session): session is TerminalSessionState & { pid: number } =>
3890 session.status === "running" &&
3891 Number.isInteger(session.pid) &&
3892 (input.terminalId === undefined || session.terminalId === input.terminalId),
3893 );
3894 if (running.length === 0) return;
3895 const marks = new Map(
3896 running.map((session) => [session.terminalId, terminalActivityMark(session)]),
3897 );
3898 // Inspect now so commands started after the last poll still protect their terminals.
3899 const { inspector: inspectorResult } = yield* acquireSubprocessInspector(
3900 platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix,
3901 );
3902 const inspector = yield* Effect.fromResult(inspectorResult);
3903 yield* Effect.forEach(
3904 running,
3905 (session) =>
3906 inspector(session.pid, session.shell).pipe(
3907 Effect.flatMap((result) =>
3908 result.hasRunningSubprocess ||
3909 terminalActivityMark(session) !== marks.get(session.terminalId)
3910 ? Effect.void
3911 : closeSession(input.threadId, session.terminalId, false),
3912 ),
3913 ),
3914 { discard: true },
3915 );
3916 }),
3917 ).pipe(
3918 Effect.catch((error) =>
3919 Effect.logWarning("failed to close idle terminals", {
3920 threadId: input.threadId,
3921 error: error.message,
3922 }),
3923 ),
3924 );
3925
3926 const closeOnSettle = Effect.fn("terminal.closeOnSettle")(function* (input: {
3927 readonly threadId: string;
3928 }) {
3929 yield* withThreadLock(
3930 input.threadId,
3931 Effect.gen(function* () {
3932 const sessions = yield* sessionsForThread(input.threadId);
3933 yield* Effect.forEach(
3934 sessions.filter((session) => session.stopOnSettle),
3935 (session) => closeSession(input.threadId, session.terminalId, false),
3936 { discard: true },
3937 );
3938 }),
3939 );
3940 yield* closeIdle(input);
3941 });
3942
3943 const hasActiveSubprocess = Effect.fn("terminal.hasActiveSubprocess")(function* (input: {
3944 readonly threadId: string;
3945 }) {
3946 const running = (yield* sessionsForThread(input.threadId)).filter(
3947 (session): session is TerminalSessionState & { pid: number } =>
3948 session.status === "running" && Number.isInteger(session.pid),
3949 );
3950 if (running.length === 0) return false;
3951 const { inspector } = yield* acquireSubprocessInspector(
3952 platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix,
3953 );
3954 // A failed process query falls back to the last poll's answer.
3955 const isActive = (session: (typeof running)[number]) =>
3956 Result.isFailure(inspector)
3957 ? Effect.succeed(session.hasRunningSubprocess)
3958 : inspector.success(session.pid, session.shell).pipe(
3959 Effect.map((result) => result.hasRunningSubprocess),
3960 Effect.orElseSucceed(() => session.hasRunningSubprocess),
3961 );
3962 return Option.isSome(yield* Effect.findFirst(running, isActive));
3963 });
3964
3965 return TerminalManager.of({
3966 open,
3967 getShell,
3968 attachStream,
3969 attachOutputStream,
3970 observeStream,
3971 resyncStream,
3972 write,
3973 resize,
3974 clear,
3975 close,
3976 closeIdle,
3977 closeOnSettle,
3978 hasActiveSubprocess,
3979 subscribe,
3980 subscribeMetadata,
3981 });
3982 });
3983
3984 export const layer = (deriveConfigMap: typeof deriveProviderInstanceConfigMap) =>
3985 Layer.effect(TerminalManager, make(deriveConfigMap)).pipe(Layer.provide(ProcessRunner.layer));