Repository navigation
Expand file tree
/
Copy pathexec.ts
More file actions
988 lines (907 loc) · 30.7 KB
/
Copy pathexec.ts
File metadata and controls
988 lines (907 loc) · 30.7 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
import { AsyncLocalStorage } from 'node:async_hooks';
import { constants } from 'node:fs';
import { access, stat } from 'node:fs/promises';
import path from 'node:path';
import { spawn, spawnSync, type ChildProcess, type StdioOptions } from 'node:child_process';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
import { createExecTraceContext, type ExecSettlementReason } from './exec-trace.ts';
import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value';
export type ExecResult = {
stdout: string;
stderr: string;
exitCode: number;
stdoutBuffer?: Buffer;
};
export type ExecOptions = {
cwd?: string;
env?: NodeJS.ProcessEnv;
allowFailure?: boolean;
binaryStdout?: boolean;
stdin?: string | Buffer;
timeoutMs?: number;
detached?: boolean;
signal?: AbortSignal;
/** Max stdout/stderr bytes for synchronous runs (default Node ~1MB). */
maxBuffer?: number;
/**
* How a deadline or a cancelled request stops the child. Without this it is SIGKILL at
* once. A child that has to undo something before it dies — the macOS helper releasing a
* mouse button it is holding — is sent `signal` first, and SIGKILL only once `graceMs`
* pass without it exiting.
*/
kill?: { readonly signal: NodeJS.Signals; readonly graceMs: number };
};
export type ExecStreamOptions = ExecOptions & {
/** Set false when chunk callbacks own output and only the exit code is needed. */
captureOutput?: boolean;
onStdoutChunk?: (chunk: string) => void;
onStderrChunk?: (chunk: string) => void;
onSpawn?: (child: ReturnType<typeof spawn>) => void;
};
export type ExecBackgroundResult = {
child: ReturnType<typeof spawn>;
wait: Promise<ExecResult>;
};
type ExecDetachedOptions = ExecOptions & {
stdio?: StdioOptions;
};
export type ExecDetachedExit = {
pid: number;
exitCode?: number;
signal?: NodeJS.Signals;
error?: string;
};
export type ExecDetachedProcess = {
pid: number;
exited: Promise<ExecDetachedExit>;
};
/**
* Background runs have no `timeoutMs`: the callers are long-lived sessions (the
* Android snapshot helper, the keep-hot xcodebuild runner, app-log capture), and
* a deadline field the spawn path never armed was one plumbing change away from
* killing them. A background deadline belongs to its caller, which cancels it with
* `signal`; a caller that kills the child directly still waits for the streams to
* drain, exactly as before.
*/
export type ExecBackgroundOptions = Omit<ExecOptions, 'timeoutMs'> & {
/**
* Capture stdout/stderr into the wait result when the child has piped stdio.
* Set false when the caller owns, ignores, or forwards the streams.
*/
captureOutput?: boolean;
stdio?: StdioOptions;
};
const BARE_COMMAND_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
const WINDOWS_PATH_EXTENSIONS = ['.com', '.exe', '.bat', '.cmd'];
export type CommandExecutorOverride = (
cmd: string,
args: readonly string[],
options: ExecOptions,
) => Promise<ExecResult> | undefined;
const commandExecutorOverrideScope = new AsyncLocalStorage<CommandExecutorOverride | undefined>();
export async function withCommandExecutorOverride<T>(
override: CommandExecutorOverride | undefined,
fn: () => Promise<T>,
): Promise<T> {
if (!override) return await fn();
return await commandExecutorOverrideScope.run(override, fn);
}
// Used by local executors to bypass the active override for intentional host command execution.
export async function withoutCommandExecutorOverride<T>(fn: () => Promise<T>): Promise<T> {
return await commandExecutorOverrideScope.run(undefined, fn);
}
type CommandHostScope = Readonly<{
host: HostEnvironment;
requestEnv: EnvMap | undefined;
}>;
const commandHostScope = new AsyncLocalStorage<CommandHostScope>();
/**
* Runs `fn` as the host that owns the commands it spawns. A command without its own `env` starts
* from `host.env`, then takes `requestEnv` on top, so neither the process's environment nor a
* concurrent request's values reach it. Outside a scope a command without `env` inherits the process's.
*/
export async function withCommandHost<T>(
scope: CommandHostScope,
fn: () => Promise<T>,
): Promise<T> {
// A nested scope of the same host that names no request env keeps the enclosing request's.
const enclosing = commandHostScope.getStore();
const requestEnv =
scope.requestEnv ?? (enclosing?.host === scope.host ? enclosing.requestEnv : undefined);
return await commandHostScope.run({ host: scope.host, requestEnv }, fn);
}
/**
* The host of the enclosing {@link withCommandHost} scope, for code that has no host of its own.
* Outside a scope there is no host to answer with, so it refuses rather than guess.
*/
export function commandHostEnvironment(): HostEnvironment {
const scope = commandHostScope.getStore();
if (!scope) {
throw new AppError('COMMAND_FAILED', 'No host environment is bound to this command.', {
reason: 'host_environment_unscoped',
});
}
return scope.host;
}
/** Effective toolchain selection; an explicitly empty request value selects `xcode-select`. */
export function commandDeveloperDir(): string | undefined {
const scope = commandHostScope.getStore();
if (scope?.requestEnv && Object.hasOwn(scope.requestEnv, 'DEVELOPER_DIR')) {
return scope.requestEnv.DEVELOPER_DIR || undefined;
}
return scope?.host.env.DEVELOPER_DIR || undefined;
}
function resolveSpawnEnv(env: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv | undefined {
const scope = commandHostScope.getStore();
if (!scope) return env;
return { ...(env ?? scope.host.env), ...scope.requestEnv };
}
export async function runCmd(
cmd: string,
args: readonly string[],
options: ExecOptions = {},
): Promise<ExecResult> {
const overrideResult = commandExecutorOverrideScope.getStore()?.(cmd, args, options);
if (overrideResult) return coerceExecResult(await overrideResult);
return await runSpawnedCommand(cmd, args, options);
}
export async function runCmdStreaming(
cmd: string,
args: readonly string[],
options: ExecStreamOptions = {},
): Promise<ExecResult> {
const overrideResult = commandExecutorOverrideScope.getStore()?.(cmd, args, options);
if (overrideResult) return coerceExecResult(await overrideResult);
return await runSpawnedCommand(cmd, args, options);
}
/**
* Normalize an exec result produced outside this module. Tool providers,
* executor overrides, and SDK-supplied adb executors are plain callbacks whose
* results cross an unchecked boundary; coercing once here lets downstream code
* trust the ExecResult types instead of re-wrapping fields defensively at every
* use. A non-number exitCode coerces to 1 — the same failure branch such a
* result already landed in at every `exitCode !== 0` guard.
*/
export function coerceExecResult<T extends Pick<ExecResult, 'stdout' | 'stderr' | 'exitCode'>>(
result: T,
): T {
const stdout = typeof result.stdout === 'string' ? result.stdout : String(result.stdout ?? '');
const stderr = typeof result.stderr === 'string' ? result.stderr : String(result.stderr ?? '');
const exitCode = typeof result.exitCode === 'number' ? result.exitCode : 1;
if (stdout === result.stdout && stderr === result.stderr && exitCode === result.exitCode) {
return result;
}
return { ...result, stdout, stderr, exitCode };
}
function runSpawnedCommand(
cmd: string,
args: readonly string[],
options: ExecStreamOptions = {},
): Promise<ExecResult> {
const executable = normalizeExecutableCommand(cmd);
const execTrace = createExecTraceContext(
cmd,
normalizeTimeoutMs(options.timeoutMs),
commandHostScope.getStore()?.host.env,
);
return new Promise((resolve, reject) => {
const child = spawn(executable, args, {
cwd: options.cwd,
env: resolveSpawnEnv(options.env),
stdio: ['pipe', 'pipe', 'pipe'],
detached: options.detached,
windowsHide: true,
shell: false,
});
child.once('spawn', () => execTrace.emit('spawn', { pid: child.pid }));
options.onSpawn?.(child);
let stdout = '';
const stdoutChunks: Buffer[] | undefined =
options.binaryStdout && options.captureOutput !== false ? [] : undefined;
let stderr = '';
let didTimeout = false;
const timeoutMs = normalizeTimeoutMs(options.timeoutMs);
let timeoutHandle: NodeJS.Timeout | null = null;
let settled = false;
function finish(reason: ExecSettlementReason): boolean {
if (settled) return false;
settled = true;
if (timeoutHandle) clearTimeout(timeoutHandle);
abort.dispose();
destroyCommandStreams(child);
execTrace.emit('settled', { reason });
return true;
}
function fail(error: AppError, reason: ExecSettlementReason): void {
if (finish(reason)) reject(error);
}
function settle(code: number | null): void {
const finalReason = abort.didAbort
? 'abort'
: didTimeout
? 'timeout'
: (code ?? 1) !== 0 && !options.allowFailure
? 'exit_failure'
: 'success';
if (!finish(finalReason)) return;
const finalExitCode = code ?? 1;
if (!abort.didAbort && didTimeout && timeoutMs) {
reject(createTimeoutError(executable, cmd, args, timeoutMs, finalExitCode, stdout, stderr));
return;
}
const failure = commandCloseFailure(
abort,
executable,
cmd,
args,
finalExitCode,
options.allowFailure,
stdout,
stderr,
);
if (failure) {
reject(failure);
return;
}
resolve({
stdout,
stderr,
exitCode: finalExitCode,
stdoutBuffer: stdoutChunks ? Buffer.concat(stdoutChunks) : undefined,
});
}
// A deadline that fires after the child exited on its own still has to settle: the
// group kill that would have ended the pipe holder can no longer run through a child
// Node already reaped.
const settlement = createCommandKillSettlement({
killProcessTree: () => killProcessTree(child, options),
settle,
});
const abort = watchCommandAbort(options, () => {
execTrace.emit('abort');
settlement.requestKill();
});
timeoutHandle = timeoutMs
? setTimeout(() => {
execTrace.emit('deadline');
didTimeout = true;
settlement.requestKill();
}, timeoutMs)
: null;
if (!options.binaryStdout) child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
void writeChildStdin(child, options.stdin).catch((error: unknown) => {
if (abort.didAbort || didTimeout) return;
if (isEpipeError(error)) return;
fail(createStdinError(executable, cmd, args, error), 'stdin_error');
killProcessTree(child, options);
});
child.stdout.on('data', (chunk) => {
if (options.binaryStdout) {
stdoutChunks?.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return;
}
const text = String(chunk);
if (options.captureOutput !== false) stdout += text;
options.onStdoutChunk?.(text);
});
child.stderr.on('data', (chunk) => {
const text = String(chunk);
if (options.captureOutput !== false) stderr += text;
options.onStderrChunk?.(text);
});
child.on('error', (err) => {
execTrace.emit('error');
fail(spawnRejectionError(abort, executable, cmd, args, err), 'spawn_error');
});
child.once('exit', (code, signal) => {
execTrace.emit('exit', { exitCode: code, signal });
settlement.recordExit(code);
});
child.once('close', (code, signal) => {
execTrace.emit('close', { exitCode: code, signal });
settle(code);
});
});
}
export async function whichCmd(cmd: string, env: EnvMap): Promise<boolean> {
const candidate = normalizeExecutableLookup(cmd);
if (!candidate) return false;
if (path.isAbsolute(candidate)) {
return isExecutablePath(candidate);
}
const pathValue = readPathVariable(env, 'PATH');
if (!pathValue) return false;
const pathExtensions = resolvePathExtensions(env);
for (const directory of pathValue.split(path.delimiter)) {
const trimmedDirectory = directory.trim();
if (!trimmedDirectory) continue;
for (const entry of resolveExecutableCandidates(candidate, pathExtensions)) {
if (await isExecutablePath(path.join(trimmedDirectory, entry))) {
return true;
}
}
}
return false;
}
export async function resolveExecutableOverridePath(
rawPath: string | undefined,
envName: string,
): Promise<string | undefined> {
return await resolveOverridePath(rawPath, envName, 'executable', isExecutablePath);
}
export async function resolveFileOverridePath(
rawPath: string | undefined,
envName: string,
): Promise<string | undefined> {
return await resolveOverridePath(rawPath, envName, 'file', isFilePath);
}
async function resolveOverridePath(
rawPath: string | undefined,
envName: string,
kind: 'executable' | 'file',
isUsable: (candidate: string) => Promise<boolean>,
): Promise<string | undefined> {
const candidate = normalizeOverridePath(rawPath, envName, kind);
if (!candidate) return undefined;
if (!(await isUsable(candidate))) {
throw new AppError(
'TOOL_MISSING',
`${envName} points to a missing or non-${kind} ${kind === 'file' ? 'path' : 'file'}: ${candidate}`,
{ envName, path: candidate },
);
}
return candidate;
}
// fallow-ignore-next-line complexity
export function runCmdSync(
cmd: string,
args: readonly string[],
options: ExecOptions = {},
): ExecResult {
const executable = normalizeExecutableCommand(cmd);
const result = spawnSync(executable, args, {
cwd: options.cwd,
env: resolveSpawnEnv(options.env),
stdio: ['pipe', 'pipe', 'pipe'],
encoding: options.binaryStdout ? undefined : 'utf8',
input: options.stdin,
timeout: normalizeTimeoutMs(options.timeoutMs),
windowsHide: true,
shell: false,
...(options.maxBuffer !== undefined ? { maxBuffer: options.maxBuffer } : {}),
});
if (result.error) {
const code = (result.error as NodeJS.ErrnoException).code;
if (code === 'ETIMEDOUT') {
throw new AppError(
'COMMAND_FAILED',
`${executable} timed out after ${normalizeTimeoutMs(options.timeoutMs)}ms`,
{
cmd,
args,
timeoutMs: normalizeTimeoutMs(options.timeoutMs),
},
result.error,
);
}
if (code === 'ENOENT') {
throw createMissingToolError(executable, cmd, result.error);
}
throw createCommandFailedError(executable, cmd, args, result.error);
}
const stdoutBuffer = options.binaryStdout
? Buffer.isBuffer(result.stdout)
? result.stdout
: Buffer.from(result.stdout ?? '')
: undefined;
const stdout = options.binaryStdout
? ''
: typeof result.stdout === 'string'
? result.stdout
: (result.stdout ?? '').toString();
const stderr =
typeof result.stderr === 'string' ? result.stderr : (result.stderr ?? '').toString();
const exitCode = result.status ?? 1;
if (exitCode !== 0 && !options.allowFailure) {
throw createExitError(executable, cmd, args, exitCode, stdout, stderr);
}
return { stdout, stderr, exitCode, stdoutBuffer };
}
export function runCmdDetached(
cmd: string,
args: readonly string[],
options: ExecDetachedOptions = {},
): number {
return runCmdDetachedMonitored(cmd, args, options).pid;
}
export function runCmdDetachedMonitored(
cmd: string,
args: readonly string[],
options: ExecDetachedOptions = {},
): ExecDetachedProcess {
const executable = normalizeExecutableCommand(cmd);
const child = spawn(executable, args, {
cwd: options.cwd,
env: resolveSpawnEnv(options.env),
stdio: options.stdio ?? 'ignore',
detached: true,
windowsHide: true,
shell: false,
});
const pid = child.pid ?? 0;
const exited = new Promise<ExecDetachedExit>((resolve) => {
child.once('error', (err) => {
resolve({ pid, error: err.message });
});
child.once('exit', (code, signal) => {
resolve({
pid,
...(typeof code === 'number' ? { exitCode: code } : {}),
...(signal ? { signal } : {}),
});
});
});
child.unref();
return { pid, exited };
}
export function runCmdBackground(
cmd: string,
args: readonly string[],
options: ExecBackgroundOptions = {},
): ExecBackgroundResult {
const executable = normalizeExecutableCommand(cmd);
const execTrace = createExecTraceContext(cmd, undefined, commandHostScope.getStore()?.host.env);
const child = spawn(executable, args, {
cwd: options.cwd,
env: resolveSpawnEnv(options.env),
stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'],
detached: options.detached,
windowsHide: true,
shell: false,
});
child.once('spawn', () => execTrace.emit('spawn', { pid: child.pid }));
let stdout = '';
let stderr = '';
const captureOutput = options.captureOutput ?? true;
if (captureOutput) {
child.stdout?.setEncoding('utf8');
child.stderr?.setEncoding('utf8');
child.stdout?.on('data', (chunk) => {
stdout += chunk;
});
child.stderr?.on('data', (chunk) => {
stderr += chunk;
});
}
const wait = new Promise<ExecResult>((resolve, reject) => {
let settled = false;
function finish(event: 'error' | 'exit'): boolean {
if (settled) return false;
settled = true;
abort.dispose();
destroyCommandStreams(child);
execTrace.emit('settled', {
reason:
event === 'error'
? 'spawn_error'
: abort.didAbort
? 'abort'
: (child.exitCode ?? 1) !== 0 && !options.allowFailure
? 'exit_failure'
: 'success',
});
return true;
}
function settle(code: number | null): void {
if (!finish('exit')) return;
const finalExitCode = code ?? 1;
const failure = commandCloseFailure(
abort,
executable,
cmd,
args,
finalExitCode,
options.allowFailure,
stdout,
stderr,
);
if (failure) {
reject(failure);
return;
}
resolve({ stdout, stderr, exitCode: finalExitCode });
}
const settlement = createCommandKillSettlement({
killProcessTree: () => killProcessTree(child, options),
settle,
});
const abort = watchCommandAbort(options, () => {
execTrace.emit('abort');
settlement.requestKill();
});
child.on('error', (err) => {
execTrace.emit('error');
if (finish('error')) reject(spawnRejectionError(abort, executable, cmd, args, err));
});
child.once('exit', (code, signal) => {
execTrace.emit('exit', { exitCode: code, signal });
settlement.recordExit(code);
});
child.once('close', (code, signal) => {
execTrace.emit('close', { exitCode: code, signal });
settle(code);
});
});
return { child, wait };
}
function normalizeExecutableCommand(cmd: string): string {
const candidate = normalizeExecutableLookup(cmd);
if (!candidate) {
throw new AppError('INVALID_ARGS', `Invalid executable command: ${JSON.stringify(cmd)}`, {
cmd,
hint: 'Use a bare command name from PATH or an absolute executable path.',
});
}
return candidate;
}
function createSpawnError(
executable: string,
cmd: string,
args: readonly string[],
err: Error,
): AppError {
const code = (err as NodeJS.ErrnoException).code;
if (code === 'ENOENT') {
return createMissingToolError(executable, cmd, err);
}
return createCommandFailedError(executable, cmd, args, err);
}
function createMissingToolError(executable: string, cmd: string, cause: Error): AppError {
return new AppError('TOOL_MISSING', `${executable} not found in PATH`, { cmd }, cause);
}
function createCommandFailedError(
executable: string,
cmd: string,
args: readonly string[],
cause: Error,
): AppError {
return new AppError('COMMAND_FAILED', `Failed to run ${executable}`, { cmd, args }, cause);
}
function createStdinError(
executable: string,
cmd: string,
args: readonly string[],
cause: unknown,
): AppError {
return new AppError(
'COMMAND_FAILED',
`Failed to write stdin for ${executable}`,
{ cmd, args },
cause instanceof Error ? cause : undefined,
);
}
function createTimeoutError(
executable: string,
cmd: string,
args: readonly string[],
timeoutMs: number,
exitCode: number,
stdout: string,
stderr: string,
): AppError {
// exec-guard-allow: deliberately no processExitError — "timed out after Nms"
// beats whatever partial stderr the killed process left behind.
return new AppError('COMMAND_FAILED', `${executable} timed out after ${timeoutMs}ms`, {
cmd,
args,
stdout,
stderr,
exitCode,
timeoutMs,
});
}
/**
* True only for the COMMAND_FAILED error this module raises when it kills a command at
* its own `timeoutMs`. Callers classify with this rather than matching the message text,
* so a command whose own output says "timed out" is not mistaken for one exec killed.
*/
export function isCommandTimeoutError(error: unknown): error is AppError {
return (
error instanceof AppError &&
error.code === 'COMMAND_FAILED' &&
typeof error.details?.timeoutMs === 'number'
);
}
function createExitError(
executable: string,
cmd: string,
args: readonly string[],
exitCode: number,
stdout: string,
stderr: string,
): AppError {
return new AppError(
'COMMAND_FAILED',
`${executable} exited with code ${exitCode}`,
execFailureDetails({ stdout, stderr, exitCode }, { cmd, args }),
);
}
// xcrun itself emits this line, including when the caller supplies no command metadata.
const XCRUN_TOOL_NOT_FOUND_STDERR = /xcrun: error: unable to find utility "([^"]+)"/;
function xcrunToolNotFoundDetails(stderr: string): Record<string, unknown> {
const tool = XCRUN_TOOL_NOT_FOUND_STDERR.exec(stderr)?.[1];
if (!tool) return {};
const developerDir = commandDeveloperDir();
const source = developerDir
? `DEVELOPER_DIR ${developerDir}`
: 'the developer dir selected by xcode-select (see xcode-select -p)';
return {
reason: 'xcrun-tool-not-found',
developerDir: developerDir ?? null,
hint: `xcrun could not find ${tool} in ${source}. Export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer (or your Xcode's path) before running agent-device, or run sudo xcode-select -s /Applications/Xcode.app.`,
};
}
/**
* Raises COMMAND_FAILED for a non-zero result, preserving stderr for normalizeError.
* Passes successful results through unchanged and evaluates functional `extra` only on failure.
*/
export function requireExecSuccess<
R extends Pick<ExecResult, 'stdout' | 'stderr'> & Readonly<{ exitCode: number | null }>,
>(
result: R,
message: string,
extra?: Record<string, unknown> | ((result: R) => Record<string, unknown>),
): R {
if (result.exitCode === 0) return result;
throw new AppError(
'COMMAND_FAILED',
message,
execFailureDetails(result, typeof extra === 'function' ? extra(result) : extra),
);
}
/**
* Exit-failure details for normalizeError, including null exit codes from signalled processes.
*/
export function execFailureDetails(
result: Pick<ExecResult, 'stdout' | 'stderr'> & Readonly<{ exitCode: number | null }>,
extra?: Record<string, unknown>,
): Record<string, unknown> {
return {
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
processExitError: true,
...extra,
// Last: a missing tool makes a caller's hint about the device or app moot.
...xcrunToolNotFoundDetails(result.stderr),
};
}
type CommandAbort = { readonly didAbort: boolean };
function spawnRejectionError(
abort: CommandAbort,
executable: string,
cmd: string,
args: readonly string[],
err: Error,
): AppError {
return abort.didAbort
? createRequestCanceledError({ cmd, args, executable })
: createSpawnError(executable, cmd, args, err);
}
function commandCloseFailure(
abort: CommandAbort,
executable: string,
cmd: string,
args: readonly string[],
exitCode: number,
allowFailure: boolean | undefined,
stdout: string,
stderr: string,
): AppError | null {
if (abort.didAbort) return createRequestCanceledError({ cmd, args, executable });
if (exitCode !== 0 && !allowFailure) {
return createExitError(executable, cmd, args, exitCode, stdout, stderr);
}
return null;
}
function normalizeOverridePath(
rawPath: string | undefined,
envName: string,
kind: 'executable' | 'file',
): string | undefined {
const candidate = rawPath?.trim();
if (!candidate) return undefined;
if (!path.isAbsolute(candidate) || candidate.includes('\0')) {
throw new AppError(
'INVALID_ARGS',
`${envName} must be an absolute ${kind} path, not ${JSON.stringify(rawPath)}`,
{ envName, path: rawPath },
);
}
return candidate;
}
function normalizeExecutableLookup(cmd: string): string | null {
const candidate = cmd.trim();
if (!candidate || candidate.includes('\0')) return null;
if (path.isAbsolute(candidate)) return candidate;
if (candidate.includes('/') || candidate.includes('\\')) {
return null;
}
return BARE_COMMAND_RE.test(candidate) ? candidate : null;
}
/** Windows names an environment variable in any case; a captured copy no longer folds it. */
function readPathVariable(env: EnvMap, name: 'PATH' | 'PATHEXT'): string | undefined {
if (process.platform !== 'win32') return env[name];
const key = Object.keys(env).find((candidate) => candidate.toUpperCase() === name);
return key === undefined ? undefined : env[key];
}
function resolvePathExtensions(env: EnvMap): string[] {
if (process.platform !== 'win32') return [''];
const rawPathExt = readPathVariable(env, 'PATHEXT');
if (!rawPathExt) return WINDOWS_PATH_EXTENSIONS;
const extensions = rawPathExt
.split(';')
.map((value) => value.trim().toLowerCase())
.filter((value) => value.length > 0);
return extensions.length > 0 ? extensions : WINDOWS_PATH_EXTENSIONS;
}
function resolveExecutableCandidates(cmd: string, pathExtensions: string[]): string[] {
if (process.platform !== 'win32') return [cmd];
const lowered = cmd.toLowerCase();
if (pathExtensions.some((extension) => lowered.endsWith(extension))) {
return [cmd];
}
return pathExtensions.map((extension) => `${cmd}${extension}`);
}
export async function isExecutablePath(filePath: string): Promise<boolean> {
try {
if (!(await isFilePath(filePath))) return false;
await access(filePath, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
return true;
} catch {
return false;
}
}
async function isFilePath(filePath: string): Promise<boolean> {
try {
const fileStat = await stat(filePath);
return fileStat.isFile();
} catch {
return false;
}
}
function normalizeTimeoutMs(value: number | undefined): number | undefined {
if (!Number.isFinite(value)) return undefined;
const timeout = Math.floor(value as number);
if (timeout <= 0) return undefined;
return timeout;
}
/**
* A killed command settles when its direct child exits: descendants can keep inherited pipes
* open indefinitely. Both kill/exit orderings must settle once without waiting for `close`.
*/
type CommandKillSettlement = {
/** Signals the command's process tree, then settles the command if its child is gone. */
readonly requestKill: () => void;
/** Records the child's exit, then settles the command if a kill was already requested. */
readonly recordExit: (code: number | null) => void;
};
function createCommandKillSettlement(input: {
readonly killProcessTree: () => void;
readonly settle: (exitCode: number | null) => void;
}): CommandKillSettlement {
let killRequested = false;
let exited = false;
let exitCode: number | null = null;
const settleIfKilledAndGone = (): void => {
if (killRequested && exited) input.settle(exitCode);
};
return {
requestKill: () => {
killRequested = true;
input.killProcessTree();
settleIfKilledAndGone();
},
recordExit: (code) => {
exited = true;
exitCode = code ?? 1;
settleIfKilledAndGone();
},
};
}
function watchCommandAbort(
options: Pick<ExecOptions, 'detached' | 'signal'>,
onKill: () => void,
): { readonly didAbort: boolean; dispose: () => void } {
let didAbort = false;
const onAbort = () => {
didAbort = true;
onKill();
};
if (options.signal?.aborted) {
onAbort();
} else {
options.signal?.addEventListener('abort', onAbort, { once: true });
}
return {
get didAbort() {
return didAbort;
},
dispose: () => {
options.signal?.removeEventListener('abort', onAbort);
},
};
}
/**
* Best-effort process-group signalling, shared by host-kit callers. This lives below
* host-process.ts to avoid an import cycle. Only positive integer pids are accepted:
* zero targets this process's group, and negative values can target unrelated processes.
*/
export function signalProcessGroupBestEffort(pid: number, signal: NodeJS.Signals): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(-pid, signal);
return true;
} catch {
return false;
}
}
// Surviving descendants keep a detached process group reserved after its direct child exits.
function killProcessTree(
child: ChildProcess,
options: Pick<ExecOptions, 'detached' | 'kill'>,
): void {
if (!options.kill) {
signalProcessTree(child, options.detached, 'SIGKILL');
return;
}
// Escalation bounds graceful cleanup; the unref timer cannot keep a worker alive.
signalProcessTree(child, options.detached, options.kill.signal);
const escalation = setTimeout(
() => signalProcessTree(child, options.detached, 'SIGKILL'),
options.kill.graceMs,
);
escalation.unref();
child.once('exit', () => clearTimeout(escalation));
}
function signalProcessTree(
child: ChildProcess,
detached: boolean | undefined,
signal: NodeJS.Signals,
): void {
if (detached && child.pid && process.platform !== 'win32') {
signalProcessGroupBestEffort(child.pid, signal);
return;
}
// A reaped, non-detached child can have its pid reassigned to an unrelated process.
if (child.exitCode !== null || child.signalCode !== null) return;
child.kill(signal);
}
/**
* A kill that cannot reach an inherited-pipe holder must at least stop this process
* from holding the other end of those pipes open after it has settled.
*/
function destroyCommandStreams(child: ChildProcess): void {
child.stdin?.destroy();
child.stdout?.destroy();
child.stderr?.destroy();
}
async function writeChildStdin(
child: ChildProcess,
stdin: string | Buffer | undefined,
): Promise<void> {
if (!child.stdin) return;
if (stdin === undefined) {
child.stdin?.end();
return;
}
await pipeline(Readable.from([stdin]), child.stdin);
}
function isEpipeError(error: unknown): boolean {
return (
error instanceof Error && 'code' in error && (error as NodeJS.ErrnoException).code === 'EPIPE'
);
}