// jdtls custom installer: eclipse.jdt.ls has no package-manager channel (no // winget/npm/pip package), so it gets a dedicated download-and-extract // installer, the same honesty rules as the recipe machinery: // - installs into a managed user directory (~/.pi/agent/lsp), touching // nothing on PATH and never replacing an existing JDK // - verifies after install: the JDK must run and the equinox launcher must // exist, "archive extracted" alone is not success // - download candidates are tried in order (official, then CN mirrors) // - archives are cached in ~/.pi/agent/lsp/archives as offline seeds: // pre-place the official archive files there and installs need no network import { type Dirent, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs"; import os from "node:os"; import path from "node:path"; import process from "node:process"; import { firstSpawnable, safeSpawnAsync, sha256OfFile, spawnOutcomeFailureReason, } from "./runners/helpers.js"; import type { CustomInstallOutcome } from "./types.js"; const MANAGED_ROOT = path.join(os.homedir(), ".pi", "agent", "lsp"); const JDTLS_DIR = path.join(MANAGED_ROOT, "jdtls"); const JDK_DIR = path.join(MANAGED_ROOT, "jdk-21"); const WRAPPER_PATH = path.join(JDTLS_DIR, "bin", "jdtls.cmd"); const ARCHIVES_DIR = path.join(MANAGED_ROOT, "archives"); const WORKSPACE_DATA_ROOT = path.join(os.tmpdir(), "pi-lsp-jdtls"); const WORKSPACE_DATA_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; /** Environment variable through which pi-lsp hands the wrapper its -data dir. */ const DATA_DIR_ENV = "PI_LSP_JDTLS_DATA"; const DOWNLOAD_TIMEOUT_MS = 600_000; const EXTRACT_TIMEOUT_MS = 300_000; const SPAWN_TIMEOUT_MS = 60_000; // Node's spawn does not reliably resolve bare names on Windows (and Git Bash // environments put msys curl first anyway), so prefer the system binaries. const SYSTEM32 = path.join(process.env.SystemRoot ?? "C:\\Windows", "System32"); const CURL_CANDIDATES = [path.join(SYSTEM32, "curl.exe"), "curl"]; const TAR_CANDIDATES = [path.join(SYSTEM32, "tar.exe"), "tar"]; // --- Paths exposed for config --- export function jdtlsWrapperCommand(): string { return WRAPPER_PATH; } // --- Per-workspace data directory (computed on the Node side) --- /** * Stable per-workspace -data directory under %TEMP%\pi-lsp-jdtls. The key is * derived from the workspace path with casing folded: Windows paths are * case-insensitive, so two spellings of the same workspace must share one * data directory. The wrapper receives the directory through * PI_LSP_JDTLS_DATA — an environment value never passes through cmd.exe * parsing, so workspace paths containing &, ^, ! or non-ASCII characters * survive intact. */ function workspaceDataDir(cwd: string): string { const key = cwd.toLowerCase().replace(/:/g, "").replace(/\\/g, "_"); return path.join(WORKSPACE_DATA_ROOT, key); } /** * Extra spawn environment for jdtls: the per-workspace data directory plus a * UTF-8 recency marker for the stale-data sweep. Both the mkdir and the * marker are written here, by Node, instead of by the old cmd echo — which * mis-encoded non-ASCII paths and had no quoting defense against & in paths. */ export function jdtlsSpawnEnv(cwd: string): Record { const dataDir = workspaceDataDir(cwd); mkdirSync(dataDir, { recursive: true }); writeFileSync(path.join(dataDir, ".workspace"), `${cwd}\n`, "utf8"); return { [DATA_DIR_ENV]: dataDir }; } /** * Remove per-workspace jdtls -data dirs that are no longer in use: a data dir * is stale when its recorded workspace path is gone, or when nothing launched * it for 30 days. Best-effort; locked dirs survive until the next sweep. */ export function sweepJdtlsWorkspaceData( now: number = Date.now(), root: string = WORKSPACE_DATA_ROOT, ): void { let entries: Dirent[]; try { entries = readdirSync(root, { withFileTypes: true }); } catch { return; // No data root (jdtls never ran on this machine). } for (const entry of entries) { if (!entry.isDirectory()) continue; const dir = path.join(root, entry.name); if (!isStaleWorkspaceData(dir, now)) continue; try { rmSync(dir, { recursive: true, force: true }); } catch { // In use or locked; the next sweep retries. } } } function isStaleWorkspaceData(dir: string, now: number): boolean { try { // The wrapper rewrites this marker on every launch with the workspace // path it was spawned from. const marker = readFileSync(path.join(dir, ".workspace"), "utf8").trim(); if (marker.length > 0) { if (existsSync(marker)) return now - statSync(dir).mtimeMs > WORKSPACE_DATA_MAX_AGE_MS; // A marker that does not even look like a path is decoding garbage // (written by the older cmd echo wrapper in a non-UTF-8 code page). // It must not read as "workspace gone": fall through to the age // check so an in-use data directory survives an upgrade. if (/^([a-zA-Z]:\\|\\\\)/.test(marker)) return true; // workspace gone } } catch { // Pre-marker layout: fall through to age-based staleness. } try { return now - statSync(dir).mtimeMs > WORKSPACE_DATA_MAX_AGE_MS; } catch { return false; } } /** Cheap structural probe: launcher jar, managed JDK and a current wrapper exist. */ export function jdtlsInstalled(): boolean { // The wrapper no longer bakes in absolute paths (it expands %USERPROFILE% // at runtime), so identity is checked by its marker lines: a wrapper from // an older layout lacks them and gets regenerated. try { const wrapper = readFileSync(WRAPPER_PATH, "utf8"); if (!wrapper.includes("jdk-21") || !wrapper.includes(DATA_DIR_ENV)) return false; } catch { return false; } if (!existsSync(path.join(JDK_DIR, "bin", "java.exe"))) return false; return findLauncherJar() !== undefined; } // --- Install steps --- export async function ensureJdtlsInstalled( _cwd: string, signal: AbortSignal | undefined, ): Promise { // The managed layout (jdtls.cmd wrapper, java.exe, windows JDK archives) is // Windows-only; elsewhere, fail honestly instead of downloading a Windows // JDK that can never run. if (process.platform !== "win32") { return { installed: false, detail: "jdtls auto-install is Windows-only; install Eclipse JDT.LS and a JDK 21 manually", }; } // spawn fails with ENOENT when cwd does not exist, so create the managed // root before any download/extract step runs there. mkdirSync(MANAGED_ROOT, { recursive: true }); mkdirSync(ARCHIVES_DIR, { recursive: true }); if (jdtlsInstalled()) return { installed: true, detail: "already installed" }; // jdtlsInstalled() also fails when only the wrapper is stale (it bakes in // absolute paths, e.g. after a MANAGED_ROOT relocation). When the launcher // jar and managed JDK are still intact, regenerate the wrapper instead of // re-downloading the whole distribution. if ( findLauncherJar() !== undefined && existsSync(path.join(JDK_DIR, "bin", "java.exe")) ) { writeWrapper(); if (jdtlsInstalled()) { return { installed: true, detail: "regenerated launcher wrapper" }; } } const attempts: string[] = []; try { await ensureJdk(signal, attempts); await ensureJdtlsDistribution(signal, attempts); writeWrapper(); } catch (error) { const message = error instanceof Error ? error.message : String(error); return { installed: false, detail: [...attempts, message].join("; ") }; } // Post-install verification: the launcher jar must be resolvable and the // managed JDK must actually run (a broken extract would fail here). const launcher = findLauncherJar(); if (!launcher) { return { installed: false, detail: `${attempts.join("; ")}; verification failed: no equinox launcher jar in ${JDTLS_DIR}/plugins`, }; } const javaCheck = await safeSpawnAsync( path.join(JDK_DIR, "bin", "java.exe"), ["-version"], { cwd: MANAGED_ROOT, timeoutMs: SPAWN_TIMEOUT_MS, signal, }, ); if (javaCheck.exitCode !== 0) { return { installed: false, detail: `${attempts.join("; ")}; verification failed: managed JDK did not run (${spawnOutcomeFailureReason(javaCheck)})`, }; } return { installed: true, detail: `[auto-installed] jdtls ${attempts.length ? `(${attempts.join("; ")})` : ""}`.trim(), }; } async function ensureJdk( signal: AbortSignal | undefined, attempts: string[], ): Promise { if (existsSync(path.join(JDK_DIR, "bin", "java.exe"))) return; const staging = path.join(MANAGED_ROOT, "jdk-staging"); rmSync(staging, { recursive: true, force: true }); const seed = findSeedArchive(JDK_ARCHIVE_PATTERN); let archive: string; if (seed) { archive = seed; attempts.push("jdk from local seed archive"); } else { const discovered = await discoverJdkDownload(signal, attempts); archive = path.join(ARCHIVES_DIR, discovered.filename); const usedUrl = await download(discovered.urls, archive, signal); attempts.push( `jdk downloaded from ${shortUrl(usedUrl)} (archived for offline reuse)`, ); await verifyArchiveChecksum(archive, discovered.sha256, "jdk", attempts); } await extract(archive, staging, signal); rmSync(JDK_DIR, { recursive: true, force: true }); renameSync(resolveDistributionRoot(staging), JDK_DIR); rmSync(staging, { recursive: true, force: true }); } async function ensureJdtlsDistribution( signal: AbortSignal | undefined, attempts: string[], ): Promise { const staging = path.join(MANAGED_ROOT, "jdtls-staging"); rmSync(staging, { recursive: true, force: true }); const seed = findSeedArchive(JDTLS_ARCHIVE_PATTERN); let archive: string; if (seed) { archive = seed; attempts.push("eclipse.jdt.ls from local seed archive"); } else { const discovered = await discoverJdtlsDownload(signal, attempts); archive = path.join(ARCHIVES_DIR, discovered.filename); const usedUrl = await download(discovered.urls, archive, signal); attempts.push( `jdtls downloaded from ${shortUrl(usedUrl)} (archived for offline reuse)`, ); // eclipse.org publishes .sha256 sidecar files; when the mirror chain // does not, the download is recorded honestly as unverified instead // of silently passing. const publishedSha256 = await tryFetchChecksum(`${usedUrl}.sha256`, signal); await verifyArchiveChecksum(archive, publishedSha256, "jdtls", attempts); } await extract(archive, staging, signal); rmSync(JDTLS_DIR, { recursive: true, force: true }); renameSync(resolveDistributionRoot(staging), JDTLS_DIR); rmSync(staging, { recursive: true, force: true }); } function shortUrl(url: string | undefined): string { if (!url) return "unknown source"; try { const parsed = new URL(url); return `${parsed.host}${parsed.pathname}`; } catch { return url; } } // --- Archive integrity --- /** Best-effort fetch of a published sidecar checksum; undefined when absent. */ async function tryFetchChecksum( url: string, signal: AbortSignal | undefined, ): Promise { // Same candidate chain as download(): a bare "curl" can resolve to an // msys binary that mishandles the URL, System32's never does. const curl = await firstSpawnable( CURL_CANDIDATES, MANAGED_ROOT, SPAWN_TIMEOUT_MS, ); const outcome = await safeSpawnAsync( curl, ["-fsSL", "--connect-timeout", "20", url], { cwd: MANAGED_ROOT, timeoutMs: SPAWN_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; } /** * Verify a downloaded archive against its published sha256 and delete it on * mismatch: an archive that will be extracted and executed must never pass * on "the download said 200 OK" alone. Local seed archives are user-placed * and skip verification. */ async function verifyArchiveChecksum( archive: string, expectedSha256: string | undefined, label: string, attempts: string[], ): Promise { if (!expectedSha256) return; const actual = await sha256OfFile(archive); if (actual === expectedSha256.toLowerCase()) { attempts.push(`${label} archive checksum verified`); return; } rmSync(archive, { force: true }); throw new Error( `${label} archive checksum mismatch (expected ${expectedSha256}, got ${actual}); archive deleted`, ); } // --- Offline seeds --- const JDK_ARCHIVE_PATTERN = /^OpenJDK21U-jdk_x64_windows_hotspot_[\w.]+\.zip$/; const JDTLS_ARCHIVE_PATTERN = /^jdt-language-server-[\w.-]+\.tar\.gz$/; /** Newest matching archive in the offline seed directory (numeric-aware version order). */ export function findSeedArchive( pattern: RegExp, dir: string = ARCHIVES_DIR, ): string | undefined { try { // Plain alphabetical order misorders versions ("21.0.12" < "21.0.9" // as strings), so compare the embedded number runs instead. const seeds = readdirSync(dir).filter((name) => pattern.test(name)); seeds.sort(compareVersionish); return seeds.length > 0 ? path.join(dir, seeds[0]) : undefined; } catch { return undefined; } } function compareVersionish(left: string, right: string): number { const leftNumbers = left.match(/\d+/g) ?? []; const rightNumbers = right.match(/\d+/g) ?? []; for ( let index = 0; index < Math.max(leftNumbers.length, rightNumbers.length); index += 1 ) { // Descending: the newest (largest version) file sorts first. const delta = Number(rightNumbers[index] ?? 0) - Number(leftNumbers[index] ?? 0); if (delta !== 0) return delta; } return left.localeCompare(right); } // --- Discovery (always latest stable; mirrors as fallback candidates) --- async function fetchText( url: string, signal: AbortSignal | undefined, ): Promise { // Same candidate chain as download(): a bare "curl" can resolve to an // msys binary that mishandles the URL, System32's never does. const curl = await firstSpawnable( CURL_CANDIDATES, MANAGED_ROOT, SPAWN_TIMEOUT_MS, ); const outcome = await safeSpawnAsync( curl, ["-fsSL", "--connect-timeout", "20", url], { cwd: MANAGED_ROOT, timeoutMs: SPAWN_TIMEOUT_MS, signal, }, ); if (outcome.exitCode !== 0) throw new Error(`curl ${url} exit ${outcome.exitCode}`); return outcome.stdout; } async function download( urls: string[], dest: string, signal: AbortSignal | undefined, ): Promise { const problems: string[] = []; const curl = await firstSpawnable(CURL_CANDIDATES, MANAGED_ROOT); // Download to a temp name and rename on success: a killed process must not // leave a partial archive behind that findSeedArchive would later accept // as a valid offline seed. const partial = `${dest}.part`; for (const candidate of urls) { const outcome = await safeSpawnAsync( curl, [ "-fL", "--retry", "2", "--connect-timeout", "20", "-o", partial, candidate, ], { cwd: MANAGED_ROOT, timeoutMs: DOWNLOAD_TIMEOUT_MS, signal }, ); if (outcome.aborted) { rmSync(partial, { force: true }); throw new Error(`download aborted: ${candidate}`); } if (!outcome.timedOut && outcome.exitCode === 0) { rmSync(dest, { force: true }); renameSync(partial, dest); return candidate; } problems.push(`${candidate} → ${spawnOutcomeFailureReason(outcome)}`); rmSync(partial, { force: true }); } throw new Error(`download failed: ${problems.join("; ")}`); } interface ArchiveDownload { filename: string; urls: string[]; /** Published sha256 of the archive, when the source provides one. */ sha256?: string; } async function discoverJdkDownload( signal: AbortSignal | undefined, attempts: string[], ): Promise { // Adoptium's JSON API names the exact asset and always points at the // latest GA 21 build; the Tsinghua mirror serves the same file as fallback. const apiAsset = "https://api.adoptium.net/v3/assets/latest/21/hotspot?os=windows&architecture=x64&image_type=jdk"; try { // Through fetchText, not fetch(): the curl candidate chain carries // the documented msys-curl fix, and the spawn timeout bounds a hung // request (fetch alone only respected the caller's abort signal). const assets = JSON.parse(await fetchText(apiAsset, signal)) as Array<{ binary?: { package?: { name?: string; link?: string; checksum?: string }; }; }>; const pkg = assets .map((asset) => asset.binary?.package) .find((pkg) => pkg?.name?.endsWith(".zip")); if (pkg?.name && pkg.link) { attempts.push("jdk source: adoptium api + tsinghua mirror"); return { filename: pkg.name, urls: [ pkg.link, `https://mirrors.tuna.tsinghua.edu.cn/Adoptium/21/jdk/x64/windows/${pkg.name}`, ], sha256: pkg.checksum, }; } throw new Error("no zip package in adoptium response"); } catch (error) { // Without the JSON API the exact filename is unknown, so the Tsinghua // directory listing must provide it. const reason = error instanceof Error ? error.message : String(error); const listing = await fetchText( "https://mirrors.tuna.tsinghua.edu.cn/Adoptium/21/jdk/x64/windows/", signal, ); const filename = listing.match( /OpenJDK21U-jdk_x64_windows_hotspot_[\w.]+\.zip/, )?.[0]; if (!filename) throw new Error( `jdk discovery failed (${reason}) and mirror listing had no zip`, ); attempts.push("jdk source: tsinghua mirror listing"); return { filename, urls: [ `https://mirrors.tuna.tsinghua.edu.cn/Adoptium/21/jdk/x64/windows/${filename}`, ], }; } } async function discoverJdtlsDownload( signal: AbortSignal | undefined, attempts: string[], ): Promise { const listing = await fetchText( "https://download.eclipse.org/jdtls/milestones/", signal, ); const versions = [ ...listing.matchAll(/jdtls\/milestones\/(\d+\.\d+\.\d+)/g), ].map((match) => match[1]); const version = highestVersion(versions); if (!version) throw new Error("could not discover latest eclipse.jdt.ls milestone"); const versionListing = await fetchText( `https://download.eclipse.org/jdtls/milestones/${version}/`, signal, ); const archive = versionListing.match( /jdt-language-server-\d+\.\d+\.\d+-\d+\.tar\.gz/, )?.[0]; if (!archive) throw new Error( `no jdt-language-server archive found for milestone ${version}`, ); attempts.push("jdtls source: eclipse.org + ustc mirror"); return { filename: archive, urls: [ `https://download.eclipse.org/jdtls/milestones/${version}/${archive}`, `https://mirrors.ustc.edu.cn/eclipse/jdtls/milestones/${version}/${archive}`, ], }; } function highestVersion(versions: string[]): string | undefined { const key = (version: string) => version.split(".").map((part) => Number.parseInt(part, 10) || 0); return versions.sort((left, right) => { const leftKey = key(left); const rightKey = key(right); for (let index = 0; index < 3; index += 1) { const delta = (rightKey[index] ?? 0) - (leftKey[index] ?? 0); if (delta !== 0) return delta; } return 0; })[0]; } // --- Launcher wrapper --- /** Wrapper batch lines, exported for tests to assert its invariants. */ export function wrapperLines(): string[] { return [ "@echo off", "setlocal", // Pure-ASCII wrapper: paths expand at runtime from %USERPROFILE%, so // the batch file itself never carries non-ASCII bytes (cmd.exe parses // batch files in the OEM code page, not UTF-8 — a Chinese-username // install path previously decoded to garbage here). 'set "PI_LSP_ROOT=%USERPROFILE%\\.pi\\agent\\lsp"', 'set "JAVA_EXE=%PI_LSP_ROOT%\\jdk-21\\bin\\java.exe"', 'set "JDTLS_HOME=%PI_LSP_ROOT%\\jdtls"', 'if not exist "%JAVA_EXE%" (', ' echo jdtls: managed JDK missing at "%JAVA_EXE%" 1>&2', " exit /b 1", ")", 'set "LAUNCHER="', 'for %%f in ("%JDTLS_HOME%\\plugins\\org.eclipse.equinox.launcher_*.jar") do set "LAUNCHER=%%f"', "if not defined LAUNCHER (", " echo jdtls: equinox launcher jar not found under %JDTLS_HOME%\\plugins 1>&2", " exit /b 1", ")", // The per-workspace -data dir is computed and created by pi-lsp and // passed in through the environment: an env value bypasses cmd.exe // parsing entirely, so workspace paths containing &, ^, !, or // non-ASCII characters survive. No delayed expansion anywhere: it // would eat ! characters from such paths. "if not defined PI_LSP_JDTLS_DATA (", " echo jdtls: PI_LSP_JDTLS_DATA is not set; launch jdtls through pi-lsp 1>&2", " exit /b 1", ")", 'if not exist "%PI_LSP_JDTLS_DATA%" mkdir "%PI_LSP_JDTLS_DATA%"', '"%JAVA_EXE%" -Declipse.application=org.eclipse.jdt.ls.core.id1 -Declipse.product=org.eclipse.jdt.ls.core.product -Dosgi.checkConfiguration=true -Dosgi.sharedConfiguration.area="%JDTLS_HOME%\\config_win" -Dosgi.sharedConfiguration.area.readOnly=true -Dosgi.configuration.cascaded=true -Xms256m -Xmx2g --add-modules=ALL-SYSTEM --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED -jar "%LAUNCHER%" -data "%PI_LSP_JDTLS_DATA%" %*', ]; } function writeWrapper(): void { mkdirSync(path.dirname(WRAPPER_PATH), { recursive: true }); // CRLF line endings: cmd.exe batch parsing is strict about them. writeFileSync(WRAPPER_PATH, `${wrapperLines().join("\r\n")}\r\n`, "utf8"); } function findLauncherJar(): string | undefined { const plugins = path.join(JDTLS_DIR, "plugins"); if (!existsSync(plugins)) return undefined; return readdirSync(plugins).find( (name) => name.startsWith("org.eclipse.equinox.launcher_") && name.endsWith(".jar"), ); } /** Archives either wrap their contents in one root dir or extract bare (eclipse.jdt.ls). */ function resolveDistributionRoot(directory: string): string { const entries = readdirSync(directory, { withFileTypes: true }).filter( (entry) => entry.isDirectory(), ); if (entries.length === 0) throw new Error(`extracted archive is empty: ${directory}`); if ( entries.length === 1 && existsSync(path.join(directory, entries[0].name, "bin")) ) { return path.join(directory, entries[0].name); } return directory; } // --- Spawn helper --- async function extract( archive: string, dest: string, signal: AbortSignal | undefined, ): Promise { mkdirSync(dest, { recursive: true }); // bsdtar (Windows system tar) handles both .zip and .tar.gz. const tar = await firstSpawnable(TAR_CANDIDATES, MANAGED_ROOT); const outcome = await safeSpawnAsync(tar, ["-xf", archive, "-C", dest], { cwd: MANAGED_ROOT, timeoutMs: EXTRACT_TIMEOUT_MS, signal, }); if (outcome.aborted) throw new Error(`extract aborted: ${archive}`); if (outcome.timedOut) throw new Error(`extract timed out: ${archive}`); if (outcome.exitCode !== 0) { throw new Error( `extract failed (exit ${outcome.exitCode}): ${outcome.stderr.trim().slice(0, 200)}`, ); } }