Context usage
ctx.getContextUsage()window + used tokens + percent
A better cockpit for coding agents
Ten focused tools that make context visible, work observable, and every agent session a little more deliberate.
10 extensions · 72 authored slides · 3 acts
Choose your entry point
M returns here · select a chapter to jump
Use arrow keys to explore sequentially.Press Esc for overview.
ACT I / 01
Before you optimize an agent, make its pressure, pace, and routing choices visible.
pi extension
Dot-grid view of your context window.
See the whole budget.
Zoom into what filled it.
the pain
Pi exposes one finite context budget. Without a breakdown, prompt instructions, active schemas, and conversation growth collapse into the same number.
one glance
under the dots
ctx.getContextUsage()window + used tokens + percent
chars ÷ 4prompt text and active schemas
model.maxTokensreserved for the next reply
zoom in
/context details. Expand the evidence.useful—not magical
System prompt rows expose named sections and advertised skill overhead.
Active tool descriptions and JSON parameters are listed separately from prompt instructions.
Per-turn and cumulative estimates reveal which entries are heavy before the next request.
Pi’s context usage gives the window, used total, and percent.
Visible prompt, tool, and turn details use token heuristics.
stop guessing at the grid
Then, after you send a message:
/context→/context detailsLive speed and first-token latency for Pi. Two readings from the reply you are watching—not another benchmark.
pi install npm:pi-gaugethen /reloadA reply can start slowly and stream quickly. Or start instantly, then crawl. One elapsed-time number hides the useful difference.
/gaugemode: e2e or streamstatus bar stays out of the proseNo provider dashboards, no copy/paste traces, and no change to the answer stream.
—⏱⚡Pi Reading the project boundaries
Pi and tracing the request path
Pi into the provider and back.
/gauge graphsession history, without leaving Pi · replay uses README example values/reload2 start a reply3 read TTFT + speed in the status bar
/gauge graphCompare recent completed replies at a glance. Switch modes, spot the outlier, then keep working.
Counts streamed usage when available; estimates token count from characters otherwise. Different providers/models can expose different usage timing and completion data.
Live TTFT, selectable e2e/stream speed, a compact graph—available from the shipped npm package.
pi install npm:pi-gauge↵/reloadoptional /gauge settingspi extension · provider priority tiers
One /fast toggle.
Four provider dialects.
the friction
the control exists · the interface is fragmented
To use it yourself, every provider needs a different field—and it only applies to a subset of models.
speed: "fast"service_tier: "priority"config.serviceTier: "priority"X-Vertex-AI-LLM-Shared-Request-Typethe insight
allowlist first · first rule wins
the trade
priority is a request option, not a latency promise
Priority may improve queueing or response time. Actual results depend on the provider, model, load, and account.
inside the request
copy-on-write · never overwrites your values
model: "gpt-5.1-codex"
messages: [...]
service_tier: absent
model: "gpt-5.1-codex"
messages: [...]
service_tier: "priority"
using it
/fasttoggle/fast onenable/fast offdisable/fast statusreportOff by default. Your choice is saved in ~/.pi/agent/pi-faster.json.
benefit & limits
use the lane when it helps · fall back when it fails
About 2× on OpenAI and Gemini. Premium rates on Anthropic.
Pi’s displayed cost may still show the standard rate.Above 10k tokens, toggling can miss the prompt cache once.
The next request may be slower and costlier once.Running /fast clears the pause. During the pause, retries run at standard speed.
verified install
github.com/championswimmer/pi-faster
Eligible models only · higher price · no speedup guarantee
ACT II / 02
Keep useful history, measure what the cache remembers, and advertise only the skills this prompt needs.
pi extension
Prune old tool output. Keep the summary.
What happened, why it matters, and refs to recover the originals.
the problem
Completed tool results remain part of future LLM context—even when the model already used them.
Old output consumes space before the new prompt even begins.
Resolved stack traces and match dumps compete with the task at hand.
why this is safe
Raw results are filtered only while Pi assembles the next request.
The extension appends index and summary entries; it does not delete or rewrite originals.
how it works
Read the auth flow, test failure points to token expiry, and matching session IDs live in four files.
context_tree_query({ toolCallIds: ["t2"] })using it
t1, t2, t3
Use context_tree_query with these refs to retrieve the original full outputs.
## toolRef: t2
Tool: bash
Args: {"command":"npm test"}
Status: ERROR
Turn: 6
FAIL src/token.test.ts:42
Expected 200, received 401
/pruner nowmanual flush/pruner treebrowse summaries + calls/pruner settingsmodel, trigger, displaychoose the boundary
agentic-autoThe model calls context_prune at a task boundary.defaultagent-messageBatch until a final text-only reply.cache-friendlyon-demandFlush only when you run /pruner now.manualon-context-tagFlush at context_checkpoint.pi-contextevery-turnFlush after each tool-using turn.debugKeep useful conclusions and short recovery refs in model context.
Latency is paid at the trigger boundary. Pick a cheap, fast summarizer model if desired.
If the summary is not smaller, originals remain and the prune frontier advances.
install
Summarize completed tool work. Prune future context. Recover every original when the details matter.
pi install npm:pi-context-prune/pruner onor try oncepi -e npm:pi-context-pruneOne cold turn tells you what happened.
The cumulative picture tells you what it means.
Per-turn spikes expose events. Cumulative hit rate exposes the overall cost of the timeline.
Pi can answer normally while an earlier context edit makes the provider re-write a long prompt prefix.
pi-context-prune affects cache hits without guessing — then inspect the active branch separately from the whole tree.It reads assistant-message usage already reported by Pi — no prompt inference, no extra model call.
cacheWrite stays separate from input and belongs in the denominator. // OPENAI-STYLE cacheWrite = 0; the same formula still applies.Find a cold start, reset, or suddenly weak hit rate in one turn.
Running cacheRead divided by the full prompt sent so far.
Stack input, cacheWrite, and cacheRead to see where tokens accumulated.
/cache graphCompare active branch and whole tree. Switch registered subagents with ← →.
/cache statsOpen the scrollable per-message table with prompt, received, hit, write, and hit%.
/cache exportWrite the stats model to <session-name>.csv at the project root.
Observability, not an optimizer.
Metrics cover assistant messages with provider-reported usage. Press r to refresh the snapshot; it does not auto-update or calculate API cost.
pi extension
Give Pi the right context for this task.
the pain
“Review these validation changes for missing edge cases.”
Useful skills should be advertised when they fit—not merely because they are installed.
why it exists
Additive on this branch. New relevant skills join the native Pi skills section. Earlier choices are never retracted.
how it works
separate, opt-in route
The picker selects skill metadata for Pi’s native skills section.
code-review→ advertisedOpt-in filtering withholds direct declarations and checks calls through Pi’s tool pipeline.
mcp__github→ availableRelevance routing, not a permissions sandbox. It does not govern OS access, process isolation, credentials, discovery, or MCP connections.
use it in Pi
Pi classifiers, TypeSafe, OpenAI, Gemini, or OpenRouter. No model is selected by default.
Global and project always-allowed lists bypass scoring; tool filtering remains independent.
Metadata leaves Pi. Decisions add latency and may incur provider charges. Failed rounds add nothing.
route less noise into the next prompt
ACT III / 03
Turn an agent session into a visible system: plan it, fan it out, watch it run, and bring the result back.
pi extension
A visible plan for long-running agent work.
the problem
Tool calls, test output and edits keep moving it upward.
plan
1 design schema
2 wire up store
3 add tests
4 update docs
read src/store.ts
edit src/store.ts +42 -7
$ npm test
3 failed
read test/store.test.ts
edit src/store.ts +9 -2
$ npm test
read src/render.ts
edit src/render.ts +18 -4
$ npm run build
the idea
create
update
read
☑ 2/4
The agent and the TUI read the same session-scoped checklist.
what it gives the agent
checklist_createCreate, replace or append tasks.
checklist_readRead status, readiness and blockers.
checklist_updateAdvance state or revise open tasks.
A task may also be cancelled; cancelled → planned is allowed.
the dependency gate
› checklist_update p9z → ongoing
blocked by [m2x]
cannot move planned → ongoing
› checklist_update m2x → done
m2x ongoing → done
› checklist_update p9z → ongoing
p9z planned → ongoing
using it
› plan and implement the auth refactor
checklist_create 4 tasks
0/4 done · 3 ready · 1 blocked
checklist_update k7q, m2x
1/4 done · 1 ongoing · 1 ready · 1 blocked
☑ 1/41111
PROG m2x Wire up store
REDY r4d Update docs
BLCK p9z Add tests ← m2x
DONE k7q Design schema
/checklistopen every task
/checklist addadd one by hand
/checklist settingstune display + guidance
/checklist hideclear the persistent view
practical value
Survives /resume, /branch, /undo and compaction.
The live widget prioritizes and shows the top five; the dialog shows all.
Optional preview. Sibling-only dependencies keep the graph local.
Limits: a maximum of 10 tasks per session list; completed tasks are frozen. Create a new task to revise finished work.
install
or pi install git:github.com/championswimmer/pi-checklist
Requires Pi 1.5.0+ and Node.js 22.19.0+
Parallel subagents you can watch and steer.
When every helper is foreground work, research blocks coding, coding blocks review — and your main thread waits too.
Spawn independent siblings with wait: false.
agent_spawn(..., wait: false)
The main conversation stays available while helpers work.
Watch live, queue direction, wait for a result, or stop a subtree.
agent_steer · agent_wait
Use it when the task depends on what you have already discussed.
/agents fork:coder fix the failing auth test
Use it for a task that needs no conversation history.
/agents fresh:researcher audit retry handling
/agents tree watchEnter steeri actionsCtrl+Q main
/agents typesconfigure roles or add your ownFan out independent work, see every branch, and steer before a wrong turn becomes a finished answer.
pi install npm:pi-subagent-managerDon’t run multiple subagent extensions together — they clash on /agents.
Long jobs keep running. Pi only comes back for a matching line.
The command is simple. The attention model around it is not.
Other prompts and parallel edits sit behind the slow job.
sleep 10; tailcompiling…routinesleep 10; tailheartbeat okroutinesleep 10; tailwatching filesroutineRepeated inspection spends model attention on unchanged state.
bgmon separates process ownership, retained output, and notification delivery.
bgmon_start launches Bash in an owned private tmux server.
Output lands in a bounded, rotating journal with visible gaps.
contains, regex, any, or exit filters completed lines and states.
ui, nextTurn, or wake emits a bounded notification.
bgmon_inspect(id, after)
page the retained log; there is no server-side grep.
bgmon_startcommand: “npm run build”
kind: regexpattern: error|failedflags: ifrom: retaineddelivery: wake
bgmon_watchmatch a line, emit metadata
{"delivery":"wake","status":"listening"}
Shutdown detaches the controller; it does not mean automatic recovery on the next launch.
logRef can still be read later.attach is for manual tmux access. logRef is for session-owned historical inspection—not controller recovery.
Builds, test suites, servers and tail -f run away from the foreground turn.
Line and terminal-state watches replace repeated “is it done yet?” inspection.
Page retained output, or open the read-only /bgmon viewer.
wake can start a turn when idle; delivery is best effort and observation is not guaranteed.Install the shipped extension, reload Pi, and ask for the behavior you want.
pi install npm:pi-background-monitor“Run npm run build in the background. Wake me if output matches error|failed, and keep the log for me to inspect.”
bgmon_start+bgmon_watch+bgmon_inspectThe PR, the checks, and nothing that costs you a glance.
git symbolic-refAsk gh pr view for this branch.
github.com/…/pull/246Used only when the branch has no open PR.
pi-footer:update-widget→draw the footer#41208pr-statuswidgetIdUse externalStatusKey: "pr-status"
with fg: "default", no extra icon.
gh-pr-numberlinked #gh-pr-stateopen / merged / closedgh-pr-checkscolored iconsgh-pr-passedraw countgh-pr-runningraw countgh-pr-failedraw countgh-pr-repoowner/repogh-pr-titletitleMissing PRs and zero-count widgets clear, so your layout never lies.
OSC 8 wraps the PR number only.
Passed, running, failed — only when nonzero.
Refreshes every 30 seconds in the background.
pi-footer is the host and the widget surface.
git + authenticated gh find and read the PR.
Nerd Font + OSC 8 terminal render glyphs and clickable links.
Your next move
Pick the extension that removes the most friction from your current session. You can always come back for the rest.
Ten small tools. One more deliberate coding loop. · Press M for the map.