tools-manager.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import chalk from "chalk";
  2. import { type SpawnSyncReturns, spawnSync } from "child_process";
  3. import { chmodSync, createWriteStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync } from "fs";
  4. import { arch, platform } from "os";
  5. import { join } from "path";
  6. import { Readable } from "stream";
  7. import { pipeline } from "stream/promises";
  8. import { APP_NAME, getBinDir } from "../config.ts";
  9. const TOOLS_DIR = getBinDir();
  10. const NETWORK_TIMEOUT_MS = 10_000;
  11. const DOWNLOAD_TIMEOUT_MS = 120_000;
  12. function isOfflineModeEnabled(): boolean {
  13. const value = process.env.PI_OFFLINE;
  14. if (!value) return false;
  15. return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";
  16. }
  17. interface ToolConfig {
  18. name: string;
  19. repo: string; // GitHub repo (e.g., "sharkdp/fd")
  20. binaryName: string; // Name of the binary inside the archive
  21. systemBinaryNames?: string[]; // Alternative system command names to try before downloading
  22. tagPrefix: string; // Prefix for tags (e.g., "v" for v1.0.0, "" for 1.0.0)
  23. getAssetName: (version: string, plat: string, architecture: string) => string | null;
  24. }
  25. const TOOLS: Record<string, ToolConfig> = {
  26. fd: {
  27. name: "fd",
  28. repo: "sharkdp/fd",
  29. binaryName: "fd",
  30. systemBinaryNames: ["fd", "fdfind"],
  31. tagPrefix: "v",
  32. getAssetName: (version, plat, architecture) => {
  33. if (plat === "darwin") {
  34. const archStr = architecture === "arm64" ? "aarch64" : "x86_64";
  35. return `fd-v${version}-${archStr}-apple-darwin.tar.gz`;
  36. } else if (plat === "linux") {
  37. const archStr = architecture === "arm64" ? "aarch64" : "x86_64";
  38. return `fd-v${version}-${archStr}-unknown-linux-gnu.tar.gz`;
  39. } else if (plat === "win32") {
  40. const archStr = architecture === "arm64" ? "aarch64" : "x86_64";
  41. return `fd-v${version}-${archStr}-pc-windows-msvc.zip`;
  42. }
  43. return null;
  44. },
  45. },
  46. rg: {
  47. name: "ripgrep",
  48. repo: "BurntSushi/ripgrep",
  49. binaryName: "rg",
  50. tagPrefix: "",
  51. getAssetName: (version, plat, architecture) => {
  52. if (plat === "darwin") {
  53. const archStr = architecture === "arm64" ? "aarch64" : "x86_64";
  54. return `ripgrep-${version}-${archStr}-apple-darwin.tar.gz`;
  55. } else if (plat === "linux") {
  56. if (architecture === "arm64") {
  57. return `ripgrep-${version}-aarch64-unknown-linux-gnu.tar.gz`;
  58. }
  59. return `ripgrep-${version}-x86_64-unknown-linux-musl.tar.gz`;
  60. } else if (plat === "win32") {
  61. const archStr = architecture === "arm64" ? "aarch64" : "x86_64";
  62. return `ripgrep-${version}-${archStr}-pc-windows-msvc.zip`;
  63. }
  64. return null;
  65. },
  66. },
  67. };
  68. // Check if a command exists in PATH by trying to run it
  69. function commandExists(cmd: string): boolean {
  70. try {
  71. const result = spawnSync(cmd, ["--version"], { stdio: "pipe" });
  72. // Check for ENOENT error (command not found)
  73. return result.error === undefined || result.error === null;
  74. } catch {
  75. return false;
  76. }
  77. }
  78. // Get the path to a tool (system-wide or in our tools dir)
  79. export function getToolPath(tool: "fd" | "rg"): string | null {
  80. const config = TOOLS[tool];
  81. if (!config) return null;
  82. // Check our tools directory first
  83. const localPath = join(TOOLS_DIR, config.binaryName + (platform() === "win32" ? ".exe" : ""));
  84. if (existsSync(localPath)) {
  85. return localPath;
  86. }
  87. // Check system PATH - if found, just return the command name (it's in PATH)
  88. const systemBinaryNames = config.systemBinaryNames ?? [config.binaryName];
  89. for (const systemBinaryName of systemBinaryNames) {
  90. if (commandExists(systemBinaryName)) {
  91. return systemBinaryName;
  92. }
  93. }
  94. return null;
  95. }
  96. // Fetch latest release version from GitHub
  97. async function getLatestVersion(repo: string): Promise<string> {
  98. const response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, {
  99. headers: { "User-Agent": `${APP_NAME}-coding-agent` },
  100. signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS),
  101. });
  102. if (!response.ok) {
  103. throw new Error(`GitHub API error: ${response.status}`);
  104. }
  105. const data = (await response.json()) as { tag_name: string };
  106. return data.tag_name.replace(/^v/, "");
  107. }
  108. // Download a file from URL
  109. async function downloadFile(url: string, dest: string): Promise<void> {
  110. const response = await fetch(url, {
  111. signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
  112. });
  113. if (!response.ok) {
  114. throw new Error(`Failed to download: ${response.status}`);
  115. }
  116. if (!response.body) {
  117. throw new Error("No response body");
  118. }
  119. const fileStream = createWriteStream(dest);
  120. await pipeline(Readable.fromWeb(response.body as any), fileStream);
  121. }
  122. function findBinaryRecursively(rootDir: string, binaryFileName: string): string | null {
  123. const stack: string[] = [rootDir];
  124. while (stack.length > 0) {
  125. const currentDir = stack.pop();
  126. if (!currentDir) continue;
  127. const entries = readdirSync(currentDir, { withFileTypes: true });
  128. for (const entry of entries) {
  129. const fullPath = join(currentDir, entry.name);
  130. if (entry.isFile() && entry.name === binaryFileName) {
  131. return fullPath;
  132. }
  133. if (entry.isDirectory()) {
  134. stack.push(fullPath);
  135. }
  136. }
  137. }
  138. return null;
  139. }
  140. function formatSpawnFailure(result: SpawnSyncReturns<Buffer>): string {
  141. if (result.error?.message) {
  142. return result.error.message;
  143. }
  144. const stderr = result.stderr?.toString().trim();
  145. if (stderr) {
  146. return stderr;
  147. }
  148. const stdout = result.stdout?.toString().trim();
  149. if (stdout) {
  150. return stdout;
  151. }
  152. return `exit status ${result.status ?? "unknown"}`;
  153. }
  154. function runExtractionCommand(command: string, args: string[]): string | null {
  155. const result = spawnSync(command, args, { stdio: "pipe" });
  156. if (!result.error && result.status === 0) {
  157. return null;
  158. }
  159. return `${command}: ${formatSpawnFailure(result)}`;
  160. }
  161. function extractTarGzArchive(archivePath: string, extractDir: string, assetName: string): void {
  162. const failure = runExtractionCommand("tar", ["xzf", archivePath, "-C", extractDir]);
  163. if (failure) {
  164. throw new Error(`Failed to extract ${assetName}: ${failure}`);
  165. }
  166. }
  167. function getWindowsTarCommand(): string {
  168. const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;
  169. if (systemRoot) {
  170. const systemTar = join(systemRoot, "System32", "tar.exe");
  171. if (existsSync(systemTar)) {
  172. return systemTar;
  173. }
  174. }
  175. return "tar.exe";
  176. }
  177. function extractZipArchive(archivePath: string, extractDir: string, assetName: string): void {
  178. const failures: string[] = [];
  179. if (platform() === "win32") {
  180. // Windows ships bsdtar as tar.exe, which supports zip files. Prefer the
  181. // System32 binary over Git Bash's GNU tar, which does not handle zip archives.
  182. const tarFailure = runExtractionCommand(getWindowsTarCommand(), ["xf", archivePath, "-C", extractDir]);
  183. if (!tarFailure) return;
  184. failures.push(tarFailure);
  185. const script =
  186. "& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }";
  187. const powershellFailure = runExtractionCommand("powershell.exe", [
  188. "-NoLogo",
  189. "-NoProfile",
  190. "-NonInteractive",
  191. "-ExecutionPolicy",
  192. "Bypass",
  193. "-Command",
  194. script,
  195. archivePath,
  196. extractDir,
  197. ]);
  198. if (!powershellFailure) return;
  199. failures.push(powershellFailure);
  200. } else {
  201. const unzipFailure = runExtractionCommand("unzip", ["-q", archivePath, "-d", extractDir]);
  202. if (!unzipFailure) return;
  203. failures.push(unzipFailure);
  204. const tarFailure = runExtractionCommand("tar", ["xf", archivePath, "-C", extractDir]);
  205. if (!tarFailure) return;
  206. failures.push(tarFailure);
  207. }
  208. throw new Error(`Failed to extract ${assetName}: ${failures.join("; ")}`);
  209. }
  210. // Download and install a tool
  211. async function downloadTool(tool: "fd" | "rg"): Promise<string> {
  212. const config = TOOLS[tool];
  213. if (!config) throw new Error(`Unknown tool: ${tool}`);
  214. const plat = platform();
  215. const architecture = arch();
  216. // Get latest version
  217. let version = await getLatestVersion(config.repo);
  218. if (tool === "fd" && plat === "darwin" && architecture === "x64") {
  219. version = "10.3.0";
  220. }
  221. // Get asset name for this platform
  222. const assetName = config.getAssetName(version, plat, architecture);
  223. if (!assetName) {
  224. throw new Error(`Unsupported platform: ${plat}/${architecture}`);
  225. }
  226. // Create tools directory
  227. mkdirSync(TOOLS_DIR, { recursive: true });
  228. const downloadUrl = `https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`;
  229. const archivePath = join(TOOLS_DIR, assetName);
  230. const binaryExt = plat === "win32" ? ".exe" : "";
  231. const binaryPath = join(TOOLS_DIR, config.binaryName + binaryExt);
  232. // Download
  233. await downloadFile(downloadUrl, archivePath);
  234. // Extract into a unique temp directory. fd and rg downloads can run concurrently
  235. // during startup, so sharing a fixed directory causes races.
  236. const extractDir = join(
  237. TOOLS_DIR,
  238. `extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
  239. );
  240. mkdirSync(extractDir, { recursive: true });
  241. try {
  242. if (assetName.endsWith(".tar.gz")) {
  243. extractTarGzArchive(archivePath, extractDir, assetName);
  244. } else if (assetName.endsWith(".zip")) {
  245. extractZipArchive(archivePath, extractDir, assetName);
  246. } else {
  247. throw new Error(`Unsupported archive format: ${assetName}`);
  248. }
  249. // Find the binary in extracted files. Some archives contain files directly
  250. // at root, others nest under a versioned subdirectory.
  251. const binaryFileName = config.binaryName + binaryExt;
  252. const extractedDir = join(extractDir, assetName.replace(/\.(tar\.gz|zip)$/, ""));
  253. const extractedBinaryCandidates = [join(extractedDir, binaryFileName), join(extractDir, binaryFileName)];
  254. let extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync(candidate));
  255. if (!extractedBinary) {
  256. extractedBinary = findBinaryRecursively(extractDir, binaryFileName) ?? undefined;
  257. }
  258. if (extractedBinary) {
  259. renameSync(extractedBinary, binaryPath);
  260. } else {
  261. throw new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);
  262. }
  263. // Make executable (Unix only)
  264. if (plat !== "win32") {
  265. chmodSync(binaryPath, 0o755);
  266. }
  267. } finally {
  268. // Cleanup
  269. rmSync(archivePath, { force: true });
  270. rmSync(extractDir, { recursive: true, force: true });
  271. }
  272. return binaryPath;
  273. }
  274. // Termux package names for tools
  275. const TERMUX_PACKAGES: Record<string, string> = {
  276. fd: "fd",
  277. rg: "ripgrep",
  278. };
  279. // Ensure a tool is available, downloading if necessary
  280. // Returns the path to the tool, or null if unavailable
  281. export async function ensureTool(tool: "fd" | "rg", silent: boolean = false): Promise<string | undefined> {
  282. const existingPath = getToolPath(tool);
  283. if (existingPath) {
  284. return existingPath;
  285. }
  286. const config = TOOLS[tool];
  287. if (!config) return undefined;
  288. if (isOfflineModeEnabled()) {
  289. if (!silent) {
  290. console.log(chalk.yellow(`${config.name} not found. Offline mode enabled, skipping download.`));
  291. }
  292. return undefined;
  293. }
  294. // On Android/Termux, Linux binaries don't work due to Bionic libc incompatibility.
  295. // Users must install via pkg.
  296. if (platform() === "android") {
  297. const pkgName = TERMUX_PACKAGES[tool] ?? tool;
  298. if (!silent) {
  299. console.log(chalk.yellow(`${config.name} not found. Install with: pkg install ${pkgName}`));
  300. }
  301. return undefined;
  302. }
  303. // Tool not found - download it
  304. if (!silent) {
  305. console.log(chalk.dim(`${config.name} not found. Downloading...`));
  306. }
  307. try {
  308. const path = await downloadTool(tool);
  309. if (!silent) {
  310. console.log(chalk.dim(`${config.name} installed to ${path}`));
  311. }
  312. return path;
  313. } catch (e) {
  314. if (!silent) {
  315. console.log(chalk.yellow(`Failed to download ${config.name}: ${e instanceof Error ? e.message : e}`));
  316. }
  317. return undefined;
  318. }
  319. }