SLOPSHOPPER

usage-bar

Usage limits, context and cost above the prompt; keeps your status line

bandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-bar
› fix the failing auth test and add an audit log call ⏺ 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 context 49% · $0.42 · session ⣿⣿⣀⣀⣀⣀⣀⣀ 31% (↻ 1h) ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
context 49% · $0.42 · session ⣿⣿⣀⣀⣀⣀⣀⣀ 31% (↻ 1h) ⟨Claude Code's own drawing⟩
README

<img src=".claude-plugin/icon.svg" width="48" align="absmiddle" alt=""> usage-bar

Your plan's usage limits, context and cost on one quiet line above the prompt, with an alert before you run out. It doesn't replace your status line: it sits above the prompt, so the two work side by side.

The bar at the right edge above Claude Code's prompt: context 62% · $1.84 · session 41% (↻ 2h10m) · week 18% (↻ 3d2h)

The line sits at the right edge, away from where you read and type. From left to right:

On the lineWhat it shows
contextHow full this conversation's context window is.
cache coldIn red: the conversation's cache has expired, so your next message re-reads all of it at full price.
$What this session has cost.
session, weekHow much of your 5-hour and weekly limits you've used. After ↻, how long until each resets: 2h10m, 3d2h, or now.

More on cache cold:

  • It works right after /resume too, before you send anything.
  • It shows only for conversations of 100,000 tokens or more. Change that size, or turn it off, in /config.
  • It doesn't notice a cache broken by switching models, but /model warns you about that itself.

The line with "cache cold" in red after context 62%

Alerts

A limit's percent turns yellow at 75% and red at 90%, as on claude.ai's usage page; the rest of the line stays grey. An alert with the limit and its percent appears at the top right at 50%, 75% and 90%:

The session limit at 78% in yellow, with the alert "session 78%"

The weekly limit at 96% in red, with the alert "week 96%"

When both limits cross at once, one alert names both: session 62% · week 97%. Each alert shows once per limit period, even across restarts and projects. When a limit resets, its alerts start over.

When the line doesn't fit

The line at the top is the full layout. When it doesn't fit, it shortens instead of wrapping, one step at a time:

ctx 62% · $1.84 · s ⣿⣿⣿⣀⣀⣀⣀⣀ 41% (↻ 2h10m) · w ⣿⣀⣀⣀⣀⣀⣀⣀ 18% (↻ 3d2h)
ctx 62% · $1.84 · s 41% (↻ 2h10m) · w 18% (↻ 3d2h)
ctx 62% · $1.84 · s 41% · w 18%

Before the first reading

For a few seconds after startup, and for as long as you're not logged in, the line reads:

usage: no data yet

The context shows – until your first reply, because Claude Code measures the context only when it answers.

In the desktop app, a new session and /clear show no line at all until you send a message: the app starts Claude Code only then.

What it is not

  • Not a status line. It sits above the prompt and leaves your status line alone.
  • Not a usage history. It shows the current figures and nothing over time.

Privacy

usage-bar reads only figures Claude Code already has: context fill, session cost and your plan's limits. It sends nothing anywhere and makes no network requests. It stores one small record per limit on your machine, listing the alerts already shown in the current period, so a restart doesn't repeat them. To learn how long the cache lasts, it reads the end of this conversation's file on your machine after each reply and keeps only 5m or 1h.

Install

In Claude Code:

/plugin install usage-bar --marketplace andrej-kolic/claude-mods

The desktop app's Code tab doesn't offer /plugin install: run it once in a terminal, at the user scope, and the line shows in the desktop app's local sessions too.

  • Claude Code: 2.1.275 or later for this one-step install. Tested on 2.1.295 and 2.1.296 in the terminal, and in the desktop app 2.31226.0.
  • Plan: usage limits need a Claude subscription. With an API key, the line shows only the context and $, and no alerts.
  • Context cost: about 0 tokens. It adds nothing to what Claude reads.
  • Where it shows: Claude Code's terminal and the desktop app's Code tab. The VS Code extension's chat panel doesn't show it yet. It does nothing on claude.ai or in Cowork.
  • Windows: tested on macOS only. In Windows 10's older console window, the bars and symbols show as empty boxes; in Windows Terminal and the desktop app they show correctly. On Windows, cache cold can show too early after /resume when you use an API key.

