SLOPSHOPPER

peek

Typing "status" while background shells or subagents run opens a pane with each task's exact elapsed time, the tail of its output and any percent it printed…

newpaneguardcommandprompttimer
★ 4v0.1.0MITupdated 2026-10-08VedantAndhale/claude-pro-kit/plugins/peek
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · peek
│ ┃ peek ✕ › fix the failing auth test and add an audit log call │ ┃ Nothing running in the background. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /peek │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · peek
Nothing running in the background.
README

claude-pro-kit

test

Make the $20 Claude Pro plan last longer in Claude Code.

Twenty-two small mods that show you exactly where your usage goes and cut the waste. One mod makes a model call: prompt-polish, once each time you press Improve, and never on its own. The others make none. None adds anything to the system prompt (read-cap adds one tool, which Claude Code lists by name only until Claude first uses it; write-guard adds one line to a tool result at most once per conversation; compact-keeper adds a note of at most 4,000 characters after a compaction): every figure on screen is one Claude Code already reports, or a time the mod measured.

ModWhat it doesWhere
tool-dietLoads tools you have not used lately on demand instead of with every requestEverywhere
skill-dietLists skills you have not used lately in this project by name only, without their descriptionsEverywhere
agent-dietRuns Explore subagents on Haiku instead of your main modelEverywhere
context-xray/xray opens the exact breakdown of what fills your context windowEverywhere
pro-hudLive meters above the prompt for your 5-hour session, your week and the context window, plus a per-turn receipt of tokens in, cached and outClaude desktop app
output-dietTrims long shell output, search results and subagent reports before Claude reads them, keeping the head, the tail and the error lines; the untrimmed text is saved to a file Claude can open without a permission promptEverywhere
reread-guardSkips Claude re-reading a file it already read when the file has not changed, with Read or a plain cat, sed -n, head, tail or Get-Content; a deliberate retry still goes throughEverywhere
write-guardSteers Claude to Edit instead of rewriting an existing file in full with Write; a deliberate rewrite still goes throughEverywhere
loop-guardHolds back a shell command that already failed twice in a row, so Claude changes approachEverywhere
cmd-dietAdds quiet flags to noisy shell commands before they run, so Claude reads short output from the start; errors, failures and warnings stay in fullEverywhere
gh-accountRuns each git push, pull, fetch, clone and gh command as the logged-in GitHub account that can see the repository, without switching the active accountEverywhere
cache-clockCounts down until the prompt cache expires; once it has, shows exactly how many tokens your next message will re-send uncachedEverywhere
read-capStops Claude reading a file over 1,000 lines whole (with Read, cat or Get-Content) and gives it an outline tool, so it reads only the lines it needs; a retry still reads the whole fileEverywhere
session-receipt/receipt opens a pane with the exact tokens every turn of the session spent, and the costliest turnsEverywhere
peekTyping status while background tasks run opens a pane with each one's exact elapsed time and last output lines, instead of sending the prompt to ClaudeEverywhere
budget-guardHolds a prompt back once your 5-hour or weekly usage reaches your limit (90% by default); sending it again goes throughEverywhere
turn-budgetWhen one turn uses more than +5 session points, writes a handoff and continues in a fresh session by itself; /handoff any timeEverywhere
compact-keeperAfter a compaction, adds a note of exact facts from before it: your latest prompt in full, the todo list, the last failed command, files editedEverywhere
collision-guardAsks before Claude edits a file another chat on this machine changed in the last 30 minutesEverywhere
answer-paneExplain, plan and ELI5 pages drawn natively in a side pane; plans have decision buttons and Respond fills the prompt boxDesktop app (no diagrams in the terminal)
prompt-polishAn Improve button beside Send (above the prompt in the terminal) rewrites your draft with Opus at low effort and puts it back in the box; Undo restores it. One model call per pressEverywhere
kit-updatesTells you when an installed mod from this kit has a newer version or a new mod joins the kit; /kit-update installs updates and new modsEverywhere

pro-hud's band updating live while Claude works

  • With tool-diet, every request in a fresh session was 15,954 tokens smaller (−36%): 43,859 → 27,905, as the API reported. Details.
  • With skill-diet on top of the other mods, every request in a fresh session was 8,226 tokens smaller (−30%): 27,423 → 19,197, as the API reported. Details.
  • With agent-diet, a task that sends one Explore subagent cost 33% less on a Sonnet session: $0.05570 → $0.03741, averaged over three runs each. Details.
  • In the benchmark, a debugging task cost 33% less with output-diet and reread-guard on, averaged over three runs each.

