The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Contains props, error tags, and the live service for executing commands. |
| 3 | * Shared between the `Build`, `Dev`, and `Exec` resources. |
| 4 | */ |
| 5 | |
| 6 | import * as Context from "effect/Context"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Duration from "effect/Duration"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Fiber from "effect/Fiber"; |
| 11 | import { flow } from "effect/Function"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import * as Option from "effect/Option"; |
| 14 | import * as Path from "effect/Path"; |
| 15 | import type { PlatformError } from "effect/PlatformError"; |
| 16 | import { BadArgument, SystemError } from "effect/PlatformError"; |
| 17 | import * as Predicate from "effect/Predicate"; |
| 18 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 19 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 20 | import * as Redacted from "effect/Redacted"; |
| 21 | import type * as Scope from "effect/Scope"; |
| 22 | import * as Sink from "effect/Sink"; |
| 23 | import * as Stream from "effect/Stream"; |
| 24 | import type { ScopedPlanStatusSession } from "../Report.ts"; |
| 25 | import { isNonInteractive } from "../Util/interactive.ts"; |
| 26 | import { initialCwd } from "../Util/Node.ts"; |
| 27 | import { makeCommandRedactor, redactPlatformReason, type CommandRedactor } from "./Redaction.ts"; |
| 28 | |
| 29 | /** |
| 30 | * Base properties for a command resource. |
| 31 | */ |
| 32 | export interface CommandProps { |
| 33 | /** |
| 34 | * The command to run. |
| 35 | */ |
| 36 | command: string; |
| 37 | /** |
| 38 | * Working directory for the command. Defaults to `process.cwd()`. |
| 39 | */ |
| 40 | cwd?: string; |
| 41 | /** |
| 42 | * If set to true, runs the command inside of a shell, defaulting to /bin/sh on UNIX systems and cmd.exe on Windows. |
| 43 | * It is generally discouraged to use this option, as it can lead to security vulnerabilities and is not portable. |
| 44 | * If set to a string, runs the command inside of the specified shell. |
| 45 | * @default false |
| 46 | */ |
| 47 | shell?: string | boolean; |
| 48 | /** |
| 49 | * Extra environment variables passed to the command on top of `process.env`. |
| 50 | * Entries whose value is `undefined` are dropped — this lets website |
| 51 | * composites forward optional values (e.g. an `Output` service URL that |
| 52 | * resolves to `undefined`) without filtering first. |
| 53 | */ |
| 54 | env?: Record<string, string | Redacted.Redacted<string> | undefined>; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Properties shared by finite commands such as {@link Build} and |
| 59 | * {@link Exec}. |
| 60 | */ |
| 61 | export interface CommandRunProps extends CommandProps { |
| 62 | /** |
| 63 | * Maximum time the command may run. When exceeded, Alchemy sends `SIGTERM` |
| 64 | * to the command's process group, waits a bounded grace period, and then |
| 65 | * sends `SIGKILL` to ensure no descendants survive. |
| 66 | * |
| 67 | * Numbers are interpreted as milliseconds. Effect duration strings and |
| 68 | * `Duration` values are also accepted. |
| 69 | * |
| 70 | * @example "5 minutes" |
| 71 | */ |
| 72 | timeout?: Duration.Input; |
| 73 | } |
| 74 | |
| 75 | export class CommandExecutor extends Context.Service< |
| 76 | CommandExecutor, |
| 77 | { |
| 78 | /** |
| 79 | * Spawns a command, returning the child process handle. |
| 80 | */ |
| 81 | readonly spawn: ( |
| 82 | props: CommandProps, |
| 83 | ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, CommandError, Scope.Scope>; |
| 84 | /** |
| 85 | * Executes a command, returning the exit code, stdout, and stderr. |
| 86 | * Throws a {@link CommandError} if the command exits with a non-zero exit code. |
| 87 | */ |
| 88 | readonly run: ( |
| 89 | props: CommandRunProps, |
| 90 | session: ScopedPlanStatusSession, |
| 91 | ) => Effect.Effect<{ exitCode: number; stdout: string; stderr: string }, CommandError>; |
| 92 | } |
| 93 | >()("alchemy/Command/CommandExecutor") {} |
| 94 | |
| 95 | /** |
| 96 | * Extends Effect's `PlatformError` to include the command that failed and some command-specific error reasons. |
| 97 | */ |
| 98 | export class CommandError extends Data.TaggedError("CommandError")<{ |
| 99 | command: string; |
| 100 | reason: SystemError | BadArgument | UnexpectedExit | OutputNotFound | CommandTimedOut; |
| 101 | cause?: unknown; |
| 102 | }> { |
| 103 | constructor({ command, reason }: { command: string; reason: CommandError["reason"] }) { |
| 104 | if ("cause" in reason) { |
| 105 | super({ command, reason, cause: reason.cause }); |
| 106 | } else { |
| 107 | super({ command, reason }); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | override get message() { |
| 112 | return `Failed to execute command "${this.command}": ${this.reason.message}`; |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | export const isCommandError = (error: unknown): error is CommandError => |
| 117 | Predicate.isTagged(error, "CommandError"); |
| 118 | |
| 119 | /** |
| 120 | * Represents when a command exits unexpectedly. |
| 121 | */ |
| 122 | export class UnexpectedExit extends Data.TaggedError("UnexpectedExit")<{ |
| 123 | exitCode: number; |
| 124 | stderr: string; |
| 125 | }> { |
| 126 | override get message() { |
| 127 | return `The command exited with code ${this.exitCode}. Standard error output: ${this.stderr}`; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * Represents when a finite command exceeds its configured timeout. |
| 133 | */ |
| 134 | export class CommandTimedOut extends Data.TaggedError("CommandTimedOut")<{ timeout: string }> { |
| 135 | override get message() { |
| 136 | return `The command timed out after ${this.timeout}; its process group was terminated.`; |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Represents when the output directory does not exist. |
| 142 | */ |
| 143 | export class OutputNotFound extends Data.TaggedError("OutputNotFound")<{ outdir: string }> { |
| 144 | override get message() { |
| 145 | return `The output directory "${this.outdir}" does not exist.`; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /** @internal */ |
| 150 | export const makeCommandError = ( |
| 151 | props: Pick<CommandProps, "command" | "env">, |
| 152 | reason: CommandError["reason"], |
| 153 | ): CommandError => { |
| 154 | const redactor = makeCommandRedactor(props.env); |
| 155 | const safeReason = |
| 156 | reason instanceof BadArgument || reason instanceof SystemError |
| 157 | ? redactPlatformReason(reason, redactor) |
| 158 | : reason._tag === "UnexpectedExit" |
| 159 | ? new UnexpectedExit({ exitCode: reason.exitCode, stderr: redactor.redact(reason.stderr) }) |
| 160 | : reason._tag === "OutputNotFound" |
| 161 | ? new OutputNotFound({ outdir: redactor.redact(reason.outdir) }) |
| 162 | : new CommandTimedOut({ timeout: redactor.redact(reason.timeout) }); |
| 163 | |
| 164 | return new CommandError({ command: redactor.redact(props.command), reason: safeReason }); |
| 165 | }; |
| 166 | |
| 167 | const TERMINATION_GRACE_PERIOD = Duration.seconds(1); |
| 168 | const TERMINATION_SIGNAL_DISPATCH_TIMEOUT = Duration.millis(25); |
| 169 | |
| 170 | const parseExecutionTimeout = ( |
| 171 | props: CommandRunProps, |
| 172 | ): Effect.Effect<Duration.Duration | undefined, CommandError> => { |
| 173 | if (props.timeout === undefined) return Effect.undefined; |
| 174 | const decoded = Duration.fromInput(props.timeout); |
| 175 | if ( |
| 176 | Option.isNone(decoded) || |
| 177 | !Duration.isFinite(decoded.value) || |
| 178 | Duration.isZero(decoded.value) || |
| 179 | Duration.isNegative(decoded.value) |
| 180 | ) { |
| 181 | return Effect.fail( |
| 182 | makeCommandError( |
| 183 | props, |
| 184 | new BadArgument({ |
| 185 | module: "Command", |
| 186 | method: "run", |
| 187 | description: "timeout must be a positive finite duration", |
| 188 | }), |
| 189 | ), |
| 190 | ); |
| 191 | } |
| 192 | return Effect.succeed(decoded.value); |
| 193 | }; |
| 194 | |
| 195 | const terminateProcessGroup = (child: ChildProcessSpawner.ChildProcessHandle) => |
| 196 | Effect.gen(function* () { |
| 197 | // Dispatch SIGTERM without waiting indefinitely for the root process. The |
| 198 | // Effect process runtime targets the detached process group on POSIX and |
| 199 | // the full process tree on Windows. |
| 200 | yield* child |
| 201 | .kill({ killSignal: "SIGTERM" }) |
| 202 | .pipe(Effect.timeoutOption(TERMINATION_SIGNAL_DISPATCH_TIMEOUT), Effect.ignore); |
| 203 | yield* Effect.sleep(TERMINATION_GRACE_PERIOD); |
| 204 | |
| 205 | // Always signal the group again: the root may have exited promptly while |
| 206 | // a descendant ignored SIGTERM. The hard-kill wait is itself bounded. |
| 207 | yield* child |
| 208 | .kill({ killSignal: "SIGKILL" }) |
| 209 | .pipe(Effect.timeoutOption(TERMINATION_GRACE_PERIOD), Effect.ignore); |
| 210 | }); |
| 211 | |
| 212 | const redactChildProcessHandle = ( |
| 213 | child: ChildProcessSpawner.ChildProcessHandle, |
| 214 | redactor: CommandRedactor, |
| 215 | ): ChildProcessSpawner.ChildProcessHandle => { |
| 216 | const stdout = child.stdout.pipe(Stream.decodeText, redactor.stream, Stream.encodeText); |
| 217 | const stderr = child.stderr.pipe(Stream.decodeText, redactor.stream, Stream.encodeText); |
| 218 | return ChildProcessSpawner.makeHandle({ |
| 219 | pid: child.pid, |
| 220 | exitCode: child.exitCode, |
| 221 | isRunning: child.isRunning, |
| 222 | kill: child.kill, |
| 223 | stdin: child.stdin, |
| 224 | stdout, |
| 225 | stderr, |
| 226 | all: Stream.merge(stdout, stderr), |
| 227 | getInputFd: child.getInputFd, |
| 228 | getOutputFd: child.getOutputFd, |
| 229 | unref: child.unref, |
| 230 | }); |
| 231 | }; |
| 232 | |
| 233 | export const CommandExecutorLive = () => |
| 234 | Layer.effect( |
| 235 | CommandExecutor, |
| 236 | Effect.gen(function* () { |
| 237 | const path = yield* Path.Path; |
| 238 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 239 | |
| 240 | /** Parses a command string into a binary and arguments, unless {@link CommandProps.shell} is true. */ |
| 241 | const parseCommand = ( |
| 242 | props: CommandProps, |
| 243 | ): Effect.Effect<{ bin: string; args: string[] }, CommandError> => { |
| 244 | if (props.shell) { |
| 245 | return Effect.succeed({ bin: props.command, args: [] }); |
| 246 | } |
| 247 | const [bin, ...args] = props.command.split(/(\s+)/).filter((part) => !!part.trim()); |
| 248 | if (!bin) { |
| 249 | return Effect.fail( |
| 250 | makeCommandError( |
| 251 | props, |
| 252 | new BadArgument({ |
| 253 | module: "Command", |
| 254 | method: "parseCommand", |
| 255 | description: "Command is empty", |
| 256 | }), |
| 257 | ), |
| 258 | ); |
| 259 | } |
| 260 | return Effect.succeed({ bin, args }); |
| 261 | }; |
| 262 | |
| 263 | /** Spawns a command, returning the child process handle. */ |
| 264 | const spawn = (props: CommandProps) => |
| 265 | parseCommand(props).pipe( |
| 266 | Effect.flatMap(({ bin, args }) => |
| 267 | Effect.acquireRelease( |
| 268 | spawner.spawn( |
| 269 | ChildProcess.make(bin, args, { |
| 270 | // Anchored: a live `process.cwd()` read can race a |
| 271 | // concurrent tool's transient chdir (see Util/Node.ts). |
| 272 | cwd: path.resolve(initialCwd, props.cwd ?? "."), |
| 273 | shell: props.shell ?? false, |
| 274 | env: Object.fromEntries( |
| 275 | Object.entries(props.env ?? {}) |
| 276 | .filter( |
| 277 | (entry): entry is [string, string | Redacted.Redacted<string>] => |
| 278 | entry[1] !== undefined, |
| 279 | ) |
| 280 | .map(([k, v]) => [k, Redacted.isRedacted(v) ? Redacted.value(v) : v]), |
| 281 | ), |
| 282 | extendEnv: true, |
| 283 | stdin: isNonInteractive() ? "ignore" : "inherit", |
| 284 | stdout: "pipe", |
| 285 | stderr: "pipe", |
| 286 | // The Effect process runtime creates a detached process group |
| 287 | // by default on POSIX. Preserve that default so timeouts and |
| 288 | // scoped interruption can terminate every descendant. |
| 289 | // Preserve hard cleanup when the leader exits with an error. |
| 290 | killSignal: "SIGKILL", |
| 291 | }), |
| 292 | ), |
| 293 | (child) => |
| 294 | child |
| 295 | .kill({ killSignal: "SIGTERM", forceKillAfter: TERMINATION_GRACE_PERIOD }) |
| 296 | .pipe(Effect.ignore), |
| 297 | ), |
| 298 | ), |
| 299 | Effect.map((child) => redactChildProcessHandle(child, makeCommandRedactor(props.env))), |
| 300 | mapError(props), |
| 301 | ); |
| 302 | |
| 303 | /** Collects the output of a stream, tapping each line to a sink. */ |
| 304 | const collect = ( |
| 305 | stream: Stream.Stream<Uint8Array, PlatformError>, |
| 306 | tap: (chunk: string) => Effect.Effect<void>, |
| 307 | redactor: CommandRedactor, |
| 308 | ) => |
| 309 | stream.pipe( |
| 310 | Stream.decodeText, |
| 311 | redactor.stream, |
| 312 | Stream.tapSink(Sink.make<string>()(flow(Stream.splitLines, Stream.runForEach(tap)))), |
| 313 | Stream.mkString, |
| 314 | ); |
| 315 | |
| 316 | /** Maps a PlatformError to a CommandError. */ |
| 317 | const mapError = (props: CommandProps) => |
| 318 | Effect.mapError((error: PlatformError | CommandError) => |
| 319 | error._tag === "CommandError" ? error : makeCommandError(props, error.reason), |
| 320 | ); |
| 321 | |
| 322 | return CommandExecutor.of({ |
| 323 | spawn, |
| 324 | /** Executes a command, returning the exit code, stdout, and stderr. */ |
| 325 | run: (props: CommandRunProps, session: ScopedPlanStatusSession) => |
| 326 | Effect.gen(function* () { |
| 327 | const timeout = yield* parseExecutionTimeout(props); |
| 328 | const redactor = makeCommandRedactor(props.env); |
| 329 | const child = yield* spawn(props); |
| 330 | const execution = Effect.all( |
| 331 | { |
| 332 | exitCode: child.exitCode, |
| 333 | stdout: collect( |
| 334 | child.stdout, |
| 335 | (line) => session.note(line, { kind: "output" }), |
| 336 | redactor, |
| 337 | ), |
| 338 | stderr: collect( |
| 339 | child.stderr, |
| 340 | (line) => session.note(line, { kind: "output" }), |
| 341 | redactor, |
| 342 | ), |
| 343 | }, |
| 344 | { concurrency: "unbounded" }, |
| 345 | ).pipe(mapError(props)); |
| 346 | |
| 347 | const runExecution = Effect.gen(function* () { |
| 348 | if (timeout === undefined) { |
| 349 | return yield* execution; |
| 350 | } |
| 351 | const fiber = yield* Effect.forkScoped(execution); |
| 352 | const completed = yield* Fiber.join(fiber).pipe(Effect.timeoutOption(timeout)); |
| 353 | if (Option.isSome(completed)) return completed.value; |
| 354 | |
| 355 | yield* terminateProcessGroup(child); |
| 356 | yield* Fiber.interrupt(fiber).pipe( |
| 357 | Effect.timeoutOption(TERMINATION_GRACE_PERIOD), |
| 358 | Effect.ignore, |
| 359 | ); |
| 360 | return yield* makeCommandError( |
| 361 | props, |
| 362 | new CommandTimedOut({ timeout: Duration.format(timeout) }), |
| 363 | ); |
| 364 | }); |
| 365 | const result = yield* runExecution; |
| 366 | if (result.exitCode !== 0) { |
| 367 | return yield* makeCommandError( |
| 368 | props, |
| 369 | new UnexpectedExit({ exitCode: result.exitCode, stderr: result.stderr }), |
| 370 | ); |
| 371 | } |
| 372 | return result; |
| 373 | }).pipe(Effect.scoped), |
| 374 | }); |
| 375 | }), |
| 376 | ); |