Repository navigation
Expand file tree
/
Copy pathexec.ts
More file actions
1041 lines (959 loc) · 33 KB
/
Copy pathexec.ts
File metadata and controls
1041 lines (959 loc) · 33 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
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 { emitDiagnostic, getDiagnosticsMeta, updateDiagnosticsScope } from './diagnostics.ts';
import { parseBooleanLiteral } 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 & {
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'];
const EXEC_DIAGNOSTIC_ARG_LIMIT = 6;
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);
}
const requestCommandEnvScope = new AsyncLocalStorage<NodeJS.ProcessEnv>();
/**
* Overlays `env` on every command spawned inside `fn`. The daemon outlives the shell that started
* it, so a variable a client exports (such as `DEVELOPER_DIR`, which picks the Xcode `xcrun`
* resolves) reaches its commands only through this per-request scope.
*/
export async function withRequestCommandEnv<T>(
env: NodeJS.ProcessEnv | undefined,
fn: () => Promise<T>,
): Promise<T> {
if (!env) return await fn();
return await requestCommandEnvScope.run(env, fn);
}
/**
* The `DEVELOPER_DIR` a command spawned here would run with: the request's, else this process's.
* A request that sets it, even to empty, overrides this process's value just as `resolveSpawnEnv`
* does. Undefined means `xcrun` falls back to `xcode-select`.
*/
export function commandDeveloperDir(): string | undefined {
const requestEnv = requestCommandEnvScope.getStore();
if (requestEnv && Object.hasOwn(requestEnv, 'DEVELOPER_DIR')) {
return requestEnv.DEVELOPER_DIR || undefined;
}
return process.env.DEVELOPER_DIR || undefined;
}
function resolveSpawnEnv(env: NodeJS.ProcessEnv | undefined): NodeJS.ProcessEnv | undefined {
const requestEnv = requestCommandEnvScope.getStore();
if (!requestEnv) return env;
return { ...(env ?? process.env), ...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();
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,
});
options.onSpawn?.(child);
let stdout = '';
const stdoutChunks: Buffer[] | undefined = options.binaryStdout ? [] : undefined;
let stderr = '';
let didTimeout = false;
const timeoutMs = normalizeTimeoutMs(options.timeoutMs);
let timeoutHandle: NodeJS.Timeout | null = null;
let settled = false;
function finish(): boolean {
if (settled) return false;
settled = true;
if (timeoutHandle) clearTimeout(timeoutHandle);
abort.dispose();
destroyCommandStreams(child);
execTrace.emitForegroundCompletion(cmd, args);
return true;
}
function fail(error: AppError): void {
if (finish()) reject(error);
}
function settle(code: number | null): void {
if (!finish()) 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, settlement.requestKill);
timeoutHandle = timeoutMs
? setTimeout(() => {
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));
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);
stdout += text;
options.onStdoutChunk?.(text);
});
child.stderr.on('data', (chunk) => {
const text = String(chunk);
stderr += text;
options.onStderrChunk?.(text);
});
child.on('error', (err) => {
fail(spawnRejectionError(abort, executable, cmd, args, err));
});
child.once('exit', settlement.recordExit);
child.once('close', settle);
});
}
export async function whichCmd(cmd: string): Promise<boolean> {
const candidate = normalizeExecutableLookup(cmd);
if (!candidate) return false;
if (path.isAbsolute(candidate)) {
return isExecutablePath(candidate);
}
const pathValue = process.env.PATH;
if (!pathValue) return false;
const pathExtensions = resolvePathExtensions();
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> {
const candidate = normalizeOverridePath(rawPath, envName, 'executable');
if (!candidate) return undefined;
if (!(await isExecutablePath(candidate))) {
throw new AppError(
'TOOL_MISSING',
`${envName} points to a missing or non-executable file: ${candidate}`,
{ envName, path: candidate },
);
}
return candidate;
}
export async function resolveFileOverridePath(
rawPath: string | undefined,
envName: string,
): Promise<string | undefined> {
const candidate = normalizeOverridePath(rawPath, envName, 'file');
if (!candidate) return undefined;
if (!(await isFilePath(candidate))) {
throw new AppError(
'TOOL_MISSING',
`${envName} points to a missing or non-file path: ${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();
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,
});
execTrace.emitBackgroundSpawn(cmd, args);
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.emitBackgroundCompletion(cmd, args, event);
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, settlement.requestKill);
child.on('error', (err) => {
if (finish('error')) reject(spawnRejectionError(abort, executable, cmd, args, err));
});
child.once('exit', settlement.recordExit);
child.once('close', settle);
});
return { child, wait };
}
type ExecTraceContext = {
emitBackgroundCompletion: (cmd: string, args: readonly string[], event: 'error' | 'exit') => void;
emitBackgroundSpawn: (cmd: string, args: readonly string[]) => void;
emitForegroundCompletion: (cmd: string, args: readonly string[]) => void;
};
function createExecTraceContext(): ExecTraceContext {
const diagnosticsMeta = getDiagnosticsMeta();
const diagnosticsDebugEnabled = diagnosticsMeta.debug === true;
const envTraceEnabled = parseBooleanLiteral(process.env.AGENT_DEVICE_EXEC_TRACE ?? '') === true;
if (!diagnosticsDebugEnabled && !envTraceEnabled) {
return createDisabledExecTraceContext();
}
if (envTraceEnabled && diagnosticsMeta.flushOnSuccess !== true) {
updateDiagnosticsScope({ flushOnSuccess: true });
}
const startedAtMs = Date.now();
let completionEmitted = false;
return {
emitForegroundCompletion: (cmd, args) => {
if (completionEmitted) return;
completionEmitted = true;
emitExecCommandDiagnostic({
cmd,
args,
startedAtMs,
});
},
emitBackgroundSpawn: (cmd, args) => {
emitExecCommandDiagnostic({
cmd,
args,
data: { event: 'spawn' },
});
},
emitBackgroundCompletion: (cmd, args, event) => {
if (completionEmitted) return;
completionEmitted = true;
emitExecCommandDiagnostic({
cmd,
args,
startedAtMs,
data: { event },
});
},
};
}
function createDisabledExecTraceContext(): ExecTraceContext {
return {
emitForegroundCompletion: () => {},
emitBackgroundSpawn: () => {},
emitBackgroundCompletion: () => {},
};
}
function emitExecCommandDiagnostic(params: {
cmd: string;
args: readonly string[];
startedAtMs?: number;
data?: Record<string, unknown>;
}): void {
const argsPrefix = params.args.slice(0, EXEC_DIAGNOSTIC_ARG_LIMIT);
emitDiagnostic({
level: 'debug',
phase: 'exec_command',
durationMs:
params.startedAtMs === undefined ? undefined : Math.max(0, Date.now() - params.startedAtMs),
data: {
command: params.cmd,
argsPrefix,
...(params.args.length > argsPrefix.length
? { omittedArgCount: params.args.length - argsPrefix.length }
: {}),
...(params.data ?? {}),
},
});
}
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 createCommandCanceledError(
executable: string,
cmd: string,
args: readonly string[],
): AppError {
return createRequestCanceledError({ cmd, args, executable });
}
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 prints this line (and exits 72) when the selected developer dir has no such tool, e.g. when
// xcode-select points at the Command Line Tools, which ship no simctl or devicectl. The wrapped tool
// never prints it, so it identifies the failure even for callers that pass no cmd.
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.`,
};
}
/**
* Guard an exec result that was obtained with `allowFailure: true`: throw a
* curated COMMAND_FAILED (with `processExitError` set, so normalizeError
* appends the stderr excerpt) on non-zero exit, and pass the result through
* otherwise. This is the standard shape for "run tool, fail with a specific
* message" call sites — it works under every executor (local spawn, tool
* providers, command overrides) because it checks the returned result rather
* than relying on the spawn layer to throw. `extra` accepts a function so
* failure-only work (hint classification) is not paid on the success path.
*/
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),
);
}
/**
* COMMAND_FAILED details for a non-zero exec result. `processExitError: true`
* lets normalizeError surface the first meaningful stderr line as the user-facing
* message instead of the generic wrap message. A process killed by a signal reports
* no exit code, so the raw child_process null is accepted as well.
*/
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 };
// Error to reject a spawned child's `error` event with: canceled if we aborted, else a spawn error.
function spawnRejectionError(
abort: CommandAbort,
executable: string,
cmd: string,
args: readonly string[],
err: Error,
): AppError {
return abort.didAbort
? createCommandCanceledError(executable, cmd, args)
: createSpawnError(executable, cmd, args, err);
}
// Failure (if any) for a spawned child's `close` event: canceled if we aborted, an exit error on
// a non-zero code unless allowed, otherwise null (the command resolves successfully).
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 createCommandCanceledError(executable, cmd, args);
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;
}
function resolvePathExtensions(): string[] {
if (process.platform !== 'win32') return [''];
const rawPathExt = process.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 command this module asked to be killed is finished once its child is gone, without
* waiting for the stdio pipes to drain: a descendant that inherited them keeps `close`
* from arriving, and the request behind the command — and the device lock it holds —
* would wait forever. Whether the kill request or the child's exit arrives first is not
* a question each caller should answer, so both report here and settlement happens once.
*/
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);
},
};
}
/**
* Signals the process group led by `pid` — the tree a detached child spawned — best-effort,
* and reports whether the write went through. One seam for every group kill in host-kit, so
* a caller outside this module can mock it instead of delivering a real signal to a
* fabricated pid (#1824). `host-process.ts` reaches it from here rather than the reverse:
* that module imports `exec.ts` for `runCmd`, and a value import back up would close a cycle
* the layering rules reject.
*
* A pid that is not a positive integer is refused without signalling: `0` would address this
* process's own group, and a negative one every process this user owns.
*/
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;
}
}
/**
* A detached command owns a process group, and the descendants we are trying to reach are
* its members — which is what keeps the group id reserved. So the group is still signalled
* after the direct child is reaped: those members are holding the pipes this command is
* waiting on. The one group-signal seam reports whether anything was reached rather than
* throwing, and a group that is gone or not ours to signal is the case it reports false.
*/
function killProcessTree(
child: ChildProcess,
options: Pick<ExecOptions, 'detached' | 'kill'>,
): void {
if (!options.kill) {
signalProcessTree(child, options.detached, 'SIGKILL');
return;
}
// The child is given its chance to clean up, and the escalation is what keeps that
// chance from becoming a way to outlive the deadline. The timer holds nothing open:
// a child that exits on the first signal clears it, and a worker shutting down owes
// a child that ignored the signal nothing further.
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,