SLOPSHOPPER

context-bar

A footer showing the model and effort, how full the context window is, and the prompt cache, with one-click compact and clear

bandspinnertimer
v0.5.1MITupdated 2026-10-17ziedgithub/claude-code-mods/context-bar
A shopper browsing a rack in a slop shop
README

context-bar

A footer for Claude Code. In the slot right of the hint line under the prompt, it shows:

context-bar, a rendered preview

  • Cache: how much of the last prompt the cache served, and roughly how long until it expires: 99% ~58m, then cold once it has lapsed or after a compaction.
  • Whether your account caches for 5 minutes or an hour is worked out from the requests themselves, and remembered between sessions. With warm-compact installed, the countdown uses the duration warm-compact worked out instead, so the two never disagree.
  • With warm-compact on, a mark after the countdown says what it will do if you stay away: 99% ~58m ⇊ for a compaction, ♨ for a keep warm renewal. Hover the block to see when: ⇊ Warm compact runs in ~57m, before the cache goes cold.
  • When another mod renews the cache in the background (keep warm in warm-compact, or any mod that does the same), the countdown starts over too. The bar sees the renewal itself, so it does not need that mod installed. If the account keeps those renewals for only 5 minutes, the bar works that out the first time the cache turns out to be gone, and counts down 5 minutes after each renewal from then on.
  • Model and effort: ◆ Opus 5.5 (1M) ▆ high, colored by model family and by effort level. Click either one to get a row of chips and pick another. This runs /model or /effort for you.
  • Context: how full the context window is, in a bar that is green under 30%, orange under 60% and red after that. It moves after every response, including each step of a long turn with many tool calls, rather than waiting for the turn to end.
  • Hover the bar to see what fills the window, over the three rows of the prompt above it: the same categories /context lists (system prompt, tools, memory files, messages, free space, the compaction buffer), each in tokens and as a share of the window, in columns three rows tall so the band above the prompt never covers them. The figures are Claude Code's own estimates, refreshed with every request.
  • When a step adds a lot, such as a large file read, the bar rises as soon as the next request goes out, marked with ~, and the response then replaces it with the measured figure. That early figure is the last measured one plus what Claude Code's local count says was added since. It only shows when it raises the percentage, so small steps don't make the ~ blink.
  • After a compaction or a /clear, and in a fresh session, Claude Code has no measured figure until the next response. Meanwhile the bar shows Claude Code's own local estimate (the one /context makes), marked with ~.
  • Where an organization manages Claude Code, plugins are not told of a compaction. The bar notices it anyway, within a second, from Claude Code dropping its measured figure.
  • Compact ⇊ and clear ⌫: one click asks first (clear context? yes no). The question goes away by itself after five seconds, so a stray click does nothing.
  • Subagents: open a subagent's transcript from the tasks list and the footer switches to that agent: ↳ Explore ◆ Haiku 4.5 Context ██░░░░ 15%. It shows the model and effort the agent's last request used, and how full its own context window is. These are for reading only: the model and effort can't be clicked, and the cache, compact and clear are hidden, since they belong to the main conversation. Go back to the main conversation and the footer goes back too.
  • The agent's context fills in after its first response. When the agent runs on the session's model, the bar uses the session's window size. On any other model it assumes 200K, or 1M for a [1m] model.

In Claude Code Desktop, which shows the model, the effort and the context of its own and draws this slot as one short line, the footer is a single line of what the app lacks: Context 10% · Cache 99% ~58m.

On a narrow terminal the labels shorten, and when one row can't hold everything the blocks stack.

What other mods put in the same slot goes at the right end of the row, along with the engine's own mode labels. warm-compact's chips sit on their own row under the prompt hint.

Install

claude plugin marketplace add ziedgithub/claude-code-mods && claude plugin install context-bar@zied-mods

Needs Claude Code 2.1.296 or later.

Then restart Claude Code.

See the repository README for running it from a clone.

