-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathshellExecutionService.ts
More file actions
1036 lines (925 loc) · 31.6 KB
/
shellExecutionService.ts
File metadata and controls
1036 lines (925 loc) · 31.6 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
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import stripAnsi from 'strip-ansi';
import type { PtyImplementation } from '../utils/getPty.js';
import { getPty } from '../utils/getPty.js';
import { spawn as cpSpawn, spawnSync } from 'node:child_process';
import { TextDecoder } from 'node:util';
import os from 'node:os';
import type { IPty } from '@lydell/node-pty';
import { getCachedEncodingForBuffer } from '../utils/systemEncoding.js';
import { isBinary } from '../utils/textUtils.js';
import {
getShellConfiguration,
isRunningInMSYS2,
} from '../utils/shell-utils.js';
import pkg from '@xterm/headless';
import {
serializeTerminalToObject,
type AnsiOutput,
} from '../utils/terminalSerializer.js';
const { Terminal } = pkg;
const SIGKILL_TIMEOUT_MS = 200;
const WINDOWS_PATH_DELIMITER = ';';
let cachedWindowsPathFingerprint: string | undefined;
let cachedMergedWindowsPath: string | undefined;
function mergeWindowsPathValues(
env: NodeJS.ProcessEnv,
pathKeys: string[],
): string | undefined {
const mergedEntries: string[] = [];
const seenEntries = new Set<string>();
for (const key of pathKeys) {
const value = env[key];
if (value === undefined) {
continue;
}
for (const entry of value.split(WINDOWS_PATH_DELIMITER)) {
if (seenEntries.has(entry)) {
continue;
}
seenEntries.add(entry);
mergedEntries.push(entry);
}
}
return mergedEntries.length > 0
? mergedEntries.join(WINDOWS_PATH_DELIMITER)
: undefined;
}
function getWindowsPathFingerprint(
env: NodeJS.ProcessEnv,
pathKeys: string[],
): string {
return pathKeys.map((key) => `${key}=${env[key] ?? ''}`).join('\0');
}
function normalizePathEnvForWindows(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
if (os.platform() !== 'win32') {
return env;
}
const normalized: NodeJS.ProcessEnv = { ...env };
const pathKeys = Object.keys(normalized).filter(
(key) => key.toLowerCase() === 'path',
);
if (pathKeys.length === 0) {
return normalized;
}
const orderedPathKeys = [...pathKeys].sort((left, right) => {
if (left === 'PATH') {
return -1;
}
if (right === 'PATH') {
return 1;
}
return left.localeCompare(right);
});
const fingerprint = getWindowsPathFingerprint(normalized, orderedPathKeys);
const canonicalValue =
fingerprint === cachedWindowsPathFingerprint
? cachedMergedWindowsPath
: mergeWindowsPathValues(normalized, orderedPathKeys);
if (fingerprint !== cachedWindowsPathFingerprint) {
cachedWindowsPathFingerprint = fingerprint;
cachedMergedWindowsPath = canonicalValue;
}
for (const key of pathKeys) {
if (key !== 'PATH') {
delete normalized[key];
}
}
if (canonicalValue !== undefined) {
normalized['PATH'] = canonicalValue;
}
return normalized;
}
/**
* On Windows with PowerShell, prefix the command with a statement that forces
* UTF-8 output encoding so that CJK and other non-ASCII characters are emitted
* as UTF-8 regardless of the system codepage.
*/
function applyPowerShellUtf8Prefix(command: string, shell: string): string {
if (os.platform() === 'win32' && shell === 'powershell') {
return '[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;' + command;
}
return command;
}
/** A structured result from a shell command execution. */
export interface ShellExecutionResult {
/** The raw, unprocessed output buffer. */
rawOutput: Buffer;
/** The combined, decoded output as a string. */
output: string;
/** The process exit code, or null if terminated by a signal. */
exitCode: number | null;
/** The signal that terminated the process, if any. */
signal: number | null;
/** An error object if the process failed to spawn. */
error: Error | null;
/** A boolean indicating if the command was aborted by the user. */
aborted: boolean;
/** The process ID of the spawned shell. */
pid: number | undefined;
/** The method used to execute the shell command. */
executionMethod: 'lydell-node-pty' | 'node-pty' | 'child_process' | 'none';
}
/** A handle for an ongoing shell execution. */
export interface ShellExecutionHandle {
/** The process ID of the spawned shell. */
pid: number | undefined;
/** A promise that resolves with the complete execution result. */
result: Promise<ShellExecutionResult>;
}
export interface ShellExecutionConfig {
terminalWidth?: number;
terminalHeight?: number;
pager?: string;
showColor?: boolean;
defaultFg?: string;
defaultBg?: string;
// Used for testing
disableDynamicLineTrimming?: boolean;
}
/**
* Describes a structured event emitted during shell command execution.
*/
export type ShellOutputEvent =
| {
/** The event contains a chunk of output data. */
type: 'data';
/** The decoded string chunk. */
chunk: string | AnsiOutput;
}
| {
/** Signals that the output stream has been identified as binary. */
type: 'binary_detected';
}
| {
/** Provides progress updates for a binary stream. */
type: 'binary_progress';
/** The total number of bytes received so far. */
bytesReceived: number;
};
interface ActivePty {
ptyProcess: IPty;
headlessTerminal: pkg.Terminal;
}
const getErrnoCode = (error: unknown): string | undefined => {
if (!error || typeof error !== 'object' || !('code' in error)) {
return undefined;
}
const code = (error as { code?: unknown }).code;
return typeof code === 'string' ? code : undefined;
};
const getErrorMessage = (error: unknown): string =>
error instanceof Error ? error.message : String(error);
const isExpectedPtyReadExitError = (error: unknown): boolean => {
const code = getErrnoCode(error);
if (code === 'EIO') {
return true;
}
const message = getErrorMessage(error);
return message.includes('read EIO');
};
const isExpectedPtyExitRaceError = (error: unknown): boolean => {
const code = getErrnoCode(error);
if (code === 'ESRCH' || code === 'EBADF') {
return true;
}
const message = getErrorMessage(error);
return (
message.includes('ioctl(2) failed, EBADF') ||
message.includes('Cannot resize a pty that has already exited')
);
};
const getFullBufferText = (terminal: pkg.Terminal): string => {
const buffer = terminal.buffer.active;
const lines: string[] = [];
for (let i = 0; i < buffer.length; i++) {
const line = buffer.getLine(i);
const lineContent = line ? line.translateToString(true) : '';
lines.push(lineContent);
}
return lines.join('\n').trimEnd();
};
const replayTerminalOutput = async (
output: string,
cols: number,
rows: number,
): Promise<string> => {
const replayTerminal = new Terminal({
allowProposedApi: true,
cols,
rows,
scrollback: 10000,
convertEol: true,
});
await new Promise<void>((resolve) => {
replayTerminal.write(output, () => resolve());
});
return getFullBufferText(replayTerminal);
};
interface ProcessCleanupStrategy {
killPty(pid: number, pty: ActivePty): void;
killChildProcesses(pids: Set<number>): void;
}
const windowsStrategy: ProcessCleanupStrategy = {
killPty: (_pid, pty) => {
pty.ptyProcess.kill();
},
killChildProcesses: (pids) => {
if (pids.size > 0) {
try {
const args = ['/f', '/t'];
for (const pid of pids) {
args.push('/pid', pid.toString());
}
spawnSync('taskkill', args);
} catch {
// ignore
}
}
},
};
const posixStrategy: ProcessCleanupStrategy = {
killPty: (pid, _pty) => {
process.kill(-pid, 'SIGKILL');
},
killChildProcesses: (pids) => {
for (const pid of pids) {
try {
process.kill(-pid, 'SIGKILL');
} catch {
// ignore
}
}
},
};
const getCleanupStrategy = () =>
os.platform() === 'win32' ? windowsStrategy : posixStrategy;
/**
* A centralized service for executing shell commands with robust process
* management, cross-platform compatibility, and streaming output capabilities.
*
*/
export class ShellExecutionService {
private static activePtys = new Map<number, ActivePty>();
private static activeChildProcesses = new Set<number>();
static cleanup() {
const strategy = getCleanupStrategy();
// Cleanup PTYs
for (const [pid, pty] of this.activePtys) {
try {
strategy.killPty(pid, pty);
} catch {
// ignore
}
}
// Cleanup child processes
strategy.killChildProcesses(this.activeChildProcesses);
}
static {
process.on('exit', () => {
ShellExecutionService.cleanup();
});
}
/**
* Executes a shell command using `node-pty`, capturing all output and lifecycle events.
*
* @param commandToExecute The exact command string to run.
* @param cwd The working directory to execute the command in.
* @param onOutputEvent A callback for streaming structured events about the execution, including data chunks and status updates.
* @param abortSignal An AbortSignal to terminate the process and its children.
* @returns An object containing the process ID (pid) and a promise that
* resolves with the complete execution result.
*/
static async execute(
commandToExecute: string,
cwd: string,
onOutputEvent: (event: ShellOutputEvent) => void,
abortSignal: AbortSignal,
shouldUseNodePty: boolean,
shellExecutionConfig: ShellExecutionConfig,
): Promise<ShellExecutionHandle> {
// MSYS2 bash is incompatible with Windows ConPTY (causes crashes)
// Fallback to child_process in MSYS2 environments
if (shouldUseNodePty && !isRunningInMSYS2()) {
const ptyInfo = await getPty();
if (ptyInfo) {
try {
return this.executeWithPty(
commandToExecute,
cwd,
onOutputEvent,
abortSignal,
shellExecutionConfig,
ptyInfo,
);
} catch (_e) {
// Fallback to child_process
}
}
}
return this.childProcessFallback(
commandToExecute,
cwd,
onOutputEvent,
abortSignal,
);
}
private static childProcessFallback(
commandToExecute: string,
cwd: string,
onOutputEvent: (event: ShellOutputEvent) => void,
abortSignal: AbortSignal,
): ShellExecutionHandle {
try {
const isWindows = os.platform() === 'win32';
const { executable, argsPrefix, shell } = getShellConfiguration();
commandToExecute = applyPowerShellUtf8Prefix(commandToExecute, shell);
const shellArgs = [...argsPrefix, commandToExecute];
// Note: CodeQL flags this as js/shell-command-injection-from-environment.
// This is intentional - CLI tool executes user-provided shell commands.
//
// windowsVerbatimArguments must only be true for cmd.exe: it skips
// Node's MSVC CRT escaping, which cmd.exe doesn't understand. For
// PowerShell (.NET), we need the default escaping so that args
// round-trip correctly through CommandLineToArgvW.
const child = cpSpawn(executable, shellArgs, {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
windowsVerbatimArguments: isWindows && shell === 'cmd',
detached: !isWindows,
windowsHide: isWindows,
env: {
...normalizePathEnvForWindows(process.env),
QWEN_CODE: '1',
TERM: 'xterm-256color',
PAGER: 'cat',
},
});
const result = new Promise<ShellExecutionResult>((resolve) => {
let stdoutDecoder: TextDecoder | null = null;
let stderrDecoder: TextDecoder | null = null;
let stdout = '';
let stderr = '';
const outputChunks: Buffer[] = [];
let error: Error | null = null;
let exited = false;
let isStreamingRawContent = true;
const MAX_SNIFF_SIZE = 4096;
let sniffedBytes = 0;
const handleOutput = (data: Buffer, stream: 'stdout' | 'stderr') => {
if (!stdoutDecoder || !stderrDecoder) {
const encoding = getCachedEncodingForBuffer(data);
try {
stdoutDecoder = new TextDecoder(encoding);
stderrDecoder = new TextDecoder(encoding);
} catch {
stdoutDecoder = new TextDecoder('utf-8');
stderrDecoder = new TextDecoder('utf-8');
}
}
outputChunks.push(data);
if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
const sniffBuffer = Buffer.concat(outputChunks.slice(0, 20));
sniffedBytes = sniffBuffer.length;
if (isBinary(sniffBuffer)) {
isStreamingRawContent = false;
}
}
if (isStreamingRawContent) {
const decoder = stream === 'stdout' ? stdoutDecoder : stderrDecoder;
const decodedChunk = decoder.decode(data, { stream: true });
if (stream === 'stdout') {
stdout += decodedChunk;
} else {
stderr += decodedChunk;
}
}
};
const handleExit = (
code: number | null,
signal: NodeJS.Signals | null,
) => {
const { finalBuffer } = cleanup();
// Ensure we don't add an extra newline if stdout already ends with one.
const separator = stdout.endsWith('\n') ? '' : '\n';
const combinedOutput =
stdout + (stderr ? (stdout ? separator : '') + stderr : '');
const finalStrippedOutput = stripAnsi(combinedOutput).trim();
if (isStreamingRawContent) {
if (finalStrippedOutput) {
onOutputEvent({ type: 'data', chunk: finalStrippedOutput });
}
} else {
onOutputEvent({ type: 'binary_detected' });
}
resolve({
rawOutput: finalBuffer,
output: finalStrippedOutput,
exitCode: code,
signal: signal ? os.constants.signals[signal] : null,
error,
aborted: abortSignal.aborted,
pid: undefined,
executionMethod: 'child_process',
});
};
child.stdout.on('data', (data) => handleOutput(data, 'stdout'));
child.stderr.on('data', (data) => handleOutput(data, 'stderr'));
child.on('error', (err) => {
error = err;
handleExit(1, null);
});
const abortHandler = async () => {
if (child.pid && !exited) {
if (isWindows) {
cpSpawn('taskkill', ['/pid', child.pid.toString(), '/f', '/t']);
} else {
try {
process.kill(-child.pid, 'SIGTERM');
await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
if (!exited) {
process.kill(-child.pid, 'SIGKILL');
}
} catch (_e) {
if (!exited) child.kill('SIGKILL');
}
}
}
};
abortSignal.addEventListener('abort', abortHandler, { once: true });
if (child.pid) {
this.activeChildProcesses.add(child.pid);
}
child.on('exit', (code, signal) => {
if (child.pid) {
this.activeChildProcesses.delete(child.pid);
}
handleExit(code, signal);
});
function cleanup() {
exited = true;
abortSignal.removeEventListener('abort', abortHandler);
if (stdoutDecoder) {
const remaining = stdoutDecoder.decode();
if (remaining) {
stdout += remaining;
}
}
if (stderrDecoder) {
const remaining = stderrDecoder.decode();
if (remaining) {
stderr += remaining;
}
}
const finalBuffer = Buffer.concat(outputChunks);
return { stdout, stderr, finalBuffer };
}
});
return { pid: child.pid, result };
} catch (e) {
const error = e as Error;
return {
pid: undefined,
result: Promise.resolve({
error,
rawOutput: Buffer.from(''),
output: '',
exitCode: 1,
signal: null,
aborted: false,
pid: undefined,
executionMethod: 'none',
}),
};
}
}
private static executeWithPty(
commandToExecute: string,
cwd: string,
onOutputEvent: (event: ShellOutputEvent) => void,
abortSignal: AbortSignal,
shellExecutionConfig: ShellExecutionConfig,
ptyInfo: PtyImplementation,
): ShellExecutionHandle {
if (!ptyInfo) {
// This should not happen, but as a safeguard...
throw new Error('PTY implementation not found');
}
try {
const cols = shellExecutionConfig.terminalWidth ?? 80;
const rows = shellExecutionConfig.terminalHeight ?? 30;
const { executable, argsPrefix, shell } = getShellConfiguration();
commandToExecute = applyPowerShellUtf8Prefix(commandToExecute, shell);
// On Windows with cmd.exe, pass args as a single string instead of
// an array. node-pty's argsToCommandLine re-quotes array elements
// that contain spaces, which mangles user-provided quoted arguments
// for cmd.exe (e.g., `type "hello world"` becomes
// `"type \"hello world\""`).
//
// For PowerShell, keep the array form: argsToCommandLine escapes for
// CommandLineToArgvW round-tripping, which .NET correctly parses.
// The string form breaks quoted paths ending in \ (e.g., "C:\Temp\")
// because CommandLineToArgvW treats \" as an escaped quote.
const args: string[] | string =
os.platform() === 'win32' && shell === 'cmd'
? [...argsPrefix, commandToExecute].join(' ')
: [...argsPrefix, commandToExecute];
const ptyProcess = ptyInfo.module.spawn(executable, args, {
cwd,
name: 'xterm',
cols,
rows,
env: {
...normalizePathEnvForWindows(process.env),
QWEN_CODE: '1',
TERM: 'xterm-256color',
PAGER: shellExecutionConfig.pager ?? 'cat',
GIT_PAGER: shellExecutionConfig.pager ?? 'cat',
},
handleFlowControl: true,
});
const result = new Promise<ShellExecutionResult>((resolve) => {
const headlessTerminal = new Terminal({
allowProposedApi: true,
cols,
rows,
});
headlessTerminal.scrollToTop();
this.activePtys.set(ptyProcess.pid, { ptyProcess, headlessTerminal });
let processingChain = Promise.resolve();
let decoder: TextDecoder | null = null;
let output: string | AnsiOutput | null = null;
const outputChunks: Buffer[] = [];
const error: Error | null = null;
let exited = false;
let isStreamingRawContent = true;
const MAX_SNIFF_SIZE = 4096;
let sniffedBytes = 0;
let totalBytesReceived = 0;
let isWriting = false;
let hasStartedOutput = false;
let renderTimeout: NodeJS.Timeout | null = null;
const RENDER_THROTTLE_MS = 100;
const renderFn = () => {
if (!isStreamingRawContent) {
return;
}
if (!shellExecutionConfig.disableDynamicLineTrimming) {
if (!hasStartedOutput) {
const bufferText = getFullBufferText(headlessTerminal);
if (bufferText.trim().length === 0) {
return;
}
hasStartedOutput = true;
}
}
let newOutput: AnsiOutput;
if (shellExecutionConfig.showColor) {
newOutput = serializeTerminalToObject(headlessTerminal);
} else {
const buffer = headlessTerminal.buffer.active;
const lines: AnsiOutput = [];
for (let y = 0; y < headlessTerminal.rows; y++) {
const line = buffer.getLine(buffer.viewportY + y);
const lineContent = line ? line.translateToString(true) : '';
lines.push([
{
text: lineContent,
bold: false,
italic: false,
underline: false,
dim: false,
inverse: false,
fg: '',
bg: '',
},
]);
}
newOutput = lines;
}
let lastNonEmptyLine = -1;
for (let i = newOutput.length - 1; i >= 0; i--) {
const line = newOutput[i];
if (
line
.map((segment) => segment.text)
.join('')
.trim().length > 0
) {
lastNonEmptyLine = i;
break;
}
}
const trimmedOutput = newOutput.slice(0, lastNonEmptyLine + 1);
const finalOutput = shellExecutionConfig.disableDynamicLineTrimming
? newOutput
: trimmedOutput;
// Using stringify for a quick deep comparison.
if (JSON.stringify(output) !== JSON.stringify(finalOutput)) {
output = finalOutput;
onOutputEvent({
type: 'data',
chunk: finalOutput,
});
}
};
// Throttle: render immediately on first call, then at most
// once per RENDER_THROTTLE_MS during continuous output.
// A trailing render is scheduled to ensure the final state
// is always displayed.
let pendingTrailingRender = false;
const render = (finalRender = false) => {
if (finalRender) {
if (renderTimeout) {
clearTimeout(renderTimeout);
renderTimeout = null;
}
renderFn();
return;
}
if (!renderTimeout) {
// No active throttle — render now and start throttle window
renderFn();
renderTimeout = setTimeout(() => {
renderTimeout = null;
if (pendingTrailingRender) {
pendingTrailingRender = false;
render();
}
}, RENDER_THROTTLE_MS);
} else {
// Throttled — mark that we need a trailing render
pendingTrailingRender = true;
}
};
headlessTerminal.onScroll(() => {
if (!isWriting) {
render();
}
});
const ensureDecoder = (data: Buffer) => {
if (decoder) {
return;
}
const encoding = getCachedEncodingForBuffer(data);
try {
decoder = new TextDecoder(encoding);
} catch {
decoder = new TextDecoder('utf-8');
}
};
const handleOutput = (data: Buffer) => {
// Capture raw output immediately. Rendering the headless terminal is
// slower than appending a Buffer, and rapid PTY output can otherwise
// overrun the render queue before finalize() races on exit.
ensureDecoder(data);
outputChunks.push(data);
totalBytesReceived += data.length;
const bytesReceived = totalBytesReceived;
processingChain = processingChain.then(
() =>
new Promise<void>((resolve) => {
if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
const sniffBuffer = Buffer.concat(outputChunks.slice(0, 20));
sniffedBytes = sniffBuffer.length;
if (isBinary(sniffBuffer)) {
isStreamingRawContent = false;
onOutputEvent({ type: 'binary_detected' });
}
}
if (isStreamingRawContent) {
const decodedChunk = decoder!.decode(data, { stream: true });
isWriting = true;
headlessTerminal.write(decodedChunk, () => {
render();
isWriting = false;
resolve();
});
} else {
onOutputEvent({
type: 'binary_progress',
bytesReceived,
});
resolve();
}
}),
);
};
ptyProcess.onData((data: string) => {
const bufferData = Buffer.from(data, 'utf-8');
handleOutput(bufferData);
});
// Handle PTY errors - EIO is expected when the PTY process exits
// due to race conditions between the exit event and read operations.
// This is a normal behavior on macOS/Linux and should not crash the app.
// See: https://github.com/microsoft/node-pty/issues/178
ptyProcess.on('error', (err: NodeJS.ErrnoException) => {
if (isExpectedPtyReadExitError(err)) {
// EIO is expected when the PTY process exits - ignore it
return;
}
// Surface unexpected PTY errors to preserve existing crash behavior.
throw err;
});
ptyProcess.onExit(
({ exitCode, signal }: { exitCode: number; signal?: number }) => {
exited = true;
abortSignal.removeEventListener('abort', abortHandler);
this.activePtys.delete(ptyProcess.pid);
const finalize = async () => {
render(true);
const finalBuffer = Buffer.concat(outputChunks);
let fullOutput = '';
try {
if (isStreamingRawContent) {
// Re-decode the full buffer with proper encoding detection.
// The streaming decoder used the first-chunk heuristic which
// can misdetect when early output is ASCII-only but later
// output is in a different encoding (e.g. GBK).
const finalEncoding = getCachedEncodingForBuffer(finalBuffer);
const decodedOutput = new TextDecoder(finalEncoding).decode(
finalBuffer,
);
fullOutput = await replayTerminalOutput(
decodedOutput,
cols,
rows,
);
} else {
fullOutput = getFullBufferText(headlessTerminal);
}
} catch {
try {
fullOutput = getFullBufferText(headlessTerminal);
} catch {
// Ignore fallback rendering errors and resolve with empty text.
}
}
resolve({
rawOutput: finalBuffer,
output: fullOutput,
exitCode,
signal: signal ?? null,
error,
aborted: abortSignal.aborted,
pid: ptyProcess.pid,
executionMethod:
(ptyInfo?.name as 'node-pty' | 'lydell-node-pty') ??
'node-pty',
});
};
// Give any last onData callbacks a chance to run before finalizing.
// onExit can arrive slightly before late PTY data is processed.
const flushChain = () => processingChain.then(() => {});
const deadline = new Promise<void>((res) =>
setTimeout(res, SIGKILL_TIMEOUT_MS),
);
const drain = () =>
new Promise<void>((res) => setImmediate(res)).then(flushChain);
void Promise.race([
flushChain().then(drain).then(drain),
deadline,
]).then(() => {
void finalize();
});
},
);
const abortHandler = async () => {
if (ptyProcess.pid && !exited) {
if (os.platform() === 'win32') {
ptyProcess.kill();
} else {
try {
// Send SIGTERM first to allow graceful shutdown
process.kill(-ptyProcess.pid, 'SIGTERM');
await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
if (!exited) {
// Escalate to SIGKILL if still running
process.kill(-ptyProcess.pid, 'SIGKILL');
}
} catch (_e) {
// Fallback to killing just the process if the group kill fails
if (!exited) {
ptyProcess.kill();
}
}
}
}
};
abortSignal.addEventListener('abort', abortHandler, { once: true });
});
return { pid: ptyProcess.pid, result };
} catch (e) {
const error = e as Error;
if (error.message.includes('posix_spawnp failed')) {
onOutputEvent({
type: 'data',
chunk:
'[WARNING] PTY execution failed, falling back to child_process. This may be due to sandbox restrictions.\n',
});
throw e;
} else {
return {
pid: undefined,
result: Promise.resolve({
error,
rawOutput: Buffer.from(''),
output: '',
exitCode: 1,
signal: null,
aborted: false,
pid: undefined,
executionMethod: 'none',
}),
};
}
}
}
/**
* Writes a string to the pseudo-terminal (PTY) of a running process.
*
* @param pid The process ID of the target PTY.
* @param input The string to write to the terminal.
*/
static writeToPty(pid: number, input: string): void {
if (!this.isPtyActive(pid)) {
return;
}
const activePty = this.activePtys.get(pid);
if (activePty) {
activePty.ptyProcess.write(input);
}
}
static isPtyActive(pid: number): boolean {
try {
// process.kill with signal 0 is a way to check for the existence of a process.
// It doesn't actually send a signal.
return process.kill(pid, 0);
} catch (_) {
return false;
}
}
/**
* Resizes the pseudo-terminal (PTY) of a running process.
*
* @param pid The process ID of the target PTY.
* @param cols The new number of columns.
* @param rows The new number of rows.
*/
static resizePty(pid: number, cols: number, rows: number): void {
if (!this.isPtyActive(pid)) {
return;
}
const activePty = this.activePtys.get(pid);
if (activePty) {
try {
activePty.ptyProcess.resize(cols, rows);
activePty.headlessTerminal.resize(cols, rows);
} catch (e) {
// Ignore errors if the pty has already exited, which can happen
// due to a race condition between the exit event and this call.
// - ESRCH: No such process (process no longer exists)
// - EBADF: Bad file descriptor (PTY fd closed, e.g., "ioctl(2) failed, EBADF")
if (isExpectedPtyExitRaceError(e)) {
// ignore
} else {
throw e;
}