@@ -104,6 +104,32 @@ export async function withoutCommandExecutorOverride<T>(fn: () => Promise<T>): P
104104 return await commandExecutorOverrideScope . run ( undefined , fn ) ;
105105}
106106
107+ const requestCommandEnvScope = new AsyncLocalStorage < NodeJS . ProcessEnv > ( ) ;
108+
109+ /** Overlays request environment values on spawned commands without changing `process.env`. */
110+ export async function withRequestCommandEnv < T > (
111+ env : NodeJS . ProcessEnv | undefined ,
112+ fn : ( ) => Promise < T > ,
113+ ) : Promise < T > {
114+ if ( ! env ) return await fn ( ) ;
115+ return await requestCommandEnvScope . run ( env , fn ) ;
116+ }
117+
118+ /** Effective toolchain selection; an explicitly empty request value selects `xcode-select`. */
119+ export function commandDeveloperDir ( ) : string | undefined {
120+ const requestEnv = requestCommandEnvScope . getStore ( ) ;
121+ if ( requestEnv && Object . hasOwn ( requestEnv , 'DEVELOPER_DIR' ) ) {
122+ return requestEnv . DEVELOPER_DIR || undefined ;
123+ }
124+ return process . env . DEVELOPER_DIR || undefined ;
125+ }
126+
127+ function resolveSpawnEnv ( env : NodeJS . ProcessEnv | undefined ) : NodeJS . ProcessEnv | undefined {
128+ const requestEnv = requestCommandEnvScope . getStore ( ) ;
129+ if ( ! requestEnv ) return env ;
130+ return { ...( env ?? process . env ) , ...requestEnv } ;
131+ }
132+
107133export async function runCmd (
108134 cmd : string ,
109135 args : readonly string [ ] ,
@@ -154,7 +180,7 @@ function runSpawnedCommand(
154180 return new Promise ( ( resolve , reject ) => {
155181 const child = spawn ( executable , args , {
156182 cwd : options . cwd ,
157- env : options . env ,
183+ env : resolveSpawnEnv ( options . env ) ,
158184 stdio : [ 'pipe' , 'pipe' , 'pipe' ] ,
159185 detached : options . detached ,
160186 windowsHide : true ,
@@ -324,7 +350,7 @@ export function runCmdSync(
324350 const executable = normalizeExecutableCommand ( cmd ) ;
325351 const result = spawnSync ( executable , args , {
326352 cwd : options . cwd ,
327- env : options . env ,
353+ env : resolveSpawnEnv ( options . env ) ,
328354 stdio : [ 'pipe' , 'pipe' , 'pipe' ] ,
329355 encoding : options . binaryStdout ? undefined : 'utf8' ,
330356 input : options . stdin ,
@@ -391,7 +417,7 @@ export function runCmdDetachedMonitored(
391417 const executable = normalizeExecutableCommand ( cmd ) ;
392418 const child = spawn ( executable , args , {
393419 cwd : options . cwd ,
394- env : options . env ,
420+ env : resolveSpawnEnv ( options . env ) ,
395421 stdio : options . stdio ?? 'ignore' ,
396422 detached : true ,
397423 windowsHide : true ,
@@ -423,7 +449,7 @@ export function runCmdBackground(
423449 const execTrace = createExecTraceContext ( ) ;
424450 const child = spawn ( executable , args , {
425451 cwd : options . cwd ,
426- env : options . env ,
452+ env : resolveSpawnEnv ( options . env ) ,
427453 stdio : options . stdio ?? [ 'ignore' , 'pipe' , 'pipe' ] ,
428454 detached : options . detached ,
429455 windowsHide : true ,
@@ -678,15 +704,26 @@ function createExitError(
678704 ) ;
679705}
680706
707+ // xcrun itself emits this line, including when the caller supplies no command metadata.
708+ const XCRUN_TOOL_NOT_FOUND_STDERR = / x c r u n : e r r o r : u n a b l e t o f i n d u t i l i t y " ( [ ^ " ] + ) " / ;
709+
710+ function xcrunToolNotFoundDetails ( stderr : string ) : Record < string , unknown > {
711+ const tool = XCRUN_TOOL_NOT_FOUND_STDERR . exec ( stderr ) ?. [ 1 ] ;
712+ if ( ! tool ) return { } ;
713+ const developerDir = commandDeveloperDir ( ) ;
714+ const source = developerDir
715+ ? `DEVELOPER_DIR ${ developerDir } `
716+ : 'the developer dir selected by xcode-select (see xcode-select -p)' ;
717+ return {
718+ reason : 'xcrun-tool-not-found' ,
719+ developerDir : developerDir ?? null ,
720+ 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.` ,
721+ } ;
722+ }
723+
681724/**
682- * Guard an exec result that was obtained with `allowFailure: true`: throw a
683- * curated COMMAND_FAILED (with `processExitError` set, so normalizeError
684- * appends the stderr excerpt) on non-zero exit, and pass the result through
685- * otherwise. This is the standard shape for "run tool, fail with a specific
686- * message" call sites — it works under every executor (local spawn, tool
687- * providers, command overrides) because it checks the returned result rather
688- * than relying on the spawn layer to throw. `extra` accepts a function so
689- * failure-only work (hint classification) is not paid on the success path.
725+ * Raises COMMAND_FAILED for a non-zero result, preserving stderr for normalizeError.
726+ * Passes successful results through unchanged and evaluates functional `extra` only on failure.
690727 */
691728export function requireExecSuccess <
692729 R extends Pick < ExecResult , 'stdout' | 'stderr' > & Readonly < { exitCode : number | null } > ,
@@ -704,10 +741,7 @@ export function requireExecSuccess<
704741}
705742
706743/**
707- * COMMAND_FAILED details for a non-zero exec result. `processExitError: true`
708- * lets normalizeError surface the first meaningful stderr line as the user-facing
709- * message instead of the generic wrap message. A process killed by a signal reports
710- * no exit code, so the raw child_process null is accepted as well.
744+ * Exit-failure details for normalizeError, including null exit codes from signalled processes.
711745 */
712746export function execFailureDetails (
713747 result : Pick < ExecResult , 'stdout' | 'stderr' > & Readonly < { exitCode : number | null } > ,
@@ -719,12 +753,13 @@ export function execFailureDetails(
719753 exitCode : result . exitCode ,
720754 processExitError : true ,
721755 ...extra ,
756+ // Last: a missing tool makes a caller's hint about the device or app moot.
757+ ...xcrunToolNotFoundDetails ( result . stderr ) ,
722758 } ;
723759}
724760
725761type CommandAbort = { readonly didAbort : boolean } ;
726762
727- // Error to reject a spawned child's `error` event with: canceled if we aborted, else a spawn error.
728763function spawnRejectionError (
729764 abort : CommandAbort ,
730765 executable : string ,
@@ -737,8 +772,6 @@ function spawnRejectionError(
737772 : createSpawnError ( executable , cmd , args , err ) ;
738773}
739774
740- // Failure (if any) for a spawned child's `close` event: canceled if we aborted, an exit error on
741- // a non-zero code unless allowed, otherwise null (the command resolves successfully).
742775function commandCloseFailure (
743776 abort : CommandAbort ,
744777 executable : string ,
@@ -830,11 +863,8 @@ function normalizeTimeoutMs(value: number | undefined): number | undefined {
830863}
831864
832865/**
833- * A command this module asked to be killed is finished once its child is gone, without
834- * waiting for the stdio pipes to drain: a descendant that inherited them keeps `close`
835- * from arriving, and the request behind the command — and the device lock it holds —
836- * would wait forever. Whether the kill request or the child's exit arrives first is not
837- * a question each caller should answer, so both report here and settlement happens once.
866+ * A killed command settles when its direct child exits: descendants can keep inherited pipes
867+ * open indefinitely. Both kill/exit orderings must settle once without waiting for `close`.
838868 */
839869type CommandKillSettlement = {
840870 /** Signals the command's process tree, then settles the command if its child is gone. */
@@ -892,15 +922,9 @@ function watchCommandAbort(
892922}
893923
894924/**
895- * Signals the process group led by `pid` — the tree a detached child spawned — best-effort,
896- * and reports whether the write went through. One seam for every group kill in host-kit, so
897- * a caller outside this module can mock it instead of delivering a real signal to a
898- * fabricated pid (#1824). `host-process.ts` reaches it from here rather than the reverse:
899- * that module imports `exec.ts` for `runCmd`, and a value import back up would close a cycle
900- * the layering rules reject.
901- *
902- * A pid that is not a positive integer is refused without signalling: `0` would address this
903- * process's own group, and a negative one every process this user owns.
925+ * Best-effort process-group signalling, shared by host-kit callers. This lives below
926+ * host-process.ts to avoid an import cycle. Only positive integer pids are accepted:
927+ * zero targets this process's group, and negative values can target unrelated processes.
904928 */
905929export function signalProcessGroupBestEffort ( pid : number , signal : NodeJS . Signals ) : boolean {
906930 if ( ! Number . isInteger ( pid ) || pid <= 0 ) return false ;
@@ -912,13 +936,7 @@ export function signalProcessGroupBestEffort(pid: number, signal: NodeJS.Signals
912936 }
913937}
914938
915- /**
916- * A detached command owns a process group, and the descendants we are trying to reach are
917- * its members — which is what keeps the group id reserved. So the group is still signalled
918- * after the direct child is reaped: those members are holding the pipes this command is
919- * waiting on. The one group-signal seam reports whether anything was reached rather than
920- * throwing, and a group that is gone or not ours to signal is the case it reports false.
921- */
939+ // Surviving descendants keep a detached process group reserved after its direct child exits.
922940function killProcessTree (
923941 child : ChildProcess ,
924942 options : Pick < ExecOptions , 'detached' | 'kill' > ,
@@ -927,10 +945,7 @@ function killProcessTree(
927945 signalProcessTree ( child , options . detached , 'SIGKILL' ) ;
928946 return ;
929947 }
930- // The child is given its chance to clean up, and the escalation is what keeps that
931- // chance from becoming a way to outlive the deadline. The timer holds nothing open:
932- // a child that exits on the first signal clears it, and a worker shutting down owes
933- // a child that ignored the signal nothing further.
948+ // Escalation bounds graceful cleanup; the unref timer cannot keep a worker alive.
934949 signalProcessTree ( child , options . detached , options . kill . signal ) ;
935950 const escalation = setTimeout (
936951 ( ) => signalProcessTree ( child , options . detached , 'SIGKILL' ) ,
@@ -949,10 +964,7 @@ function signalProcessTree(
949964 signalProcessGroupBestEffort ( child . pid , signal ) ;
950965 return ;
951966 }
952- // A non-detached child leaves its pid free for the kernel to hand to an unrelated
953- // process once Node has reaped it, so a late signal from a stale deadline could
954- // strike a stranger. Nothing waits for a kill of a child that is already gone:
955- // settlement happens on `exit`.
967+ // A reaped, non-detached child can have its pid reassigned to an unrelated process.
956968 if ( child . exitCode !== null || child . signalCode !== null ) return ;
957969 child . kill ( signal ) ;
958970}
0 commit comments