Install

In Claude Code:

/plugin marketplace add VedantAndhale/claude-pro-kit
/plugin install tool-diet@claude-pro-kit
/plugin install skill-diet@claude-pro-kit
/plugin install agent-diet@claude-pro-kit
/plugin install context-xray@claude-pro-kit
/plugin install pro-hud@claude-pro-kit
/plugin install output-diet@claude-pro-kit
/plugin install reread-guard@claude-pro-kit
/plugin install write-guard@claude-pro-kit
/plugin install loop-guard@claude-pro-kit
/plugin install cmd-diet@claude-pro-kit
/plugin install gh-account@claude-pro-kit
/plugin install cache-clock@claude-pro-kit
/plugin install read-cap@claude-pro-kit
/plugin install session-receipt@claude-pro-kit
/plugin install peek@claude-pro-kit
/plugin install budget-guard@claude-pro-kit
/plugin install turn-budget@claude-pro-kit
/plugin install compact-keeper@claude-pro-kit
/plugin install collision-guard@claude-pro-kit
/plugin install answer-pane@claude-pro-kit
/plugin install prompt-polish@claude-pro-kit
/plugin install kit-updates@claude-pro-kit

Updates are off by default for marketplaces you add yourself. With kit-updates installed you are told when a fix ships and /kit-update installs it, from the desktop app or the terminal. Without it, turn on auto-update once: in a terminal, run claude, then /plugin → Marketplaces → claude-pro-kit → Enable auto-update; the desktop app has no toggle for it.

Install any one on its own; they do not depend on each other. Mods are not sandboxed, so read the code before installing: each mod is a single file under plugins/<name>/hooks/.

tool-diet

Every tool listed in front sends its whole description and schema with every request. A deferred tool is listed by name only, and Claude loads it through ToolSearch when it needs it; Claude Code already does this for most MCP tools. tool-diet does it for the rest of the tools you are not using: anything outside the core set (Bash, PowerShell, Read, Edit, Write, Glob, Grep, Agent, Skill, ToolSearch, TodoWrite, AskUserQuestion) that you have not used in your last five sessions.

Measured with one prompt, "Reply with just OK.", in a fresh session, as the API reported each request:

Prompt tokens per request
Without tool-diet43,859
With tool-diet27,905
Change−15,954 (−36%)

On that setup, the largest tool moved was Artifact, whose description alone is 19,870 characters. What moves depends on your tools and your habits; /xray shows yours.

  • The first time a deferred tool is used in a session costs one extra step, a ToolSearch call. After that it stays loaded for the session.
  • Using a tool keeps it loaded for your next five sessions, so the set follows what you actually use.
  • The choice is made once per tool per session, so the prompt cache is never disturbed mid-session. Changes apply from the next session.
  • /tool-diet lists what is on demand this session, grouped by where each tool comes from; /tool-diet keep <tool> always loads one, unkeep undoes it, and /tool-diet off|on switches it. Answers are toasts, so they add nothing to the conversation. The status line keeps the count: 38 tools on demand.

The /tool-diet toast: 38 tools on demand, grouped by source

skill-diet

Every request carries the skill listing: each installed skill's name and its whole description. With a few plugins installed that is dozens of skills, most of which a given project never uses (video skills in a backend repo, document skills in a game). skill-diet keeps the skills you used lately in this project listed in full and lists the rest on one line by name only. The Skill tool still loads any of them, and typing /name still works.

Measured with one prompt, "Reply with just OK.", in a fresh session with 45 skills installed and the other mods on, as the API reported the request:

Prompt tokens per request
Without skill-diet27,423
With skill-diet19,197
Change−8,226 (−30%)

In the same setup, asked to fill in a PDF form, Claude found anthropic-skills:pdf from its name alone and loaded it with the Skill tool. What moves depends on your skills; /xray shows yours.

  • A skill used in this project in one of your last five sessions stays listed in full. Every use counts: typed as /name or called by Claude through the Skill tool.
  • Usage is kept per project folder, so a skill you use in one repo does not crowd the listing in another.
  • A skill installed after skill-diet stays listed in full for five sessions, so Claude can find it before you have used it.
  • The listing is decided once per session, so the prompt cache is never disturbed mid-session. Changes apply from the next session.
  • /skill-diet shows what is listed by name only this session and how many characters left the listing; /skill-diet keep <skill> always lists one in full, unkeep undoes it, and /skill-diet off|on switches it. Answers are toasts, so they add nothing to the conversation. The status line keeps the count, in the form <n> skills by name only, <n> characters off.
  • /xray shows the skills line before and after, in tokens.

