A better cockpit for coding agents

The Pi
extension suite.

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

One system. Ten levers.

M returns here · select a chapter to jump

Use arrow keys to explore sequentially.Press Esc for overview.

ACT I / 01

First, see the system.

Before you optimize an agent, make its pressure, pace, and routing choices visible.

context-usagegaugefaster

pi extension

pi-context-usage

Dot-grid view of your context window.

See the whole budget.
Zoom into what filled it.

$pi install npm:pi-context-usage
pi-context-usage blue and amber dot-grid icon
11 × 8 dot budget/context summary/context details inspect

the pain

A token total tells you that space is gone.
Not what took it.

session contextsingle total
31.4k / 200.0k
used 16%
system prompt?tool schemas?large outputs?old turns?
?

You can see the edge of the window.

Pi exposes one finite context budget. Without a breakdown, prompt instructions, active schemas, and conversation growth collapse into the same number.

Guesswork is the problem—not the total.

one glance

Fill the window. Keep five layers visible.

11 columns × 8 rows
Context Usagedocumented sample
0%claude-sonnet-4-5 · 200.0k
buckettokenswindow
System Prompt1.7k1%
Tools2750%
Messages29.4k15%
Empty152.2k76%
Buffer16.4k8%
Values follow the README’s concrete example. One dot is proportional—not exactly one token.

under the dots

Five buckets. Two measurement layers.

reported

Context usage

ctx.getContextUsage()

window + used tokens + percent

visible estimate

System + tools

chars ÷ 4

prompt text and active schemas

model budget

Output buffer

model.maxTokens

reserved for the next reply

System Promptceil(prompt.length / 4)
Toolsname + description + parameters
Messagesused − visible system − tools
Emptywindow − used − buffer
Buffermodel.maxTokens
Important: summary size and percent come from Pi’s usage API; the visible prompt and tool split is intentionally estimated.

zoom in

Run /context details. Expand the evidence.

↑↓EnterTabEsc
/context details90% overlay
Context Usage31.4k / 200.0k tokens (16%)
▾System Prompt1.7k tokens est. · README sample
▸<tools>serialized prompt section
▸Available Skillsskill rows exposed in prompt
▾Rulesexpand to read the text
Visible rule text from the system prompt…
▾Tools275 tokens est. · README sample
▸active tooldescription + schema preview
▾Conversation29.4k derived · per-message drill-down

useful—not magical

A map for deciding where to look.

1

Spot a large baseline

System prompt rows expose named sections and advertised skill overhead.

2

Find schema weight

Active tool descriptions and JSON parameters are listed separately from prompt instructions.

3

Trace conversation growth

Per-turn and cumulative estimates reveal which entries are heavy before the next request.

≈

Know the boundary.

Measured / reported

Pi’s context usage gives the window, used total, and percent.

Estimated / inspectable

Visible prompt, tool, and turn details use token heuristics.

Different totals are expected. Provider-side scaffolding and cached context are not visible to the extension, so the cached prompt number is not directly comparable with the visible sum.
pi-context-usage icon

stop guessing at the grid

Install once.
See every layer.

$pi install npm:pi-context-usage

Then, after you send a message:

/context→/context details
github.com/championswimmer/pi-context-usage
SHIPPED EXTENSION pi-gauge

See the wait.
Feel the stream.

Live speed and first-token latency for Pi. Two readings from the reply you are watching—not another benchmark.

pi install npm:pi-gaugethen /reload
first token tokens / sec graph on demand
TOKENS / SEC
FIRST TOKEN—TTFT
STREAMING—tokens / sec
README example values · live pattern
THE PROBLEM

“It feels slow” mixes two different waits.

A reply can start slowly and stream quickly. Or start instantly, then crawl. One elapsed-time number hides the useful difference.

01Waiting for the first token
before outputTTFT
≠
02How fast the answer arrives
Thereplyismoving.
after the first tokenstream speed
Gauge separates them.So “slow” becomes a diagnosis, not a hunch.
TWO READINGS, ONE REPLY

Measure the silence.
Then measure the flow.

