/** * ollama-graceful — Graceful Ollama lifecycle for pi. * * Automatically starts `ollama serve` as a user process when you switch to a * local model and kills it when you switch away or exit pi. No sudo, no * systemd — keeps your GPU free when using cloud models. * * Commands: * /ollama-start — manually start Ollama * /ollama-stop — manually stop Ollama * /ollama-status — show current Ollama state * * Usage: * pi -e ~/repos/ollama-graceful * # or install: pi install npm:ollama-graceful */ import { spawn, type ChildProcess } from "node:child_process"; import type { ExtensionAPI } from "@mariozechner/pi-coding-agent"; const READY_TIMEOUT = 30_000; const READY_POLL_INTERVAL = 500; const OLLAMA_URL = "http://localhost:11434"; const LLAMA_WIDGET = [" 🦙 Ollama running "]; export default function (pi: ExtensionAPI) { let weStartedOllama = false; let ollamaRunning = false; let ollamaProcess: ChildProcess | null = null; // ── Helpers ──────────────────────────────────────────────────────── async function isOllamaReady(): Promise { try { const res = await fetch(`${OLLAMA_URL}/api/version`, { signal: AbortSignal.timeout(2_000), }); return res.ok; } catch { return false; } } async function waitForReady(): Promise { const deadline = Date.now() + READY_TIMEOUT; while (Date.now() < deadline) { if (await isOllamaReady()) return true; await sleep(READY_POLL_INTERVAL); } return false; } function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } function isOllamaModel(model: { provider: string }): boolean { return model.provider === "ollama"; } function showRunning(ctx: { ui: any }) { ctx.ui.setStatus("ollama", "🦙 Ollama running"); ctx.ui.setWidget("ollama", LLAMA_WIDGET); } function showStopped(ctx: { ui: any }) { ctx.ui.setStatus("ollama", ""); ctx.ui.setWidget("ollama", []); } // ── Lifecycle ───────────────────────────────────────────────────── async function startOllama(): Promise { if (await isOllamaReady()) { ollamaRunning = true; return true; } return new Promise((resolve) => { const child = spawn("ollama", ["serve"], { stdio: "ignore", detached: false, env: { ...process.env, OLLAMA_HOST: "127.0.0.1:11434" }, }); child.on("error", (err) => { console.error(`[ollama-graceful] spawn failed: ${err.message}`); ollamaProcess = null; resolve(false); }); child.on("exit", (code) => { if (ollamaProcess === child) { console.error(`[ollama-graceful] ollama exited unexpectedly (code ${code})`); ollamaProcess = null; ollamaRunning = false; weStartedOllama = false; } }); ollamaProcess = child; waitForReady().then((ready) => { if (ready) { weStartedOllama = true; ollamaRunning = true; } resolve(ready); }); }); } async function stopOllama(): Promise { if (!weStartedOllama || !ollamaProcess) return; const child = ollamaProcess; ollamaProcess = null; await new Promise((resolve) => { const timeout = setTimeout(() => { try { child.kill("SIGKILL"); } catch {} resolve(); }, 5_000); child.on("exit", () => { clearTimeout(timeout); resolve(); }); child.kill("SIGTERM"); }); ollamaRunning = false; weStartedOllama = false; } // ── Commands ────────────────────────────────────────────────────── pi.registerCommand("ollama-start", { description: "Start Ollama server", handler: async (_args, ctx) => { if (ollamaRunning) { ctx.ui.notify("🦙 Ollama is already running", "info"); return; } ctx.ui.setStatus("ollama", "🦙 Starting Ollama…"); ctx.ui.notify("🦙 Starting Ollama…", "info"); const ok = await startOllama(); if (ok) { showRunning(ctx); ctx.ui.notify("🦙 Ollama ready", "success"); } else { showStopped(ctx); ctx.ui.notify("🦙 Failed to start Ollama — is it installed?", "error"); } }, }); pi.registerCommand("ollama-stop", { description: "Stop Ollama server", handler: async (_args, ctx) => { if (!ollamaRunning) { ctx.ui.notify("🦙 Ollama is not running", "info"); return; } if (!weStartedOllama) { ctx.ui.notify("🦙 Ollama was started externally — not stopping it", "info"); return; } ctx.ui.setStatus("ollama", "🦙 Stopping Ollama…"); ctx.ui.notify("🦙 Stopping Ollama…", "info"); await stopOllama(); showStopped(ctx); ctx.ui.notify("🦙 Ollama stopped — GPU freed", "success"); }, }); pi.registerCommand("ollama-status", { description: "Show Ollama server status", handler: async (_args, ctx) => { const ready = await isOllamaReady(); if (ready) { const owner = weStartedOllama ? "started by this extension" : "started externally"; ctx.ui.notify(`🦙 Ollama is running (${owner})`, "info"); } else { ctx.ui.notify("🦙 Ollama is not running", "info"); } }, }); // ── Event hooks ─────────────────────────────────────────────────── pi.on("model_select", async (event, ctx) => { const { model, previousModel } = event; const toOllama = isOllamaModel(model); const fromOllama = previousModel ? isOllamaModel(previousModel) : false; if (toOllama && !ollamaRunning) { ctx.ui.setStatus("ollama", "🦙 Starting Ollama…"); ctx.ui.notify("🦙 Starting Ollama…", "info"); const ok = await startOllama(); if (ok) { showRunning(ctx); ctx.ui.notify("🦙 Ollama ready", "success"); } else { showStopped(ctx); ctx.ui.notify("🦙 Failed to start Ollama — is it installed?", "error"); } } else if (!toOllama && fromOllama && ollamaRunning) { ctx.ui.setStatus("ollama", "🦙 Stopping Ollama…"); ctx.ui.notify("🦙 Stopping Ollama…", "info"); await stopOllama(); showStopped(ctx); ctx.ui.notify("🦙 Ollama stopped — GPU freed", "success"); } else if (toOllama && ollamaRunning) { showRunning(ctx); } }); pi.on("session_start", async (_event, ctx) => { if (await isOllamaReady()) { ollamaRunning = true; showRunning(ctx); } }); pi.on("session_shutdown", async () => { if (weStartedOllama && ollamaRunning) { await stopOllama(); } }); }