SLOPSHOPPER

session-progress

Animated progress band for long-running turns, with a completion summary

bandspinnerrowsguardprompttool
v0.4.0MITupdated 2026-10-17VAlux/claude-session-progress
A shopper browsing a rack in a slop shop
README

session-progress

A live progress band for long Claude Code tasks, and a short summary when they finish.

License: MIT Claude Code plugin Surfaces: terminal, desktop

<img src="docs/demo.gif" alt="session-progress following a six-step plan in Claude Code, then showing its details, the cost and the session total" width="900">

Install

At the prompt of a Claude Code terminal session:

/plugin install session-progress --marketplace VAlux/claude-session-progress

Answer y to add the marketplace, then pick a scope. The user scope loads it in every session. It starts working in the current session right away.

The desktop app's Code tab has no /plugin command. Install it from a terminal at the user scope, and the local sessions the desktop app starts load it too.

At a glance

While Claude works

Ask Claude for something that takes a while, say "Implement plan.md step by step", and after a few seconds a band appears above the prompt:

<img src="docs/band-live.png" alt="The live band: the step in progress, a bar with ~20s left, counts of tool calls, files, reads, steps and tokens with their cost, and the plan's steps ticked off below" width="900">

Read it top to bottom:

  • Exit with status 1 and a clear message when the file is missing: the step Claude is on now, taken from plan.md.
  • plan.md · 2/6 steps · 12s: where the steps come from, how many are done, and how long the turn has run.
  • The bar and ~20s left: how much of the work is behind it, and the countdown for the rest.
  • ⚒ 4 tool calls ✎ 2 files +32 −2 ⌕ 1 read ↻ 2 steps ⇅ 64k↑ 746↓ · $0.09: what the turn has done so far: tool calls, files changed with lines added and removed, files read, model requests, and tokens in and out with what they cost. Click any of them to see the list behind it.
  • ↳ editing plan.md: what is running right now.
  • The steps: ✓ done, ◐ in progress, ○ still to do.

When it finishes

<img src="docs/band-summary.png" alt="The summary: Task complete with a full green bar, the counts, the files changed with their line counts opened, tokens and cost, the tools used, and the first estimate against how long the turn took" width="900">

The bar fills and turns green, and the band becomes a summary: ✓ Task complete, 12 tool calls, 4 files changed (opened here, so each file shows its own +30 −0), 6 of 6 steps done, one failed call to look into, 277k tokens in (87% of them from the cache) and 3.4k out for $0.17, the model, the tools it used most, and a last line comparing the first estimate with how long the turn took. It goes away when you send your next prompt.

How the countdown is worked out

The countdown doesn't guess from the clock. It counts the work Claude has said is left and prices each piece by what similar pieces took before:

  1. What is left. Claude reports its remaining items through the mod's progress tool, each sized small, medium or large (s, m, l). A task list or a - [ ] plan file counts too.
  2. How many rounds each needs. A round is one model request plus the tools it ran. The mod remembers how many rounds items of each size took in your past turns: say a medium item took 4 rounds and a small one 1½.
  3. How fast rounds go right now. If this turn's rounds take about 15 s each, then two medium items and one small one are (4 + 4 + 1½) × 15 s ≈ 2m 20s.
  4. Commands it has timed. An item that is just running a command, like npm test, uses how long that command took the last times it ran in this project.
  5. How your past turns compared. Once 5 turns are on record, if they tend to take 1.3× their first estimate, because work turned up that the first list didn't name, the time left is scaled to match: ~3m left (2–4m).
  6. As items finish, how they compared with their own estimates corrects the rest, and the range narrows.

Steps 5 and 6 form a loop that runs across turns. When a turn ends, the mod keeps its first estimate (before any correction) beside how long the turn took, and works the correction out again from the last 50 of those pairs:

<img src="docs/calibration-loop.png" alt="The self-calibration loop. During a turn: work left becomes a raw estimate (rounds per size times this turn's pace), which is calibrated (time times bias, range widened) and shown as the countdown. After the turn: the raw first estimate and the time it took go into a log row, the calibration is recomputed from the last 50 rows (5 or more needed), and its bias and widen feed the next turn's calibration." width="900">

The log keeps the estimate from before the correction on purpose. If it kept the corrected one, each row would only record what the last correction missed. The correction would then shrink, and turns would start running long again.

Nothing is sent anywhere: what it learns stays in a small file under your Claude Code configuration folder. The details are in How long is left.

What it shows

While Claude worksA pulsing spinner and the step Claude is on, an animated bar, elapsed time, and a row of counts, each with its own icon: ⚒ tool calls, ⑂ subagents, ✎ files changed with the lines added and removed, ⌕ files read, ↻ model steps, ⇅ tokens with their estimated cost in USD, and ⚠ errors. Below them, what is running right now.
When you click a countIts details open under the row (see Details). Click it again to close them.
When the steps are knownThe headline names the step in progress, and the bar moves toward the end as the countdown runs down. A plan file's steps, and the items Claude reports, are listed under the bar with ✓ done, ◐ in progress and ○ to do. A task list's are not, because Claude Code already draws its own.
How long is leftOnce Claude has said what is left, the bar's label counts it down: ~4m left (3–6m), then ~1m 30s left, then a few seconds left. It turns amber with ↑ for a few seconds when the estimate grows, and the bar itself never moves back. See How long is left.
When Claude hands off to a subagentA turn that ends while the subagents it started still run says Waiting for N subagents, not Task complete. Its bar goes on with their countdown instead of filling, and waits where it is while one of them has none.
In a subagent's transcriptOpen a subagent from the tasks list and the band follows that subagent alone: its current task or activity, its own task list or report, its countdown and bar, its tool calls, files, tokens and time. When it answers, the band says Subagent complete. A subagent the band never saw (one that started before the mod loaded) gets no band, rather than the main one's.
When it finishesThe bar fills and turns green, or amber if you interrupted it, or red on an error. The summary lists work done, tokens in and out with the cache share, the estimated cost of the task in USD, the model and the most-used tools, how long the first estimate said the turn would take against how long it took (⏱ estimated ~7m (4–10m) · took 7m 40s, when the turn had a countdown and ended with nothing left running), and, from the second turn on, one line of totals for the session, cost included. It leaves the turn's time to Claude Code's own closing line (Brewed for 5m 59s).
On your next promptThe summary goes away.

Details

Each count under the bar is a button. Click it, or focus the band with ctrl+x tab and press Enter on it, and the band lists what is behind it. One list is open at a time, and it stays open across turns until you click the count again.

CountWhat it lists
⚒ tool callsA tally by tool, then the latest calls: ✓ done, ◐ running, ✗ failed (with why), and how long each took
⑂ subagentsEach subagent the turn started: its description and type, its calls, output tokens and time, and what it is doing now
✎ filesEach file changed, by name, with the lines added and removed (a.ts +12 −3). Two files with one name show their folder too. Shell commands that changed files they don't name are listed first (+ shell changes it can't name: git merge)
⌕ readThe files read, side by side
↻ stepsTime spent in the model and in tools, then each model request: the tools it called, its tokens and its time
⇅ tokensThe estimated cost, input split into fresh, cache read and cache write, output per step, the context at the last step, and the model
⚠ errorsEach failed call, a subagent's marked with ⑂, and why it failed
☰ tasksIn the summary: the task list or plan steps, with ✓ ◐ ○

A list shows its latest rows, with a +N earlier (or +N more) row when others do not fit. Press that row to list them all, up to the room the band has, and press ▴ show fewer to go back. Closing the list or opening another one starts it capped again.

The summary keeps the finished turn's details, so you can open them after the turn ends. Line counts come from each edit's own patch. A notebook edit, or a rewrite of a file too large to diff, has no line count, and its file reads changed instead.

Files changed through Bash count too, as far as the command's text tells: a redirect, tee, sed -i, perl -pi, rm/mv/cp, git mv/rm/restore, and a Python, Node or Ruby script that writes a literal path. These read changed. Some commands change files without naming them: git merge, git checkout of a branch, git stash pop, prettier --write, a script that writes a path it computes. After one of those, the count reads 3 files changed (+ shell edits), or files changed by shell when that is all the turn changed, because the real number may be higher.

How progress is measured

SourceWhat the countdown counts
Claude's own report, through the mod's progress toolThe items Claude says are left, each sized s, m or l, or named by the command that running is the item. Claude Code draws nothing for them, so the band lists them under the bar, each with its estimate.
A task list (TodoWrite, or TaskCreate / TaskUpdate)The tasks not yet done, the one in progress by what is left of it
A Markdown plan with - [ ] / - [x] boxes that Claude reads or editsThe boxes not yet ticked
A plan with two or more ### Task N: headingsThe tasks not yet done. A task is done when all its boxes are ticked, or when a superpowers ledger reports Task N: complete, whether in a Bash call's output (task-done) or in its progress.md that Claude reads. superpowers' executor never ticks a plan's boxes, so without this its plans never moved.
None of theseA soft streak sweeps the track. There is nothing to count down, so it does not invent a number, and the bar carries no label: the clock is on the row above.

A report wins over a task list for the countdown, and a task list over a plan file; the rows under the bar and the 2/5 tasks count keep following a task list or plan when there is one. A plan that is still unfinished carries over to the next turn, and a finished one is cleared; a report belongs to its turn. A subagent's own task list, report or checklist file (superpowers' task brief, say) never replaces the main one, but a subagent can still mark the main session's tasks done or tick its plan. Its own drives its own band instead.

The mod adds two lines to the system prompt: one asking Claude to keep a task list when a task has several known steps, one asking it to report what is left with the progress tool when it has not, starting with its first tool calls. How to report is left to the tool's own description, which Claude sees anyway: items of a few words, done rather than the whole list again, sent with the first tool calls of the next item and for one item at a time (a done for several items at once cannot tell how long each took, so none of them is learned), and no last report once the work is done, since the turn ending closes the last item. Claude does not always follow that line, so a turn that reaches 5 tool calls with no report, task list or plan gets one reminder, attached to that call's result, which the transcript does not show. Claude also often works through its reported items without saying they finished, which leaves the first one shown in progress throughout; so once a report has stood unchanged with items still listed for 3 rounds when the item in progress is size s, 6 when it is m, unsized or a command, or 8 when it is l, the next call gets one reminder that names the item shown in progress and asks Claude to send done if it finished, unless it is about to answer. Each new report can bring one such reminder.

How long is left

Each item is worked out in rounds (a model request and the tools it ran), from how many rounds items of its size took in your past turns (built-in guesses until there are some), times how long this turn's rounds take. History stores rounds, not seconds, so a slower model or a higher effort changes the pace, not the history. A run item's estimate is that command's own measured time in this project: the band times every foreground Bash call. As the turn goes, how its finished items compared with their estimates corrects the rest. When Claude answers with one item still listed, that item counts as finished when the answer began.

The range, (3–6m), comes from how much those past times varied. It narrows as items finish. The bar moves at the speed that reaches the end with the countdown, slows when the work grows, and waits at 97% until the turn ends.

It also checks itself against your past turns. Each turn's first estimate is kept beside what the turn took, and once 5 turns are on record, the last 50 correct the estimates that follow: the time left is scaled by how much longer (or shorter) turns took than first estimated, often because work turned up that the first list did not name, and the range is widened or narrowed until about 6 turns in 10 would have landed inside it. With few turns on record the correction counts for less, and within a turn it gives way to the turn's own items as they finish. It applies to the time left as a whole, not to each item's own estimate, and leaves a command's measured time as it is.

There is no countdown before Claude has said what is left — a report, a task list or a plan — while the turn waits on a subagent that has none, once Claude reports nothing left yet keeps working, and once an item runs far past its range (twice its top) with no report for 12 rounds.

What it learns is kept in the mod's own store, a JSON file under your Claude Code configuration directory: samples per size, the last 10 run times of each command per project, kept by a hash of the command rather than its text, and each turn's first estimate, as shown and before that correction, against what followed (the last 200), which is what the correction is worked out from, and how its accuracy can be judged on your own turns. Each report is a tool call Claude makes alongside its others: tens of output tokens, and no extra model request. The tool's definition also adds a few hundred input tokens to each request, and a report Claude sends on its own costs a round. Most of those were a last done sent just before the answer, which is why Claude is asked to skip it. Each reminder, when a turn gets one, is under 100 input tokens. Its rows are hidden from the transcript.

When it appears

Quick answers and short Q&A never show the band. It appears once a turn has run:

20 s, with at least 3 tool callsordinary multi-step work
8 s, with a task list, plan or report of 2+ stepsplanned work, which shows sooner
45 sanything that runs long

The thresholds are the constants at the top of hooks/register.tsx.

While the band shows, Claude Code's own spinner line (Sauteing… (12s, 300 tokens)) is hidden, since the band's head row has the clock and its stats the tokens. Before the band appears, after the turn, and in VS Code, the spinner is drawn as usual, and it stays whenever it names a state in place of its word. A subagent's spinner is always left alone. Set spinner to keep to always see it.

Settings

Change it in /config, or with claude plugin configure session-progress.

SettingValuesWhat it does
stepRowsauto, always, neverWhen the band lists the steps under its bar. auto lists a Markdown plan's steps and the items Claude reports, since Claude Code draws its own task list. always lists task lists too, and never lists nothing.
etaon, offWhether the band counts down the work left. off registers no tool, adds no prompt line, records nothing, and the bar shows the share of a task list or plan done, as before 0.2.0.
spinnerauto, keepWhether Claude Code's spinner line shows while the band does. auto hides it then, and only then; keep always shows it.

To make the band your only task view, hide Claude Code's own list with ctrl+t and set stepRows to always.

Good to know

  • It draws in the terminal and in the desktop app. On the desktop the bar and spinner are vector drawings that animate themselves, and the finish lands at once instead of easing in. The VS Code extension and the mobile app have no band above the prompt, so they show nothing extra.
  • Costs are estimates: each model step's tokens at Anthropic's list prices (the table at the top of hooks/frames.ts), subagents included. A model missing from the table adds nothing, and a plan's discount or a different provider's rate is not reflected.
  • The countdown is an estimate: early on it rests on few items and Claude's own sizing, and the summary's ⏱ line shows how far off it was.
  • A command's learned time includes any wait for you to approve it, so a run you approved slowly reads long until later runs push it out. A refused command is never learned.
  • Collapse the band at any time with ctrl+x ctrl+a, or with the [-] mark at its right edge.
  • A bug in the mod never blocks a tool call: its tool hook passes the call through if it fails.
  • It shares the space above the prompt: another mod's band there (factory-floor's strip, say) is drawn above it, not hidden.
  • It is built on Claude Code's function-hooks plugin API, which is in early access and may change between releases.

Develop

git clone https://github.com/VAlux/claude-session-progress
claude --plugin-dir ./claude-session-progress     # load the working copy for one session
claude plugin validate ./claude-session-progress
claude plugin test ./claude-session-progress
PathWhat it holds
hooks/register.tsxThe hooks: turn and tool tracking, plan files, the system-prompt lines, the band
hooks/details.tsWhat each count opens onto: the per-call, per-file and per-step records, line counting, and the detail rows
hooks/eta.tsThe countdown: pace, each item's spread, the total, the fill, and what a loop learns
hooks/report.tsThe progress tool, its prompt line, and reading reports into a work list
hooks/history.tsThe countdown's samples in the mod's store
hooks/frames.tsBar and spinner frames (terminal cells, desktop SVG), the plan and ledger parsers, formatting
types/index.d.tsThe mod's state contract
tests/Behaviour tests, run with claude plugin test

The demo in docs/ was recorded with VHS from docs/demo.tape. The two band screenshots under At a glance are frames cut from it.

License

MIT