WAITfrom turn start → first delta
TTFTtime to first token
capturesqueue + provider latency
FLOWfirst delta → message end
t/sstreaming throughput
also availablerequest-wide e2e speed
/gaugemode: e2e or streamstatus bar stays out of the prose
HOW IT WORKS

Listen to Pi’s events. Draw one tiny instrument.

No provider dashboards, no copy/paste traces, and no change to the answer stream.

01before_agent_startstart the clock—
02first *_deltarecord TTFT⏱
03message_endfreeze the reading⚡
throughput denominatore2e request startstream first token
live for the current turn text, off, or ◖ ◕ sparkline widget render throttled to 120ms
CONCRETE USAGE

Run a command. Watch the reply become data.

pi · current session
pi› explain this repository

Pi Reading the project boundaries

Pi and tracing the request path

Pi into the provider and back.

gauge⚡ — t/s⏱ —mswaiting
/gauge graphsession history, without leaving Pi · replay uses README example values
1 install + /reload2 start a reply3 read TTFT + speed in the status bar
ON DEMAND

/gauge graph
sees the pattern.

Compare recent completed replies at a glance. Switch modes, spot the outlier, then keep working.

  • e2eend-to-end average from request start
  • streamspeed excludes the first-token wait
  • TTFTalways shown alongside the graph
pi-gauge · recent turnsconceptual shape
faster →
01020304050607
no score. no leaderboard.just your session
USEFUL CONTEXT, NOT CERTAINTY

Counts streamed usage when available; estimates token count from characters otherwise. Different providers/models can expose different usage timing and completion data.

VERIFIED INSTALL

Put a little
instrument
in Pi.

Live TTFT, selectable e2e/stream speed, a compact graph—available from the shipped npm package.

in Pipi install npm:pi-gauge↵
then /reloadoptional /gauge settings
pi-gauge amber and blue speedometer icon
pi-gauge0.3.2
✓ npm package installed path✓ commands: /gauge, settings, graph✓ source README matches this deck
FIRSTwaitTHENflow
Measure the reply you have.Not the benchmark you don’t.
pi-faster coral chevron icon

pi extension · provider priority tiers

pi-faster

One /fast toggle.
Four provider dialects.

request·eligible lane·higher price

the friction

the control exists · the interface is fragmented

Priority mode speaks four dialects.

To use it yourself, every provider needs a different field—and it only applies to a subset of models.

01
Anthropicspeed: "fast"
02
OpenAI · Azure · Codexservice_tier: "priority"
03
Gemini APIconfig.serviceTier: "priority"
04
Vertex AIX-Vertex-AI-LLM-Shared-Request-Type
> Choose the model and know the provider rule—or leave the request alone.

the insight

allowlist first · first rule wins

The toggle is broad.
The request change is not.

incoming request
apiprovidermodel
fast-config.json eligible? API + provider + model
MATCH inject priority field supported model lane
— NO MATCH payload untouched unsupported · Bedrock included
Safety property: unknown models are never “best-effort” injected.

the trade

priority is a request option, not a latency promise

Same work. A different service lane.

STANDARDnormal lane
request
rate
standard
request
unchanged
vs
ELIGIBLEpriority lane
request
rate
higher price
request
priority fields
NO SPEEDUP GUARANTEED

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

Match, then make the smallest change.

before_provider_requestincoming
model: "gpt-5.1-codex" messages: [...] service_tier: absent
applyFast()+ setonly if absent / null
provider-native payloadoutgoing
model: "gpt-5.1-codex" messages: [...] service_tier: "priority"
set absent onlyappend unique betasetHeader no overwrite

using it

Turn it on.
Keep the same flow.

/fasttoggle
/fast onenable
/fast offdisable
/fast statusreport

Off by default. Your choice is saved in ~/.pi/agent/pi-faster.json.

pi
›
Fast mode: off
›
Fast mode is on. Requests will cost more.
›

benefit & limits

use the lane when it helps · fall back when it fails

Fast by opt-in. Boring by default.

PRICE

Priority costs more.

About 2× on OpenAI and Gemini. Premium rates on Anthropic.

