import { readFileSync } from "node:fs"; import path from "node:path"; import { type ExtensionAPI, type ExtensionContext, SettingsManager, } from "@earendil-works/pi-coding-agent"; import { LeaksEngine } from "./engine.ts"; import { isPlainObject, sanitizeTag } from "./safety.ts"; import { loadLeaksSettings } from "./settings.ts"; class NondurableAppendError extends Error {} export default function leaks(pi: ExtensionAPI) { const engine = new LeaksEngine(); const reportedWarnings = new Set(); const persistence = { tainted: false }; pi.on("session_start", async (_event, ctx) => { rebuildPersistence(engine, pi, ctx, persistence); engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env); notifyInMemorySession(ctx, reportedWarnings); flushWarnings(engine, ctx, reportedWarnings); updateLeakStatus(ctx, engine); }); pi.on("session_tree", async (_event, ctx) => { rebuildPersistence(engine, pi, ctx, persistence); flushWarnings(engine, ctx, reportedWarnings); }); pi.on("context", async (event, ctx) => { const result = engine.redactDeep(event.messages, "context"); updateLeakStatus(ctx, engine); return { messages: result.value }; }); pi.on("before_provider_request", async (event, ctx) => { if (ctx.sessionManager) rebuildPersistence(engine, pi, ctx, persistence); const result = engine.redactDeep(event.payload, "provider"); try { flushWarnings(engine, ctx, reportedWarnings); updateProviderUi(ctx, engine, result, reportedWarnings); } catch { // Diagnostics must never compromise the authoritative redacted return. } return result.value; }); pi.on("message_update", async (event, ctx) => { if (containsLeaksSourceMutation(event.message, ctx.cwd)) return; restoreEventProperty( engine, event as unknown as Record, "message", ); }); pi.on("tool_call", async (event, ctx) => { if (isLeaksSourceMutation(event, ctx.cwd)) return; const record = event as unknown as Record; const current = record.input; const result = engine.hydrateToolInput(current); record.input = result.value; copyRestoredInPlace(current, result.value); if (!result.issue) return; const toolName = typeof event.toolName === "string" ? event.toolName : "tool"; const reason = `Blocked ${toolName}: unresolved leaks placeholder at ${result.issue.path} (${result.issue.label})`; notify(ctx, reason, "warning"); return { block: true, reason }; }); pi.on("tool_execution_start", async (event, ctx) => { if (isLeaksSourceMutation(event, ctx.cwd)) return; restoreEventProperty( engine, event as unknown as Record, "args", ); }); pi.on("tool_execution_update", async (event, ctx) => { if (isLeaksSourceMutation(event, ctx.cwd)) return; restoreEventProperty( engine, event as unknown as Record, "args", ); }); pi.on("tool_result", async (event, ctx) => { const patch = restoreToolResult( engine, event as unknown as Record, ); if (!isLeaksPathEvent(event, ctx.cwd)) { warnUnknownLocal( engine, event.content, ctx, "tool result", reportedWarnings, ); warnUnknownLocal( engine, event.details, ctx, "tool result", reportedWarnings, ); } return patch; }); pi.on("message_end", async (event, ctx) => { if (containsLeaksSourceMutation(event.message, ctx.cwd)) return; const restored = engine.restoreDeep(event.message).value; warnUnknownLocal( engine, restored, ctx, "assistant message", reportedWarnings, ); 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 === "") { notify(ctx, formatStatus(engine), "info"); return; } if (command === "reload") { rebuildPersistence(engine, pi, ctx, persistence); engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env); flushWarnings(engine, ctx, reportedWarnings); notify(ctx, "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) { notify(ctx, "clear cancelled", "info"); return; } } const cleared = persistence.tainted ? false : engine.clear(); flushWarnings(engine, ctx, reportedWarnings); notify( ctx, cleared ? "leaks cleared" : "leaks clear failed; mappings kept active", cleared ? "info" : "error", ); return; } if (command.startsWith("test ")) { const result = engine.redactText(command.slice(5), "diagnostic"); notify(ctx, `matches: ${result.count}`, "info"); return; } notify(ctx, "usage: /leaks status|reload|test |clear", "warning"); }, }); } type RedactionResult = ReturnType; function updateLeakStatus(ctx: ExtensionContext, engine: LeaksEngine) { try { if (!ctx.hasUI) return; const stats = engine.stats(); const status = stats.persistenceEnabled ? `󰒘  ${stats.totalProtectedRedactionCount}` : `󰀦 degraded  ${stats.totalProtectedRedactionCount}`; ctx.ui.setStatus("leaks", status); } catch { // Status is best-effort. } } function updateProviderUi( ctx: ExtensionContext, engine: LeaksEngine, result: RedactionResult, reported: Set, ) { try { const actionable = result.ambiguities.filter((item) => /^(?:PERSISTENCE|MAPPING|PLACEHOLDER|REDACTION)/.test(item.family), ); const newActionable = actionable.filter((item) => { const key = `ambiguity:${item.family}`; if (reported.has(key)) return false; reported.add(key); return true; }); if (newActionable.length > 0) notify(ctx, formatAmbiguities(newActionable), "warning"); if (!ctx.hasUI) return; updateLeakStatus(ctx, engine); if (result.count === 0) return; const newPlaceholders = result.redactions .flatMap((r) => r.placeholders) .filter((p) => !engine.notifiedPlaceholders.has(p)); if (newPlaceholders.length === 0) return; 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", ); } catch { // Stale or broken UI diagnostics never affect provider redaction. } } function restoreEventProperty( engine: LeaksEngine, event: Record, key: string, ) { const current = event[key]; if (current === undefined) return; const restored = engine.restoreDeep(current).value; event[key] = restored; copyRestoredInPlace(current, restored); } function restoreToolResult( engine: LeaksEngine, event: Record, ) { const patch: Record = {}; for (const key of ["content", "details"] as const) { const current = event[key]; if (current === undefined) continue; const result = engine.restoreDeep(current); if (!result.changed) continue; event[key] = result.value; copyRestoredInPlace(current, result.value); patch[key] = result.value; } return Object.keys(patch).length > 0 ? patch : undefined; } function copyRestoredInPlace(target: unknown, source: unknown) { if (target === source) return; if (Array.isArray(target) && Array.isArray(source)) { target.length = 0; target.push(...source); return; } if (!isPlainObject(target) || !isPlainObject(source)) return; for (const key of Reflect.ownKeys(target)) Reflect.deleteProperty(target, key); Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } const LEAKS_EXTENSION_ROOT = path.resolve(import.meta.dirname, ".."); function isLeaksSourceMutation(event: unknown, cwd: string) { if (!isPlainObject(event)) return false; const toolName = event.toolName ?? event.name; if (toolName !== "write" && toolName !== "edit") return false; return isLeaksPathEvent(event, cwd); } function isLeaksPathEvent(event: unknown, cwd: string) { if (!isPlainObject(event)) return false; const input = event.input ?? event.args ?? event.arguments; if (!isPlainObject(input) || typeof input.path !== "string") return false; const target = path.resolve(cwd, input.path.replace(/^@/, "")); const relative = path.relative(LEAKS_EXTENSION_ROOT, target); return ( relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)) ); } function containsLeaksSourceMutation(value: unknown, cwd: string): boolean { if (isLeaksSourceMutation(value, cwd)) return true; if (Array.isArray(value)) return value.some((item) => containsLeaksSourceMutation(item, cwd)); if (!isPlainObject(value)) return false; return Object.values(value).some((item) => containsLeaksSourceMutation(item, cwd), ); } function warnUnknownLocal( engine: LeaksEngine, value: unknown, ctx: ExtensionContext, surface: string, reported: Set, ) { if (value === undefined) return; const issue = engine.hydrateToolInput(value).issue; if ( !issue || issue.label.startsWith("TRAVERSAL_") || issue.label === "UNSUPPORTED_OBJECT" ) return; const key = `unresolved:${surface}:${issue.path}:${issue.label}`; if (reported.has(key)) return; reported.add(key); notify( ctx, `unresolved leaks placeholder in ${surface} at ${issue.path} (${issue.label})`, "warning", ); } function rebuildPersistence( engine: LeaksEngine, pi: ExtensionAPI, ctx: ExtensionContext, state: { tainted: boolean }, ) { const branch = ctx.sessionManager?.getBranch() ?? []; const durableIds = persistedEntryIds(ctx); const leaksEntries = branch.flatMap((entry) => entry.type === "custom" && entry.customType.startsWith("leaks-") ? [entry] : [], ); if (durableIds && leaksEntries.some((entry) => !durableIds.has(entry.id))) state.tainted = true; const entries = leaksEntries .filter((entry) => !durableIds || durableIds.has(entry.id)) .map((entry) => ({ type: "custom" as const, customType: entry.customType, data: entry.data, })); engine.configurePersistence(entries, (customType, data) => { try { const manager = ctx.sessionManager; const before = new Set(manager?.getBranch().map((entry) => entry.id)); pi.appendEntry(customType, data); if (manager?.getSessionFile()) { const appended = manager .getBranch() .findLast( (entry) => entry.type === "custom" && entry.customType === customType && !before.has(entry.id), ); if (!appended || !persistedEntryIds(ctx)?.has(appended.id)) { notify( ctx, "session entry is not durable yet; values remain visible until Pi flushes the session", "warning", ); throw new NondurableAppendError( "leaks mapping was not durably appended", ); } } } catch (error) { if (!(error instanceof NondurableAppendError)) state.tainted = true; throw error; } }); if (state.tainted) engine.taintPersistence(); } function persistedEntryIds(ctx: ExtensionContext) { const file = ctx.sessionManager?.getSessionFile(); if (!file) return undefined; try { return new Set( readFileSync(file, "utf8") .split(/\r?\n/) .filter(Boolean) .map((line) => JSON.parse(line) as { id?: unknown }) .flatMap((entry) => (typeof entry.id === "string" ? [entry.id] : [])), ); } catch { return new Set(); } } function notifyInMemorySession(ctx: ExtensionContext, reported: Set) { if (ctx.sessionManager?.getSessionFile() !== undefined) return; const key = "session.in-memory"; if (reported.has(key)) return; reported.add(key); notify( ctx, "in-memory session mappings cannot survive process restart", "warning", ); } function flushWarnings( engine: LeaksEngine, ctx: ExtensionContext, reported: Set, ) { for (const warning of engine.stats().warnings) { const key = `${warning.code}:${warning.message}`; if (reported.has(key)) continue; reported.add(key); notify(ctx, warning.message, warning.severity); } } function notify( ctx: ExtensionContext, message: string, severity: "info" | "warning" | "error", ) { try { if (ctx.hasUI) ctx.ui.notify(message, severity); else console.error(`[leaks] ${message.replace(/\s*\n\s*/g, " | ")}`); } catch { // Diagnostics are best-effort and never alter extension behavior. } } function readSettings(cwd: string) { const manager = SettingsManager.create(cwd); const global = manager.getGlobalSettings() as Record; const project = manager.getProjectSettings() as Record; return loadLeaksSettings({ leaks: { ...(isPlainObject(global.leaks) ? global.leaks : {}), ...(isPlainObject(project.leaks) ? project.leaks : {}), }, }).settings; } function formatAmbiguities( ambiguities: Array<{ path: string; family: string }>, ) { const counts = new Map(); for (const item of ambiguities) { const key = `${item.path || "$"} — ${item.family}`; counts.set(key, (counts.get(key) ?? 0) + 1); } const rows = [...counts] .slice(0, 8) .map(([key, count]) => `• ${key}${count > 1 ? ` ×${count}` : ""}`); if (counts.size > rows.length) rows.push(`• ${counts.size - rows.length} more location(s)`); return [ `leaks kept ${ambiguities.length} ambiguous candidate(s) visible`, ...rows, ].join("\n"); } function formatNotice(result: { count: number; redactions: Array<{ path: string; labels: string[] }>; }) { const grouped = new Map>(); for (const redaction of result.redactions) { const path = redaction.path || "$"; let labels = redaction.labels.map(noticeLabel); if (labels.includes("COOKIE")) labels = ["COOKIE"]; if (labels.length === 0) labels = ["SECRET"]; const counts = grouped.get(path) ?? new Map(); for (const label of new Set(labels)) counts.set(label, (counts.get(label) ?? 0) + 1); grouped.set(path, counts); } const rows = [...grouped.entries()] .slice(0, 8) .map(([path, labels]) => `• ${path} — ${formatNoticeLabels(labels)}`); if (grouped.size > rows.length) rows.push(`• ${grouped.size - rows.length} more path(s)`); return [`leaks redacted ${result.count} provider value(s)`, ...rows].join( "\n", ); } function noticeLabel(raw: string) { const tag = sanitizeTag(raw); if (tag.startsWith("COOKIE")) return "COOKIE"; return tag; } function formatNoticeLabels(labels: Map) { const visible = [...labels.entries()] .slice(0, 6) .map(([label, count]) => (count > 1 ? `${label} ×${count}` : label)); if (labels.size > visible.length) visible.push(`${labels.size - visible.length} more`); return visible.join(", "); } function formatStatus(engine: LeaksEngine) { const stats = engine.stats(); return [ `leaks ${stats.persistenceEnabled ? "on" : "degraded"}`, `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}`, `total protected redactions: ${stats.totalProtectedRedactionCount}`, `last provider ambiguities: ${stats.lastProviderAmbiguityCount}`, `recent labels: ${stats.recentLabels.map(noticeLabel).join(", ")}`, `latest tags: ${stats.latestTags.join(", ")}`, ].join("\n"); }