More

The screenshots use sample readings. The yellow and red follow your Claude Code theme.

The spec has every rule: rounding, colours, widths, and when alerts repeat.

Source 3 files
hooks/register.tsx 522 lines
1import type {
2  EngineInterface,
3  Register,
4  SessionMeasureInput,
5  Timer,
6} from 'claude-code';
7import { atom, read, update } from 'claude-code';
8
9import type { LimitReading, Reading } from '../types';
10import { type CacheInputs, cacheLength, isCold, writtenLength } from './cache';
11
12const reading = atom({ plugin: 'usage-bar', key: 'reading' } as const, null);
13// Bumped each minute so the countdowns redraw while no reading arrives.
14const minute = atom({ plugin: 'usage-bar', key: 'minute' } as const, 0);
15const lastRequest = atom(
16  { plugin: 'usage-bar', key: 'lastRequest' } as const,
17  null,
18);
19// What the latest main-conversation reply showed about the cache; see CacheSeen.
20const cacheSeen = atom(
21  { plugin: 'usage-bar', key: 'cacheSeen' } as const,
22  null,
23);
24// True while a main-conversation turn runs: the cache is being used, so it is never cold then.
25const working = atom({ plugin: 'usage-bar', key: 'working' } as const, false);
26const resumed = atom({ plugin: 'usage-bar', key: 'resumed' } as const, null);
27// This session's conversation file, as classic.SessionStart names it, and the cache length its latest write used.
28const transcript = atom(
29  { plugin: 'usage-bar', key: 'transcript' } as const,
30  null,
31);
32const written = atom({ plugin: 'usage-bar', key: 'written' } as const, null);
33
34// Alerts at 50%, then claude.ai's own warning (75%) and critical (90%) colours on Settings → Usage.
35const THRESHOLDS = [50, 75, 90];
36
37type Window = { label: string; letter: string };
38
39// The two windows the line shows; any other kind (a gateway's spend_limit) is ignored.
40const WINDOWS: Record<string, Window> = {
41  five_hour: { label: 'session', letter: 's' },
42  seven_day: { label: 'week', letter: 'w' },
43};
44
45// The line's layouts, widest first: the line uses the first whose text fits bodyColumns (see docs/usage-bar.md).
46type Layout = 'full' | 'short-bars' | 'short' | 'tiny';
47const LAYOUTS: Layout[] = ['full', 'short-bars', 'short', 'tiny'];
48
49const BAR_CELLS = 8;
50
51// A run of the line; a colored one shows a window's percent.
52type Segment = { text: string; color?: 'warning' | 'error' };
53
54// What $.store holds per window kind: the period's resetsAt and the thresholds already toasted in it.
55type Toasted = { resetsAt: string; thresholds: number[] };
56
57// Time left until resetsAt, in whole minutes rounded up: `3d2h`, `2h10m`, `45m`; a zero part is dropped, `4h`.
58// `now` once it has passed: the limit has reset, and the next reading brings the new period's percent.
59function countdown(resetsAt: string, now: number): string {
60  const minutes = Math.max(
61    0,
62    Math.ceil((new Date(resetsAt).getTime() - now) / 60_000),
63  );
64  const days = Math.floor(minutes / 1440);
65  const hours = Math.floor((minutes % 1440) / 60);
66
67  const part = (n: number, unit: string) => (n > 0 ? `${n}${unit}` : '');
68
69  return days > 0
70    ? `${days}d${part(hours, 'h')}`
71    : hours > 0
72      ? `${hours}h${part(minutes % 60, 'm')}`
73      : minutes > 0
74        ? `${minutes}m`
75        : 'now';
76}
77
78function bar(percent: number): string {
79  const filled = Math.min(
80    BAR_CELLS,
81    Math.max(0, Math.floor((percent / 100) * BAR_CELLS)),
82  );
83
84  // Braille: a full cell against a low baseline looks the same in every terminal and the desktop app, and stays light.
85  return '⣿'.repeat(filled) + '⣀'.repeat(BAR_CELLS - filled);
86}
87
88const levelColor = (percent: number): Segment['color'] =>
89  percent >= 90 ? 'error' : percent >= 75 ? 'warning' : undefined;
90
91function windowSegments(
92  limit: LimitReading,
93  layout: Layout,
94  now: number,
95): Segment[] | undefined {
96  const window = WINDOWS[limit.kind];
97  if (!window) return undefined;
98
99  const label = layout === 'full' ? window.label : window.letter;
100  const percent = `${Math.floor(limit.percentUsed)}%`;
101  const barText =
102    layout === 'full' || layout === 'short-bars'
103      ? `${bar(limit.percentUsed)} `
104      : '';
105  const time =
106    limit.resetsAt && layout !== 'tiny'
107      ? countdown(limit.resetsAt, now)
108      : undefined;
109  const resets = time === undefined ? '' : ` (↻ ${time})`;
110
111  return [
112    { text: `${label} ${barText}` },
113    { text: percent, color: levelColor(limit.percentUsed) },
114    { text: resets },
115  ];
116}
117
118// The line's items at the right edge: this conversation's figures, then the account's limits.
119// Items are drawn apart with a dot between and a one-column gap either side of it, not a typed ` · `: the
120// desktop app's spaces are narrower than a column.
121type Item = Segment[];
122const SEPARATOR = 3;
123
124const lineLength = (items: Item[]) =>
125  items.reduce(
126    (n, item) => n + item.reduce((m, s) => m + s.text.length, 0),
127    0,
128  ) +
129  Math.max(0, items.length - 1) * SEPARATOR;
130
131function lineItems(
132  r: Reading,
133  columns: number,
134  now: number,
135  cold: boolean,
136): Item[] {
137  const fits = (items: Item[]) => lineLength(items) <= columns;
138
139  // The narrowest layout shows even where nothing fits.
140  return (
141    LAYOUTS.map((layout) => layoutItems(r, layout, now, cold)).find(fits) ??
142    layoutItems(r, 'tiny', now, cold)
143  );
144}
145
146// The cold item's text by layout: its own item after context, so it never reads as the context being cold.
147// ❆ (U+2746) is not an emoji, so it takes one column; ❄ (U+2744) can draw two wide.
148const COLD_TEXT: Record<Layout, string> = {
149  full: 'cache cold',
150  'short-bars': 'cold',
151  short: 'cold',
152  tiny: '❆',
153};
154
155function layoutItems(
156  r: Reading,
157  layout: Layout,
158  now: number,
159  cold: boolean,
160): Item[] {
161  // A figure the reading lacks is a dash, not a made-up 0: the fill before any response
162  // reports it, the cost where Claude Code keeps no cost record.
163  const ctx =
164    r.contextPercent === undefined ? '–' : `${Math.floor(r.contextPercent)}%`;
165  const usd = r.usd === undefined ? '–' : r.usd.toFixed(2);
166  const conversation: Item[] = [
167    [{ text: `${layout === 'full' ? 'context' : 'ctx'} ${ctx}` }],
168    ...(cold ? [[{ text: COLD_TEXT[layout], color: 'error' as const }]] : []),
169    [{ text: `$${usd}` }],
170  ];
171
172  const limits: Item[] = [];
173  for (const limit of r.rateLimits) {
174    const window = windowSegments(limit, layout, now);
175    if (window) limits.push(window.filter((segment) => segment.text !== ''));
176  }
177
178  return [...conversation, ...limits];
179}
180
181// The record to save when the window crossed a threshold not yet toasted this period, else undefined.
182// It marks every crossed threshold, so a lower one never toasts later in this period.
183async function freshRecord(
184  $: EngineInterface,
185  limit: LimitReading,
186): Promise<Toasted | undefined> {
187  const period = limit.resetsAt ?? '';
188  const stored = (await $.store.get(`toasted:${limit.kind}`)) as
189    | Toasted
190    | undefined;
191  const shown = stored?.resetsAt === period ? stored.thresholds : [];
192
193  // A threshold counts as shown when one at least as high was: 0.1.0 stored 80 and 95, not 75 and 90.
194  const crossed = THRESHOLDS.filter((t) => limit.percentUsed >= t);
195  if (crossed.every((t) => shown.some((s) => s >= t))) return undefined;
196
197  return { resetsAt: period, thresholds: crossed };
198}
199
200// Just the windows and numbers, named as in the line's full layout: `week 97%`, or `session 62% · week 97%`.
201const toastText = (limits: { limit: LimitReading; window: Window }[]): string =>
202  limits
203    .map(
204      ({ limit, window }) =>
205        `${window.label} ${Math.floor(limit.percentUsed)}%`,
206    )
207    .join(' · ');
208
209// The figures session.measure and $.session.usage() both carry, as the line keeps them.
210const toReading = (
211  u: Pick<SessionMeasureInput, 'context' | 'rateLimits' | 'cost'>,
212): Reading => ({
213  contextPercent: u.context.percent,
214  usd: u.cost?.usd,
215  rateLimits: u.rateLimits.map(({ kind, percentUsed, resetsAt }) => ({
216    kind,
217    percentUsed,
218    resetsAt,
219  })),
220});
221
222// After /clear, /resume or /branch the new session holds no reading, and none is measured until the next turn
223// ends; the engine still has the last response's limits, or the resumed conversation's context and cost, so draw
224// those. Null while it has none: before the startup quota check. The CLI's cost ledger is always there, so a cost
225// alone is no reading. Drawing can't write state, so the next session.measure is what stores a reading.
226async function engineReading($: EngineInterface): Promise<Reading | null> {
227  const usage = await $.session.usage().catch(() => undefined);
228  const has =
229    usage &&
230    (usage.rateLimits.length > 0 || usage.context.percent !== undefined);
231
232  return has ? toReading(usage) : null;
233}
234
235// The last 256 KiB of the conversation file hold the latest reply's row (A18). A failed or empty read, or a tail
236// with no cache write, keeps the last known length.
237const TAIL_BYTES = '262144';
238
239async function readWritten($: EngineInterface): Promise<void> {
240  try {
241    const path = await read($, transcript);
242    if (path === null) return;
243    const { exitCode, stdout } = await $.process.run([
244      'tail',
245      '-c',
246      TAIL_BYTES,
247      path,
248    ]);
249    const length = exitCode === 0 ? writtenLength(stdout) : undefined;
250    if (length !== undefined) await update($, written, () => length);
251  } catch {
252    // No file, no tail, no process access: the rules decide.
253  }
254}
255
256// Read each time the check runs: the limits change, and arrive only with the first reading (A3.5).
257// $.env.get takes literal names only.
258async function cacheInputs($: EngineInterface): Promise<CacheInputs> {
259  const settings = (await $.settings.read().catch(() => ({}))) as {
260    promptCacheTtl?: unknown;
261  };
262  const r = (await read($, reading)) ?? (await engineReading($));
263
264  return {
265    env: {
266      DISABLE_PROMPT_CACHING: await $.env.get('DISABLE_PROMPT_CACHING'),
267      DISABLE_PROMPT_CACHING_HAIKU: await $.env.get(
268        'DISABLE_PROMPT_CACHING_HAIKU',
269      ),
270      DISABLE_PROMPT_CACHING_SONNET: await $.env.get(
271        'DISABLE_PROMPT_CACHING_SONNET',
272      ),
273      DISABLE_PROMPT_CACHING_OPUS: await $.env.get(
274        'DISABLE_PROMPT_CACHING_OPUS',
275      ),
276      DISABLE_PROMPT_CACHING_FABLE: await $.env.get(
277        'DISABLE_PROMPT_CACHING_FABLE',
278      ),
279      DISABLE_PROMPT_CACHING_MYTHOS: await $.env.get(
280        'DISABLE_PROMPT_CACHING_MYTHOS',
281      ),
282      FORCE_PROMPT_CACHING_5M: await $.env.get('FORCE_PROMPT_CACHING_5M'),
283      CLAUDE_CODE_PROMPT_CACHE_TTL: await $.env.get(
284        'CLAUDE_CODE_PROMPT_CACHE_TTL',
285      ),
286      ENABLE_PROMPT_CACHING_1H: await $.env.get('ENABLE_PROMPT_CACHING_1H'),
287    },
288    setting: settings.promptCacheTtl,
289    model: await $.session.model(),
290    rateLimits: r?.rateLimits ?? [],
291    cacheSeen: await read($, cacheSeen),
292    written: await read($, written),
293  };
294}
295
296// The cache warning's /config settings (plugin.json userConfig), defaults filled in by the engine.
297type ColdSettings = { warnCold: boolean; coldTokens: number };
298
299// Whether the cache is cold now, from the plugin's state and the engine; read where the line needs it.
300async function coldNow(
301  $: EngineInterface,
302  coldSettings: ColdSettings,
303): Promise<boolean> {
304  const inputs = await cacheInputs($);
305
306  return isCold({
307    ...coldSettings,
308    working: await read($, working),
309    lastRequest: await read($, lastRequest),
310    resumed: await read($, resumed),
311    cacheLength: cacheLength(inputs),
312    lengthFromFile: inputs.written !== null,
313    now: await $.clock.now(),
314  });
315}
316
317export const register: Register = (on, options) => {
318  const coldSettings: ColdSettings = {
319    warnCold: options.warnCold === true,
320    coldTokens: Number(options.coldTokens),
321  };
322
323  // One timer per module: session.start can fire again without a reload, and a reload drops the old timer itself.
324  let tick: Timer | undefined;
325
326  on('session.start', async ($, e, next) => {
327    tick?.cancel();
328    tick = $.clock.every(60_000, () => void update($, minute, (n) => n + 1));
329
330    return next(e);
331  });
332
333  on('session.measure', async ($, e, next) => {
334    const r = toReading(e);
335    await update($, reading, () => r);
336
337    // One toast per reading: the desktop app shows one toast per plugin at a time and drops the next.
338    // Toast before saving the records: a failed save repeats a toast later rather than losing it.
339    const crossed: { limit: LimitReading; window: Window; record: Toasted }[] =
340      [];
341    for (const limit of r.rateLimits) {
342      const window = WINDOWS[limit.kind];
343      const record = window && (await freshRecord($, limit));
344      if (window && record) crossed.push({ limit, window, record });
345    }
346    if (crossed.length > 0) $.ui.toast(toastText(crossed));
347    for (const { limit, record } of crossed) {
348      await $.store.set(`toasted:${limit.kind}`, record);
349    }
350
351    return next(e);
352  });
353
354  // $.state starts empty after /clear, /resume and /branch, and no request has told the plugin anything yet.
355  // A resume or fork reports the transcript's last response, so the bar knows the pause before the first message,
356  // and the file already holds that response's row.
357  on('classic.SessionStart', async ($, e, next) => {
358    const path = e.transcript_path;
359    if (path) await update($, transcript, () => path);
360    if (e.source === 'clear') {
361      await update($, lastRequest, () => null);
362      await update($, resumed, () => null);
363    }
364    if (
365      (e.source === 'resume' || e.source === 'fork') &&
366      e.seconds_since_last_response !== undefined &&
367      e.context_tokens !== undefined
368    ) {
369      const {
370        seconds_since_last_response: gapSeconds,
371        context_tokens: tokens,
372      } = e;
373      const at = (await $.clock.now()) - gapSeconds * 1000;
374      await update($, lastRequest, () => ({ at, tokens }));
375      await update($, resumed, () => ({
376        cacheLikelyExpired: e.prompt_cache_likely_expired ?? false,
377      }));
378    }
379    if (e.source === 'resume' || e.source === 'fork') await readWritten($);
380
381    return next(e);
382  });
383
384  // A compaction replaces the conversation with a summary, so the last size and a resume's verdict on it no
385  // longer hold; the next request reports the new size. A precompute installs nothing, a vetoed one changes
386  // nothing, a subagent's isn't ours.
387  on('session.compact', async ($, e, next) => {
388    const result = await next(e);
389    if (
390      e.agentId === undefined &&
391      e.trigger !== 'precompute' &&
392      result.skip === undefined
393    ) {
394      await update($, lastRequest, () => null);
395      await update($, resumed, () => null);
396    }
397
398    return result;
399  });
400
401  on('turn.start', async ($, e, next) => {
402    await update($, working, () => true);
403
404    return next(e);
405  });
406
407  // Every way a turn ends completes it: answered, interrupted, refused or failed. A subagent's run completes
408  // with its agentId while the main turn still runs; it raises no turn.start, and writes a file of its own.
409  // The reply's row lands in the file 300–600 ms after the request returns (A18), so read it a second later.
410  on('turn.complete', async ($, e, next) => {
411    if (e.agentId === undefined) {
412      await update($, working, () => false);
413      $.clock.after(1_000, () => void readWritten($));
414    }
415
416    return next(e);
417  });
418
419  // Subagents' requests (agentId set) run on their own cache, so only the main conversation's count.
420  on('turn.step', async function* ($, e, next) {
421    const result = yield* next(e);
422    const usage = result.usage;
423    if (e.agentId !== undefined || usage === null) return result;
424
425    const {
426      input_tokens,
427      output_tokens,
428      cache_read_input_tokens,
429      cache_creation_input_tokens,
430    } = usage;
431    const tokens =
432      input_tokens +
433      cache_read_input_tokens +
434      cache_creation_input_tokens +
435      output_tokens;
436    const at = await $.clock.now();
437    await update($, lastRequest, () => ({ at, tokens }));
438    await update($, resumed, () => null);
439    const cached =
440      cache_read_input_tokens > 0 || cache_creation_input_tokens > 0;
441    await update($, cacheSeen, () => ({ model: usage.model, cached }));
442
443    return result;
444  });
445
446  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
447    if (e.props.hasSurvey) return next(e);
448
449    const { Box, Text } = $.ui.resolve(e);
450
451    const usageLine = async () => {
452      // No reading until Claude Code's startup quota check, and none at all while not logged in: say so, so the line doesn't look missing.
453      const r = (await read($, reading)) ?? (await engineReading($));
454
455      if (r === null) {
456        return (
457          <Box
458            key="line"
459            flexDirection="row"
460            justifyContent="flex-end"
461            width="100%"
462          >
463            <Text dimColor>usage: no data yet</Text>
464          </Box>
465        );
466      }
467
468      await read($, minute);
469      const items = lineItems(
470        r,
471        e.props.bodyColumns,
472        await $.clock.now(),
473        await coldNow($, coldSettings),
474      );
475
476      // Never wrap: while a desktop window is resized, a frame can draw the layout chosen for the previous width,
477      // and a wrapped piece would make the row jump to two lines. Cut it short instead.
478      return (
479        <Box
480          key="line"
481          flexDirection="row"
482          justifyContent="flex-end"
483          columnGap={1}
484          width="100%"
485        >
486          {items.flatMap((item, i) => [
487            ...(i > 0
488              ? [
489                  <Text dimColor wrap="truncate-end">
490                    ·
491                  </Text>,
492                ]
493              : []),
494            <Box key={`item:${i}`} flexDirection="row">
495              {item.map(({ text, color }) =>
496                color ? (
497                  <Text color={color} wrap="truncate-end">
498                    {text}
499                  </Text>
500                ) : (
501                  <Text dimColor wrap="truncate-end">
502                    {text}
503                  </Text>
504                ),
505              )}
506            </Box>,
507          ])}
508        </Box>
509      );
510    };
511
512    // Other mods draw in this band too: their rows go below the line rather than being replaced.
513    // No width here: the engine refuses its own drawing under a Box that sets one.
514    return (
515      <Box flexDirection="column">
516        {await usageLine()}
517        {await next(e)}
518      </Box>
519    );
520  });
521};
522
hooks/cache.ts 169 lines
1// The cache warning's rules as plain functions: no engine calls, so they read and test on their own.
2// register.tsx gathers their inputs from the engine and the plugin's state.
3
4import type {
5  CacheSeen,
6  CacheWritten,
7  LastRequest,
8  LimitReading,
9  Resumed,
10} from '../types';
11
12// How long the main conversation's prompt cache lives, or 'off' when it isn't used.
13export type CacheLength = '5m' | '1h' | 'off';
14
15// What the cache length is worked out from: the env vars by name, the promptCacheTtl setting, the session's
16// model id as $.session.model() gives it (`claude-haiku-4-5`), the latest limit windows, what the latest
17// reply showed (cacheSeen), and the length the latest cache write used (written; null before one).
18export type CacheInputs = {
19  env: Partial<Record<CacheEnvName, string>>;
20  setting: unknown;
21  model: string;
22  rateLimits: LimitReading[];
23  cacheSeen: CacheSeen | null;
24  written: CacheWritten | null;
25};
26
27type CacheEnvName =
28  | 'DISABLE_PROMPT_CACHING'
29  | 'DISABLE_PROMPT_CACHING_HAIKU'
30  | 'DISABLE_PROMPT_CACHING_SONNET'
31  | 'DISABLE_PROMPT_CACHING_OPUS'
32  | 'DISABLE_PROMPT_CACHING_FABLE'
33  | 'DISABLE_PROMPT_CACHING_MYTHOS'
34  | 'FORCE_PROMPT_CACHING_5M'
35  | 'CLAUDE_CODE_PROMPT_CACHE_TTL'
36  | 'ENABLE_PROMPT_CACHING_1H';
37
38// Each per-model switch and the models it covers. Claude Code matches Fable and Mythos by these names, but
39// Haiku, Sonnet and Opus only on the family's default model (what `opus` resolves to), which a plugin can't
40// learn; the family name stands in for it until a reply shows what the cache did (A15).
41const MODEL_SWITCHES = [
42  ['claude-fable-', 'DISABLE_PROMPT_CACHING_FABLE'],
43  ['claude-mythos-', 'DISABLE_PROMPT_CACHING_MYTHOS'],
44  ['haiku', 'DISABLE_PROMPT_CACHING_HAIKU'],
45  ['sonnet', 'DISABLE_PROMPT_CACHING_SONNET'],
46  ['opus', 'DISABLE_PROMPT_CACHING_OPUS'],
47] as const;
48
49// One model however it is spelled: a reply names `claude-haiku-4-5-20251001` where $.session.model() gives
50// `claude-haiku-4-5`, and a context-window suffix (`[1m]`) may follow.
51const baseModel = (model: string) =>
52  model.replace(/\[.*\]$/, '').replace(/-\d{8}$/, '');
53
54// Off by a switch: all caching, or the model's own.
55const switchedOff = (i: CacheInputs) =>
56  isOn(i.env.DISABLE_PROMPT_CACHING) ||
57  MODEL_SWITCHES.some(
58    ([name, env]) => i.model.includes(name) && isOn(i.env[env]),
59  );
60
61// Claude Code's own reading of an on/off variable: `1`, `true`, `yes`, `on`, any case.
62const isOn = (value: string | undefined) =>
63  ['1', 'true', 'yes', 'on'].includes((value ?? '').trim().toLowerCase());
64
65const asLength = (value: unknown) =>
66  value === '5m' || value === '1h' ? value : undefined;
67
68// The limit windows Claude Code reports for a subscription (A9.1); a gateway's spend_limit is not one.
69const PLAN_WINDOWS = ['five_hour', 'seven_day'];
70
71// A subscriber within the plan's included usage gets 1 hour; on usage credits (a window at 100% while requests
72// still go through), with no windows (API key, cloud provider), it is 5 minutes.
73function withinIncludedUsage(rateLimits: LimitReading[]): boolean {
74  const windows = rateLimits.filter((limit) =>
75    PLAN_WINDOWS.includes(limit.kind),
76  );
77
78  return (
79    windows.length > 0 && windows.every((limit) => limit.percentUsed < 100)
80  );
81}
82
83// The first rule that applies, in Claude Code's own order (plan step 4, A9.1, checked live in A12).
84export function cacheLength(i: CacheInputs): CacheLength {
85  // A reply on this model shows whether caching is on; the switches decide only before one (after a resume or a
86  // /model change). Caching off shows as a request that reads and writes no cache (A7.6).
87  const seen =
88    i.cacheSeen && baseModel(i.cacheSeen.model) === baseModel(i.model)
89      ? i.cacheSeen.cached
90      : undefined;
91  if (seen === false || (seen === undefined && switchedOff(i))) return 'off';
92  // What the cache was written with is what the rules below only guess at (A18).
93  if (i.written !== null) return i.written;
94  if (isOn(i.env.FORCE_PROMPT_CACHING_5M)) return '5m';
95
96  return (
97    asLength(i.env.CLAUDE_CODE_PROMPT_CACHE_TTL) ??
98    asLength(i.setting) ??
99    (isOn(i.env.ENABLE_PROMPT_CACHING_1H)
100      ? '1h'
101      : withinIncludedUsage(i.rateLimits)
102        ? '1h'
103        : '5m')
104  );
105}
106
107// The newest row of the conversation file's tail whose reply wrote the cache, by its split (A18). Rows that only
108// read the cache split 0 and 0, and say nothing; the tail's first row may be cut in half.
109export function writtenLength(tail: string): CacheWritten | undefined {
110  for (const line of tail.split('\n').reverse()) {
111    const split = parseRow(line)?.message?.usage?.cache_creation;
112    if ((split?.ephemeral_1h_input_tokens ?? 0) > 0) return '1h';
113    if ((split?.ephemeral_5m_input_tokens ?? 0) > 0) return '5m';
114  }
115
116  return undefined;
117}
118
119type Row = {
120  message?: {
121    usage?: {
122      cache_creation?: {
123        ephemeral_1h_input_tokens?: number;
124        ephemeral_5m_input_tokens?: number;
125      };
126    };
127  };
128};
129
130function parseRow(line: string): Row | undefined {
131  try {
132    return JSON.parse(line) as Row;
133  } catch {
134    return undefined;
135  }
136}
137
138const LENGTH_MS = { '5m': 5 * 60_000, '1h': 60 * 60_000 } as const;
139
140// What the check reads: the user's settings (warnCold, coldTokens), whether a turn runs, the last request,
141// a resume's verdict, the cache length and whether the conversation file gave it, and the time now.
142export type ColdInputs = {
143  warnCold: boolean;
144  coldTokens: number;
145  working: boolean;
146  lastRequest: LastRequest | null;
147  resumed: Resumed | null;
148  cacheLength: CacheLength;
149  lengthFromFile: boolean;
150  now: number;
151};
152
153// Cold: the next message re-reads the whole context at the cache-write price (plan step 5).
154// Right after a resume, Claude Code's own verdict counts only when the file gave no length: it goes by the last
155// reply's split alone, and by its rules when that reply only read the cache (A18).
156export function isCold(i: ColdInputs): boolean {
157  if (
158    !i.warnCold ||
159    i.working ||
160    i.cacheLength === 'off' ||
161    i.lastRequest === null
162  )
163    return false;
164  if (i.lastRequest.tokens < i.coldTokens) return false;
165  if (i.resumed?.cacheLikelyExpired && !i.lengthFromFile) return true;
166
167  return i.now - i.lastRequest.at > LENGTH_MS[i.cacheLength];
168}
169
types/index.d.ts 41 lines
1export type LimitReading = {
2  kind: string;
3  percentUsed: number;
4  resetsAt?: string;
5};
6
7export type Reading = {
8  contextPercent?: number;
9  usd?: number;
10  rateLimits: LimitReading[];
11};
12
13// The main conversation's latest model request: when its response arrived, and the context it carried
14// (input + cache read + cache write + output tokens).
15export type LastRequest = { at: number; tokens: number };
16
17// Claude Code's verdict on the cache when a session was resumed or forked, kept until its first request.
18export type Resumed = { cacheLikelyExpired: boolean };
19
20// What the main conversation's latest reply showed: the model that answered (`claude-haiku-4-5-20251001`) and
21// whether the request read or wrote the prompt cache.
22export type CacheSeen = { model: string; cached: boolean };
23
24// The length the main conversation's latest reply with a cache write wrote it with, from the conversation file (A18).
25export type CacheWritten = '5m' | '1h';
26
27declare module 'claude-code' {
28  interface PluginState {
29    'usage-bar': {
30      reading: Reading | null;
31      minute: number;
32      lastRequest: LastRequest | null;
33      cacheSeen: CacheSeen | null;
34      working: boolean;
35      resumed: Resumed | null;
36      transcript: string | null;
37      written: CacheWritten | null;
38    };
39  }
40}
41