Pi’s displayed cost may still show the standard rate.
CACHE

One warning for big contexts.

Above 10k tokens, toggling can miss the prompt cache once.

The next request may be slower and costlier once.
request402 / 403 / 429 / 529
extensionfast: paused
10 MINUTESretry at standard speed

verified install

Choose the priority lane
without learning every dialect.

$ pi install npm:pi-faster

github.com/championswimmer/pi-faster

AnthropicOpenAIGeminiVertex AI

Eligible models only · higher price · no speedup guarantee

ACT II / 02

Then, spend context with intent.

Keep useful history, measure what the cache remembers, and advertise only the skills this prompt needs.

context-prunecache-graphcontext-decisions

pi extension

pi-context-prune

Prune old tool output. Keep the summary.

future request contextraw -> compact
read
bash
grep
summary

What happened, why it matters, and refs to recover the originals.

the problem

Your next prompt still carries yesterday's logs.

Completed tool results remain part of future LLM context—even when the model already used them.

prompt N · assembled contextgrowing payload
current user askkeep this
read · source file
bash · test output
grep · match dump
bash · build log
next prompt
<

Repeated verbatim

Old output consumes space before the new prompt even begins.

+

Less useful signal

Resolved stack traces and match dumps compete with the task at hand.

the model still needs the lesson not every line

why this is safe

Two views. One session history.

future request contextcan be compacted
userlatest request
assistantsummary with refs
ToolResultverbose output omitted
LLM sees this

Raw results are filtered only while Pi assembles the next request.

session JSONLnever rewritten
toolResultoriginal output retained
context-prune-indexfull record + short refs
context-prune-summarycompact, recoverable view
session keeps this

The extension appends index and summary entries; it does not delete or rewrite originals.

how it works

Collapse. Keep. Recover.

captured batchcompleted calls
t1read
t2bash
t3grep
01captureturn_end
02summarizesmaller only
03filtercontext event
future promptcompact summary
What Pi should remember

Read the auth flow, test failure points to token expiry, and matching session IDs live in four files.

refs t1 t2 t3
exact detail neededcontext_tree_query({ toolCallIds: ["t2"] })
session index
originals intactt1 · t2 · t3

using it

The agent calls the tool. You keep the audit trail.

pi · agentic-autodefault trigger
tool context_prune()
Context prune running...
Summarized related tool calls.
Summarized tool refs: t1, t2, t3

Use context_tree_query with these refs to retrieve the original full outputs.

tool context_tree_query({ toolCallIds: ["t2"] })
original from session indexrecovered
## toolRef: t2
Tool: bash
Args: {"command":"npm test"}
Status: ERROR
Turn: 6

FAIL src/token.test.ts:42
  Expected 200, received 401
full outputtool argsstatusturn index
/pruner nowmanual flush/pruner treebrowse summaries + calls/pruner settingsmodel, trigger, display

choose the boundary

Compact when the work is actually done.

more automaticmore controlled
agent-messageBatch until a final text-only reply.cache-friendly
on-demandFlush only when you run /pruner now.manual
on-context-tagFlush at context_checkpoint.pi-context
every-turnFlush after each tool-using turn.debug
benefit

Lean future prompts

Keep useful conclusions and short recovery refs in model context.

trade-off

Summaries cost a call

Latency is paid at the trigger boundary. Pick a cheap, fast summarizer model if desired.

guardrail

Skip bad compression

If the summary is not smaller, originals remain and the prune frontier advances.

install

Let long sessions shed the payload.

Summarize completed tool work. Prune future context. Recover every original when the details matter.

$pi install npm:pi-context-prune
then/pruner onor try oncepi -e npm:pi-context-prune
Pi 1.5.0+npmauto-loaded after install
github.com/championswimmer/pi-context-prune
pi extension
pi-cache-graph icon
PROMPT CACHE OBSERVABILITY

pi-cache-graph

One cold turn tells you what happened.
The cumulative picture tells you what it means.

/cache graph · whole session timeline3 views
100%50%0%
hit% = cacheRead / full prompt
THE STORY IS NOT ONE TURN

