feat: two-tier smart compaction for Pi

Warn tier injects a one-shot context notice to the agent; force tier
triggers ctx.compact() at a clean turn boundary before Pi's built-in
threshold compaction. Never registers session_before_compact, so
pi-lcm stays in charge of DAG summaries; mirrors pi-dcp's null-token
caching and session_compact cycle reset.
This commit is contained in:
AlexKucera committed 2026-11-15 18:51:02 +01:00
commit 2c6d98995a
3 files changed
+292

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
/**
* 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 a clean turn boundary — deliberately BEFORE Pi's
* emergency threshold compaction (window − reserveTokens) fires. 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).
*
* 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) — force always fires before Pi's built-in
* threshold compaction, never after the window is already exhausted.
*/
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
interface SmartCompactUserConfig {
enabled?: boolean;
warnTokens?: number;
forceTokens?: number;
warnFraction?: number;
forceFraction?: number;
}
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. */
function resolveConfig(): SmartCompactConfig {
const read = (file: string): Partial<SmartCompactUserConfig> => {
try {
const raw = fs.readFileSync(file, "utf-8");
const parsed = JSON.parse(raw);
return parsed?.smartCompact ?? {};
} catch {
return {};
}
};
const merged: Partial<SmartCompactUserConfig> = {
...read(path.join(os.homedir(), ".pi", "agent", "settings.json")),
...read(path.join(process.cwd(), ".pi", "settings.json")),
};
return { ...DEFAULTS, ...merged };
}
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;
pi.on("turn_end", async (event: any, ctx: any) => {
const usage = ctx.getContextUsage?.();
if (usage?.tokens !== null && usage?.tokens !== undefined) {
lastKnownTokens = usage.tokens;
}
const tokens = usage?.tokens ?? lastKnownTokens;
if (tokens === null || tokens === undefined) return;
const window = usage?.contextWindow ?? null;
const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window);
const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window);
// ── Tier 2: force compaction at a clean turn boundary ──────────
// Runs before Pi's own threshold check (window − reserveTokens)
// thanks to forceFraction < 1 − reserve/window. ctx.compact()
// triggers LCM's session_before_compact hook when installed.
const cooldownActive = Date.now() - lastForceFailureAt < FAILURE_COOLDOWN_MS;
if (tokens >= forceAt && !forceInFlight && !cooldownActive) {
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 */
}
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;
},
onError: () => {
forceInFlight = false;
lastForceFailureAt = Date.now();
},
});
return;
}
// ── 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.
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
};
}
});
// New cycle after ANY compaction — manual (/compact, /lcm compact),
// forced (ours), threshold (Pi's), or overflow recovery.
const resetCycle = () => {
warnedThisCycle = false;
forceInFlight = false;
};
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 usage = ctx.getContextUsage?.();
const window = usage?.contextWindow ?? null;
const tokens = usage?.tokens ?? lastKnownTokens;
const warnAt = effective(cfg.warnTokens, cfg.warnFraction, window);
const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window);
const lines = [
`smart-compact ${cfg.enabled ? "enabled" : "DISABLED"}`,
` 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");
},
});
}