import { type ChildProcess, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import path from "node:path"; import process from "node:process"; import { augmentedPathValue, cmdShellSpawnSpec, resetExtraToolDirectories, resolveSpawnableCommandPath, } from "../command.js"; // --- Process spawn --- export interface SpawnOutcome { stdout: string; stderr: string; exitCode: number | null; /** The run exceeded its wall-clock timeout. */ timedOut: boolean; /** The caller's AbortSignal fired (distinct from a timeout). */ aborted: boolean; } const OUTPUT_CAP_BYTES = 2_000_000; /** One-line reason a spawn did not succeed, honest about cancel vs timeout. */ export function spawnOutcomeFailureReason(outcome: SpawnOutcome): string { if (outcome.aborted) return "aborted"; if (outcome.timedOut) return "timed out"; return `exit code ${outcome.exitCode ?? "unknown"}`; } /** * Kill a child and its descendants. On Windows, .cmd/.bat children are * cmd.exe shells: killing just the shell leaks the actual tool behind it * (a JVM behind jdtls.cmd, node behind an npm shim). taskkill /T walks the * tree instead; elsewhere, a direct SIGTERM keeps the existing behavior, * escalating to SIGKILL if the child ignores it (a server stuck in a * syscall would otherwise survive close() and leak). */ const SIGKILL_ESCALATION_MS = 2_000; export function killProcessTree( child: ChildProcess, fallbackSignal: NodeJS.Signals = "SIGTERM", ): void { const pid = child.pid; if (process.platform !== "win32" || pid === undefined) { child.kill(fallbackSignal); if (fallbackSignal !== "SIGKILL") { // Unref'd: an escalation that never fires must not hold the event // loop open during process teardown. const escalation = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) { child.kill("SIGKILL"); } }, SIGKILL_ESCALATION_MS); escalation.unref?.(); } return; } try { spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, }).on("error", () => { // taskkill itself unavailable: fall back to the direct child. child.kill(fallbackSignal); }); } catch { child.kill(fallbackSignal); } } export function safeSpawnAsync( command: string, args: string[], options: { cwd: string; timeoutMs: number; signal?: AbortSignal }, ): Promise { return new Promise((resolve, reject) => { const spec = cmdShellSpawnSpec(command, args); const child = spawn(spec.command, spec.args, { cwd: options.cwd, env: process.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, }); let stdout = ""; let stderr = ""; let stdoutBytes = 0; let stderrBytes = 0; let timedOut = false; let aborted = false; const timer = setTimeout(() => { timedOut = true; killProcessTree(child); }, options.timeoutMs); const abort = () => { aborted = true; killProcessTree(child); }; options.signal?.addEventListener("abort", abort, { once: true }); // Independent caps: chatty stderr (progress bars, warnings) must not // truncate the stdout payload the parsers depend on. const capAndAppend = (target: "stdout" | "stderr", chunk: Buffer) => { const isStdout = target === "stdout"; const used = isStdout ? stdoutBytes : stderrBytes; if (used >= OUTPUT_CAP_BYTES) return; const total = used + chunk.length; if (isStdout) stdoutBytes = total; else stderrBytes = total; const text = chunk.toString("utf8"); if (isStdout) stdout += text; else stderr += text; if (total >= OUTPUT_CAP_BYTES) { const suffix = "\n...[output truncated]"; if (isStdout) stdout += suffix; else stderr += suffix; } }; child.stdout.on("data", (chunk: Buffer) => capAndAppend("stdout", chunk)); child.stderr.on("data", (chunk: Buffer) => capAndAppend("stderr", chunk)); child.once("error", (error) => { clearTimeout(timer); options.signal?.removeEventListener("abort", abort); reject( new Error(`Failed to run ${path.basename(command)}: ${error.message}`), ); }); child.once("close", (code) => { clearTimeout(timer); options.signal?.removeEventListener("abort", abort); resolve({ stdout, stderr, exitCode: code, timedOut, aborted }); }); }); } /** * Return the first candidate that actually runs (probe: --version). Node's * spawn does not reliably resolve bare names on Windows (and Git Bash * environments put msys curl first anyway), so callers pass absolute * System32 paths as the preferred candidates. */ export async function firstSpawnable( candidates: string[], cwd: string, timeoutMs = 60_000, ): Promise { for (const candidate of candidates) { const probe = await safeSpawnAsync(candidate, ["--version"], { cwd, timeoutMs, }); // A caller cancel must not read as "the tool is broken". if (probe.aborted) throw new Error(`aborted while probing ${candidate}`); if (probe.exitCode === 0) return candidate; } throw new Error(`none of ${candidates.join(", ")} is runnable`); } // --- Availability probe with cwd-keyed TTL cache --- // Distilled from pi-lens's createAvailabilityChecker: probes are cheap but not // free, so a resolved command path is cached for a bounded window. interface AvailabilityEntry { commandPath: string | undefined; resolvedAt: number; } const AVAILABILITY_TTL_MS = 30_000; const availabilityCache = new Map(); // The augmented tool search path lives in command.ts so the LSP client's // spawn resolution shares it (freshly installed servers land there too). export function resolveRunnerCommand( toolId: string, command: string, cwd: string, pathValue?: string, ): string | undefined { const searchPath = pathValue ?? augmentedPathValue(); const cacheKey = `${toolId}\0${command}\0${searchPath}`; const cached = availabilityCache.get(cacheKey); if (cached && Date.now() - cached.resolvedAt < AVAILABILITY_TTL_MS) { return cached.commandPath || undefined; } const commandPath = resolveWindowsCommand( command, cwd, process.platform, searchPath, ); availabilityCache.set(cacheKey, { commandPath: commandPath ?? "", resolvedAt: Date.now(), }); return commandPath; } // resolveWindowsCommand was promoted to command.ts's // resolveSpawnableCommandPath so the LSP client shares the fix. const resolveWindowsCommand = ( command: string, cwd: string, platform: NodeJS.Platform, pathValue: string, ): string | undefined => resolveSpawnableCommandPath(command, cwd, platform, pathValue); export function resetRunnerAvailabilityCache() { availabilityCache.clear(); } export function invalidateRunnerAvailability(toolId: string) { for (const key of [...availabilityCache.keys()]) { if (key.startsWith(`${toolId}\0`)) availabilityCache.delete(key); } } // --- Auto-install (pi-lens-inspired, system-package-manager based) --- // Unlike pi-lens's managed installer (~/.pi-lens/tools), we install through // whatever package manager the user already has (pip/pipx/npm/winget/scoop), // so the tool lands in the user's normal PATH. Attempts are shared in flight // per tool+cwd so concurrent callers never spawn duplicate installs. export interface InstallCandidate { label: string; command: string; args: string[]; /** Per-candidate post-install probe; overrides the global verify spec. */ verify?: InstallVerifySpec; } /** * Shared in-flight/failure key for one install attempt, derived from the * actual install command rather than the caller: the same install requested * through different lanes (an LSP server recipe and a CLI runner recipe, * different workspace roots) shares one attempt instead of racing. All * supported channels install globally (npm -g, winget, uv tool, managed * dirs), so the workspace root is not part of the identity. */ export function installKey(candidates: InstallCandidate[]): string { return `install:${candidates .map((candidate) => `${candidate.command} ${candidate.args.join(" ")}`) .join("|")}`; } /** SHA-256 of a file, streamed: archives can be hundreds of MB. */ export function sha256OfFile(filePath: string): Promise { return new Promise((resolve, reject) => { const hash = createHash("sha256"); const stream = createReadStream(filePath); stream.on("error", reject); stream.on("data", (chunk) => hash.update(chunk)); stream.on("end", () => resolve(hash.digest("hex"))); }); } export interface InstallOutcome { installed: boolean; detail: string; } /** Post-install probe: the installed tool itself must run `verify.args`. */ export interface InstallVerifySpec { command: string; args: string[]; } const INSTALL_TIMEOUT_MS = 180_000; const VERIFY_TIMEOUT_MS = 15_000; const inFlightInstalls = new Map>(); // Failed installs are remembered briefly so a burst of tool calls does not // re-pay the full attempt cost (up to INSTALL_TIMEOUT_MS per candidate) when // the environment is simply broken. Successes are never cached here; command // availability stays live through the availability TTL cache. const FAILED_INSTALL_TTL_MS = 60_000; const failedInstalls = new Map< string, { at: number; outcome: InstallOutcome } >(); // Distinct keys accumulate across tools over a long-lived process; evict // expired entries once the map grows past a healthy size (same policy as // the commandExists cache in command.ts). const FAILED_INSTALL_CACHE_MAX = 128; function pruneFailedInstalls() { if (failedInstalls.size < FAILED_INSTALL_CACHE_MAX) return; const now = Date.now(); for (const [key, failed] of failedInstalls) { if (now - failed.at >= FAILED_INSTALL_TTL_MS) failedInstalls.delete(key); } } export function shareInstall( key: string, factory: () => Promise, ): Promise { const failed = failedInstalls.get(key); if (failed && Date.now() - failed.at < FAILED_INSTALL_TTL_MS) { return Promise.resolve(failed.outcome); } failedInstalls.delete(key); const existing = inFlightInstalls.get(key); if (existing) return existing; const promise = factory() .then((outcome) => { if (outcome.installed) failedInstalls.delete(key); else { failedInstalls.set(key, { at: Date.now(), outcome }); pruneFailedInstalls(); } return outcome; }) .finally(() => { inFlightInstalls.delete(key); }); inFlightInstalls.set(key, promise); return promise; } export async function tryInstallCandidates( candidates: InstallCandidate[], cwd: string, signal?: AbortSignal, verify?: InstallVerifySpec, ): Promise { const attempts: string[] = []; for (const candidate of candidates) { signal?.throwIfAborted(); // The install may create the tool's bin directory (first winget // global install, first npm i -g); rescan so the probe below can see // a directory that did not exist when this process started. resetExtraToolDirectories(); const commandPath = resolveSpawnableCommandPath( candidate.command, cwd, process.platform, augmentedPathValue(), ); if (!commandPath) { attempts.push(`${candidate.label}: ${candidate.command} not on PATH`); continue; } const outcome = await safeSpawnAsync(commandPath, candidate.args, { cwd, timeoutMs: INSTALL_TIMEOUT_MS, signal, }); if (!outcome.timedOut && !outcome.aborted && outcome.exitCode === 0) { // "pip said success" is not "the tool runs" (a broken dependency // can make the installed launcher die on any invocation, including // --version). Verify before accepting the candidate. const effectiveVerify = candidate.verify ?? verify; if (effectiveVerify) { const verdict = await verifyInstall(effectiveVerify, cwd, signal); if (!verdict.ok) { attempts.push( `${candidate.label}: installed but verification failed (${verdict.reason})`, ); continue; } } return { installed: true, detail: candidate.label }; } const reason = spawnOutcomeFailureReason(outcome); const stderr = outcome.stderr.trim(); attempts.push( `${candidate.label}: ${reason}${stderr ? ` — ${stderr.split("\n")[0].slice(0, 160)}` : ""}`, ); } return { installed: false, detail: attempts.join("; ") }; } async function verifyInstall( verify: InstallVerifySpec, cwd: string, signal?: AbortSignal, ): Promise<{ ok: boolean; reason?: string }> { // See tryInstallCandidates: the freshly created bin directory must be // visible to the augmented search path before resolving the probe. resetExtraToolDirectories(); const resolved = resolveSpawnableCommandPath( verify.command, cwd, process.platform, augmentedPathValue(), ); if (!resolved) { return { ok: false, reason: `${verify.command} not found on search path after install`, }; } const outcome = await safeSpawnAsync(resolved, verify.args, { cwd, timeoutMs: VERIFY_TIMEOUT_MS, signal, }); if (outcome.timedOut || outcome.aborted) return { ok: false, reason: `verification spawn ${spawnOutcomeFailureReason(outcome)}`, }; if (outcome.exitCode !== 0) return { ok: false, reason: `exit code ${outcome.exitCode ?? "unknown"}` }; return { ok: true }; }