A cold turn can be 0%.
The session can still be healthy.

Per-turn spikes expose events. Cumulative hit rate exposes the overall cost of the timeline.

turn #4 · cache resetper-turn
0.0%cacheRead
fresh input20cacheWrite900cacheRead0
+prior turns→
turns 1–4 · running aggregatecumulative
66.4%aggregate hit%
T1T2T3T4
ILLUSTRATIVE SESSION The event and the aggregate answer different questions — keep both visible.
WHY IT EXISTS

Cache breaks are quiet.

Pi can answer normally while an earlier context edit makes the provider re-write a long prompt prefix.

BEFOREstable prefix
system
tools
history 1…8
new
Tokens after the same prefix can arrive from cache.
EDIT
AFTERprefix no longer matches
system
changed
remaining prefix re-written
new
No chat error. A different token mix appears in the next assistant usage record.
Built to make pruning measurable.
Watch how pi-context-prune affects cache hits without guessing — then inspect the active branch separately from the whole tree.
HOW IT WORKS

Three usage fields. One honest denominator.

It reads assistant-message usage already reported by Pi — no prompt inference, no extra model call.

01

assistant usage

inputfreshcacheReadservedcacheWritewritten
→
02

canonical hit rate

cacheReadinput + cacheRead + cacheWrite
full prompt sent in this turn
→
03

inspect anywhere

/cache graph/cache stats/cache export
ANTHROPIC-STYLE cacheWrite stays separate from input and belongs in the denominator. // OPENAI-STYLE cacheWrite = 0; the same formula still applies.
THE GRAPH

One overlay. Three lenses.

Context Cache Graph — /root — Per-turn (%)←/→ agent · 1/2/3 view
ILLUSTRATIVE · SEE THE EVENT

Per-turn (%)

Find a cold start, reset, or suddenly weak hit rate in one turn.

0%the cold turn
ILLUSTRATIVE · SEE THE TREND

Cumulative %

Running cacheRead divided by the full prompt sent so far.

74.8%aggregate picture
0%100%
ILLUSTRATIVE · SEE THE VOLUME

Cumulative total

Stack input, cacheWrite, and cacheRead to see where tokens accumulated.

▇ input░ write▒ read
▇░░
▇░░▒
▇░░▒▒▒
▇░░▒▒▒▒▒
▇░░▒▒▒▒▒▒▒▒▒▒
GRAPH → STATS → EXPORT

From “looks warm” to inspectable evidence.

01
/cache graph

Compare active branch and whole tree. Switch registered subagents with ← →.

02
/cache stats

Open the scrollable per-message table with prompt, received, hit, write, and hit%.

03
/cache export

Write the stats model to <session-name>.csv at the project root.

pi · project sessioninteractive + export
› /cache stats
Token/cache stats by assistant message · illustrative rows
# Bmodelpromptrecvhitwritehit%
38 *claude-sonnet46,5201,20444,9001,60096.5%
39 *claude-sonnet47,31098645,7801,51096.8%
40 *claude-opus49,220842048,9000.0%
Active branch + whole tree + delta
› /cache export
✓
session-name.csv24 columns · summary + per-message rows
CSV
MAKE CACHE BEHAVIOR VISIBLE

Inspect the timeline.
Tune with evidence.

What it gives you

Per-turn events and cumulative impact
Active-branch vs whole-tree totals
Subagent graphs and refresh-on-demand
Portable CSV for your own charts

Keep in mind

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.

VERIFIED INSTALL COMMAND
$ pi install npm:pi-cache-graph
sourcegithub.com/championswimmer/pi-cache-graph
/cache graph/cache stats/cache exportMIT

pi extension

pi-context-decisions pixel icon

pi-context-decisions

Give Pi the right context for this task.

task → relevance route → contextadditive
nowReview validation
changes
decision
model
score metadata
code-review
test-edge-cases
release-notes

the pain

Your skill shelf grows.
Every prompt sees it all.

Pi system skills sectionunfiltered
release-notescode-reviewdatabaseemail-copyui-polishedge-casesterraformslideson-callchangeloga11yk8s-debugmigrationsci-repairseo-auditdocs-style
→relevant signal
gets buried
current prompt

