Skip to content

Open-source, local-first AI agent for real work.

1.9 KB
Raw Blame
import { accessSync, constants, existsSync, statSync } from "node:fs";
import { delimiter, isAbsolute, resolve } from "node:path";

export function findUnixExecutableOnPath(binary: string): string | undefined {
	for (const directory of (process.env.PATH ?? "").split(delimiter)) {
		if (!directory) continue;
		const candidate = resolve(directory, binary);
		try {
			accessSync(candidate, constants.X_OK);
			if (statSync(candidate).isFile()) return candidate;
		} catch {
			// Continue to the next PATH entry.
		}
	}
	return undefined;
}

export type LinuxSandboxBackend = "bundled-bwrap" | "system-bwrap";

interface LinuxBubblewrapBinary {
	readonly path: string;
	readonly backend: LinuxSandboxBackend;
}

export function findLinuxBubblewrapBinary(
	options: { explicitPath?: string; bundledPath?: string } = {},
): LinuxBubblewrapBinary | undefined {
	const configured = options.explicitPath?.trim() || process.env.VETTA_LINUX_BWRAP_PATH?.trim();
	if (configured) {
		const path =
			configured.includes("/") || isAbsolute(configured)
				? resolve(configured)
				: findUnixExecutableOnPath(configured);
		return path ? { path, backend: "system-bwrap" } : undefined;
	}
	if (options.bundledPath && existsSync(options.bundledPath)) {
		return { path: options.bundledPath, backend: "bundled-bwrap" };
	}
	const path = findUnixExecutableOnPath("bwrap") ?? findUnixExecutableOnPath("bubblewrap");
	return path ? { path, backend: "system-bwrap" } : undefined;
}

export function resolveLinuxBubblewrapPath(explicitPath?: string): string {
	const binary = findLinuxBubblewrapBinary({ explicitPath });
	if (!binary) {
		throw new Error(
			"Linux sandbox requires bubblewrap. Install `bwrap`/`bubblewrap` or set VETTA_LINUX_BWRAP_PATH to an executable.",
		);
	}
	if (!existsSync(binary.path)) throw new Error(`Configured Linux sandbox binary does not exist: ${binary.path}`);
	return binary.path;
}