SLOPSHOPPER

cc-cost

Minimal band above the prompt with session and daily tokens, context and usage limits

bandtoast
v0.6.1MITupdated 2026-10-17edsoncantuaria/cc-cost
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cc-cost
› 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 ▁ 0 tokens · ↑ 0 ↓ 0 · cache 0% · today 0 · 5h 31% · ctx 97k/200k [ compact ] ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▁ 0 tokens · ↑ 0 ↓ 0 · cache 0% · today 0 · 5h 31% · ctx 97k/200k [ compact ] ⟨Claude Code's own drawing⟩
README

💸 cc-cost

What your Claude Code session is using — live, right above the prompt.

Tokens, context and your subscription's 5h / 7d windows — not API dollars.

Claude Code Mod License: MIT No telemetry

English · Português · Español

<img src="docs/band.png" alt="cc-cost band above the Claude Code prompt" width="100%">

<sub>⚡ zero config &nbsp;•&nbsp; 🔒 100% local &nbsp;•&nbsp; 🎯 one-key compaction &nbsp;•&nbsp; 🌈 color-coded limits</sub>


🚀 Install

At the prompt of a Claude Code session:

/plugin install cc-cost --marketplace edsoncantuaria/cc-cost

[!TIP] Answer y to add the marketplace, then pick a scope. The band shows up on the next turn — nothing to configure.


🔎 Reading the band

| | Segment | Meaning | | :-: | --- | --- | | 🧮 | 19k tokens | New tokens in the session: input + cache writes + output. A volume, not your quota: each kind weighs differently in the windows, so the 5h / 7d % is what you actually spend | | ↕️ | ↑ 19k ↓ 30 | Input / output split | | ♻️ | cache 83% | Share of input served from cache reads — left out of the total, since they resend the same context every request | | 📅 | today 156k | Today's total across every session, kept locally for 7 days | | ⏱️ | 5h 9% 7d 10% | Subscription usage windows (and spend limit, when set) | | 🧠 | ctx 111k/1.0M | Current context against the auto-compact window | | 📈 | ▁▃▅█ | Sparkline of new tokens per turn | | 🗜️ | [ compact ] | One-key (c) compaction, picking the cheaper mode | | 🤖 | subagents | Count and largest context while they run; their tokens count toward today, not the session |

🚦 Colors

| Color | Usage windows | Context | | :-: | --- | --- | | 🟢 | comfortable | plenty of room | | 🟡 | rising — keep an eye on it | getting close to the compaction window | | 🔴 | close to the limit | compact now, before autocompact kicks in |


🌐 Language

The band and its notices follow your system locale (LC_ALL, LC_MESSAGES, LANG): Portuguese, Spanish, or English for anything else. To pin one, set cc-cost.language in /config to en, pt-BR or es (auto is the default).


🗜️ Smart compaction

The compact button picks what costs less:

flowchart LR
    A([compact · c]) --> B{File reads ≥ 40%<br>of the conversation?}
    B -- yes --> C["/compact micro<br><sub>drops stale reads</sub>"]
    B -- no --> D["/compact<br><sub>focused summary</sub>"]

[!NOTE] micro needs the micro-compaction plugin. Without it, the button falls back to the native /compact and tells you so. When the context turns 🔴, a toast says which mode the button will use and, for micro, how much of the conversation is file reads.


🤔 Why not ccusage?

ccusagecc-cost
MeasuresAPI dollarssubscription windows
Whenafter the fact, from logslive, inside the session
Whereseparate commandabove the prompt
Context & compaction—✅

On a Pro/Max subscription the dollar estimate isn't what you pay — the limit that matters is the 5h window, right now.


📋 Requirements

  • Claude Code 2.1.287+ with mods (function hooks, early access).
  • Optional: the micro-compaction plugin for micro mode.

🛠️ Development

git clone https://github.com/edsoncantuaria/cc-cost ~/.claude/mods/cc-cost
claude plugin validate ~/.claude/mods/cc-cost   # check manifest + hooks
claude plugin test     ~/.claude/mods/cc-cost   # run the test suite
claude --plugin-dir    ~/.claude/mods/cc-cost   # try it in one session

To load the clone in every session, set CLAUDE_CODE_PLUGIN_DIRS to its folder in the env block of ~/.claude/settings.json and restart Claude Code.

[!WARNING] Copying the folder alone doesn't load it. And don't combine a local clone with the marketplace install, or the band is drawn twice.

Code layout

FileOwns
hooks/register.tsxwiring only: which event calls what
hooks/accounting.tstoken counting, the daily store, context thresholds
hooks/compaction.tsthe compact button's policy (micro vs. summary), the 🔴 notice, the micro-compaction contract
hooks/band.tsxdrawing the band
hooks/texts.tstranslations and number formatting
hooks/state.tsthe session state ($.state atoms); the only file that reads or writes it
hooks/runtime.tswrite ordering and safe, which keeps a failure of the mod out of your turn

Everything the mod remembers lives in the session's $.state (or $.store for the daily totals), so a hot reload keeps it; the module itself holds no mutable state. What cc-cost assumes about the micro-compaction plugin (which ships no types) is gathered in one MICRO object in compaction.ts.

