import { accessSync, constants, existsSync, lstatSync, readdirSync, statSync, } from "node:fs"; import os from "node:os"; import path from "node:path"; import process from "node:process"; export function commandExists( command: string, cwd = process.cwd(), pathValue = process.env.PATH ?? "", ) { // Same TTL semantics as the runner availability cache (runners/helpers.ts): // PATH probing is cheap but not free, and lsp_checks probes ~20 non // auto-install servers per call. Invalidated together with the extra // tool directories so a fresh install is visible immediately. const key = `${command}\0${cwd}\0${pathValue}`; const cached = commandExistsCache.get(key); if (cached && Date.now() - cached.at < COMMAND_EXISTS_TTL_MS) { return cached.exists; } const exists = resolveCommandPath(command, cwd, process.platform, pathValue) !== undefined; commandExistsCache.set(key, { exists, at: Date.now() }); pruneCommandExistsCache(); return exists; } const COMMAND_EXISTS_TTL_MS = 30_000; const commandExistsCache = new Map(); // The cache key embeds the effective PATH value, which changes whenever the // extra tool directories rescan finds a different set. Unbounded keys would // grow the map for the life of the process, so evict expired entries once // the map grows past a healthy size. const COMMAND_EXISTS_CACHE_MAX = 512; function pruneCommandExistsCache() { if (commandExistsCache.size < COMMAND_EXISTS_CACHE_MAX) return; const now = Date.now(); for (const [key, cached] of commandExistsCache) { if (now - cached.at >= COMMAND_EXISTS_TTL_MS) commandExistsCache.delete(key); } } /** Force the next commandExists() probes to re-resolve (used by tests/installs). */ export function resetCommandExistsCache() { commandExistsCache.clear(); } export function commandPathValue( env: Record | undefined, platform: NodeJS.Platform = process.platform, ) { const base = environmentValue(env, "PATH", platform) ?? environmentValue(process.env, "PATH", platform) ?? ""; const separator = platform === "win32" ? ";" : ":"; return [base, ...extraToolDirectories()] .filter((part) => part.length > 0) .join(separator); } // --- Augmented tool search path --- // Per-user installs (python.org, pipx, winget portable shims) are often not on // the current process PATH: the package manager adds them to the user PATH in // the registry, but already-running processes never re-read it. Well-known // per-user tool directories are appended to the search PATH. The scan is a // handful of syscalls, refreshed on a short TTL, so directories that appear // mid-process (a first winget install creating its Links dir) become visible // without a restart. let extraDirectories: string[] | undefined; let extraDirectoriesResolvedAt = 0; const EXTRA_DIRECTORIES_TTL_MS = 10_000; export function extraToolDirectories(): string[] { if ( extraDirectories && Date.now() - extraDirectoriesResolvedAt < EXTRA_DIRECTORIES_TTL_MS ) { return extraDirectories; } const directories = new Set(); const localAppData = process.env.LOCALAPPDATA; if (localAppData) { // python.org per-user installs: %LOCALAPPDATA%\Programs\Python\Python3XX[/Scripts] const programsPython = path.join(localAppData, "Programs", "Python"); try { for (const entry of readdirSync(programsPython, { withFileTypes: true, })) { if (entry.isDirectory() && /^python/i.test(entry.name)) { directories.add(path.join(programsPython, entry.name)); directories.add(path.join(programsPython, entry.name, "Scripts")); } } } catch { // No per-user Python installs. } // winget portable package shims (written to the user PATH for future // processes; running processes must search this explicitly). directories.add(path.join(localAppData, "Microsoft", "WinGet", "Links")); } const appData = process.env.APPDATA; if (appData) directories.add(path.join(appData, "Python", "Scripts")); // npm's global install bin directory on Windows (npm i -g tools land // here; the dir is created on the first global install, so a long-running // process must rescan to see it). if (appData) directories.add(path.join(appData, "npm")); // pipx default binary directory. directories.add(path.join(os.homedir(), ".local", "bin")); extraDirectories = [...directories].filter((directory) => existsSync(directory), ); extraDirectoriesResolvedAt = Date.now(); return extraDirectories; } /** Force the next extraToolDirectories() call to rescan (used by tests). */ export function resetExtraToolDirectories() { extraDirectories = undefined; extraDirectoriesResolvedAt = 0; // The augmented search path changed; cached PATH probes may be stale. commandExistsCache.clear(); } export function augmentedPathValue( platform: NodeJS.Platform = process.platform, ): string { const separator = platform === "win32" ? ";" : ":"; return [process.env.PATH ?? "", ...extraToolDirectories()] .filter((part) => part.length > 0) .join(separator); } export function mergeEnvironment( overrides: Record | undefined, platform: NodeJS.Platform = process.platform, ) { const environment: NodeJS.ProcessEnv = { ...process.env }; for (const [key, value] of Object.entries(overrides ?? {})) { if (platform === "win32") { for (const existingKey of Object.keys(environment)) { if (existingKey.toLowerCase() === key.toLowerCase()) delete environment[existingKey]; } } environment[key] = value; } return environment; } function environmentValue( environment: NodeJS.ProcessEnv | Record | undefined, name: string, platform: NodeJS.Platform, ) { if (platform !== "win32") return environment?.[name]; let value: string | undefined; for (const [key, candidate] of Object.entries(environment ?? {})) { if (key.toLowerCase() === name.toLowerCase()) value = candidate; } return value; } export function resolveCommandPath( command: string, cwd = process.cwd(), platform: NodeJS.Platform = process.platform, pathValue = process.env.PATH ?? "", ) { const extensions = platform === "win32" ? ["", ".exe", ".cmd", ".bat"] : [""]; if (command.includes("/") || command.includes("\\")) { const commandPath = path.isAbsolute(command) ? command : path.resolve(cwd, command); return resolveRunnableFile(commandPath, extensions, platform); } for (const directory of pathValue.split(platform === "win32" ? ";" : ":")) { const resolved = resolveRunnableFile( path.resolve(cwd, directory || ".", command), extensions, platform, ); if (resolved) return resolved; } return undefined; } /** * Resolve a command the way a process spawn will need it: on Windows an * extension-less PATH shim (e.g. nvm's sh-script wrappers) resolves first but * cannot be spawned, so prefer .cmd/.bat/.exe variants when they exist. */ export function resolveSpawnableCommandPath( command: string, cwd = process.cwd(), platform: NodeJS.Platform = process.platform, pathValue = process.env.PATH ?? "", ) { if (platform !== "win32") return resolveCommandPath(command, cwd, platform, pathValue); const direct = resolveCommandPath(command, cwd, platform, pathValue); if (direct && /\.(?:exe|cmd|bat)$/i.test(direct)) return direct; for (const extension of [".cmd", ".bat", ".exe"]) { const candidate = resolveCommandPath( command + extension, cwd, platform, pathValue, ); if (candidate) return candidate; } return direct; } /** * Windows cannot spawn .cmd/.bat files directly (Node raises EINVAL without a * shell), so route them through cmd.exe. Shared by the LSP client and the CLI * runner spawn helper. */ export function cmdShellSpawnSpec( command: string, args: string[], platform: NodeJS.Platform = process.platform, comSpec = process.env.ComSpec, ): { command: string; args: string[] } { if (platform === "win32" && /\.(?:bat|cmd)$/i.test(command)) { return { command: comSpec?.trim() || "cmd.exe", args: ["/d", "/s", "/c", command, ...args], }; } return { command, args }; } function resolveRunnableFile( filePath: string, extensions: string[], platform: NodeJS.Platform, ) { for (const extension of extensions) { const candidate = `${filePath}${extension}`; if (isRunnableFile(candidate, platform)) return candidate; } return undefined; } function isRunnableFile(filePath: string, platform: NodeJS.Platform) { if (platform === "win32") { try { const linked = lstatSync(filePath); // MSIX app-execution aliases (winget.exe, Store-installed python, ...) // are 0-byte reparse points: existsSync/statSync fail on them, but they // are perfectly spawnable via CreateProcess. They always carry an // executable extension, so a 0-byte file without one is just data — // an empty stray file in a PATH directory must not count as runnable. if (linked.isSymbolicLink()) return true; if (linked.isFile() && linked.size === 0) return /\.(?:exe|com|bat|cmd)$/i.test(filePath); if (!linked.isFile()) return false; } catch { return false; } } if (!existsSync(filePath)) return false; try { if (!statSync(filePath).isFile()) return false; if (platform !== "win32") accessSync(filePath, constants.X_OK); return true; } catch { return false; } }