Source 9 files
hooks/register.tsx 1505 lines
1import { atom, read, update } from 'claude-code'
2import type { Color, Elements, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { AgentRun, Detail, EtaPending, EtaTurn, Live, PlanFile, PlanTask, Spread, StatKind, Summary, Task, TaskStatus, Totals } from '../types'
5import {
6  ICONS,
7  changedFiles,
8  detailLines,
9  detailOf,
10  editLines,
11  emptyDetail,
12  errorText,
13  finishCall,
14  withAgent,
15  withCall,
16  withFile,
17  withRead,
18  withShellEdits,
19  withStep,
20  type DetailLine,
21  type DetailSource,
22} from './details'
23import {
24  ACCENT,
25  DONE,
26  FAIL,
27  WARN,
28  activityLabel,
29  barCells,
30  barSvg,
31  capitalize,
32  countdownLabel,
33  etaRange,
34  etaValue,
35  hex,
36  isGrowing,
37  MUTED,
38  pctLabel,
39  duration,
40  glyphCells,
41  isMarkdown,
42  ledgerPlanName,
43  ledgerTasks,
44  parsePlan,
45  plural,
46  shortToolName,
47  spinnerCells,
48  spinnerSvg,
49  stepCost,
50  tokens,
51  usd,
52  type Palette,
53} from './frames'
54import {
55  closingAt,
56  combine,
57  commandKey,
58  correction,
59  emptyPending,
60  estimate,
61  freshEta,
62  learnCommand,
63  learnItem,
64  learnOpenTop,
65  learnTasks,
66  paceOf,
67  runningSince,
68  tickEta,
69  type EtaInput,
70  type TaskKind,
71} from './eta'
72import { calibrated } from './calibrate'
73import { flushHistory, loadHistory, logRowOf, seeded, type History, type LogRow, type Store } from './history'
74import { PROGRESS_SPEC, PROGRESS_TOOL, applyReport, etaLine, nudgeLine, parseReport, staleLine, workTasks } from './report'
75import { shellWrites } from './shell'
76
77const live = atom({ plugin: 'session-progress', key: 'live' } as const, null)
78const summary = atom({ plugin: 'session-progress', key: 'summary' } as const, null)
79const tasks = atom({ plugin: 'session-progress', key: 'tasks' } as const, [])
80const planFile = atom({ plugin: 'session-progress', key: 'planFile' } as const, null)
81const totals = atom({ plugin: 'session-progress', key: 'totals' } as const, {
82  turns: 0,
83  longTurns: 0,
84  totalMs: 0,
85  toolCalls: 0,
86  tokensIn: 0,
87  tokensOut: 0,
88})
89const tick = atom({ plugin: 'session-progress', key: 'tick' } as const, 0)
90const agents = atom({ plugin: 'session-progress', key: 'agents' } as const, [])
91const openStat = atom({ plugin: 'session-progress', key: 'openStat' } as const, null)
92const showAll = atom({ plugin: 'session-progress', key: 'showAll' } as const, false)
93const etaTurn = atom({ plugin: 'session-progress', key: 'eta' } as const, null)
94
95// What the settings turned on, read by the timers and hooks outside `register`. Module state: a reload sets it again.
96const config = { eta: true }
97// The countdown's history: read from the store when a session starts, refreshed by each write.
98let history: History = seeded()
99let project: string | null = null
100// Writes to the store, one after another, so two loops ending at once never drop each other's samples.
101let flushing: Promise<void> = Promise.resolve()
102
103/** The part of `$.store` the history uses, spelled out here: the host lets a hooks module make only the `$` calls it can see it make. */
104const storeOf = ($: Dollar): Store => ({ get: key => $.store.get(key), set: (key, value) => $.store.set(key, value) })
105
106// When a turn earns the band: a quick answer or a short Q/A never does.
107const SHOW_AFTER_MS = 20_000
108const SHOW_AFTER_TOOLS = 3
109const SHOW_WITH_PLAN_AFTER_MS = 8_000
110const SHOW_ALWAYS_AFTER_MS = 45_000
111// When a turn with nothing to count down reminds Claude, once, to report what is left.
112const NUDGE_AFTER_TOOLS = 5
113// Rounds a report may stand unchanged, items still listed, before Claude is reminded, once a report, that it may be out of date:
114// by the top item's size, just past the tool calls its description allows. Fixed, since the learned samples run long when `done` comes late.
115const REMIND_AFTER_ROUNDS = { s: 3, m: 6, l: 8 } as const
116
117const FRAME_MS = 70
118const FINISH_MS = 1_400
119const SPINNER_KEY = 'spin'
120const BAR_KEY = 'bar'
121const MAX_TASK_ROWS = 5
122const MAX_DETAIL_ROWS = 8
123// A subagent's band draws its own Raster keys, so the main bar's frame loop never paints into it.
124const AGENT_SPINNER_KEY = 'agent-spin'
125const AGENT_BAR_KEY = 'agent-bar'
126const MAX_AGENTS = 30
127// Spare columns after the bar's label: a row that fills the band exactly wraps on some terminals.
128const BAR_SLACK = 2
129
130const PLAN_TOOLS = new Set(['TodoWrite', 'TaskCreate', 'TaskUpdate'])
131const WRITE_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
132const PLAN_FILE_TOOLS = new Set(['Read', 'Edit', 'MultiEdit', 'Write'])
133
134/** A subagent's own TodoWrite/TaskCreate list never replaces the main one; its TaskUpdate may tick main tasks. */
135export function tracksPlanTool(tool: string, isSubagent: boolean): boolean {
136  return PLAN_TOOLS.has(tool) && (!isSubagent || tool === 'TaskUpdate')
137}
138
139function taskListLine(tools: readonly string[]): string | null {
140  const how = tools.includes('TaskCreate') ? 'TaskCreate and TaskUpdate' : tools.includes('TodoWrite') ? 'TodoWrite' : null
141  if (how === null) return null
142  return (
143    `When a task has several known steps, such as implementing a spec or a plan, keep a task list with ${how}: ` +
144    'one entry per step before you start, marked in progress when you begin it and completed as soon as it is done. ' +
145    'Skip the list for quick questions and single-step changes.'
146  )
147}
148
149type Dollar = EngineInterface
150
151type BarLook = { shimmer: boolean; label: string; labelColor: number }
152
153/** What draws the band's spinner, marks and bar on one surface; the rows around them are the same on both. */
154type Marks = {
155  /** A row's width: the terminal lays the band out in cells, the desktop to its page. */
156  rowWidth: number | string
157  spinner(key: string, palette: Palette, t: number): JSX.Element
158  mark(key: string, glyph: string, palette: Palette): JSX.Element
159  bar(key: string, columns: number, progress: number | null, t: number, palette: Palette, look: BarLook): JSX.Element
160}
161
162/** Raster cells, which the frame loop repaints between redraws by their keys. */
163function terminalMarks({ Raster }: Elements['terminal'], width: number): Marks {
164  return {
165    rowWidth: width,
166    spinner: (key, palette, t) => <Raster key={key} columns={1} rows={1} cells={spinnerCells(t, palette)} />,
167    mark: (key, glyph, palette) => <Raster key={key} columns={1} rows={1} cells={glyphCells(glyph, palette.base)} />,
168    bar: (key, columns, progress, t, palette, look) => (
169      <Raster key={key} columns={columns} rows={1} cells={barCells(columns, progress, t, palette, look)} />
170    ),
171  }
172}
173
174/** SVG that animates itself: the desktop takes no blits, so nothing repaints it between redraws. */
175function desktopMarks({ Box, Text, Svg }: Elements['desktop']): Marks {
176  return {
177    rowWidth: '100%',
178    spinner: (key, palette) => <Svg key={key} source={spinnerSvg(palette)} alt="Working" width={12} height={12} isInteractive />,
179    mark: (key, glyph, palette) => (
180      <Text key={key} bold color={hex(palette.base)}>
181        {glyph}
182      </Text>
183    ),
184    bar: (key, _columns, progress, _t, palette, { shimmer, label, labelColor }) => {
185      const { source, isAnimated } = barSvg(progress, palette, { shimmer })
186      const pct = label.trim()
187      return (
188        <Box flexDirection="row" flexGrow={1} alignItems="center" gap={1}>
189          <Box flexGrow={1}>
190            <Svg key={key} source={source} alt={pct === '' ? 'Progress: working' : `Progress: ${pct}`} height={6} isInteractive={isAnimated} />
191          </Box>
192          {pct !== '' && <Text color={hex(labelColor)}>{pct}</Text>}
193        </Box>
194      )
195    },
196  }
197}
198
199// What the frame loop paints between redraws. Module state: a reload refills it on the next draw.
200const scene = {
201  requestId: null as string | null,
202  barWidth: 0,
203  // What the bar's own label shows between redraws: the live percentage, or a fixed text (none while nothing is measured).
204  showPct: false,
205  label: '',
206  labelColor: MUTED,
207  target: null as number | null,
208  shown: 0,
209  palette: ACCENT,
210  isFinishing: false,
211  finishFrom: 0,
212  finishFrames: 0,
213}
214let frameTimer: Timer | null = null
215let tickTimer: Timer | null = null
216
217function freshLive(turnId: string, startedAt: number): Live {
218  return {
219    turnId,
220    startedAt,
221    isLong: false,
222    steps: 0,
223    toolCalls: 0,
224    subagentToolCalls: 0,
225    subagents: 0,
226    errors: 0,
227    byTool: {},
228    running: [],
229    lastActivity: null,
230    tokensIn: 0,
231    tokensCached: 0,
232    tokensCacheWrite: 0,
233    tokensOut: 0,
234    cost: 0,
235    model: null,
236    detail: emptyDetail(),
237  }
238}
239
240function freshAgent(id: string, startedAt: number): AgentRun {
241  return {
242    id,
243    description: null,
244    type: null,
245    parentId: null,
246    dispatchedByMain: false,
247    startedAt,
248    finishedAt: null,
249    durationMs: null,
250    reason: null,
251    steps: 0,
252    toolCalls: 0,
253    errors: 0,
254    running: [],
255    lastActivity: null,
256    tokensIn: 0,
257    tokensOut: 0,
258    detail: emptyDetail(),
259    tasks: [],
260    ...(config.eta ? { eta: freshEta(startedAt) } : {}),
261  }
262}
263
264const isRunning = (run: AgentRun) => run.finishedAt === null
265
266/** The subagents a finished main turn still waits on: the ones its own Agent calls started that have not answered. */
267export function waitingOn(runs: readonly AgentRun[]): number {
268  return runs.filter(run => run.dispatchedByMain && isRunning(run)).length
269}
270
271/** Applies `change` to an agent's run, adding the run first if the band has not seen that agent yet. */
272async function updateAgent($: Dollar, id: string, now: number, change: (run: AgentRun) => AgentRun) {
273  await update($, agents, list => {
274    const i = list.findIndex(run => run.id === id)
275    if (i >= 0) return list.map((run, j) => (j === i ? change(run) : run))
276    return [...list, change(freshAgent(id, now))].slice(-MAX_AGENTS)
277  })
278}
279
280const ENDED: Record<string, Summary['reason']> = { completed: 'answer', failed: 'error', killed: 'aborted' }
281
282/** Marks the runs the engine says have ended, for an agent whose own end the band missed. */
283async function reconcileAgents($: Dollar) {
284  let known: { id: string; status: string }[]
285  try {
286    known = await $.agent.list()
287  } catch {
288    return
289  }
290  const ended = new Map(known.filter(a => ENDED[a.status] !== undefined).map(a => [a.id, ENDED[a.status]!]))
291  if (ended.size === 0) return
292  const now = await $.clock.now()
293  await update($, agents, list =>
294    list.map(run => (isRunning(run) && ended.has(run.id) ? { ...run, finishedAt: now, reason: ended.get(run.id)!, running: [] } : run)),
295  )
296}
297
298function planProgress(list: readonly Task[]): number | null {
299  if (list.length === 0) return null
300  const done = list.filter(t => t.status === 'completed').length
301  const active = list.filter(t => t.status === 'in_progress').length
302  return (done + active * 0.5) / list.length
303}
304
305type Steps = { list: Task[]; progress: number | null; unit: 'tasks' | 'steps'; source: string | null }
306
307export function stepsOf(taskList: readonly Task[], plan: PlanFile | null): Steps {
308  if (taskList.length > 0) return { list: [...taskList], progress: planProgress(taskList), unit: 'tasks', source: null }
309  if (plan === null) return { list: [], progress: null, unit: 'tasks', source: null }
310  const headed = plan.tasks ?? []
311  if (headed.length >= 2) {
312    // A task is done when a ledger reported it or all its boxes are ticked: superpowers' executor only does the first.
313    const completed = new Set(plan.completed ?? [])
314    const isDone = (task: PlanTask) => completed.has(task.n) || (task.steps > 0 && task.stepsDone === task.steps)
315    const firstOpen = headed.findIndex(task => !isDone(task))
316    const list = headed.map((task, i): Task => ({
317      id: `plan-task-${task.n}`,
318      subject: task.text,
319      status: isDone(task) ? 'completed' : i === firstOpen ? 'in_progress' : 'pending',
320    }))
321    return { list, progress: headed.filter(isDone).length / headed.length, unit: 'tasks', source: plan.name }
322  }
323  if (plan.items.length < 2) return { list: [], progress: null, unit: 'tasks', source: null }
324  const firstOpen = plan.items.findIndex(item => !item.done)
325  const list = plan.items.map((item, i): Task => ({
326    id: `plan-${i}`,
327    subject: item.text,
328    status: item.done ? 'completed' : i === firstOpen ? 'in_progress' : 'pending',
329  }))
330  const done = plan.items.filter(item => item.done).length
331  return { list, progress: done / plan.items.length, unit: 'steps', source: plan.name }
332}
333
334async function readSteps($: Dollar): Promise<Steps> {
335  return stepsOf(await read($, tasks), await read($, planFile))
336}
337
338async function trackPlanFile($: Dollar, path: string, written: string | null, isSub: boolean) {
339  let text = written
340  if (text === null) {
341    try {
342      text = await $.fs.read(path)
343    } catch {
344      return
345    }
346  }
347  const { items, tasks: headed } = parsePlan(text)
348  const reported = ledgerTasks(text)
349  const name = path.split('/').pop() || path
350  await update($, planFile, current => {
351    if (items.length < 2) {
352      // A superpowers ledger read on its own ticks the plan it names (or the current one, if it names none).
353      if (reported.length > 0 && current !== null && current.path !== path) {
354        const of = ledgerPlanName(text)
355        if (of === null || of === current.name) return withCompleted(current, reported)
356      }
357      return current?.path === path ? null : current
358    }
359    // A subagent's own checklist (superpowers' task brief, say) never takes over; its edit to the main plan still counts.
360    if (isSub && current?.path !== path) return current
361    // Another file only takes over while it still has open steps (a finished checklist read for reference does not).
362    const isOpen = items.some(item => !item.done)
363    if (current !== null && current.path !== path && !isOpen && current.items.some(item => !item.done)) return current
364    return { path, name, items, tasks: headed, completed: current?.path === path ? (current.completed ?? []) : [] }
365  })
366}
367
368function withCompleted(plan: PlanFile, numbers: readonly number[]): PlanFile {
369  const known = plan.completed ?? []
370  const added = numbers.filter(n => !known.includes(n))
371  return added.length === 0 ? plan : { ...plan, completed: [...known, ...added] }
372}
373
374/** The tasks a Bash call reports complete in its output, as superpowers' task-done prints them. */
375function bashReported(ran: unknown): number[] {
376  const r = ran as { result?: { stdout?: unknown }; text?: unknown }
377  const out = typeof r.result?.stdout === 'string' ? r.result.stdout : typeof r.text === 'string' ? r.text : ''
378  return ledgerTasks(out)
379}
380
381/** Which samples a step list's entries take: a task list's, a plan's `### Task N:` headings', or a plan's boxes'. */
382const taskKind = (steps: Steps): TaskKind => (steps.source === null ? 'task' : steps.unit === 'tasks' ? 'planTask' : 'planStep')
383
384/** Reads the history once a session: at its start, or at a turn's when the session started before the mod. */
385async function ensureHistory($: Dollar) {
386  if (project !== null) return
387  try {
388    project = await $.session.root()
389  } catch {
390    project = ''
391  }
392  history = await loadHistory(storeOf($), project)
393}
394
395/** Writes a loop's samples after any write still under way. An interrupted loop's command times are not its commands' run times. */
396async function flush($: Dollar, pending: EtaPending, isAborted: boolean, row: LogRow | null) {
397  const kept = isAborted ? { ...pending, commands: {} } : pending
398  flushing = flushing
399    .then(async () => {
400      const written = await flushHistory(storeOf($), project ?? '', kept, await $.clock.now(), row)
401      if (written !== null) history = written
402    })
403    .catch(() => {})
404  await flushing
405}
406
407/** A subagent's estimate as a main turn waiting on it combines it: as shown, and before calibration. */
408type Waited = { shown: Spread | null; raw: Spread | null }
409
410/** One loop's countdown worked out again: its finished tasks learned, its estimate made and calibrated, its bar moved on. */
411function refreshed(eta: EtaTurn, detail: Detail, tasks: EtaInput['tasks'], rounds: number, now: number, waitedOn: readonly Waited[] | null): EtaTurn {
412  const pace = paceOf(detail, eta.runs)
413  const learned = tasks === null ? eta : learnTasks(eta, tasks.list, tasks.kind, now, pace, history.sizes)
414  const own = estimate({
415    now,
416    pace,
417    work: learned.work,
418    runningSince: runningSince(detail, learned.work),
419    tasks,
420    since: learned.since,
421    sizes: history.sizes,
422    commands: history.commands,
423    c: correction(learned.actual, learned.estimated),
424    roundsSinceReport: rounds - learned.lastReportRound,
425  })
426  // Past turns' correction goes on the whole estimate, not on its items: it stands mostly for work the first list did not name.
427  const raw = own.estimate
428  const shown = raw === null || pace === null ? raw : calibrated(raw, history.calibration, learned.estimated, pace, own.measuredMs)
429  const out =
430    waitedOn === null
431      ? { ...own, estimate: shown, raw }
432      : { ...own, estimate: combine(shown, waitedOn.map(w => w.shown)), raw: combine(raw, waitedOn.map(w => w.raw)) }
433  return tickEta(learned, out, now)
434}
435
436/** Every loop's countdown, again: the subagents' first, since a main turn waiting on them shows the longest of theirs. */
437async function refreshEta($: Dollar, now: number) {
438  if (!config.eta) return
439  await update($, agents, list =>
440    list.map(run =>
441      run.eta === undefined || !isRunning(run)
442        ? run
443        : { ...run, eta: refreshed(run.eta, detailOf(run), run.tasks.length > 0 ? { list: run.tasks, kind: 'task' } : null, run.steps, now, null) },
444    ),
445  )
446  const l = await read($, live)
447  const turnStart = (await read($, etaTurn))?.startedAt
448  // While the turn is live, a subagent an earlier turn started is not its to wait on; after it, the ones still running are what the wait is.
449  const waitedOn = (await read($, agents))
450    .filter(run => run.dispatchedByMain && isRunning(run) && (l === null || turnStart === undefined || run.startedAt >= turnStart))
451    .map((run): Waited => ({ shown: run.eta?.last ?? null, raw: run.eta === undefined ? null : run.eta.lastRaw === undefined ? run.eta.last : run.eta.lastRaw }))
452  const steps = await readSteps($)
453  await update($, etaTurn, eta => {
454    if (eta === null) return eta
455    // After the turn's own end, only the subagents it waits on are left to estimate.
456    if (l === null) return tickEta(eta, { estimate: combine(null, waitedOn.map(w => w.shown)), raw: combine(null, waitedOn.map(w => w.raw)), items: [], source: null }, now)
457    return refreshed(eta, detailOf(l), steps.list.length > 0 ? { list: steps.list, kind: taskKind(steps) } : null, l.steps, now, waitedOn)
458  })
459}
460
461/** Takes in one of Claude's reports: its loop's list changes, a top item that finished is learned, the countdown is worked out again. */
462async function takeReport($: Dollar, agentId: string | undefined, input: Record<string, unknown>) {
463  const report = parseReport(input)
464  if (report === null) return
465  const now = await $.clock.now()
466  const take = (eta: EtaTurn, detail: Detail, rounds: number): EtaTurn => {
467    const { work, finished } = applyReport(eta.work, report, now)
468    const added = 'left' in report ? report.left.flatMap(item => (item.run === undefined ? [] : [commandKey(item.run)])) : []
469    const runs = [...new Set([...eta.runs, ...added])]
470    const next = { ...eta, work, runs, lastReportRound: rounds }
471    return finished === null ? next : learnItem(next, finished, now, paceOf(detail, runs), history.sizes)
472  }
473  if (agentId !== undefined) {
474    await updateAgent($, agentId, now, run => ({ ...run, eta: take(run.eta ?? freshEta(run.startedAt), detailOf(run), run.steps) }))
475  } else {
476    const l = await read($, live)
477    await update($, etaTurn, eta => (eta === null || l === null ? eta : take(eta, detailOf(l), l.steps)))
478  }
479  await refreshEta($, now)
480}
481
482/**
483 * The reminder to report, the first time a turn reaches `NUDGE_AFTER_TOOLS` calls with no report, task list or plan;
484 * or that a report may be out of date (`staleOf`). Marked in the same update that reads it, so calls that end together remind once.
485 */
486async function nudgeOf($: Dollar): Promise<string | null> {
487  if (!config.eta) return null
488  const l = await read($, live)
489  const stale = await staleOf($, l?.steps ?? 0)
490  if (stale !== null) return stale
491  const calls = l?.toolCalls ?? 0
492  if (calls < NUDGE_AFTER_TOOLS) return null
493  if ((await readSteps($)).list.length > 0) return null
494  let isDue = false
495  await update($, etaTurn, eta => {
496    if (eta === null || eta.nudged === true || eta.work !== null) return eta
497    isDue = true
498    return { ...eta, nudged: true }
499  })
500  return isDue ? nudgeLine(calls) : null
501}
502
503/**
504 * The reminder that a report may be out of date: `REMIND_AFTER_ROUNDS` rounds after it for the top item's size (an unsized or `run` one as `m`),
505 * with items still listed, once a report. Claude often works through the items and forgets to say so, and the band then shows the first one
506 * in progress throughout; by the time it says so, several have finished, and a `done` for several at once times none of them.
507 */
508async function staleOf($: Dollar, rounds: number): Promise<string | null> {
509  let line: string | null = null
510  await update($, etaTurn, eta => {
511    const top = eta?.work?.items[0]
512    if (eta === null || eta.work === null || top === undefined) return eta
513    const since = rounds - eta.lastReportRound
514    if (since < REMIND_AFTER_ROUNDS[top.size ?? 'm'] || eta.remindedRound === eta.lastReportRound) return eta
515    line = staleLine(since, top.do, eta.work.items.length - 1)
516    return { ...eta, remindedRound: eta.lastReportRound }
517  })
518  return line
519}
520
521/** A change to a task list or plan file is a report too, for the stale rule. */
522async function markReport($: Dollar, agentId: string | undefined, now: number) {
523  if (!config.eta) return
524  if (agentId !== undefined) {
525    await updateAgent($, agentId, now, run => (run.eta === undefined ? run : { ...run, eta: { ...run.eta, lastReportRound: run.steps } }))
526  } else {
527    const rounds = (await read($, live))?.steps ?? 0
528    await update($, etaTurn, eta => (eta === null ? eta : { ...eta, lastReportRound: rounds }))
529  }
530  await refreshEta($, now)
531}
532
533/** Runs a change to the plan file, counted as a report only when the plan came out different (reading a README is no report). */
534async function reportsPlanChange($: Dollar, now: number, change: () => Promise<unknown>) {
535  if (!config.eta) {
536    await change()
537    return
538  }
539  const before = JSON.stringify(await read($, planFile))
540  await change()
541  if (JSON.stringify(await read($, planFile)) !== before) await markReport($, undefined, now)
542}
543
544export function shouldShow(l: Live, now: number, planSize: number): boolean {
545  const elapsed = now - l.startedAt
546  if (elapsed >= SHOW_ALWAYS_AFTER_MS) return true
547  if (planSize >= 2 && elapsed >= SHOW_WITH_PLAN_AFTER_MS) return true
548  return elapsed >= SHOW_AFTER_MS && l.toolCalls + l.subagentToolCalls >= SHOW_AFTER_TOOLS
549}
550
551// A frame that did not land (the band collapsed or redrawing) is simply skipped.
552const skipFrame = () => {}
553
554function paint($: Dollar) {
555  const t = Date.now()
556  if (scene.isFinishing) {
557    // A timed ease-out that lands exactly on the target, then one redraw so the
558    // band's own tree (what a collapse and reopen shows) holds the settled bar.
559    scene.finishFrames += 1
560    const k = Math.min(1, (scene.finishFrames * FRAME_MS) / FINISH_MS)
561    const to = scene.target ?? scene.finishFrom
562    scene.shown = scene.finishFrom + (to - scene.finishFrom) * (1 - (1 - k) ** 3)
563    if (k >= 1) return settle($)
564  } else if (scene.target !== null) {
565    scene.shown += (scene.target - scene.shown) * 0.12
566  }
567  if (scene.requestId === null || scene.barWidth <= 0) return
568  const progress = scene.target === null ? null : scene.shown
569  const label = scene.showPct ? pctLabel(scene.shown) : scene.label
570  const labelColor = scene.showPct ? scene.palette.base : scene.labelColor
571  const cells = barCells(scene.barWidth, progress, t, scene.palette, { shimmer: true, label, labelColor })
572  $.ui.blit({ requestId: scene.requestId, key: BAR_KEY, cells }).catch(skipFrame)
573  if (!scene.isFinishing) {
574    $.ui.blit({ requestId: scene.requestId, key: SPINNER_KEY, cells: spinnerCells(t, scene.palette) }).catch(skipFrame)
575  }
576}
577
578function settle($: Dollar) {
579  stopFrames()
580  scene.isFinishing = false
581  scene.shown = scene.target ?? scene.shown
582  void update($, tick, n => n + 1)
583}
584
585function startFrames($: Dollar) {
586  if (frameTimer === null) frameTimer = $.clock.every(FRAME_MS, () => paint($))
587}
588
589function stopFrames() {
590  frameTimer?.cancel()
591  frameTimer = null
592}
593
594function startTicking($: Dollar) {
595  if (tickTimer !== null) return
596  tickTimer = $.clock.every(1000, async () => {
597    const now = await $.clock.now()
598    const plan = await readSteps($)
599    // A Progress list of two or more items counts as a plan for when the band appears.
600    const reported = (await read($, etaTurn))?.work?.items.length ?? 0
601    let becameLong = false
602    await update($, live, l => {
603      if (l === null || l.isLong || !shouldShow(l, now, Math.max(plan.list.length, reported))) return l
604      becameLong = true
605      return { ...l, isLong: true }
606    })
607    if (becameLong) startFrames($)
608    // A failure in the estimator must not skip the tick below, or the band's clock would freeze.
609    await refreshEta($, now).catch(() => {})
610    await update($, tick, n => n + 1)
611  })
612}
613
614function stopTicking() {
615  tickTimer?.cancel()
616  tickTimer = null
617}
618
619function setTaskStatus(list: readonly Task[], id: string, status: TaskStatus | 'deleted', subject?: string, activeForm?: string): Task[] {
620  if (status === 'deleted') return list.filter(t => t.id !== id)
621  return list.map(t => (t.id === id ? { ...t, status, subject: subject ?? t.subject, activeForm: activeForm ?? t.activeForm } : t))
622}
623
624/** A task list after one TodoWrite, TaskCreate or TaskUpdate call. */
625function applyPlanTool(list: Task[], e: { tool: string } & Record<string, unknown>, result: unknown): Task[] {
626  if (e.tool === 'TodoWrite' && Array.isArray(e.todos)) {
627    const todos = e.todos as { content: string; status: TaskStatus; activeForm?: string }[]
628    return todos.map((t, i) => ({ id: `todo-${i}`, subject: t.content, activeForm: t.activeForm, status: t.status }))
629  } else if (e.tool === 'TaskCreate') {
630    const id = (result as { task?: { id?: string } } | undefined)?.task?.id
631    if (typeof id !== 'string') return list
632    const task: Task = {
633      id,
634      subject: String(e.subject ?? 'Task'),
635      activeForm: typeof e.activeForm === 'string' ? e.activeForm : undefined,
636      status: 'pending',
637    }
638    return [...list.filter(t => t.id !== id), task]
639  } else if (e.tool === 'TaskUpdate' && typeof e.taskId === 'string') {
640    const status = (e.status as TaskStatus | 'deleted' | undefined) ?? undefined
641    const subject = typeof e.subject === 'string' ? e.subject : undefined
642    const activeForm = typeof e.activeForm === 'string' ? e.activeForm : undefined
643    const current = list.find(t => t.id === e.taskId)
644    if (current === undefined) return list
645    return setTaskStatus(list, e.taskId, status ?? current.status, subject, activeForm)
646  }
647  return list
648}
649
650/** One count under the bar, drawn with its kind's icon; pressed, it opens that kind's details. */
651type Stat = { kind: StatKind; text: string; color?: Color; lines?: { added: number; removed: number } }
652
653const stat = (kind: StatKind, text: string, color?: Color): Stat => (color === undefined ? { kind, text } : { kind, text, color })
654
655/** Files changed, with the lines added and removed where every write could be measured. */
656export function filesStat(detail: Detail, count = detail.files.length): Stat {
657  // A shell command that changed files it did not name: the count is a floor, and its lines are not the turn's.
658  const isShell = (detail.shellEdits?.length ?? 0) > 0
659  if (isShell) return stat('files', count === 0 ? 'files changed by shell' : `${plural(count, 'file')} changed (+ shell edits)`)
660  const measured = detail.files.length > 0 && detail.files.every(f => f.added !== null && f.removed !== null)
661  if (!measured) return stat('files', `${plural(count, 'file')} changed`)
662  const lines = detail.files.reduce((sum, f) => ({ added: sum.added + (f.added ?? 0), removed: sum.removed + (f.removed ?? 0) }), { added: 0, removed: 0 })
663  return { kind: 'files', text: plural(count, 'file'), lines }
664}
665
666type StepRows = 'auto' | 'always' | 'never'
667
668/** Whether the band lists the steps: in `auto`, only a plan file's, since Claude Code draws its own task list. */
669export function showsStepRows(setting: StepRows, fromPlanFile: boolean): boolean {
670  return setting === 'always' || (setting === 'auto' && fromPlanFile)
671}
672
673export const register: Register = (on, options) => {
674  const stepRows: StepRows = options.stepRows === 'always' || options.stepRows === 'never' ? options.stepRows : 'auto'
675  config.eta = options.eta !== 'off'
676  const keepsSpinner = options.spinner === 'keep'
677  // A fresh activation reads the history again, at the session's start or its first turn.
678  project = null
679  history = seeded()
680
681  on('session.start', async ($, e, next) => {
682    const started = await next(e)
683    // The tool the countdown's reports come through; a reload registers it again, replacing it.
684    if (config.eta) await $.tool.register(PROGRESS_SPEC).catch(() => {})
685    // The history is read afresh whenever a session starts or the mod reloads: another session may have added to it.
686    if (config.eta) {
687      project = null
688      await ensureHistory($)
689    }
690    // A reload mid-turn: the state survived, the timers did not.
691    const current = await read($, live)
692    if (current !== null || (await read($, agents)).some(isRunning)) startTicking($)
693    if (current?.isLong) startFrames($)
694    return started
695  })
696
697  on('prompt.compose', async ($, e, next) => {
698    const composed = await next(e)
699    const lines = [
700      { id: 'session-progress:task-list', text: taskListLine(e.tools) },
701      { id: 'session-progress:eta', text: config.eta ? etaLine(e.tools) : null },
702    ].filter((line): line is { id: string; text: string } => line.text !== null)
703    if (lines.length === 0) return composed
704    return { ...composed, sections: [...composed.sections, ...lines.map(line => ({ ...line, scope: 'session' as const }))] }
705  }).catch(($, e, next) => next(e))
706
707  // The mod's own tool runs without asking: it only feeds the band. The matcher spells the name out so the host's
708  // scan can read it, and the check inside keeps every other tool's decision the engine's.
709  on('tool.check', { tool: 'mcp__session-progress__progress' }, async ($, e, next) =>
710    e.tool === PROGRESS_TOOL ? { decision: 'allow' as const } : next(e),
711  ).catch(($, e, next) => next(e))
712
713  // Claude's reports are answered here and never passed on: no other hook serves the mod's own tool.
714  on('tool.call', { tool: 'mcp__session-progress__progress' }, async ($, e, next) => {
715    if (e.tool !== PROGRESS_TOOL) return next(e)
716    if (config.eta) await takeReport($, e.agentId, e as unknown as Record<string, unknown>)
717    return { result: 'ok' }
718  }).catch(() => ({ result: 'ok' }))
719
720  // A report is for the band, not the transcript: its rows draw nothing.
721  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
722    if (e.props.tool !== PROGRESS_TOOL) return next(e)
723    const { Box } = $.ui.resolve(e)
724    return <Box />
725  }).catch(($, e, next) => next(e))
726  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
727    if (e.props.tool !== PROGRESS_TOOL) return next(e)
728    const { Box } = $.ui.resolve(e)
729    return <Box />
730  }).catch(($, e, next) => next(e))
731
732  // While the band shows, the engine's spinner says nothing it does not (the clock, the tokens), so it gives way; it stays when it
733  // names a state (`message`), on a surface with no band, and for a subagent, which the hook is not told where it is drawn.
734  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
735    if (keepsSpinner || (e.surface !== 'terminal' && e.surface !== 'desktop') || e.props.message !== null) return next(e)
736    if (!(await read($, live))?.isLong) return next(e)
737    if ((await read($, agents)).some(run => run.id === e.requestId)) return next(e)
738    const { Box } = $.ui.resolve(e)
739    return <Box />
740  }).catch(($, e, next) => next(e))
741
742  on('turn.start', async ($, e, next) => {
743    const now = await $.clock.now()
744    await update($, summary, () => null)
745    // A plan that finished last turn starts this one clean; an unfinished one carries on.
746    await update($, tasks, list => (list.length > 0 && list.every(t => t.status === 'completed') ? [] : list))
747    await update($, planFile, plan => (plan !== null && stepsOf([], plan).progress === 1 ? null : plan))
748    await update($, live, () => freshLive(e.turnId, now))
749    await ensureHistory($)
750    // A Progress list belongs to its turn: unlike a plan, it does not carry over.
751    await update($, etaTurn, () => (config.eta ? freshEta(now) : null))
752    stopFrames()
753    scene.isFinishing = false
754    scene.palette = ACCENT
755    scene.shown = 0
756    startTicking($)
757    return next(e)
758  })
759
760  on('turn.step', async function* ($, e, next) {
761    const startedAt = await $.clock.now()
762    const result = yield* next(e)
763    const usage = result.usage
764    const stepIn = usage ? usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens : 0
765    const stepOut = usage?.output_tokens ?? 0
766    const now = await $.clock.now()
767    const step = {
768      index: e.index,
769      startedAt,
770      durationMs: now - startedAt,
771      tools: result.toolUses.filter(use => use.name !== PROGRESS_TOOL).map(use => shortToolName(use.name)),
772      tokensIn: stepIn,
773      tokensOut: stepOut,
774      stopReason: result.stopReason,
775    }
776    if (e.agentId !== undefined) {
777      await updateAgent($, e.agentId, now, run => ({
778        ...run,
779        steps: run.steps + 1,
780        tokensIn: run.tokensIn + stepIn,
781        tokensOut: run.tokensOut + stepOut,
782        detail: withStep(detailOf(run), step),
783      }))
784    }
785    await update($, live, l => {
786      if (l === null) return l
787      return {
788        ...l,
789        steps: e.agentId === undefined ? l.steps + 1 : l.steps,
790        tokensIn: l.tokensIn + stepIn,
791        tokensCached: l.tokensCached + (usage?.cache_read_input_tokens ?? 0),
792        tokensCacheWrite: (l.tokensCacheWrite ?? 0) + (usage?.cache_creation_input_tokens ?? 0),
793        tokensOut: l.tokensOut + stepOut,
794        cost: (l.cost ?? 0) + stepCost(usage?.model ?? e.model, usage),
795        model: e.agentId === undefined ? (usage?.model ?? e.model) : l.model,
796        detail: e.agentId === undefined ? withStep(detailOf(l), step) : l.detail,
797      }
798    })
799    return result
800  })
801
802  on('tool.call', async ($, e, next) => {
803    // The mod's own tool is answered by its own hook, and counts toward nothing.
804    if (e.tool === PROGRESS_TOOL) return next(e)
805    const agentId = e.agentId
806    const isSub = agentId !== undefined
807    // A background subagent goes on after the main turn ends: its calls still count toward its own run.
808    const isLive = (await read($, live)) !== null
809    if (!isLive && !isSub) return next(e)
810
811    const input = e as unknown as { tool: string } & Record<string, unknown>
812    const name = shortToolName(e.tool)
813    const label = activityLabel(e.tool, input)
814    const isAgent = e.tool === 'Agent' || String(e.tool) === 'Task'
815    const now = await $.clock.now()
816
817    const command = config.eta && e.tool === 'Bash' && typeof input.command === 'string' && input.command.trim() !== '' ? commandKey(input.command) : null
818    const call = {
819      id: e.tool_use_id,
820      tool: e.tool,
821      label,
822      agentId,
823      startedAt: now,
824      durationMs: null,
825      status: 'running' as const,
826      ...(command === null ? {} : { command }),
827    }
828
829    if (agentId !== undefined) {
830      await updateAgent($, agentId, now, run => ({
831        ...run,
832        finishedAt: null,
833        reason: null,
834        toolCalls: run.toolCalls + 1,
835        running: [...run.running, { id: e.tool_use_id, label }],
836        lastActivity: label,
837        detail: withCall(detailOf(run), { ...call, agentId: undefined }),
838      }))
839      startTicking($)
840    }
841
842    await update($, live, l =>
843      l === null
844        ? l
845        : {
846            ...l,
847            toolCalls: isSub ? l.toolCalls : l.toolCalls + 1,
848            subagentToolCalls: isSub ? l.subagentToolCalls + 1 : l.subagentToolCalls,
849            subagents: isAgent ? l.subagents + 1 : l.subagents,
850            byTool: isSub ? l.byTool : { ...l.byTool, [name]: (l.byTool[name] ?? 0) + 1 },
851            running: isSub ? l.running : [...l.running, { id: e.tool_use_id, label }],
852            lastActivity: isSub ? l.lastActivity : label,
853            detail: withCall(detailOf(l), call),
854          },
855    )
856
857    const ran = await next(e)
858    const failed = ran.deny !== undefined || ran.isError === true
859    const path = typeof input.file_path === 'string' ? input.file_path : typeof input.notebook_path === 'string' ? input.notebook_path : null
860    const ended = await $.clock.now()
861    const finished = { durationMs: ended - now, status: failed ? ('error' as const) : ('ok' as const), error: failed ? errorText(ran) : undefined }
862    const wrote = !failed && WRITE_TOOLS.has(e.tool) && path !== null
863    const lines = wrote ? editLines(e.tool, input, ran.result) : null
864    const isRead = !failed && e.tool === 'Read' && path !== null
865    // A command's writes count though it failed later on; one refused never ran.
866    const shell =
867      e.tool === 'Bash' && ran.deny === undefined && typeof input.command === 'string'
868        ? shellWrites(input.command, await $.session.cwd().catch(() => null))
869        : null
870    const started = (ran.result as { agentId?: unknown; agentType?: unknown } | undefined) ?? {}
871    const startedId = !failed && isAgent && typeof started.agentId === 'string' ? started.agentId : null
872    /** What this call adds to a turn's or a run's details once it has run. */
873    const ranInto = (d: Detail): Detail => {
874      let out = finishCall(d, e.tool_use_id, finished)
875      if (path !== null && wrote) out = withFile(out, path, lines)
876      if (path !== null && isRead) out = withRead(out, path)
877      if (shell !== null) {
878        for (const p of shell.paths) out = withFile(out, p, null)
879        out = withShellEdits(out, shell.unnamed)
880      }
881      if (startedId !== null) out = withAgent(out, startedId)
882      return out
883    }
884
885    await update($, live, l =>
886      l === null
887        ? l
888        : {
889            ...l,
890            errors: failed ? l.errors + 1 : l.errors,
891            running: l.running.filter(r => r.id !== e.tool_use_id),
892            detail: ranInto(detailOf(l)),
893          },
894    )
895    if (agentId !== undefined) {
896      await updateAgent($, agentId, now, run => ({
897        ...run,
898        errors: failed ? run.errors + 1 : run.errors,
899        running: run.running.filter(r => r.id !== e.tool_use_id),
900        detail: ranInto(detailOf(run)),
901        tasks: !failed && PLAN_TOOLS.has(e.tool) ? applyPlanTool(run.tasks, input, ran.result) : run.tasks,
902      }))
903    }
904    if (startedId !== null) {
905      await updateAgent($, startedId, now, run => ({
906        ...run,
907        description: typeof input.description === 'string' ? input.description : run.description,
908        type: typeof started.agentType === 'string' ? started.agentType : typeof input.subagent_type === 'string' ? input.subagent_type : run.type,
909        parentId: agentId ?? null,
910        dispatchedByMain: !isSub,
911      }))
912    }
913    // A foreground command's time is how long it runs; a background one returns at once, and a refused one never ran.
914    if (config.eta && command !== null && input.run_in_background !== true && ran.deny === undefined) {
915      const ms = ended - now
916      if (agentId !== undefined) await updateAgent($, agentId, ended, run => (run.eta === undefined ? run : { ...run, eta: learnCommand(run.eta, command, ms) }))
917      else await update($, etaTurn, eta => (eta === null ? eta : learnCommand(eta, command, ms)))
918    }
919    if (agentId !== undefined && !failed && PLAN_TOOLS.has(e.tool)) await markReport($, agentId, ended)
920    if (!isLive) return ran
921
922    if (!failed && tracksPlanTool(e.tool, isSub)) {
923      await update($, tasks, list => applyPlanTool(list, input, ran.result))
924      await markReport($, undefined, ended)
925    }
926    if (!failed && e.tool === 'Bash') {
927      const reported = bashReported(ran)
928      if (reported.length > 0) {
929        await reportsPlanChange($, ended, () => update($, planFile, plan => (plan === null ? plan : withCompleted(plan, reported))))
930      }
931    }
932    if (!failed && PLAN_FILE_TOOLS.has(e.tool) && path !== null && isMarkdown(path)) {
933      await reportsPlanChange($, ended, () => trackPlanFile($, path, e.tool === 'Write' && typeof input.content === 'string' ? input.content : null, isSub))
934    }
935    if (!isSub && ran.deny === undefined) {
936      const nudge = await nudgeOf($)
937      if (nudge !== null) return { ...ran, context: [...(ran.context ?? []), nudge] }
938    }
939
940    return ran
941  }).catch(($, e, next) => next(e)) // an observer: its failure never blocks the call
942
943  on('turn.complete', async ($, e, next) => {
944    if (e.agentId !== undefined) {
945      const now = await $.clock.now()
946      const endedRun = (await read($, agents)).find(run => run.id === e.agentId)
947      // An item still listed when the subagent answered was in progress until its closing round: learned with the rest.
948      const ended =
949        endedRun?.eta === undefined || e.reason !== 'answer'
950          ? endedRun?.eta
951          : learnOpenTop(endedRun.eta, closingAt(detailOf(endedRun)), paceOf(detailOf(endedRun), endedRun.eta.runs), history.sizes)
952      await updateAgent($, e.agentId, now, run => ({
953        ...run,
954        finishedAt: now,
955        durationMs: e.durationMs,
956        reason: e.reason,
957        running: [],
958        // Its open item, learned now, stays learned: a message sent to it later starts from there.
959        ...(ended === undefined ? {} : { eta: { ...ended, pending: emptyPending() } }),
960      }))
961      if (ended !== undefined) await flush($, ended.pending, e.reason === 'aborted', null)
962      if ((await read($, live)) === null && !(await read($, agents)).some(isRunning)) stopTicking()
963      return next(e)
964    }
965    await reconcileAgents($)
966    const waiting = e.reason === 'answer' ? waitingOn(await read($, agents)) : 0
967    if (waiting === 0) stopTicking()
968
969    const l = await read($, live)
970    const plan = await readSteps($)
971    const eta = config.eta ? await read($, etaTurn) : null
972    // The first estimate against what followed, for a turn that answered with nothing left running.
973    const first = e.reason === 'answer' && waiting === 0 ? (eta?.first ?? null) : null
974    const verdict =
975      first === null ? null : { atMs: first.atMs, estimatedMs: first.ms, lowMs: first.lowMs, highMs: first.highMs, tookMs: Math.max(0, e.durationMs - first.atMs) }
976    if (l !== null) {
977      const usage = e.usage
978      const tokensIn = Math.max(l.tokensIn, usage ? usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens : 0)
979      const tokensOut = Math.max(l.tokensOut, usage?.output_tokens ?? 0)
980      await update($, totals, (t): Totals => ({
981        turns: t.turns + 1,
982        longTurns: t.longTurns + (l.isLong ? 1 : 0),
983        totalMs: t.totalMs + e.durationMs,
984        toolCalls: t.toolCalls + l.toolCalls + l.subagentToolCalls,
985        tokensIn: t.tokensIn + tokensIn,
986        tokensOut: t.tokensOut + tokensOut,
987        cost: (t.cost ?? 0) + (l.cost ?? 0),
988      }))
989
990      if (l.isLong) {
991        const done: Summary = {
992          reason: e.reason,
993          durationMs: e.durationMs,
994          steps: l.steps,
995          toolCalls: l.toolCalls,
996          subagentToolCalls: l.subagentToolCalls,
997          subagents: l.subagents,
998          errors: l.errors,
999          topTools: Object.entries(l.byTool)
1000            .sort((a, b) => b[1] - a[1])
1001            .slice(0, 6),
1002          files: detailOf(l).files.length,
1003          tasksDone: plan.list.filter(t => t.status === 'completed').length,
1004          tasksTotal: plan.list.length,
1005          stepsUnit: plan.unit,
1006          stepsSource: plan.source,
1007          tokensIn,
1008          tokensCached: Math.max(l.tokensCached, usage?.cache_read_input_tokens ?? 0),
1009          tokensCacheWrite: Math.max(l.tokensCacheWrite ?? 0, usage?.cache_creation_input_tokens ?? 0),
1010          tokensOut,
1011          cost: l.cost ?? 0,
1012          model: usage?.model ?? l.model,
1013          detail: detailOf(l),
1014          ...(eta !== null && eta.fill !== null ? { fill: eta.fill } : {}),
1015          ...(verdict === null ? {} : { eta: verdict }),
1016        }
1017        await update($, summary, () => done)
1018        // Handed off to a background subagent, the work is not done: the bar keeps what the plan says.
1019        scene.palette = waiting > 0 ? ACCENT : e.reason === 'answer' ? DONE : e.reason === 'aborted' ? WARN : FAIL
1020        scene.target = e.reason === 'answer' && waiting === 0 ? 1 : (eta?.fill ?? plan.progress ?? scene.shown)
1021        scene.finishFrom = scene.shown
1022        scene.finishFrames = 0
1023        scene.isFinishing = true
1024        startFrames($)
1025      } else {
1026        stopFrames()
1027      }
1028    }
1029    if (eta !== null) {
1030      const row = first === null || verdict === null ? null : logRowOf(first, verdict.tookMs, await $.clock.now())
1031      // An item still listed when Claude answered was in progress until the closing round: learned with the rest.
1032      const ended = l !== null && e.reason === 'answer' && waiting === 0 ? learnOpenTop(eta, closingAt(detailOf(l)), paceOf(detailOf(l), eta.runs), history.sizes) : eta
1033      await flush($, ended.pending, e.reason === 'aborted', row)
1034      // Waiting on subagents, the countdown goes on with theirs; otherwise it is done with.
1035      await update($, etaTurn, x => (x === null || waiting === 0 ? null : { ...x, pending: emptyPending() }))
1036    }
1037    await update($, live, () => null)
1038    return next(e)
1039  })
1040
1041  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1042    // The band is raised on the terminal and the desktop alone.
1043    if ((e.surface !== 'terminal' && e.surface !== 'desktop') || e.props.hasSurvey) return next(e)
1044
1045    await read($, tick) // redraw each second for the clock
1046    const { Box, Text, Button } = $.ui.resolve(e)
1047    const width = Math.max(20, e.props.bodyColumns)
1048    const opened = await read($, openStat)
1049    const isAll = await read($, showAll)
1050    const isTerminal = e.surface === 'terminal'
1051    const marks = e.surface === 'terminal' ? terminalMarks($.ui.resolve(e), width) : desktopMarks($.ui.resolve(e))
1052
1053    /** Up to `room` rows of a step list, keeping the active step in view, then a `+N more` row; a row with a trail (its estimate) ends with it. */
1054    const stepRowsOf = (list: readonly Task[], room: number, trails: Readonly<Record<string, string>> = {}) => {
1055      const out: JSX.Element[] = []
1056      if (list.length === 0 || room <= 0) return out
1057      // Keep the active task in view: start from just before the first unfinished one.
1058      const firstOpen = Math.max(0, list.findIndex(task => task.status !== 'completed'))
1059      const start = Math.max(0, Math.min(firstOpen - 1, list.length - room))
1060      const visible = list.slice(start, start + room)
1061      for (const task of visible) {
1062        const isDone = task.status === 'completed'
1063        const isActive = task.status === 'in_progress'
1064        const row = (
1065          <Text key={`task-${task.id}`} wrap="truncate-end" dimColor={!isActive} strikethrough={false}>
1066            <Text color={isDone ? 'success' : isActive ? 'claude' : 'inactive'}>{isDone ? '  ✓ ' : isActive ? '  ◐ ' : '  ○ '}</Text>
1067            {isActive ? <Text bold>{task.subject}</Text> : task.subject}
1068          </Text>
1069        )
1070        const trail = trails[task.id]
1071        out.push(
1072          trail === undefined ? (
1073            row
1074          ) : (
1075            <Box key={`task-row-${task.id}`} flexDirection="row" justifyContent="space-between" width={marks.rowWidth}>
1076              <Box flexShrink={1}>{row}</Box>
1077              <Box flexShrink={0}>
1078                <Text dimColor>{` ${trail}`}</Text>
1079              </Box>
1080            </Box>
1081          ),
1082        )
1083      }
1084      const hidden = list.length - visible.length
1085      if (hidden > 0) out.push(<Text key="more" dimColor>{`    +${hidden} more`}</Text>)
1086      return out
1087    }
1088
1089    /** Each listed item's estimate, as its row's trail. */
1090    const trailsOf = (items: readonly { key: string; ms: number }[] | undefined) => Object.fromEntries((items ?? []).map(item => [item.key, etaValue(item.ms)]))
1091
1092    /** One stat as a Button that opens its details under the row, or closes them when they are open. */
1093    const statButton = (stat: Stat) => {
1094      const isOpen = opened === stat.kind
1095      const iconColor = stat.color ?? (isOpen ? 'claude' : undefined)
1096      const parts: (string | JSX.Element)[] = [
1097        iconColor === undefined ? <Text key="icon">{ICONS[stat.kind]}</Text> : <Text key="icon" color={iconColor}>{ICONS[stat.kind]}</Text>,
1098        ` ${stat.text}`,
1099      ]
1100      if (stat.lines !== undefined) {
1101        parts.push(' ', <Text key="added" color="success">{`+${stat.lines.added}`}</Text>, ' ', <Text key="removed" color="error">{`−${stat.lines.removed}`}</Text>)
1102      }
1103      if (isOpen) parts.push(' ▾')
1104      return (
1105        <Box key={`stat-box-${stat.kind}`} flexShrink={0}>
1106          <Button key={`stat-${stat.kind}`} plain dimColor={!isOpen} onPress={() => {
1107            void update($, showAll, () => false)
1108            void update($, openStat, now => (now === stat.kind ? null : stat.kind))
1109          }}>
1110            {parts}
1111          </Button>
1112        </Box>
1113      )
1114    }
1115
1116    /** A row of stats, wrapping onto a second line rather than cutting one off. */
1117    const statsRow = (key: string, items: readonly (Stat | false)[]) => (
1118      <Box key={key} flexDirection="row" flexWrap="wrap" columnGap={2} width={marks.rowWidth}>
1119        {items.filter((item): item is Stat => item !== false).map(statButton)}
1120      </Box>
1121    )
1122
1123    /** The open stat's details, when this band draws that stat. */
1124    const detailRowsOf = (items: readonly (Stat | false)[], src: DetailSource, room: number) => {
1125      if (opened === null || !items.some(item => item !== false && item.kind === opened)) return []
1126      // Pressing a `+N earlier` row lifts the cap: the list takes whatever room the band has.
1127      const lines = detailLines(opened, src, isAll ? room : Math.min(MAX_DETAIL_ROWS, room))
1128      const rows = lines.map(line => detailRow(line))
1129      if (isAll && lines.length > MAX_DETAIL_ROWS) {
1130        rows.push(
1131          <Button key="detail-fewer" plain dimColor onPress={() => void update($, showAll, () => false)}>
1132            {'  ▴ show fewer'}
1133          </Button>,
1134        )
1135      }
1136      return rows
1137    }
1138
1139    const detailRow = (line: DetailLine) => {
1140      const parts: (string | JSX.Element)[] = ['  ']
1141      if (line.glyph !== undefined) {
1142        parts.push(line.color === undefined ? `${line.glyph} ` : <Text key="glyph" color={line.color}>{`${line.glyph} `}</Text>)
1143      }
1144      parts.push(line.text)
1145      if (line.lines !== undefined) {
1146        parts.push('  ', <Text key="added" color="success">{`+${line.lines.added}`}</Text>, ' ', <Text key="removed" color="error">{`−${line.lines.removed}`}</Text>)
1147      }
1148      if (line.trail !== undefined) parts.push(<Text key="trail" dimColor>{`  ${line.trail}`}</Text>)
1149      if (line.isMore === true && !isAll) {
1150        return (
1151          <Button key={`detail-${line.key}`} plain dimColor onPress={() => void update($, showAll, () => true)}>
1152            {`  ${line.text} ▸ show all`}
1153          </Button>
1154        )
1155      }
1156      return line.isNote ? (
1157        <Text key={`detail-${line.key}`} dimColor wrap="truncate-end">
1158          {parts}
1159        </Text>
1160      ) : (
1161        <Text key={`detail-${line.key}`} wrap="truncate-end">
1162          {parts}
1163        </Text>
1164      )
1165    }
1166
1167    // A subagent's transcript in view: its own run, never the main conversation's.
1168    const viewed = e.props.view.agentId
1169    if (viewed !== undefined) {
1170      const run = (await read($, agents)).find(a => a.id === viewed)
1171      if (run === undefined) return next(e)
1172      const below = await next(e)
1173      const maxRows = Math.max(1, e.props.maxRows - (below == null ? 0 : 2))
1174      const now = await $.clock.now()
1175      const t = Date.now()
1176      const isDone = !isRunning(run)
1177      const runEta = config.eta ? run.eta : undefined
1178      const work = runEta?.work ?? null
1179      // Claude Code draws no list for a subagent: its band lists its tasks, or its reports when it keeps no tasks.
1180      const usesWork = work !== null && run.tasks.length === 0
1181      const list = usesWork ? workTasks(work) : run.tasks
1182      const progress = isDone && run.reason === 'answer' ? 1 : config.eta ? (runEta?.fill ?? null) : planProgress(list)
1183      const palette = !isDone ? ACCENT : run.reason === 'answer' ? DONE : run.reason === 'aborted' ? WARN : FAIL
1184      const color = !isDone ? 'claude' : run.reason === 'answer' ? 'success' : run.reason === 'aborted' ? 'warning' : 'error'
1185      const current = list.find(task => task.status === 'in_progress')
1186      const named = current === undefined ? undefined : usesWork ? capitalize(current.subject) : (current.activeForm ?? current.subject)
1187      const headline = isDone
1188        ? run.reason === 'answer'
1189          ? 'Subagent complete'
1190          : run.reason === 'aborted'
1191            ? 'Subagent interrupted'
1192            : 'Subagent ended with an error'
1193        : (named ?? run.running[run.running.length - 1]?.label ?? run.lastActivity ?? 'Starting')
1194      const elapsed = isDone ? (run.durationMs ?? (run.finishedAt ?? now) - run.startedAt) : now - run.startedAt
1195      const doneCount = list.filter(task => task.status === 'completed').length
1196      const barWidth = Math.max(12, width - BAR_SLACK)
1197      const isUp = !isDone && isGrowing(runEta?.upUntil, now)
1198      // Running with the countdown on, the label counts down; finished, or without it, it is the share done.
1199      // A fill paced by time is no share, so with the countdown on only an answer names one.
1200      const label =
hooks/details.ts 387 lines
1// What a band's stats open onto: the records a turn keeps of its calls, files, reads and steps, and the rows that list them.
2
3import type { Color } from 'claude-code'
4
5import type { AgentRun, CallRecord, Detail, FileChange, StatKind, StepRecord, Task } from '../types'
6import { basename, duration, plural, shortToolName, tokens } from './frames'
7
8const MAX_CALLS = 500
9const MAX_FILES = 500
10const MAX_READS = 500
11const MAX_STEPS = 300
12const MAX_SHELL_EDITS = 100
13
14/** The glyph each stat is drawn with, so its kind reads at a glance. */
15export const ICONS: Record<StatKind, string> = {
16  tools: '⚒',
17  subagents: '⑂',
18  files: '✎',
19  reads: '⌕',
20  steps: '↻',
21  tokens: '⇅',
22  errors: '⚠',
23  tasks: '☰',
24}
25
26export const emptyDetail = (): Detail => ({ calls: [], files: [], reads: [], stepLog: [], agentIds: [] })
27
28/** A turn's or a run's details; one kept from before they existed has none. */
29export const detailOf = (x: { detail?: Detail } | null | undefined): Detail => x?.detail ?? emptyDetail()
30
31export function withCall(d: Detail, call: CallRecord): Detail {
32  return { ...d, calls: [...d.calls, call].slice(-MAX_CALLS) }
33}
34
35export function finishCall(d: Detail, id: string, change: Pick<CallRecord, 'durationMs' | 'status' | 'error'>): Detail {
36  return { ...d, calls: d.calls.map(c => (c.id === id ? { ...c, ...change } : c)) }
37}
38
39/** Adds a write's lines to its file's count; a write that could not be measured leaves the file unmeasured. */
40export function withFile(d: Detail, path: string, lines: { added: number; removed: number } | null): Detail {
41  const add = (a: number | null, b: number | undefined) => (a === null || b === undefined ? null : a + b)
42  const known = d.files.find(f => f.path === path)
43  if (known === undefined) {
44    const file: FileChange = { path, added: lines?.added ?? null, removed: lines?.removed ?? null }
45    return { ...d, files: [...d.files, file].slice(-MAX_FILES) }
46  }
47  return {
48    ...d,
49    files: d.files.map(f => (f.path === path ? { path, added: add(f.added, lines?.added), removed: add(f.removed, lines?.removed) } : f)),
50  }
51}
52
53/** Shell commands that changed files they do not name. */
54export function withShellEdits(d: Detail, labels: readonly string[]): Detail {
55  return labels.length === 0 ? d : { ...d, shellEdits: [...(d.shellEdits ?? []), ...labels].slice(-MAX_SHELL_EDITS) }
56}
57
58/** Whether a turn changed files: by name, or by a shell command that did not name them. */
59export const changedFiles = (d: Detail): boolean => d.files.length > 0 || (d.shellEdits?.length ?? 0) > 0
60
61export function withRead(d: Detail, path: string): Detail {
62  return d.reads.includes(path) ? d : { ...d, reads: [...d.reads, path].slice(-MAX_READS) }
63}
64
65export function withStep(d: Detail, step: StepRecord): Detail {
66  return { ...d, stepLog: [...d.stepLog, step].slice(-MAX_STEPS) }
67}
68
69export function withAgent(d: Detail, id: string): Detail {
70  return d.agentIds.includes(id) ? d : { ...d, agentIds: [...d.agentIds, id] }
71}
72
73// Line counts of a write: from the tool's own patch where it gave one, else from what the call was asked to write.
74
75export function linesOf(text: string): string[] {
76  if (text === '') return []
77  const lines = text.split('\n')
78  if (lines[lines.length - 1] === '') lines.pop()
79  return lines
80}
81
82/** Lines added and removed between two texts, the unchanged head and tail aside. */
83export function lineDelta(before: string, after: string): { added: number; removed: number } {
84  const a = linesOf(before)
85  const b = linesOf(after)
86  let head = 0
87  while (head < a.length && head < b.length && a[head] === b[head]) head += 1
88  let tail = 0
89  while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1
90  return { added: b.length - head - tail, removed: a.length - head - tail }
91}
92
93type Hunk = { lines?: unknown }
94
95/** The `+` and `-` lines of a structured patch, or null for none. */
96export function patchCount(patch: unknown): { added: number; removed: number } | null {
97  if (!Array.isArray(patch) || patch.length === 0) return null
98  let added = 0
99  let removed = 0
100  for (const hunk of patch as Hunk[]) {
101    if (!Array.isArray(hunk.lines)) continue
102    for (const line of hunk.lines) {
103      if (typeof line !== 'string') continue
104      if (line.startsWith('+')) added += 1
105      else if (line.startsWith('-')) removed += 1
106    }
107  }
108  return { added, removed }
109}
110
111/** What one successful write changed, in lines; null when it cannot be told. */
112export function editLines(tool: string, input: Record<string, unknown>, result: unknown): { added: number; removed: number } | null {
113  const r = (typeof result === 'object' && result !== null ? result : {}) as {
114    structuredPatch?: unknown
115    type?: unknown
116    originalFile?: unknown
117  }
118  const str = (v: unknown) => (typeof v === 'string' ? v : '')
119  if (tool === 'Write') {
120    const content = str(input.content)
121    if (r.type === 'create') return { added: linesOf(content).length, removed: 0 }
122    const patched = patchCount(r.structuredPatch)
123    if (patched !== null) return patched
124    if (typeof r.originalFile === 'string') return lineDelta(r.originalFile, content)
125    // A tool that said nothing of the file it replaced: count it as written.
126    return r.type === undefined ? { added: linesOf(content).length, removed: 0 } : null
127  }
128  if (tool === 'Edit' || tool === 'MultiEdit') {
129    const patched = patchCount(r.structuredPatch)
130    if (patched !== null) return patched
131    const edits = Array.isArray(input.edits) ? (input.edits as Record<string, unknown>[]) : [input]
132    return edits.reduce<{ added: number; removed: number }>(
133      (sum, edit) => {
134        const one = lineDelta(str(edit.old_string), str(edit.new_string))
135        return { added: sum.added + one.added, removed: sum.removed + one.removed }
136      },
137      { added: 0, removed: 0 },
138    )
139  }
140  return null
141}
142
143/** The first line of why a call failed. */
144export function errorText(ran: { deny?: unknown; result?: unknown; text?: unknown }): string | undefined {
145  const raw = typeof ran.deny === 'string' ? ran.deny : typeof ran.result === 'string' ? ran.result : typeof ran.text === 'string' ? ran.text : ''
146  const line = raw.replace(/<\/?tool_use_error>/g, '').trim().split('\n')[0] ?? ''
147  return line === '' ? undefined : line.length > 120 ? `${line.slice(0, 119)}…` : line
148}
149
150// The rows a stat opens onto.
151
152export function briefDuration(ms: number): string {
153  if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`
154  if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`
155  return duration(ms)
156}
157
158/** Each path's file name, with its folder where two share a name. */
159export function shortPaths(paths: readonly string[]): string[] {
160  const counts = new Map<string, number>()
161  for (const p of paths) counts.set(basename(p), (counts.get(basename(p)) ?? 0) + 1)
162  return paths.map(p => {
163    const name = basename(p)
164    if ((counts.get(name) ?? 0) < 2) return name
165    const parts = p.split('/').filter(Boolean)
166    return parts.slice(-2).join('/')
167  })
168}
169
170/** `Read ×3, Edit` for a list of tool names. */
171export function toolTally(names: readonly string[]): string {
172  const counts = new Map<string, number>()
173  for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1)
174  return [...counts]
175    .sort((a, b) => b[1] - a[1])
176    .map(([name, n]) => (n > 1 ? `${name} ×${n}` : name))
177    .join(', ')
178}
179
180export type DetailLine = {
181  key: string
182  /** A leading status mark, drawn in `color`. */
183  glyph?: string
184  color?: Color
185  text: string
186  /** Drawn dim after the text. */
187  trail?: string
188  /** A file's lines, drawn green and red. */
189  lines?: { added: number; removed: number }
190  /** A header or a `+N more` row, drawn dim. */
191  isNote?: boolean
192  /** The `+N earlier` / `+N more` row: pressed, it opens the whole list. */
193  isMore?: boolean
194}
195
196export type DetailSource = {
197  detail: Detail
198  agents: readonly AgentRun[]
199  tasks: readonly Task[]
200  tokensIn: number
201  tokensOut: number
202  tokensCached?: number
203  tokensCacheWrite?: number
204  model: string | null
205  now: number
206  /** Cells a row may take, for rows that pack names side by side. */
207  columns: number
208}
209
210const callMark = (c: CallRecord): Pick<DetailLine, 'glyph' | 'color'> =>
211  c.status === 'running' ? { glyph: '◐', color: 'claude' } : c.status === 'ok' ? { glyph: '✓', color: 'success' } : { glyph: '✗', color: 'error' }
212
213const runMark = (run: AgentRun): Pick<DetailLine, 'glyph' | 'color'> =>
214  run.finishedAt === null
215    ? { glyph: '◐', color: 'claude' }
216    : run.reason === 'answer'
217      ? { glyph: '✓', color: 'success' }
218      : run.reason === 'aborted'
219        ? { glyph: '■', color: 'warning' }
220        : { glyph: '✗', color: 'error' }
221
222/** The last `room` of `lines`, a `+N earlier` row first when some do not fit. */
223function latest(lines: DetailLine[], room: number, what = 'earlier'): DetailLine[] {
224  if (lines.length <= room) return lines
225  const keep = Math.max(1, room - 1)
226  return [{ key: 'more', text: `+${lines.length - keep} ${what}`, isNote: true, isMore: true }, ...lines.slice(-keep)]
227}
228
229/** The first `room` of `lines`, a `+N more` row last when some do not fit. */
230function first(lines: DetailLine[], room: number): DetailLine[] {
231  if (lines.length <= room) return lines
232  const keep = Math.max(1, room - 1)
233  return [...lines.slice(0, keep), { key: 'more', text: `+${lines.length - keep} more`, isNote: true, isMore: true }]
234}
235
236/** Names packed side by side into rows of `columns` cells. */
237function packed(names: readonly string[], columns: number, room: number): DetailLine[] {
238  const rows: string[] = []
239  for (const name of names) {
240    const last = rows[rows.length - 1]
241    if (last !== undefined && last.length + 3 + name.length <= columns) rows[rows.length - 1] = `${last}   ${name}`
242    else rows.push(name)
243  }
244  return first(
245    rows.map((text, i) => ({ key: `row-${i}`, text })),
246    room,
247  )
248}
249
250/** The rows `kind`'s stat opens onto, at most `room` of them. */
251export function detailLines(kind: StatKind, src: DetailSource, room: number): DetailLine[] {
252  if (room <= 0) return []
253  const d = src.detail
254  switch (kind) {
255    case 'tools': {
256      const calls = d.calls.filter(c => c.agentId === undefined)
257      if (calls.length === 0) return [{ key: 'none', text: 'No tool calls yet', isNote: true }]
258      const header: DetailLine = { key: 'tally', text: toolTally(calls.map(c => shortToolName(c.tool))), isNote: true }
259      const rows = calls.map(
260        (c): DetailLine => ({
261          key: c.id,
262          ...callMark(c),
263          text: c.label,
264          trail: c.durationMs === null ? briefDuration(src.now - c.startedAt) : c.error !== undefined ? `${briefDuration(c.durationMs)} · ${c.error}` : briefDuration(c.durationMs),
265        }),
266      )
267      return [header, ...latest(rows, room - 1)].slice(0, room)
268    }
269    case 'subagents': {
270      const runs = d.agentIds.map(id => src.agents.find(run => run.id === id)).filter((run): run is AgentRun => run !== undefined)
271      if (runs.length === 0) return [{ key: 'none', text: 'No subagents yet', isNote: true }]
272      const rows = runs.map((run): DetailLine => {
273        const elapsed = run.finishedAt === null ? src.now - run.startedAt : (run.durationMs ?? run.finishedAt - run.startedAt)
274        const what = run.finishedAt === null && run.lastActivity !== null ? ` · ${run.lastActivity}` : ''
275        return {
276          key: run.id,
277          ...runMark(run),
278          text: `${run.description ?? run.type ?? 'subagent'}${run.description !== null && run.type !== null ? ` (${run.type})` : ''}`,
279          trail: `${plural(run.toolCalls, 'call')} · ${tokens(run.tokensOut)}↓ · ${duration(elapsed)}${what}`,
280        }
281      })
282      return first(rows, room)
283    }
284    case 'files': {
285      const shell = d.shellEdits ?? []
286      const hint: DetailLine[] = shell.length === 0 ? [] : [{ key: 'shell', text: `+ shell changes it can't name: ${toolTally(shell)}`, isNote: true }]
287      if (d.files.length === 0) return hint.length > 0 ? hint : [{ key: 'none', text: 'No files changed yet', isNote: true }]
288      const names = shortPaths(d.files.map(f => f.path))
289      const width = Math.min(40, Math.max(...names.map(n => n.length)))
290      const rows = d.files.map(
291        (f, i): DetailLine => ({
292          key: f.path,
293          text: (names[i] ?? f.path).padEnd(width),
294          ...(f.added === null || f.removed === null ? { trail: 'changed' } : { lines: { added: f.added, removed: f.removed } }),
295        }),
296      )
297      return [...hint, ...first(rows, room - hint.length)].slice(0, room)
298    }
299    case 'reads': {
300      if (d.reads.length === 0) return [{ key: 'none', text: 'No files read yet', isNote: true }]
301      return packed(shortPaths(d.reads), Math.max(20, src.columns - 4), room)
302    }
303    case 'steps': {
304      const steps = d.stepLog
305      if (steps.length === 0) return [{ key: 'none', text: 'No model steps yet', isNote: true }]
306      const modelMs = steps.reduce((sum, s) => sum + s.durationMs, 0)
307      const toolMs = d.calls.filter(c => c.agentId === undefined).reduce((sum, c) => sum + (c.durationMs ?? 0), 0)
308      const header: DetailLine = { key: 'time', text: `model ${duration(modelMs)} · tools ${duration(toolMs)}`, isNote: true }
309      const rows = steps.map(
310        (s): DetailLine => ({
311          key: `step-${s.index}`,
312          glyph: `#${s.index + 1}`,
313          color: 'claude',
314          text:
315            s.tools.length > 0
316              ? toolTally(s.tools)
317              : s.stopReason === 'end_turn'
318                ? 'answered'
319                : s.stopReason === 'max_tokens'
320                  ? 'hit the output limit'
321                  : s.stopReason === null
322                    ? 'no response'
323                    : s.stopReason.replace(/_/g, ' '),
324          trail: `${tokens(s.tokensIn)}↑ ${tokens(s.tokensOut)}↓ · ${briefDuration(s.durationMs)}`,
325        }),
326      )
327      return [header, ...latest(rows, room - 1)].slice(0, room)
328    }
329    case 'tokens': {
330      const rows: DetailLine[] = []
331      const cached = src.tokensCached
332      if (cached !== undefined && src.tokensIn > 0) {
333        const write = src.tokensCacheWrite ?? 0
334        const fresh = Math.max(0, src.tokensIn - cached - write)
335        const pct = Math.round((cached / src.tokensIn) * 100)
336        rows.push({
337          key: 'in',
338          glyph: '↑',
339          color: 'claude',
340          text: `${tokens(src.tokensIn)} in`,
341          trail: `${tokens(fresh)} fresh · ${tokens(cached)} cache read (${pct}%)${write > 0 ? ` · ${tokens(write)} cache write` : ''}`,
342        })
343      } else {
344        rows.push({ key: 'in', glyph: '↑', color: 'claude', text: `${tokens(src.tokensIn)} in` })
345      }
346      const steps = d.stepLog.length
347      rows.push({
348        key: 'out',
349        glyph: '↓',
350        color: 'claude',
351        text: `${tokens(src.tokensOut)} out`,
352        trail: steps > 0 ? `${tokens(Math.round(src.tokensOut / steps))} per step` : undefined,
353      })
354      const last = d.stepLog[d.stepLog.length - 1]
355      if (last !== undefined) rows.push({ key: 'context', glyph: '◧', color: 'claude', text: `${tokens(last.tokensIn)} context`, trail: 'at the last step' })
356      if (src.model !== null) rows.push({ key: 'model', glyph: '◆', color: 'claude', text: src.model })
357      return rows.slice(0, room)
358    }
359    case 'errors': {
360      const failed = d.calls.filter(c => c.status === 'error')
361      if (failed.length === 0) return [{ key: 'none', text: 'No failed calls', isNote: true }]
362      const rows = failed.map(
363        (c): DetailLine => ({
364          key: c.id,
365          glyph: '✗',
366          color: 'error',
367          text: `${c.agentId !== undefined ? `${ICONS.subagents} ` : ''}${c.label}`,
368          trail: c.error,
369        }),
370      )
371      return latest(rows, room)
372    }
373    case 'tasks': {
374      if (src.tasks.length === 0) return [{ key: 'none', text: 'No steps', isNote: true }]
375      const rows = src.tasks.map(
376        (task): DetailLine => ({
377          key: task.id,
378          glyph: task.status === 'completed' ? '✓' : task.status === 'in_progress' ? '◐' : '○',
379          color: task.status === 'completed' ? 'success' : task.status === 'in_progress' ? 'claude' : 'inactive',
380          text: task.subject,
381        }),
382      )
383      return first(rows, room)
384    }
385  }
386}
387
hooks/frames.ts 385 lines
1// Pure drawing helpers: Raster cells (terminal) and SVG markup (desktop) for the bar and spinner, and text formatting.
2
3import type { PlanTask } from '../types'
4
5export type Palette = { base: number; glow: number; dim: number }
6
7export const ACCENT: Palette = { base: 0xd97757, glow: 0xffc9a8, dim: 0x8a4a35 }
8export const DONE: Palette = { base: 0x4eba65, glow: 0xb8f0c4, dim: 0x2f7a3f }
9export const WARN: Palette = { base: 0xd8a64a, glow: 0xffe2a6, dim: 0x8a6a2c }
10export const FAIL: Palette = { base: 0xd2555a, glow: 0xffb0b2, dim: 0x8a3236 }
11
12const TRACK = 0x5c5c5c
13const DEFAULT_BG = 0x01000000
14const FILLED = 0x2501 // ━
15const EMPTY = 0x2500 // ─
16const HALF = 0x2578 // ╸
17
18const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
19
20function lerp(a: number, b: number, t: number): number {
21  const k = Math.max(0, Math.min(1, t))
22  const ch = (shift: number) => {
23    const x = (a >> shift) & 0xff
24    const y = (b >> shift) & 0xff
25    return Math.round(x + (y - x) * k) << shift
26  }
27  return ch(16) | ch(8) | ch(0)
28}
29
30function encode(words: Uint32Array): string {
31  const bytes = new Uint8Array(words.buffer)
32  const withBase64 = bytes as Uint8Array & { toBase64?: () => string }
33  if (typeof withBase64.toBase64 === 'function') return withBase64.toBase64()
34  let s = ''
35  for (const b of bytes) s += String.fromCharCode(b)
36  return btoa(s)
37}
38
39export const MUTED = 0x9a9a9a
40
41export type BarOptions = {
42  /** The moving highlight along the filled part; off for a settled bar. */
43  shimmer?: boolean
44  /** Text drawn in the bar's own last cells (a percentage, a clock), so it can never wrap away from it. */
45  label?: string
46  labelColor?: number
47}
48
49export function pctLabel(progress: number): string {
50  return `${Math.round(Math.max(0, Math.min(1, progress)) * 100)}%`.padStart(4)
51}
52
53/**
54 * One row of bar cells, `width` wide including the label. `progress` in [0, 1],
55 * or null for an indeterminate comet sweeping the track. `t` is milliseconds,
56 * driving the shimmer.
57 */
58export function barCells(width: number, progress: number | null, t: number, palette: Palette, options: BarOptions = {}): string {
59  const { shimmer = true, label = '', labelColor = palette.base } = options
60  const w = Math.max(1, Math.min(512, Math.floor(width)))
61  const words = new Uint32Array(w * 3)
62  const put = (i: number, glyph: number, color: number) => {
63    words[i * 3] = glyph
64    words[i * 3 + 1] = color
65    words[i * 3 + 2] = DEFAULT_BG
66  }
67  const text = label.length > 0 && label.length + 2 <= w ? label : ''
68  const barW = text.length > 0 ? w - text.length - 1 : w
69  if (text.length > 0) {
70    put(barW, 0x20, labelColor)
71    for (let k = 0; k < text.length; k++) put(barW + 1 + k, text.charCodeAt(k), labelColor)
72  }
73
74  if (progress === null) {
75    const tail = Math.max(6, Math.round(barW / 5))
76    const period = 2200
77    const head = ((t % period) / period) * (barW + tail)
78    for (let i = 0; i < barW; i++) {
79      const d = head - i
80      if (d >= 0 && d < tail) {
81        const k = 1 - d / tail
82        put(i, FILLED, lerp(TRACK, d < 1 ? palette.glow : palette.base, k * k))
83      } else {
84        put(i, EMPTY, TRACK)
85      }
86    }
87    return encode(words)
88  }
89
90  const exact = Math.max(0, Math.min(1, progress)) * barW
91  const full = Math.floor(exact)
92  const shimmerAt = ((t % 2600) / 2600) * (full + 16) - 8
93  for (let i = 0; i < barW; i++) {
94    if (i < full) {
95      const gradient = lerp(palette.dim, palette.base, full <= 1 ? 1 : 0.35 + (0.65 * i) / (full - 1))
96      const glow = shimmer ? Math.exp(-((i - shimmerAt) ** 2) / 10) : 0
97      put(i, FILLED, lerp(gradient, palette.glow, glow * 0.85))
98    } else if (i === full && exact - full >= 0.5) {
99      put(i, HALF, palette.base)
100    } else {
101      put(i, EMPTY, TRACK)
102    }
103  }
104  return encode(words)
105}
106
107export function spinnerCells(t: number, palette: Palette): string {
108  const glyph = SPINNER.charCodeAt(Math.floor(t / 80) % SPINNER.length)
109  const pulse = (Math.sin(t / 400) + 1) / 2
110  return encode(Uint32Array.of(glyph, lerp(palette.base, palette.glow, pulse * 0.6), DEFAULT_BG))
111}
112
113export function glyphCells(char: string, color: number): string {
114  return encode(Uint32Array.of(char.charCodeAt(0), color, DEFAULT_BG))
115}
116
117// The desktop's bar and spinner: SVG markup the page draws as an image, or in a frame when it animates.
118// Nothing in it depends on the clock, so the band's once-a-second redraw leaves an animation running.
119
120export const hex = (color: number) => `#${(color & 0xffffff).toString(16).padStart(6, '0')}`
121
122const SVG_W = 1000
123const SVG_H = 6
124const SVG_TRACK = '<rect width="1000" height="6" rx="3" fill="#8c8c8c" fill-opacity="0.3"/>'
125
126/** The bar as SVG, stretched to its row: `progress` in [0, 1], or null for a comet sweeping the track. */
127export function barSvg(progress: number | null, palette: Palette, options: { shimmer?: boolean } = {}): { source: string; isAnimated: boolean } {
128  const open = `<svg xmlns="http://www.w3.org/2000/svg" width="${SVG_W}" height="${SVG_H}" viewBox="0 0 ${SVG_W} ${SVG_H}" preserveAspectRatio="none">`
129  if (progress === null) {
130    const tail = 200
131    const comet =
132      `<defs><linearGradient id="c"><stop offset="0" stop-color="${hex(palette.base)}" stop-opacity="0"/>` +
133      `<stop offset="0.85" stop-color="${hex(palette.base)}"/><stop offset="1" stop-color="${hex(palette.glow)}"/></linearGradient></defs>` +
134      `<rect x="${-tail}" width="${tail}" height="6" rx="3" fill="url(#c)">` +
135      `<animate attributeName="x" from="${-tail}" to="${SVG_W}" dur="2.2s" repeatCount="indefinite"/></rect>`
136    return { source: `${open}${SVG_TRACK}${comet}</svg>`, isAnimated: true }
137  }
138  const fill = Math.round(Math.max(0, Math.min(1, progress)) * SVG_W)
139  const bar =
140    `<defs><linearGradient id="f"><stop offset="0" stop-color="${hex(palette.dim)}"/><stop offset="1" stop-color="${hex(palette.base)}"/></linearGradient>` +
141    `<clipPath id="k"><rect width="${fill}" height="6" rx="3"/></clipPath></defs>` +
142    `<rect width="${fill}" height="6" rx="3" fill="url(#f)"/>`
143  const isAnimated = options.shimmer === true && fill > 0
144  const shimmer = isAnimated
145    ? `<defs><linearGradient id="s"><stop offset="0" stop-color="${hex(palette.glow)}" stop-opacity="0"/>` +
146      `<stop offset="0.5" stop-color="${hex(palette.glow)}" stop-opacity="0.85"/><stop offset="1" stop-color="${hex(palette.glow)}" stop-opacity="0"/></linearGradient></defs>` +
147      `<g clip-path="url(#k)"><rect x="-120" width="120" height="6" fill="url(#s)">` +
148      `<animate attributeName="x" from="-120" to="${fill}" dur="2.6s" repeatCount="indefinite"/></rect></g>`
149    : ''
150  return { source: `${open}${SVG_TRACK}${bar}${shimmer}</svg>`, isAnimated }
151}
152
153/** The desktop's live spinner: an arc turning on its own. */
154export function spinnerSvg(palette: Palette): string {
155  return (
156    '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12">' +
157    `<circle cx="6" cy="6" r="4.5" fill="none" stroke="${hex(palette.base)}" stroke-opacity="0.25" stroke-width="2"/>` +
158    `<path d="M6 1.5 A4.5 4.5 0 0 1 10.5 6" fill="none" stroke="${hex(palette.base)}" stroke-width="2" stroke-linecap="round">` +
159    '<animateTransform attributeName="transform" type="rotate" from="0 6 6" to="360 6 6" dur="0.9s" repeatCount="indefinite"/></path></svg>'
160  )
161}
162
163export function duration(ms: number): string {
164  const s = Math.max(0, Math.round(ms / 1000))
165  if (s < 60) return `${s}s`
166  const m = Math.floor(s / 60)
167  if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`
168  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
169}
170
171/** The countdown rounded to the unit its label shows: whole minutes from 2 minutes, 10 s steps under them, 0 under 10 s. */
172export function shownMs(ms: number): number {
173  if (ms >= 120_000) return Math.round(ms / 60_000) * 60_000
174  if (ms >= 10_000) return Math.round(ms / 10_000) * 10_000
175  return 0
176}
177
178/** The countdown's value as its label reads: `~4m`, `~1m 30s`, `~40s`, or `a few seconds`. */
179export function etaValue(ms: number): string {
180  const shown = shownMs(ms)
181  if (shown === 0) return 'a few seconds'
182  if (ms >= 120_000) return `~${shown / 60_000}m`
183  const m = Math.floor(shown / 60_000)
184  const s = (shown % 60_000) / 1000
185  if (m === 0) return `~${s}s`
186  return s === 0 ? `~${m}m` : `~${m}m ${s}s`
187}
188
189/** The range after a countdown of 2 minutes or more, ` (3–6m)`; null under 2 minutes or when its ends round to the same minute. */
190export function etaRange(est: { ms: number; lowMs: number; highMs: number }): string | null {
191  if (est.ms < 120_000) return null
192  const lo = Math.max(1, Math.round(est.lowMs / 60_000))
193  const hi = Math.round(est.highMs / 60_000)
194  return hi > lo ? ` (${lo}–${hi}m)` : null
195}
196
197/** The countdown's labels, longest first: with its range, without it, the value alone. */
198export function etaLabels(est: { ms: number; lowMs: number; highMs: number }): string[] {
199  const value = etaValue(est.ms)
200  const range = etaRange(est)
201  return range === null ? [`${value} left`, value] : [`${value} left${range}`, `${value} left`, value]
202}
203
204/** The cells a bar keeps for its track beside its label. */
205export const MIN_BAR_CELLS = 20
206
207/** The longest label that leaves the bar its track in `width` cells, or the shortest when none does. */
208export function fitLabel(labels: readonly string[], width: number): string {
209  return labels.find(label => width - label.length - 1 >= MIN_BAR_CELLS) ?? labels[labels.length - 1] ?? ''
210}
211
212/** Whether a countdown grew a moment ago, so its label shows `↑`. */
213export const isGrowing = (upUntil: number | null | undefined, now: number) => upUntil !== null && upUntil !== undefined && now < upUntil
214
215/** A countdown's label on a bar of `width` cells, `↑` after it while it has just grown: the fullest that fits on the terminal, the whole one on the desktop. */
216export function countdownLabel(est: { ms: number; lowMs: number; highMs: number } | null, isUp: boolean, isTerminal: boolean, width: number): string {
217  if (est === null) return ''
218  const labels = etaLabels(est).map(text => (isUp ? `${text} ↑` : text))
219  return isTerminal ? fitLabel(labels, width) : labels[0]!
220}
221
222/** The text with its first letter in capitals. */
223export const capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1)
224
225export function tokens(n: number): string {
226  if (n < 1000) return String(n)
227  if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
228  return `${(n / 1_000_000).toFixed(1)}M`
229}
230
231/** USD per million tokens: fresh input, output, cache read. Cache writes bill at 1.25x input. */
232const PRICES: [prefix: string, input: number, output: number, cacheRead: number][] = [
233  ['claude-fable-5', 10, 50, 0.25],
234  ['claude-mythos-5', 10, 50, 0.25],
235  ['claude-opus-5-5', 4, 20, 0.2],
236  ['claude-opus-5', 5, 25, 0.5],
237  ['claude-opus-4', 5, 25, 0.5],
238  ['claude-sonnet-5', 2, 10, 0.2],
239  ['claude-sonnet-4', 3, 15, 0.3],
240  ['claude-haiku-5', 0.1, 0.5, 0.01],
241  ['claude-haiku-4', 1, 5, 0.1],
242]
243
244export type StepUsage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
245
246/** What one model request costs, from list prices. 0 for a model the table does not know. */
247export function stepCost(model: string | null | undefined, usage: StepUsage | null | undefined): number {
248  if (!model || !usage) return 0
249  const price = PRICES.find(([prefix]) => model.startsWith(prefix))
250  if (!price) return 0
251  const [, input, output, cacheRead] = price
252  return (
253    (usage.input_tokens * input +
254      usage.cache_creation_input_tokens * input * 1.25 +
255      usage.cache_read_input_tokens * cacheRead +
256      usage.output_tokens * output) /
257    1_000_000
258  )
259}
260
261export function usd(n: number): string {
262  if (n < 0.005) return '<$0.01'
263  return `$${n < 10 ? n.toFixed(2) : n.toFixed(1)}`
264}
265
266export function plural(n: number, one: string, many = `${one}s`): string {
267  return `${n} ${n === 1 ? one : many}`
268}
269
270export function basename(path: string): string {
271  const parts = path.split('/')
272  return parts[parts.length - 1] || path
273}
274
275function firstLine(text: string, max = 60): string {
276  const line = (text.split('\n')[0] ?? '').trim()
277  return line.length > max ? `${line.slice(0, max - 1)}…` : line
278}
279
280/** A short "what is happening" label for a tool call. */
281export function activityLabel(tool: string, input: Record<string, unknown>): string {
282  const str = (k: string) => (typeof input[k] === 'string' ? (input[k] as string) : '')
283  switch (tool) {
284    case 'Bash':
285      return `$ ${firstLine(str('description') || str('command'))}`
286    case 'Read':
287      return `reading ${basename(str('file_path'))}`
288    case 'Edit':
289    case 'MultiEdit':
290      return `editing ${basename(str('file_path'))}`
291    case 'Write':
292      return `writing ${basename(str('file_path'))}`
293    case 'NotebookEdit':
294      return `editing ${basename(str('notebook_path'))}`
295    case 'Grep':
296      return `searching “${firstLine(str('pattern'), 40)}”`
297    case 'Glob':
298      return `finding ${firstLine(str('pattern'), 40)}`
299    case 'Agent':
300    case 'Task':
301      return `subagent: ${firstLine(str('description'), 50)}`
302    case 'WebFetch':
303      try {
304        return `fetching ${new URL(str('url')).host}`
305      } catch {
306        return 'fetching a page'
307      }
308    case 'WebSearch':
309      return `searching the web: ${firstLine(str('query'), 40)}`
310    case 'TodoWrite':
311    case 'TaskCreate':
312    case 'TaskUpdate':
313      return 'updating the plan'
314    default:
315      if (tool.startsWith('mcp__')) {
316        const [, server, name] = tool.split('__')
317        return `${server} · ${name}`
318      }
319      return tool
320  }
321}
322
323export function shortToolName(tool: string): string {
324  if (!tool.startsWith('mcp__')) return tool
325  const parts = tool.split('__')
326  return parts[parts.length - 1] || tool
327}
328
329const CHECKBOX = /^\s*(?:[-*+]|\d+[.)])\s+\[([ xX])\]\s+(.+?)\s*$/
330const TASK_HEADING = /^#{2,4}\s+Task\s+(\d+)\s*[:.)—–-]\s*(.+?)\s*#*\s*$/
331// What superpowers' task-done appends to its ledger, and prints prefixed with `ledger: `.
332const LEDGER_DONE = /^(?:ledger:\s*)?Task (\d+): complete\b/gm
333const LEDGER_PLAN = /^# SDD ledger — plan: (.+?)\s*$/m
334
335const plain = (text: string) => text.replace(/[*_`]/g, '')
336
337/** A Markdown plan, outside fenced code blocks: its checkboxes, and its `### Task N:` headings with the boxes beneath each. */
338export function parsePlan(text: string): { items: { text: string; done: boolean }[]; tasks: PlanTask[] } {
339  const items: { text: string; done: boolean }[] = []
340  const tasks: PlanTask[] = []
341  let fence: string | null = null
342  for (const line of text.split('\n')) {
343    const marker = /^\s*(```+|~~~+)/.exec(line)?.[1]
344    if (marker !== undefined) {
345      if (fence === null) fence = marker[0] ?? null
346      else if (marker[0] === fence) fence = null
347      continue
348    }
349    if (fence !== null) continue
350    const heading = TASK_HEADING.exec(line)
351    if (heading !== null) {
352      tasks.push({ n: Number(heading[1]), text: plain(heading[2] ?? ''), steps: 0, stepsDone: 0 })
353      continue
354    }
355    const m = CHECKBOX.exec(line)
356    if (m === null) continue
357    const done = m[1] !== ' '
358    items.push({ text: plain(m[2] ?? ''), done })
359    const task = tasks[tasks.length - 1]
360    if (task !== undefined) {
361      task.steps += 1
362      if (done) task.stepsDone += 1
363    }
364  }
365  return { items: items.slice(0, 300), tasks: tasks.slice(0, 100) }
366}
367
368/** The checkbox items of a Markdown text, outside fenced code blocks. */
369export function parseCheckboxes(text: string): { text: string; done: boolean }[] {
370  return parsePlan(text).items
371}
372
373/** The task numbers a superpowers ledger (or task-done's output) reports complete. */
374export function ledgerTasks(text: string): number[] {
375  return [...new Set([...text.matchAll(LEDGER_DONE)].map(m => Number(m[1])))]
376}
377
378/** The file name of the plan a ledger names in its first line, if it names one. */
379export function ledgerPlanName(text: string): string | null {
380  const path = LEDGER_PLAN.exec(text)?.[1]
381  return path === undefined ? null : path.split('/').pop() || path
382}
383
384export const isMarkdown = (path: string) => /\.(md|markdown|mdx)$/i.test(path)
385
hooks/eta.ts 344 lines
1// The countdown's arithmetic: from samples of how long items took, how long the work left will take, and how far the bar has come.
2
3import type { CallRecord, Detail, EtaPending, EtaTurn, SampleKind, Spread, StepRecord, Task, Work, WorkItem } from '../types'
4import { shownMs } from './frames'
5
6export type Sizes = Record<SampleKind, number[]>
7
8/** Each kind's samples before any are learned, in round-equivalents. */
9export const SEEDS: Sizes = {
10  s: [1, 1.5, 2, 3, 4],
11  m: [3, 4, 5, 7, 10],
12  l: [8, 10, 12, 18, 25],
13  task: [3, 4, 5, 7, 10],
14  planTask: [3, 4, 5, 7, 10],
15  planStep: [3, 4, 5, 7, 10],
16}
17
18/** How many round-equivalents of evidence the seeds weigh against this turn's own, in *c*. */
19export const PRIOR_WEIGHT = 10
20/** Rounds without a report after which an item running far past its range loses its estimate. */
21export const STALE_ROUNDS = 12
22/** How many times its range's top an item must have run for, as well, to count as far past it. */
23export const STALE_OVERRUN = 2
24/** Where the bar waits until the turn ends. */
25export const FILL_CAP = 0.97
26/** The most one tick moves the bar: a laptop waking from sleep does not leap it ahead. */
27export const MAX_TICK_MS = 5_000
28/** A command with fewer runs than this gets half to double its median as its range. */
29const FEW_RUNS = 5
30
31export const byNumber = (a: number, b: number) => a - b
32
33/** The q-quantile of sorted values, interpolated linearly between neighbours; NaN for none. */
34export function quantile(sorted: readonly number[], q: number): number {
35  if (sorted.length === 0) return Number.NaN
36  const at = (sorted.length - 1) * q
37  const lo = Math.floor(at)
38  const hi = Math.ceil(at)
39  return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (at - lo)
40}
41
42/** What one item's estimate rests on: its samples in milliseconds, sorted, and whether they are a command's few runs. */
43export type Basis = { samples: number[]; isFew: boolean }
44
45/** A sized item's or a task's basis: its kind's samples at this turn's pace, corrected by *c*. */
46export function sizedBasis(rounds: readonly number[], pace: number, c: number): Basis {
47  return { samples: rounds.map(r => r * pace * c).sort(byNumber), isFew: false }
48}
49
50/** A `run` item's basis: its command's times here, or a size `m` item's for a command never timed. */
51export function commandBasis(runs: readonly number[] | undefined, mRounds: readonly number[], pace: number, c: number): Basis {
52  if (runs === undefined || runs.length === 0) return sizedBasis(mRounds, pace, c)
53  return { samples: [...runs].sort(byNumber), isFew: runs.length < FEW_RUNS }
54}
55
56/** A whole item's median and range. */
57export function spreadOf({ samples, isFew }: Basis): Spread {
58  const ms = quantile(samples, 0.5)
59  if (isFew) return { ms, lowMs: ms / 2, highMs: ms * 2 }
60  return { ms, lowMs: quantile(samples, 0.2), highMs: quantile(samples, 0.8) }
61}
62
63/** What is left of an item in progress: its median less the time spent, and past it, how much longer the items that ran this long went on. */
64export function remainingOf(basis: Basis, spentMs: number, pace: number): Spread {
65  const spent = Math.max(0, spentMs)
66  const whole = spreadOf(basis)
67  if (spent < whole.ms) return { ms: whole.ms - spent, lowMs: Math.max(0, whole.lowMs - spent), highMs: whole.highMs - spent }
68  const longer = basis.samples.filter(x => x > spent)
69  if (longer.length === 0) {
70    const ms = Math.max(spent / 4, pace)
71    return { ms, lowMs: ms / 2, highMs: ms * 2 }
72  }
73  return { ms: quantile(longer, 0.5) - spent, lowMs: Math.max(0, quantile(longer, 0.2) - spent), highMs: quantile(longer, 0.8) - spent }
74}
75
76/** The work left: the items' times and one round for the closing answer; the range from each item's own, by root-sum-square. */
77export function totalOf(items: readonly Spread[], pace: number): Spread {
78  const ms = items.reduce((sum, s) => sum + s.ms, 0) + pace
79  const down = Math.sqrt(items.reduce((sum, s) => sum + (s.ms - s.lowMs) ** 2, 0))
80  const up = Math.sqrt(items.reduce((sum, s) => sum + (s.highMs - s.ms) ** 2, 0))
81  return { ms, lowMs: Math.max(pace, ms - down), highMs: ms + up }
82}
83
84/** A main turn's estimate while subagents it started run: the longest of its own and theirs, or none while one of them has none. */
85export function combine(own: Spread | null, agents: readonly (Spread | null)[]): Spread | null {
86  if (agents.some(a => a === null)) return null
87  const all = [own, ...agents].filter((s): s is Spread => s !== null)
88  if (all.length === 0) return null
89  return { ms: Math.max(...all.map(s => s.ms)), lowMs: Math.max(...all.map(s => s.lowMs)), highMs: Math.max(...all.map(s => s.highMs)) }
90}
91
92/** This turn's correction, *c*: its finished items' actual round-equivalents against their estimates, weighed against the seeds. */
93export const correction = (actual: number, estimated: number) => (actual + PRIOR_WEIGHT) / (estimated + PRIOR_WEIGHT)
94
95/** Whether an estimate is fit to show. */
96export const isUsable = (s: Spread) => [s.ms, s.lowMs, s.highMs].every(Number.isFinite) && s.ms > 0
97
98/** The bar at the first estimate: the share of the turn already done, were the estimate right. */
99export function startFill(elapsedMs: number, remainingMs: number): number {
100  const done = Math.max(0, elapsedMs)
101  return Math.min(FILL_CAP, done / (done + remainingMs))
102}
103
104/** The bar one tick on, at the speed that reaches the end when the countdown does; it holds without an estimate and never goes back. */
105export function advanceFill(fill: number, dtMs: number, remainingMs: number | null): number {
106  if (remainingMs === null || !(remainingMs > 0)) return fill
107  const dt = Math.max(0, Math.min(dtMs, MAX_TICK_MS))
108  return Math.max(fill, Math.min(FILL_CAP, fill + (1 - fill) * Math.min(1, dt / remainingMs)))
109}
110
111/** A command as the history keys it: trimmed, its spaces collapsed, a leading `cd <dir> &&` dropped, cut to 200 characters. */
112export function normalizeCommand(command: string): string {
113  return command
114    .trim()
115    .replace(/\s+/g, ' ')
116    .replace(/^cd (?:"[^"]*"|'[^']*'|\S+) && /, '')
117    .slice(0, 200)
118}
119
120/** A 53-bit hash of a text (cyrb53), as 14 hex digits. */
121function cyrb53(text: string): string {
122  let h1 = 0xdeadbeef
123  let h2 = 0x41c6ce57
124  for (let i = 0; i < text.length; i++) {
125    const ch = text.charCodeAt(i)
126    h1 = Math.imul(h1 ^ ch, 2654435761)
127    h2 = Math.imul(h2 ^ ch, 1597334677)
128  }
129  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
130  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
131  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0')
132}
133
134/** How the countdown keys a command — its run times, its rounds, a `run` item — by a hash of its normalized text, so the text is never stored. */
135export const commandKey = (command: string) => cyrb53(normalizeCommand(command))
136
137/** Each completed round's wall time (a model request and the tools it ran), leaving out rounds that ran a `run` item's command. */
138export function roundTimes(steps: readonly StepRecord[], calls: readonly CallRecord[], runs: ReadonlySet<string>): number[] {
139  const out: number[] = []
140  for (let i = 0; i + 1 < steps.length; i++) {
141    const from = steps[i]!.startedAt
142    const to = steps[i + 1]!.startedAt
143    if (from === undefined || to === undefined || to <= from) continue
144    const ranRun = calls.some(c => c.command !== undefined && runs.has(c.command) && c.startedAt >= from && c.startedAt < to)
145    if (!ranRun) out.push(to - from)
146  }
147  return out
148}
149
150/** A loop's pace: its median round, leaving out those that ran a `runs` command (by key); before any round has completed, its first request's own time. */
151export function paceOf(detail: Detail, runs: readonly string[]): number | null {
152  const times = roundTimes(detail.stepLog, detail.calls, new Set(runs)).sort(byNumber)
153  if (times.length > 0) return quantile(times, 0.5)
154  const first = detail.stepLog[0]
155  return first !== undefined && first.durationMs > 0 ? first.durationMs : null
156}
157
158/** Since when the top item's command has been running, when the top item is a `run` and its command is. */
159export function runningSince(detail: Detail, work: Work | null): number | null {
160  const run = work?.items[0]?.run
161  if (run === undefined) return null
162  const command = commandKey(run)
163  return [...detail.calls].reverse().find(c => c.status === 'running' && c.command === command)?.startedAt ?? null
164}
165
166/** A task's key for its timing: its id and its text, since a TodoWrite list numbers its entries by position. */
167export const taskKey = (task: Task) => `${task.id}:${task.subject}`
168
169/** Which kind of list an estimate's items come from: a task list, a plan's tasks, or a plan's steps. */
170export type TaskKind = 'task' | 'planTask' | 'planStep'
171/** Which report an estimate was worked out from: a Progress list, a task list, or a plan. */
172export type EtaSource = 'progress' | 'tasks' | 'plan'
173
174/** What a loop's estimate is worked out from. */
175export type EtaInput = {
176  now: number
177  pace: number | null
178  work: Work | null
179  /** Since when the top item's command has run, for a `run` item whose command is running. */
180  runningSince: number | null
181  tasks: { list: readonly Task[]; kind: TaskKind } | null
182  since: Readonly<Record<string, number>>
183  sizes: Sizes
184  commands: Readonly<Record<string, readonly number[]>>
185  c: number
186  roundsSinceReport: number
187}
188
189/**
190 * A loop's estimate, each item's own (the time left on the one in progress, the others' medians), what it rests on, the estimate before
191 * calibration, and how much of it is measured command time (`run` items whose command was timed here).
192 */
193export type EtaOutput = { estimate: Spread | null; items: { key: string; ms: number }[]; source: EtaSource | null; raw?: Spread | null; measuredMs?: number }
194
195const NONE: EtaOutput = { estimate: null, items: [], source: null }
196
197/** A loop's estimate: a Progress list's when it has one, else its task list's or plan's, else none. */
198export function estimate(x: EtaInput): EtaOutput {
199  if (x.pace === null || !(x.pace > 0)) return NONE
200  const pace = x.pace
201  /** `isMeasured`: a `run` item whose command has been timed here, so its time is that command's own. */
202  type Part = { key: string; basis: Basis; spentMs: number | null; isMeasured: boolean }
203  let parts: Part[]
204  let source: EtaSource
205  const work = x.work
206  if (work !== null) {
207    source = 'progress'
208    parts = work.items.map((item, i) => ({
209      key: `work-${i}`,
210      basis: item.run !== undefined ? commandBasis(x.commands[commandKey(item.run)], x.sizes.m, pace, x.c) : sizedBasis(x.sizes[item.size ?? 'm'], pace, x.c),
211      spentMs: i > 0 ? null : x.now - (item.run !== undefined && x.runningSince !== null ? x.runningSince : work.topSince),
212      isMeasured: item.run !== undefined && (x.commands[commandKey(item.run)]?.length ?? 0) > 0,
213    }))
214  } else if (x.tasks !== null && x.tasks.list.length > 0) {
215    source = x.tasks.kind === 'task' ? 'tasks' : 'plan'
216    const basis = sizedBasis(x.sizes[x.tasks.kind], pace, x.c)
217    parts = x.tasks.list
218      .filter(task => task.status !== 'completed')
219      .map(task => ({ key: task.id, basis, spentMs: task.status === 'in_progress' ? x.now - (x.since[taskKey(task)] ?? x.now) : null, isMeasured: false }))
220  } else {
221    return NONE
222  }
223  // Nothing left by its report, yet still at work rounds later: it no longer knows what is left.
224  if (parts.length === 0 && x.roundsSinceReport >= 2) return NONE
225  // A long tool call is one round however long it runs, so a Progress list with nothing left also expires by time.
226  if (parts.length === 0 && work !== null && x.now - work.topSince > 3 * pace) return NONE
227
228  const spreads: Spread[] = []
229  const items: EtaOutput['items'] = []
230  let measuredMs = 0
231  for (const part of parts) {
232    // Far past its range with no report for a good while: Claude may simply have stopped reporting.
233    if (part.spentMs !== null && part.spentMs > STALE_OVERRUN * spreadOf(part.basis).highMs && x.roundsSinceReport >= STALE_ROUNDS) return NONE
234    const spread = part.spentMs === null ? spreadOf(part.basis) : remainingOf(part.basis, part.spentMs, pace)
235    spreads.push(spread)
236    items.push({ key: part.key, ms: spread.ms })
237    if (part.isMeasured) measuredMs += spread.ms
238  }
239  const total = totalOf(spreads, pace)
240  return isUsable(total) ? { estimate: total, items, source, measuredMs } : NONE
241}
242
243/** A loop's samples before any are gathered. */
244export const emptyPending = (): EtaPending => ({ sizes: {}, commands: {} })
245
246/** A loop's countdown before anything is reported. */
247export function freshEta(startedAt: number): EtaTurn {
248  return {
249    startedAt,
250    work: null,
251    runs: [],
252    since: {},
253    counted: [],
254    last: null,
255    items: [],
256    first: null,
257    fill: null,
258    lastTickAt: startedAt,
259    lastReportRound: 0,
260    actual: 0,
261    estimated: 0,
262    shownMs: null,
263    upUntil: null,
264    pending: emptyPending(),
265  }
266}
267
268const median = (rounds: readonly number[]) => quantile([...rounds].sort(byNumber), 0.5)
269
270/** Adds one finished item's round-equivalents to its kind's samples, and to the sums *c* is made of. */
271function withFinished(eta: EtaTurn, kind: SampleKind, rounds: number, sizes: Sizes): EtaTurn {
272  if (!Number.isFinite(rounds) || !(rounds > 0)) return eta
273  return {
274    ...eta,
275    actual: eta.actual + rounds,
276    estimated: eta.estimated + median(sizes[kind]),
277    pending: { ...eta.pending, sizes: { ...eta.pending.sizes, [kind]: [...(eta.pending.sizes[kind] ?? []), rounds] } },
278  }
279}
280
281/** Learns a Progress item that finished on its own: a sized one's time goes to its size; a `run` item's is learned from its Bash call. */
282export function learnItem(eta: EtaTurn, finished: { item: WorkItem; since: number }, now: number, pace: number | null, sizes: Sizes): EtaTurn {
283  if (finished.item.run !== undefined || pace === null || !(pace > 0)) return eta
284  return withFinished(eta, finished.item.size ?? 'm', (now - finished.since) / pace, sizes)
285}
286
287/** When a loop's closing round began: its last request's start; null before any request, or one with no start. */
288export const closingAt = (detail: Detail): number | null => detail.stepLog[detail.stepLog.length - 1]?.startedAt ?? null
289
290/**
291 * At a loop's answer, the one item still listed: Claude was on it until the closing round began, so it is learned like one reported done.
292 * With more than one still listed there is no telling which took the time; a `run` item is learned from its Bash call.
293 */
294export function learnOpenTop(eta: EtaTurn, closing: number | null, pace: number | null, sizes: Sizes): EtaTurn {
295  const work = eta.work
296  if (work === null || work.items.length !== 1 || closing === null || !(closing > work.topSince)) return eta
297  const top = work.items[0]!
298  // Marked finished, so a subagent sent another message later never learns it again.
299  const learned = learnItem(eta, { item: top, since: work.topSince }, closing, pace, sizes)
300  return { ...learned, work: { items: [], finished: [...work.finished, top.do], topSince: closing } }
301}
302
303/** Notes when each task came into progress, and learns the ones that finished since, each once. */
304export function learnTasks(eta: EtaTurn, list: readonly Task[], kind: TaskKind, now: number, pace: number | null, sizes: Sizes): EtaTurn {
305  let out = eta
306  for (const task of list) {
307    const key = taskKey(task)
308    const since = out.since[key]
309    if (task.status === 'in_progress' && since === undefined) {
310      out = { ...out, since: { ...out.since, [key]: now } }
311    } else if (task.status === 'completed' && since !== undefined && !out.counted.includes(key)) {
312      out = { ...out, counted: [...out.counted, key] }
313      if (pace !== null && pace > 0) out = withFinished(out, kind, (now - since) / pace, sizes)
314    }
315  }
316  return out
317}
318
319/** Adds a Bash call's time to its command's runs (by its key), keeping the last 10. */
320export function learnCommand(eta: EtaTurn, command: string, ms: number): EtaTurn {
321  if (command === '' || !(ms > 0)) return eta
322  const runs = [...(eta.pending.commands[command] ?? []), ms].slice(-10)
323  return { ...eta, pending: { ...eta.pending, commands: { ...eta.pending.commands, [command]: runs } } }
324}
325
326/** How long the label's `↑` shows after the estimate grows. */
327export const UP_MS = 5_000
328
329/** A loop's countdown after one more look: the estimate kept, the first one noted, the bar moved on, and the `↑` set when it grew. */
330export function tickEta(eta: EtaTurn, out: EtaOutput, now: number): EtaTurn {
331  const last = out.estimate
332  const elapsed = now - eta.startedAt
333  const first =
334    eta.first ??
335    (last === null || out.source === null
336      ? null
337      : { atMs: Math.max(0, elapsed), ms: last.ms, lowMs: last.lowMs, highMs: last.highMs, source: out.source, ...(out.raw ? { raw: out.raw } : {}) })
338  const fill = last === null ? eta.fill : eta.fill === null ? startFill(elapsed, last.ms) : advanceFill(eta.fill, now - eta.lastTickAt, last.ms)
339  const shown = last === null ? null : shownMs(last.ms)
340  const grew = shown !== null && eta.shownMs !== null && shown > eta.shownMs
341  const lastRaw = out.raw === undefined ? last : out.raw
342  return { ...eta, last, lastRaw, items: out.items, first, fill, lastTickAt: now, shownMs: shown ?? eta.shownMs, upUntil: grew ? now + UP_MS : eta.upUntil }
343}
344
hooks/calibrate.ts 80 lines
1// The countdown checked against past turns: how far each turn's first estimate was from what it took, and the correction that follows.
2
3import type { Spread } from '../types'
4import { PRIOR_WEIGHT, byNumber, isUsable, quantile } from './eta'
5
6/** What past turns teach the countdown: how much longer they took than first estimated, how much wider their range had to be, and how many turns say so. */
7export type Calibration = { bias: number; widen: number; turns: number }
8
9/** The calibration while too few turns are on record: none. */
10export const NO_CALIBRATION: Calibration = { bias: 1, widen: 1, turns: 0 }
11
12/** The past turns a calibration rests on, at most. */
13export const CAL_ROWS = 50
14/** The fewest turns a calibration needs. */
15export const CAL_MIN_ROWS = 5
16/** How many turns' evidence no correction at all weighs against the log's. */
17export const CAL_WEIGHT = 10
18/** The share of turns a range should hold: what each item's 20th to 80th percentile stand for. */
19export const COVERAGE = 0.6
20/** The bounds each correction is held between. */
21const BIAS = { min: 0.5, max: 3 }
22const WIDEN = { min: 0.5, max: 3 }
23
24/** One past turn as the calibration reads it: its first estimate as shown and before calibration (absent on rows from before it), and what it took. */
25export type CalRow = { estimatedMs: number; lowMs: number; highMs: number; tookMs: number; raw?: Spread }
26
27type Measured = { raw: Spread; tookMs: number }
28
29const clamp = (x: number, bounds: { min: number; max: number }) => Math.min(bounds.max, Math.max(bounds.min, x))
30
31/** A turn's estimate before calibration and what it took; null for a turn that cannot be measured. A row from before calibration showed its estimate raw. */
32function measured(row: CalRow): Measured | null {
33  const raw: unknown = row.raw ?? { ms: row.estimatedMs, lowMs: row.lowMs, highMs: row.highMs }
34  if (typeof raw !== 'object' || raw === null) return null
35  const s = raw as Spread
36  if (!isUsable(s) || !(s.lowMs > 0 && s.lowMs <= s.ms && s.ms <= s.highMs)) return null
37  if (!(Number.isFinite(row.tookMs) && row.tookMs > 0)) return null
38  return { raw: s, tookMs: row.tookMs }
39}
40
41/**
42 * The correction the last `CAL_ROWS` turns call for: the median of what they took against their first estimate, and how many
43 * half-widths of its range a turn missed by, at `COVERAGE`. Each leans from none toward the log's as turns add up; none below `CAL_MIN_ROWS`.
44 */
45export function calibrationOf(rows: readonly CalRow[]): Calibration {
46  const turns = rows
47    .slice(-CAL_ROWS)
48    .map(measured)
49    .filter((m): m is Measured => m !== null)
50  if (turns.length < CAL_MIN_ROWS) return NO_CALIBRATION
51  const weight = turns.length / (turns.length + CAL_WEIGHT)
52  const ratio = quantile(turns.map(t => Math.log(t.tookMs / t.raw.ms)).sort(byNumber), 0.5)
53  const bias = clamp(Math.exp(weight * ratio), BIAS)
54  // How far each turn missed its estimate as now corrected, in half-widths of its range on the side it missed.
55  const misses = turns.flatMap(t => {
56    const off = Math.log(t.tookMs / (t.raw.ms * bias))
57    const half = off >= 0 ? Math.log(t.raw.highMs / t.raw.ms) : Math.log(t.raw.ms / t.raw.lowMs)
58    return half > 0 ? [Math.abs(off) / half] : []
59  })
60  const widen = misses.length < CAL_MIN_ROWS ? 1 : clamp(1 + weight * (quantile(misses.sort(byNumber), COVERAGE) - 1), WIDEN)
61  return { bias, widen, turns: turns.length }
62}
63
64/**
65 * A loop's whole estimate with the log's correction: its time scaled by the bias, all but `measuredMs` (commands timed here, whose time is
66 * their own), and its range widened or narrowed about it. Both give way to the turn's own evidence as its items finish (`evidence`, in
67 * round-equivalents, as *c* weighs it); the low end stays a round or more.
68 */
69export function calibrated(raw: Spread, cal: Calibration, evidence: number, pace: number, measuredMs = 0): Spread {
70  if (cal.bias === 1 && cal.widen === 1) return raw
71  const share = PRIOR_WEIGHT / (PRIOR_WEIGHT + Math.max(0, evidence))
72  const bias = cal.bias ** share
73  const widen = cal.widen ** share
74  const measured = Math.min(raw.ms, Math.max(0, measuredMs))
75  const ms = measured + (raw.ms - measured) * bias
76  const lowMs = raw.lowMs > 0 ? ms * (raw.lowMs / raw.ms) ** widen : 0
77  const highMs = ms * (raw.highMs / raw.ms) ** widen
78  return { ms, lowMs: Math.min(ms, Math.max(pace, lowMs)), highMs: Math.max(ms, highMs) }
79}
80
hooks/history.ts 177 lines
1// The countdown's memory across sessions: how long each size of item and each command took, in the mod's own store.
2
3import type { EtaPending, EtaTurn, SampleKind, Spread } from '../types'
4import { NO_CALIBRATION, calibrationOf, type Calibration } from './calibrate'
5import { SEEDS, type Sizes } from './eta'
6
7const KEY = { version: 'eta.version', sizes: 'eta.sizes', commands: 'eta.commands', log: 'eta.log' } as const
8const VERSION = 1
9
10/** How much the store keeps: samples per kind, runs per command, commands per project, projects, and log rows. */
11export type Bounds = { sizes: number; runs: number; commands: number; projects: number; log: number }
12export const BOUNDS: Bounds = { sizes: 50, runs: 10, commands: 100, projects: 50, log: 200 }
13
14/** One turn's first estimate against what followed; `raw` is that estimate before calibration, absent on rows from before it. */
15export type LogRow = { at: number; firstAtMs: number; estimatedMs: number; lowMs: number; highMs: number; tookMs: number; source: 'progress' | 'tasks' | 'plan'; raw?: Spread }
16
17/** What the estimator reads: every kind's samples, this project's command runs, and the correction past turns call for. */
18export type History = { sizes: Sizes; commands: Record<string, number[]>; calibration: Calibration }
19
20/** The part of `$.store` the history uses. */
21export type Store = { get: (key: string) => Promise<unknown>; set: (key: string, value: unknown) => Promise<void> }
22
23type Runs = { samples: number[]; lastUsed: number }
24type Commands = Record<string, Record<string, Runs>>
25
26const isTime = (x: unknown): x is number => typeof x === 'number' && Number.isFinite(x) && x > 0
27const isTimes = (v: unknown): v is number[] => Array.isArray(v) && v.length > 0 && v.every(isTime)
28const asRecord = (v: unknown): Record<string, unknown> => (typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {})
29
30/** The history before anything is learned. */
31export const seeded = (): History => ({ sizes: readSizes(undefined), commands: {}, calibration: NO_CALIBRATION })
32
33/** Every kind's stored samples; a kind missing or unreadable takes its seeds. */
34export function readSizes(stored: unknown): Sizes {
35  const s = asRecord(stored)
36  const out = {} as Sizes
37  for (const kind of Object.keys(SEEDS) as SampleKind[]) {
38    const v = s[kind]
39    out[kind] = isTimes(v) ? [...v] : [...SEEDS[kind]]
40  }
41  return out
42}
43
44/** The stored commands of every project, without the entries that cannot be read. */
45function readAll(stored: unknown): Commands {
46  const out: Commands = {}
47  for (const [project, commands] of Object.entries(asRecord(stored))) {
48    const kept: Record<string, Runs> = {}
49    for (const [command, runs] of Object.entries(asRecord(commands))) {
50      const r = asRecord(runs)
51      if (isTimes(r.samples) && typeof r.lastUsed === 'number') kept[command] = { samples: [...r.samples], lastUsed: r.lastUsed }
52    }
53    if (Object.keys(kept).length > 0) out[project] = kept
54  }
55  return out
56}
57
58/** One project's command runs. */
59export function readCommands(stored: unknown, project: string): Record<string, number[]> {
60  return Object.fromEntries(Object.entries(readAll(stored)[project] ?? {}).map(([command, runs]) => [command, runs.samples]))
61}
62
63/** The stored samples with a turn's added, each kind keeping its last `max`. */
64export function mergeSizes(stored: unknown, added: EtaPending['sizes'], max = BOUNDS.sizes): Sizes {
65  const out = readSizes(stored)
66  for (const kind of Object.keys(added) as SampleKind[]) out[kind] = [...out[kind], ...(added[kind] ?? []).filter(isTime)].slice(-max)
67  return out
68}
69
70const lastUsedOf = (commands: Record<string, Runs>) => Math.max(0, ...Object.values(commands).map(r => r.lastUsed))
71
72/** The stored commands with a turn's runs added under its project; past the bounds the least recently used commands and projects go. */
73export function mergeCommands(stored: unknown, project: string, added: EtaPending['commands'], now: number, bounds = BOUNDS): Commands {
74  const all = readAll(stored)
75  const mine = { ...(all[project] ?? {}) }
76  for (const [command, runs] of Object.entries(added)) {
77    const kept = runs.filter(isTime)
78    if (kept.length === 0) continue
79    mine[command] = { samples: [...(mine[command]?.samples ?? []), ...kept].slice(-bounds.runs), lastUsed: now }
80  }
81  const recent = Object.fromEntries(Object.entries(mine).sort((a, b) => b[1].lastUsed - a[1].lastUsed).slice(0, bounds.commands))
82  const projects = Object.entries({ ...all, [project]: recent })
83    .filter(([, commands]) => Object.keys(commands).length > 0)
84    .sort((a, b) => lastUsedOf(b[1]) - lastUsedOf(a[1]))
85  return Object.fromEntries(projects.slice(0, bounds.projects))
86}
87
88const isRow = (v: unknown): v is LogRow => {
89  const r = asRecord(v)
90  return ['at', 'firstAtMs', 'estimatedMs', 'lowMs', 'highMs', 'tookMs'].every(k => typeof r[k] === 'number') && typeof r.source === 'string'
91}
92
93/** The stored log's rows, without the ones that cannot be read. */
94export function readLog(stored: unknown): LogRow[] {
95  return Array.isArray(stored) ? stored.filter(isRow) : []
96}
97
98/** The stored log with one row added, keeping the last `max`. */
99export function appendLog(stored: unknown, row: LogRow, max = BOUNDS.log): LogRow[] {
100  return [...readLog(stored), row].slice(-max)
101}
102
103/** A turn's log row: its first estimate, as shown and before calibration, against the time it took from there. */
104export function logRowOf(first: NonNullable<EtaTurn['first']>, tookMs: number, at: number): LogRow {
105  return {
106    at,
107    firstAtMs: first.atMs,
108    estimatedMs: first.ms,
109    lowMs: first.lowMs,
110    highMs: first.highMs,
111    tookMs,
112    source: first.source,
113    ...(first.raw === undefined ? {} : { raw: first.raw }),
114  }
115}
116
117/** Whether a stored version is this one's, or none yet. */
118const isCurrent = (version: unknown) => version === undefined || version === VERSION
119
120/** One project's history as stored; the seeds when the store cannot be read or holds another version. */
121export async function loadHistory(store: Store, project: string): Promise<History> {
122  try {
123    if (!isCurrent(await store.get(KEY.version))) return seeded()
124    return {
125      sizes: readSizes(await store.get(KEY.sizes)),
126      commands: readCommands(await store.get(KEY.commands), project),
127      calibration: calibrationOf(readLog(await store.get(KEY.log))),
128    }
129  } catch {
130    return seeded()
131  }
132}
133
134const halved = (b: Bounds): Bounds => ({
135  sizes: Math.ceil(b.sizes / 2),
136  runs: Math.ceil(b.runs / 2),
137  commands: Math.ceil(b.commands / 2),
138  projects: Math.ceil(b.projects / 2),
139  log: Math.ceil(b.log / 2),
140})
141
142/**
143 * Writes a turn's samples and its log row, each pass merging from one read of the keys, so a retry never counts a sample twice.
144 * A failed write prunes to half the bounds and tries once more. Resolves the project's history as written, its calibration included, or null when nothing was.
145 */
146export async function flushHistory(store: Store, project: string, pending: EtaPending, now: number, row: LogRow | null): Promise<History | null> {
147  const hasSizes = Object.values(pending.sizes).some(list => (list?.length ?? 0) > 0)
148  const hasCommands = Object.values(pending.commands).some(list => list.length > 0)
149  if (!hasSizes && !hasCommands && row === null) return null
150  // One read before any write: a retry merges from it again, so a pass that failed halfway is never counted twice.
151  let stored: { sizes: unknown; commands: unknown; log: unknown }
152  try {
153    const version = await store.get(KEY.version)
154    // A newer release's data (a dev copy beside an installed one) is read by that release alone, and never written over.
155    if (typeof version === 'number' && version > VERSION) return null
156    const get = async (key: string) => (isCurrent(version) ? await store.get(key) : undefined)
157    stored = { sizes: await get(KEY.sizes), commands: await get(KEY.commands), log: await get(KEY.log) }
158  } catch {
159    return null
160  }
161  for (const bounds of [BOUNDS, halved(BOUNDS)]) {
162    try {
163      const sizes = mergeSizes(stored.sizes, pending.sizes, bounds.sizes)
164      const commands = mergeCommands(stored.commands, project, pending.commands, now, bounds)
165      const log = row === null ? readLog(stored.log) : appendLog(stored.log, row, bounds.log)
166      await store.set(KEY.version, VERSION)
167      await store.set(KEY.sizes, sizes)
168      await store.set(KEY.commands, commands)
169      if (row !== null) await store.set(KEY.log, log)
170      return { sizes, commands: readCommands(commands, project), calibration: calibrationOf(log) }
171    } catch {
172      // Over the store's 4 MiB, say: the second pass keeps half as much.
173    }
174  }
175  return null
176}
177
hooks/report.ts 139 lines
1// The `progress` tool Claude reports the work left with: its definition and the system-prompt line asking for it.
2
3import type { ToolSpec } from 'claude-code'
4
5import type { Task, Work, WorkItem } from '../types'
6
7/** The tool's short name, and the name the model calls it by. */
8export const PROGRESS_NAME = 'progress'
9export const PROGRESS_TOOL = 'mcp__session-progress__progress'
10
11const DESCRIPTION =
12  'Reports the work left in this turn, for the progress display only. Use it during work that will take more than a few steps ' +
13  'when you keep no task list: start in your first response that calls tools, with a rough guess if that is all you have, ' +
14  'and send it in the same response as your other tool calls, never on its own. ' +
15  'List the items in order, the one you are on first, each in a few words (5 at most). ' +
16  'Give each a size: s — a quick change or lookup, about 1–2 tool calls; m — a few files or a few rounds, 3–8; ' +
17  'l — a broad change or a debugging loop, 9 or more. When running a command is the item (a test suite, a build), ' +
18  'give `run` with the exact command instead of a size. Send `{done: 1}` with the first tool calls of the next item, one item at a time ' +
19  'and not the list again: a late `done`, or one for several items, loses their times. Send `left` only when items are added, dropped or changed. ' +
20  'Once the last item is done, just answer: the turn ending closes it. ' +
21  'Returns `ok`.'
22
23/** The tool as the mod registers it: in the prompt's tool list, not behind ToolSearch, since a report there would cost a round. */
24export const PROGRESS_SPEC: ToolSpec = {
25  name: PROGRESS_NAME,
26  description: DESCRIPTION,
27  inputSchema: {
28    type: 'object',
29    properties: {
30      left: {
31        type: 'array',
32        maxItems: 30,
33        items: {
34          type: 'object',
35          properties: {
36            // No descriptions here: the tool's description says what each field is, and they would cost every request.
37            do: { type: 'string' },
38            size: { type: 'string', enum: ['s', 'm', 'l'] },
39            run: { type: 'string' },
40          },
41          required: ['do'],
42        },
43      },
44      done: { type: 'integer', minimum: 1 },
45    },
46  },
47  isDeferred: false,
48}
49
50/**
51 * The system-prompt line asking Claude to report, when the tool is offered. It says only when to start, which Claude skipped
52 * without it; how to report is the tool's description, which every request carries already.
53 */
54export function etaLine(tools: readonly string[]): string | null {
55  if (!tools.includes(PROGRESS_TOOL)) return null
56  return (
57    `During work that will take more than a few steps and has no task list, report what is left with ${PROGRESS_TOOL} ` +
58    'in your first response that calls tools, before you know the details: a rough guess is fine, and exploring counts as an item. ' +
59    'Its description says how.'
60  )
61}
62
63/** The reminder a turn's call carries once the turn has run a few calls with nothing to count down. */
64export function nudgeLine(calls: number): string {
65  return (
66    `This turn has made ${calls} tool calls with no task list and no report, so the progress display has nothing to count down. ` +
67    `If more work is left, report it with ${PROGRESS_TOOL} in your next response, alongside your other tool calls. If you are about to answer, ignore this.`
68  )
69}
70
71/** The reminder a call carries once a report has stood unchanged for some rounds with items still listed. */
72export function staleLine(rounds: number, top: string, after: number): string {
73  const rest = after === 0 ? '' : after === 1 ? ', with 1 more item after it' : `, with ${after} more items after it`
74  return (
75    `Your last ${PROGRESS_TOOL} report was ${rounds} rounds ago, and the progress display still shows "${top}" in progress${rest}. ` +
76    'If it or later items are finished, send {done: 1} (or how many finished), or `left` with what is left now, in your next response alongside your other tool calls. ' +
77    'If it is still in progress, or you are about to answer, ignore this.'
78  )
79}
80
81/** One report: the whole list left, or how many items at its top are finished. */
82export type Report = { left: WorkItem[] } | { done: number }
83
84const MAX_ITEMS = 30
85const MAX_TEXT = 80
86const MAX_FINISHED = 50
87
88/** One item of `left`: an object with its text, or the text alone. */
89function itemOf(raw: unknown): WorkItem | null {
90  const r = (typeof raw === 'object' && raw !== null ? raw : typeof raw === 'string' ? { do: raw } : {}) as Record<string, unknown>
91  const text = typeof r.do === 'string' ? r.do.trim().slice(0, MAX_TEXT) : ''
92  if (text === '') return null
93  if (typeof r.run === 'string' && r.run.trim() !== '') return { do: text, run: r.run.trim() }
94  if (r.size === 's' || r.size === 'm' || r.size === 'l') return { do: text, size: r.size }
95  return { do: text }
96}
97
98/** A report from the tool's input, trimmed to what the band holds; null for one that says nothing, a list with no usable item included. */
99export function parseReport(input: Record<string, unknown>): Report | null {
100  if (Array.isArray(input.left)) {
101    const left = input.left.slice(0, MAX_ITEMS).map(itemOf).filter((item): item is WorkItem => item !== null)
102    if (input.left.length > 0 && left.length === 0) return null
103    return { left }
104  }
105  const done = typeof input.done === 'number' && Number.isFinite(input.done) ? Math.floor(input.done) : 0
106  return done >= 1 ? { done } : null
107}
108
109/** The top item that finished, and since when it had been on top: what its time is learned from. */
110export type Finished = { item: WorkItem; since: number }
111
112/** A work list after a report, and the top item when the report says it ended on its own, so its time can be learned. */
113export function applyReport(work: Work | null, report: Report, now: number): { work: Work | null; finished: Finished | null } {
114  if ('done' in report) {
115    if (work === null || work.items.length === 0) return { work, finished: null }
116    const ended = work.items.slice(0, report.done)
117    const next: Work = { items: work.items.slice(report.done), finished: [...work.finished, ...ended.map(item => item.do)].slice(-MAX_FINISHED), topSince: now }
118    // Several at once leave no telling how long each took.
119    return { work: next, finished: report.done === 1 && ended.length === 1 ? { item: ended[0]!, since: work.topSince } : null }
120  }
121  const { left } = report
122  if (work === null) return { work: { items: left, finished: [], topSince: now }, finished: null }
123  const top = work.items[0]
124  const isGone = top !== undefined && !left.some(item => item.do === top.do)
125  const isStill = top !== undefined && left[0]?.do === top.do
126  return {
127    work: { items: left, finished: isGone ? [...work.finished, top.do].slice(-MAX_FINISHED) : work.finished, topSince: isStill ? work.topSince : now },
128    finished: isGone ? { item: top, since: work.topSince } : null,
129  }
130}
131
132/** A work list as the band's step rows: what finished, the item in progress, the rest. */
133export function workTasks(work: Work): Task[] {
134  return [
135    ...work.finished.map((text, i): Task => ({ id: `done-${i}`, subject: text, status: 'completed' })),
136    ...work.items.map((item, i): Task => ({ id: `work-${i}`, subject: item.do, status: i === 0 ? 'in_progress' : 'pending' })),
137  ]
138}
139
hooks/shell.ts 325 lines
1// What a Bash command wrote, as far as its text tells: the files it names, and what changed files it cannot name.
2
3/** The files a command names as written, absolute where the session's directory is known; and, per command that changed files it does not name, a short label (`git merge`, `python3`). */
4export type ShellWrites = { paths: string[]; unnamed: string[] }
5
6/** A word of the command: its text with quotes taken off, and whether the shell computes part of it (`$x`, a glob, a backtick). */
7type Word = { text: string; isDynamic: boolean }
8
9/** One simple command: its words, the files it redirects output to, and the heredocs fed to it. */
10type Segment = { words: Word[]; outputs: Word[]; bodies: string[] }
11
12const INTERPRETERS = /^(python[\d.]*|node|bun|deno|ruby|tsx|ts-node)$/
13const INLINE_FLAGS = new Set(['-c', '-e', '--eval', '-p', '--print'])
14/** git subcommands that rewrite the working tree without naming its files. */
15const GIT_REWRITES = new Set(['merge', 'pull', 'rebase', 'cherry-pick', 'revert', 'am', 'apply', 'clean'])
16const WRAPPERS = new Set(['sudo', 'env', 'time', 'command', 'nohup', 'npx', 'pnpx', 'bunx'])
17const XARGS_VALUES = new Set(['-I', '-n', '-P', '-L', '-d', '-E', '-s'])
18/** Formatters whose `-w` writes the files back. */
19const WRITES_WITH_W = new Set(['gofmt', 'goimports', 'gofumpt', 'shfmt'])
20const SEPARATORS = ['&&', '||', ';', '|', '&', '\n', '(', ')']
21
22/** Splits a command into simple commands, quotes resolved and heredoc bodies attached to the command that reads them. */
23function segments(command: string): Segment[] {
24  const out: Segment[] = []
25  let seg: Segment = { words: [], outputs: [], bodies: [] }
26  let word: Word | null = null
27  /** Where the next word goes: a word, an output file, a heredoc's delimiter, or nowhere (an input file, a descriptor). */
28  let into: 'word' | 'output' | 'heredoc' | 'body' | 'skip' = 'word'
29  const heredocs: { tag: string; seg: Segment }[] = []
30
31  const endWord = () => {
32    if (word === null) return
33    if (into === 'output') seg.outputs.push(word)
34    else if (into === 'heredoc') heredocs.push({ tag: word.text, seg })
35    else if (into === 'body') seg.bodies.push(word.text)
36    else if (into === 'word') seg.words.push(word)
37    word = null
38    into = 'word'
39  }
40  const endSegment = () => {
41    endWord()
42    if (seg.words.length > 0 || seg.outputs.length > 0) out.push(seg)
43    seg = { words: [], outputs: [], bodies: [] }
44  }
45  const append = (text: string, isDynamic = false) => {
46    word = word === null ? { text, isDynamic } : { text: word.text + text, isDynamic: word.isDynamic || isDynamic }
47  }
48
49  let i = 0
50  while (i < command.length) {
51    const c = command[i] as string
52    if (c === '#' && word === null) {
53      // A comment runs to the end of its line.
54      const eol = command.indexOf('\n', i)
55      i = eol === -1 ? command.length : eol
56      continue
57    }
58    if (c === '\\') {
59      if (command[i + 1] !== '\n') append(command[i + 1] ?? '')
60      i += 2
61      continue
62    }
63    if (c === "'") {
64      const end = command.indexOf("'", i + 1)
65      const stop = end === -1 ? command.length : end
66      append(command.slice(i + 1, stop))
67      i = stop + 1
68      continue
69    }
70    if (c === '"') {
71      let j = i + 1
72      let text = ''
73      while (j < command.length && command[j] !== '"') {
74        if (command[j] === '\\' && j + 1 < command.length) j += 1
75        text += command[j]
76        j += 1
77      }
78      append(text, /[$`]/.test(text))
79      i = j + 1
80      continue
81    }
82    if (c === '$' && command[i + 1] === '(') {
83      let depth = 0
84      let j = i + 1
85      for (; j < command.length; j++) {
86        if (command[j] === '(') depth += 1
87        else if (command[j] === ')' && --depth === 0) break
88      }
89      append(command.slice(i, j + 1), true)
90      i = j + 1
91      continue
92    }
93    if (c === '`') {
94      const end = command.indexOf('`', i + 1)
95      const stop = end === -1 ? command.length : end
96      append(command.slice(i, stop + 1), true)
97      i = stop + 1
98      continue
99    }
100    if (c === '\n') {
101      endSegment()
102      // Heredoc bodies start on the line after their command, in the order they were opened.
103      let at = i + 1
104      for (const doc of heredocs.splice(0)) {
105        const lines: string[] = []
106        while (at < command.length) {
107          const eol = command.indexOf('\n', at)
108          const line = command.slice(at, eol === -1 ? command.length : eol)
109          at = eol === -1 ? command.length : eol + 1
110          if (line.trim() === doc.tag) break
111          lines.push(line)
112        }
113        doc.seg.bodies.push(lines.join('\n'))
114      }
115      i = at
116      continue
117    }
118    if (c === '<') {
119      endWord()
120      if (command.startsWith('<<<', i)) {
121        into = 'body'
122        i += 3
123      } else if (command.startsWith('<<', i)) {
124        into = 'heredoc'
125        i += command[i + 2] === '-' ? 3 : 2
126      } else {
127        into = 'skip'
128        i += 1
129      }
130      continue
131    }
132    if (c === '>' || (c === '&' && command[i + 1] === '>')) {
133      // `2>` and `&>`: a descriptor number before `>` is no word.
134      if (word !== null && /^\d+$/.test((word as Word).text)) word = null
135      endWord()
136      let j = c === '&' ? i + 2 : i + 1
137      if (command[j] === '>' || command[j] === '|') j += 1
138      if (command[j] === '&') {
139        // `>&2`, `2>&1`: a descriptor, not a file.
140        into = 'skip'
141        j += 1
142      } else {
143        into = 'output'
144      }
145      i = j
146      continue
147    }
148    const sep = SEPARATORS.find(s => command.startsWith(s, i))
149    if (sep !== undefined && sep !== '\n') {
150      endSegment()
151      i += sep.length
152      continue
153    }
154    if (c === ' ' || c === '\t') {
155      endWord()
156      i += 1
157      continue
158    }
159    append(c, c === '*' || c === '?')
160    i += 1
161  }
162  endSegment()
163  return out
164}
165
166/** `/a/b/../c` → `/a/c`; a relative path joins `dir` when there is one. */
167function resolve(dir: string | null, path: string): string {
168  if (path.startsWith('~')) return path
169  const joined = path.startsWith('/') || dir === null ? path : `${dir}/${path}`
170  const isAbsolute = joined.startsWith('/')
171  const parts: string[] = []
172  for (const part of joined.split('/')) {
173    if (part === '' || part === '.') continue
174    if (part === '..' && parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
175    else parts.push(part)
176  }
177  const out = parts.join('/')
178  return isAbsolute ? `/${out}` : out === '' ? '.' : out
179}
180
181/** The words after the command that are not options; `takesValue` names the options that eat the next word. */
182function operands(args: Word[], takesValue: ReadonlySet<string> = new Set()): Word[] {
183  const out: Word[] = []
184  let isOptionsDone = false
185  for (let i = 0; i < args.length; i++) {
186    const text = (args[i] as Word).text
187    if (!isOptionsDone && text === '--') isOptionsDone = true
188    else if (!isOptionsDone && text.startsWith('-') && text !== '-') {
189      if (takesValue.has(text)) i += 1
190    } else out.push(args[i] as Word)
191  }
192  return out
193}
194
195/** The literal paths a script writes, and whether it also writes one it computes. */
196function scriptWrites(script: string): { paths: string[]; isUnnamed: boolean } {
197  const paths: string[] = []
198  let isUnnamed = false
199  const str = `(?:r|b)?['"\`]([^'"\`\\n]+)['"\`]`
200  // Python: a Path kept in a variable, then written through it.
201  const assigned = new Map<string, string[]>()
202  const events: { at: number; kind: 'assign' | 'write'; name: string; path?: string }[] = []
203  for (const m of script.matchAll(new RegExp(`\\b(\\w+)\\s*=\\s*(?:pathlib\\.)?Path\\(\\s*${str}\\s*\\)`, 'g')))
204    events.push({ at: m.index ?? 0, kind: 'assign', name: m[1] as string, path: m[2] as string })
205  for (const m of script.matchAll(/\b(\w+)\.(?:write_text|write_bytes)\(/g)) events.push({ at: m.index ?? 0, kind: 'write', name: m[1] as string })
206  for (const ev of events.sort((a, b) => a.at - b.at)) {
207    if (ev.kind === 'assign') assigned.set(ev.name, [ev.path as string])
208    else {
209      const known = assigned.get(ev.name)
210      if (known === undefined) isUnnamed = true
211      else paths.push(...known)
212    }
213  }
214  // A Path written where it is made, a file opened to write, and Node's and Ruby's writes.
215  for (const m of script.matchAll(new RegExp(`Path\\(\\s*${str}\\s*\\)\\s*\\.(?:write_text|write_bytes)\\(`, 'g'))) paths.push(m[1] as string)
216  for (const m of script.matchAll(new RegExp(`\\bopen\\(\\s*${str}\\s*,\\s*(?:mode\\s*=\\s*)?['"]([^'"]*)['"]`, 'g')))
217    if (/[wax+]/.test(m[2] as string)) paths.push(m[1] as string)
218  for (const m of script.matchAll(/\bopen\(\s*[^'"`\s,)][^,)]*,\s*(?:mode\s*=\s*)?['"]([^'"]*)['"]/g)) if (/[wax+]/.test(m[1] as string)) isUnnamed = true
219  for (const m of script.matchAll(new RegExp(`\\b(?:writeFileSync|writeFile|appendFileSync|appendFile|File\\.write)\\(\\s*${str}`, 'g'))) paths.push(m[1] as string)
220  if (/\b(?:writeFileSync|writeFile|appendFileSync|appendFile|File\.write)\(\s*[^'"`\s]/.test(script)) isUnnamed = true
221  if (/\b(?:shutil\.(?:copy\w*|move|rmtree)|os\.(?:remove|unlink|rename|replace)|unlinkSync|renameSync|rmSync)\(/.test(script)) isUnnamed = true
222  return { paths: [...new Set(paths)], isUnnamed }
223}
224
225const optionIn = (args: Word[], ...flags: string[]) => args.some(a => flags.includes(a.text))
226
227/** What one Bash command wrote, as far as its text tells; relative paths resolve against `cwd` (and any `cd` in the command). */
228export function shellWrites(command: string, cwd: string | null): ShellWrites {
229  const paths: string[] = []
230  const unnamed: string[] = []
231  let dir = cwd
232  const name = (w: Word, label: string) => {
233    if (w.isDynamic || w.text === '' || w.text.includes('{}')) unnamed.push(label)
234    else if (!w.text.startsWith('/dev/')) paths.push(resolve(dir, w.text))
235  }
236
237  for (const seg of segments(command)) {
238    for (const out of seg.outputs) name(out, '>')
239    let words = seg.words
240    while (words.length > 0 && (/^\w+=/.test((words[0] as Word).text) || WRAPPERS.has((words[0] as Word).text))) words = words.slice(1)
241    if (words.length === 0) continue
242    const isXargs = (words[0] as Word).text === 'xargs'
243    if (isXargs) {
244      words = words.slice(1)
245      while (words[0]?.text.startsWith('-') === true) words = words.slice(XARGS_VALUES.has((words[0] as Word).text) ? 2 : 1)
246    }
247    const head = words[0]
248    if (head === undefined) continue
249    const cmd = head.text.split('/').pop() ?? head.text
250    const args = words.slice(1)
251    /** Files a command names; under xargs they come from its input, so none can be named. */
252    const named = (files: Word[], label: string) => {
253      if (isXargs) unnamed.push(`xargs ${cmd}`)
254      else for (const f of files) name(f, label)
255    }
256
257    if (cmd === 'cd') {
258      const to = args[0]
259      if (to === undefined || to.isDynamic) dir = null
260      else dir = to.text.startsWith('/') ? resolve(null, to.text) : dir === null ? null : resolve(dir, to.text)
261    } else if (cmd === 'tee') {
262      named(operands(args), 'tee')
263    } else if (cmd === 'sed') {
264      const inPlace = args.findIndex(a => a.text.startsWith('-i') || a.text.startsWith('--in-place') || /^-[a-zA-Z]+i$/.test(a.text))
265      if (inPlace === -1) continue
266      // macOS takes the backup suffix as its own word: `sed -i '' ...`.
267      const rest = args[inPlace]?.text === '-i' && args[inPlace + 1]?.text === '' ? [...args.slice(0, inPlace + 1), ...args.slice(inPlace + 2)] : args
268      const files = operands(rest, new Set(['-e', '-f', '--expression', '--file']))
269      named(optionIn(rest, '-e', '-f', '--expression', '--file') ? files : files.slice(1), 'sed')
270    } else if (cmd === 'perl') {
271      if (!args.some(a => /^-[a-zA-Z]*i/.test(a.text))) {
272        const inline = args.findIndex(a => a.text === '-e' || a.text === '-E')
273        if (inline !== -1 && scriptWrites(args[inline + 1]?.text ?? '').isUnnamed) unnamed.push('perl')
274        continue
275      }
276      const files = operands(args, new Set(['-e', '-E']))
277      named(optionIn(args, '-e', '-E') || args.some(a => /^-[a-zA-Z]*e$/.test(a.text)) ? files : files.slice(1), 'perl')
278    } else if (['rm', 'touch', 'unlink', 'shred', 'truncate'].includes(cmd)) {
279      named(operands(args, new Set(['-s', '--size'])), cmd)
280    } else if (cmd === 'mv') {
281      named(operands(args, new Set(['-t', '-S'])), 'mv')
282    } else if (cmd === 'cp' || cmd === 'install' || cmd === 'ln') {
283      const files = operands(args, new Set(['-t', '-S', '-m', '-o', '-g']))
284      named(files.slice(-1), cmd)
285    } else if (cmd === 'dd') {
286      for (const a of args) if (a.text.startsWith('of=')) name({ ...a, text: a.text.slice(3) }, 'dd')
287    } else if (cmd === 'git') {
288      const rest = [...args]
289      while (rest.length > 0 && (rest[0] as Word).text.startsWith('-')) rest.splice(0, ['-C', '-c'].includes((rest[0] as Word).text) ? 2 : 1)
290      const sub = rest[0]?.text
291      const subArgs = rest.slice(1)
292      if (sub === undefined) continue
293      if (sub === 'mv' || sub === 'rm') named(operands(subArgs), `git ${sub}`)
294      else if (sub === 'restore') named(operands(subArgs, new Set(['-s', '--source'])), 'git restore')
295      else if (sub === 'checkout' || sub === 'switch') {
296        const dashes = subArgs.findIndex(a => a.text === '--')
297        if (dashes !== -1) named(subArgs.slice(dashes + 1), `git ${sub}`)
298        else if (!optionIn(subArgs, '-b', '-B', '-c', '-C', '--orphan') && subArgs.length > 0) unnamed.push(`git ${sub}`)
299      } else if (sub === 'reset') {
300        if (optionIn(subArgs, '--hard', '--merge', '--keep')) unnamed.push('git reset')
301      } else if (sub === 'stash') {
302        if (subArgs.length === 0 || ['push', 'save', 'pop', 'apply'].includes((subArgs[0] as Word).text)) unnamed.push('git stash')
303      } else if (GIT_REWRITES.has(sub)) unnamed.push(`git ${sub}`)
304    } else if (cmd === 'find') {
305      const exec = args.findIndex(a => a.text === '-exec' || a.text === '-execdir')
306      const run = exec === -1 ? undefined : args[exec + 1]?.text
307      if (optionIn(args, '-delete') || (run !== undefined && ['sed', 'perl', 'rm', 'mv', 'cp', 'tee', 'truncate'].includes(run))) unnamed.push('find')
308    } else if (cmd === 'patch') {
309      unnamed.push('patch')
310    } else if (INTERPRETERS.test(cmd)) {
311      const inline = args.findIndex(a => INLINE_FLAGS.has(a.text))
312      const scripts = [...seg.bodies, ...(inline === -1 ? [] : [args[inline + 1]?.text ?? ''])]
313      for (const script of scripts) {
314        const wrote = scriptWrites(script)
315        for (const p of wrote.paths) paths.push(resolve(dir, p))
316        if (wrote.isUnnamed) unnamed.push(cmd)
317      }
318    } else if (optionIn(args, '--fix', '--write') || (WRITES_WITH_W.has(cmd) && optionIn(args, '-w'))) {
319      // A formatter or linter fixing files in place: prettier --write, eslint --fix, gofmt -w.
320      unnamed.push(cmd)
321    }
322  }
323  return { paths: [...new Set(paths)], unnamed: [...new Set(unnamed)] }
324}
325
types/index.d.ts 213 lines
1export type TaskStatus = 'pending' | 'in_progress' | 'completed'
2
3export type Task = { id: string; subject: string; activeForm?: string; status: TaskStatus }
4
5export type PlanItem = { text: string; done: boolean }
6
7/** A `### Task N:` heading of a plan, with the boxes beneath it. */
8export type PlanTask = { n: number; text: string; steps: number; stepsDone: number }
9
10/**
11 * A Markdown plan or spec whose `- [ ]` / `- [x]` boxes stand for the steps.
12 * With two or more `### Task N:` headings its tasks are the steps instead, and `completed`
13 * holds the ones a superpowers ledger reported done (its executor never ticks the boxes).
14 * Both are absent on a plan kept from before they existed.
15 */
16export type PlanFile = { path: string; name: string; items: PlanItem[]; tasks?: PlanTask[]; completed?: number[] }
17
18/** The kinds of work whose times the countdown learns, in round-equivalents: Claude's item sizes, and a task list's, a plan's tasks' and a plan's steps'. */
19export type SampleKind = 's' | 'm' | 'l' | 'task' | 'planTask' | 'planStep'
20
21/** A time in milliseconds with its likely range. */
22export type Spread = { ms: number; lowMs: number; highMs: number }
23
24/** Samples a loop gathered and has not yet written: round-equivalents by kind, and milliseconds by command key. */
25export type EtaPending = { sizes: Partial<Record<SampleKind, number[]>>; commands: Record<string, number[]> }
26
27/** One item of a `progress` report: sized, or named by the command that running is the item. */
28export type WorkItem = { do: string; size?: 's' | 'm' | 'l'; run?: string }
29
30/** A loop's Progress list: what is left in order, the item in progress first; what finished; and since when the top item has been on top. */
31export type Work = { items: WorkItem[]; finished: string[]; topSince: number }
32
33/** One loop's countdown, the main turn's or a subagent run's, kept whole so every band draws the same fill. */
34export type EtaTurn = {
35  /** When the loop started. */
36  startedAt: number
37  work: Work | null
38  /** The command keys of every `run` item reported this turn, so a finished one's long round stays out of the pace. */
39  runs: string[]
40  /** When each task or plan entry came into progress, and the ones already learned: both keyed by each task's id and text (its `taskKey`). */
41  since: Record<string, number>
42  counted: string[]
43  /** The estimate as last worked out, and each listed item's own: the time left on the one in progress, the median of the rest. */
44  last: Spread | null
45  items: { key: string; ms: number }[]
46  /**
47   * The first estimate, for the summary and the log: when it came, what it said, what it rested on, and what it said before
48   * calibration (`raw`, absent on a turn kept from before it existed).
49   */
50  first: (Spread & { atMs: number; source: 'progress' | 'tasks' | 'plan'; raw?: Spread }) | null
51  fill: number | null
52  lastTickAt: number
53  /** The loop's round count at its last report, for the stale rule. */
54  lastReportRound: number
55  /** Round-equivalents of the items finished so far, as they went and as estimated: what *c* is made of. */
56  actual: number
57  estimated: number
58  /** The value the label last showed, and until when its `↑` shows. */
59  shownMs: number | null
60  upUntil: number | null
61  pending: EtaPending
62  /** The estimate as last worked out before calibration, for a main turn that waits on this loop. Absent on a turn kept from before it existed. */
63  lastRaw?: Spread | null
64  /** Whether a call already reminded Claude to report this turn. Absent on a turn kept from before it existed. */
65  nudged?: boolean
66  /** The `lastReportRound` of the report a call last reminded Claude may be out of date. Absent on a turn kept from before it existed. */
67  remindedRound?: number
68}
69
70/** One tool call as a band's details list it; `agentId` marks a subagent's. */
71export type CallRecord = {
72  id: string
73  tool: string
74  label: string
75  /** A Bash call's command key (a hash of its normalized text). Absent on other tools and on a record kept from before it existed. */
76  command?: string
77  agentId?: string
78  startedAt: number
79  durationMs: number | null
80  status: 'running' | 'ok' | 'error'
81  /** The first line of why it failed. */
82  error?: string
83}
84
85/** Lines a file's writes added and removed; null where the change could not be measured (a notebook cell). */
86export type FileChange = { path: string; added: number | null; removed: number | null }
87
88/** One model request of a turn: what it asked to run and what it cost. `startedAt` is absent on a record kept from before it existed. */
89export type StepRecord = { index: number; startedAt?: number; durationMs: number; tools: string[]; tokensIn: number; tokensOut: number; stopReason: string | null }
90
91/** What a band's stats open onto: the calls, files, reads, steps and subagents of one turn or one subagent's run. */
92export type Detail = {
93  calls: CallRecord[]
94  files: FileChange[]
95  reads: string[]
96  stepLog: StepRecord[]
97  agentIds: string[]
98  /** Per shell command that changed files it does not name, what it was (`git merge`, `python3`). Absent on a turn kept from before it existed. */
99  shellEdits?: string[]
100}
101
102/** Which stat's details the band lists under its stats row. */
103export type StatKind = 'tools' | 'subagents' | 'files' | 'reads' | 'steps' | 'tokens' | 'errors' | 'tasks'
104
105export type Live = {
106  turnId: string
107  startedAt: number
108  isLong: boolean
109  steps: number
110  toolCalls: number
111  subagentToolCalls: number
112  subagents: number
113  errors: number
114  byTool: Record<string, number>
115  running: { id: string; label: string }[]
116  lastActivity: string | null
117  tokensIn: number
118  tokensCached: number
119  /** Absent on a turn kept from before it existed. */
120  tokensCacheWrite?: number
121  tokensOut: number
122  /** Estimated USD at list prices. Absent on a turn kept from before it existed. */
123  cost?: number
124  model: string | null
125  /** Absent on a turn kept from before it existed. */
126  detail?: Detail
127}
128
129export type Summary = {
130  reason: 'answer' | 'aborted' | 'refusal' | 'error'
131  durationMs: number
132  steps: number
133  toolCalls: number
134  subagentToolCalls: number
135  subagents: number
136  errors: number
137  topTools: [string, number][]
138  files: number
139  tasksDone: number
140  tasksTotal: number
141  stepsUnit: 'tasks' | 'steps'
142  stepsSource: string | null
143  tokensIn: number
144  tokensCached: number
145  tokensCacheWrite?: number
146  tokensOut: number
147  /** Estimated USD at list prices. */
148  cost?: number
149  model: string | null
150  /** The finished turn's details, which its stats still open onto. */
151  detail?: Detail
152  /** Where the bar's fill got to, with the countdown on. */
153  fill?: number
154  /** The first estimate against what followed, for a turn that answered with nothing left running. */
155  eta?: { atMs: number; estimatedMs: number; lowMs: number; highMs: number; tookMs: number }
156}
157
158/**
159 * One subagent's run as the band saw it: what its transcript's band draws.
160 * `dispatchedByMain` marks an agent the main loop's Agent call started, the ones a finished main turn waits for.
161 */
162export type AgentRun = {
163  id: string
164  description: string | null
165  type: string | null
166  parentId: string | null
167  dispatchedByMain: boolean
168  startedAt: number
169  finishedAt: number | null
170  durationMs: number | null
171  reason: Summary['reason'] | null
172  steps: number
173  toolCalls: number
174  errors: number
175  running: { id: string; label: string }[]
176  lastActivity: string | null
177  tokensIn: number
178  tokensOut: number
179  /** Absent on a run kept from before it existed. */
180  detail?: Detail
181  /** Its own TodoWrite / TaskCreate list, which never replaces the main one. */
182  tasks: Task[]
183  /** Its countdown, with the countdown on. Absent on a run kept from before it existed. */
184  eta?: EtaTurn
185}
186
187export type Totals = { turns: number; longTurns: number; totalMs: number; toolCalls: number; tokensIn: number; tokensOut: number; cost?: number }
188
189declare module 'claude-code' {
190  /** The mod's own tool, as the model calls it: Claude's report of the work left. Its input is read leniently, so it stays loose here. */
191  interface McpToolInputs {
192    'mcp__session-progress__progress': { left?: unknown; done?: unknown }
193  }
194
195  interface PluginState {
196    'session-progress': {
197      live: Live | null
198      summary: Summary | null
199      tasks: Task[]
200      planFile: PlanFile | null
201      totals: Totals
202      tick: number
203      agents: AgentRun[]
204      /** The stat whose details are open under the stats row, in every band, until pressed again. */
205      openStat: StatKind | null
206      /** The open stat lists everything, not its latest few: set by pressing its `+N earlier` row. */
207      showAll: boolean
208      /** The main turn's countdown: made at `turn.start`, kept past its end while it waits on subagents. */
209      eta: EtaTurn | null
210    }
211  }
212}
213