agent-diet

A subagent runs on your main model unless its definition or Claude's Agent call names another. Explore only searches and reads, yet in the author's own 85 subagent transcripts, every one of the 2,043 Explore requests ran on Opus or Sonnet, reading 147,298,992 input tokens. agent-diet starts the agent types you list (Explore by default) on Haiku.

  • A model Claude names in the Agent call is kept, and a fork always runs on its parent's model.
  • Other agent types (general-purpose, Plan, your own) keep their usual model.
  • /agent-diet shows the setting and how many subagents it moved this session; /agent-diet model haiku|sonnet|opus picks the model, /agent-diet add|remove <agent type> changes the list, and /agent-diet off|on switches it. Answers are toasts, so they add nothing to the conversation. The status line keeps the count, in the form 2 subagents on haiku.

Measured with claude -p --model sonnet --output-format json on a task that sends one Explore subagent to find a file, three runs each in alternating order. Every run found the file. Figures are the cost and tokens Claude Code reported per model:

RunWithout: costWithout: Sonnet tokens inWith: costWith: Sonnet tokens inWith: Haiku tokens in
1$0.0569268,395$0.0372440,21327,848
2$0.0557768,111$0.0376439,59327,872
3$0.0544168,123$0.0373640,18442,770
Average$0.05570$0.03741

context-xray

The /xray pane: what is sent with every request, what loads on demand, memory files and listings

/xray opens a pane with the exact breakdown /context computes: what is sent with every request (system prompt, tools, MCP tools, memory files, skills, messages), what is loaded on demand, which MCP tools load every time, and each memory file's size. It measures when the pane opens and when you press Refresh (or r), never in the background, because the exact count sends one token-count request per tool and memory file.

Opens by itself when the context crosses 60% and again at 80%, with a toast pointing at /compact and /handoff. /xray auto off keeps it to /xray only.

pro-hud

The recording at the top of this page is the band. In text:

Session    ━━━━━━━━━━━━━━──────   69%  resets in 32m
Week       ━━━━━━━━━━━━━━━─────   74%  resets in 4d 17h
Context    ━━━━━━━━────────────   44%  436,034 tokens
This turn  1m 35s · 1 tool · 0 files edited · 436,034 in · 431,260 cached · 580 out

On a wide window the three meters sit side by side on one row; on a narrow one each figure on the turn line wraps whole rather than being cut off.

  • Session / Week: the share of your plan's 5-hour and 7-day allowance used, and when each resets. Account-wide: every chat and device counts.
  • Context: how full this conversation is. Every request resends it, so a fuller context spends your session faster; /compact when it climbs.
  • This turn / Last turn: updates live while Claude works (per tool call and per model request), then shows the turn's final figures and how many points of your session it used.
  • The spinner gains · session 20%, and finished tool calls draw as one line: status dot, tool, target, time.
  • A toast when the session crosses 80% and 90%.

/hud shows what is on; /hud all on|off, or /hud band|spinner|cards on|off. The answer is a toast, so toggling adds nothing to the conversation. It draws in the desktop app only and leaves the terminal as it is. Rows other mods put above the prompt still draw beneath the band.

Weekly toasts at 50%, 75% and 90% of the week, once each, because the weekly limit drains quietly across many sessions.

output-diet

When a Bash or PowerShell result runs past 120 lines or 8,000 characters, Claude reads:

[output-diet: 82/500 lines shown; all 500 in ~/.claude/projects/<project>/<session>/tool-results/output-diet-<call>.txt]

<first 30 lines>
… [lines 31–450 omitted; error/warning lines from them:]
   250│ ERROR: build failed in src/app.ts
   300│ Warning: deprecated API
