Repository navigation
Expand file tree
/
Copy pathManager.ts
More file actions
3173 lines (2902 loc) · 103 KB
/
Copy pathManager.ts
File metadata and controls
3173 lines (2902 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* TerminalManager - Terminal session orchestration service interface.
*
* Owns terminal lifecycle operations, output fanout, and session state
* transitions for thread-scoped terminals.
*
* @module TerminalManager
*/
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import {
DEFAULT_TERMINAL_ID,
TerminalCwdError,
TerminalCwdNotDirectoryError,
TerminalCwdNotFoundError,
TerminalCwdStatError,
TerminalError,
TerminalHistoryError,
TerminalNotRunningError,
TerminalProviderInstanceNotFoundError,
TerminalProviderEnvironmentError,
TerminalResizeError,
TerminalSessionLookupError,
TerminalWriteError,
type TerminalAttachInput,
type TerminalAttachStreamEvent,
type TerminalClearInput,
type TerminalCloseInput,
type TerminalEvent,
type TerminalMetadataStreamEvent,
type TerminalOpenInput,
type TerminalResizeInput,
type ResourceMonitorProcessTableEntry,
type TerminalRestartInput,
type TerminalSessionSnapshot,
type TerminalSessionStatus,
type TerminalSummary,
type TerminalWriteInput,
ClaudeSettings,
CodexSettings,
ProviderInstanceId,
} from "@t3tools/contracts";
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { mergePathEntries } from "@t3tools/shared/shell";
import { acpRegistryManagedBinaryDirectories } from "../provider/acp/AcpRegistrySupport.ts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as DateTime from "effect/DateTime";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as ServerConfig from "../config.ts";
import {
literalProviderInstanceEnvironment,
mergeProviderInstanceEnvironment,
} from "../provider/ProviderInstanceEnvironment.ts";
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts";
import * as ServerSettings from "../serverSettings.ts";
import {
increment,
terminalRestartsTotal,
terminalSessionsTotal,
} from "../observability/Metrics.ts";
import { expandHomePath } from "../pathExpansion.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as PortScanner from "../preview/PortScanner.ts";
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
import * as PtyAdapter from "./PtyAdapter.ts";
export {
TerminalCwdError,
TerminalCwdNotDirectoryError,
TerminalCwdNotFoundError,
TerminalCwdStatError,
TerminalError,
TerminalHistoryError,
TerminalNotRunningError,
TerminalProviderInstanceNotFoundError,
TerminalProviderEnvironmentError,
TerminalResizeError,
TerminalSessionLookupError,
TerminalWriteError,
};
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_HISTORY_BYTE_LIMIT = 8 * 1024 * 1024;
const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000;
const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;
const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
const DEFAULT_OPEN_COLS = 120;
const DEFAULT_OPEN_ROWS = 30;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const MAX_TERMINAL_LABEL_LENGTH = 128;
const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
class TerminalSubprocessCheckError extends Schema.TaggedError<TerminalSubprocessCheckError>()(
"TerminalSubprocessCheckError",
{
cause: Schema.optional(Schema.Defect()),
command: Schema.Literals(["powershell", "ps", "resource-monitor"]),
exitCode: Schema.optional(Schema.NullOr(Schema.Number)),
timedOut: Schema.optional(Schema.Boolean),
stdoutTruncated: Schema.optional(Schema.Boolean),
},
) {
override get message(): string {
const details = [
this.exitCode !== undefined && this.exitCode !== null ? `exit code ${this.exitCode}` : null,
this.timedOut ? "timed out" : null,
this.stdoutTruncated ? "output truncated" : null,
]
.filter((detail) => detail !== null)
.join(", ");
return `Failed to inspect terminal subprocesses with ${this.command}${details.length > 0 ? ` (${details})` : ""}`;
}
}
class TerminalProcessSignalError extends Schema.TaggedError<TerminalProcessSignalError>()(
"TerminalProcessSignalError",
{
cause: Schema.optional(Schema.Defect()),
signal: Schema.Literals(["SIGTERM", "SIGKILL"]),
terminalPid: Schema.Number,
},
) {
override get message(): string {
return `Failed to send ${this.signal} to terminal process ${this.terminalPid}`;
}
}
/**
* TerminalManager - Service tag for terminal session orchestration.
*/
export class TerminalManager extends Context.Service<
TerminalManager,
{
/**
* Open or attach to a terminal session.
*
* Reuses an existing session for the same thread/terminal id and restores
* persisted history on first open.
*/
readonly open: (
input: TerminalOpenInput,
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
/**
* Attach to a terminal and stream its initial snapshot followed by live events.
*
* Returns an unsubscribe function.
*/
readonly attachStream: (
input: TerminalAttachInput,
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void, TerminalError>;
/**
* Write input bytes to a terminal session.
*/
readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;
/**
* Resize the PTY backing a terminal session.
*/
readonly resize: (input: TerminalResizeInput) => Effect.Effect<void, TerminalError>;
/**
* Clear terminal output history.
*/
readonly clear: (input: TerminalClearInput) => Effect.Effect<void, TerminalError>;
/**
* Restart a terminal session in place.
*
* Always resets history before spawning the new process.
*/
readonly restart: (
input: TerminalRestartInput,
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
/**
* Close an active terminal session.
*
* When `terminalId` is omitted, closes all sessions for the thread.
*/
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
/**
* Close a thread's terminals that wait at an idle shell prompt. A terminal
* that runs a command stays open. When `terminalId` is set, only that
* terminal is considered. Used when a thread settles and when a setup
* script finishes.
*/
readonly closeIdle: (input: {
readonly threadId: string;
readonly terminalId?: string;
}) => Effect.Effect<void>;
/**
* Subscribe to terminal runtime events with a direct callback.
*
* Returns an unsubscribe function.
*/
readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
/**
* Subscribe to lightweight terminal metadata with an initial full snapshot.
*
* Returns an unsubscribe function.
*/
readonly subscribeMetadata: (
listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
}
>()("t3/terminal/Manager/TerminalManager") {}
interface TerminalSubprocessInspectResult {
readonly hasRunningSubprocess: boolean;
readonly childCommand: string | null;
readonly processIds: ReadonlyArray<number>;
}
interface TerminalSubprocessInspector {
(
terminalPid: number,
): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError>;
}
const resizePtyProcess = (
session: TerminalSessionState,
process: PtyAdapter.PtyProcess,
cols: number,
rows: number,
) =>
Effect.try({
try: () => process.resize(cols, rows),
catch: (cause) =>
new TerminalResizeError({
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid: process.pid,
cols,
rows,
cause,
}),
});
export interface ShellCandidate {
shell: string;
args?: string[];
}
export interface TerminalStartInput extends TerminalOpenInput {
cols: number;
rows: number;
}
interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
worktreePath: string | null;
status: TerminalSessionStatus;
pid: number | null;
history: BoundedTerminalHistory;
pendingHistoryControlSequence: string;
pendingProcessEvents: Array<PendingProcessEvent>;
pendingProcessEventIndex: number;
processEventDrainRunning: boolean;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
eventSequence: number;
/** Counts writes, so closeIdle can see input that has not echoed yet. */
inputCount: number;
cols: number;
rows: number;
process: PtyAdapter.PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
/** Normalized child command name when `hasRunningSubprocess`; cleared when idle. */
childCommandLabel: string | null;
runtimeEnv: Record<string, string> | null;
}
interface PersistHistoryRequest {
history: BoundedTerminalHistory;
immediate: boolean;
}
type PendingProcessEvent =
| { type: "output"; data: string }
| { type: "exit"; event: PtyAdapter.PtyExitEvent };
type DrainProcessEventAction =
| { type: "idle" }
| {
type: "output";
threadId: string;
terminalId: string;
sequence: number;
history: BoundedTerminalHistory | null;
data: string;
}
| {
type: "exit";
process: PtyAdapter.PtyProcess | null;
threadId: string;
terminalId: string;
sequence: number;
exitCode: number | null;
exitSignal: number | null;
};
interface TerminalManagerState {
sessions: Map<string, TerminalSessionState>;
killFibers: Map<PtyAdapter.PtyProcess, Fiber.Fiber<void, never>>;
}
function truncateTerminalWireLabel(value: string): string {
if (value.length <= MAX_TERMINAL_LABEL_LENGTH) return value;
return value.slice(0, MAX_TERMINAL_LABEL_LENGTH);
}
function normalizeChildCommandName(raw: string, platform: NodeJS.Platform): string | null {
let trimmed = raw.trim();
if (trimmed.length === 0) return null;
if (
(trimmed.startsWith("[") && trimmed.endsWith("]")) ||
(trimmed.startsWith("(") && trimmed.endsWith(")"))
) {
trimmed = trimmed.slice(1, -1).trim();
}
const firstToken = (trimmed.split(/\s+/)[0] ?? trimmed).trim();
if (firstToken.length === 0) return null;
const separators = platform === "win32" ? /[\\/]/ : /\//;
const base = firstToken.split(separators).at(-1) ?? firstToken;
const withoutExe =
platform === "win32" && base.toLowerCase().endsWith(".exe") ? base.slice(0, -4) : base;
return withoutExe.length > 0 ? withoutExe : null;
}
function terminalWireLabel(session: TerminalSessionState): string {
if (session.hasRunningSubprocess && session.childCommandLabel) {
const trimmed = session.childCommandLabel.trim();
if (trimmed.length > 0) {
return truncateTerminalWireLabel(trimmed);
}
}
return truncateTerminalWireLabel(getTerminalLabel(session.terminalId));
}
function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
return {
threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd,
worktreePath: session.worktreePath,
status: session.status,
pid: session.pid,
history: session.history.value(),
exitCode: session.exitCode,
exitSignal: session.exitSignal,
label: terminalWireLabel(session),
updatedAt: session.updatedAt,
sequence: session.eventSequence,
};
}
function summary(session: TerminalSessionState): TerminalSummary {
return {
threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd,
worktreePath: session.worktreePath,
status: session.status,
pid: session.pid,
exitCode: session.exitCode,
exitSignal: session.exitSignal,
hasRunningSubprocess: session.hasRunningSubprocess,
label: terminalWireLabel(session),
updatedAt: session.updatedAt,
};
}
function shouldPublishTerminalMetadataEvent(event: TerminalEvent): boolean {
switch (event.type) {
case "started":
case "restarted":
case "exited":
case "closed":
case "error":
case "activity":
return true;
case "output":
case "cleared":
return false;
}
}
function terminalEventToAttachEvent(event: TerminalEvent): TerminalAttachStreamEvent | null {
switch (event.type) {
case "started":
return {
type: "snapshot",
snapshot: event.snapshot,
};
case "output":
case "exited":
case "closed":
case "error":
case "cleared":
case "restarted":
case "activity":
return event;
}
}
function isDuplicateAttachSnapshotEvent(
event: TerminalEvent,
initialSnapshot: TerminalSessionSnapshot,
) {
return typeof event.sequence === "number" && typeof initialSnapshot.sequence === "number"
? event.sequence <= initialSnapshot.sequence
: event.type === "started" &&
event.snapshot.threadId === initialSnapshot.threadId &&
event.snapshot.terminalId === initialSnapshot.terminalId &&
event.snapshot.updatedAt <= initialSnapshot.updatedAt;
}
function advanceEventSequence(session: TerminalSessionState): {
readonly updatedAt: string;
readonly sequence: number;
} {
const updatedAt = DateTime.formatIso(DateTime.nowUnsafe());
session.eventSequence += 1;
session.updatedAt = updatedAt;
return { updatedAt, sequence: session.eventSequence };
}
function cleanupProcessHandles(session: TerminalSessionState): void {
session.unsubscribeData?.();
session.unsubscribeData = null;
session.unsubscribeExit?.();
session.unsubscribeExit = null;
}
function enqueueProcessEvent(
session: TerminalSessionState,
expectedPid: number,
event: PendingProcessEvent,
): boolean {
if (!session.process || session.status !== "running" || session.pid !== expectedPid) {
return false;
}
session.pendingProcessEvents.push(event);
if (session.processEventDrainRunning) {
return false;
}
session.processEventDrainRunning = true;
return true;
}
function defaultShellResolver(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string {
if (platform === "win32") {
return "pwsh.exe";
}
return env.SHELL ?? "bash";
}
function normalizeShellCommand(
value: string | undefined,
platform: NodeJS.Platform,
): string | null {
if (!value) return null;
const trimmed = value.trim();
if (trimmed.length === 0) return null;
if (platform === "win32") {
return trimmed;
}
const firstToken = trimmed.split(/\s+/g)[0]?.trim();
if (!firstToken) return null;
return firstToken.replace(/^['"]|['"]$/g, "");
}
function basenameForPlatform(command: string, platform: NodeJS.Platform): string {
const normalized =
platform === "win32" ? command.replaceAll("/", "\\") : command.replaceAll("\\", "/");
const parts = normalized
.split(platform === "win32" ? /\\+/ : /\/+/)
.filter((part) => part.length > 0);
return parts.at(-1) ?? normalized;
}
function joinWindowsPath(...parts: ReadonlyArray<string>): string {
return parts
.map((part, index) => {
if (index === 0) return part.replace(/[\\/]+$/g, "");
return part.replace(/^[\\/]+|[\\/]+$/g, "");
})
.filter((part) => part.length > 0)
.join("\\");
}
function shellCandidateFromCommand(
command: string | null,
platform: NodeJS.Platform,
): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = basenameForPlatform(command, platform).toLowerCase();
if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
return { shell: command, args: ["-NoLogo"] };
}
if (platform !== "win32" && shellName === "zsh") {
return { shell: command, args: ["-o", "nopromptsp"] };
}
return { shell: command };
}
function windowsSystemRoot(env: NodeJS.ProcessEnv): string {
return env.SystemRoot?.trim() || env.windir?.trim() || "C:\\Windows";
}
function windowsPowerShellPath(env: NodeJS.ProcessEnv): string {
return joinWindowsPath(
windowsSystemRoot(env),
"System32",
"WindowsPowerShell",
"v1.0",
"powershell.exe",
);
}
function windowsCmdPath(env: NodeJS.ProcessEnv): string {
return joinWindowsPath(windowsSystemRoot(env), "System32", "cmd.exe");
}
function formatShellCandidate(candidate: ShellCandidate): string {
if (!candidate.args || candidate.args.length === 0) return candidate.shell;
return `${candidate.shell} ${candidate.args.join(" ")}`;
}
function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
const seen = new Set<string>();
const ordered: ShellCandidate[] = [];
for (const candidate of candidates) {
if (!candidate) continue;
const key = formatShellCandidate(candidate);
if (seen.has(key)) continue;
seen.add(key);
ordered.push(candidate);
}
return ordered;
}
function resolveShellCandidates(
shellResolver: () => string,
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): ShellCandidate[] {
const requested = shellCandidateFromCommand(
normalizeShellCommand(shellResolver(), platform),
platform,
);
if (platform === "win32") {
return uniqueShellCandidates([
requested,
shellCandidateFromCommand("pwsh.exe", platform),
shellCandidateFromCommand(windowsPowerShellPath(env), platform),
shellCandidateFromCommand("powershell.exe", platform),
shellCandidateFromCommand(env.ComSpec ?? null, platform),
shellCandidateFromCommand(windowsCmdPath(env), platform),
shellCandidateFromCommand("cmd.exe", platform),
]);
}
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(normalizeShellCommand(env.SHELL, platform), platform),
shellCandidateFromCommand("/bin/zsh", platform),
shellCandidateFromCommand("/bin/bash", platform),
shellCandidateFromCommand("/bin/sh", platform),
shellCandidateFromCommand("zsh", platform),
shellCandidateFromCommand("bash", platform),
shellCandidateFromCommand("sh", platform),
]);
}
function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
const queue: unknown[] = [error];
const seen = new Set<unknown>();
const messages: string[] = [];
while (queue.length > 0) {
const current = queue.shift();
if (!current || seen.has(current)) {
continue;
}
seen.add(current);
if (typeof current === "string") {
messages.push(current);
continue;
}
if (current instanceof Error) {
messages.push(current.message);
if (current.cause) {
queue.push(current.cause);
}
continue;
}
if (typeof current === "object") {
const value = current as { message?: unknown; cause?: unknown };
if (typeof value.message === "string") {
messages.push(value.message);
}
if (value.cause) {
queue.push(value.cause);
}
}
}
const message = messages.join(" ").toLowerCase();
return (
message.includes("posix_spawnp failed") ||
message.includes("enoent") ||
message.includes("not found") ||
message.includes("file not found") ||
message.includes("no such file")
);
}
interface TerminalProcessTableSnapshot {
readonly childrenByParent: ReadonlyMap<number, ReadonlyArray<number>>;
readonly commandById: ReadonlyMap<number, string>;
}
export function subprocessSnapshotPollDelayMs(
pollIntervalMs: number,
failureCount: number,
): number {
return Math.min(pollIntervalMs * 2 ** failureCount, MAX_SUBPROCESS_POLL_INTERVAL_MS);
}
function parsePosixProcessTable(stdout: string): TerminalProcessTableSnapshot {
const childrenByParent = new Map<number, number[]>();
const commandById = new Map<number, string>();
for (const line of stdout.split(/\r?\n/g)) {
// `comm=` is the final column and may itself contain spaces, so only the
// first two tokens are structural.
const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
if (!match) continue;
const pid = Number(match[1]);
const ppid = Number(match[2]);
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
commandById.set(pid, (match[3] ?? "").trim());
const children = childrenByParent.get(ppid) ?? [];
children.push(pid);
childrenByParent.set(ppid, children);
}
return { childrenByParent, commandById };
}
function processTableSnapshotFromProcesses(
processes: ReadonlyArray<ResourceMonitorProcessTableEntry>,
): TerminalProcessTableSnapshot {
const childrenByParent = new Map<number, number[]>();
const commandById = new Map<number, string>();
for (const process of processes) {
const { pid, ppid: parentPid, name } = process;
if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;
commandById.set(pid, name.trim());
const children = childrenByParent.get(parentPid) ?? [];
children.push(pid);
childrenByParent.set(parentPid, children);
}
return { childrenByParent, commandById };
}
function deriveSubprocessInspectResult(
snapshot: TerminalProcessTableSnapshot,
terminalPid: number,
platform: NodeJS.Platform,
): TerminalSubprocessInspectResult {
const commandName = (pid: number) =>
normalizeChildCommandName(snapshot.commandById.get(pid) ?? "", platform);
const shellName = commandName(terminalPid);
// Async prompt themes fork the shell into a helper that waits with no
// children of its own. That copy is not a command the user started.
const childPid = (snapshot.childrenByParent.get(terminalPid) ?? []).find(
(pid) =>
shellName === null ||
commandName(pid) !== shellName ||
(snapshot.childrenByParent.get(pid)?.length ?? 0) > 0,
);
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
const processIds = new Set<number>([terminalPid]);
const pending = [terminalPid];
while (pending.length > 0) {
const parentPid = pending.pop();
if (parentPid === undefined) continue;
for (const pid of snapshot.childrenByParent.get(parentPid) ?? []) {
if (processIds.has(pid)) continue;
processIds.add(pid);
pending.push(pid);
}
}
const normalized = commandName(childPid);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
processIds: [...processIds],
};
}
const POSIX_PS_ABSOLUTE_PATHS = ["/bin/ps", "/usr/bin/ps"] as const;
// Resolve `ps` to an absolute path once at startup. Spawning by bare name
// walks every PATH entry per spawn (one failed posix_spawn per directory
// until the hit), which is measurable at a 1s poll cadence on long PATHs.
const resolvePosixPsCommand = Effect.fn("terminal.resolvePosixPsCommand")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
for (const candidate of POSIX_PS_ABSOLUTE_PATHS) {
const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
if (exists) return candidate;
}
return "ps";
});
const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot")(function* (
psCommand: string,
): Effect.fn.Return<
TerminalProcessTableSnapshot,
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const result = yield* processRunner
.run({
command: psCommand,
args: ["-eo", "pid=,ppid=,comm="],
timeout: "1 second",
maxOutputBytes: 524_288,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
cause,
command: "ps",
}),
),
);
if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
// Not authoritative: an empty or partial table would mark every terminal
// idle and clear its registered process ids. Failing skips the tick.
return yield* new TerminalSubprocessCheckError({
command: "ps",
exitCode: result.code,
timedOut: result.timedOut,
stdoutTruncated: result.stdoutTruncated,
});
}
return parsePosixProcessTable(result.stdout);
});
const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnapshot")(
function* (): Effect.fn.Return<
TerminalProcessTableSnapshot,
TerminalSubprocessCheckError,
ProcessRunner.ProcessRunner
> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const command =
'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }';
const result = yield* processRunner
.run({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: 262_144,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) => new TerminalSubprocessCheckError({ cause, command: "powershell" }),
),
);
if (result.code !== 0 || result.timedOut || result.stdoutTruncated) {
return yield* new TerminalSubprocessCheckError({
command: "powershell",
exitCode: result.code,
timedOut: result.timedOut,
stdoutTruncated: result.stdoutTruncated,
});
}
const processes = result.stdout.split(/\r?\n/g).flatMap((line) => {
const [pidRaw, ppidRaw, name = ""] = line.trim().split("|", 3);
const pid = Number(pidRaw);
const ppid = Number(ppidRaw);
return Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid)
? [{ pid, ppid, name }]
: [];
});
return processTableSnapshotFromProcesses(processes);
},
);
interface TerminalHistoryChunk {
data: string;
byteLength: number;
lineBreaks: number;
}
export class BoundedTerminalHistory {
private readonly maxLines: number;
private readonly maxBytes: number;
private chunks: Array<TerminalHistoryChunk | undefined> = [];
private start = 0;
private byteLength = 0;
private lineBreaks = 0;
// Reading the old string's tail on each append can force chunk concatenation.
private lastCodeUnit: number | undefined;
private cachedValue: string | null = "";
constructor(maxLines: number, initial: string, maxBytes = DEFAULT_HISTORY_BYTE_LIMIT) {
this.maxLines = maxLines;
this.maxBytes = maxBytes;
this.append(initial);
}
append(text: string): void {
if (text.length === 0) return;
this.cachedValue = null;
if (this.maxBytes <= 0 || this.maxLines <= 0) {
this.clear();
// Preserve the existing zero-line limit's trailing newline behavior.
if (this.maxBytes > 0 && text.endsWith("\n")) this.appendChunk("\n");
return;
}
let offset = 0;
const previous = this.chunks.at(-1);
const lastCode = this.lastCodeUnit;
const firstCode = text.charCodeAt(0);
if (
previous &&
lastCode !== undefined &&
lastCode >= 0xd800 &&
lastCode <= 0xdbff &&
firstCode >= 0xdc00 &&
firstCode <= 0xdfff
) {
// Joining a split surrogate changes its UTF-8 size from 3 to 4 bytes.
previous.data += text[0];
previous.byteLength += 1;
this.byteLength += 1;
this.lastCodeUnit = firstCode;
offset = 1;
this.trim();
}
while (offset < text.length) {
let end = Math.min(offset + MAX_HISTORY_CHUNK_LENGTH, text.length);
const before = text.charCodeAt(end - 1);
const after = text.charCodeAt(end);
if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) {
end -= 1;
}
const data = text.slice(offset, end);
// Detach small chunks from large input strings so evicted prefixes can be collected.
this.appendChunk(
text.length > MAX_HISTORY_CHUNK_LENGTH
? Buffer.from(data, "utf16le").toString("utf16le")
: data,
);
this.trim();
offset = end;
}
}
private appendChunk(data: string): void {
const byteLength = Buffer.byteLength(data);
let lineBreaks = 0;
for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) {
lineBreaks += 1;
}
const previous = this.chunks.at(-1);
if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) {
previous.data += data;
previous.byteLength += byteLength;
previous.lineBreaks += lineBreaks;
} else {
this.chunks.push({ data, byteLength, lineBreaks });
}
this.byteLength += byteLength;
this.lineBreaks += lineBreaks;
this.lastCodeUnit = data.charCodeAt(data.length - 1);
this.cachedValue = null;
}
private discardChunk(): void {
const first = this.chunks[this.start]!;
this.byteLength -= first.byteLength;
this.lineBreaks -= first.lineBreaks;
this.chunks[this.start++] = undefined;
}
private trimChunk(offset: number, byteLength: number, lineBreaks: number): void {
const first = this.chunks[this.start]!;
if (offset === first.data.length) {
this.discardChunk();
return;
}
first.data = first.data.slice(offset);
first.byteLength -= byteLength;
first.lineBreaks -= lineBreaks;
this.byteLength -= byteLength;
this.lineBreaks -= lineBreaks;
}
private trim(): void {
const trailingNewline = this.lastCodeUnit === 10;
let linesToDrop = this.lineBreaks + (trailingNewline ? 0 : 1) - this.maxLines;
while (linesToDrop > 0) {
const first = this.chunks[this.start]!;
if (first.lineBreaks < linesToDrop) {
linesToDrop -= first.lineBreaks;
this.discardChunk();
continue;
}
let offset = 0;
for (let line = 0; line < linesToDrop; line += 1) {
offset = first.data.indexOf("\n", offset) + 1;
}
this.trimChunk(offset, Buffer.byteLength(first.data.slice(0, offset)), linesToDrop);
linesToDrop = 0;
}
while (this.byteLength > this.maxBytes) {
const first = this.chunks[this.start]!;
const bytesToDrop = this.byteLength - this.maxBytes;
if (first.byteLength <= bytesToDrop) {
this.discardChunk();
continue;
}
if (first.byteLength === first.data.length && first.lineBreaks === 0) {
// ASCII without newlines needs no scan to find the byte cutoff.
this.trimChunk(bytesToDrop, bytesToDrop, 0);
continue;
}
let offset = 0;
let bytes = 0;
let lineBreaks = 0;
// Scan only the discarded prefix of one small chunk, never all history.
while (bytes < bytesToDrop) {
const codePoint = first.data.codePointAt(offset)!;
bytes += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;
offset += codePoint <= 0xffff ? 1 : 2;
if (codePoint === 10) lineBreaks += 1;
}
this.trimChunk(offset, bytes, lineBreaks);
}
if (
this.start === this.chunks.length ||
(this.start > 2_048 && this.start * 2 >= this.chunks.length)