repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/leaks/src/pi.ts

Raw
File outline
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { LeaksEngine } from "./engine.ts";
import { loadLeaksSettings } from "./settings.ts";

export default function leaks(pi: ExtensionAPI) {
	const engine = new LeaksEngine();

	pi.on("session_start", async (_event, ctx) => {
		engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
		if (ctx.hasUI) ctx.ui.setStatus("leaks", "leaks on | last 0");
	});

	pi.on("context", async (event) => {
		return { messages: engine.redactDeep(event.messages, "context").value };
	});

	pi.on("before_provider_request", async (event, ctx) => {
		const result = engine.redactDeep(event.payload, "provider");
		if (ctx.hasUI) {
			ctx.ui.setStatus("leaks", `leaks on | last ${result.count}`);
			if (result.count > 0) {
				const newPlaceholders = result.redactions
					.flatMap((r) => r.placeholders)
					.filter((p) => !engine.notifiedPlaceholders.has(p));
				if (newPlaceholders.length > 0) {
					for (const p of newPlaceholders) engine.notifiedPlaceholders.add(p);
					const freshRedactions = result.redactions.filter((r) =>
						r.placeholders.some((p) => newPlaceholders.includes(p)),
					);
					ctx.ui.notify(
						formatNotice({
							count: newPlaceholders.length,
							redactions: freshRedactions,
						}),
						"info",
					);
				}
			}
		}
		return result.value;
	});

	pi.on("tool_call", async (event) => {
		const input = (event as { input?: unknown }).input;
		if (input !== undefined)
			(event as { input: unknown }).input = engine.restoreDeep(input).value;
	});

	pi.on("message_end", async (event) => {
		const restored = engine.restoreDeep(event.message).value;
		return { message: restored };
	});

	pi.registerCommand("leaks", {
		description: "Inspect and control provider-bound redaction",
		async handler(args, ctx) {
			const command = args.trim();
			if (command === "status" || command === "") {
				ctx.ui.notify(formatStatus(engine), "info");
				return;
			}
			if (command === "reload") {
				engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
				ctx.ui.notify("leaks reloaded", "info");
				return;
			}
			if (command === "clear") {
				if (ctx.hasUI) {
					const confirmed = await ctx.ui.confirm(
						"Clear leaks mappings?",
						"Old placeholders become unrestorable.",
					);
					if (!confirmed) {
						ctx.ui.notify("clear cancelled", "info");
						return;
					}
				}
				engine.clear();
				ctx.ui.notify("leaks cleared", "info");
				return;
			}
			if (command.startsWith("test ")) {
				const result = engine.redactText(command.slice(5), "diagnostic");
				ctx.ui.notify(`matches: ${result.count}\n${result.text}`, "info");
				return;
			}
			ctx.ui.notify("usage: /leaks status|reload|test <text>|clear", "warning");
		},
	});
}

function readSettings(cwd: string) {
	const file = path.join(cwd, ".pi", "settings.json");
	if (!existsSync(file)) return { regex: [] };
	try {
		return loadLeaksSettings(JSON.parse(readFileSync(file, "utf8"))).settings;
	} catch {
		return { regex: [] };
	}
}

function formatNotice(result: {
	count: number;
	redactions: Array<{ path: string; labels: string[] }>;
}) {
	const grouped = new Map<string, number>();
	for (const redaction of result.redactions) {
		const key = `${redaction.path}: ${redaction.labels.join(", ")}`;
		grouped.set(key, (grouped.get(key) ?? 0) + 1);
	}
	return [
		`leaks redacted ${result.count} provider value(s)`,
		...[...grouped.entries()].map(([line, n]) =>
			n > 1 ? `${line} (×${n})` : line,
		),
	].join("\n");
}

function formatStatus(engine: LeaksEngine) {
	const stats = engine.stats();
	return [
		"leaks on",
		`built-in rules: ${stats.builtInRuleCount}`,
		`custom regex: ${stats.customRegexCount}`,
		`regex warnings: ${stats.regexWarningCount}`,
		`invalid regex: ${stats.invalidRegexCount}`,
		`learned: ${stats.learnedCount}`,
		`mappings: ${stats.mappingCount}`,
		`last provider redactions: ${stats.lastProviderRedactionCount}`,
		`total provider redactions: ${stats.totalProviderRedactionCount}`,
		`recent labels: ${stats.recentLabels.join(", ")}`,
		`latest tags: ${stats.latestTags.join(", ")}`,
	].join("\n");
}