← Catalog

pi-compactor

Phased context compaction for Pi: preflight handoff before compacting, safe points, pins, pruning, and per-model thresholds, all configurable from a TUI.

Package

Install

Install with PiG

pig install npm:pi-compactor

Install with Pi

pi install npm:pi-compactor
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "image": "https://raw.githubusercontent.com/jals1212/pi-compactor/main/assets/preview.png",
  "extensions": [
    "./extensions/compactor.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.2.0 (README.md). PiG does not review it.

🗜️ pi-compactor

pi-compactor: the agent hands off, then the press compacts the context

Phased context compaction for Pi: the agent hands off first, then the press comes down.

pi-compactor is an extension for Pi. When the context gets full, pi-compactor waits for a safe moment, asks the agent to hand off its state, and then compacts. The handoff survives compaction and the agent picks up where it left off.

soft threshold → (prune old tool outputs) → wait for a safe point → preflight: agent calls compaction_ready
              → compact with the configured strategy → resume if work was interrupted

Install

pi install npm:pi-compactor

How it works

  1. Pruning. When usage crosses softThreshold, large old tool outputs are replaced with a short stub. Superseded file reads go first, then the largest outputs. A read counts as superseded only when a later read of the same path covers it (the whole file, or the same offset/limit). The last pruning.keepRecentTurns turns are never touched, and neither is output the model has not seen yet (tool results after the last assistant message), even with keepRecentTurns: 0. If pruning brings usage back under the threshold, nothing else happens.

  2. Safe point. Compaction never interrupts important work. safePoint decides when it may run:

    • settle (default): only when the agent has finished.
    • turn: between turns, but not while tool calls from that turn are still pending.
    • any: at any boundary.

    Critical sections (see below) also defer it. Deferral is bounded: at hardThreshold, or once the context has grown by maxDeferTokens, the cycle proceeds anyway.

  3. Preflight. The agent receives hidden instructions to finish or pause, save what must persist, and call compaction_ready({ handoff }). Preflight is bounded by preflight.maxTurns and preflight.budgetTokens. If either limit is reached, compaction runs without a handoff.

  4. Compaction. The route depends on the runtime (ctx.mode). The cut keeps about Pi's compaction.keepRecentTokens of recent context, and the summary follows the strategy.

    • Interactive (TUI) and RPC: Pi's own compaction (ctx.compact), once the agent has settled, or at a turn end (aborting that turn) when the hard limit leaves no headroom. Pi fires session_before_compact and session_compact, so extensions that listen to them (memory extensions, for example) see the compaction. If the cycle interrupted the work, a hidden resume message is sent as a follow-up when the compaction completes.
    • Print and JSON: written as a boundary entry while the run settles (or at a turn end), because the runtime exits as soon as the prompt resolves and would abort a fire-and-forget compaction. No session_compact is fired. If the cycle interrupted the work, a hidden resume message follows the compaction and the run continues in the same prompt.

    /compactor now while idle always uses Pi's own compaction.

Pi's own threshold compaction is cancelled while pi-compactor still has headroom. Overflow compaction is never cancelled.

Strategies

StrategyWhat survives
summaryLLM summary of the discarded part + recent messages
hybrid (default)Handoff + contributions + LLM summary + recent messages
handoff-onlyHandoff + contributions only; no previous messages are kept and no LLM call is made. Without a handoff it falls back to hybrid and records the fallback.

Every strategy also keeps pins verbatim (the original request, user corrections, manual pins) and the cumulative lists of read and modified files.

With a UI, the footer always shows a 🗜️ status (status key compactor). The distance is measured against your own softThreshold for the current model, not Pi's built-in threshold.

StateText
Idle, usage known🗜️ 620k to compact (tokens left until softThreshold of the model's window; 999, 620k, 1.2M)
Idle, at or past the threshold🗜️ due 82%
Cycle running🗜️ pending 75%, preflight 75%, compacting 75% or cooldown 75%
Automatic compaction off (enabled: false, /compactor off)🗜️ off
Right after a compaction, until Pi reports usage again🗜️ compacted from 208k (🗜️ compacted when the size is unknown)
Usage not known yet (other cases)🗜️ measuring

The status updates at each turn end and settle, on session start and model change, and after every /compactor command (including settings and on/off).

Compaction count

Once the session has compacted, the status starts with how many compactions the current branch went through, followed by · and the state from the table above. The count is read from the session itself, so it survives /reload and restarts, and a fork counts only the compactions of its own branch. With no compactions yet the status has no count, exactly as above.

FooterRead it as
🗜️ 88k to compactNo compactions yet; 88k tokens left before the next cycle starts
🗜️ 1× · 88k to compactCompacted once; 88k tokens left before the next cycle
🗜️ 3× · preflight 75%Compacted three times; the fourth cycle is running: context is at 75% and the agent is writing its handoff
🗜️ 3× · compacted from 208kThe third compaction just finished; it started from 208k tokens
🗜️ 3× · start fresh · 88k to compactCompacted three times, and each compaction now keeps so much that a new session would give you clearly more room (see below)

When to start fresh

Compacting is not free. Every compaction leaves something behind that the next ones carry again: the summary, the handoff, pins and the lists of read and modified files. As that grows, each compaction gives you less room to work before the next one. At some point, opening a new session gives you more room than compacting again.

The compactor measures this from the session entries alone; nothing extra is stored:

  • Floor: the context of the session's first assistant turn (system prompt, tools, first request). This is what any new session costs.
  • Baseline: the context of the first assistant turn after the last compaction. This is what the session costs now.
  • Room: the token count at softThreshold (a percent of the model's window) minus the floor. With a 1M window and softThreshold: 40 the cycle starts at 400k tokens, so the room is 400k - floor. This is the space a new session has before its first compaction.
  • Carry-over: (baseline - floor) / room. The share of that room the last compaction still takes.

The carry-over is rounded to a whole percent, and the advice is decided on that rounded number, so what you read always matches the advice: when it reaches freshStartCarryover (default 25%), the footer adds start fresh. The baseline is only known after the first turn that follows a compaction, so the advice never shows right after compacting; it shows from the next turn on.

Example 1, large window, no advice. A model with a 1M window and softThreshold: 40 compacts at 400k. The session started at 60k (floor) and, after its third compaction, the next turn measured 105k (baseline).

room       = 400k - 60k            = 340k
carry-over = (105k - 60k) / 340k   = 13%    -> below 25%, no advice
footer     = 🗜️ 3× · 295k to compact

Each compaction still leaves 87% of what a new session would have, so compacting is the better deal.

Example 2, smaller window, advice. Same session on a model with a 200k window and softThreshold: 70, which compacts at 140k.

room       = 140k - 60k            = 80k
carry-over = (105k - 60k) / 80k    = 56%    -> 25% or more, advice
footer     = 🗜️ 3× · start fresh · 35k to compact

The same 45k left behind now takes more than half the room, so every compaction buys less than half of what a new session would.

The advice never resets anything; you decide when. The cheapest moment is a task boundary (a merged change, a closed task), once the state that matters lives in commits, task documents or memory, not only in the conversation. A new session starts with no pins and no compactions.

/compactor status shows the numbers behind the footer:

session: 3 compactions · carry-over 13% of a fresh session's room (start fresh at 25%)
session: 3 compactions · carry-over 56% of a fresh session's room (start fresh at 25%) · start fresh advised
session: 3 compactions · carry-over measured after the next turn
session: 0 compactions

The third line appears right after a compaction, until the next turn measures the new baseline.

Tune it with freshStartCarryover in /compactor settings: a lower value advises earlier, a higher one later, and 0 turns the advice off (the count stays).

Commands

CommandEffect
/compactor or /compactor statusPhase, usage, thresholds, critical sections, last compaction metrics (read from the session, so they survive /reload), session compactions and carry-over, settings warnings
/compactor nowStart a cycle now (preflight, then compact)
/compactor on / offEnable or disable automatic compaction for this project (.pi/compactor.json); warns when a model override keeps the effective setting unchanged
/compactor planDescribe what the next compaction would do, without doing it
/compactor pin <text>Pin text that survives every compaction in this session; pin alone lists pins. Warns when the pin is larger than pins.maxTokens. Pins cannot be removed: Pi has no API to delete session entries
/compactor settingsInteractive editor for every setting

Pins are session entries and Pi cannot remove them; a new session starts without pins.

Settings

Edit every setting with /compactor settings. You first pick a scope: global, project, or the current model in either file. The editor validates values and shows the effective value next to the scope's own value; Reset makes a key inherit from the lower layer again.

Precedence: defaults < global < project < global model override < project model override.

The editor writes these files, which are storage only:

  • Global: <Pi agent dir>/extensions/pi-compactor/config.json (default ~/.pi/agent)
  • Project: .pi/compactor.json

The project file is honored only when Pi trusts the project (ctx.isProjectTrusted()). In an untrusted project it is ignored, model overrides included, with the warning project settings ignored: project not trusted, and /compactor on|off and the editor's project scopes refuse to write it. Pi's own compaction.keepRecentTokens is read with the same trust. A Pi without isProjectTrusted keeps the previous behavior.

Settings are nested objects: write { "preflight": { "maxTurns": 7 } }, not { "preflight.maxTurns": 7 } (a flat dotted key is ignored with a warning). Percent settings (softThreshold, hardThreshold, freshStartCarryover) accept fractions; counts and token sizes are whole numbers. Model ids may contain spaces; provider/modelId is split at the first /.

Writes keep a symlinked config and its file mode (new files are created 0600). A project file that is a symlink pointing outside the project is never written through.

Per-model overrides live under "models": { "provider/modelId": { ... } }. Invalid values are ignored with a warning. A softThreshold that is not below hardThreshold is adjusted to hardThreshold - 5.

KeyDefaultMeaning
enabledtrueCompact automatically
softThreshold70Context % that starts a cycle
hardThreshold90Context % that stops waiting for a safe point
strategyhybridsummary, hybrid, handoff-only
safePointsettlesettle, turn, any
maxDeferTokens20000Most the context may grow while waiting
summaryModelnullprovider/modelId for summaries; null uses the session model
freshStartCarryover25Carry-over % that advises a fresh session in the footer; 0 turns the advice off
preflight.enabledtrueAsk the agent for a handoff first
preflight.maxTurns3Max agent turns for preflight
preflight.budgetTokens8000Max tokens preflight may add
preflight.templatenullCustom instructions; placeholders {{percent}}, {{reason}}, {{strategy}}, {{steps}}
pruning.enabledtruePrune old large tool outputs first
pruning.minToolResultTokens2000Smallest output that may be pruned
pruning.keepRecentTurns3Recent turns never pruned
pins.originalRequesttrueKeep the original request verbatim
pins.userCorrectionstrueKeep discarded user messages verbatim (newest first, within budget)
pins.maxTokens4000Budget for pins. The original request and manual pins are cut to fit it (manual pins together take at most half) and end with […truncated by the compactor: pin exceeds pins.maxTokens]

Agent tools

  • compaction_ready({ handoff }): hands off state during preflight. The handoff must not be empty.
  • compaction_defer({ active, reason? }): starts or ends a critical section that compaction waits for.

Extension protocol

The protocol runs over pi.events and does not depend on any particular extension. Listeners must act synchronously.

// Add preflight steps and handoff text.
pi.events.on("compactor:collect", (p) => {
  p.contribute({ source: "my-ext", steps: ["Flush the queue"], handoff: "Queue: 3 jobs pending" });
});

// Open and close a critical section.
pi.events.emit("compactor:defer", { source: "my-ext", active: true, reason: "migration" });
pi.events.emit("compactor:defer", { source: "my-ext", active: false });

// After each compaction: reason, why, strategy, handoff, tokensBefore and compactor (details).
pi.events.on("compactor:done", (metrics) => { /* ... */ });

Development

npm test   # node --test, no Pi install needed (fake Pi API)

prototype/retain-none.test.ts pins the Pi behavior that handoff-only relies on: a compaction whose firstKeptEntryId is null keeps nothing. Run it with PI_CODING_AGENT=<path to pi-coding-agent> node --test prototype/.

License

MIT