…
<last 50 lines>
  • You still see the output in the transcript as before; only Claude's copy is trimmed.
  • The status line keeps a running count: 3 trimmed · 41,200 chars saved.
  • The untrimmed text is written to disk first; if the write fails, nothing is trimmed.
  • It goes in the session's own tool-results folder, beside the transcript, where Claude Code keeps the outputs it saves itself, so Claude can open it without a permission prompt. When that folder cannot be found, it goes under ~/.claude/output-diet/ (or CLAUDE_CONFIG_DIR).
  • A Grep result past the same limits keeps its first 100 lines, with a note to narrow the search: [output-diet: first 100/252 lines shown; narrow the search, or read all in …]. In the author's 1,048 past Grep results, 26 went past the limits, and keeping the first 100 lines would have cut 104,052 characters. Glob is left alone: none of 128 went past.
  • A subagent's report past 8,000 characters keeps its first 6,000 and last 2,000 characters, so the opening and the conclusion stay. In the author's 123 past reports, 17 went past it, 313,365 characters between them.
  • Claude Code itself already cuts the middle out of very long shell output (past roughly 10,000 characters) before any mod sees it, and for a failing command no uncut copy is kept. output-diet works on what is left: the saved file holds everything Claude would have read, and an error line Claude Code cut is not in it.

reread-guard

When Claude asks to Read the same range of the same file again in the same conversation, and the file's size and modification time have not changed, the read is skipped and Claude is told to use the copy it has. Any edit, a different range, or a subagent (which has its own context) reads freely. Claude Code can clear old tool results from context, so retrying the identical read straight after a skip always goes through. The record resets on /compact and /clear.

What Claude is told in place of the repeat read, kept to one line because the model reads it:

api.ts unchanged since you read it; use that copy. If it's gone from context, retry the same Read.

Shell reads too. Claude often reads a file with the shell instead of Read: in the author's transcripts, 318 sed -n runs went past the guard. A shell command that only prints one file is now treated the same way: cat FILE, sed -n 'A,Bp' FILE, head -n N / tail -n N, and in PowerShell Get-Content, gc, cat or type (with -TotalCount, -Head, -First, -Tail, -Last or -Raw). The same range of the same unchanged file is skipped once, and retrying the same command goes through. A whole cat after a whole Read that showed every line counts as a repeat. A pipe, a chain, a variable, a glob or any other flag runs untouched. A shell read never counts as a Read, since Edit needs a real one first.

The status line counts them: 2 re-reads skipped.

write-guard

Write sends the whole file as Claude's output, the most expensive kind of token; Edit sends only the lines that change. Claude sometimes rewrites a file it has already read in full to change a few lines. In the author's own 272 session transcripts, 141 writes rewrote a file Claude had already read or written (999,273 characters), and 112 of them followed an earlier rewrite in the same session. Of the 512,847 characters in the rewrites whose previous version was in the transcript, 171,325 had changed.

A hook runs after Claude has written the content, so write-guard cannot save the rewrite it sees; it stops the ones after it:

  • The first rewrite of an existing file in a conversation goes through, with one line for Claude after the result: You rewrote all of api.ts. For changes to an existing file use Edit: it sends only the changed lines.
  • A later rewrite is held back once, and Claude is told: api.ts exists; change it with Edit, not a full Write. If a full rewrite is intended, retry the same Write. Retrying the same Write goes through.
  • New files, and files under 2,048 bytes, are never touched. A subagent has its own conversation and its own first rewrite; a compaction or /clear starts over.
  • The status line counts them: 1 full rewrite held back.

loop-guard

Each retry of a failing command re-sends the whole conversation, and the same command usually fails the same way. In the author's 272 session transcripts, 10 commands failed 3 or more times, 38 runs between them.

Once the exact same Bash or PowerShell command has failed twice in a row, the next try is held back once, and Claude is told:

This exact command failed 2 times in a row. Change the approach instead of rerunning it. If a rerun is intended, retry the same command.
  • Retrying the same command straight after the hold goes through, for a command that is meant to be rerun.
  • A success clears the count, and each command is counted on its own. A subagent counts its own commands; a compaction or /clear starts over.
  • The status line counts them: 1 failing retry held back.

cmd-diet

output-diet trims long output after a command has run; cmd-diet keeps the noise from being printed at all. Before a Bash or PowerShell command runs, a known noisy command gets its own quiet flags, which drop progress lines and keep errors, test failures and warnings:

CommandRuns asOutput, measured
git statusgit status --short --branch415 to 58 characters
pytestpytest -q1,063 to 495 characters, failure details unchanged
cargo build / test / check / clippy / runcargo build -q197 to 0 characters on success, warnings unchanged
npm install / cinpm install --no-audit --no-fund62 to 18 characters
curl (Bash only)curl -sS1,049 to 577 characters, the progress meter removed
mvnmvn -B -ntpnot measured: drops download progress
wget (Bash only)wget -nvnot measured: one line per file
docker pulldocker pull -qnot measured: drops layer progress

