import type { ExtensionAPI } from "@selesai/code"; /** * Compact automatically once context exceeds `compaction.thresholdTokens` (settings.json). * Runs when the agent settles, so it never races a streaming response. * ponytail: checked per settled run, not mid-run; core reserveTokens still guards mid-run overflow. */ export default function autoCompactExtension(pi: ExtensionAPI): void { let compacting = false; pi.on("agent_settled", (_event, ctx) => { const threshold = (pi.getSettings().compaction as { thresholdTokens?: unknown } | undefined)?.thresholdTokens; if (compacting || typeof threshold !== "number" || threshold <= 0) return; if (pi.getSettings().compaction?.enabled === false) return; const tokens = ctx.getContextUsage()?.tokens; if (typeof tokens !== "number" || tokens <= threshold) return; compacting = true; const done = () => { compacting = false; }; ctx.compact({ onComplete: done, onError: (error) => { done(); ctx.ui.notify(`Auto-compact failed: ${error.message}`, "warning"); }, }); }); }