“Review these validation changes for missing edge cases.”

code-review
test-edge-cases
Two clear candidates among a lot of unrelated guidance.

Useful skills should be advertised when they fit—not merely because they are installed.

why it exists

Tasks shift. Context can grow with them.

TURN 01
Review this diff.
+code-review
+test-edge-cases
TURN 08
Prepare v6.0 release notes.
stayscode-review
staystest-edge-cases
+release-notes
+changelog
⌁

Additive on this branch. New relevant skills join the native Pi skills section. Earlier choices are never retracted.

how it works

Score metadata. Route what fits.

before_agent_start · skill pickerscanning
01 · task
> Review these validation changes.
candidate metadata
code-review
release-notes
ui-polish
test-edge-cases
02 · decision model
score0–2 relevance rubric
code-review1.88
test-edge-cases1.64
threshold · 0.75 raw
03 · advertised to Pi
native skills section
code-review
test-edge-cases
name + description + location
not the skill body
50 candidates / shard max12 new skills / round max8s whole-round timeoutfail closed by default

separate, opt-in route

Skills are advertised.
Tools can be made available.

SKILLScontext

The picker selects skill metadata for Pi’s native skills section.

code-review→ advertised
It does not hide installed skills from explicit use or file reads.
independent
switches
TOOLS / MCPavailability

Opt-in filtering withholds direct declarations and checks calls through Pi’s tool pipeline.

mcp__github→ available
Unavailable calls return an error. Discovery and server connections are unchanged.
!

Relevance routing, not a permissions sandbox. It does not govern OS access, process isolation, credentials, discovery, or MCP connections.

use it in Pi

One dialog. Then work normally.

pi sessionfresh session
❯ /decisions
Decision · Decision model · select provider
❯ /decisions status
Decision model configured · skill routing on
❯ Prepare the release notes.
Working Deciding Context
01

Choose a model

Pi classifiers, TypeSafe, OpenAI, Gemini, or OpenRouter. No model is selected by default.

02

Keep essentials pinned

Global and project always-allowed lists bypass scoring; tool filtering remains independent.

03

Know the trade-offs

Metadata leaves Pi. Decisions add latency and may incur provider charges. Failed rounds add nothing.

Tab tabs Enter select Space toggle Ctrl+S save allowlists Esc close

route less noise into the next prompt

Install once. Let task relevance steer.

$pi install npm:pi-context-decisions
1/decisionsopen settings
→
2Decision modelchoose one
→
3Fresh sessionroute your first task
Node 22.18+Pi 1.1.0+MIT

ACT III / 03

Finally, coordinate the work.

Turn an agent session into a visible system: plan it, fan it out, watch it run, and bring the result back.

checklistsubagent-managerbackground-monitorgh-footer

pi extension

pi-checklist pixel icon

pi-checklist

A visible plan for long-running agent work.

/checklist1/4
k7qDesign schemaDONE
m2xWire up storePROG
p9zAdd testsBLCK
r4dUpdate docsREDY

the problem

A plan in context
does not stay in view.

Tool calls, test output and edits keep moving it upward.

you what is actually left?
agent session

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

Put the plan in the session,
not just in the conversation.

agent

create

update

read

session.jsonldurable snapshot
you

☑ 2/4

The agent and the TUI read the same session-scoped checklist.

what it gives the agent

Three tools. One honest list.

checklist_create

Create, replace or append tasks.

checklist_read

Read status, readiness and blockers.

checklist_update

Advance state or revise open tasks.

task p9z
idp9z3 a–z / 0–9
titleAdd tests
dependsOnm2xmust be done
planned→ongoing→donedone is terminal

A task may also be cancelled; cancelled → planned is allowed.

the dependency gate

Finish the prerequisite.
The next task unlocks.

/checklistblocked
k7qDesign schemaDONE
m2xWire up storePROG
depends on m2x
p9zAdd testsBLCK
agent tools

› 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

status changeonly after every dependency isdone

using it