🔒 Privacy

No network, no telemetry. It only reads the session usage Claude Code already provides and keeps daily counters in the mod's local store.


Made with ☕ by @edsoncantuaria · MIT

<sub>If it saves your 5h window, leave a ⭐</sub>

Source 8 files
hooks/register.tsx 162 lines
1import type { Register } from 'claude-code'
2
3import { add, BARS, compactionWindow, day, daySum, limits, prune, setAgent } from './accounting'
4import { drawBand } from './band'
5import { afterCompaction, warnOnRed } from './compaction'
6import { runtime, safe } from './runtime'
7import { EMPTY, readSpend, updateSpend, ZERO } from './state'
8import { chooseLanguage } from './texts'
9
10export const register: Register = (on, options) => {
11  // A new load (mod reload, another option) starts its own write order; the data stays in $.state.
12  const rt = runtime(options.language)
13
14  on('session.start', async ($, e, next) => {
15    await safe($, rt, 'session.start', () =>
16      rt.enqueue(async () => {
17        await chooseLanguage($, options.language)
18        const now = await $.clock.now()
19        await prune($, now)
20        const current = (await readSpend($)) ?? EMPTY
21        const today = day(now)
22        const todayTotal = await daySum($, today, current.own)
23        const { rateLimits, context } = await $.session.usage()
24        const window = await compactionWindow($)
25        await updateSpend($, a => ({
26          ...(a ?? EMPTY),
27          today: todayTotal,
28          day: today,
29          limits: rateLimits.length > 0 ? limits(rateLimits) : (a?.limits ?? []),
30          context: context.tokens ?? a?.context ?? null,
31          window,
32          modelWindow: context.window,
33          // On a mod reload the old list may hold an agent already done; those still running come back on their
34          // next step, recognized by $.agent.list().
35          agents: {},
36        }))
37      }),
38    )
39
40    return next(e)
41  })
42
43  // Only the main thread opens a turn: each turn is a bar. A subagent goes into the list of running ones.
44  on('turn.start', async ($, e, next) => {
45    const id = e.agentId
46    await safe($, rt, 'turn.start', () =>
47      rt.enqueue(() =>
48        id !== undefined
49          ? setAgent($, id, current => current ?? 0)
50          : updateSpend($, a => {
51              const s = a ?? EMPTY
52
53              return { ...s, turns: [...s.turns, 0].slice(-BARS), inTurn: true }
54            }),
55      ),
56    )
57
58    return next(e)
59  })
60
61  on('turn.complete', async ($, e, next) => {
62    const id = e.agentId
63    await safe($, rt, 'turn.complete', () =>
64      rt.enqueue(() =>
65        id === undefined
66          ? updateSpend($, a => (a ? { ...a, inTurn: false } : a))
67          : setAgent($, id, () => null),
68      ),
69    )
70
71    return next(e)
72  })
73
74  // Each request to the model: main thread, subagent or an engine process (compaction).
75  // Compaction comes with an agentId but no turn.start: it stays out of the list and counts as the main thread's.
76  on('turn.step', async function* ($, e, next) {
77    const response = yield* next(e)
78    const usage = response.usage
79    if (!usage) return response
80    const id = e.agentId
81    await safe($, rt, 'turn.step', () =>
82      // Inside the queue: a subagent's turn.start that came before this step is already in the list.
83      rt.enqueue(async () => {
84        if (id === undefined) return add($, usage, true)
85        // Out of the list: an engine fork (compaction), which $.agent.list() does not name, or a subagent
86        // whose turn.start came before a mod reload, which it does and goes back into the list.
87        const known = (await readSpend($))?.agents?.[id] !== undefined
88        if (!known && !(await $.agent.list()).some(a => a.id === id)) return add($, usage, true)
89        await add($, usage, false)
90        const occupied = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
91        await setAgent($, id, () => occupied)
92      }),
93    )
94
95    return response
96  })
97
98  on('session.measure', async ($, e, next) => {
99    await safe($, rt, 'session.measure', () =>
100      rt.enqueue(async () => {
101        const current = (await readSpend($)) ?? EMPTY
102        const today = day(await $.clock.now())
103        const todayTotal = await daySum($, today, current.own)
104        const context = e.context.tokens ?? current.context
105        // /model (or a new autoCompactWindow) moves the model's window: the compaction window comes along, measured again.
106        const window = e.context.window !== current.modelWindow ? await compactionWindow($) : current.window
107        await updateSpend($, a => ({
108          ...(a ?? EMPTY),
109          today: todayTotal,
110          day: today,
111          limits: e.rateLimits.length > 0 ? limits(e.rateLimits) : (a?.limits ?? []),
112          context: e.context.tokens ?? a?.context ?? null,
113          window,
114          modelWindow: e.context.window,
115        }))
116        await warnOnRed($, rt, current.context, context, window)
117      }),
118    )
119
120    return next(e)
121  })
122
123  on('session.compact', async ($, e, next) => {
124    const r = await next(e)
125    if (e.trigger !== 'precompute' && e.agentId === undefined && r.messages) {
126      await safe($, rt, 'session.compact', () => afterCompaction($, rt, e, r))
127    }
128
129    return r
130  })
131    // Should the hook fail anyway, the compaction goes on as the engine did it.
132    .catch(($, e, next) => next(e))
133
134  // /clear goes on in the same process with another id and no session.start: only the session resets.
135  on('session.end', async ($, e, next) => {
136    if (e.reason === 'clear') {
137      await safe($, rt, 'session.end', () =>
138        rt.enqueue(() =>
139          updateSpend($, a => (a ? { ...a, session: ZERO, turns: [], inTurn: false, context: null, agents: {} } : a)),
140        ),
141      )
142    }
143
144    return next(e)
145  })
146
147  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
148    const band = await drawBand($, e, rt)
149    if (band === null) return next(e)
150    // Composes with whoever comes next in the chain: another mod's notice or controls must not vanish.
151    const below = await next(e)
152    const { Box } = $.ui.resolve(e)
153
154    return (
155      <Box flexDirection="column">
156        {band}
157        {below}
158      </Box>
159    )
160  })
161}
162
hooks/accounting.ts 134 lines
1import type { EngineInterface, ModelUsage, SessionRateLimit } from 'claude-code'
2
3import type { Limit, Spend, Tokens } from '../types'
4import { EMPTY, readSpend, updateSpend } from './state'
5
6export const BARS = 12
7const DAYS_KEPT = 7
8
9// Headroom to the compaction window: red leaves ~30k to compact before autocompact. On large windows a
10// fixed headroom would turn yellow only when nearly full, so the headroom grows with the window.
11const WARN_HEADROOM = 60_000
12const SWITCH_HEADROOM = 30_000
13const WARN_SHARE = 0.15
14const SWITCH_SHARE = 0.075
15// Window used for the thresholds until the engine's first reading: the default of 200k models.
16const DEFAULT_WINDOW = 200_000
17// Daily counters live under `novos:<day>:<sessionId>`; the prefix predates the English code and stays so stored totals survive.
18const DAY_PREFIX = 'novos:'
19// Keys the mod no longer uses: the old version's and the recap of the old "new session" button.
20const STALE_KEYS = ['dia:', 'tokens:', 'ultimoRecap']
21
22/** Local date YYYY-MM-DD; alphabetical order is chronological order. */
23export function day(ms: number): string {
24  const d = new Date(ms)
25  const p = (n: number) => String(n).padStart(2, '0')
26
27  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`
28}
29
30/** Cache reads stay out: it is the same context resent on every request, and adding it counts the conversation many times. */
31export function fresh(t: Tokens): number {
32  return t.input + t.cacheWrite + t.output
33}
34
35export function thresholds(window: number | null): { warn: number; switch: number } {
36  const total = window ?? DEFAULT_WINDOW
37
38  return {
39    warn: total - Math.max(WARN_HEADROOM, total * WARN_SHARE),
40    switch: total - Math.max(SWITCH_HEADROOM, total * SWITCH_SHARE),
41  }
42}
43
44/** The compaction window (autoCompactWindow), not the model's; the `summary` breakdown is estimated locally, with no request. */
45export async function compactionWindow($: EngineInterface): Promise<number> {
46  const { context } = await $.session.usage({ breakdown: 'summary' })
47
48  return context.breakdown?.rawMaxTokens ?? context.window
49}
50
51/** Updates the list of running subagents; `null` drops the agent. Runs inside the queue. */
52export function setAgent($: EngineInterface, id: string, change: (current: number | undefined) => number | null | undefined) {
53  return updateSpend($, a => {
54    const s = a ?? EMPTY
55    const agents = { ...s.agents }
56    const next = change(agents[id])
57    if (next === undefined) return s
58    if (next === null) delete agents[id]
59    else agents[id] = next
60
61    return { ...s, agents }
62  })
63}
64
65export function limits(windows: readonly SessionRateLimit[]): Limit[] {
66  return windows.map(({ kind, percentUsed, resetsAt }) => ({ kind, percentUsed, ...(resetsAt ? { resetsAt } : {}) }))
67}
68
69/**
70 * Each session writes only its own key `novos:<day>:<sessionId>`: two open sessions
71 * do not erase each other's sum, and resuming the same session picks up where it stopped.
72 */
73export async function daySum($: EngineInterface, today: string, own: Spend['own']): Promise<number> {
74  const prefix = `${DAY_PREFIX}${today}:`
75  const others = (await $.store.keys()).filter(key => key.startsWith(prefix) && key !== own.key)
76  const values = await Promise.all(others.map(key => $.store.get(key)))
77
78  return values.reduce<number>((sum, v) => sum + Number(v ?? 0), own.key.startsWith(prefix) ? own.n : 0)
79}
80
81export async function prune($: EngineInterface, now: number) {
82  const cutoff = `${DAY_PREFIX}${day(now - DAYS_KEPT * 86_400_000)}`
83  for (const key of await $.store.keys()) {
84    const old = key.startsWith(DAY_PREFIX) ? key < cutoff : STALE_KEYS.some(p => key.startsWith(p))
85    if (old) await $.store.delete(key)
86  }
87}
88
89/** A subagent stays out of the session and the bars (which are the main thread's), but goes into `today`. Runs inside the queue. */
90export async function add($: EngineInterface, usage: ModelUsage, main: boolean) {
91  const t: Tokens = {
92    input: usage.input_tokens,
93    output: usage.output_tokens,
94    cacheRead: usage.cache_read_input_tokens,
95    cacheWrite: usage.cache_creation_input_tokens,
96  }
97  const n = fresh(t)
98  if (n === 0 && t.cacheRead === 0) return
99
100  const today = day(await $.clock.now())
101  const key = `${DAY_PREFIX}${today}:${await $.session.id()}`
102  const current = (await readSpend($)) ?? EMPTY
103  const sameKey = current.own.key === key
104  const before = sameKey ? current.own.n : Number((await $.store.get(key)) ?? 0)
105  const own = { key, n: before + n }
106  await $.store.set(key, own.n)
107  // On the same key `today` already holds the other sessions: adding the step is enough. The other sessions
108  // come in again on session.measure; scanning the store on every request only when the day or the session changed.
109  const todayTotal = sameKey ? current.today + n : await daySum($, today, own)
110
111  await updateSpend($, a => {
112    const s = a ?? EMPTY
113    if (!main) return { ...s, today: todayTotal, day: today, own }
114    // Compaction and work outside a turn go into the total only.
115    const turns = s.inTurn && s.turns.length > 0
116      ? [...s.turns.slice(0, -1), (s.turns.at(-1) ?? 0) + n]
117      : s.turns
118
119    return {
120      ...s,
121      session: {
122        input: s.session.input + t.input,
123        output: s.session.output + t.output,
124        cacheRead: s.session.cacheRead + t.cacheRead,
125        cacheWrite: s.session.cacheWrite + t.cacheWrite,
126      },
127      today: todayTotal,
128      day: today,
129      own,
130      turns,
131    }
132  })
133}
134
hooks/band.tsx 135 lines
1import type { EngineInterface, RenderElement, RenderInput } from 'claude-code'
2
3import type { Mode, Spend } from '../types'
4import { day, fresh, thresholds } from './accounting'
5import { compactNow } from './compaction'
6import type { Runtime } from './runtime'
7import { safe, texts } from './runtime'
8import { readCompacting, readFailing, readSpend } from './state'
9import type { Texts } from './texts'
10import { short } from './texts'
11
12const LEVELS = '▁▂▃▄▅▆▇█'
13
14function sparkline(values: number[]): string {
15  const largest = Math.max(1, ...values)
16
17  return values.map(v => LEVELS[Math.min(LEVELS.length - 1, Math.floor((v / largest) * LEVELS.length))]).join('')
18}
19
20function color(pct: number): string {
21  if (pct >= 85) return 'red'
22  if (pct >= 60) return 'yellow'
23
24  return 'green'
25}
26
27function contextColor(tokens: number, window: number | null): string {
28  const t = thresholds(window)
29  if (tokens >= t.switch) return 'red'
30  if (tokens >= t.warn) return 'yellow'
31
32  return 'green'
33}
34
35type AbovePrompt = RenderInput<'AbovePrompt'>
36
37/** The band, or null when there is nothing to show yet (or no data to show it with). */
38export async function drawBand($: EngineInterface, e: AbovePrompt, rt: Runtime): Promise<RenderElement | null> {
39  let s: Spend | null
40  let t: Texts
41  let now: number
42  let running: Mode | null
43  let stale: boolean
44  try {
45    s = await readSpend($)
46    t = await texts($, rt)
47    now = await $.clock.now()
48    running = await readCompacting($)
49    stale = (await readFailing($)) !== null
50  } catch {
51    // Without the data the band has nothing to show: the chain goes on without it.
52    return null
53  }
54  if (e.props.hasSurvey || s === null) return null
55
56  const ss = s.session
57  const inputTotal = ss.input + ss.cacheRead + ss.cacheWrite
58  if (inputTotal + ss.output === 0 && s.today === 0 && s.limits.length === 0 && s.context === null && !stale) return null
59
60  const { Box, Button, Text } = $.ui.resolve(e)
61  const k = (n: number) => short(n, t.decimal)
62  const busy = e.props.isWorking || running !== null
63  const cache = inputTotal > 0 ? Math.round((ss.cacheRead / inputTotal) * 100) : 0
64  // Past midnight with no count yet: yesterday's total is not today's.
65  const today = s.day === day(now) ? s.today : 0
66  const dot = <Text dimColor>  ·  </Text>
67  // Before its first response a subagent has no measured context yet.
68  const agents = Object.values(s.agents ?? {}).filter(n => n > 0)
69  const largest = Math.max(0, ...agents)
70  const limit = thresholds(s.window)
71
72  return (
73    <Box paddingX={1} flexDirection="row">
74      <Text wrap="truncate-end">
75        {stale && <Text color="yellow">{`⚠ ${t.stale}  `}</Text>}
76        {s.turns.length > 0 && <Text color="cyan">{sparkline(s.turns)}  </Text>}
77        <Text bold>{k(fresh(ss))}</Text>
78        <Text dimColor> tokens</Text>
79        {dot}
80        <Text dimColor>↑ </Text>
81        <Text>{k(ss.input + ss.cacheWrite)}</Text>
82        <Text dimColor>  ↓ </Text>
83        <Text>{k(ss.output)}</Text>
84        {dot}
85        <Text dimColor>cache </Text>
86        <Text>{cache}%</Text>
87        {dot}
88        <Text dimColor>{`${t.today} `}</Text>
89        <Text bold>{k(today)}</Text>
90        {s.limits.map(l => {
91          // The window already rolled over and no new response brought the value: do not show the old one.
92          const pct = l.resetsAt && Date.parse(l.resetsAt) <= now ? 0 : l.percentUsed
93
94          return (
95            <Text key={l.kind}>
96              {dot}
97              <Text dimColor>{t.labels[l.kind] ?? l.kind} </Text>
98              <Text color={color(pct)}>{Math.round(pct)}%</Text>
99            </Text>
100          )
101        })}
102      </Text>
103      {/* Outside the truncating text: on a narrow terminal the context is the last to go. */}
104      {s.context !== null && (
105        <Text>
106          {dot}
107          <Text dimColor>ctx </Text>
108          <Text color={contextColor(s.context, s.window)}>{k(s.context)}</Text>
109          {s.window !== null && <Text dimColor>/{k(s.window)}</Text>}
110        </Text>
111      )}
112      {agents.length > 0 && (
113        <Text>
114          {dot}
115          <Text dimColor>{`${agents.length === 1 ? t.agent : t.agents(agents.length)} `}</Text>
116          <Text color={contextColor(largest, s.window)}>{k(largest)}</Text>
117        </Text>
118      )}
119      <Text>  </Text>
120      {busy ? (
121        e.props.isWorking || running === null ? null : <Text dimColor>{t.compacting(running)}</Text>
122      ) : (
123        <Button
124          key="compact"
125          label="compact"
126          hotkey="c"
127          variant={s.context !== null && s.context >= limit.switch ? 'primary' : undefined}
128          dimColor={s.context === null || s.context < limit.warn}
129          onPress={() => safe($, rt, 'compact', () => compactNow($, rt))}
130        />
131      )}
132    </Box>
133  )
134}
135
hooks/compaction.ts 121 lines
1import type { EngineInterface, SessionCompacted, SessionCompactInput, SessionMessage } from 'claude-code'
2
3import type { Mode } from '../types'
4import { thresholds } from './accounting'
5import type { Runtime } from './runtime'
6import { message, texts } from './runtime'
7import { readCompacting, updateCompacting, updateSpend } from './state'
8import { short } from './texts'
9
10/**
11 * Everything this mod assumes about the micro-compaction plugin, which ships no types to depend on.
12 * It answers only a typed `/compact micro`, in core's place, with the rewritten messages alone: no request
13 * of its own (`usage`) and no size (`tokensAfter`). A file read it removed leaves `elided` in its result.
14 * Should that plugin change any of this, here is the one place to follow it.
15 */
16const MICRO = {
17  command: { command: 'compact', args: 'micro' },
18  isAsked: (e: SessionCompactInput) => e.instructions?.trim().toLowerCase() === 'micro',
19  elided: / elided by compaction: /,
20  /** A "micro" that came back with a request or a size was core's summary: the plugin did not answer. */
21  answeredByCore: (r: SessionCompacted) => r.usage !== undefined || r.tokensAfter !== undefined,
22} as const
23
24// From this share of the conversation in file reads on, micro is worth rewriting the whole cache.
25const MICRO_SHARE = 0.4
26// Rough figure for the ctx right after a micro compaction, which reports no size; the engine's next measure replaces it.
27const CHARS_PER_TOKEN = 4
28
29function chars(msgs: readonly SessionMessage[]): number {
30  let n = 0
31  for (const m of msgs) n += m.text.length + (m.toolResults ?? []).reduce((s, r) => s + r.text.length, 0)
32
33  return n
34}
35
36/**
37 * Share of the conversation's text held by file reads (Read) still whole: what /compact micro removes.
38 * Characters against characters, so no token ratio is assumed.
39 */
40function readShare(msgs: readonly SessionMessage[]): number {
41  const reads = new Set(msgs.flatMap(m => m.toolUses.filter(u => u.tool === 'Read').map(u => u.tool_use_id)))
42  let readChars = 0
43  for (const m of msgs) {
44    for (const r of m.toolResults ?? []) {
45      if (reads.has(r.tool_use_id) && !r.isError && !MICRO.elided.test(r.text)) readChars += r.text.length
46    }
47  }
48  const total = chars(msgs)
49
50  return total > 0 ? readChars / total : 0
51}
52
53/** Micro when the reads weigh on the conversation; otherwise the summary, which shrinks the conversation itself. */
54function mode(share: number): Mode {
55  return share >= MICRO_SHARE ? 'micro' : 'summary'
56}
57
58/**
59 * Compacts the way that pays off most now. Micro goes as a typed /compact, the only trigger the plugin
60 * answers. The summary goes directly, and ctx gets here the size it left, because this mod's
61 * session.compact hook does not run on the call the mod makes itself.
62 */
63export async function compactNow($: EngineInterface, rt: Runtime) {
64  const t = await texts($, rt)
65  let chosen = null as Mode | null
66  try {
67    // Checked and claimed inside the queue: two presses in a row see each other's claim, and only the first compacts.
68    await rt.enqueue(async () => {
69      if ((await readCompacting($)) !== null) return
70      const picked = mode(readShare(await $.session.messages()))
71      await updateCompacting($, () => picked)
72      chosen = picked
73    })
74    if (chosen === null) return
75    if (chosen === 'micro') {
76      await $.command.run(MICRO.command)
77      return
78    }
79    const r = await $.session.compact({ instructions: t.focus })
80    // Vetoed by a hook: the engine itself shows the line with the reason.
81    if (r.skip !== undefined) return
82    const after = r.tokensAfter ?? null
83    await rt.enqueue(() => updateSpend($, a => (a ? { ...a, context: after } : a)))
84  } catch (error) {
85    $.ui.toast(t.compactFailed(message(error)))
86  } finally {
87    if (chosen !== null) await updateCompacting($, () => null)
88  }
89}
90
91/**
92 * Only on the way up through the red threshold: after /clear or a compaction the context drops and the notice
93 * applies again. Says what the button would do now.
94 */
95export async function warnOnRed($: EngineInterface, rt: Runtime, before: number | null, context: number | null, window: number | null) {
96  const limit = thresholds(window).switch
97  if (context === null || context < limit || (before !== null && before >= limit)) return
98  const t = await texts($, rt)
99  const share = readShare(await $.session.messages())
100  const does = mode(share) === 'micro' ? t.dropsReads(Math.round(share * 100)) : t.summarizes
101  $.ui.toast(t.red(short(context, t.decimal), window ? short(window, t.decimal) : null, does))
102}
103
104/**
105 * After a compaction the engine only measures the context on the next response: until then, the size it left.
106 * Micro does not report that size: the estimate of what left the messages stands in. Runs inside `safe`.
107 */
108export async function afterCompaction($: EngineInterface, rt: Runtime, e: SessionCompactInput, r: SessionCompacted) {
109  const reported = r.tokensAfter
110  const removed = Math.round((chars(e.messages) - chars(r.messages)) / CHARS_PER_TOKEN)
111  await rt.enqueue(() =>
112    updateSpend($, a => {
113      if (!a) return a
114      const estimated = a.context === null ? null : Math.max(0, a.context - removed)
115
116      return { ...a, context: reported ?? estimated }
117    }),
118  )
119  if (MICRO.isAsked(e) && MICRO.answeredByCore(r)) $.ui.toast((await texts($, rt)).microBecameSummary)
120}
121
hooks/runtime.ts 75 lines
1import type { EngineInterface, PluginOptions } from 'claude-code'
2
3import { readFailing, readWarned, updateFailing, updateWarned } from './state'
4import type { Texts } from './texts'
5import { textsOf } from './texts'
6
7export type Runtime = {
8  /** Runs `task` after every task enqueued before it. */
9  enqueue: (task: () => Promise<unknown>) => Promise<void>
10  /** The mod's `language` option of this load. */
11  language: PluginOptions[string] | undefined
12}
13
14export function message(error: unknown): string {
15  return error instanceof Error ? error.message : String(error)
16}
17
18/** Updates the hooks whose last run failed; a state that fails too leaves only the toast. */
19async function markFailing($: EngineInterface, hook: string, failed: boolean) {
20  try {
21    if (((await readFailing($)) ?? []).includes(hook) === failed) return
22    await updateFailing($, list => {
23      const rest = (list ?? []).filter(h => h !== hook)
24      const next = failed ? [...rest, hook] : rest
25
26      return next.length > 0 ? next : null
27    })
28  } catch {
29    // The toast already went out (or will): the band just misses the marker.
30  }
31}
32
33/**
34 * One per load of the module, built by `register`: the session's data lives in $.state, so the only thing
35 * kept here is the order of the writes. Reading the store, adding and writing must not interleave between
36 * parallel steps (subagents), or one sum erases the other; and a subagent's turn.start must land before its step.
37 */
38export function runtime(language: PluginOptions[string] | undefined): Runtime {
39  let queue: Promise<unknown> = Promise.resolve()
40
41  return {
42    language,
43    enqueue(task) {
44      const turn = queue.then(task).then(() => undefined)
45      queue = turn.catch(() => undefined)
46
47      return turn
48    },
49  }
50}
51
52export function texts($: EngineInterface, rt: Runtime): Promise<Texts> {
53  return textsOf($, rt.language)
54}
55
56/**
57 * The mod only observes: a failure of its own never takes down the turn or the session. The toast goes out
58 * once per session; the band stays marked while `hook` keeps failing and clears on its next success.
59 */
60export async function safe($: EngineInterface, rt: Runtime, hook: string, task: () => Promise<unknown>): Promise<void> {
61  try {
62    await task()
63    await markFailing($, hook, false)
64  } catch (error) {
65    await markFailing($, hook, true)
66    try {
67      if (await readWarned($)) return
68      await updateWarned($, () => true)
69      $.ui.toast((await texts($, rt)).failed(message(error)))
70    } catch {
71      // Not even the notice went out: there is no one left to tell.
72    }
73  }
74}
75
hooks/state.ts 56 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface } from 'claude-code'
3
4import type { Language, Mode, Spend, Tokens } from '../types'
5
6// Everything the mod remembers lives here, in the session's $.state: per session, kept across hot reloads.
7// The other files reach it only through these functions, since the engine's scan reads each atom where it is declared.
8const spend = atom({ plugin: 'cc-cost', key: 'spend' } as const, null)
9const compacting = atom({ plugin: 'cc-cost', key: 'compacting' } as const, null)
10const failing = atom({ plugin: 'cc-cost', key: 'failing' } as const, null)
11const warned = atom({ plugin: 'cc-cost', key: 'warned' } as const, false)
12const language = atom({ plugin: 'cc-cost', key: 'language' } as const, null)
13
14export const ZERO: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
15export const EMPTY: Spend = { session: ZERO, today: 0, day: '', own: { key: '', n: 0 }, turns: [], inTurn: false, limits: [], context: null, window: null, modelWindow: null, agents: {} }
16
17export function readSpend($: EngineInterface) {
18  return read($, spend)
19}
20
21export function updateSpend($: EngineInterface, change: (s: Spend | null) => Spend | null) {
22  return update($, spend, change)
23}
24
25export function readCompacting($: EngineInterface) {
26  return read($, compacting)
27}
28
29export function updateCompacting($: EngineInterface, change: (m: Mode | null) => Mode | null) {
30  return update($, compacting, change)
31}
32
33export function readFailing($: EngineInterface) {
34  return read($, failing)
35}
36
37export function updateFailing($: EngineInterface, change: (hooks: string[] | null) => string[] | null) {
38  return update($, failing, change)
39}
40
41export function readWarned($: EngineInterface) {
42  return read($, warned)
43}
44
45export function updateWarned($: EngineInterface, change: (w: boolean) => boolean) {
46  return update($, warned, change)
47}
48
49export function readLanguage($: EngineInterface) {
50  return read($, language)
51}
52
53export function updateLanguage($: EngineInterface, change: (l: Language | null) => Language | null) {
54  return update($, language, change)
55}
56
hooks/texts.ts 127 lines
1import type { EngineInterface, PluginOptions } from 'claude-code'
2
3import type { Language, Mode } from '../types'
4import { readLanguage, updateLanguage } from './state'
5
6export type Texts = {
7  decimal: string
8  today: string
9  labels: Record<string, string>
10  agent: string
11  agents: (n: number) => string
12  modes: Record<Mode, string>
13  compacting: (mode: Mode) => string
14  focus: string
15  compactFailed: (error: string) => string
16  red: (context: string, window: string | null, does: string) => string
17  dropsReads: (percent: number) => string
18  summarizes: string
19  microBecameSummary: string
20  failed: (error: string) => string
21  stale: string
22}
23
24const TEXTS: Record<Language, Texts> = {
25  en: {
26    decimal: '.',
27    today: 'today',
28    labels: { five_hour: '5h', seven_day: '7d', spend_limit: 'limit' },
29    agent: 'agent',
30    agents: n => `${n} agents, largest`,
31    modes: { micro: 'micro', summary: 'summary' },
32    compacting: m => `compacting (${TEXTS.en.modes[m]})…`,
33    focus:
34      'Prioritize what is needed to continue the work: goal, changed files (with paths), ' +
35      'decisions and why, current state (tests, what is broken), next steps and open items.',
36    compactFailed: error => `Could not compact (${error}); the session stays as it is.`,
37    red: (ctx, window, does) => `Context at ${ctx}${window ? ` of ${window}` : ''}: "compact" in the band (c) ${does}, before autocompact.`,
38    dropsReads: pct => `removes the file reads, ~${pct}% of the conversation (micro)`,
39    summarizes: 'summarizes the conversation',
40    microBecameSummary: '/compact micro became a summary: the micro-compaction plugin is not active.',
41    failed: error => `cc-cost: counting failed (${error}); the session goes on, the band may lag.`,
42    stale: 'stale',
43  },
44  'pt-BR': {
45    decimal: ',',
46    today: 'hoje',
47    labels: { five_hour: '5h', seven_day: '7d', spend_limit: 'limite' },
48    agent: 'agente',
49    agents: n => `${n} agentes, maior`,
50    modes: { micro: 'micro', summary: 'resumo' },
51    compacting: m => `compactando (${TEXTS['pt-BR'].modes[m]})…`,
52    focus:
53      'Priorize o que é preciso para continuar o trabalho: objetivo, arquivos alterados (com caminho), ' +
54      'decisões e o porquê, estado atual (testes, o que está quebrado), próximos passos e pendências em aberto.',
55    compactFailed: error => `Não consegui compactar (${error}); a sessão continua como está.`,
56    red: (ctx, window, does) => `Contexto em ${ctx}${window ? ` de ${window}` : ''}: "compact" na faixa (c) ${does}, antes do autocompact.`,
57    dropsReads: pct => `tira as leituras de arquivo, ~${pct}% da conversa (micro)`,
58    summarizes: 'resume a conversa',
59    microBecameSummary: 'O /compact micro virou resumo: o plugin micro-compaction não está ativo.',
60    failed: error => `cc-cost: a contagem falhou (${error}); a sessão segue, a faixa pode atrasar.`,
61    stale: 'desatualizada',
62  },
63  es: {
64    decimal: ',',
65    today: 'hoy',
66    labels: { five_hour: '5h', seven_day: '7d', spend_limit: 'límite' },
67    agent: 'agente',
68    agents: n => `${n} agentes, mayor`,
69    modes: { micro: 'micro', summary: 'resumen' },
70    compacting: m => `compactando (${TEXTS.es.modes[m]})…`,
71    focus:
72      'Prioriza lo necesario para seguir el trabajo: objetivo, archivos modificados (con ruta), ' +
73      'decisiones y el porqué, estado actual (tests, lo que está roto), próximos pasos y pendientes.',
74    compactFailed: error => `No pude compactar (${error}); la sesión sigue como está.`,
75    red: (ctx, window, does) => `Contexto en ${ctx}${window ? ` de ${window}` : ''}: "compact" en la franja (c) ${does}, antes del autocompact.`,
76    dropsReads: pct => `quita las lecturas de archivo, ~${pct}% de la conversación (micro)`,
77    summarizes: 'resume la conversación',
78    microBecameSummary: 'El /compact micro se volvió resumen: el plugin micro-compaction no está activo.',
79    failed: error => `cc-cost: el conteo falló (${error}); la sesión sigue, la franja puede atrasarse.`,
80    stale: 'desactualizada',
81  },
82}
83
84/** `pt_BR.UTF-8` → pt-BR, `es_AR` → es; anything else, English. */
85function languageOfLocale(locale: string | undefined): Language {
86  if (locale === undefined) return 'en'
87  if (/^pt/i.test(locale)) return 'pt-BR'
88  if (/^es/i.test(locale)) return 'es'
89
90  return 'en'
91}
92
93/** The mod's `language` option; on `auto`, the system locale, as the rest of the terminal. */
94async function resolve($: EngineInterface, option: PluginOptions[string] | undefined): Promise<Language> {
95  if (option === 'en' || option === 'pt-BR' || option === 'es') return option
96  try {
97    const locale = (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG'))
98
99    return languageOfLocale(locale)
100  } catch {
101    return 'en'
102  }
103}
104
105/** Resolves the language again and keeps it in the session: session.start calls it on every load, so a new option takes. */
106export async function chooseLanguage($: EngineInterface, option: PluginOptions[string] | undefined): Promise<Texts> {
107  const chosen = await resolve($, option)
108  await updateLanguage($, () => chosen)
109
110  return TEXTS[chosen]
111}
112
113/** The texts of the language already chosen; resolves it first when nothing did yet. */
114export async function textsOf($: EngineInterface, option: PluginOptions[string] | undefined): Promise<Texts> {
115  const chosen = await readLanguage($)
116
117  return chosen === null ? chooseLanguage($, option) : TEXTS[chosen]
118}
119
120/** 950 · 12.4k · 312k · 1.2M — one decimal place only below 10; the separator is the language's. */
121export function short(n: number, decimal: string): string {
122  const [value, suffix] = n >= 1e6 ? [n / 1e6, 'M'] : n >= 1e3 ? [n / 1e3, 'k'] : [n, '']
123  const places = suffix && value < 10 ? 1 : 0
124
125  return value.toFixed(places).replace('.', decimal) + suffix
126}
127
types/index.d.ts 50 lines
1export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number }
2
3/** micro: drops the file reads (micro-compaction plugin); summary: the native /compact. */
4export type Mode = 'micro' | 'summary'
5
6/** Language of the band and its notices. */
7export type Language = 'en' | 'pt-BR' | 'es'
8
9export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
10
11export type Spend = {
12  session: Tokens
13  /** New tokens of the day, summed over every session (the `novos:<day>:*` keys in $.store). */
14  today: number
15  /** Local day (YYYY-MM-DD) `today` was summed for: past it, the band shows 0 until the next count. */
16  day: string
17  /** This session's $.store key for the day and how much it has written there. */
18  own: { key: string; n: number }
19  /** New tokens per main-thread turn, the most recent ones, for the sparkline. */
20  turns: number[]
21  /** Whether a main-thread turn is running: only then does usage go into the last bar. */
22  inTurn: boolean
23  limits: Limit[]
24  /** Tokens of the current context (input of the last response); null before the first one and after /clear. */
25  context: number | null
26  /** Compaction window (autoCompactWindow) the ctx thresholds come from; null until the first reading. */
27  window: number | null
28  /** The model's window (`context.window`) `window` was measured under: when it moves, `window` is measured again. */
29  modelWindow: number | null
30  /** Context of each running subagent (input of its last response), 0 before the first; ctx is the main thread's only. */
31  agents?: Record<string, number>
32}
33
34declare module 'claude-code' {
35  interface PluginState {
36    /**
37     * `compacting`: which compaction the button is running; null outside one. `failing`: hooks whose last run
38     * failed; null when all are fine. `warned`: whether the counting-failure toast already went out this session.
39     * `language`: the language resolved from the option or the locale; null until the first resolution.
40     */
41    'cc-cost': {
42      spend: Spend | null
43      compacting: Mode | null
44      failing: string[] | null
45      warned: boolean
46      language: Language | null
47    }
48  }
49}
50