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:
commit
2c6d98995a
3 files changed
+292
No files matched your search
@@ -0,0 +1,2 @@
|
||||
.DS_Store
|
||||
node_modules/
|
||||
@@ -0,0 +1,90 @@
|
||||
# Smart Compact
|
||||
|
||||
**Two-tier context management for [Pi](https://github.com/earendil-works/pi): a gentle heads-up to the agent when context fills up, and a deliberate compaction at a clean turn boundary before the window is exhausted. Designed to compose with pi-lcm and pi-dcp instead of fighting them.**
|
||||
|
||||
## Why Smart Compact
|
||||
|
||||
Pi's built-in auto-compaction works, but it's a single emergency trigger: when context passes `contextWindow − reserveTokens`, everything old gets summarized in one shot. Two things get lost:
|
||||
|
||||
- **The agent never sees it coming.** At 100k tokens the model is still happily reading whole files and dumping full tool output, unaware that in a few turns its working memory is about to be summarized away.
|
||||
- **Compaction happens at the worst moment** — right at the edge, with a 16k reserve, during whatever the agent happened to be doing.
|
||||
|
||||
Smart Compact adds the two missing tiers:
|
||||
|
||||
| Tier | Trigger | Action |
|
||||
|------|---------|--------|
|
||||
| **Warn** | `min(warnTokens, warnFraction × window)` — default 100k or 55% | One-shot `custom_message` into the context (invisible in the UI, ~60 tokens): prefer targeted searches over full files, consolidate findings, keep key facts stated explicitly. |
|
||||
| **Force** | `min(forceTokens, forceFraction × window)` — default 200k or 80% | `ctx.compact()` at a clean turn boundary, with a UI notification. Always fires *before* Pi's built-in threshold compaction. |
|
||||
|
||||
The fractional floors keep both tiers correctly ordered on any window size. On a 128k model: warn ≈ 70k, force ≈ 102k, built-in emergency at 112k. On a 200k model: warn 100k, force 160k, built-in at 184k. The absolute values act as ceilings for very large windows.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This is the design center. Smart Compact deliberately touches only the events the other extensions don't own:
|
||||
|
||||
### pi-lcm
|
||||
|
||||
[pi-lcm](https://www.npmjs.com/package/pi-lcm) hooks `session_before_compact` to replace Pi's flat summary with a hierarchical DAG (searchable via `lcm_grep` / `lcm_expand`). Smart Compact **never registers `session_before_compact`** — the one hook that would conflict. It triggers compaction only through `ctx.compact()`, which fires LCM's hook like any other compaction, so forced compactions get the DAG summary. The `customInstructions` passed to `ctx.compact()` only matter if LCM declines (fewer than `minMessagesForCompaction` messages) and Pi's default compaction runs instead.
|
||||
|
||||
### @davecodes/pi-dcp
|
||||
|
||||
[pi-dcp](https://www.npmjs.com/package/@davecodes/pi-dcp) nudges the model (30k soft / 70k hard by default) toward its `compress` tool, which shrinks old tool results in place. Smart Compact's warn message uses deliberately different language — general frugality and advance notice, not compress-the-tool — so the model doesn't get two copies of the same instruction. It also copies DCP's two hardening patterns:
|
||||
|
||||
- **Null-token window.** `ctx.getContextUsage().tokens` returns `null` immediately after compaction (before the first post-compaction response). The last non-null value is cached and used as a fallback.
|
||||
- **Cycle reset.** State resets on `session_compact`, so the warn can fire once per compaction cycle rather than once per session. This also catches `/compact`, `/lcm compact`, and Pi's own threshold/overflow compactions.
|
||||
|
||||
## Guards
|
||||
|
||||
- Warn fires once per cycle (`warnedThisCycle` flag).
|
||||
- Force is once per cycle with an in-flight lock, plus a 60s cooldown after a failed compaction. Pi's overflow recovery remains the final backstop.
|
||||
- `continue: true` on the warn entry only forces a model request if the run was ending anyway — mid-run it rides along with the next request free.
|
||||
|
||||
## Configuration
|
||||
|
||||
Optional. `~/.pi/agent/settings.json` (global) or `.pi/settings.json` (project; wins):
|
||||
|
||||
```json
|
||||
{
|
||||
"smartCompact": {
|
||||
"enabled": true,
|
||||
"warnTokens": 100000,
|
||||
"forceTokens": 200000,
|
||||
"warnFraction": 0.55,
|
||||
"forceFraction": 0.8
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|-----|---------|---------|
|
||||
| `enabled` | `true` | Master switch; extension loads as a no-op when `false` |
|
||||
| `warnTokens` | `100000` | Absolute warn floor (token count) |
|
||||
| `forceTokens` | `200000` | Absolute force floor (token count) |
|
||||
| `warnFraction` | `0.55` | Fraction of the context window; effective warn = `min(warnTokens, warnFraction × window)` |
|
||||
| `forceFraction` | `0.8` | Effective force = `min(forceTokens, forceFraction × window)` |
|
||||
|
||||
## Command
|
||||
|
||||
`/smart-compact` shows live state: current tokens, window, both effective thresholds (with crossed indicators), and cycle flags. Useful for checking what a given model's thresholds resolve to without filling a session.
|
||||
|
||||
## Install
|
||||
|
||||
Single file, no dependencies. Symlink from Pi's global extensions directory:
|
||||
|
||||
```bash
|
||||
ln -s /path/to/pi-extensions/smart-compact ~/.pi/agent/extensions/smart-compact
|
||||
```
|
||||
|
||||
Pi discovers `*/index.ts` one level deep, following the symlink. Reload with `/reload`.
|
||||
|
||||
## Design notes
|
||||
|
||||
- **Warn is a `custom_message`, not a system-prompt addendum.** Dynamic prompt addendum changes break provider prompt caching; an in-conversation message costs ~60 tokens once and is a valid compaction cut point.
|
||||
- **Force uses `ctx.compact()` rather than returning a compaction from `session_before_compact`** so pi-lcm (or any other compaction-owning extension) stays in charge of summary generation.
|
||||
- **Thresholds are computed per turn** from `ctx.getContextUsage()`, so model switches mid-session (e.g. to a different window size) take effect immediately.
|
||||
|
||||
## Verification
|
||||
|
||||
- Loads clean under Pi 1.5.2 (`pi -p` smoke test).
|
||||
- 16/16 mock-harness assertions: warn fires once per cycle at the effective threshold; force calls `ctx.compact` before the built-in trigger on both 200k and 128k windows; in-flight and failure-cooldown guards; null-token fallback; cycle reset on `session_compact`; status command output.
|
||||
- Live-session validation of the first real 100k crossing is still pending — the warn message is a single string in `index.ts` if the wording needs tuning.
|
||||
@@ -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");
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user