import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { findProjectVenv, ensureSharedVenv, activateVenv, getActiveVenv, getSharedVenvPath, } from "./venv.js"; export default function (pi: ExtensionAPI) { pi.on("session_start", async (_event, ctx) => { // 1. Respect existing VIRTUAL_ENV — user already activated something if (process.env.VIRTUAL_ENV) { return; } // 2. Discover project venv in cwd const projectVenv = findProjectVenv(ctx.cwd); if (projectVenv) { activateVenv(projectVenv); return; } // 3. Fall back to shared venv try { const sharedVenv = await ensureSharedVenv(); if (sharedVenv) { activateVenv(sharedVenv); } } catch (err: any) { const msg = err?.message ?? String(err); ctx.ui.notify( `pi-pyvenv: venv initialization failed. ${msg} Fix: install python3-venv (e.g. sudo apt install python3-venv)`, "warning" ); } }); pi.registerCommand("pyvenv", { description: "Show or manage the Python virtual environment", handler: async (args, ctx) => { const arg = args.trim(); if (arg === "recreate") { const sharedPath = getSharedVenvPath(); if (!getActiveVenv()?.startsWith(sharedPath)) { ctx.ui.notify("Only the shared fallback venv can be recreated.", "warning"); return; } const ok = await ctx.ui.confirm( "Recreate shared venv?", `Delete ${sharedPath} and rebuild it?` ); if (!ok) return; const { rm } = await import("node:fs/promises"); try { await rm(sharedPath, { recursive: true, force: true }); ctx.ui.notify("Shared venv deleted. Rebuilding...", "info"); } catch (e: any) { ctx.ui.notify(`Failed to delete venv: ${e.message}`, "error"); return; } const rebuilt = await ensureSharedVenv(); if (rebuilt) { activateVenv(rebuilt); ctx.ui.notify(`Shared venv rebuilt: ${rebuilt}`, "info"); } else { ctx.ui.notify("No Python interpreter found to rebuild shared venv.", "error"); } return; } if (arg === "" || arg === "status") { const active = getActiveVenv(); if (!active) { ctx.ui.notify("No Python venv is active.", "warning"); } else { ctx.ui.notify(`Python venv: ${active}`, "info"); } return; } ctx.ui.notify( `Unknown pyvenv command: "${arg}". Try "status" or "recreate".`, "warning" ); }, }); }