repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/uv/index.ts

Raw
File outline
import { spawnSync } from "node:child_process";
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",
);

function uvInstalled(): boolean {
	const result = spawnSync("uv", ["--version"], { stdio: "ignore" });
	return !result.error && result.status === 0;
}

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

function prependInterceptedCommands(ctx: BashSpawnContext): BashSpawnContext {
	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 };

export default function uvExtension(pi: ExtensionAPI) {
	pi.on("session_start", (_event, ctx) => {
		if (!uvInstalled() && ctx.hasUI) {
			ctx.ui.notify("uv extension: uv not found on PATH", "warning");
		}
	});

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