repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/code-actions/index.ts

Raw
File outline
/**
 * code-actions — /code command
 *
 * Extract code blocks and inline file paths from assistant messages,
 * then copy, insert, or run them. Fuzzy-search UI with ranked results.
 *
 * Based on tmustier/pi-extensions (code-actions).
 * MIT License — https://github.com/tmustier/pi-extensions
 */

import type { ExtensionAPI, ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
import { DynamicBorder } from "@mariozechner/pi-coding-agent";
import { Container, Text, matchesKey, truncateToWidth } from "@mariozechner/pi-tui";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";

// ── Snippet types ──────────────────────────────────────────────────────────

export type SnippetType = "block" | "inline";

export type Snippet = {
	id: number;
	type: SnippetType;
	language?: string;
	content: string;
	messageId: string;
	sourceLabel: string;
};

const MIN_SLASH_COUNT = 2;
const HAS_FILE_EXTENSION = /\.[a-zA-Z0-9]{1,6}$/;
const IGNORED_COMMANDS = new Set([
	"main", "inline", "blocks", "bash -lc", "ls", "pwd", "cd",
	"git status", "git diff", "git add", "git commit", "git push", "git pull",
	"git checkout", "git switch", "npm install", "pnpm install", "yarn install",
	"bun install", "npm test", "pnpm test", "yarn test", "npm run", "pnpm run",
	"yarn run", "make", "make test", "make lint", "make build",
]);

// ── Text extraction ────────────────────────────────────────────────────────

function extractText(content: unknown): string {
	if (typeof content === "string") return content;
	if (!Array.isArray(content)) return "";
	let text = "";
	for (const part of content) {
		if (part && typeof part === "object" && (part as { type?: string }).type === "text") {
			const value = (part as { text?: string }).text;
			if (value) text += value;
		}
	}
	return text;
}

// ── Inline filtering ──────────────────────────────────────────────────────

function looksLikePath(content: string): boolean {
	const slashCount = (content.match(/\//g) || []).length;
	if (/(?:^|[\s"'])~\//.test(content)) return true;
	if (content.startsWith("./")) return true;
	if (content.startsWith("/")) return slashCount >= MIN_SLASH_COUNT || HAS_FILE_EXTENSION.test(content);
	return slashCount >= MIN_SLASH_COUNT;
}

function shouldIncludeInlineSnippet(content: string): boolean {
	const trimmed = content.trim();
	if (trimmed.length === 0) return false;
	if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return false;
	if (IGNORED_COMMANDS.has(trimmed)) return false;
	if (/^[A-Za-z0-9._-]{1,5}$/.test(trimmed)) return false;
	return looksLikePath(trimmed);
}

// ── Extraction ─────────────────────────────────────────────────────────────

export function extractSnippets(
	text: string, messageId: string, sourceLabel: string, startId: number,
	includeInline: boolean, limit: number,
): Snippet[] {
	const snippets: Snippet[] = [];
	const fencedRanges: Array<{ start: number; end: number }> = [];
	const fencedRegex = /```([^\n`]*)\n([\s\S]*?)```/g;
	let match: RegExpExecArray | null;

	while ((match = fencedRegex.exec(text))) {
		if (snippets.length >= limit) return snippets;
		const language = match[1]?.trim() || undefined;
		const content = match[2]?.replace(/\n$/, "") ?? "";
		snippets.push({ id: startId + snippets.length, type: "block", language, content, messageId, sourceLabel });
		fencedRanges.push({ start: match.index, end: match.index + match[0].length });
	}

	if (!includeInline) return snippets;

	const inlineRegex = /`([^`\n]+)`/g;
	while ((match = inlineRegex.exec(text))) {
		if (snippets.length >= limit) return snippets;
		const index = match.index;
		if (fencedRanges.some((r) => index >= r.start && index < r.end)) continue;
		const content = match[1] ?? "";
		if (!shouldIncludeInlineSnippet(content)) continue;
		snippets.push({ id: startId + snippets.length, type: "inline", content, messageId, sourceLabel });
	}

	return snippets;
}

function getSnippetPreview(snippet: Snippet): string {
	const content = snippet.content.trim();
	if (content.length === 0) return "(empty)";
	if (snippet.type === "block") return content.replace(/\s+/g, " ");
	const lines = content.split(/\r?\n/);
	const first = lines.find((l) => l.trim().length > 0) ?? lines[0] ?? "";
	return first.trim() || "(empty)";
}

// ── Search ─────────────────────────────────────────────────────────────────

type SearchIndexItem = { item: SelectItem; idx: number; raw: string; normalized: string };

function normalizeForSearch(value: string): string {
	return value.toLowerCase().replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim();
}

function buildSearchIndex(snippets: Snippet[], items: SelectItem[]): SearchIndexItem[] {
	return snippets.map((snippet, idx) => {
		const preview = getSnippetPreview(snippet);
		const type = snippet.type;
		const lang = snippet.language ?? "";
		const raw = `${preview} ${type} ${lang} ${snippet.sourceLabel}`.toLowerCase();
		return { item: items[idx]!, idx, raw, normalized: normalizeForSearch(raw) };
	});
}

function rankedFilterItems(filter: string, items: SelectItem[], searchIndex: SearchIndexItem[]): SelectItem[] {
	const lower = filter.toLowerCase();
	if (!lower) return items;
	const norm = normalizeForSearch(lower);
	const tokens = norm ? norm.split(" ") : [];
	const scored: Array<{ item: SelectItem; score: number }> = [];

	for (const entry of searchIndex) {
		let score = 0;
		const rawIndex = entry.raw.indexOf(lower);
		if (rawIndex !== -1) {
			score = 1000 - rawIndex;
		} else if (tokens.length > 0) {
			let allMatch = true;
			let firstPos = Number.MAX_SAFE_INTEGER;
			for (const token of tokens) {
				const pos = entry.normalized.indexOf(token);
				if (pos === -1) { allMatch = false; break; }
				firstPos = Math.min(firstPos, pos);
			}
			if (!allMatch) continue;
			score = 500 - firstPos;
		} else {
			continue;
		}
		scored.push({ item: entry.item, score });
	}

	scored.sort((a, b) => b.score !== a.score ? b.score - a.score : 0);
	return scored.map((e) => e.item);
}

// ── Actions ────────────────────────────────────────────────────────────────

async function copyToClipboard(pi: ExtensionAPI, content: string): Promise<boolean> {
	const tmpPath = path.join(os.tmpdir(), `pi-code-${Date.now()}.txt`);
	fs.writeFileSync(tmpPath, content, "utf8");

	const commands: Array<{ command: string; args: string[] }> = [];
	if (process.platform === "darwin") {
		commands.push({ command: "sh", args: ["-c", `cat "${tmpPath}" | pbcopy`] });
	} else if (process.platform === "win32") {
		commands.push({ command: "powershell", args: ["-NoProfile", "-Command", `Get-Content -Raw "${tmpPath}" | Set-Clipboard`] });
	} else {
		commands.push({ command: "sh", args: ["-c", `cat "${tmpPath}" | wl-copy`] });
		commands.push({ command: "sh", args: ["-c", `cat "${tmpPath}" | xclip -selection clipboard`] });
		commands.push({ command: "sh", args: ["-c", `cat "${tmpPath}" | xsel --clipboard --input`] });
	}

	let success = false;
	for (const cmd of commands) {
		try {
			const result = await pi.exec(cmd.command, cmd.args);
			if (result.code === 0) { success = true; break; }
		} catch { /* try next */ }
	}
	try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
	return success;
}

function insertIntoEditor(ctx: ExtensionCommandContext, content: string): void {
	const existing = ctx.ui.getEditorText();
	ctx.ui.setEditorText(existing ? `${existing}\n${content}` : content);
}

async function runSnippet(pi: ExtensionAPI, ctx: ExtensionCommandContext, snippet: string): Promise<void> {
	const isWindows = process.platform === "win32";
	const command = isWindows ? "powershell" : "bash";
	const args = isWindows ? ["-NoProfile", "-Command", snippet] : ["-lc", snippet];
	const result = await pi.exec(command, args, { cwd: ctx.cwd });

	const lines: string[] = [`Command: ${command}`, `Exit code: ${result.code}`];
	if (result.stdout.trim()) lines.push("", "STDOUT:", result.stdout.trimEnd());
	if (result.stderr.trim()) lines.push("", "STDERR:", result.stderr.trimEnd());
	const output = lines.join("\n").split(/\r?\n/).slice(0, 200).join("\n");

	await ctx.ui.custom<void>((tui, theme, _kb, done) => {
		const container = new Container();
		container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
		container.addChild(new Text(theme.fg("accent", theme.bold("Command Output")), 1, 0));
		container.addChild(new Text(output, 1, 0));
		container.addChild(new Text(theme.fg("dim", "Enter/Esc to close"), 1, 0));
		container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
		return {
			render: (width: number) => container.render(width).map((line) => truncateToWidth(line, width)),
			invalidate: () => container.invalidate(),
			handleInput: (data: string) => {
				if (matchesKey(data, "escape") || matchesKey(data, "enter")) done();
			},
		};
	});
}

// ── Pick UI ────────────────────────────────────────────────────────────────

import type { SelectItem } from "@mariozechner/pi-tui";
import { SelectList } from "@mariozechner/pi-tui";

const PREVIEW_WIDTH = 52;

type PickResult = { snippet: Snippet; action?: "copy" | "insert" };

async function pickSnippet(ctx: ExtensionCommandContext, snippets: Snippet[]): Promise<PickResult | undefined> {
	const indexWidth = String(snippets.length).length;
	const timeWidth = Math.max(...snippets.map((s) => s.sourceLabel.length));
	const items: SelectItem[] = snippets.map((snippet, idx) => {
		const preview = getSnippetPreview(snippet);
		const truncated = preview.length > PREVIEW_WIDTH ? `${preview.slice(0, PREVIEW_WIDTH - 1)}…` : preview.padEnd(PREVIEW_WIDTH, " ");
		const number = String(idx + 1).padStart(indexWidth, " ");
		const type = snippet.type === "block" ? "Block" : "Inline";
		const lang = snippet.type === "block" && snippet.language ? ` (${snippet.language})` : "";
		const time = snippet.sourceLabel.padEnd(timeWidth, " ");
		return { value: String(idx), label: `${number}. ${truncated} ${time} ${type}${lang}`, description: "" };
	});
	const searchIndex = buildSearchIndex(snippets, items);

	const selectedIndex = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
		const container = new Container();
		container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
		container.addChild(new Text(theme.fg("accent", theme.bold("Select Code Snippet")), 1, 0));

		const list = new SelectList(items, Math.min(items.length, 12), {
			selectedPrefix: (t) => theme.fg("accent", t),
			selectedText: (t) => theme.fg("accent", t),
			description: (t) => theme.fg("muted", t),
			scrollInfo: (t) => theme.fg("dim", t),
			noMatch: (t) => theme.fg("warning", t),
		});
		list.onSelect = (item) => done(`copy:${item.value}`);
		list.onCancel = () => done(null);
		container.addChild(list);

		const help = new Text(theme.fg("dim", "Filter: (none)   Enter copy   Right/Tab insert   Esc cancel"), 1, 0);
		container.addChild(help);
		container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));

		let filter = "";
		const updateFilter = (next: string) => {
			filter = next;
			const listAny = list as unknown as { filteredItems: SelectItem[]; selectedIndex: number };
			listAny.filteredItems = rankedFilterItems(filter, items, searchIndex);
			listAny.selectedIndex = 0;
			help.setText(theme.fg("dim", `Filter: ${filter || "(none)"}   Enter copy   Right/Tab insert   Esc cancel`));
			list.invalidate();
			tui.requestRender();
		};

		return {
			render: (width: number) => container.render(width),
			invalidate: () => container.invalidate(),
			handleInput: (data: string) => {
				if (matchesKey(data, "backspace")) { if (filter.length > 0) updateFilter(filter.slice(0, -1)); return; }
				if (matchesKey(data, "right") || matchesKey(data, "tab")) { const s = list.getSelectedItem(); if (s) done(`insert:${s.value}`); return; }
				if (data.length === 1 && data >= " " && data <= "~") { updateFilter(filter + data); return; }
				list.handleInput?.(data);
				tui.requestRender();
			},
		};
	});

	if (selectedIndex === null || selectedIndex === undefined) return undefined;
	const [action, rawIndex] = selectedIndex.split(":");
	const index = Number.parseInt(rawIndex ?? "", 10);
	if (Number.isNaN(index)) return undefined;
	const snippet = snippets[index];
	if (!snippet) return undefined;
	if (action === "copy" || action === "insert") return { snippet, action };
	return { snippet };
}

async function pickAction(ctx: ExtensionCommandContext): Promise<"copy" | "insert" | "run" | undefined> {
	const action = await ctx.ui.select("Action", ["Copy", "Insert", "Run"]);
	if (!action) return undefined;
	return action.toLowerCase() as "copy" | "insert" | "run";
}

// ── Arg parsing & collection ───────────────────────────────────────────────

type ParsedArgs = {
	scope: "last" | "all"; action?: "copy" | "insert" | "run";
	index?: number; includeInline: boolean; limit: number;
};

function parseArgs(args?: string): ParsedArgs {
	const tokens = args?.trim().split(/\s+/).filter(Boolean) ?? [];
	const parsed: ParsedArgs = { scope: "all", includeInline: true, limit: 200 };
	for (const token of tokens) {
		if (token === "all" || token === "last") { parsed.scope = token; continue; }
		if (token === "blocks") { parsed.includeInline = false; continue; }
		if (token === "copy" || token === "insert" || token === "run") { parsed.action = token; continue; }
		if (token.startsWith("limit=")) { const v = Number.parseInt(token.slice(6), 10); if (!Number.isNaN(v) && v > 0) parsed.limit = v; continue; }
		if (/^\d+$/.test(token)) parsed.index = Math.max(0, Number.parseInt(token, 10) - 1);
	}
	return parsed;
}

function collectSnippets(ctx: ExtensionCommandContext, scope: "last" | "all", includeInline: boolean, limit: number): Snippet[] {
	const branchEntries = ctx.sessionManager.getBranch();
	const assistantEntries = branchEntries.filter((e) => e.type === "message" && e.message?.role === "assistant");
	if (!assistantEntries.length) return [];

	const sorted = assistantEntries.slice().sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
	const entriesToScan = scope === "all" ? sorted : [sorted[0]!];

	let snippets: Snippet[] = [];
	let nextId = 0;
	for (const entry of entriesToScan) {
		if (snippets.length >= limit) break;
		const text = extractText(entry.message.content);
		if (!text) continue;
		const label = new Date(entry.timestamp).toLocaleTimeString();
		snippets = snippets.concat(extractSnippets(text, entry.id, label, nextId, includeInline, limit - snippets.length));
		nextId = snippets.length;
	}
	return snippets;
}

// ── Extension ──────────────────────────────────────────────────────────────

function handleAction(pi: ExtensionAPI, ctx: ExtensionCommandContext, action: "copy" | "insert" | "run", snippet: Snippet) {
	if (action === "copy") {
		copyToClipboard(pi, snippet.content).then(ok => {
			if (ctx.hasUI) ctx.ui.notify(ok ? "Copied." : "Failed to copy.", ok ? "info" : "error");
		});
	} else if (action === "insert") {
		if (!ctx.hasUI) return;
		insertIntoEditor(ctx, snippet.content);
		ctx.ui.notify("Inserted.", "info");
	} else if (action === "run") {
		if (!ctx.hasUI) return;
		ctx.ui.confirm("Run snippet?", "Executes in your shell.").then(ok => {
			if (ok) runSnippet(pi, ctx, snippet.content);
		});
	}
}

export default function codeActionsExtension(pi: ExtensionAPI) {
	pi.registerCommand("code", {
		description: "Pick code from assistant messages and copy/insert/run it",
		handler: async (args, ctx) => {
			if (!ctx.hasUI && (!args || !args.trim())) return;

			const parsed = parseArgs(args);
			const snippets = collectSnippets(ctx, parsed.scope, parsed.includeInline, parsed.limit);

			if (!snippets.length) {
				if (ctx.hasUI) ctx.ui.notify("No code snippets found.", "warning");
				return;
			}

			let snippet: Snippet | undefined;
			let pickedAction: PickResult["action"];

			if (parsed.index !== undefined) {
				snippet = snippets[parsed.index];
				if (!snippet) { if (ctx.hasUI) ctx.ui.notify("Snippet index out of range.", "warning"); return; }
			} else {
				if (!ctx.hasUI) return;
				const result = await pickSnippet(ctx, snippets);
				if (!result) return;
				snippet = result.snippet;
				pickedAction = result.action;
			}

			const action = parsed.action ?? pickedAction;
			if (!action) {
				if (!ctx.hasUI) return;
				const a = await pickAction(ctx);
				if (!a) return;
				handleAction(pi, ctx, a, snippet!);
			} else {
				handleAction(pi, ctx, action, snippet!);
			}
		},
	});
}