Ask for a plan. Watch it tick off.

pi

› 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

/checklist

open every task

/checklist add

add one by hand

/checklist settings

tune display + guidance

/checklist hide

clear the persistent view

practical value

Visible progress,
with useful guardrails.

↻

Session-durable

Survives /resume, /branch, /undo and compaction.

10

Tasks, bounded

The live widget prioritizes and shows the top five; the dialog shows all.

3

Subtasks per task

Optional preview. Sibling-only dependencies keep the graph local.

display statusbarwidget-onlystatus-minimalend-of-turnhidden

Limits: a maximum of 10 tasks per session list; completed tasks are frozen. Create a new task to revise finished work.

install

Give long-running work
a visible checklist

$pi install npm:pi-checklist

or pi install git:github.com/championswimmer/pi-checklist

Requires Pi 1.5.0+ and Node.js 22.19.0+

visible plan dependency-aware session-durable
pi-checklist pixel icon
pi extension · parallel delegation
pi-subagent-manager icon

pi-subagent-manager

Parallel subagents you can watch and steer.

/agents tree3 active branches
mainkeep working
coderrunningsteer → add tests
researcherrunning
reviewerdone
the bottleneck

Independent work. One waiting line.

When every helper is foreground work, research blocks coding, coding blocks review — and your main thread waits too.

serialone turn at a time
mainwaiting
research
implement
review
next prompt is behind the active job
→fan out
asyncmain stays interactive
mainkeep typing
researcherworking
coderworking
reviewerworking
results return to the main agent
the async lifecycle

Spawn. Continue. Rejoin the branch.

01

Launch detached

Spawn independent siblings with wait: false.

agent_spawn(..., wait: false)
02

Keep your turn

The main conversation stays available while helpers work.

input remains open
03

Inspect or steer

Watch live, queue direction, wait for a result, or stop a subtree.

agent_steer · agent_wait
lifecycle Completed, paused, failed, and stopped sessions remain readable — and can be resumed.
watch the mechanism

Three branches. One live tree.

/agents tree · /rootrefreshes live
/rootmain agent
coder/root/fix-auth
running
researcher/root/retry-audit
running
reviewer/root/review-change
running
steeradd tests→
watch · coderEnter
readsrc/auth/session.ts
editfix token expiry guard
steerqueued: add tests
stateresumed with direction
Steeradd testsEnter
i actionsEsc treeCtrl+Q main
Nested descendants stay in the same retained tree. Select a path, watch it, steer it, then return to main.
choose what the child knows

Fork the conversation. Or start fresh.

fork:

Lexical snapshot

messagesshell outputcustom messages
frozen at spawn
/root/fix-authhas the handoff

Use it when the task depends on what you have already discussed.

/agents fork:coder fix the failing auth test
VS
fresh:

Independent root

/root historynot inheritedno parent turns
clean start
/investigatetask-only context

Use it for a task that needs no conversation history.

/agents fresh:researcher audit retry handling
Frozen, not synced. Later parent turns do not change the forked child’s snapshot.
practical use

Ask in plain language. Or pick the branch yourself.

main sessiondetached helpers
plain language
›
direct command
$ /agents fork:coder fix the failing auth test
✓ Agents widget appears above the input
/agents tree watchEnter steeri actionsCtrl+Q main
practical Agents share your working directory and OS permissions. Tool policies are not a sandbox.
six bundled rolesmodel, tools and instructions can change
architectplans & coordination
coderimplementation & debugging
researchercodebase & web research
reviewercorrectness & security
taskersmall jobs & quick lookups
writerdrafting & editing prose
install

Keep the main thread moving.

Fan out independent work, see every branch, and steer before a wrong turn becomes a finished answer.

$pi install npm:pi-subagent-manager
Pi 0.99.2+github.com/championswimmer/pi-subagent-manager
before you fan out

Don’t run multiple subagent extensions together — they clash on /agents.

pi extension · keep Pi moving
pi-background-monitor icon

pi-background-monitor

Long jobs keep running. Pi only comes back for a matching line.

