repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/uv/index.ts

Raw
File outline
import { constants } from "node:fs";
import { access } from "node:fs/promises";
import { delimiter, join } from "node:path";
import {
	type BashSpawnContext,
	createBashTool,
	type ExtensionAPI,
} from "@earendil-works/pi-coding-agent";

const INTERCEPTED_COMMANDS_PATH = join(
	import.meta.dirname,
	"intercepted-commands",
);

async function uvInstalled(
	env = process.env,
	platform = process.platform,
): Promise<boolean> {
	const names = platform === "win32" ? ["uv.exe", "uv.cmd", "uv.bat"] : ["uv"];
	const mode = platform === "win32" ? constants.F_OK : constants.X_OK;
	for (const directory of (env[pathEnvKey(env)] ?? "").split(delimiter)) {
		for (const name of names) {
			try {
				await access(join(directory.replace(/^"|"$/gu, ""), name), mode);
				return true;
			} catch {}
		}
	}
	return false;
}

function pathEnvKey(env: NodeJS.ProcessEnv): string {
	return Object.keys(env).find((key) => key.toLowerCase() === "path") ?? "PATH";
}

function prependInterceptedCommands(
	ctx: BashSpawnContext,
	platform = process.platform,
): BashSpawnContext {
	if (platform === "win32") return ctx;
	const key = pathEnvKey(ctx.env);
	const path = [INTERCEPTED_COMMANDS_PATH, ctx.env[key]]
		.filter(Boolean)
		.join(delimiter);
	return { ...ctx, env: { ...ctx.env, [key]: path } };
}

function blocked(message: string, ...body: string[]): string {
	return [
		`Error: ${message}. Use uv instead:`,
		"",
		...body.map((line) => `  ${line}`),
		"",
	].join("\n");
}

function getBlockedCommandMessage(command: string): string | null {
	const pip = /(?:^|\n|[;|&]{1,2})\s*(?:\S+\/)?pip\s*(?:$|\s)/m;
	const pip3 = /(?:^|\n|[;|&]{1,2})\s*(?:\S+\/)?pip3\s*(?:$|\s)/m;
	const poetry = /(?:^|\n|[;|&]{1,2})\s*(?:\S+\/)?poetry\s*(?:$|\s)/m;
	const python = String.raw`(?:^|\n|[;|&]{1,2})\s*(?:\S+\/)?python(?:3(?:\.\d+)?)?\b[^\n;|&]*`;

	if (pip.test(command)) {
		return blocked(
			"pip is disabled",
			"To install a package for a script: uv run --with PACKAGE python script.py",
			"To add a dependency to the project: uv add PACKAGE",
		);
	}
	if (pip3.test(command)) {
		return blocked(
			"pip3 is disabled",
			"To install a package for a script: uv run --with PACKAGE python script.py",
			"To add a dependency to the project: uv add PACKAGE",
		);
	}
	if (poetry.test(command)) {
		return blocked(
			"poetry is disabled",
			"To initialize a project: uv init",
			"To add a dependency: uv add PACKAGE",
			"To sync dependencies: uv sync",
			"To run commands: uv run COMMAND",
		);
	}
	if (
		new RegExp(`${python}(?:\\s-m\\s*pip\\b|\\s-mpip\\b)`, "m").test(command)
	) {
		return blocked(
			"'python -m pip' is disabled",
			"To install a package for a script: uv run --with PACKAGE python script.py",
			"To add a dependency to the project: uv add PACKAGE",
		);
	}
	if (
		new RegExp(`${python}(?:\\s-m\\s*venv\\b|\\s-mvenv\\b)`, "m").test(command)
	) {
		return blocked(
			"'python -m venv' is disabled",
			"To create a virtual environment: uv venv",
		);
	}
	if (
		new RegExp(
			`${python}(?:\\s-m\\s*py_compile\\b|\\s-mpy_compile\\b)`,
			"m",
		).test(command)
	) {
		return [
			"Error: 'python -m py_compile' is disabled because it writes .pyc files to __pycache__.",
			"",
			"  To verify syntax without bytecode output: uv run python -m ast path/to/file.py >/dev/null",
			"",
		].join("\n");
	}

	return null;
}

export const __test = {
	getBlockedCommandMessage,
	prependInterceptedCommands,
	uvInstalled,
};

export default function uvExtension(pi: ExtensionAPI) {
	let generation = 0;

	pi.on("session_start", (_event, ctx) => {
		const ticket = ++generation;
		void uvInstalled().then((installed) => {
			if (ticket === generation && !installed && ctx.hasUI)
				ctx.ui.notify("uv extension: uv not found on PATH", "warning");
		});
	});
	pi.on("session_shutdown", () => {
		generation++;
	});

	pi.registerTool(
		createBashTool(process.cwd(), {
			spawnHook: (ctx) => {
				const message = getBlockedCommandMessage(ctx.command);
				if (message) throw new Error(message);
				return prependInterceptedCommands(ctx);
			},
		}),
	);
}