Add the metadata layer from /init-project: canonical GPL-3.0-or-later LICENSE, CITATION.cff, seeded CHANGELOG, .editorconfig, and ADRs 0001-0003 recording the stack, license, and forge/CI decisions. README gains a forge badge and a License section. Root AGENTS.md gains the DOX framework with child docs for docs/, docs/devlog/, and docs/adr/ so the doc tree has binding contracts.
7.2 KiB
Smart Compact
Two-tier context management for Pi: a gentle heads-up to the agent when context fills up, and a deliberate compaction when the session settles, well 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 the agent_settled boundary — the first moment no run is active, so nothing in progress is aborted. With a UI notification. |
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. When (1 − forceFraction) × window > reserveTokens (defaults: windows above ~82k) the force threshold sits below the built-in trigger, but execution order is not guaranteed: a run that crosses both thresholds before settling lets Pi's built-in check compact first — which is safe, it preserves the run.
Compatibility
This is the design center. Smart Compact deliberately touches only the events the other extensions don't own:
pi-lcm
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 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().tokensreturnsnullimmediately after compaction (before the first post-compaction response). The last non-null value is cached and used as a fallback — and the cache is cleared onsession_compact, so a stale pre-compaction count cannot re-trigger the force tier. - 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 (
warnedThisCycleflag). - Force fires only at
agent_settled(never mid-run), once per cycle with an in-flight lock, plus a 60s cooldown after a failed compaction. Mid-run, Pi's built-in threshold check and overflow recovery remain the actors and preserve the run. continue: trueon 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):
{
"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 opens a centered overlay panel (the /dcp context look): current tokens, a usage bar, both effective thresholds (with crossed indicators), and cycle flags. Dismiss it with esc, enter, q, or ctrl+c. Where overlays are unavailable (print/RPC mode) it falls back to a plain notification. 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:
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 fromsession_before_compactso pi-lcm (or any other compaction-owning extension) stays in charge of summary generation. - Force runs at
agent_settled, notturn_end.ctx.compact()aborts any active run and never resumes the interrupted turn, so triggering it mid-run would destroy agent work. Atagent_settledthe session is idle (ctx.isIdle()is guaranteed) and compaction aborts nothing. - 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 -psmoke test). - 14-test committed harness:
node --test harness.ts(Node ≥ 22.18 with type stripping). Covers warn-once-per-cycle at the effective threshold, force only atagent_settled(never fromturn_end, not when busy), awaiting compaction completion in the settled handler, the in-flight lock and failure cooldown, the stale-token guard aftersession_compact, per-field config validation (null/string/zero/oversized values), cycle reset,enabled: false, and the status command. - Live-session validation of the first real 100k crossing is still pending — the warn message is a single string in
index.tsif the wording needs tuning.
License
GPL-3.0-or-later — see LICENSE.