private tmux · build live journal
02:41:03compiling src/broker.tsquiet
02:41:04emitting dist/index.jsquiet
02:41:08error: database connection failedMATCH
wake
One matching alert deliveredmetadata only · inspect the retained log next
the cost of long-running work

Foreground waits block. Polling turns noise into turns.

The command is simple. The attention model around it is not.

BLOCKING

Wait in the foreground

$ npm run build && npm test
command still owns the turn
⌁

Other prompts and parallel edits sit behind the slow job.

POLLING

Check the tail again

sleep 10; tailcompiling…routine
sleep 10; tailheartbeat okroutine
sleep 10; tailwatching filesroutine
↻

Repeated inspection spends model attention on unchanged state.

instead Run detached. Retain bounded logs. Match completed lines or an exit event. →
how it works

A bounded pipeline from command to signal.

bgmon separates process ownership, retained output, and notification delivery.

01›_

Start

bgmon_start launches Bash in an owned private tmux server.

returns monitorId · logRef · attach
02▥

Capture

Output lands in a bounded, rotating journal with visible gaps.

8 × 1 MiB per source
03⌕

Watch

contains, regex, any, or exit filters completed lines and states.

from: now · retained
04!

Deliver

ui, nextTurn, or wake emits a bounded notification.

metadata, not matching output
After an alert bgmon_inspect(id, after) page the retained log; there is no server-side grep.
concrete usage · build watch

Routine lines stay quiet. One line creates one alert.

tool callbuild
1
bgmon_start

command: “npm run build”

running
watchkind: regexpattern: error|failedflags: ifrom: retaineddelivery: wake
2
bgmon_watch

match a line, emit metadata

armed
deliverywake
oncetrue
alerts0
journal · regex /error|failed/iseq #104
COMPLETED LINES0 scanned
WAITINGunmatched lines remain silent
{"delivery":"wake","status":"listening"}
routine output → no delivery
the important boundary

The job can survive Pi. The live watch cannot.

Shutdown detaches the controller; it does not mean automatic recovery on the next launch.

NORMALLY SURVIVES

Private tmux process

Pishutdowntmux job continues
  • The owned job keeps running in its private server.
  • Journal pages and a saved logRef can still be read later.
SESSION-ONLY

Controller, watches & wake-ups

Pishutdownnot resumed
  • Reopening Pi does not reconnect controllers or resume watches.
  • Offline output is not matched and no automatic orphan adoption occurs.
↓
Save the start result if recovery may matter.

attach is for manual tmux access. logRef is for session-owned historical inspection—not controller recovery.

practical benefit · explicit limits

Built for useful handoff, not an exactly-once promise.

01

Keep the session useful

Builds, test suites, servers and tail -f run away from the foreground turn.

02

Interrupt on a condition

Line and terminal-state watches replace repeated “is it done yet?” inspection.

03

Inspect later

Page retained output, or open the read-only /bgmon viewer.

KNOW THE EDGESBounded and best effort
!Rotation, capture failure, slow readers and long lines can create gaps.
!wake can start a turn when idle; delivery is best effort and observation is not guaranteed.
!Commands run with your privileges and may contain secrets or prompt injection in output.
!Stopping can leave detached descendants; inspect with care and clean up explicitly.
8 running16 retained1–64 configurable16 KiB / 200 lines per inspect page
install · verified package path

Start the build.
Keep the conversation moving.

Install the shipped extension, reload Pi, and ask for the behavior you want.

$pi install npm:pi-background-monitor
Pi 1.5.0+Node.js 22+Bash + tmux 3.2+Linux / macOS
one useful promptcopy → ask

“Run npm run build in the background. Wake me if output matches error|failed, and keep the log for me to inspect.”

Pi translates
bgmon_start+bgmon_watch+bgmon_inspect
after installReload PiA full restart is recommended when upgrading an older loaded extension.
github.com/championswimmer/pi-background-monitor

Your next move

Start with one lever.

Pick the extension that removes the most friction from your current session. You can always come back for the rest.

pi install npm:pi-context-usage Replay chapter

Ten small tools. One more deliberate coding loop. · Press M for the map.