SLOPSHOPPER

session-meter

Shows a live session pane (/ctx): context breakdown, usage limits with pace, tool calls and model requests; sends the model a one-time note when limits or…

paneguardcommandtoastprompttool
★ 7v0.4.25MITupdated 2026-10-24arasovic/claude-code-mods/session-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-meter
│ ┃ Session ✕ › fix the failing auth test and add an audit log call │ ┃ Waiting for the first context reading. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /ctx │ ⎿ session-meter: Session pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Session
Waiting for the first context reading.
README

session-meter

A docked pane that shows what is happening in a Claude Code session while you work.

The session-meter pane with context, limits, tools and requests

What it shows

  • Context: what fills the context window by category, where auto-compact kicks in, the context size over turns, and the three heaviest items (memory files, MCP servers, the skills listing, slash commands, agents).
  • Limits: the 5-hour and 7-day usage windows, time to reset, and whether the current pace lasts until the reset.
  • Tools: recent tool calls with their target and duration; running calls stay on top, subagent calls are marked ↳.
  • Requests: each model request with its loop (main or subagent type), input and output tokens, cache hit rate and duration. A low cache rate turns yellow or red.

The note to the model

It also sends the model one hidden note when a threshold is crossed, and again only after the figure drops 10 points below it:

ThresholdWhat the model is told
5h window at 80%Mention it in one line and keep going
7d window at 80% and 90%Warn clearly and ask before starting a large task
Context at contextAt (60%)When new work starts, suggest /compact, a fresh session, or a short handoff, whichever fits

The note goes in as prompt context, not as a system prompt change, so the prompt cache is not invalidated. The pane lists the last five notes it sent.

Letting the model reset the context

By default the model only suggests a reset and you decide. Two options in /config change that:

OptionValuesWhat it does
contextActionsuggest (default)The model suggests /compact or a fresh session.
compactThe model gets a context_reset tool. At a natural break it calls the tool. When the turn ends, the mod compacts the conversation and sends the model its next step, so the work goes on. A message you send while it compacts carries that step instead, and the mod drops its own step message, so the step never arrives after the work it names. The mod hands the step on only once its compact call (/compact in the desktop app) has returned. A message that runs before that, such as a note from another session queued ahead of it, gets no step, and the step message still follows. When the next step is yours, such as a decision, the model sets wait and the mod compacts, then waits for you. With wait, the model's next holds what it wants to remember: the mod sends no message of its own and adds it, hidden, to the next message you send. The model writes its whole reply, question included, before it calls the tool, so you answer from what it wrote. When the compaction waits for you, the tool refuses the call until the turn has shown you some text: a model can write its reply only in its thinking, which is hidden or summarized. The refused compaction is kept: the model ends its turn with its reply as text, and the compaction runs after it. If the turn's last message has no text, or you stop it, nothing runs.
compact-or-clearAs compact. The model can also choose a clear when the next work does not build on the conversation. A clear needs a handoff of at least 200 characters. The mod saves the handoff to ~/.claude/handoffs/, runs /clear, then sends the handoff as the first message of the new session. A message you send while it clears carries the handoff instead, and the mod drops its own handoff message.
contextAt10 to 95, default 60The context percentage that sends the note.

The tool refuses a call below contextAt and a call from a subagent. A plain headless run (claude -p) gets no tool and only the suggestion, since it ends with the turn. The desktop app also runs Claude Code headless, but it stays open: there the mod compacts by queueing a bare /compact once the turn ends, so a hook that vetoes the compaction shows no "skipped" toast. The step goes only in the message that follows, so you see it, and the model reads it, once. When you interrupt the turn, no reset runs. The old conversation stays available with /resume.

How this differs from Claude Code's own auto-compact:

Built-in auto-compactcontextAction
Who decidesA fixed threshold near the window limitThe model, at a natural break after contextAt
When it runsWhenever the threshold is crossed, even mid-taskWhen the turn that called the tool ends
What carries overThe engine's summaryThe summary, steered by the model's next step, which is also sent as the next prompt; with wait, the mod waits for you and adds next to your next message
A fresh startNoWith compact-or-clear, a /clear that needs a written handoff

Auto-compact stays on. The mod only resets earlier, at a moment the model chooses.

Idle compaction

Claude Code can also compact a long conversation on its own while the session is idle, before the one-hour prompt cache expires. The transcript then shows "Compacted while idle, before the prompt cache expired". Anthropic turns this on from its side; no setting turns it on.

Idle compaction does not know about contextAction, and the two can overlap:

  • It does not wait for contextAt or for a natural break. It can compact between two steps of a task you paused, and it sends no next step.
  • After the mod compacts, a conversation that is still long can be compacted again while you are away, so more detail is lost.
  • If an idle compaction leaves the context below contextAt, context_reset refuses until the context fills again.

To leave resets to the model and to the built-in auto-compact, turn idle compaction off in ~/.claude/settings.json:

{ "idleCompaction": false }

Setting it to true does not turn it on. Checked in Claude Code 2.1.300.

Install

claude plugin marketplace add arasovic/claude-code-mods
claude plugin install session-meter@claude-code-mods

Restart Claude Code. The pane opens on its own in a terminal 144 columns or wider; otherwise type /ctx. In the desktop app it does not open on its own, since the app shows context in its own sidebar; /ctx opens it there too. It docks beside the transcript in fullscreen mode, from 110 columns.

To keep the screen clear, turn off Open the pane at start in /config (the autoOpen option). /ctx still opens the pane, and the notes to the model still go out.

Notes

  • Context percentages come from the same breakdown as /context, so they follow CLAUDE_CODE_AUTO_COMPACT_WINDOW if you set it.
  • Usage limits show after the first model reply of a session; pace needs about 10 minutes of history in the current window.
  • Everything stays local. The pane reads Claude Code's own session data and makes no network calls.

Develop

