/** * smart-compact — two-tier context management. * * Tier 1 (warn): when context crosses the warn threshold, inject a short * custom_message telling the agent to be economical. Once per compaction * cycle. Invisible to the user UI (display: false). * Tier 2 (force): when context crosses the force threshold, trigger * ctx.compact() at the agent_settled boundary — the first point where no * run is active. ctx.compact() aborts any active run and never resumes * the interrupted turn, so it must NOT be called from turn_end mid-run. * Mid-run, Pi's built-in threshold check (window − reserveTokens) remains * the actor and preserves the run; our force fires before the next prompt * instead. Under that condition the force threshold sits below the * built-in trigger (window − reserveTokens; defaults: window > ~82k), * but ordering is not guaranteed: a run that crosses both thresholds * before settling lets Pi's built-in check compact first — safely, it * preserves the run. * Once per cycle, with a cooldown on failure. * * Compatibility with other extensions in this setup: * - pi-lcm: LCM owns session_before_compact (DAG summaries). This * extension NEVER registers that event; ctx.compact() routes through * LCM's hook automatically, so forced compactions get the DAG summary. * customInstructions only matter if LCM declines (< minMessages) and * Pi's default compaction runs instead. * - @davecodes/pi-dcp: DCP nudges the model to call its `compress` tool * (30k soft / 70k hard by default) and resets its own nudge tracking * on session_compact. We do the same reset, and our warn message * deliberately does not duplicate DCP's compress-the-tool language. * ctx.getContextUsage().tokens is null right after compaction, so we * cache the last non-null value (same workaround DCP uses) — and clear * that cache on session_compact, because a stale pre-compaction count * would immediately re-trigger the force tier. * * Config (~/.pi/agent/settings.json or project .pi/settings.json): * "smartCompact": { * "enabled": true, * "warnTokens": 100000, // absolute warn floor * "forceTokens": 200000, // absolute force floor * "warnFraction": 0.55, // effective warn = min(warnTokens, fraction × window) * "forceFraction": 0.8 // effective force = min(forceTokens, fraction × window) * } * Fractions keep the tiers correctly ordered on models with smaller * windows (e.g. 128k). Invalid values (wrong type, non-finite, out of * range) fall back per field to the defaults above — a null or string * token count must neither zero the threshold nor silently NaN it away. */ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; interface SmartCompactConfig { enabled: boolean; warnTokens: number; forceTokens: number; warnFraction: number; forceFraction: number; } const DEFAULTS: SmartCompactConfig = { enabled: true, warnTokens: 100_000, forceTokens: 200_000, warnFraction: 0.55, forceFraction: 0.8, }; /** * Project .pi/settings.json overrides the global file, mirroring pi-lcm. * Each field is validated; invalid values fall back to that field's default. */ function resolveConfig(): SmartCompactConfig { const read = (file: string): Partial => { try { const raw = fs.readFileSync(file, "utf-8"); const parsed = JSON.parse(raw); return parsed?.smartCompact ?? {}; } catch { return {}; } }; const merged: Partial = { ...read(path.join(os.homedir(), ".pi", "agent", "settings.json")), ...read(path.join(process.cwd(), ".pi", "settings.json")), }; const num = (value: unknown, ok: (n: number) => boolean): number | undefined => { if (typeof value !== "number" || !Number.isFinite(value)) return undefined; return ok(value) ? value : undefined; }; return { enabled: typeof merged.enabled === "boolean" ? merged.enabled : DEFAULTS.enabled, warnTokens: num(merged.warnTokens, (n) => n > 0) ?? DEFAULTS.warnTokens, forceTokens: num(merged.forceTokens, (n) => n > 0) ?? DEFAULTS.forceTokens, warnFraction: num(merged.warnFraction, (n) => n > 0 && n <= 1) ?? DEFAULTS.warnFraction, forceFraction: num(merged.forceFraction, (n) => n > 0 && n <= 1) ?? DEFAULTS.forceFraction, }; } const FAILURE_COOLDOWN_MS = 60_000; export default function smartCompact(pi: any) { const cfg = resolveConfig(); if (!cfg.enabled) return; let warnedThisCycle = false; let forceInFlight = false; let lastForceFailureAt = 0; let lastKnownTokens: number | null = null; /** min(absolute, fraction × window); absolute-only when window unknown. */ const effective = (absolute: number, fraction: number, window?: number | null): number => window && window > 0 ? Math.min(absolute, Math.floor(fraction * window)) : absolute; /** Track tokens through the null-usage window that follows compaction. */ const currentTokens = (ctx: any): { tokens: number | null; window: number | null } => { const usage = ctx.getContextUsage?.(); if (usage?.tokens !== null && usage?.tokens !== undefined) { lastKnownTokens = usage.tokens; } return { tokens: usage?.tokens ?? lastKnownTokens, window: usage?.contextWindow ?? null, }; }; // ── Tier 1: one-shot heads-up to the agent ───────────────────── // Complements pi-dcp's compress nudges (no compress-tool language) // and gives advance notice before forced compaction. pi.on("turn_end", async (event: any, ctx: any) => { const { tokens, window } = currentTokens(ctx); if (tokens === null) return; const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window); if (!warnedThisCycle && tokens >= warnAt) { warnedThisCycle = true; const pct = window ? ` (~${Math.round((tokens / window) * 100)}% of window)` : ""; return { entries: [ ...(event.entries ?? []), { type: "custom_message", customType: "smart-compact-notice", content: `[context notice] Context is at ${Math.round(tokens / 1000)}k tokens${pct}. ` + "Be economical now: prefer targeted searches and read ranges over full files, " + "and consolidate findings as you go. Auto-compaction will run before the window " + "fills — keep key facts stated explicitly in your replies.", display: false, }, ], continue: true, // only forces a request if the run was ending anyway }; } }); // ── Tier 2: force compaction once the session has settled ────────── // agent_settled is the first point where no run is active (ctx.isIdle() // is true there), so ctx.compact() aborts nothing. Never call it from // turn_end: manual compaction aborts the active run and does not resume // the interrupted turn. pi.on("agent_settled", async (_event: any, ctx: any) => { if (forceInFlight) return; if (Date.now() - lastForceFailureAt < FAILURE_COOLDOWN_MS) return; if (ctx.isIdle && !ctx.isIdle()) return; const { tokens, window } = currentTokens(ctx); if (tokens === null) return; // unknown after compaction — wait for fresh usage const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window); if (tokens < forceAt) return; forceInFlight = true; warnedThisCycle = true; // warning is moot now try { ctx.ui?.notify?.( `smart-compact: ${Math.round(tokens / 1000)}k tokens — compacting`, "info", ); } catch { /* notification is best-effort */ } // Await completion: prompts deferred from agent_settled (and print-mode // message loops) must resume after the compaction finishes, not race it. await new Promise((resolve) => { ctx.compact({ // Used only if LCM declines and Pi's default compaction runs. customInstructions: "Thorough summary: preserve file paths, symbols, line anchors, " + "decisions with rationale, and open tasks.", onComplete: () => { forceInFlight = false; resolve(); }, onError: () => { forceInFlight = false; lastForceFailureAt = Date.now(); resolve(); }, }); }); }); // New cycle after ANY compaction — manual (/compact, /lcm compact), // forced (ours), threshold (Pi's), or overflow recovery. The token // cache must be cleared too: usage reads null until the next assistant // response, and the stale pre-compaction count would re-trigger force. const resetCycle = () => { warnedThisCycle = false; forceInFlight = false; lastKnownTokens = null; }; pi.on("session_compact", async () => resetCycle()); pi.on("session_compact_failed", async () => { forceInFlight = false; // Keep warnedThisCycle set — context is still large; don't re-nag. }); // ── Debug/status command ───────────────────────────────────────── pi.registerCommand?.("smart-compact", { description: "Show smart-compact thresholds and current state", handler: async (_args: string | undefined, ctx: any) => { const { tokens, window } = currentTokens(ctx); const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window); const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window); const lines = [ "smart-compact enabled", ` tokens now: ${tokens === null ? "unknown" : `${Math.round(tokens / 1000)}k`}`, ` window: ${window ? `${Math.round(window / 1000)}k` : "unknown"}`, ` warn threshold: ${Math.round(warnAt / 1000)}k${tokens !== null && tokens >= warnAt ? " (crossed)" : ""}`, ` force threshold: ${Math.round(forceAt / 1000)}k${tokens !== null && tokens >= forceAt ? " (crossed)" : ""}`, ` warned this cycle: ${warnedThisCycle}`, ` force in flight: ${forceInFlight}`, ]; ctx.ui?.notify?.(lines.join("\n"), "info"); }, }); }