// Portable installer for Python-ecosystem tools (ty, ruff) through uv. // // "pip installed the package" does not mean "the command is on PATH": the // Microsoft Store Python writes user scripts into its Packages sandbox, // per-user python.org installs write to %APPDATA%\Python\Python3XX\Scripts, // and pipx/uv shims land in ~/.local/bin — none of which the current // process PATH necessarily contains. uv sidesteps all of that: it is a // static single-file binary with no Python dependency, and every // `uv tool install` shim lands in ~/.local/bin, which // extraToolDirectories() already covers (with a short TTL rescan, so a // fresh install is visible without restarting pi). // // uv itself is installed from the official GitHub release archive (a plain // binary download-and-extract, the same trust level as the jdtls installer) // rather than by piping a remote install script into a shell interpreter — // "irm https://astral.sh/uv/install.ps1 | iex" executed whatever the // network delivered, with no integrity check of any kind. import { chmodSync, copyFileSync, type Dirent, existsSync, mkdirSync, readdirSync, renameSync, rmSync, } from "node:fs"; import os from "node:os"; import path from "node:path"; import process from "node:process"; import { augmentedPathValue, resetExtraToolDirectories, resolveSpawnableCommandPath, } from "./command.js"; import { firstSpawnable, type InstallCandidate, type InstallOutcome, installKey, invalidateRunnerAvailability, safeSpawnAsync, sha256OfFile, shareInstall, spawnOutcomeFailureReason, tryInstallCandidates, } from "./runners/helpers.js"; import type { CustomInstallOutcome } from "./types.js"; const UV_DOWNLOAD_TIMEOUT_MS = 600_000; const UV_EXTRACT_TIMEOUT_MS = 120_000; const UV_PROBE_TIMEOUT_MS = 60_000; const UV_BIN_DIR = path.join(os.homedir(), ".local", "bin"); export function findUv(cwd: string): string | undefined { return resolveSpawnableCommandPath( "uv", cwd, process.platform, augmentedPathValue(), ); } /** * Make sure the uv binary is available, installing it from the official * GitHub release archive when it is missing. The attempt is shared in * flight and briefly cached on failure so bursts of tool calls never spawn * duplicate installs. */ export async function ensureUv( cwd: string, signal?: AbortSignal, ): Promise { if (findUv(cwd)) return { installed: true, detail: "uv already available" }; return shareInstall("uv:ensure", async () => { // Double-check inside the shared attempt: a concurrent install may // have finished between the caller's check and this one. if (findUv(cwd)) return { installed: true, detail: "uv already available" }; const label = "uv release download (github.com/astral-sh/uv)"; const outcome = await installUvFromRelease(cwd, signal); if (!outcome.installed) return outcome; // The binaries landed in ~/.local/bin; make the directory visible to // the augmented search path without restarting pi. resetExtraToolDirectories(); if (!findUv(cwd)) { return { installed: false, detail: `${label}: download succeeded but uv is not resolvable`, }; } return { installed: true, detail: label }; }); } // --- Release download-and-extract --- interface UvReleaseAsset { triple: string; extension: "zip" | "tar.gz"; } function uvReleaseAsset(): UvReleaseAsset | undefined { const arch = process.arch === "x64" ? "x86_64" : process.arch === "arm64" ? "aarch64" : undefined; if (!arch) return undefined; if (process.platform === "win32") return { triple: `${arch}-pc-windows-msvc`, extension: "zip" }; if (process.platform === "linux") return { triple: `${arch}-unknown-linux-gnu`, extension: "tar.gz" }; if (process.platform === "darwin") return { triple: `${arch}-apple-darwin`, extension: "tar.gz" }; return undefined; } function systemToolCandidates(name: "curl" | "tar"): string[] { if (process.platform !== "win32") return [name]; const system32 = path.join( process.env.SystemRoot ?? "C:\\Windows", "System32", ); return [path.join(system32, `${name}.exe`), name]; } async function installUvFromRelease( cwd: string, signal: AbortSignal | undefined, ): Promise { const asset = uvReleaseAsset(); if (!asset) { return { installed: false, detail: `no prebuilt uv release for ${process.platform}/${process.arch}`, }; } const staging = path.join(os.tmpdir(), `pi-lsp-uv-install-${process.pid}`); rmSync(staging, { recursive: true, force: true }); mkdirSync(staging, { recursive: true }); try { const curl = await firstSpawnable( systemToolCandidates("curl"), cwd, UV_PROBE_TIMEOUT_MS, ); const url = `https://github.com/astral-sh/uv/releases/latest/download/uv-${asset.triple}.${asset.extension}`; const archive = path.join(staging, `uv-${asset.triple}.${asset.extension}`); // Download to a temp name and rename on success: a killed process // must not leave a partial archive behind to be extracted. const partial = `${archive}.part`; const outcome = await safeSpawnAsync( curl, ["-fL", "--retry", "2", "--connect-timeout", "20", "-o", partial, url], { cwd, timeoutMs: UV_DOWNLOAD_TIMEOUT_MS, signal }, ); if (outcome.aborted) return { installed: false, detail: "uv download aborted" }; if (outcome.timedOut || outcome.exitCode !== 0) { const stderr = outcome.stderr.trim(); return { installed: false, detail: `uv download failed: ${spawnOutcomeFailureReason(outcome)}${stderr ? ` — ${stderr.split("\n")[0].slice(0, 160)}` : ""}`, }; } renameSync(partial, archive); // The release publishes per-asset .sha256 sidecars (" "); // an archive that will be extracted and executed must never pass on // "the download said 200 OK" alone. A missing sidecar is recorded // honestly as unverified instead of failing the install. const expectedSha256 = await tryFetchUvChecksum(url, cwd, signal); let checksumNote = "checksum unavailable (unverified)"; if (expectedSha256) { const actual = await sha256OfFile(archive); if (actual !== expectedSha256) { rmSync(archive, { force: true }); return { installed: false, detail: `uv archive checksum mismatch (expected ${expectedSha256}, got ${actual}); archive deleted`, }; } checksumNote = "checksum verified"; } // bsdtar (Windows system tar) handles both .zip and .tar.gz. const tar = await firstSpawnable( systemToolCandidates("tar"), cwd, UV_PROBE_TIMEOUT_MS, ); const extractDir = path.join(staging, "extract"); mkdirSync(extractDir, { recursive: true }); const extract = await safeSpawnAsync( tar, ["-xf", archive, "-C", extractDir], { cwd, timeoutMs: UV_EXTRACT_TIMEOUT_MS, signal }, ); if (extract.aborted) return { installed: false, detail: "uv extract aborted" }; if (extract.timedOut || extract.exitCode !== 0) { return { installed: false, detail: `uv extract failed: ${spawnOutcomeFailureReason(extract)}`, }; } // The archive is flat on Windows (uv.exe at the root) and wrapped in // one directory elsewhere. Find uv regardless of layout. const uvBinary = findInArchive( extractDir, process.platform === "win32" ? "uv.exe" : "uv", ); if (!uvBinary) { return { installed: false, detail: "uv archive extracted but the uv binary was not found in it", }; } const uvxName = process.platform === "win32" ? "uvx.exe" : "uvx"; const binaries = [uvBinary]; const uvx = findInArchive(extractDir, uvxName); if (uvx) binaries.push(uvx); mkdirSync(UV_BIN_DIR, { recursive: true }); for (const binary of binaries) { const target = path.join(UV_BIN_DIR, path.basename(binary)); copyFileSync(binary, target); if (process.platform !== "win32") chmodSync(target, 0o755); } return { installed: true, detail: `uv installed to ${UV_BIN_DIR} (${checksumNote})`, }; } catch (error) { return { installed: false, detail: `uv install failed: ${error instanceof Error ? error.message : String(error)}`, }; } finally { rmSync(staging, { recursive: true, force: true }); } } function findInArchive(directory: string, name: string): string | undefined { const direct = path.join(directory, name); if (existsSync(direct)) return direct; // One wrapping directory (tar.gz layout: uv-/uv). let entries: Dirent[] | undefined; try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return undefined; } for (const entry of entries) { if (!entry.isDirectory()) continue; const candidate = path.join(directory, entry.name, name); if (existsSync(candidate)) return candidate; } return undefined; } /** Best-effort fetch of the release's .sha256 sidecar; undefined when absent. */ async function tryFetchUvChecksum( url: string, cwd: string, signal: AbortSignal | undefined, ): Promise { try { const curl = await firstSpawnable( systemToolCandidates("curl"), cwd, UV_PROBE_TIMEOUT_MS, ); const outcome = await safeSpawnAsync( curl, ["-fsSL", "--connect-timeout", "20", `${url}.sha256`], { cwd, timeoutMs: UV_PROBE_TIMEOUT_MS, signal }, ); if (outcome.exitCode !== 0) return undefined; // " " or bare "" — take the first token. const candidate = outcome.stdout.trim().split(/\s+/)[0]; return /^[0-9a-f]{64}$/i.test(candidate) ? candidate.toLowerCase() : undefined; } catch { // No usable curl at all: the download itself would already have // failed, but a probe failure here must not sink the install. return undefined; } } /** * Install the given tools as uv tool environments (shims in ~/.local/bin). * If uv cannot be made available or the install fails, the returned detail * says why and callers fall back to their package-manager recipes. */ export async function uvToolInstall( packages: string[], cwd: string, signal?: AbortSignal, ): Promise { if (packages.length === 0) { return { installed: false, detail: "no uv tool packages requested" }; } const uv = await ensureUv(cwd, signal); if (!uv.installed) { return { installed: false, detail: `uv unavailable: ${uv.detail}` }; } const candidate: InstallCandidate = { label: `uv tool install ${packages.join(" ")}`, command: "uv", args: ["tool", "install", ...packages], }; // Shared by install command: the same `uv tool install ruff` requested // through the ruff CLI runner's recipe shares this one attempt instead // of racing it (the loser would die on "already installed"). return shareInstall(installKey([candidate]), async () => { // uv itself may have been on PATH all along while ~/.local/bin (its // default shim target) is not in the cached extra directories yet. resetExtraToolDirectories(); const outcome = await tryInstallCandidates( [candidate], cwd, signal, // The installed tool itself must run, not just "uv reported success". { command: packages[0], args: ["--version"] }, ); if (outcome.installed) { resetExtraToolDirectories(); for (const pkg of packages) invalidateRunnerAvailability(pkg); } return outcome; }); } /** CustomInstaller factory for LSP servers shipped as uv tools (ty, ruff). */ export function uvToolCustomInstaller( packages: string[], ): ( cwd: string, signal: AbortSignal | undefined, ) => Promise { return async (cwd, signal) => { const outcome = await uvToolInstall(packages, cwd, signal); return { installed: outcome.installed, detail: outcome.detail }; }; }