claude plugin validate .
claude plugin test .
../typecheck.sh session-meter
Source 2 files
hooks/register.tsx 746 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionContextBreakdown } from 'claude-code'
3
4import type { MeterBreakdown, MeterItem, MeterNote, MeterReading, MeterRequest, MeterReset, MeterResume, MeterSample, MeterTool } from '../types'
5
6const PANE = 'ctx'
7// A level fires again only once its figure has fallen this far below it: a window reset or a /compact.
8const REARM = 10
9// Pace needs this much history in the current window before it projects anything.
10const PACE_MIN_MS = 10 * 60_000
11const EIGHTHS = ' ▏▎▍▌▋▊▉'
12const KEEP = 30
13
14export const levels = (contextAt: number) => [
15  { id: 'five_hour:80', kind: 'five_hour', at: 80 },
16  { id: 'seven_day:80', kind: 'seven_day', at: 80 },
17  { id: 'seven_day:90', kind: 'seven_day', at: 90 },
18  { id: `context:${contextAt}`, kind: 'context', at: contextAt },
19]
20type Level = ReturnType<typeof levels>[number]
21// The tool the model calls to compact or clear on its own; registered only when contextAction is not `suggest`.
22const RESET = 'context_reset'
23const RESET_TOOL = 'mcp__session-meter__context_reset'
24// After a clear the model has only the handoff, so one shorter than this cannot carry the goal, state and next step.
25const HANDOFF_MIN = 200
26const ACTIONS = ['suggest', 'compact', 'compact-or-clear'] as const
27export type ContextAction = (typeof ACTIONS)[number]
28
29// A value outside the manifest's choices or range falls back to the default, so a typo can never turn the tool on.
30export const readOptions = (options: Readonly<Record<string, unknown>>) => {
31  const action = ACTIONS.find(a => a === options.contextAction) ?? 'suggest'
32  const at = Number(options.contextAt)
33  return { action, contextAt: Number.isFinite(at) && at >= 10 && at <= 95 ? at : 60 }
34}
35
36const WINDOWS = [
37  { kind: 'five_hour', label: '5h' },
38  { kind: 'seven_day', label: '7d' },
39]
40
41const reading = atom({ plugin: 'session-meter', key: 'reading' } as const, { context: null, limits: [] } as MeterReading)
42const fired = atom({ plugin: 'session-meter', key: 'fired' } as const, [] as string[])
43const breakdown = atom({ plugin: 'session-meter', key: 'breakdown' } as const, null as MeterBreakdown | null)
44const history = atom({ plugin: 'session-meter', key: 'history' } as const, [] as number[])
45const samples = atom({ plugin: 'session-meter', key: 'samples' } as const, [] as MeterSample[])
46const notes = atom({ plugin: 'session-meter', key: 'notes' } as const, [] as MeterNote[])
47const tools = atom({ plugin: 'session-meter', key: 'tools' } as const, [] as MeterTool[])
48const requests = atom({ plugin: 'session-meter', key: 'requests' } as const, [] as MeterRequest[])
49// The reset the model asked for, run when its turn ends, and the next step it leaves behind. Held by the host, so a
50// hot reload of this module between the call, the reset and the Continue's dequeue keeps them.
51const pending = atom({ plugin: 'session-meter', key: 'pending' } as const, null as MeterReset | null)
52// What the model reads once a reset ends, sent as a prompt of its own. A prompt sent while the reset ran is dequeued
53// ahead of that one, so it carries the text instead and the separate prompt is dropped when its turn comes. It is
54// `ready` only once the reset call has resolved; a prompt dequeued before that leaves the step to the separate prompt.
55// A compact that waits has no separate prompt, so its text goes only with the next prompt the user sends.
56const resume = atom({ plugin: 'session-meter', key: 'resume' } as const, null as MeterResume | null)
57
58// Subagent ids never change type, so one lookup per id is enough.
59const agentTypes = new Map<string, string>()
60
61const valueOf = (r: MeterReading, kind: string) =>
62  kind === 'context' ? (r.context ?? undefined) : r.limits.find(l => l.kind === kind)?.percentUsed
63
64export const cross = (r: MeterReading, firedIds: readonly string[], list = levels(60)) => {
65  const kept = firedIds.filter(id => {
66    const level = list.find(l => l.id === id)
67    const value = level && valueOf(r, level.kind)
68    return level !== undefined && (value === undefined || value >= level.at - REARM)
69  })
70  const fresh = list.filter(l => !kept.includes(l.id) && (valueOf(r, l.kind) ?? 0) >= l.at)
71  return { fired: [...kept, ...fresh.map(l => l.id)], fresh }
72}
73
74export const duration = (ms: number) => {
75  const min = Math.max(0, Math.floor(ms / 60_000))
76  if (min >= 1440) return `${Math.floor(min / 1440)}d${Math.floor((min % 1440) / 60)}h`
77  if (min >= 60) return `${Math.floor(min / 60)}h${min % 60}m`
78  return `${min}m`
79}
80
81export const elapsed = (ms: number) => {
82  const s = Math.max(0, Math.round(ms / 1000))
83  return ms < 60_000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : `${Math.floor(s / 60)}m${s % 60}s`
84}
85
86const resetsIn = (resetsAt: string | undefined, now: number) => (resetsAt ? Date.parse(resetsAt) - now : 0)
87
88export const note = (r: MeterReading, fresh: readonly Level[], now: number, action: ContextAction = 'suggest') => {
89  const kinds = [...new Set(fresh.map(l => l.kind))]
90  const lines = kinds.map(kind => {
91    const pct = Math.round(valueOf(r, kind) ?? 0)
92    const resets = duration(resetsIn(r.limits.find(l => l.kind === kind)?.resetsAt, now))
93    if (kind === 'five_hour')
94      return `- The 5-hour usage window is at ${pct}% (resets in ${resets}). Tell the user in one short line. Do not stop or slow down: the session continues automatically at the usage limit, so hitting it only pauses work until the reset.`
95    if (kind === 'seven_day')
96      return `- The 7-day usage window is at ${pct}% (resets in ${resets}). Warn the user clearly: if it runs out, work stops and does NOT resume on its own when the reset is over 24 hours away. Before starting any large new task, ask the user whether to proceed.`
97    if (action !== 'suggest')
98      return `- The context window is ${pct}% full. At the next natural break, call the ${RESET} tool yourself, as its description says. Do not ask the user first.`
99    return `- The context window is ${pct}% full. From now on, when a request starts new work: if it continues the current work, suggest /compact at a natural break; if it is unrelated and needs nothing from this conversation, suggest a fresh session (/clear or a new terminal); if it is new but needs a few facts from here, suggest a short handoff and then a fresh session. If the current request already starts new work, apply this now. Suggest it once; the user decides.`
100  })
101  return ['session-meter: an automatic note the user does not see. Mention it once; do not repeat it in later replies.', ...lines].join('\n')
102}
103
104const noteLabel = (fresh: readonly Level[]) => {
105  const top = new Map(fresh.map(l => [l.kind, l.at]))
106  const name: Record<string, string> = { five_hour: '5h window', seven_day: '7d window', context: 'context' }
107  return [...top].map(([kind, at]) => `${name[kind]} crossed ${at}%`).join(', ')
108}
109
110// Projects when a window fills, from the samples taken since its last reset; idle time counts, so it errs late, not early.
111export const pace = (list: readonly MeterSample[], kind: string, now: number) => {
112  const mine = list.filter(s => s.kind === kind)
113  const last = mine.at(-1)
114  if (!last) return { kind: 'measuring' as const }
115  const first = mine.find(s => s.resetsAt === last.resetsAt)
116  if (!first || now - first.at < PACE_MIN_MS || last.pct <= first.pct) return { kind: 'measuring' as const }
117  const perMs = (last.pct - first.pct) / (now - first.at)
118  const fullIn = (100 - last.pct) / perMs
119  const resets = resetsIn(last.resetsAt, now)
120  return fullIn < resets ? { kind: 'full' as const, inMs: fullIn } : { kind: 'fine' as const }
121}
122
123// A bar chart in braille, two values per cell and four dots of height per row, bottom row first in the dot math.
124export const braille = (values: readonly number[], max: number, cols: number, rows: number) => {
125  const LEFT = [0x40, 0x04, 0x02, 0x01]
126  const RIGHT = [0x80, 0x20, 0x10, 0x08]
127  const heights = values.slice(-cols * 2).map(v => Math.round((Math.min(v, max) / Math.max(1, max)) * rows * 4))
128  if (heights.length % 2) heights.unshift(0)
129  return Array.from({ length: rows }, (_, r) => {
130    const floor = (rows - 1 - r) * 4
131    let line = ''
132    for (let i = 0; i < heights.length; i += 2) {
133      const dots = (h: number, bits: number[]) => bits.slice(0, Math.max(0, Math.min(4, h - floor))).reduce((a, b) => a | b, 0)
134      line += String.fromCharCode(0x2800 + dots(heights[i] ?? 0, LEFT) + dots(heights[i + 1] ?? 0, RIGHT))
135    }
136    return line
137  })
138}
139
140export const cells = (part: number, whole: number, width: number) => (whole > 0 ? Math.round((part / whole) * width) : 0)
141
142export const tokens = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n))
143
144export const heaviest = (b: Pick<SessionContextBreakdown, 'memoryFiles' | 'mcpTools' | 'skills' | 'slashCommands' | 'agents'>) => {
145  const servers = new Map<string, number>()
146  for (const t of b.mcpTools) if (t.isLoaded) servers.set(t.serverName, (servers.get(t.serverName) ?? 0) + t.tokens)
147  const items: MeterItem[] = [
148    ...b.memoryFiles.map(f => ({ name: f.path.split('/').pop() ?? f.path, tokens: f.tokens })),
149    ...[...servers].map(([name, n]) => ({ name: `${name} MCP`, tokens: n })),
150    ...(b.skills ? [{ name: 'Skills listing', tokens: b.skills.tokens }] : []),
151    ...(b.slashCommands ? [{ name: 'Slash commands', tokens: b.slashCommands.tokens }] : []),
152    ...b.agents.map(a => ({ name: `${a.agentType} agent`, tokens: a.tokens })),
153  ]
154  return items.sort((x, y) => y.tokens - x.tokens).slice(0, 3)
155}
156
157// What a tool call is about, in a few words: the command, the file's name, the pattern, the URL.
158export const target = (input: Record<string, unknown>) => {
159  for (const key of ['command', 'file_path', 'path', 'pattern', 'url', 'description', 'query', 'prompt', 'skill']) {
160    const value = input[key]
161    if (typeof value !== 'string' || !value) continue
162    const text = key === 'file_path' || key === 'path' ? (value.split('/').pop() ?? value) : value
163    return text.replace(/\s+/g, ' ').trim()
164  }
165  return ''
166}
167
168export const toolName = (tool: string) => (tool.startsWith('mcp__') ? (tool.split('__').at(-1) ?? tool) : tool)
169
170// Rows are runs of styled text. The terminal draws them on a grid of cells, so frames pad and cut them exactly.
171// Other surfaces draw text in a proportional font, where spaces line nothing up: there a row is a flex line.
172// `fill` stretches, `w` is a column that many characters wide (`right` aligns it), `keep` never gives way when
173// the line runs short, a Bar draws `parts` as real bars in place of its `cells`, a Spark draws a bar per value,
174// and a Group takes an equal share of the line.
175export type Seg = { t: string; c?: string; d?: boolean; b?: boolean; fill?: boolean; w?: number; right?: boolean; keep?: boolean }
176type Bar = { cells: Seg[]; parts: { n: number; c?: string }[] }
177type Spark = { spark: readonly number[]; max: number; c: string }
178type Group = { group: Row }
179type Row = (Seg | Bar | Spark | Group)[]
180
181// The empty part of a bar where the surface draws real bars.
182const TRACK = 'userMessageBackgroundHover'
183
184const segs = (row: Row): Seg[] => row.flatMap(s => ('t' in s ? [s] : 'cells' in s ? s.cells : 'group' in s ? segs(s.group) : []))
185
186const width = (row: Row) => segs(row).reduce((n, s) => n + s.t.length, 0)
187
188export const fit = (row: Row, w: number): Seg[] => {
189  const out: Seg[] = []
190  let n = 0
191  for (const s of segs(row)) {
192    const room = w - n
193    if (room <= 0) break
194    if (s.t.length <= room) {
195      out.push(s)
196      n += s.t.length
197    } else {
198      out.push({ ...s, t: `${s.t.slice(0, room - 1)}…` })
199      n = w
200    }
201  }
202  if (n < w) out.push({ t: ' '.repeat(w - n) })
203  return out
204}
205
206const spread = (left: Row, right: Row, w: number): Row => [...left, { t: ' '.repeat(Math.max(1, w - width(left) - width(right))), fill: true }, ...right]
207
208const zone = (pct: number) => (pct >= 80 ? 'error' : pct >= 60 ? 'warning' : 'success')
209
210// The meter's fill split at the zone edges, so a real bar warms as it fills, as the terminal's cells do.
211export const zoneParts = (pct: number) => {
212  const p = Math.min(100, Math.max(0, pct))
213  return [{ n: Math.min(p, 60), c: 'success' }, { n: Math.min(Math.max(p - 60, 0), 20), c: 'warning' }, { n: Math.max(p - 80, 0), c: 'error' }, { n: 100 - p }]
214}
215
216// A meter with eighth-cell precision; filled cells take the colour of the zone they sit in, so the bar warms as it fills.
217export const meter = (pct: number, w: number): Seg[] => {
218  const eighths = Math.round((Math.min(100, Math.max(0, pct)) / 100) * w * 8)
219  const out: Seg[] = []
220  for (let i = 0; i < w; i++) {
221    const left = eighths - i * 8
222    const ch = left >= 8 ? '█' : left > 0 ? (EIGHTHS[left] ?? ' ') : '·'
223    const seg = left > 0 ? { t: ch, c: zone(((i + 1) / w) * 100) } : { t: ch, d: true }
224    const prev = out.at(-1)
225    if (prev && prev.c === seg.c && prev.d === seg.d) prev.t += ch
226    else out.push(seg)
227  }
228  return out
229}
230
231export type Reset = MeterReset
232
233// Reads the model's context_reset call: the reset to run after the turn, or why it is refused.
234export const checkReset = (input: Record<string, unknown>, action: ContextAction): Reset | string => {
235  const next = typeof input.next === 'string' ? input.next.trim() : ''
236  const handoff = typeof input.handoff === 'string' ? input.handoff.trim() : ''
237  if (input.mode === 'compact') return next ? { mode: 'compact', next, ...(input.wait === true ? { wait: true as const } : {}) } : { mode: 'compact' }
238  if (input.mode !== 'clear' || action !== 'compact-or-clear') return `mode must be ${action === 'compact-or-clear' ? '"compact" or "clear"' : '"compact"'}.`
239  if (handoff.length < HANDOFF_MIN)
240    return `A clear needs a \`handoff\` of at least ${HANDOFF_MIN} characters: the new session sees nothing else. Give the goal, what is done, the decisions taken, the files that matter and the next step.`
241  return { mode: 'clear', handoff }
242}
243
244const resetSpec = (action: ContextAction) => {
245  const canClear = action === 'compact-or-clear'
246  return {
247    name: RESET,
248    description: [
249      'Compacts this conversation after your turn ends, then sends `next` back to you as a new prompt, so the work goes on without the user.',
250      'Set `wait` to true when the next step is the user\'s, such as a decision or an answer: the compaction then runs and waits for the user, and `next`, if given, is what to remember; it reaches you with the user\'s next message.',
251      'Call it yourself, without asking, once session-meter has said the context is full and you reach a natural break: a step is done and nothing is half-edited. Never call it in the middle of a step.',
252      ...(canClear
253        ? ['Use mode "clear" instead when the next work does not build on this conversation. The conversation is cleared and the new session sees only your `handoff`, so it must carry the goal, what is done, the decisions taken, the files that matter and the next step.']
254        : []),
255      'Write your whole reply as a `text` block before the call, including any question or choice you put to the user: a `thinking` block is hidden or summarized, so it cannot carry a reply. After the call, end your turn with one short line, or, if it answered "Not run yet", with your whole reply.',
256    ].join(' '),
257    inputSchema: {
258      type: 'object',
259      properties: {
260        mode: { type: 'string', enum: canClear ? ['compact', 'clear'] : ['compact'] },
261        next: { type: 'string', description: 'For compact: the step the work continues with. With `wait`: what to remember until the user\'s next message.' },
262        wait: { type: 'boolean', description: 'For compact: true when the next step is the user\'s. No prompt is sent; the compaction waits for them.' },
263        ...(canClear ? { handoff: { type: 'string', description: 'For clear: everything the new session needs, in full.' } } : {}),
264      },
265      required: ['mode'],
266    },
267    isDeferred: false as const,
268  }
269}
270
271// The handoff goes to disk before the clear, so a failed submit cannot lose it.
272const saveHandoff = async ($: EngineInterface, handoff: string) => {
273  const at = new Date(await $.clock.now())
274  const cwd = await $.session.cwd()
275  const sessionId = await $.session.id()
276  const home = (await $.env.get('HOME')) ?? '.'
277  const project = (cwd.split('/').filter(Boolean).pop() ?? 'root').replace(/[^\w.-]+/g, '-')
278  const pad = (n: number) => String(n).padStart(2, '0')
279  const stamp = `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}`
280  const path = `${home}/.claude/handoffs/${stamp}-clear-${project}-${sessionId.slice(0, 8)}.md`
281  await $.fs.write(path, `# Handoff before /clear\n\n- Cwd: ${cwd}\n- Session: ${sessionId}\n\n${handoff}\n`)
282  return path.replace(home, '~')
283}
284
285const refresh = async ($: EngineInterface) => {
286  const { context, rateLimits } = await $.session.usage({ breakdown: 'summary' })
287  const b = context.breakdown
288  // The breakdown measures against the compaction window (CLAUDE_CODE_AUTO_COMPACT_WINDOW when set); `context.percent` uses the model's full window.
289  await update($, reading, () => ({ context: b?.percentage ?? context.percent ?? null, limits: [...rateLimits] }))
290  if (!b) return
291  await update($, breakdown, () => ({
292    percent: b.percentage,
293    tokens: b.totalTokens,
294    window: b.rawMaxTokens,
295    threshold: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
296    categories: b.categories.filter(c => !c.isDeferred).map(c => ({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind })),
297    heaviest: heaviest(b),
298  }))
299}
300
301const sample = async ($: EngineInterface, limits: MeterReading['limits']) => {
302  const at = await $.clock.now()
303  await update($, samples, list => [...list, ...limits.map(l => ({ kind: l.kind, at, pct: l.percentUsed, resetsAt: l.resetsAt }))].slice(-200))
304}
305
306const agentLabel = async ($: EngineInterface, id: string | undefined) => {
307  if (!id) return 'main'
308  // The engine's own forks (compaction, memory) carry ids no list names, so they are never cached.
309  const type = agentTypes.get(id) ?? (await $.agent.list()).find(a => a.id === id)?.type
310  if (type) agentTypes.set(id, type)
311  return type ?? 'fork'
312}
313
314export const register: Register = (on, options) => {
315  const { action, contextAt } = readOptions(options)
316  const thresholds = levels(contextAt)
317  // A plain -p run ends with the turn, so the tool would only stop the work. The desktop app is headless too,
318  // but it stays open and attaches as a surface, which a -p run never does.
319  let live: ContextAction = 'suggest'
320  // Only the REPL can compact from a hook; a headless host compacts through a queued /compact.
321  let isRepl = false
322  // Whether this main turn has shown the person any text. A model can put its whole reply in thinking, which
323  // is hidden or summarized, and then reset; an instruction alone did not stop that (0.4.19). Checked only on a compact
324  // that waits (no `next`, or `wait`), which hands the turn to the person; a reset with a next step goes on alone.
325  // ponytail: any text counts, a one-line progress note too; compare against the reply if that slips through.
326  // A reload of this module mid-turn resets it, which can only refuse wrongly: the refused reset still runs at the end.
327  let isTextShown = false
328
329  on('session.start', async ($, e, next) => {
330    await $.command.register({ name: 'ctx', description: 'Show what fills the context window and how fast limits run down' })
331    isRepl = e.isInteractive
332    // An options change reloads this module and runs session.start again, but an app attached before raises no
333    // session.attach, so the reload reads the roster itself. At the app's first start the roster is still empty.
334    const isAttached = !isRepl && (await $.session.surfaces()).some(s => s !== 'terminal')
335    if ((isRepl || isAttached) && live !== action) {
336      live = action
337      await $.tool.register(resetSpec(live))
338    }
339    await refresh($)
340    await sample($, (await read($, reading)).limits)
341    // Only the terminal REPL: the desktop app runs without one and shows context in its own sidebar.
342    if (options.autoOpen !== false && e.surface === 'terminal') void $.ui.open({ id: PANE, title: 'Session' })
343    return next(e)
344  })
345
346  on('session.attach', async ($, e, next) => {
347    if (e.surface !== 'terminal' && live !== action) {
348      live = action
349      await $.tool.register(resetSpec(live))
350    }
351    return next(e)
352  })
353
354  on('command.run', { command: 'ctx' }, async $ => {
355    await refresh($)
356    const opened = await $.ui.open({ id: PANE, title: 'Session' })
357    return { text: opened.isPlaced ? 'Session pane opened.' : `Session pane is waiting: ${opened.reason}` }
358  })
359
360  on('session.measure', async ($, e, next) => {
361    await update($, reading, r => ({ context: r.context, limits: [...e.rateLimits] }))
362    if (e.changed.includes('rateLimits')) await sample($, e.rateLimits)
363    if (e.changed.includes('context')) {
364      if (e.context.tokens !== undefined) await update($, history, list => [...list, e.context.tokens ?? 0].slice(-120))
365      await refresh($)
366    }
367    return next(e)
368  })
369
370  on('prompt.submit', async ($, e, next) => {
371    // Nothing measures between a compaction and the prompt after it, so the stored reading can still be the full
372    // window from before it. Measured first: a measure that throws skips the whole hook before a prompt takes the step.
373    await refresh($)
374    // Queued prompts are dequeued one at a time, each once the session is idle, so these awaits keep their order.
375    // A meta prompt takes no context and a slash command may not reach the model, so both leave it to the
376    // separate prompt.
377    let prompt = e
378    let isDropped = false
379    if (await read($, resume))
380      await update($, resume, r => {
381        isDropped = false
382        prompt = e
383        if (!r) return r
384        if (e.origin?.kind === 'plugin' && e.text === r.alone) {
385          isDropped = r.taken === true
386          return null
387        }
388        if (!r.ready || r.taken || e.isMeta || e.command) return r
389        prompt = { ...e, context: [...(e.context ?? []), r.carried] }
390        // With no separate prompt of its own to drop later, the carried text is done.
391        return r.alone === undefined ? null : { ...r, taken: true as const }
392      })
393    if (isDropped) return { drop: 'session-meter: an earlier message already carried the next step; skipped this copy' }
394    const r = await read($, reading)
395    const crossed = cross(r, await read($, fired), thresholds)
396    await update($, fired, () => crossed.fired)
397    if (crossed.fresh.length === 0) return next(prompt)
398    const now = await $.clock.now()
399    await update($, notes, list => [...list, { at: now, text: noteLabel(crossed.fresh) }].slice(-5))
400    return next({ ...prompt, context: [...(prompt.context ?? []), note(r, crossed.fresh, now, live)] })
401  })
402
403  on('tool.call', { tool: RESET_TOOL }, async ($, e) => {
404    // After a /clear no session.start runs, so the stored reading is stale until measured again.
405    await refresh($)
406    const pct = (await read($, reading)).context ?? 0
407    const reset = checkReset(e as unknown as Record<string, unknown>, action)
408    if (e.agentId !== undefined) return { isError: true as const, result: 'Only the main conversation can reset its context.' }
409    if (pct < contextAt) return { isError: true as const, result: `The context is only ${Math.round(pct)}% full; wait for session-meter's note.` }
410    if (typeof reset === 'string') return { isError: true as const, result: reset }
411    if (reset.mode === 'compact' && (reset.wait || !reset.next) && !isTextShown) {
412      // Told to write text and call again, a model kept writing the reply as thinking before each call (0.4.23): it
413      // wrote text only in a message with no tool call. So the reset is kept and runs if the turn's last message shows text.
414      await update($, pending, () => ({ ...reset, needsText: true as const }))
415      return {
416        isError: true as const,
417        result: 'Not run yet: this turn has no `text` block. Your reply is in a `thinking` block, which is hidden or summarized, so it cannot carry a reply. Now end your turn with your whole reply as a `text` block (the answer, any table, any question) and no tool call. The compaction then runs after your turn. Do not call context_reset again, and do not tell the user the compaction failed.',
418      }
419    }
420    await update($, pending, () => reset)
421    return { result: `The ${reset.mode} runs when this turn ends. If your visible reply left out anything you meant to tell the user, write it now. Then end your turn with one short line.` }
422  })
423
424  on('turn.complete', async ($, e, next) => {
425    const result = await next(e)
426    if (e.agentId !== undefined) return result
427    const job = await read($, pending)
428    if (!job) return result
429    await update($, pending, () => null)
430    // An interrupted turn hands control back to the user: no reset behind their back.
431    if (e.reason !== 'answer') return result
432    // The turn's answer, not isTextShown: a reload between the refusal and here would reset the flag.
433    if (job.mode === 'compact' && job.needsText && !e.answer.trim()) {
434      $.ui.toast('session-meter: compaction skipped: the turn ended without text')
435      return result
436    }
437    let saved: string | undefined
438    // What the model reads once the reset ends. Kept armed: the prompt.submit hook drops it if a prompt dequeued
439    // before it has carried the text.
440    let alone: string | undefined
441    try {
442      if (job.mode === 'compact') {
443        const isWaiting = job.wait || !job.next
444        $.ui.toast(isWaiting ? 'session-meter: compacting' : 'session-meter: compacting, then continuing')
445        const instructions = !job.next ? undefined : job.wait ? `Keep in mind for the user's next message: ${job.next}` : `The work continues with: ${job.next}`
446        // A compact that waits sends no prompt of its own: its notes go only with the user's next message.
447        if (job.next && job.wait) {
448          const carried = `session-meter compacted the conversation just before this message. You asked to remember: ${job.next}`
449          await update($, resume, () => ({ carried }))
450        } else if (job.next) {
451          const armed = {
452            alone: `session-meter compacted the conversation. Continue: ${job.next}`,
453            carried: `session-meter compacted the conversation just before this message. Its next step was: ${job.next}\nHandle this message first, then go on with that step if it still applies.`,
454          }
455          alone = armed.alone
456          await update($, resume, () => armed)
457        }
458        // A queued /compact reports no veto, so only the REPL's direct call can come back skipped.
459        // It runs bare: its arguments would stay in the conversation, shown and sent beside the Continue that
460        // already carries the step, and the summarizer sees the step in the context_reset call anyway.
461        let skip: string | undefined
462        if (isRepl) skip = (await $.session.compact(instructions === undefined ? undefined : { instructions })).skip
463        else await $.command.run({ command: 'compact' })
464        if (skip !== undefined) {
465          await update($, resume, () => null)
466          $.ui.toast(`session-meter: compaction skipped: ${skip}`)
467          return result
468        }
469        if (isWaiting) $.ui.toast('session-meter: compacted; waiting for you')
470      } else {
471        saved = await saveHandoff($, job.handoff)
472        $.ui.toast(`session-meter: clearing; handoff saved to ${saved}`)
473        const text = `session-meter cleared the previous conversation. Its handoff, also saved to ${saved}:\n\n${job.handoff}`
474        alone = text
475        await $.command.run({ command: 'clear' })
476        // The host empties every plugin's $.state once a session ends, a /clear's included, so the step is held only
477        // once the clear has run: in the conversation it started, which no other session reads.
478        await update($, resume, () => ({ alone: text, carried: text }))
479      }
480      // The REPL's direct call and a queued /compact or /clear behind command.run both resolve once the reset has run.
481      // No hook of ours can tell: the host does not run them for an event raised beneath our own pending call.
482      await update($, resume, r => r && { ...r, ready: true as const })
483      if (alone) await $.prompt.submit({ text: alone })
484    } catch (err) {
485      await update($, resume, () => null)
486      $.ui.toast(`session-meter: ${job.mode} failed: ${String(err)}${saved ? `; handoff saved to ${saved}` : ''}`)
487    }
488    return result
489  })
490
491  on('tool.call', async ($, e, next) => {
492    const at = await $.clock.now()
493    const id = e.tool_use_id ?? `${e.tool}:${at}`
494    const entry: MeterTool = { id, name: toolName(e.tool), target: target(e as unknown as Record<string, unknown>), sub: e.agentId !== undefined, at }
495    await update($, tools, list => [entry, ...list.filter(t => t.id !== id)].slice(0, KEEP))
496    let ok = false
497    try {
498      const result = await next(e)
499      ok = result.deny === undefined && !result.isError
500      return result
501    } finally {
502      const ms = (await $.clock.now()) - at
503      await update($, tools, list => list.map(t => (t.id === id ? { ...t, ms, ok } : t)))
504    }
505  })
506
507  on('turn.step', async function* ($, e, next) {
508    const at = await $.clock.now()
509    const isMain = e.agentId === undefined
510    if (isMain && e.index === 0) isTextShown = false
511    const stream = next(e)
512    // Read per chunk, not from the result: the engine can start a tool call before the step's result returns.
513    for await (const chunk of stream) {
514      if (isMain && chunk.kind === 'text' && chunk.text.trim()) isTextShown = true
515      yield chunk
516    }
517    const result = await stream.result
518    const usage = result.usage
519    if (usage) {
520      try {
521        const ms = (await $.clock.now()) - at
522        const agent = await agentLabel($, e.agentId)
523        const input = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
524        const row = { at, agent, input, cached: usage.cache_read_input_tokens, output: usage.output_tokens, ms, model: usage.model }
525        await update($, requests, list => [row, ...list].slice(0, KEEP))
526      } catch {
527        // The log is a convenience: a failed write must never break the model's response.
528      }
529    }
530    return result
531  })
532
533  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
534    const { Box, Text } = $.ui.resolve(e)
535    const b = await read($, breakdown)
536    const r = await read($, reading)
537    const turns = await read($, history)
538    const list = await read($, samples)
539    const sent = await read($, notes)
540    const calls = await read($, tools)
541    const asks = await read($, requests)
542    const now = await $.clock.now()
543    const w = Math.max(28, e.props.bodyColumns - 1)
544    const inner = w - 6
545    const isGrid = e.surface === 'terminal'
546    if (!b) return <Text dimColor>Waiting for the first context reading.</Text>
547
548    const draw = (row: Row, width: number) =>
549      fit(row, width).map((s, j) => <Text key={String(j)} color={s.c} dimColor={s.d} bold={s.b}>{s.t}</Text>)
550    // A row as a flex line, for surfaces that draw text in a proportional font.
551    const items = (row: Row) =>
552      row.map((s, j) => {
553        if ('group' in s) return <Box flexGrow={1} width={0} alignItems="center">{items(s.group)}</Box>
554        if ('cells' in s) {
555          // The engine takes a flexGrow up to 10000, so parts are weighed per thousand.
556          const total = Math.max(1, s.parts.reduce((n, p) => n + p.n, 0))
557          return <Box flexGrow={1} height={0.5}>{s.parts.map(p => <Box flexGrow={(p.n / total) * 1000} backgroundColor={p.c ?? TRACK} />)}</Box>
558        }
559        if ('spark' in s)
560          return (
561            <Box flexGrow={1} height={2} alignItems="flex-end">
562              {s.spark.map(v => <Box flexGrow={1} height={`${Math.max(1, Math.round((Math.min(v, s.max) / Math.max(1, s.max)) * 100))}%`} backgroundColor={s.c} />)}
563            </Box>
564          )
565        // As on the grid, a spacer keeps at least a cell, so a cut name never runs into the number after it.
566        if (s.fill) return <Box flexGrow={1} minWidth={1} />
567        const text = <Text key={String(j)} color={s.c} dimColor={s.d} bold={s.b} wrap="truncate-end">{!s.w ? s.t : s.right ? s.t.trim() : s.t.trimEnd()}</Text>
568        return s.w || s.keep ? <Box width={s.w} flexShrink={0} justifyContent={s.right ? 'flex-end' : 'flex-start'}>{text}</Box> : text
569      })
570    const line = (row: Row) => (row.length ? <Box alignItems="center">{items(row)}</Box> : <Box height={0.5} />)
571    const frame = (title: string, tone: string, rows: Row[], right = '') => {
572      if (!isGrid)
573        return (
574          <Box flexDirection="column" marginTop={2} borderStyle="round" borderColor={tone} borderDimColor>
575            <Box marginBottom={1}>
576              <Box flexShrink={0}>
577                <Text color={tone} bold>{title}</Text>
578              </Box>
579              <Box flexGrow={1} minWidth={1} />
580              {right ? <Text dimColor wrap="truncate-end">{right}</Text> : null}
581            </Box>
582            {rows.map(line)}
583          </Box>
584        )
585      const rule = Math.max(0, w - 6 - title.length - (right ? right.length + 2 : 0))
586      return (
587        <Box key={title} flexDirection="column" marginTop={1}>
588          <Text>
589            <Text color={tone} dimColor>╭─ </Text>
590            <Text color={tone} bold>{title}</Text>
591            <Text color={tone} dimColor> {'─'.repeat(rule)}</Text>
592            {right ? <Text dimColor> {right} </Text> : null}
593            <Text color={tone} dimColor>─╮</Text>
594          </Text>
595          {rows.map((row, i) => (
596            <Text key={String(i)}>
597              <Text color={tone} dimColor>│  </Text>
598              {draw(row, inner)}
599              <Text color={tone} dimColor>  │</Text>
600            </Text>
601          ))}
602          <Text color={tone} dimColor>╰{'─'.repeat(w - 2)}╯</Text>
603        </Box>
604      )
605    }
606
607    // Context: one stacked bar of what fills it, the compaction mark, a legend, the size over turns, the heaviest items.
608    const used = b.categories.filter(c => c.kind === 'used' && c.tokens > 0)
609    const bar: Seg[] = used.map(c => ({ t: '█'.repeat(cells(c.tokens, b.window, inner)), c: c.color }))
610    const filled = width(bar)
611    const mark = b.threshold === undefined ? -1 : Math.min(inner - 1, cells(b.threshold, b.window, inner))
612    for (let i = filled; i < inner; i++) bar.push(i === mark ? { t: '┊', c: 'warning' } : { t: '·', d: true, c: mark >= 0 && i > mark ? 'error' : undefined })
613    // Real bars mark the compaction point by tinting the room past it.
614    const usedTokens = used.reduce((n, c) => n + c.tokens, 0)
615    const free = Math.max(0, (b.threshold ?? b.window) - usedTokens)
616    const parts = [...used.map(c => ({ n: c.tokens, c: c.color })), { n: free }, { n: Math.max(0, b.window - usedTokens - free), c: 'diffRemovedDimmed' }]
617    // The legend is a two-column grid, names left and counts right-aligned in each column.
618    const colW = Math.floor((inner - 3) / 2)
619    const keys = [
620      ...used.map(c => ({ mark: '■', c: c.color, name: c.name, n: tokens(c.tokens) })),
621      ...(b.threshold === undefined ? [] : [{ mark: isGrid ? '┊' : '■', c: isGrid ? 'warning' : 'diffRemovedDimmed', name: 'compacts at', n: tokens(b.threshold) }]),
622    ]
623    const key = (k: (typeof keys)[number]): Row =>
624      spread([{ t: `${k.mark} `, c: k.c, keep: true }, { t: isGrid ? k.name.slice(0, colW - k.n.length - 3) : k.name }], [{ t: k.n, d: true, keep: true }], colW)
625    const legend: Row[] = []
626    for (let i = 0; i < keys.length; i += 2) {
627      const [a, z] = [keys[i], keys[i + 1]]
628      if (a) legend.push([{ group: key(a) }, ...(z ? [{ t: '   ' }, { group: key(z) }] : [{ group: [] }])])
629    }
630    const last = turns.at(-1)
631    const prev = turns.at(-2)
632    const delta = last !== undefined && prev !== undefined ? last - prev : undefined
633    const chartCols = inner - 12
634    const chart = turns.length < 2 ? [] : braille(turns, b.window, chartCols, 2)
635    const change: Seg = { t: `${delta !== undefined && delta >= 0 ? '+' : '-'}${tokens(Math.abs(delta ?? 0))}`, b: true }
636    const contextRows: Row[] = [
637      spread([{ t: tokens(b.tokens), b: true, keep: true }, { t: ` of ${tokens(b.window)}`, d: true }], [{ t: `${Math.round(b.percent)}%`, c: zone(b.percent), b: true, keep: true }], inner),
638      [],
639      [{ cells: bar, parts }],
640      [],
641      ...legend,
642      [],
643      ...(!chart.length
644        ? [[{ t: 'Size over turns shows after two turns.', d: true }]]
645        : isGrid
646          ? [
647              [{ t: chart[0] ?? '', c: 'suggestion' }, { t: '  ' }, change],
648              [{ t: chart[1] ?? '', c: 'suggestion' }, { t: '  last turn', d: true }],
649            ]
650          : [[{ spark: turns.slice(-chartCols * 2), max: b.window, c: 'suggestion' }, { t: '  ' }, change, { t: '  last turn', d: true }]]),
651      ...(b.heaviest.length ? [[] as Row, ...b.heaviest.map(item => spread([{ t: '▸ ', d: true }, { t: item.name }], [{ t: tokens(item.tokens), d: true, keep: true }], inner))] : []),
652    ]
653
654    // Limits: each window's meter, its reset, and whether the current pace lasts until then.
655    const limitRows: Row[] = []
656    const tones: string[] = []
657    const glance: Row = [{ t: 'ctx ', d: true }, { t: `${Math.round(b.percent)}%`, c: zone(b.percent), b: true, keep: true }]
658    for (const win of WINDOWS) {
659      const limit = r.limits.find(l => l.kind === win.kind)
660      if (!limit) continue
661      const p = pace(list, win.kind, now)
662      const tone = limit.percentUsed >= 80 || (p.kind === 'full' && p.inMs < 3_600_000) ? 'error' : p.kind === 'full' ? 'warning' : 'success'
663      tones.push(tone)
664      const pct = `${Math.round(limit.percentUsed)}%`.padStart(4)
665      const reset = `↻${duration(resetsIn(limit.resetsAt, now))}`.padEnd(7)
666      if (limitRows.length) limitRows.push([])
667      limitRows.push([
668        { t: `${win.label} `, b: true, w: 3 },
669        { cells: [{ t: '▕', d: true }, ...meter(limit.percentUsed, inner - 18), { t: '▏', d: true }], parts: zoneParts(limit.percentUsed) },
670        { t: ` ${pct} `, c: tone, b: true, w: 6, right: true },
671        { t: reset, d: true, w: 8, right: true },
672      ])
673      // The pace line starts under the meter: three cells on the grid, the label's column elsewhere.
674      const under: Seg = isGrid ? { t: '   ' } : { t: '', w: 3 }
675      limitRows.push(
676        p.kind === 'measuring'
677          ? [under, { t: 'measuring pace…', d: true }]
678          : p.kind === 'full'
679            ? [under, { t: `full in ~${duration(p.inMs)} at this pace`, c: tone }]
680            : [under, { t: 'lasts until the reset at this pace', d: true }],
681      )
682      glance.push({ t: `   ${win.label} `, d: true }, { t: `${Math.round(limit.percentUsed)}%`, c: tone, b: true, keep: true })
683    }
684    // toTimeString starts with the local HH:MM:SS.
685    const hhmm = (ms: number) => new Date(ms).toTimeString().slice(0, 5)
686    if (sent.length) limitRows.push([], ...sent.map(n => [{ t: `${hhmm(n.at)} `, d: true, keep: true }, { t: `note sent: ${n.text}` }]))
687    const limitTone = tones.includes('error') ? 'error' : tones.includes('warning') ? 'warning' : 'success'
688
689    // Tools and Requests share the rows left below; each keeps at least three.
690    // The top padding and glance row, each frame's two borders and top margin, and the Requests column header.
691    const fixed = 2 + (contextRows.length + 3) + (limitRows.length ? limitRows.length + 3 : 0) + 3 + 4
692    const left = Math.max(6, e.props.scroll.bodyRows - fixed)
693    const toolCount = Math.max(3, Math.ceil(left / 2))
694    const askCount = Math.max(3, left - toolCount)
695
696    const shown = [...calls.filter(t => t.ok === undefined), ...calls.filter(t => t.ok !== undefined)].slice(0, toolCount)
697    const running = calls.filter(t => t.ok === undefined).length
698    const toolRows: Row[] = shown.length
699      ? shown.map(t => {
700          const icon = t.ok === undefined ? { t: '◌', c: 'warning' } : t.ok ? { t: '✓', c: 'success' } : { t: '✗', c: 'error' }
701          const time = t.ms === undefined ? '…' : elapsed(t.ms)
702          // Off the grid the surface cuts the target, and the time never gives way.
703          return spread(
704            [{ ...icon, keep: true }, { t: ` ${(t.sub ? `↳${t.name}` : t.name).padEnd(7)} `, b: !t.sub, d: t.sub, w: 11 }, { t: isGrid ? t.target.slice(0, inner - 16) : t.target, d: true }],
705            [{ t: time, d: true, keep: true }],
706            inner,
707          )
708        })
709      : [[{ t: 'No tool calls yet.', d: true }]]
710    const toolTone = shown.find(t => t.ok !== undefined)?.ok === false ? 'error' : 'success'
711
712    // A right-aligned column n wide.
713    const num = (t: string, n: number, s: Omit<Seg, 't'> = {}): Seg => ({ ...s, t: t.padStart(n), w: n, right: true })
714    // The loop column; off the grid it gives way, so the four numbers stay inside a narrow pane.
715    const loop = (s: Seg): Row => (isGrid ? [s] : [{ ...s, t: s.t.trimEnd(), w: undefined }, { t: '', fill: true }])
716    const askRows: Row[] = asks.length
717      ? [
718          [...loop({ t: 'loop'.padEnd(10), d: true, w: 10 }), num('in', 6, { d: true }), num('out', 6, { d: true }), num('cache', 7, { d: true }), num('time', 7, { d: true })],
719          ...asks.slice(0, askCount).map(q => {
720            const hit = q.input ? Math.round((q.cached / q.input) * 100) : 0
721            const cacheTone = hit < 20 ? 'error' : hit < 50 ? 'warning' : undefined
722            return [
723              ...loop({ t: isGrid ? q.agent.padEnd(10).slice(0, 10) : q.agent, b: q.agent === 'main', d: q.agent !== 'main', w: 10 }),
724              num(tokens(q.input), 6),
725              num(tokens(q.output), 6),
726              num(`${hit}%`, 7, { c: cacheTone, d: cacheTone === undefined }),
727              num(elapsed(q.ms), 7, { d: true }),
728            ]
729          }),
730        ]
731      : [[{ t: 'No model requests yet.', d: true }]]
732    const lastHit = asks[0] && asks[0].input ? asks[0].cached / asks[0].input : 1
733    const model = asks[0]?.model.replace(/^claude-/, '') ?? ''
734
735    return (
736      <Box flexDirection="column" paddingTop={1}>
737        {isGrid ? <Text>{draw(glance, w - 3)}</Text> : line(glance)}
738        {frame('Context', zone(b.percent), contextRows)}
739        {limitRows.length ? frame('Limits', limitTone, limitRows) : null}
740        {frame('Tools', toolTone, toolRows, running ? `${running} running` : '')}
741        {frame('Requests', lastHit < 0.5 ? 'warning' : 'success', askRows, model)}
742      </Box>
743    )
744  })
745}
746
types/index.d.ts 29 lines
1export type MeterLimit = { kind: string; percentUsed: number; resetsAt?: string }
2export type MeterReading = { context: number | null; limits: MeterLimit[] }
3export type MeterCategory = { name: string; tokens: number; color: string; kind: string }
4export type MeterItem = { name: string; tokens: number }
5export type MeterBreakdown = { percent: number; tokens: number; window: number; threshold?: number; categories: MeterCategory[]; heaviest: MeterItem[] }
6export type MeterSample = { kind: string; at: number; pct: number; resetsAt?: string }
7export type MeterNote = { at: number; text: string }
8export type MeterTool = { id: string; name: string; target: string; sub: boolean; at: number; ms?: number; ok?: boolean }
9export type MeterRequest = { at: number; agent: string; input: number; cached: number; output: number; ms: number; model: string }
10export type MeterReset = { mode: 'compact'; next?: string; wait?: true; needsText?: true } | { mode: 'clear'; handoff: string }
11export type MeterResume = { alone?: string; carried: string; ready?: true; taken?: true }
12
13declare module 'claude-code' {
14  interface PluginState {
15    'session-meter': {
16      reading: MeterReading
17      fired: string[]
18      breakdown: MeterBreakdown | null
19      history: number[]
20      samples: MeterSample[]
21      notes: MeterNote[]
22      tools: MeterTool[]
23      requests: MeterRequest[]
24      pending: MeterReset | null
25      resume: MeterResume | null
26    }
27  }
28}
29