Source 5 files
hooks/register.tsx 962 lines
1import { atom, memberOf, read, update } from 'claude-code'
2import type { ContextCategory, EngineInterface, Register, Timer } from 'claude-code'
3
4import type { AgentStats, CacheInfo, CacheTtl, ContextAction, ContextFill, ContextRow, LearnedTtl, ModelInfo, Question, Setting, Upcoming } from '../types'
5import { COLD_TEXT, formatRemaining, hitColor, remainingMs, ttlOf } from './cache'
6import { DEFAULT_TTL, hitPercent, inferRenewTtl, inferTtl, inputTokens, isCacheTtl } from './shared/cache-ttl'
7import { tap } from './shared/stream'
8
9const BAR_MIN = 3
10const BAR_MAX = 8
11const BAR_SHARE = 0.05
12const COMPACT_BELOW = 80
13const DEFAULT_COLUMNS = 120
14const BLOCK_GAP = 2
15const EFFORT_GAP = 2
16const GREEN_BELOW = 30
17const ORANGE_BELOW = 60
18const MODEL_POLL_MS = 1000
19const FILL_POLL_MS = 1000
20const CACHE_TICK_MS = 1000
21const CACHE_TTL_KEY = 'cacheTtl'
22const RENEW_TTL_KEY = 'renewTtl'
23const COLD_COLOR = '#58a6ff'
24const CONFIRM_MS = 5000
25const CHOOSE_MS = 10000
26const ACTION_GAP = 2
27const MODEL_ICON = '◆'
28const NEUTRAL = '#8b949e'
29// One glyph each, one cell wide, drawn on a chip of the action's color: a Button takes no
30// color of its own at rest, so the color is the Box behind it
31const ACTIONS: Record<ContextAction, { icon: string; question: string; color: string }> = {
32  compact: { icon: '⇊', question: 'compact context?', color: '#1f6feb' },
33  clear: { icon: '⌫', question: 'clear context?', color: '#da3633' },
34}
35const NO_COLOR = '#6e7681'
36const CONTEXT_ACTIONS: readonly ContextAction[] = ['compact', 'clear']
37// `/effort`'s answer as the transcript keeps it: `Set effort level to high (this session only): …`
38const EFFORT_SET = /<local-command-stdout>Set effort level to ([a-z]+)\b/
39// The same answer as `$.command.run` returns it, before the transcript wraps it
40const EFFORT_ANSWER = /^Set effort level to ([a-z]+)\b/
41
42const MODEL_COLORS: Record<string, string> = {
43  opus: '#bc8cff',
44  sonnet: '#58a6ff',
45  haiku: '#7ee787',
46  fable: '#f778ba',
47}
48
49const EFFORT_STYLES: Record<string, { icon: string; color: string }> = {
50  low: { icon: '▂', color: '#8b949e' },
51  medium: { icon: '▄', color: '#39c5bb' },
52  high: { icon: '▆', color: '#e3b341' },
53  xhigh: { icon: '▇', color: '#ffa657' },
54  max: { icon: '█', color: '#ff7b72' },
55}
56
57// The aliases `/model` takes, each switching to the latest model of its family
58const MODEL_CHOICES = ['opus', 'sonnet', 'haiku', 'fable']
59// The chips' backgrounds are darker than the text colors above, so the terminal's own text
60// color, the only one a Button takes at rest, stays readable on them
61const MODEL_CHIPS: Record<string, string> = {
62  opus: '#8957e5',
63  sonnet: '#1f6feb',
64  haiku: '#238636',
65  fable: '#bf4b8a',
66}
67const EFFORT_CHIPS: Record<string, string> = {
68  low: '#6e7681',
69  medium: '#1b7c83',
70  high: '#9e6a03',
71  xhigh: '#bd561d',
72  max: '#da3633',
73}
74const CURRENT_MARK = '✔'
75const CLOSE_ICON = '✕'
76// What a subagent's footer starts with, so its figures are not taken for the conversation's
77const AGENT_ICON = '↳'
78const AGENT_FALLBACK = 'agent'
79const AGENT_LABEL_MAX = 20
80// The window of a model other than the session's, which the engine reports for its own alone
81const DEFAULT_WINDOW = 200_000
82const LONG_WINDOW = 1_000_000
83// The card over the bar, a cell per category of what fills the window, in columns as tall as
84// the rows it has: the prompt and its two rules, since the band above them paints over it
85const CARD_ROWS = 3
86const ROW_GLYPHS: Record<ContextRow['kind'], string> = { used: '■', free: '□', buffer: '▒' }
87// What warm-compact has in store for the pause, beside the countdown it runs on
88const UPCOMING_STYLES: Record<Upcoming['kind'], { icon: string; color: string }> = {
89  compact: { icon: '⇊', color: '#58a6ff' },
90  renew: { icon: '♨', color: '#ffa657' },
91}
92
93const fill = atom({ plugin: 'context-bar', key: 'fill' } as const, null)
94const model = atom({ plugin: 'context-bar', key: 'model' } as const, null)
95const asking = atom({ plugin: 'context-bar', key: 'asking' } as const, null)
96const cache = atom({ plugin: 'context-bar', key: 'cache' } as const, null)
97const viewing = atom({ plugin: 'context-bar', key: 'viewing' } as const, null)
98// One member per agent, keyed by its id
99const agents = atom({ plugin: 'context-bar', key: 'agents' } as const, null)
100const breakdown = atom({ plugin: 'context-bar', key: 'breakdown' } as const, null)
101// warm-compact's, while it is loaded: it acts on the cache, so the countdown runs on its figures
102const warmTtl = atom({ plugin: 'warm-compact', key: 'ttl' } as const, null)
103const warmUpcoming = atom({ plugin: 'warm-compact', key: 'upcoming' } as const, null)
104
105// The bar takes a twentieth of the terminal width, so it follows resizes
106export const barWidthFor = (columns: number): number =>
107  Math.min(BAR_MAX, Math.max(BAR_MIN, Math.round(columns * BAR_SHARE)))
108
109// The blocks stack, right-aligned, when one row cannot hold them
110export const fitsInRow = (columns: number, rightLength: number): boolean => rightLength <= columns
111
112export const colorFor = (percent: number): string => {
113  if (percent < GREEN_BELOW) return '#3fb950'
114  if (percent < ORANGE_BELOW) return '#ff9500'
115  return '#f85149'
116}
117
118const capitalize = (word: string): string => word.charAt(0).toUpperCase() + word.slice(1)
119
120// `claude-sonnet-5-5` -> `Sonnet 5.5`, `claude-haiku-4-5-20251001` -> `Haiku 4.5`,
121// `claude-3-5-sonnet-20241022` -> `Sonnet 3.5`; anything else is left as received
122export const displayModelName = (id: string): string => {
123  const isLongContext = id.endsWith('[1m]')
124  const bare = id.replace(/\[1m\]$/, '')
125  const suffix = isLongContext ? ' (1M)' : ''
126  const modern = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$/.exec(bare)
127
128  if (modern !== null) {
129    const [, family = '', major, minor] = modern
130    return `${capitalize(family)} ${minor === undefined ? major : `${major}.${minor}`}${suffix}`
131  }
132
133  const legacy = /^claude-(\d+)(?:-(\d{1,2}))?-([a-z]+)(?:-\d{8})?$/.exec(bare)
134
135  if (legacy !== null) {
136    const [, major, minor, family = ''] = legacy
137    return `${capitalize(family)} ${minor === undefined ? major : `${major}.${minor}`}${suffix}`
138  }
139
140  return id
141}
142
143export type ModelParts = {
144  name: string
145  family: string
146  modelColor: string
147  effort: { icon: string; color: string; label: string } | null
148  length: number
149}
150
151// An effort neither the settings nor a request has told yet is shown as `…`
152export const modelParts = (info: ModelInfo): ModelParts => {
153  const name = displayModelName(info.name)
154  const family = (name.split(' ')[0] ?? '').toLowerCase()
155  const modelColor = MODEL_COLORS[family] ?? NEUTRAL
156
157  let effort: ModelParts['effort'] = null
158
159  if (!info.isEffortKnown) {
160    effort = { icon: '', color: NEUTRAL, label: '…' }
161  } else if (info.effort !== null) {
162    const style = EFFORT_STYLES[info.effort] ?? { icon: '●', color: NEUTRAL }
163    effort = { ...style, label: info.effort }
164  }
165
166  const effortLength =
167    effort === null
168      ? 0
169      : EFFORT_GAP + (effort.icon === '' ? 0 : effort.icon.length + 1) + effort.label.length
170
171  return { name, family, modelColor, effort, length: MODEL_ICON.length + 1 + name.length + effortLength }
172}
173
174const isRecord = (value: unknown): value is Record<string, unknown> =>
175  typeof value === 'object' && value !== null
176
177// What the settings ask of a model until a request reports it: the model's own
178// `modelSettings` row, else the global `effortLevel`. A level the model does not take is
179// only corrected by the next request
180export const configuredEffort = (settings: Readonly<Record<string, unknown>>, modelId: string): string | null => {
181  const rows = settings.modelSettings
182  const row = isRecord(rows) ? rows[modelId.replace(/\[1m\]$/, '')] : undefined
183  const own = isRecord(row) ? row.effortLevel : undefined
184  const level = typeof own === 'string' ? own : settings.effortLevel
185  return typeof level === 'string' && level in EFFORT_STYLES ? level : null
186}
187
188export const withEffort = (name: string, effort: string | null): ModelInfo => ({
189  name,
190  effort,
191  isEffortKnown: effort !== null,
192  isEffortPinned: false,
193})
194
195export const pinEffort = (prev: ModelInfo | null, effort: string): ModelInfo | null =>
196  prev === null ? prev : { ...prev, effort, isEffortKnown: true, isEffortPinned: true }
197
198// `/effort` sets the level for the whole session, so a model switch keeps it; otherwise the
199// new model starts at what the settings ask of it
200export const switchedModel = (prev: ModelInfo | null, name: string, configured: string | null): ModelInfo =>
201  prev !== null && prev.isEffortPinned ? { ...prev, name } : withEffort(name, configured)
202
203const knownLevel = (level: string | undefined): string | null =>
204  level !== undefined && level in EFFORT_STYLES ? level : null
205
206// The level `/effort` set, read from its answer row; null for any other row
207export const effortFromRow = (blocks: readonly { type: string }[]): string | null => {
208  for (const block of blocks) {
209    const text = 'text' in block && typeof block.text === 'string' ? block.text : ''
210    const level = knownLevel(EFFORT_SET.exec(text)?.[1])
211    if (level !== null) return level
212  }
213  return null
214}
215
216// The level `/effort` set, read from the answer `$.command.run` returns; null for a refusal
217export const effortFromAnswer = (text: string | undefined): string | null =>
218  text === undefined ? null : knownLevel(EFFORT_ANSWER.exec(text)?.[1])
219
220// /clear ends the session and the next one starts with empty state, while the engine keeps
221// the model and its effort: they are carried over from the end to the next refresh
222let carried: ModelInfo | null = null
223
224const refreshModel = async ($: EngineInterface): Promise<void> => {
225  const name = await $.session.model()
226  const prev = await read($, model)
227  if (prev !== null && prev.name === name) return
228  const kept = prev === null && carried?.name === name ? carried : null
229  carried = null
230  const effort = configuredEffort(await $.settings.read(), name)
231  await update($, model, () => kept ?? switchedModel(prev, name, effort))
232}
233
234// A turn with no response, an interrupted one, leaves the last fill as it was
235const refreshFill = async ($: EngineInterface): Promise<void> => {
236  const { context } = await $.session.usage()
237  await update($, fill, prev => toFill(context) ?? prev)
238}
239
240// The window's categories as /context lists them, less the tool schemas loaded on demand,
241// which stay outside it, and the empty ones
242export const contextRows = (categories: readonly ContextCategory[], window: number): ContextRow[] =>
243  categories.flatMap(({ name, tokens, color, kind }) =>
244    kind === 'deferred' || tokens <= 0 ? [] : [{ name, tokens, percent: Math.round((tokens / window) * 100), color, kind }],
245  )
246
247// The engine's local count, as /context makes it with no request. What fills the window, by
248// category, goes to the card over the bar
249const countTokens = async ($: EngineInterface): Promise<{ tokens: number; window: number } | null> => {
250  const { context } = await $.session.usage({ breakdown: 'summary' })
251  const counted = context.breakdown
252  if (counted === undefined) return null
253  const rows = contextRows(counted.categories, counted.maxTokens)
254  if (JSON.stringify(await read($, breakdown)) !== JSON.stringify(rows)) await update($, breakdown, () => rows)
255  return { tokens: counted.totalTokens, window: context.window }
256}
257
258// The engine measures the window on each response, and a compaction or a /clear leaves its
259// last measure behind: until the next response the bar shows the engine's own estimate
260const estimateFill = async ($: EngineInterface): Promise<void> => {
261  const counted = await countTokens($)
262  if (counted !== null) await update($, fill, () => estimatedFill(counted.tokens, counted.window))
263}
264
265// A fresh session, and one `/clear` started, has no fill until its first response
266const estimateMissingFill = async ($: EngineInterface): Promise<void> => {
267  if ((await read($, fill)) === null) await estimateFill($)
268}
269
270// The local count as a request left, and what its response then measured. The count is not
271// the measure, but what it grows by is near what the conversation grew by
272type Baseline = { counted: number; measured: number }
273let baseline: Baseline | null = null
274
275// The engine takes the compacted or cleared conversation some time after the hooks have
276// returned, and until then its estimate still counts the old one, matched to the old measure:
277// the bar would keep its figure, with a `~`. It drops that measure once it has the new one,
278// so the estimate waits for that, on the free figures, and after TAKE_WAIT_MS stops waiting. A
279// response that measured the window meanwhile has the last word
280const TAKE_POLL_MS = 50
281const TAKE_WAIT_MS = 10_000
282let isAwaitingTake = false
283
284const estimateOnceTaken = async ($: EngineInterface, waitedMs = 0): Promise<void> => {
285  if (!isAwaitingTake) return
286  const { context } = await $.session.usage()
287  if (context.percent !== undefined && waitedMs < TAKE_WAIT_MS) {
288    $.clock.after(TAKE_POLL_MS, () => void estimateOnceTaken($, waitedMs + TAKE_POLL_MS))
289    return
290  }
291  const counted = await countTokens($)
292  await update($, fill, prev =>
293    !isAwaitingTake || counted === null ? prev : estimatedFill(counted.tokens, counted.window),
294  )
295  isAwaitingTake = false
296}
297
298const estimateWhenTaken = ($: EngineInterface): void => {
299  isAwaitingTake = true
300  // A drop to come is told of only where there is a measure to drop
301  isDropTold = wasMeasured
302  $.clock.after(0, () => void estimateOnceTaken($))
303}
304
305// Where an organization manages Claude Code, `session.compact` passes over the plugins a person
306// installs, and nothing tells the footer of a compaction. The engine still drops its measure
307// once it has taken the compacted conversation: the clock sees the measure go, and the bar
308// takes it as a compaction. A drop a hook already told of is left to that hook
309let wasMeasured = false
310let isDropTold = false
311
312const followMeasure = async ($: EngineInterface): Promise<void> => {
313  const { context } = await $.session.usage()
314  const isDropped = wasMeasured && context.percent === undefined
315  wasMeasured = context.percent !== undefined
316  if (!isDropped) return
317  if (isDropTold) {
318    isDropTold = false
319    return
320  }
321  baseline = null
322  await update($, cache, prev => (prev === null || prev.requestAt === null ? prev : { ...prev, requestAt: null }))
323  await estimateFill($)
324}
325
326// The last measure, and what the conversation grew by since its request, as counted locally
327export const earlyTokens = (base: Baseline | null, counted: number): number | null =>
328  base === null ? null : base.measured + Math.max(0, counted - base.counted)
329
330// An early figure is shown only where it raises the bar: one that would not move the
331// percentage leaves the measured figure, so the `~` comes and goes only on a real jump
332export const raisedFill = (prev: ContextFill | null, early: ContextFill): ContextFill | null =>
333  prev !== null && early.percent <= prev.percent ? prev : early
334
335export const isAction = (question: Question): question is ContextAction => question in ACTIONS
336
337// A click only asks: the question that replaces the icons runs the command on `yes`, and
338// drops back to the icons after CONFIRM_MS, so a stray click never clears or compacts. The
339// choices that replace the model or the effort close likewise after CHOOSE_MS
340let askTimer: Timer | null = null
341
342// The cache's countdown is drawn from the clock's last reading, and the footer drawn again
343// only when its text changes: once a minute, then once a second for the last one
344let cacheTtl: CacheTtl = DEFAULT_TTL
345// How long a fork's entry lasts, once a request after one has told; until then, a request's
346let renewTtl: CacheTtl | null = null
347let cacheNow = 0
348let shownRemaining = ''
349
350// The agent in view as the band last told it; undefined until it tells after a load, so a
351// reload never keeps a view the person has since left
352let viewedAgent: string | null | undefined
353
354// The TTLs the countdown runs on: warm-compact's while it is loaded, else the footer's own
355const ttlsOf = async ($: EngineInterface): Promise<LearnedTtl> =>
356  (await read($, warmTtl)) ?? { cache: cacheTtl, renew: renewTtl }
357
358const tickCache = async ($: EngineInterface): Promise<void> => {
359  cacheNow = await $.clock.now()
360  const info = await read($, cache)
361  // A model switch makes no request, so the clock sees it too
362  const name = (await read($, model))?.name ?? null
363  let text = ''
364  if (info !== null) text = name !== null && name !== info.model ? COLD_TEXT : formatRemaining(remainingMs(info, ttlOf(info, await ttlsOf($)), cacheNow))
365  if (text === shownRemaining) return
366  shownRemaining = text
367  $.ui.invalidate('ui.render')
368}
369
370// The engine keeps its TTL to itself: a request after a long enough pause tells it, and it
371// is kept between sessions since it holds for the account
372const learnTtl = async ($: EngineInterface, ttl: CacheTtl | null): Promise<void> => {
373  if (ttl === null || ttl === cacheTtl) return
374  cacheTtl = ttl
375  await $.store.set(CACHE_TTL_KEY, ttl)
376}
377
378// A fork's entry is told apart the same way, by the first request after a long enough pause.
379// On an account that caches for five minutes it can last no less
380const learnRenewTtl = async ($: EngineInterface, ttl: CacheTtl | null): Promise<void> => {
381  if (ttl === null || ttl === renewTtl || cacheTtl !== '1h') return
382  renewTtl = ttl
383  await $.store.set(RENEW_TTL_KEY, ttl)
384}
385
386// The first request after a pause tells how long the entry the last read left lasts, a fork's
387// or a request's. While warm-compact is loaded it learns that itself, and the countdown runs on
388// its figures, so the two never disagree
389// `cacheRead`: what the request read from the cache, out of the `tokens` it was answered over,
390// against the entry `prev` left
391const learnFrom = async ($: EngineInterface, prev: CacheInfo, model: string, cacheRead: number, tokens: number, requestAt: number): Promise<void> => {
392  if ((await read($, warmTtl)) !== null) return
393  if (prev.isFork !== true) return learnTtl($, inferTtl({ at: prev.requestAt, model: prev.model, tokens: prev.tokens }, model, cacheRead, tokens, requestAt))
394  if (prev.requestAt !== null && prev.model === model) await learnRenewTtl($, inferRenewTtl(prev.requestAt, prev.tokens, cacheRead, tokens, requestAt))
395}
396
397const ask = async ($: EngineInterface, question: Question): Promise<void> => {
398  askTimer?.cancel()
399  await update($, asking, () => question)
400  askTimer = $.clock.after(isAction(question) ? CONFIRM_MS : CHOOSE_MS, () => void update($, asking, () => null))
401}
402
403const settle = async ($: EngineInterface): Promise<void> => {
404  askTimer?.cancel()
405  askTimer = null
406  await update($, asking, () => null)
407}
408
409const confirm = async ($: EngineInterface, action: ContextAction): Promise<void> => {
410  await settle($)
411  await $.command.run({ command: action })
412}
413
414// `/model <alias>` and `/effort <level>` save the pick as the default, as typed. A plugin's
415// run skips its own `command.run` hooks, so the footer is updated from the answer here
416const choose = async ($: EngineInterface, setting: Setting, choice: string): Promise<void> => {
417  await settle($)
418  const { text } = await $.command.run({ command: setting, args: choice })
419
420  if (setting === 'model') {
421    await refreshModel($)
422    return
423  }
424
425  const effort = effortFromAnswer(text)
426  if (effort !== null) await update($, model, prev => pinEffort(prev, effort))
427}
428
429export const choicesFor = (setting: Setting): readonly string[] =>
430  setting === 'model' ? MODEL_CHOICES : Object.keys(EFFORT_STYLES)
431
432const choiceLabel = (choice: string, current: string | null): string =>
433  choice === current ? `${choice} ${CURRENT_MARK}` : choice
434
435// The label pads the glyph so the whole chip, not its one middle cell, takes the click
436export const chipLabel = (text: string): string => ` ${text} `
437
438export const chooserLength = (setting: Setting, current: string | null): number =>
439  `${setting}:`.length +
440  choicesFor(setting).reduce((sum, choice) => sum + 1 + chipLabel(choiceLabel(choice, current)).length, 0) +
441  1 +
442  chipLabel(CLOSE_ICON).length
443
444export const actionsLength = (pending: ContextAction | null): number =>
445  pending === null
446    ? CONTEXT_ACTIONS.reduce((sum, action) => sum + chipLabel(ACTIONS[action].icon).length, 0) +
447      ACTION_GAP * (CONTEXT_ACTIONS.length - 1)
448    : ACTIONS[pending].question.length + ` ${chipLabel('yes')} ${chipLabel('no')}`.length
449
450// `percent` is absent until the first response of a fresh or just-compacted window
451export const toFill = (context: {
452  percent?: number
453  tokens?: number
454  window: number
455}): ContextFill | null =>
456  context.percent === undefined || context.tokens === undefined
457    ? null
458    : { percent: context.percent, tokens: context.tokens, window: context.window, isEstimate: false }
459
460export const estimatedFill = (tokens: number, window: number): ContextFill => ({
461  percent: Math.min(100, Math.round((tokens / window) * 100)),
462  tokens,
463  window,
464  isEstimate: true,
465})
466
467const bareModel = (id: string): string => id.replace(/\[1m\]$/, '')
468
469// A subagent on the session's model has the session's window; another model, its own default
470export const agentWindow = (agentModel: string, sessionModel: string, sessionWindow: number): number => {
471  if (agentModel.endsWith('[1m]')) return LONG_WINDOW
472  return bareModel(agentModel) === bareModel(sessionModel) ? sessionWindow : DEFAULT_WINDOW
473}
474
475// What the request was answered over: uncached, cache-read and cache-written input alike
476export { inputTokens }
477
478// A response's own count of what it was answered over, as the engine measures it at turn end
479export const measuredFill = (tokens: number, window: number): ContextFill => ({
480  ...estimatedFill(tokens, window),
481  isEstimate: false,
482})
483
484export const agentFill = (stats: AgentStats | null): ContextFill | null =>
485  stats === null || stats.tokens === null ? null : measuredFill(stats.tokens, stats.window)
486
487// A subagent's effort is the one its request named, never a setting the person pinned
488export const agentModel = (stats: AgentStats | null): ModelInfo | null =>
489  stats === null ? null : { name: stats.model, effort: stats.effort, isEffortKnown: true, isEffortPinned: false }
490
491export const agentLabel = (info: { type: string; name?: string } | undefined): string => {
492  const label = info === undefined ? AGENT_FALLBACK : info.type === 'teammate' ? (info.name ?? info.type) : info.type
493  return label.length > AGENT_LABEL_MAX ? `${label.slice(0, AGENT_LABEL_MAX - 1)}…` : label
494}
495
496// 850, 3.1k, 98k, 1.2M: as short as the card's column allows
497export const tokenText = (tokens: number): string => {
498  if (tokens < 1000) return String(tokens)
499  if (tokens < 10_000) return `${(tokens / 1000).toFixed(1)}k`
500  if (tokens < 1_000_000) return `${Math.round(tokens / 1000)}k`
501  return `${(tokens / 1_000_000).toFixed(1)}M`
502}
503
504export type CardCell = { glyph: string; color: string; text: string; isDim: boolean }
505
506// The card's lines, the categories down each column of CARD_ROWS, every column lined up and every
507// line padded to the card's full width: drawn over the rows above the footer, it covers every
508// cell of them it spans. The window left and the compaction buffer are dimmed
509export const cardLines = (rows: readonly ContextRow[]): CardCell[][] => {
510  const columns: ContextRow[][] = []
511  for (let i = 0; i < rows.length; i += CARD_ROWS) columns.push(rows.slice(i, i + CARD_ROWS))
512  const cells = columns.map(column => {
513    const nameWidth = Math.max(...column.map(row => row.name.length))
514    const tokenWidth = Math.max(...column.map(row => tokenText(row.tokens).length))
515    return column.map(row => ({
516      glyph: ` ${ROW_GLYPHS[row.kind]}`,
517      color: row.color,
518      text: ` ${row.name.padEnd(nameWidth)}  ${tokenText(row.tokens).padStart(tokenWidth)} ${`${row.percent}%`.padStart(4)} `,
519      isDim: row.kind !== 'used',
520    }))
521  })
522  return Array.from({ length: Math.min(rows.length, CARD_ROWS) }, (_, line) =>
523    cells.map(column => {
524      const [first] = column
525      return column[line] ?? { glyph: '', color: first?.color ?? '', text: ' '.repeat((first?.glyph.length ?? 0) + (first?.text.length ?? 0)), isDim: true }
526    }),
527  )
528}
529
530// What the card over warm-compact's mark says: what runs, and when
531export const upcomingText = (coming: Upcoming, now: number): string => {
532  const ms = coming.at - now
533  const when = ms <= 0 ? 'now' : `in ${formatRemaining(ms)}`
534  const { icon } = UPCOMING_STYLES[coming.kind]
535  return coming.kind === 'compact'
536    ? `${icon} Warm compact runs ${when}, before the cache goes cold`
537    : `${icon} Keep warm renews the cache ${when}`
538}
539
540export type DesktopSegment = { text: string; color?: string }
541
542// The desktop's line: the agent in view, how full its window is and the cache, each short
543export const desktopSegments = (parts: {
544  agent: string | null
545  fill: ContextFill | null
546  cached: CacheInfo | null
547  remaining: string | null
548  upcoming: Upcoming | null
549}): DesktopSegment[] => {
550  const segments: DesktopSegment[] = []
551  if (parts.agent !== null) segments.push({ text: `${AGENT_ICON} ${parts.agent}` })
552  if (parts.fill !== null) {
553    const percent = Math.min(100, Math.max(0, parts.fill.percent))
554    segments.push({ text: `Context ${parts.fill.isEstimate ? '~' : ''}${percent}%`, color: colorFor(percent) })
555  }
556  if (parts.cached !== null && parts.remaining !== null) {
557    const mark = parts.upcoming === null ? '' : ` ${UPCOMING_STYLES[parts.upcoming.kind].icon}`
558    segments.push({
559      text: `Cache ${parts.cached.hitPercent}% ${parts.remaining}${mark}`,
560      color: parts.remaining === COLD_TEXT ? COLD_COLOR : hitColor(parts.cached.hitPercent),
561    })
562  }
563  return segments
564}
565
566export const register: Register = on => {
567  on('session.start', async ($, e, next) => {
568    const { context } = await $.session.usage()
569    // A reload fires session.start before any new response: keep the last known fill
570    await update($, fill, prev => toFill(context) ?? prev)
571    const name = await $.session.model()
572    const effort = configuredEffort(await $.settings.read(), name)
573    // A reload keeps what a request or `/effort` told about the same model
574    await update($, model, prev =>
575      prev !== null && prev.name === name && prev.isEffortKnown ? prev : withEffort(name, effort),
576    )
577    // `/model`, its picker and alt+p switch the model without any event or request
578    $.clock.every(MODEL_POLL_MS, () => void refreshModel($))
579    wasMeasured = context.percent !== undefined
580    isDropTold = false
581    $.clock.every(FILL_POLL_MS, () => void estimateMissingFill($).then(() => followMeasure($)))
582    const stored = await $.store.get(CACHE_TTL_KEY)
583    if (isCacheTtl(stored)) cacheTtl = stored
584    const storedRenewTtl = await $.store.get(RENEW_TTL_KEY)
585    if (isCacheTtl(storedRenewTtl)) renewTtl = storedRenewTtl
586    cacheNow = await $.clock.now()
587    $.clock.every(CACHE_TICK_MS, () => void tickCache($))
588    // A resumed session has a measure and no breakdown until its first request
589    $.clock.after(0, () => void countTokens($))
590    viewedAgent = undefined
591    return next(e)
592  })
593
594  // Only the band above the prompt is told which transcript is on screen, and told again on
595  // each switch: the footer follows it from there. It draws nothing of its own, and as a
596  // drawing writes no state, the footer is told from the clock
597  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
598    const agentId = e.props.view?.agentId ?? null
599    if (agentId !== viewedAgent) {
600      viewedAgent = agentId
601      const label = agentId === null ? '' : agentLabel((await $.agent.list()).find(agent => agent.id === agentId))
602      $.clock.after(0, () => void update($, viewing, () => (agentId === null ? null : { id: agentId, label })))
603    }
604    return next(e)
605  })
606
607  // The card over the bar takes in the turn's last answer
608  on('turn.complete', async ($, e, next) => {
609    await refreshFill($)
610    await refreshModel($)
611    if (e.agentId === undefined) $.clock.after(0, () => void countTokens($))
612    return next(e)
613  })
614
615  // The effort is only known on a request, after any downgrade for the selected model, and the
616  // window's fill on each response
617  // The cache is read on each main-thread request; the first after a message says how much
618  // of the conversation was still cached when it was sent
619  on('turn.step', async function* ($, e, next) {
620    const effort = e.effort === undefined ? null : String(e.effort)
621    // A subagent's requests are kept apart, for the footer to show while its transcript is
622    const agentId = e.agentId
623    if (agentId !== undefined) {
624      const { context } = await $.session.usage()
625      const window = agentWindow(e.model, await $.session.model(), context.window)
626      const stats = memberOf(agents, { requestId: agentId })
627      await update($, stats, prev => ({ model: e.model, effort, tokens: prev?.tokens ?? null, window }))
628      return yield* tap(next(e), async chunk => {
629        if (chunk.kind !== 'stop' || chunk.usage === null) return
630        const tokens = inputTokens(chunk.usage)
631        await update($, stats, prev => (prev === null ? prev : { ...prev, tokens }))
632      })
633    }
634    const name = await $.session.model()
635    await update($, model, prev => ({ name, effort, isEffortKnown: true, isEffortPinned: prev?.isEffortPinned ?? false }))
636    const requestAt = await $.clock.now()
637    const { context } = await $.session.usage()
638    // What the conversation took on since the last response (tool results, the new prompt) is
639    // counted as the request leaves, without holding it, and shown until this one measures
640    let isMeasured = false
641    const counting = countTokens($).catch(() => null)
642    void counting.then(async counted => {
643      const tokens = counted === null ? null : earlyTokens(baseline, counted.tokens)
644      if (tokens === null || counted === null || isMeasured) return
645      const early = estimatedFill(tokens, counted.window)
646      await update($, fill, prev => (isMeasured ? prev : raisedFill(prev, early)))
647    })
648    // A request the API ran tools of its own in (an advisor) reports usage summed over its steps,
649    // which tells no TTL and is no entry's size: it is learned from once it is answered
650    const telling: { read: { prev: CacheInfo; cacheRead: number; tokens: number } | null } = { read: null }
651    const result = yield* tap(next(e), async chunk => {
652      if (chunk.kind !== 'stop' || chunk.usage === null) return
653      // Each response of a turn moves the bar, not only the turn's end
654      isMeasured = true
655      isAwaitingTake = false
656      const tokens = inputTokens(chunk.usage)
657      await update($, fill, () => measuredFill(tokens, context.window))
658      const counted = await counting
659      baseline = counted === null ? null : { counted: counted.tokens, measured: tokens }
660      const hit = hitPercent(chunk.usage)
661      const prev = await read($, cache)
662      if (e.index === 0 && hit !== null && prev !== null) telling.read = { prev, cacheRead: chunk.usage.cache_read_input_tokens, tokens }
663      const hitNow = e.index === 0 || prev === null ? (hit ?? prev?.hitPercent ?? 0) : prev.hitPercent
664      await update($, cache, () => ({ hitPercent: hitNow, requestAt, model: name, tokens }))
665    })
666    if ((result.serverToolUses ?? []).length > 0) {
667      await update($, cache, prev => (prev === null ? prev : { ...prev, tokens: undefined }))
668      return result
669    }
670    const seen = telling.read
671    if (seen !== null) await learnFrom($, seen.prev, name, seen.cacheRead, seen.tokens, requestAt)
672    return result
673  })
674
675  // A plugin's fork re-sends the main thread's last request with one more message after it,
676  // whichever plugin forks: it reads the conversation from the cache, or writes it there once
677  // the entry lapsed, and either way the entry starts over. Keep warm renews the cache so
678  on('model.fork', async ($, e, next) => {
679    const requestAt = await $.clock.now()
680    const result = await next(e)
681    const usage = result.value !== undefined && 'usage' in result.value ? result.value.usage : null
682    const hit = usage === null ? null : hitPercent(usage)
683    if (usage === null || hit === null) return result
684    const name = await $.session.model()
685    const tokens = inputTokens(usage)
686    await update($, cache, () => ({ hitPercent: hit, requestAt, model: name, isFork: true, tokens }))
687    return result
688  })
689
690  // `/effort` changes the level without a request: its answer row says to what
691  on('session.append', { door: 'command' }, async ($, e, next) => {
692    const effort = e.agentId === undefined ? effortFromRow(e.message.content) : null
693    if (effort !== null) await update($, model, prev => pinEffort(prev, effort))
694    return next(e)
695  })
696
697  // The cleared conversation is estimated once the engine has emptied it
698  // A /clear or a /resume goes on with another conversation, whose first request tells no TTL
699  // from the last one's entry. A cleared one has none cached; a resumed one may, kept warm by
700  // Claude Code since it was left, which only that request shows: until then nothing is shown
701  on('session.end', async ($, e, next) => {
702    if (e.reason === 'clear') await update($, cache, prev => (prev === null ? prev : { ...prev, requestAt: null }))
703    if (e.reason === 'resume') await update($, cache, () => null)
704    // The last request's measure is the other conversation's, which no count since sets against
705    if (e.reason === 'clear' || e.reason === 'resume') baseline = null
706    if (e.reason !== 'clear') return next(e)
707    carried = await read($, model)
708    const result = await next(e)
709    estimateWhenTaken($)
710    return result
711  })
712
713  // The compacted conversation is estimated once the engine has taken it. A compaction computed ahead or vetoed leaves the conversation as it was,
714  // and a subagent's leaves the main one. A compacted conversation is a new prefix, which the
715  // cache has none of yet
716  on('session.compact', async ($, e, next) => {
717    const result = await next(e)
718    if (e.trigger === 'precompute' || e.agentId !== undefined || result.skip !== undefined) return result
719    baseline = null
720    estimateWhenTaken($)
721    await update($, cache, prev => (prev === null ? prev : { ...prev, requestAt: null }))
722    return result
723  })
724
725  // The footer's right-hand slot, which the engine lays out after the hint line. A tree
726  // drawn for `PromptHint` instead shares a row with the mode label the engine puts ahead
727  // of it, and any width it claims squeezes that label until its ` · ` wraps
728  // While an agent's transcript is on screen the footer shows that agent's model, effort and
729  // window, read-only: the picks, the cache and the actions are the conversation's
730  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
731    const viewed = await read($, viewing)
732    const stats = viewed === null ? null : await read($, memberOf(agents, { requestId: viewed.id }))
733    const current = viewed === null ? await read($, fill) : agentFill(stats)
734    const info = viewed === null ? await read($, model) : agentModel(stats)
735
736    if (viewed === null && current === null && info === null) {
737      return next(e)
738    }
739
740    const { Box, Text, Button } = $.ui.resolve(e)
741    const columns = e.viewport?.columns ?? DEFAULT_COLUMNS
742    // The labels already in the slot (`focus`, `memory paused`) keep the engine's drawing, and
743    // what other mods beneath draw there goes with them, at the right end
744    const modesText = e.props.modes.join(' & ')
745    const beneath = await next(e)
746
747    // The desktop draws the model, the effort and the window's fill of its own, and lays this
748    // slot out as one short line, its buttons first: it gets one line of what it lacks
749    if (e.surface !== 'terminal') {
750      const cached = viewed === null ? await read($, cache) : null
751      const isSameModel = cached === null || info === null || info.name === cached.model
752      const remaining =
753        cached === null ? null : isSameModel ? formatRemaining(remainingMs(cached, ttlOf(cached, await ttlsOf($)), cacheNow)) : COLD_TEXT
754      const coming = remaining === null || remaining === COLD_TEXT ? null : await read($, warmUpcoming)
755      const segments = desktopSegments({ agent: viewed?.label ?? null, fill: current, cached, remaining, upcoming: coming })
756      return (
757        <Box flexShrink={0} gap={1}>
758          {segments.map((segment, i) => (
759            <Text color={segment.color} dimColor={segment.color === undefined}>{`${i === 0 ? '' : '· '}${segment.text}`}</Text>
760          ))}
761          {beneath}
762        </Box>
763      )
764    }
765
766    const parts = info === null ? null : modelParts(info)
767    const pending = viewed === null ? await read($, asking) : null
768    const confirming = pending !== null && isAction(pending) ? pending : null
769    // An effort pick is moot once the model in use takes none
770    const choosing =
771      pending === null || isAction(pending) || parts === null || (pending === 'effort' && parts.effort === null)
772        ? null
773        : pending
774    const selected =
775      choosing === 'model' ? (parts?.family ?? null) : info !== null && info.isEffortKnown ? info.effort : null
776
777    let modelBlock = null
778    let modelLength = 0
779
780    if (parts !== null && choosing !== null) {
781      const chips = choosing === 'model' ? MODEL_CHIPS : EFFORT_CHIPS
782      modelLength = chooserLength(choosing, selected)
783      modelBlock = (
784        <Box flexShrink={0} gap={1}>
785          <Text dimColor>{`${choosing}:`}</Text>
786          {choicesFor(choosing).map(choice => (
787            <Box backgroundColor={chips[choice] ?? NO_COLOR}>
788              <Button
789                key={`${choosing}:${choice}`}
790                label={chipLabel(choiceLabel(choice, selected))}
791                plain
792                onPress={() => void (choice === selected ? settle($) : choose($, choosing, choice))}
793              />
794            </Box>
795          ))}
796          <Box backgroundColor={NO_COLOR}>
797            <Button key="close" label={chipLabel(CLOSE_ICON)} plain onPress={() => void settle($)} />
798          </Box>
799        </Box>
800      )
801    } else if (parts !== null) {
802      modelLength = parts.length
803      // A Button takes no color at rest: the icons keep the model's and the effort's
804      modelBlock = (
805        <Box flexShrink={0}>
806          <Text color={parts.modelColor}>{`${MODEL_ICON} `}</Text>
807          {viewed === null ? (
808            <Button key="model" label={parts.name} plain onPress={() => void ask($, 'model')} />
809          ) : (
810            <Text>{parts.name}</Text>
811          )}
812          {parts.effort !== null && (
813            <Text color={parts.effort.color}>
814              {`${' '.repeat(EFFORT_GAP)}${parts.effort.icon === '' ? '' : `${parts.effort.icon} `}`}
815            </Text>
816          )}
817          {parts.effort !== null &&
818            (viewed === null ? (
819              <Button key="effort" label={parts.effort.label} plain onPress={() => void ask($, 'effort')} />
820            ) : (
821              <Text>{parts.effort.label}</Text>
822            ))}
823        </Box>
824      )
825    }
826
827    let bar = null
828    let barLength = 0
829
830    if (current !== null) {
831      const percent = Math.min(100, Math.max(0, current.percent))
832      const isCompact = columns < COMPACT_BELOW
833      const barWidth = barWidthFor(columns)
834      const filled = Math.round((percent / 100) * barWidth)
835      const color = colorFor(percent)
836      const label = isCompact ? '' : 'Context '
837      const percentText = ` ${current.isEstimate ? '~' : ''}${percent}%`
838      barLength = label.length + barWidth + percentText.length
839      // The conversation's alone: a subagent's window has no breakdown
840      const rows = viewed === null ? await read($, breakdown) : null
841      const card = rows === null || rows.length === 0 ? null : cardLines(rows)
842
843      // Hovering the bar shows the card over the rows above it, right-aligned to it
844      bar = (
845        <Box key="context-card" flexShrink={0}>
846          {label !== '' && <Text dimColor>{label}</Text>}
847          <Text color={color}>{'█'.repeat(filled)}</Text>
848          <Text dimColor>{'░'.repeat(barWidth - filled)}</Text>
849          <Text color={color} bold>
850            {percentText}
851          </Text>
852          {card !== null && (
853            <Box position="absolute" bottom={1} right={0} display="none" hover={{ display: 'flex' }} flexDirection="column">
854              {card.map(line => (
855                <Box>
856                  {line.flatMap(cell => [
857                    <Text color={cell.color}>{cell.glyph}</Text>,
858                    <Text dimColor={cell.isDim}>{cell.text}</Text>,
859                  ])}
860                </Box>
861              ))}
862            </Box>
863          )}
864        </Box>
865      )
866    }
867
868    let cacheBlock = null
869    let cacheLength = 0
870    const cached = viewed === null ? await read($, cache) : null
871
872    if (cached !== null) {
873      const label = columns < COMPACT_BELOW ? '' : 'Cache '
874      const percentText = `${cached.hitPercent}%`
875      // The cache is per model: one switched to has none of the conversation yet
876      const isSameModel = info === null || info.name === cached.model
877      const remaining = isSameModel ? formatRemaining(remainingMs(cached, ttlOf(cached, await ttlsOf($)), cacheNow)) : COLD_TEXT
878      // warm-compact's mark for what it does before the entry lapses, while there is one
879      const upcoming = await read($, warmUpcoming)
880      const coming = remaining === COLD_TEXT ? null : upcoming
881      const mark = coming === null ? null : UPCOMING_STYLES[coming.kind]
882      cacheLength = label.length + percentText.length + 1 + remaining.length + (mark === null ? 0 : 1 + mark.icon.length)
883
884      cacheBlock = (
885        <Box key="cache-card" flexShrink={0}>
886          {label !== '' && <Text dimColor>{label}</Text>}
887          <Text color={hitColor(cached.hitPercent)} bold>
888            {percentText}
889          </Text>
890          {remaining === COLD_TEXT ? <Text color={COLD_COLOR}>{` ${remaining}`}</Text> : <Text dimColor>{` ${remaining}`}</Text>}
891          {mark !== null && <Text color={mark.color}>{` ${mark.icon}`}</Text>}
892          {coming !== null && (
893            <Box position="absolute" bottom={1} right={0} display="none" hover={{ display: 'flex' }} borderStyle="round" borderDimColor>
894              <Text>{` ${upcomingText(coming, cacheNow)} `}</Text>
895            </Box>
896          )}
897        </Box>
898      )
899    }
900
901    const agentText = viewed === null ? '' : `${AGENT_ICON} ${viewed.label}`
902    const agentBlock = agentText === '' ? null : <Text dimColor>{agentText}</Text>
903
904    const actions =
905      viewed !== null ? null : confirming === null ? (
906        <Box flexShrink={0} gap={ACTION_GAP}>
907          {CONTEXT_ACTIONS.map(action => (
908            <Box backgroundColor={ACTIONS[action].color}>
909              <Button key={action} label={chipLabel(ACTIONS[action].icon)} plain onPress={() => void ask($, action)} />
910            </Box>
911          ))}
912        </Box>
913      ) : (
914        <Box flexShrink={0} gap={1}>
915          <Text color={ACTIONS[confirming].color} bold>
916            {ACTIONS[confirming].question}
917          </Text>
918          <Box backgroundColor={ACTIONS[confirming].color}>
919            <Button key="yes" label={chipLabel('yes')} plain onPress={() => void confirm($, confirming)} />
920          </Box>
921          <Box backgroundColor={NO_COLOR}>
922            <Button key="no" label={chipLabel('no')} plain onPress={() => void settle($)} />
923          </Box>
924        </Box>
925      )
926
927    const blocks = [
928      agentText.length,
929      cacheLength,
930      modelLength,
931      barLength,
932      viewed === null ? actionsLength(confirming) : 0,
933      modesText.length,
934    ].filter(n => n > 0)
935    const rightLength = blocks.reduce((sum, n) => sum + n, 0) + BLOCK_GAP * (blocks.length - 1)
936
937    if (fitsInRow(columns, rightLength)) {
938      return (
939        <Box flexShrink={0} gap={BLOCK_GAP}>
940          {agentBlock}
941          {cacheBlock}
942          {modelBlock}
943          {bar}
944          {actions}
945          {beneath}
946        </Box>
947      )
948    }
949
950    return (
951      <Box flexShrink={0} flexDirection="column" alignItems="flex-end">
952        {agentBlock}
953        {cacheBlock}
954        {modelBlock}
955        {bar}
956        {actions}
957        {beneath}
958      </Box>
959    )
960  })
961}
962
hooks/cache.ts 32 lines
1import type { CacheInfo, CacheTtl, LearnedTtl } from '../types'
2import { TTL_MS } from './shared/cache-ttl'
3
4const GOOD_FROM = 80
5const FAIR_FROM = 40
6const MINUTE_MS = 60_000
7const SECOND_MS = 1000
8export const COLD_TEXT = 'cold'
9
10// A fork's entry may not last as long as one a request of the conversation leaves
11export const ttlOf = (info: CacheInfo, ttls: LearnedTtl): CacheTtl =>
12  info.isFork === true ? (ttls.renew ?? ttls.cache) : ttls.cache
13
14// Each request that reads the cache renews its entry, so it lapses one TTL after the last.
15// The clock is read once a second, so a request just made may postdate its last reading
16export const remainingMs = (info: CacheInfo, ttl: CacheTtl, now: number): number =>
17  info.requestAt === null ? 0 : Math.min(TTL_MS[ttl], Math.max(0, info.requestAt + TTL_MS[ttl] - now))
18
19// Rounded up, so `~1m` still has the cache warm and nothing shows `~0m`
20export const formatRemaining = (ms: number): string => {
21  if (ms <= 0) return COLD_TEXT
22  if (ms < MINUTE_MS) return `~${Math.ceil(ms / SECOND_MS)}s`
23  return `~${Math.ceil(ms / MINUTE_MS)}m`
24}
25
26export const hitColor = (percent: number): string => {
27  if (percent >= GOOD_FROM) return '#3fb950'
28  if (percent >= FAIR_FROM) return '#ff9500'
29  return '#f85149'
30}
31
32
hooks/shared/cache-ttl.ts 86 lines
1// The master copy, kept at the repository's root: each mod that uses it holds a copy under
2// hooks/shared/, as a mod loads and installs on its own. Edit it here, then run
3// scripts/sync-shared.sh
4
5// The mod's own contract names the two TTLs, for the values it keeps
6import type { CacheTtl } from '../../types'
7
8const MINUTE_MS = 60_000
9
10export const TTL_MS: Record<CacheTtl, number> = { '5m': 5 * MINUTE_MS, '1h': 60 * MINUTE_MS }
11// What the engine picks for a main thread that may cache for an hour, which a session on a
12// Claude subscription does, until a request shows otherwise
13export const DEFAULT_TTL: CacheTtl = '1h'
14// Past a TTL by this much, a request's hit or miss is the entry's lapse and not a race
15const TTL_MARGIN_MS = 30_000
16// What a request read from the cache is set against the entry the last read left, all that read
17// was answered over: one that holds is read whole, whatever is added after it (a long message
18// pasted in), and one that lapsed leaves only the tools and the system prompt other sessions keep
19// cached, some 25k tokens, half a small conversation, a fifth of a large one. So under half of
20// the entry read found it gone, and only 80% or more of an entry large enough that the shared
21// part cannot reach it found it whole
22const WARM_FROM = 80
23const COLD_BELOW = 50
24const TELLING_TOKENS = 50_000
25// Past a renewal, a read this warm found the conversation, and one this cold found only
26// the tools and the system prompt, which other sessions keep cached
27const RENEWED_FROM = 90
28const LAPSED_BELOW = 50
29
30type RequestUsage = { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
31
32// All the input the request was answered over: what was read, what was written, and what went
33// uncached
34export const inputTokens = (usage: RequestUsage): number => usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
35
36// The share of the prompt the cache served, out of all its input
37export const hitPercent = (usage: RequestUsage): number | null => {
38  const total = inputTokens(usage)
39  return total === 0 ? null : Math.round((usage.cache_read_input_tokens / total) * 100)
40}
41
42export const isCacheTtl = (value: unknown): value is CacheTtl => value === '5m' || value === '1h'
43
44// Only a pause longer than five minutes and shorter than an hour tells the two TTLs apart
45const isTelling = (pause: number): boolean =>
46  pause >= TTL_MS['5m'] + TTL_MARGIN_MS && pause <= TTL_MS['1h'] - TTL_MARGIN_MS
47
48// A conversation only grows between two requests: a later one answered over less than this share of
49// the entry, or reading more than SERVED_ABOVE of it, went through something the figures do not
50// show (a request whose usage is summed over its own server-side steps, as an advisor's is; a
51// compaction or a /clear no hook was told of), and tells nothing
52const SHRUNK_BELOW = 90
53const SERVED_ABOVE = 150
54
55// The share of an entry of `tokens` a later request of `requestTokens` read, or null with no
56// entry to set it against, or none the two figures can be trusted for
57const servedOf = (read: number, tokens: number | undefined, requestTokens: number): number | null => {
58  if (tokens === undefined || tokens <= 0 || requestTokens * 100 < tokens * SHRUNK_BELOW) return null
59  const served = Math.round((read / tokens) * 100)
60  return served > SERVED_ABOVE ? null : served
61}
62
63// `last`: the main thread's last request, when it left (null once a compaction changed the
64// prefix), on which model, and all it was answered over. `read`: what the request after it read
65// from the cache, out of the `tokens` it was answered over. Past a telling pause, an entry still read means an hour, one gone means five
66// minutes. A miss can also come from a prompt that changed meanwhile (an edited CLAUDE.md, a
67// server connected), which a long pause with a hit corrects, unless compactions take each pause
68export const inferTtl = (last: { at: number | null; model: string; tokens?: number }, model: string, read: number, tokens: number, requestAt: number): CacheTtl | null => {
69  if (last.at === null || last.model !== model || !isTelling(requestAt - last.at)) return null
70  const served = servedOf(read, last.tokens, tokens)
71  if (served === null) return null
72  if (served < COLD_BELOW) return '5m'
73  return served >= WARM_FROM && (last.tokens ?? 0) >= TELLING_TOKENS ? '1h' : null
74}
75
76// A renewal (a plugin's fork of the conversation) reads the entry without the hour-long TTL a
77// session's own requests ask for. Whether it holds the entry, of `tokens`, an hour or five
78// minutes shows in what a read of `readTokens` a telling pause after it finds
79export const inferRenewTtl = (renewedAt: number, tokens: number | undefined, read: number, readTokens: number, readAt: number): CacheTtl | null => {
80  if (!isTelling(readAt - renewedAt)) return null
81  const served = servedOf(read, tokens, readTokens)
82  if (served === null) return null
83  if (served >= RENEWED_FROM && (tokens ?? 0) >= TELLING_TOKENS) return '1h'
84  return served < LAPSED_BELOW ? '5m' : null
85}
86
hooks/shared/stream.ts 14 lines
1// The master copy, kept at the repository's root: each mod that uses it holds a copy under
2// hooks/shared/, as a mod loads and installs on its own. Edit it here, then run
3// scripts/sync-shared.sh
4
5// Passes the response on as it streams, seeing each chunk on the way
6export async function* tap<T, R>(stream: AsyncGenerator<T, R>, see: (chunk: T) => Promise<void>): AsyncGenerator<T, R> {
7  for (;;) {
8    const step = await stream.next()
9    if (step.done === true) return step.value
10    await see(step.value)
11    yield step.value
12  }
13}
14
types/index.d.ts 52 lines
1// `isEstimate`: the engine's own estimate, as /context makes it, while no response has measured
2// the window yet: in a fresh or cleared session, or just after a compaction
3export type ContextFill = { percent: number; tokens: number; window: number; isEstimate: boolean }
4export type ContextAction = 'compact' | 'clear'
5export type Setting = 'model' | 'effort'
6// What the footer asks in place of its blocks: to confirm an action, or to pick a setting
7export type Question = ContextAction | Setting
8// `isEffortPinned`: `/effort` set the level, which then holds for the session across models
9export type ModelInfo = { name: string; effort: string | null; isEffortKnown: boolean; isEffortPinned: boolean }
10
11export type CacheTtl = '5m' | '1h'
12// `hitPercent`: what the cache served of the first request after the last message.
13// `requestAt`: the last main-thread request, null once a compaction changed the prefix.
14// `model`: the session's model then, the one the cache entry belongs to.
15// `isFork`: that request was a plugin's fork of the conversation (keep warm's renewal), whose
16// entry may not last as long as one a request of the conversation leaves
17export type CacheInfo = { hitPercent: number; requestAt: number | null; model: string; isFork?: boolean; tokens?: number }
18
19// The agent whose transcript the person opened from the tasks list. `label`: its type, or a
20// teammate's name
21export type AgentView = { id: string; label: string }
22// What a subagent's own requests told: the model and effort its last one named, and the input
23// tokens it was answered over (null until its first response) against `window`
24export type AgentStats = { model: string; effort: string | null; tokens: number | null; window: number }
25// One row of the card over the bar: what fills the window, by category as /context lists it,
26// in tokens and in percent of the window. `color`: the theme key /context draws it in
27export type ContextRow = { name: string; tokens: number; percent: number; color: string; kind: 'used' | 'free' | 'buffer' }
28
29// warm-compact's own, read while it is loaded and never written: the TTLs as it learned them,
30// and what the pause holds if the person stays away. As its contract declares them
31export type LearnedTtl = { cache: CacheTtl; renew: CacheTtl | null }
32export type Upcoming = { kind: 'compact' | 'renew'; at: number; expiresAt: number }
33
34declare module 'claude-code' {
35  interface PluginState {
36    'context-bar': {
37      fill: ContextFill | null
38      model: ModelInfo | null
39      asking: Question | null
40      cache: CacheInfo | null
41      viewing: AgentView | null
42      agents: StateFamily<AgentStats | null>
43      // What fills the window as the engine last counted it, null before its first count
44      breakdown: ContextRow[] | null
45    }
46    'warm-compact': {
47      ttl: LearnedTtl | null
48      upcoming: Upcoming | null
49    }
50  }
51}
52