/** * prune — Lossless Conversation Compactor * * Algorithmic compaction that preserves searchable transcript. * Replaces default LLM summarization with deterministic extraction. */ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { DEFAULT_SECTION_LIMIT, DEFAULT_TRANSCRIPT_LIMIT, MAX_RAW_TAIL_TOKENS, } from "./src/constants.ts"; import { extract } from "./src/extract.ts"; import { format } from "./src/format.ts"; import { merge } from "./src/merge.ts"; import { normalize } from "./src/normalize.ts"; import { formatRecallResults, recall } from "./src/recall.ts"; import type { Message, PruneSettings } from "./src/types.ts"; // ─── Settings ────────────────────────────────────────────────────────────── const RECALL_TOOL = "prune_recall"; const PRUNE_DETAILS_KIND = "prune"; interface PruneCompactionDetails { kind: typeof PRUNE_DETAILS_KIND; version: 1; sourceEntriesProcessed: number; tailKept: number; splitPrefixMessages: number; } const DEFAULT_SETTINGS: Required = { overrideDefault: true, sectionLimit: DEFAULT_SECTION_LIMIT, transcriptLimit: DEFAULT_TRANSCRIPT_LIMIT, toolCapPerTurn: 8, debug: false, }; // ─── State ──────────────────────────────────────────────────────────────── let settings = { ...DEFAULT_SETTINGS }; // ─── Helpers ──────────────────────────────────────────────────────────── function loadSettings(pi: ExtensionAPI): void { const raw = ( pi as unknown as { settingsManager?: { getSettings?: () => { prune?: PruneSettings } }; } ).settingsManager?.getSettings?.(); if (raw?.prune) { settings = { ...DEFAULT_SETTINGS, ...raw.prune }; } } function isPruneCompaction(entry: unknown): boolean { const e = entry as { type?: string; summary?: string; fromHook?: boolean; details?: { kind?: string }; }; if (e?.type !== "compaction") return false; if (e.details?.kind === PRUNE_DETAILS_KIND) return true; // Backwards-compatible detection for prune compactions created before details existed. return ( e.fromHook === true && typeof e.summary === "string" && e.summary.includes("Use prune_recall") ); } function setContains(values: string[], value: string): boolean { return values.includes(value); } // ─── Core prune function ───────────────────────────────────────────────── function prune( messages: Message[], previous?: string, metadata: { sourceEntriesProcessed?: number; tailKept?: number; splitPrefixMessages?: number; tokenEstimate?: number; } = {}, ): string { const blocks = normalize(messages); const data = extract(blocks, { toolCapPerTurn: settings.toolCapPerTurn }); const output = format(data, { sectionLimit: settings.sectionLimit, transcriptLimit: settings.transcriptLimit, ...metadata, }); const summary = previous ? merge(previous, output.summary) : output.summary; if (settings.debug) { console.log("[prune]", { blocks: blocks.length, outputLines: output.stats.messagesOut, elapsedMs: output.stats.elapsedMs.toFixed(2), }); } return summary; } function toPruneMessage(message: unknown): Message | undefined { const m = message as { role?: string; content?: | string | Array<{ type: string; text?: string; name?: string; arguments?: Record; thinking?: string; }>; toolName?: string; isError?: boolean; command?: string; output?: string; exitCode?: number; summary?: string; }; switch (m.role) { case "user": return { role: "user", content: m.content }; case "assistant": return { role: "assistant", content: m.content }; case "tool": case "toolResult": return { role: "tool", content: m.content, toolName: m.toolName, isError: m.isError, }; case "bashExecution": return { role: "tool", content: m.output ?? "", toolName: "bash", isError: typeof m.exitCode === "number" ? m.exitCode !== 0 : false, }; case "branchSummary": case "compactionSummary": return m.summary ? { role: "assistant", content: m.summary } : undefined; case "custom": return undefined; default: if (settings.debug) console.log("[prune] skipped unsupported message role", m.role); return undefined; } } type SessionEntryLike = { type?: string; id?: string; message?: unknown; summary?: string; content?: unknown; }; function planRawTail( branchEntries: unknown[], firstKeptEntryId: string, ): { firstKeptEntryId: string; extraMessages: Message[]; rawTailKept: number } { const entries = branchEntries as SessionEntryLike[]; const oldIndex = entries.findIndex((entry) => entry.id === firstKeptEntryId); if (oldIndex < 0) return { firstKeptEntryId, extraMessages: [], rawTailKept: 0 }; let accumulated = 0; let candidate = oldIndex; for (let i = entries.length - 1; i >= oldIndex; i--) { const next = accumulated + estimateEntryTokens(entries[i]); if (next > MAX_RAW_TAIL_TOKENS) break; accumulated = next; if (isSafeBoundary(entries[i])) candidate = i; } const newFirstKeptEntryId = entries[candidate]?.id ?? firstKeptEntryId; const extraMessages = candidate > oldIndex ? entries .slice(oldIndex, candidate) .map(entryToPruneMessage) .filter((message): message is Message => message !== undefined) : []; return { firstKeptEntryId: newFirstKeptEntryId, extraMessages, rawTailKept: entries.length - candidate, }; } function entryToPruneMessage(entry: SessionEntryLike): Message | undefined { if (entry.type === "message") return toPruneMessage(entry.message); if (entry.type === "branch_summary" && entry.summary) return { role: "assistant", content: entry.summary }; if (entry.type === "custom_message") return { role: "user", content: entry.content as Message["content"] }; return undefined; } function isSafeBoundary(entry: SessionEntryLike): boolean { if (entry.type === "custom_message" || entry.type === "branch_summary") return true; if (entry.type !== "message") return false; const role = (entry.message as { role?: string } | undefined)?.role; return role === "user" || role === "assistant" || role === "bashExecution"; } function estimateEntryTokens(entry: SessionEntryLike): number { if (entry.type === "message") return estimateUnknownTokens(entry.message); if (entry.type === "branch_summary") return estimateStringTokens(entry.summary ?? ""); if (entry.type === "custom_message") return estimateUnknownTokens(entry.content); return 0; } function estimateUnknownTokens(value: unknown): number { if (typeof value === "string") return estimateStringTokens(value); if (Array.isArray(value)) return estimateStringTokens( value .map((part) => { if (typeof part !== "object" || part == null) return String(part); const p = part as { text?: string; thinking?: string; arguments?: unknown; name?: string; }; if (p.text) return p.text; if (p.thinking) return p.thinking; if (p.arguments) return `${p.name ?? ""} ${JSON.stringify(p.arguments)}`; return JSON.stringify(p); }) .join("\n"), ); if (value && typeof value === "object" && "content" in value) { return estimateUnknownTokens((value as { content?: unknown }).content); } return estimateStringTokens(JSON.stringify(value ?? "")); } function estimateStringTokens(text: string): number { return Math.ceil(text.length / 4); } // ─── Extension ──────────────────────────────────────────────────────────── export default function (pi: ExtensionAPI) { loadSettings(pi); function enableRecallTool(): void { const active = pi.getActiveTools(); if (!setContains(active, RECALL_TOOL)) pi.setActiveTools([...active, RECALL_TOOL]); } function disableRecallTool(): void { const active = pi.getActiveTools(); if (setContains(active, RECALL_TOOL)) pi.setActiveTools(active.filter((name) => name !== RECALL_TOOL)); } function syncRecallTool(ctx: { sessionManager: { getBranch(): unknown[] }; }): void { const hasPruneSummary = ctx.sessionManager .getBranch() .some(isPruneCompaction); if (hasPruneSummary) enableRecallTool(); else disableRecallTool(); } // ─── session_before_compact ────────────────────────────────────────── pi.on("session_before_compact", async (event) => { const { preparation } = event; if (!settings.overrideDefault) return; const tail = planRawTail(event.branchEntries, preparation.firstKeptEntryId); const allMessages = [ ...preparation.messagesToSummarize, ...preparation.turnPrefixMessages, ] .map(toPruneMessage) .filter((message): message is Message => message !== undefined); allMessages.push(...tail.extraMessages); const summary = prune(allMessages, preparation.previousSummary, { sourceEntriesProcessed: allMessages.length, tailKept: tail.rawTailKept, splitPrefixMessages: preparation.turnPrefixMessages.length, tokenEstimate: preparation.tokensBefore, }); const details: PruneCompactionDetails = { kind: PRUNE_DETAILS_KIND, version: 1, sourceEntriesProcessed: allMessages.length, tailKept: tail.rawTailKept, splitPrefixMessages: preparation.turnPrefixMessages.length, }; return { compaction: { summary, firstKeptEntryId: tail.firstKeptEntryId, tokensBefore: preparation.tokensBefore, details, }, }; }); // ─── recall tool activation ────────────────────────────────────────── pi.on("session_start", async (_event, ctx) => { syncRecallTool(ctx); }); pi.on("session_tree", async (_event, ctx) => { syncRecallTool(ctx); }); // ─── session_compact ───────────────────────────────────────────────── pi.on("session_compact", async (event, ctx) => { if (!event.fromExtension || !isPruneCompaction(event.compactionEntry)) return; enableRecallTool(); const entry = event.compactionEntry as { id?: string; summary?: string; tokensBefore?: number; }; const lineCount = entry.summary?.split("\n").length ?? 0; const msg = `prune compaction saved${entry.id ? ` #${entry.id}` : ""}: ${lineCount} lines${entry.tokensBefore ? ` from ${entry.tokensBefore.toLocaleString()} tok` : ""}`; if (settings.debug) console.log("[prune]", msg); if (ctx.hasUI) ctx.ui.notify(msg, "info"); }); // ─── Tool: prune_recall ─────────────────────────────────────────────── pi.registerTool({ name: "prune_recall", label: "Prune Recall", description: "Search compacted session history. Returns matching messages with relevance scores.", parameters: Type.Object({ query: Type.String({ description: "Search query (string or regex pattern)", }), scope: Type.Optional( Type.Union([Type.Literal("lineage"), Type.Literal("all")]), ), limit: Type.Optional(Type.Number({ minimum: 1, maximum: 20 })), expand: Type.Optional(Type.Array(Type.Number())), }), async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const results = recall(ctx.sessionManager, { query: params.query, scope: params.scope ?? "lineage", limit: params.limit ?? 5, expand: params.expand ?? [], }); return { content: [{ type: "text", text: formatRecallResults(results) }], details: { count: results.length }, }; }, }); // ─── Command: /prune ─────────────────────────────────────────────── pi.registerCommand("prune", { description: "Run lossless compaction: /prune [focus?]", handler: async (_args, ctx) => { if (settings.debug) console.log("[prune] Manual compaction requested"); ctx.compact({ onComplete: (result) => { if (ctx.hasUI) ctx.ui.notify( `prune compaction complete: ${result.summary.split("\n").length} lines`, "info", ); }, onError: (error) => { if (ctx.hasUI) ctx.ui.notify(`prune compaction failed: ${error.message}`, "error"); else console.error(`[prune] compaction failed: ${error.message}`); }, }); if (ctx.hasUI) ctx.ui.notify("prune compaction started", "info"); }, }); // ─── Command: /prune-recall ──────────────────────────────────────── pi.registerCommand("prune-recall", { description: "Search compacted history: /prune-recall [scope]", handler: async (args, ctx) => { const parts = args.trim().split(/\s+/).filter(Boolean); const scope = parts.at(-1) === "all" ? "all" : "lineage"; const query = scope === "all" ? parts.slice(0, -1).join(" ") : parts.join(" "); const results = recall(ctx.sessionManager, { query, scope, limit: 10 }); const text = formatRecallResults(results); if (ctx.hasUI) { ctx.ui.notify(text.slice(0, 1000), results.length ? "info" : "warning"); } else { console.log(text); } }, }); }