/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * `bxc install` — install BXC runtime assets for the current platform. */ import { dirname, join } from "node:path"; import { chmodSync, existsSync, mkdirSync, renameSync } from "node:fs"; import { ROOT, type CommonOptions, parseCommonArgs, logger } from "./shared.ts"; import { buildRustWorkspace, detectCurlPlatform, installCurlImpersonate, installRustBridge, inspectNativeToolchain, resolveCurlInstallPath, type NativeInstallResult, } from "../native/install.ts"; import { NATIVE_DEPENDENCIES } from "../native/versions.ts"; export interface InstallOptions { dryRun?: boolean; /** Install all prebuilt runtime libraries and build Rust when available. */ full?: boolean; /** Require the source-native build step instead of treating it as optional. */ source?: boolean; /** Verify installation status of all runtime dependencies without writing. */ check?: boolean; } type LightpandaPlatformId = | "x86_64-linux" | "aarch64-linux" | "x86_64-macos" | "aarch64-macos"; interface LightpandaPlatform { id: LightpandaPlatformId; dirName: "linux-x64" | "linux-arm64" | "darwin-x64" | "darwin-arm64"; assetName: string; } import { getBinDir, getVendorDir } from "../utils/paths.ts"; export const VENDOR_DIR = Bun.env.BXC_VENDOR_DIR ?? getVendorDir(); const LIGHTPANDA_TAG = Bun.env.LIGHTPANDA_RELEASE_TAG ?? NATIVE_DEPENDENCIES.lightpandaTag; function printUsage(): void { Bun.stdout.write( `bxc install — install BXC runtime dependencies for the current platform Usage: bxc install [options] Options: --check verify installation status of all runtime dependencies --dry-run show what would be downloaded without writing to disk --full install Lightpanda + curl-impersonate + Rust bridge + embedding models --source require the Rust workspace build (source checkouts only) --models download the local embedding + reranking models (~115 MB, sha256-verified, into ~/.bxc/models or BXC_MODELS_DIR) --help, -h print this help `, ); } /** * Install the embedding and reranking models used for key-less semantic * search (`bxc-embed`). Weights are never embedded in the executable. */ async function installModels(dryRun: boolean): Promise { const { embeddingModelsInfo, installEmbeddingModel } = await import("../embed/native-embedder.ts"); const info = embeddingModelsInfo(); if (!info) { logger.error("This build of the Rust bridge has no embedding support (rebuild with `bun run build:linux`)."); process.exit(1); } for (const model of [info.embed, info.rerank]) { if (!model) continue; if (model.installed) { logger.log(`${model.id}: already installed in ${model.dir}`); continue; } if (dryRun) { logger.log(`[dry-run] would download ${model.id} (${fmtMB(model.sizeBytes)}) -> ${model.dir}`); continue; } logger.log(`Downloading ${model.id} (${fmtMB(model.sizeBytes)})...`); const installed = await installEmbeddingModel(model.id.split("@")[0] as string); logger.log(`${installed.id}: installed in ${installed.dir}`); } } function fmtMB(bytes: number): string { return `${(bytes / 1_048_576).toFixed(1)} MB`; } async function streamDownload( url: string, destPath: string, expectedSize: number, dryRun: boolean, ): Promise { if (dryRun) { logger.log( `[dry-run] would download ${url} -> ${destPath}${expectedSize > 0 ? ` (${fmtMB(expectedSize)})` : ""}`, ); return; } const partial = `${destPath}.partial`; // `dirname` gère `C:\\…` comme `/…` ; `lastIndexOf("/")` renvoyait -1 sous // Windows et produisait un `mkdir ""`. mkdirSync(dirname(destPath), { recursive: true }); const res = await fetch(url, { headers: { "User-Agent": "bxc-install" }, redirect: "follow", }); if (!res.ok || !res.body) { throw new Error(`HTTP ${res.status} downloading ${url}`); } const contentLength = res.headers.get("content-length"); const totalBytes = contentLength ? parseInt(contentLength, 10) : expectedSize; const writer = Bun.file(partial).writer(); let written = 0; let lastPct = -1; const reader = res.body.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) break; writer.write(value); written += value.byteLength; if (totalBytes > 0) { const pct = Math.floor((written / totalBytes) * 100); if (pct !== lastPct && pct % 10 === 0) { Bun.stdout.write( `\r[bxc install] ${fmtMB(written)} / ${fmtMB(totalBytes)} (${pct}%) `, ); lastPct = pct; } } } await writer.flush(); await writer.end(); } catch (err) { try { writer.end(); } catch {} throw err; } Bun.stdout.write("\n"); renameSync(partial, destPath); } export function detectLightpandaPlatform( platform: NodeJS.Platform = process.platform, arch: NodeJS.Architecture = process.arch, ): LightpandaPlatform | null { if (platform === "linux") { if (arch === "x64") return { id: "x86_64-linux", dirName: "linux-x64", assetName: "lightpanda-x86_64-linux", }; if (arch === "arm64") return { id: "aarch64-linux", dirName: "linux-arm64", assetName: "lightpanda-aarch64-linux", }; } if (platform === "darwin") { if (arch === "x64") return { id: "x86_64-macos", dirName: "darwin-x64", assetName: "lightpanda-x86_64-macos", }; if (arch === "arm64") return { id: "aarch64-macos", dirName: "darwin-arm64", assetName: "lightpanda-aarch64-macos", }; } return null; } export function resolveLightpandaPath( platform: LightpandaPlatform, vendorDir: string = VENDOR_DIR, ): string { return join(vendorDir, "lightpanda-bin", platform.dirName, "lightpanda"); } async function fetchLightpandaAsset( platform: LightpandaPlatform, tag: string, ): Promise<{ url: string; size: number } | null> { const overrideUrl = Bun.env.LIGHTPANDA_DOWNLOAD_URL; if (overrideUrl) return { url: overrideUrl, size: 0 }; const apiUrl = `https://api.github.com/repos/lightpanda-io/browser/releases/tags/${encodeURIComponent(tag)}`; try { const res = await fetch(apiUrl, { headers: { "User-Agent": "bxc-install", Accept: "application/vnd.github+json", }, }); if (!res.ok) { logger.warn(`GitHub API ${apiUrl} -> HTTP ${res.status}`); return null; } const body = (await res.json()) as any; const asset = body.assets?.find((a: any) => a.name === platform.assetName); if (!asset) { logger.warn(`No asset '${platform.assetName}' in release '${tag}'.`); return null; } return { url: asset.browser_download_url, size: asset.size }; } catch (error) { logger.warn(`Failed to connect to ${apiUrl}: ${error}`); return null; } } export async function installLightpanda( dryRun = false, vendorDir: string = VENDOR_DIR, ): Promise<{ status: "installed" | "present" | "failed" | "unsupported"; path?: string; }> { const platform = detectLightpandaPlatform(); if (!platform) return { status: "unsupported" }; const destPath = resolveLightpandaPath(platform, vendorDir); const existing = Bun.file(destPath); if (await existing.exists()) { if (existing.size > 0) { logger.log( `Lightpanda already installed: ${destPath} (${fmtMB(existing.size)})`, ); return { status: "present", path: destPath }; } } logger.log( `Fetching Lightpanda release '${LIGHTPANDA_TAG}' for ${platform.dirName}...`, ); const asset = await fetchLightpandaAsset(platform, LIGHTPANDA_TAG); if (!asset) return { status: "failed" }; logger.log(`Downloading Lightpanda: ${asset.url}`); try { await streamDownload(asset.url, destPath, asset.size, dryRun); if (!dryRun) { // Pas de `Bun.$\`chmod\`` : ce n'est pas un builtin du shell Bun et le // binaire n'existe pas sous Windows, où le bit exec n'a pas de sens. if (process.platform !== "win32") chmodSync(destPath, 0o755); logger.log(`Installed Lightpanda: ${destPath}`); } return { status: "installed", path: destPath }; } catch (err) { logger.warn( `Download failed: ${err instanceof Error ? err.message : String(err)}`, ); return { status: "failed" }; } } export async function runInstall( opts: { dryRun?: boolean; full?: boolean; source?: boolean }, vendorDir = VENDOR_DIR, ) { const lightpanda = await installLightpanda(opts.dryRun, vendorDir); if (!opts.full) return { lightpanda }; const curlImpersonate = await installCurlImpersonate(opts.dryRun, vendorDir); const rustBuild = await buildRustWorkspace(opts.dryRun, ROOT); const rust = rustBuild.status === "skipped" ? await installRustBridge(opts.dryRun, getBinDir(), ROOT) : rustBuild; const toolchain = opts.dryRun ? undefined : await inspectNativeToolchain(); return { lightpanda, curlImpersonate, rust, toolchain }; } export async function runCheck(vendorDir: string = VENDOR_DIR): Promise<{ ok: boolean; dependencies: Record; }> { const deps: Record = {}; // 1. Lightpanda const lpPlatform = detectLightpandaPlatform(); if (!lpPlatform) { deps.lightpanda = { ok: true, status: "unsupported on this target (bxc falls back to Chrome / HTTP/2)", }; } else { const lpPath = resolveLightpandaPath(lpPlatform, vendorDir); const file = Bun.file(lpPath); const exists = await file.exists(); deps.lightpanda = { ok: exists && file.size > 0, status: exists && file.size > 0 ? `installed (${fmtMB(file.size)})` : "missing (run `bxc install`)", path: lpPath, }; } // 2. curl-impersonate const curlTarget = detectCurlPlatform(); if (!curlTarget) { deps["curl-impersonate"] = { ok: false, status: "unsupported platform target", }; } else { const curlPath = resolveCurlInstallPath(vendorDir); const exists = curlPath ? existsSync(curlPath) : false; deps["curl-impersonate"] = { ok: exists, status: exists ? "installed" : "missing (run `bxc install --full`)", path: curlPath ?? undefined, }; } // 3. Rust bridge try { const { bridgeAbiVersion, bridgeLibraryPath, BXC_BRIDGE_ABI_VERSION } = await import("../rust/bridge.ts"); const abi = bridgeAbiVersion(); const libPath = bridgeLibraryPath(); deps["rust-bridge"] = { ok: abi === BXC_BRIDGE_ABI_VERSION, status: abi === BXC_BRIDGE_ABI_VERSION ? `loaded (ABI ${abi})` : `ABI mismatch (got ${abi}, expected ${BXC_BRIDGE_ABI_VERSION})`, path: libPath ?? undefined, }; } catch (err) { deps["rust-bridge"] = { ok: false, status: `load failed: ${err instanceof Error ? err.message : String(err)}`, }; } // 4. Embedding & Reranking models try { const { embeddingModelsInfo } = await import("../embed/native-embedder.ts"); const info = embeddingModelsInfo(); if (info) { const embedOk = Boolean(info.embed?.installed); const rerankOk = Boolean(info.rerank?.installed); deps.models = { ok: embedOk && rerankOk, status: embedOk && rerankOk ? "installed in ~/.bxc/models" : "not installed (run `bxc install --models`)", path: info.embed?.dir, }; } } catch { deps.models = { ok: false, status: "embedding support not compiled in Rust bridge", }; } // 5. Chrome / Chromium CDP fallback const chrome = Bun.which("google-chrome") ?? Bun.which("google-chrome-stable") ?? Bun.which("chromium") ?? Bun.which("chromium-browser") ?? Bun.which("chrome"); deps.chrome = { ok: Boolean(chrome), status: chrome ? "detected" : "not found in PATH (CDP profile fallback unavailable)", path: chrome ?? undefined, }; const allOk = Object.values(deps).every((d) => d.ok); Bun.stdout.write(`\n[bxc install --check] Runtime Dependency Status (${process.platform}-${process.arch}):\n\n`); for (const [name, info] of Object.entries(deps)) { const mark = info.ok ? "✓" : "!"; const tag = info.ok ? "OK" : "WARN"; Bun.stdout.write(` [${mark}] ${name.padEnd(18)} : [${tag}] ${info.status}${info.path ? ` -> ${info.path}` : ""}\n`); } Bun.stdout.write("\n"); return { ok: allOk, dependencies: deps }; } export async function main( args: string[], _opts: CommonOptions, ): Promise { if (args.includes("--help") || args.includes("-h")) { printUsage(); return; } if (args.includes("--check")) { const checkResult = await runCheck(VENDOR_DIR); if (!checkResult.ok) process.exit(1); return; } const dryRun = args.includes("--dry-run"); const full = args.includes("--full"); const source = args.includes("--source"); if (args.includes("--models")) { await installModels(dryRun); if (!full) return; } logger.log( `Installing BXC runtime into ${VENDOR_DIR}${full ? " [full]" : ""}${dryRun ? " [dry-run]" : ""}`, ); const result = await runInstall({ dryRun, full, source }, VENDOR_DIR); const lightpanda = result.lightpanda; if (lightpanda.status === "failed") { logger.warn("Lightpanda install failed."); process.exit(1); } else if (lightpanda.status === "unsupported") { // Lightpanda ne publie pas d'asset Windows : ce n'est pas une erreur // d'installation, seulement un profil indisponible sur cette cible. logger.warn( `No Lightpanda release for ${process.platform}/${process.arch} — bxc falls back to the chrome/http profiles.`, ); } else { logger.log("Lightpanda installed successfully."); } if (!full) return; const native = result as typeof result & { curlImpersonate: NativeInstallResult; rust: NativeInstallResult; toolchain?: Awaited>; }; if (native.curlImpersonate.status === "failed") { logger.error(`curl-impersonate install failed: ${native.curlImpersonate.reason ?? "unknown error"}`); process.exit(1); } if (native.curlImpersonate.status === "unsupported") { logger.warn("curl-impersonate has no prebuilt asset for this platform."); } else { logger.log(`curl-impersonate: ${native.curlImpersonate.status}.`); } if (native.rust.status === "failed") { const message = `Rust workspace build failed: ${native.rust.reason ?? "unknown error"}`; if (source) { logger.error(message); process.exit(1); } logger.warn(message); } else if (native.rust.status === "skipped") { const message = "Rust workspace not present; using packaged/embedded native assets when available."; if (source) { logger.error(message); process.exit(1); } logger.log(message); } else { logger.log(`Rust workspace: ${native.rust.status}.`); } if (native.toolchain) { const missing = Object.entries(native.toolchain) .filter(([, value]) => value === null) .map(([name]) => name); if (missing.length > 0) { logger.warn(`Optional native build tools not found: ${missing.join(", ")}.`); } else { logger.log("Native toolchain detected (Rust, Zig and C++/CMake)."); } } // In full mode, also complete models installation if not already installed if (!args.includes("--models")) { try { await installModels(dryRun); } catch (err) { logger.warn(`Optional embedding models install: ${err instanceof Error ? err.message : String(err)}`); } } } if (import.meta.main) { const { opts, remaining } = parseCommonArgs(process.argv.slice(2)); main(remaining, opts).catch((err) => { console.error(err); process.exit(1); }); }