UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

80 lines • 2.88 kB
/** * Shared command execution utilities for extensions and custom tools. */ import { spawn } from "node:child_process"; import { waitForChildProcess } from "../utils/child-process.js"; import { signalSpawnedChild } from "../utils/child-signal.js"; /** * Execute a shell command and return stdout/stderr/code. * Supports timeout and abort signal. */ export async function execCommand(command, args, cwd, options) { return new Promise((resolve) => { const proc = spawn(command, args, { cwd, shell: false, stdio: ["ignore", "pipe", "pipe"], // senpi#3965: hide the console window for console-subsystem children on Windows. windowsHide: true, }); let stdout = ""; let stderr = ""; let killed = false; let timeoutId; const killProcess = () => { if (!killed) { killed = true; // A child that never started has nothing to stop, so no escalation is armed for it either. if (!signalSpawnedChild(proc, "SIGTERM") && proc.pid === undefined) return; // Force kill after 5 seconds if SIGTERM doesn't work setTimeout(() => { if (!proc.killed) { signalSpawnedChild(proc, "SIGKILL"); } }, 5000); } }; // Handle abort signal if (options?.signal) { if (options.signal.aborted) { killProcess(); } else { options.signal.addEventListener("abort", killProcess, { once: true }); } } // Handle timeout if (options?.timeout && options.timeout > 0) { timeoutId = setTimeout(() => { killProcess(); }, options.timeout); } proc.stdout?.on("data", (data) => { stdout += data.toString(); }); proc.stderr?.on("data", (data) => { stderr += data.toString(); }); // Wait for process termination without hanging on inherited stdio handles // held open by detached descendants. waitForChildProcess(proc) .then((code) => { if (timeoutId) clearTimeout(timeoutId); if (options?.signal) { options.signal.removeEventListener("abort", killProcess); } resolve({ stdout, stderr, code: code ?? 0, killed }); }) .catch((_err) => { if (timeoutId) clearTimeout(timeoutId); if (options?.signal) { options.signal.removeEventListener("abort", killProcess); } resolve({ stdout, stderr, code: 1, killed }); }); }); } //# sourceMappingURL=exec.js.map