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

+90
View File
@@ -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.