In a live headless run (git status && python -m pytest on 41 test files, one failing), the request cost 41,535 tokens without cmd-diet and 40,571 with it, by the API's usage, and both runs named the failing test and its reason correctly. The shorter output stays in context, so every later request in the session sends less too.

  • Each step of a &&, || or ; chain is handled on its own. A step that pipes, redirects or substitutes (| grep, > file, $(...)) is left alone, since something else reads its output; 2>&1 is fine.
  • A command that already sets its output level (git status --porcelain, pytest -v, curl -fsSL, npm install --silent) is left alone, and a flag already present is not added twice.
  • If a tool rejects a flag (an old version), that rule stops for the session and Claude's retry runs the command as typed.
  • The status line counts them: 3 commands quieted.

gh-account

With two GitHub accounts logged in to gh, a push to a repository the other account owns fails, and Claude spends turns on gh auth status and gh auth switch. Before a Bash or PowerShell command runs, gh-account matches each git push, pull, fetch, clone, ls-remote and gh step to the repository's owner, and the owner to a logged-in account. When that account is not gh's active one, that step alone runs with its token:

GH_TOKEN="$(gh auth token --user ACCOUNT)" git push

The token itself never appears in the command or its output, and the active account is not switched. For git it also asks gh for the credential.

  • The owner comes from a URL in the command, -R owner/repo, a gh api repos/<owner>/... path, or the folder's remotes. With no remote named, every remote must point at the same owner.
  • The account is the one whose login is the owner, else the one account that is a member of that organization. The accounts come from gh auth status, and organizations from gh api user/orgs. What it learns is kept across sessions.
  • Nothing is guessed: no owner, more than one matching account, or anything unclear leaves the command as typed. It also leaves alone gh auth and other gh commands that reach no repository, a command that already sets GH_TOKEN, a token from the environment, git over ssh, hosts other than github.com, and subshells or substitutions.
  • /gh-account shows which account each owner uses, and /gh-account forget clears it. Answers are toasts. The status line counts them: 2 commands sent as <account>.

cache-clock

Claude's prompt cache keeps your conversation for a fixed time after each request. Reply within it and the context is read from cache; reply after it and the whole context is sent again at full price. That message pays the cache-write price (1.25 times the input price for a 5-minute cache, 2 times for a 1-hour one) on every token instead of the cache-read price (0.1 times): 12.5 to 20 times more for the same context, and nothing on screen says so.

cache-clock puts the countdown in the status line, restarted by every response from the main conversation:

cache warm · 3m left
cache cold · next message re-sends 61,204 tokens

When the cache runs out, a toast says so once (after the lifetime is known, see below). The token figure is the previous response

Source 2 files
hooks/register.tsx 386 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register } from 'claude-code'
3
4// Typing "status" while Claude waits on background work re-sends the whole
5// conversation just to ask how it is going. peek answers it locally: the
6// prompt is dropped and a pane lists each background shell and subagent with
7// its exact elapsed time and the last lines of its output. A percent bar is
8// drawn only from a percent the task printed itself; nothing is estimated and
9// nothing is sent to the model.
10
11const PANE = 'peek'
12const TAIL_LINES = 3
13const CLIP = 70
14const RECENT_MS = 10 * 60_000
15const TICK_MS = 1_000
16const MAX_READ = 4 * 1024 * 1024
17const MAX_TRACKED = 100
18const BAR_CELLS = 20
19
20const SHELLS = new Set(['Bash', 'PowerShell'])
21const LIVE_AGENT = new Set(['pending', 'running', 'waiting'])
22
23const tick = atom({ plugin: 'peek', key: 'tick' } as const, 0)
24
25export type Shell = {
26  id: string
27  command: string
28  startedAt: number
29  path?: string
30  /** The loop that started it: a subagent's id, absent on the main loop. */
31  loop?: string
32  /** Claude Code ends it with its caller's final answer: no notification follows. */
33  endsWithCaller?: boolean
34  endedAt?: number
35  status?: string
36}
37
38export type Agent = { id: string; description: string; startedAt?: number; endedAt?: number; ms?: number; status?: string }
39
40// ---- Pure helpers (exported for the tests) ----
41
42export const isStatus = (text: string) => text.trim().toLowerCase() === 'status'
43
44/** `4m 12s`, `1h 3m 7s`, `9s`: exact to the second. */
45export const elapsed = (ms: number) => {
46  const s = Math.floor(Math.max(0, ms) / 1000)
47  const h = Math.floor(s / 3600)
48  const m = Math.floor((s % 3600) / 60)
49  if (h > 0) return `${h}h ${m}m ${s % 60}s`
50  return m > 0 ? `${m}m ${s % 60}s` : `${s}s`
51}
52
53export const clip = (text: string, max = CLIP) => {
54  const line = text.trim().split(/\r?\n/)[0] ?? ''
55  return line.length > max ? `${line.slice(0, max - 3)}...` : line
56}
57
58/**
59 * The id and output file Claude Code names when a shell goes to the
60 * background: "Command running in background with ID: b1x2. Output is being
61 * written to: C:\...\tasks\b1x2.output. You will be notified when it completes."
62 */
63export const parseBackground = (text: string) => {
64  const id = /in background with ID:\s*([A-Za-z0-9_-]+)/.exec(text)?.[1]
65  const path = /Output is being written to:\s*(.+?)(?=\.\s|\.?\s*$)/m.exec(text)?.[1]?.trim()
66  return { id, path }
67}
68
69/** Each `<task-notification>` in a text: the task's id and how it ended. */
70export const parseNotifications = (text: string) => {
71  const found: { id: string; status: string }[] = []
72  for (const block of text.split('<task-notification>').slice(1)) {
73    const id = /<task-id>\s*([^<\s]+)\s*<\/task-id>/.exec(block)?.[1]
74    const status = /<status>\s*([^<]+?)\s*<\/status>/.exec(block)?.[1]
75    if (id) found.push({ id, status: status ?? 'ended' })
76  }
77  return found
78}
79
80const ANSI = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07/g
81
82/** The last non-empty lines; a carriage return (a progress redraw) starts a line. */
83export const tail = (text: string, n = TAIL_LINES) =>
84  text
85    .replace(ANSI, '')
86    .split(/\r\n|\n|\r/)
87    .map(l => l.trimEnd())
88    .filter(l => l.trim() !== '')
89    .slice(-n)
90
91/** The latest percent figure in the lines, as printed; undefined when none. */
92export const lastPercent = (lines: readonly string[]) => {
93  let pct: number | undefined
94  for (const m of lines.join('\n').matchAll(/(\d{1,3}(?:\.\d+)?)\s?%/g)) {
95    const n = Number(m[1])
96    if (n >= 0 && n <= 100) pct = n
97  }
98  return pct
99}
100
101export const bar = (pct: number, cells = BAR_CELLS) => {
102  const full = Math.floor((pct / 100) * cells)
103  return `[${'#'.repeat(full)}${'-'.repeat(cells - full)}] ${pct}%`
104}
105
106// ---- The mod ----
107
108// Kept in the module, reset at each load and at /clear: a reload forgets the
109// tasks it saw, and the pane says so for a subagent it never saw start.
110let shells = new Map<string, Shell>()
111let agents = new Map<string, Agent>()
112let isOpen = false
113let ticker: { cancel: () => void } | undefined
114
115const trim = <T,>(map: Map<string, T>) => {
116  while (map.size > MAX_TRACKED) map.delete(map.keys().next().value as string)
117}
118
119const runningShells = () => [...shells.values()].filter(s => s.endedAt === undefined)
120
121function stopTicker() {
122  ticker?.cancel()
123  ticker = undefined
124}
125
126function forget() {
127  shells = new Map()
128  agents = new Map()
129  isOpen = false
130  stopTicker()
131}
132
133async function bump($: EngineInterface) {
134  const t = await $.clock.now()
135  await update($, tick, () => t)
136}
137
138async function liveAgents($: EngineInterface): Promise<AgentInfo[]> {
139  const list = await $.agent.list().catch(() => [] as AgentInfo[])
140  return list.filter(a => LIVE_AGENT.has(a.status))
141}
142
143// One clock, only while the pane is open and something runs: the timers
144// count up live, and nothing ticks otherwise.
145function startTicker($: EngineInterface) {
146  if (!isOpen || ticker) return
147  // A tick that fails (the session or the plugin went away) stops the clock.
148  ticker = $.clock.every(TICK_MS, () => void onTick($).catch(stopTicker))
149}
150
151async function onTick($: EngineInterface) {
152  if (runningShells().length === 0 && (await liveAgents($)).length === 0) stopTicker()
153  await bump($)
154}
155
156async function openPane($: EngineInterface) {
157  await $.ui.open({ id: PANE, title: 'peek' })
158  isOpen = true
159  await bump($)
160  startTicker($)
161}
162
163async function finish($: EngineInterface, id: string, status: string) {
164  const at = await $.clock.now()
165  const shell = shells.get(id)
166  if (shell && shell.endedAt === undefined) {
167    shell.endedAt = at
168    shell.status = status
169  }
170  const agent = agents.get(id)
171  if (agent && agent.endedAt === undefined) {
172    agent.endedAt = at
173    agent.status = status
174  }
175  if (shell || agent) await bump($)
176}
177
178async function hearNotifications($: EngineInterface, text: string) {
179  for (const n of parseNotifications(text)) await finish($, n.id, n.status)
180}
181
182/** The output file's last lines, read through $.fs; a note when there are none. */
183async function readTail($: EngineInterface, path: string | undefined): Promise<{ lines?: string[]; note?: string }> {
184  if (!path) return { note: 'output file not reported' }
185  const stat = await $.fs.stat(path).catch(() => undefined)
186  if (!stat) return { note: 'no output file yet' }
187  if (stat.size > MAX_READ) return { note: `output is ${stat.size.toLocaleString('en-US')} bytes, too large to tail` }
188  const text = await $.fs.read(path).catch(() => undefined)
189  if (typeof text !== 'string') return { note: 'output file unreadable' }
190  const lines = tail(text)
191  return lines.length === 0 ? { note: 'no output yet' } : { lines }
192}
193
194export const register: Register = on => {
195  forget()
196
197  on('session.start', async ($, e, next) => {
198    await $.command.register({
199      name: 'peek',
200      description: 'peek: background shells and subagents, their elapsed time and latest output, in a pane',
201    })
202    return next(e)
203  })
204
205  on('tool.call', async ($, e, next) => {
206    // The model stopping a task ends it.
207    if (e.tool === 'TaskStop') {
208      const ran = await next(e)
209      const id = e.task_id ?? e.shell_id
210      if (ran.deny === undefined && ran.isError !== true && id) await finish($, id, 'killed')
211      return ran
212    }
213    if (!SHELLS.has(e.tool) || typeof e.command !== 'string') return next(e)
214
215    const before = await $.clock.now()
216    const ran = await next(e)
217    if (ran.deny !== undefined || ran.isError === true) return ran
218
219    const record = (ran.result ?? {}) as {
220      backgroundTaskId?: string
221      backgroundedByUser?: boolean
222      timedOutAfterMs?: number
223      backgroundEndsWithFinalResponse?: true
224    }
225    const parsed = parseBackground(ran.text ?? '')
226    const id = record.backgroundTaskId ?? parsed.id
227    if (!id) return ran
228
229    // run_in_background starts the command as the call returns; Ctrl+B or a
230    // timeout moves one that has been running since the call began.
231    const movedLater = record.backgroundedByUser === true || record.timedOutAfterMs !== undefined
232    shells.set(id, {
233      id,
234      command: e.command,
235      startedAt: movedLater ? before : await $.clock.now(),
236      path: parsed.path,
237      loop: e.agentId,
238      endsWithCaller: record.backgroundEndsWithFinalResponse === true,
239    })
240    trim(shells)
241    await bump($)
242    startTicker($)
243
244    return ran
245  })
246
247  on('agent.spawn', async ($, e, next) => {
248    const spawned = await next(e)
249    if (spawned.agentId) {
250      agents.set(spawned.agentId, { id: spawned.agentId, description: e.description, startedAt: await $.clock.now() })
251      trim(agents)
252      await bump($)
253      startTicker($)
254    }
255    return spawned
256  })
257
258  on('turn.complete', async ($, e, next) => {
259    const agent = e.agentId === undefined ? undefined : agents.get(e.agentId)
260    if (agent && agent.endedAt === undefined) {
261      agent.endedAt = await $.clock.now()
262      agent.ms = e.durationMs
263      agent.status = e.reason === 'answer' ? 'completed' : e.reason
264    }
265    // A shell bound to its caller's final answer ends with it, unannounced.
266    for (const s of runningShells()) {
267      if (s.endsWithCaller && s.loop === e.agentId) await finish($, s.id, 'ended with its caller')
268    }
269    if (agent) await bump($)
270    return next(e)
271  })
272
273  // A notification can also start a turn of its own.
274  on('turn.start', async ($, e, next) => {
275    if (e.text.includes('<task-notification>')) await hearNotifications($, e.text)
276    return next(e)
277  })
278
279  on('prompt.submit', async ($, e, next) => {
280    if (e.text.includes('<task-notification>')) await hearNotifications($, e.text)
281    if (e.origin.kind === 'task-notification' || !isStatus(e.text)) return next(e)
282
283    const n = runningShells().length + (await liveAgents($)).length
284    if (n === 0) return next(e)
285
286    await openPane($)
287    // Shown to the person only; the prompt never enters the conversation.
288    return { drop: `peek: ${n} running, opened in the pane` }
289  })
290
291  // Answered with no text: opening the pane adds nothing to the conversation.
292  on('command.run', { command: 'peek' }, async $ => {
293    await openPane($)
294    return {}
295  })
296
297  on('ui.close', async ($, e, next) => {
298    if (e.id === PANE) {
299      isOpen = false
300      stopTicker()
301    }
302    return next(e)
303  })
304
305  // /clear starts a fresh conversation; its background work is not this one's.
306  on('session.end', async ($, e, next) => {
307    forget()
308    return next(e)
309  })
310
311  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
312    const { Box, Text } = $.ui.resolve(e)
313    await read($, tick)
314    const now = await $.clock.now()
315    const live = await liveAgents($)
316    const running = runningShells()
317    const recent = <T extends { endedAt?: number }>(list: T[]) =>
318      list.filter(t => t.endedAt !== undefined && now - t.endedAt <= RECENT_MS)
319    const doneShells = recent([...shells.values()])
320    const doneAgents = recent([...agents.values()])
321    const count = running.length + live.length
322
323    const rows = await Promise.all(
324      running.map(async s => ({ s, out: await readTail($, s.path) })),
325    )
326
327    return (
328      <Box flexDirection="column">
329        <Text bold>{count === 0 ? 'Nothing running in the background.' : `${count} running`}</Text>
330        {rows.map(({ s, out }) => {
331          const pct = out.lines ? lastPercent(out.lines) : undefined
332          return (
333            <Box key={`s-${s.id}`} flexDirection="column" marginTop={1}>
334              <Box flexDirection="row">
335                <Text bold>shell</Text>
336                <Text wrap="truncate-end">{`  ${clip(s.command)}  ·  ${elapsed(now - s.startedAt)}`}</Text>
337              </Box>
338              {pct !== undefined && <Text>{`  ${bar(pct)}  as reported by the task's output`}</Text>}
339              {out.lines ? (
340                out.lines.map((l, i) => <Text key={`l${i}`} dimColor wrap="truncate-end">{`  ${l}`}</Text>)
341              ) : (
342                <Text dimColor>{`  ${out.note}`}</Text>
343              )}
344            </Box>
345          )
346        })}
347        {live.map(a => {
348          const seen = agents.get(a.id)?.startedAt
349          return (
350            <Box key={`a-${a.id}`} flexDirection="column" marginTop={1}>
351              <Box flexDirection="row">
352                <Text bold>subagent</Text>
353                <Text wrap="truncate-end">
354                  {`  ${clip(a.description || a.type)}  ·  ${seen === undefined ? 'started before peek loaded' : elapsed(now - seen)}`}
355                </Text>
356              </Box>
357              <Text dimColor>{`  ${a.type} · ${a.status}`}</Text>
358            </Box>
359          )
360        })}
361        {doneShells.length + doneAgents.length > 0 && (
362          <Box flexDirection="column" marginTop={1}>
363            <Text dimColor bold>Finished in the last 10 minutes</Text>
364            {doneShells.map(s => (
365              <Text key={`ds-${s.id}`} dimColor>
366                {`shell  ${clip(s.command)}  ·  ${s.status}, notified after ${elapsed((s.endedAt ?? now) - s.startedAt)}`}
367              </Text>
368            ))}
369            {doneAgents.map(a => (
370              <Text key={`da-${a.id}`} dimColor>
371                {`subagent  ${clip(a.description)}  ·  ${a.status}${
372                  a.ms !== undefined
373                    ? `, ran ${elapsed(a.ms)}`
374                    : a.startedAt !== undefined
375                      ? `, notified after ${elapsed((a.endedAt ?? now) - a.startedAt)}`
376                      : ''
377                }`}
378              </Text>
379            ))}
380          </Box>
381        )}
382      </Box>
383    )
384  })
385}
386
types/index.d.ts 12 lines
1/** The pane's redraw counter: the clock reading of the latest change or tick. */
2export type PeekTick = number
3
4declare module 'claude-code' {
5  interface PluginState {
6    peek: {
7      /** Bumped on every change and every second while the pane is open, so it redraws. */
8      tick: PeekTick
9    }
10  }
11}
12