Two rows above the prompt in three divided columns: context with the model, effort and cache hit rate; the 5-hour window with its pace (used over the window…

Personal collection of Claude Code and Codex skills.
Each top-level folder containing a SKILL.md is one skill. This repo is the single source of truth; skills become active by linking them into each agent's skill directory, where Claude Code and Codex discover them.
| Skill | What it does |
|---|---|
thegraph-codex | Codex-native, explicitly invoked version of thegraph's end-to-end discipline: establish the task from repository guidance and primary sources, make routine implementation decisions autonomously, ask only for consequential product or scope decisions, prove behavioural tests can fail, then run verification proportionate to the changed surface. It does not require Claude Code platform skills or create external tracker records without an explicit request. |
to-html | Convert a markdown file — or content already in the conversation — into a single self-contained, styled HTML file: inline CSS, sticky table of contents, callouts, premium layout blocks. No build step. |
brief | Explain the work in flight to the person who has to decide about it — state, the next action, what it changes and what it leaves alone, and what they must decide (including "nothing", which is information). Publishes a one-screen Artifact with its own briefing layout; falls back to chat when there is no structure worth laying out. Status claims are queried with gh/git rather than copied out of the conversation, and measured facts are marked apart from inferred ones. Vocabulary is governed by a structural check — every noun must point at something the user can see or do — not by a banned-word list, because the words that lose someone next are never the ones already on the list. A view, never a source: nothing may exist only in a briefing. Invoked only (/brief, /brief <issue>, /brief session) — judging whether someone understands you is not yours to do. |
gate | The Acceptance Gate — review an AFK agent's finished work on an issue, render a verdict (Pass / Rework / Respec / Escalate) with the matching next action, and run it on the tracker once you approve. Delegates the diff review to the code-review skill. |
to-deck | Retired — no longer installed; moved to retired/, see ADR-0059 and ADR-0027. Turned a study PDF into a reusable JSON question bank through an interactive Korean Q&A session: keeps the workbook's own questions in order (origin: workbook) and adds generated extras (origin: extra) — a mix of explanatory and single-term recall questions — each a plain {question, answer} pair. Offers a one-at-a-time session or batch extraction; no question-type labels — a downstream tool classifies them. |
grill-code | Retired — no longer installed; moved to retired/, see ADR-0058 and ADR-0027. Grilled code along one chosen mode — security, common-component extraction, refactoring, performance, or learning — scanning the scope relentlessly. Defect modes score each finding on severity + effort and rank them by priority (P0–P3); the non-defect learning mode explains AI-written code as Lessons ranked by Value. Report only; standalone (no dependency on code-review/audit). Can save the report as HTML via to-html. |
img-to-pdf | Combine a folder of images (or an explicit file list) into one PDF, one image per page, in natural-sort order (2.jpg before 10.jpg). Default: a searchable PDF — the page image plus an invisible, selectable/searchable text layer via macOS Vision OCR (Korean + English). --image-only instead embeds JPEG/PNG losslessly with no text layer (HEIC/HEIF/WEBP pre-converted via sips; img2pdf auto-installed into a cached venv). OCR mode is macOS-only; the Swift helper compiles once and caches. |
theflow | Retired — no longer installed; moved to retired/, see ADR-0027. The seven-step working discipline for a substantive change to a boundary-defined codebase, succeeded by thegraph which carries every rule it held (ADR-0019). Kept readable because the docs/agents/theflow.md bindings it read still exist in the repos it onboarded — nothing reads them now, grill-the-graph's path for compiling one having gone with ADR-0067. |
grill-the-flow | Retired — no longer installed; moved to retired/, see ADR-0027. The setup half of theflow — it interrogated a maintainer to author the repo's docs/agents/theflow.md bindings. Succeeded by grill-the-graph, which asks a much smaller question and writes a much smaller file. Nothing reads the bindings docs it wrote, that path having gone with ADR-0067. |
read-it | Read the situation before touching anything, and come back with a route. The first act of a change and the only one whose mistakes nothing downstream catches — a wrong proof method fails at the proof and a wrong placement fails at the diff, while a wrong reading of the issue passes everything, a run that solves the wrong problem well having still solved something well. Four reads, three of them conditional on something you check rather than weigh: the build (short, and answering little on purpose); the cluster, where one tracker query finds a parent (spine — the anchor's root is a hypothesis to test); the territory map where the repo keeps one; and always the real sources plus the hidden state (firsthand, one reflex rather than two — the source list widens what you read, it never decides whether you read, and with no outside source named you still enumerate the hidden state of the code you are touching). Doing one of the four and doing all four are both ordinary; what is not is skipping one and being unable to say why. Then restates the issue in its own words and stops to ask — the only guaranteed stop, since every later one is conditional and a run where nothing goes wrong first reaches a person with the work already done and nowhere to have redirected it. Returns a route label, never a skill name, so what runs next stays the caller's to decide. Everything it finds is a candidate; nothing reaches a tracker unasked. |
make-it | Write the change. Calls tdd for the tests and redden after every one of them — a green from a test nobody watched fail is not evidence, which is the one thing tdd does not do. Keeps the narrow exception where compilation itself enforces completeness and a round-trip test replaces strict RED, and the rhythm a whole-suite-at-the-end habit loses: typecheck and the nearby tests often, everything once at the end. Prose changes walk it too, with the test section conditional. Carries the rule that a comment says what the code is, and follows the repo's CLAUDE.md for where the rest goes rather than holding its own copy — comments are written on every edit, and most edits never pass through make-it. Its substance is the four signals that only appear while your hands are in the code, since you cannot schedule the moment you will feel one: "this is a bit odd, I'll just fix it up here" — the tell that the problem is one step further in, tempting because it works and costs nothing visible, until the day somebody fixes the real thing and every patch like it becomes silently wrong; a new file with no obvious home; writing against an outside reference; and a call that is the maintainer's. What you notice and do not fix is carried, never filed. |
check-it | Measure a finished change before anyone calls it done — the hand that shaped a thing is the worst judge of whether it is finished. Eight checks, ordered by cost rather than ceremony, each conditional: the gates bare (bare), whether new or moved files landed where the layout rule said, proof against something real rather than a fake, the diff read for shape (assay), for cost (silt) and for exposure (security-review) at the same time, the whole corpus read for what is missing (lens), and the surfaces that describe the behaviour (sweep). A prose change runs the last two and nothing else. One question runs through all of it — a red, a defect, a defensive line: is it mine? Answered by re-running against the tree without this change and comparing the failure, never the exit code, since a baseline red for its own reason makes every red compare 1 to 1 and inverts the attribution silently. And one shape is hunted assuming the writer left no help at all, because whoever did not notice could not have written it down: for each defensive line, what would have to be true for this to be unnecessary? — if the answer names something you did not change, that is where it belongs. Fixes nothing; measures, attributes, hands on. |
pub-ready | Bring a Dart or Flutter package to the point where only pub publish is left — the maintainer's release bar, held once instead of in each package's CLAUDE.md, where it had been copied into at least seven packages and drifted (ADR-0086). Reads what pub.dev already has first, raw from its API, since that settles whether the version is new, which CHANGELOG entries are frozen and what changed since the last release. Then pubspec (version size against the diff, the 0.x caret trap, the SDK floor, fields checked by pana itself rather than a copied limit), CHANGELOG (an entry per behaviour change, a published one never rewritten), README (every API name it shows grepped in lib/), the CI steps plus the gates CI does not reach — pub get before dart format, the example, the dry-run at 0 warnings on a clean tree with its file list read — all run bare. Never publishes: it ends with the command written out for the maintainer. A package's own guidance adds to it and, where they differ, wins. Runs only when a release is being prepared, in a repo that chose it: grill-the-graph asks, recommending it for an open-source package, and records pub-ready or None. in the build, which this reads first. |
decant | Sort source comments paragraph by paragraph under one policy: a comment says what the code is, and the why, the trap, the measured value and the history move to the repo's map. Six bins; the unit is the paragraph; the drop question is asked last, because a wrong move costs a lookup and a wrong drop costs a measurement. Checks every DESIGN against the code and then its note, and reports what the map is missing (notes owed) and where note and comment give different reasons (two grounds). Runs on a whole repository, territory by territory in an order derived by counting, when a maintainer asks — never per change, because a check after the fact is undone by the next edit made outside it; the write-time rule lives in the repo's CLAUDE.md. Reports and stops — unless the maintainer hands it the writes, and then it moves sentences rather than rewriting them, accounts for every one, and re-points whatever quoted them. The measurements behind it are ADR-0076. In a repository you contribute to, upstream's guidance and closest merged PR replace that policy, and only the comments the branch adds or changes are read (ADR-0079). |
winnow | Cut an always-loaded agent document — CLAUDE.md, AGENTS.md, a skill body — down to what every run needs. Five bins per paragraph: rule stays, detail moves behind a pointer that names its trigger, number stays only where a decision turns on it, roster becomes the command that derives it, history leaves for version control. History is asked last, and an incident story has its rule extracted before the story goes. Shows the table — every history part quoted, not counted — and stops for the maintainer; on approval writes, then proves every rule still has a home by reading the original from version control, and repoints references to moved sections. The case it was cut from is ADR-0077. |
assay | Test what a change is made of, along two axes kept apart because a change can pass one and fail the other: does the code hold up, and does it do what was asked. The first carries this repo's own documented standards — which always outrank it — plus Fowler's twelve code smells as labelled heuristics, never hard violations, covering cohesion (Divergent Change), coupling (Feature Envy, Shotgun Surgery, Message Chains) and duplication (Duplicated Code, Data Clumps, Primitive Obsession); and it opens the module the change landed in, since "edited for several unrelated reasons" is a claim about a module and a diff shows one slice of it. The second asks what the issue wanted and got, what it wanted and did not, and what arrived that nobody asked for. Findings are graded violation / judgement / already-decided — the third is why the records get read, since a finding that contradicts a recorded decision re-opens a call somebody made. Never merged, never ranked across axes, one closing line per axis. |
silt | Read a change for what will make it slow, and refuse to call anything a defect without a number. Silt is what a river drops: nothing dramatic, nothing wrong on any given day, and one season later the channel is shallow — which is the shape of the performance defects that actually cost, since the ones that announce themselves get found. Carries seven shapes with, for each, the cheapest way to find out whether it is real here: registered and never released, a container that only grows, I/O inside a loop, a large structure copied by value, recomputed every time, blocking the thread that must not block, a lookup with nothing to make it fast. A suspicion arrives with the way to settle it or it does not go out at all — that bar is what stops this becoming a list of things that make somebody uneasy. And a number with nothing beside it is not a number: measure the same thing on the tree without the change. Proposes no optimisation, does not widen, and does not accept "it's fine, it's small" — if it is small the measurement is cheap. |
ask-it | Put everything that has been carried in front of a person, once, and file only what they keep — the one door, since nothing may evaporate into a pull-request body or a code comment, where it is buried on merge. envelope owns the collecting and the seven columns; what this adds is that the items arrive from different places with dispositions that share no vocabulary — something to file, something to decide, something belonging to another repository, something a release will oblige — and interleaved, the reader classifies before answering, which is the sorting that presenting one at a time was bought to remove. byartifact searches before anything is opened, and only for items actually being filed. A follow-up is parented through the tracker's own relation in the same act as filing it, and whether it also joins the cluster is a separate judgement: provenance and root are different claims, and the error is not symmetric — missing a sibling costs a reconstruction, counting an adjacent one corrupts the roster that somebody later copies almost verbatim. A release's obligations are the consumer tests that actually broke, named; a purely additive release obliges nothing, and that is an answer worth writing. |
thegraph | Take one change from an issue to done, in a codebase whose identity is a boundary — a core that stays correct by not absorbing the concerns of the things that consume it. Four skills in order — read-it → make-it → check-it → ask-it — with one guaranteed stop before any of them run: the reading of the issue, confirmed by the person who holds it, since a change where no signal fires otherwise reaches a person for the first time at the very end, with the work done and nowhere to have redirected it. Two routes after that, and the one that gets missed is expensive: an issue asking for a choice gets the adversarial read over the options before any proposal, or the enumeration lands after approval and its costs get demoted into follow-ups. Everything else is a signal you cannot schedule — the urge to patch around something one step further in, a test just written, an outside reference about to be relied on, a call that is the maintainer's — acted on where it arrives rather than noted for later. What holds throughout: nothing reaches a tracker unasked; what can be counted is counted; a derivation falls to a better derivation and a judgement falls only to the person who made it, so a record that does not say which it holds reads as the first. Human-invoked (/thegraph). |
grill-the-graph | The setup half of thegraph. Writes one short prose file, docs/agents/thegraph.md, holding what a person already knows and no file in the repo answers — which is very nearly just the real sources the project is built against, each marked how it works or where files go, raw or summarized, an example to follow or a spec that binds. A line earns its place only by clearing three conditions together: no file here answers it, a person already knows it, and something reads it. The second is the one that used to be missing — "only a person could decide it" and "a person already knows it" are different sets, and everything this skill once asked for (sacred paths, the tie-breaker, the seams, a proof method per layer) cleared the first and failed the second, so the answers came back drafted by the builder and ratified by someone who could not have produced them. Generates no scripts and no agents, carries no build stamp, and copies nothing the repo already states; the build grows as runs ask for what it lacks. Run again, it updates: where docs/agents/thegraph.md exists it keeps the build, asks nothing already answered, and brings what it installed — the comment rule, the map hub, the attribution pieces — and the lines pointing at them up to its current text; /grill-the-graph init rebuilds from scratch instead, written only on the maintainer's approval (ADR-0085). An older generated build — scripts/thegraph/, .claude/agents/thegraph-* — is handed to salvage rather than read or updated. A project built against nothing outside itself yet answers none yet, and the file records that the question was put rather than inventing a row. Where the repo has no territory map, it makes the map's folder with a one-line hub instead of building one — the rule needs a destination on disk, and an empty map is a young repo's honest state; notes arrive as edits need them or all at once through grill-map. Then it writes the comment rule into the repo's CLAUDE.md: a comment says what the code is, with the rest sent to the map, the decision records or the commit message, naming only destinations that exist on disk. That is the one place the rule is written, because comments are written on every edit and a pass that checks them afterwards is undone by the next one. In a repository you contribute to rather than own — named by the argument (/grill-the-graph local, or own for your own), and asked first when there is none, with viewerPermission on the receiving repository as the recommendation — it commits nothing: the same file and a rule deferring to upstream's own guidance go in untracked, excluded files, no map is made, and a hook blocks Claude attribution on the way out (ADR-0079). In your own repository attribution stays unless you turn it off when asked, and off installs the same check, locally. In your own repository holding a Dart package for pub.dev, it asks whether pub-ready is the release bar — recommending it when the package is open source — records the answer, and on a yes offers to replace each older copy of the bar with a pointer, keeping what only that package has (ADR-0086). |
salvage | Clear an older grill-the-graph build out of a repo without losing the answers a person gave it. The whole job is telling two things apart: what somebody sat down and answered, which has to survive, and what was copied out of the repository, which is why that build went. Finds what is ours by the build stamp every generated file carries and by the build document's own manifest, and reads both — a stamped file the manifest does not name is the case that matters, the manifest being a copy like any other. Four rings: ours (build doc, generated agents and scripts, the ignore line, and the run-state cache version control never shows you); somebody else's file pointing at ours, where only the line comes out — a repo left with a hook invoking a deleted script cannot commit, so clearing the first ring and reporting the second is a break with a note attached; produced by our rules but not written by us, shown and asked, and any generated file a later commit touched, because that made it theirs; and outside, untouched — decision records describe the world when they were written, broken links included. Lifts the reference list into the short file the current skill defines, drops the rest with a reason each, and re-reads the tree afterwards, since a cleanup reporting success without looking again has checked nothing. |
tickets | Retired — no longer installed; moved to retired/, see ADR-0069 and ADR-0027. Put back what slicing dropped — the third producer in the thegraph family. A general slicer keeps a ticket thin because it cannot know who will execute it; here the executor was known, so the calls a maintainer had already made travelled with the ticket instead of staying behind in the spec. Ran right after the tickets were cut, in the same unbroken window as the grilling: transcribed the settled calls into each ticket, enrolled the parent as the relation the tracker actually renders (which is still why spine's roster is a query and not a body parse), and marked each entry human / derived / unknown. It read thegraph's "What the issue must supply" at runtime rather than hardcoding it, and that is the one thing it demonstrably bought: the schema went from five slots to six and the producer needed zero edits. Retired on the maintainer's call, with the falsification ADR-0045 had written in advance already fired — on the only run anyone measured, every contract entry was marked derived, which licenses nothing. The schema it filled is live; thegraph reads a contract wherever one is written, and a ticket that answers none of it was always the ordinary case. |
| spine | Read the cluster before the ticket, extracted from
hooks/register.tsx 363 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionMeasureInput, SessionUsage } from 'claude-code'
3
4import type { Credential, Live } from '../types'
5import {
6 CACHE_READINGS,
7 FIGURE_COLOR,
8 carryResets,
9 WINDOW_MS,
10 cacheHit,
11 cacheLevel,
12 clockOf,
13 TODAY_LOUD_USD,
14 contextUsed,
15 effortFromSettings,
16 evenPace,
17 fiveHourRate,
18 gaugeCells,
19 gaugeWidth,
20 isLoud,
21 isTodayUnpriced,
22 levelOf,
23 paceLevel,
24 paceOf,
25 dailyShare,
26 modelLabel,
27 parseBurn,
28 parseToday,
29 recordFive,
30 runsOutAt,
31 shareLevel,
32 sinceArg,
33 usd,
34} from './format'
35
36const live = atom({ plugin: 'usage-band', key: 'live' } as const, null)
37const effort = atom({ plugin: 'usage-band', key: 'effort' } as const, null)
38const ledger = atom({ plugin: 'usage-band', key: 'ledger' } as const, null)
39const fiveSamples = atom({ plugin: 'usage-band', key: 'fiveSamples' } as const, [])
40const cacheReadings = atom({ plugin: 'usage-band', key: 'cacheReadings' } as const, [])
41const credential = atom({ plugin: 'usage-band', key: 'credential' } as const, null)
42
43/** Blank cells at the band's left, so its text lines up with the turn line's after `✻ `; and at its right. */
44const LEFT = 2
45const RIGHT = 1
46
47/** Cells for a gauge's label (`ctx `, `5h `), and the divider between two columns. */
48const GAUGE_LABEL = 4
49const DIVIDER = ' │ '
50
51/** How often ccusage is asked between turns; each answer also redraws, so %/h decays while idle. */
52const LEDGER_MS = 120_000
53/** A turn's measurement asks again only once this long has passed since the last ask. */
54const LEDGER_GAP_MS = 30_000
55
56// No shell runs the argv: on Windows `ccusage` is a .cmd shim that only cmd.exe starts.
57const LAUNCHERS: readonly (readonly string[])[] = [['ccusage'], ['cmd', '/c', 'ccusage']]
58
59type Figures = Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'> | SessionMeasureInput
60
61const toLive = (model: string, u: Figures): Live => ({
62 model,
63 context: {
64 tokens: u.context.tokens ?? null,
65 window: u.context.window,
66 percent: u.context.percent ?? null,
67 },
68 rateLimits: u.rateLimits.map(r => ({
69 kind: r.kind,
70 percentUsed: r.percentUsed,
71 resetsAt: r.resetsAt ?? null,
72 })),
73 usd: u.cost?.usd ?? null,
74})
75
76const fiveOf = (l: Live | null) => l?.rateLimits.find(r => r.kind === 'five_hour')
77
78// Takes a reading: a limit the engine dropped once its reset passed goes on at 0%, and the
79// 5-hour window's goes in its history for the forecast.
80const refreshLive = async ($: EngineInterface, figures?: Figures) => {
81 const model = await $.session.model()
82 const u = figures ?? (await $.session.usage())
83 const now = await $.clock.now()
84 const before = await read($, live)
85 const reading = toLive(model, u)
86 const next = { ...reading, rateLimits: carryResets(before?.rateLimits ?? [], reading.rateLimits, now) }
87 const previous = fiveOf(before)
88 const five = fiveOf(next)
89 if (five) {
90 await update($, fiveSamples, samples =>
91 recordFive(samples, five.percentUsed, five.resetsAt, previous?.resetsAt ?? five.resetsAt, now),
92 )
93 }
94 await update($, live, () => next)
95}
96
97// Which credential the session holds, so a login's limits not yet reported show as waiting.
98const readCredential = async ($: EngineInterface) => {
99 let kind: Credential = null
100 try {
101 kind = (await $.session.authorize())?.kind ?? null
102 } catch {
103 // None to name: no limits are expected.
104 }
105 await update($, credential, () => kind)
106}
107
108// Module state: a reload starts these over, which costs one extra ccusage run.
109let launcher: readonly string[] | null = null
110let lastAsk = -Infinity
111let isAsking = false
112
113const ccusage = async ($: EngineInterface, args: readonly string[]): Promise<string | null> => {
114 for (const l of launcher ? [launcher] : LAUNCHERS) {
115 try {
116 const r = await $.process.run([...l, ...args], { timeoutMs: 20_000 })
117 if (r.exitCode === 0) {
118 launcher = l
119 return r.stdout
120 }
121 } catch {
122 // This launcher cannot start here; try the next.
123 }
124 }
125 return null
126}
127
128const parsed = <T,>(stdout: string | null, parse: (s: string) => T): T | null => {
129 if (stdout === null) return null
130 try {
131 return parse(stdout)
132 } catch {
133 return null
134 }
135}
136
137const askLedger = async ($: EngineInterface, isForced = false) => {
138 const now = await $.clock.now()
139 if (isAsking || (!isForced && now - lastAsk < LEDGER_GAP_MS)) return
140 isAsking = true
141 lastAsk = now
142 try {
143 const [blocks, daily] = await Promise.all([
144 ccusage($, ['blocks', '--active', '--json', '--offline']),
145 ccusage($, ['daily', '--json', '--offline', '--since', sinceArg(now)]),
146 ])
147 await update($, ledger, () => ({ burnPerHour: parsed(blocks, parseBurn), today: parsed(daily, parseToday) }))
148 } finally {
149 isAsking = false
150 }
151}
152
153// Until the first request says what effort it was sent with, show what settings name.
154const seedEffort = async ($: EngineInterface) => {
155 if ((await read($, effort)) !== null) return
156 const l = await read($, live)
157 if (l === null) return
158 const fromSettings = effortFromSettings(await $.settings.read(), l.model)
159 if (fromSettings !== null) await update($, effort, () => fromSettings)
160}
161
162// Everything the band shows, read again: at start, and after /clear, /resume or /branch
163// reset $.state, which session.start does not follow.
164const fill = async ($: EngineInterface, isForced: boolean) => {
165 await readCredential($)
166 await refreshLive($)
167 await seedEffort($)
168 await askLedger($, isForced)
169}
170
171export const register: Register = on => {
172 on('session.start', async ($, e, next) => {
173 const result = await next(e)
174 await readCredential($)
175 await refreshLive($)
176 await seedEffort($)
177 // Off the start's path: ccusage takes about a second and the first prompt need not wait.
178 $.clock.after(0, () => void askLedger($))
179 // The reading too, so a limit whose reset passes while idle draws as started over.
180 $.clock.every(LEDGER_MS, () => void refreshLive($).then(() => askLedger($)))
181 return result
182 })
183
184 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
185 const result = await next(e)
186 await fill($, true)
187 return result
188 }).catch(($, e, next) => next(e))
189
190 on('session.measure', async ($, e, next) => {
191 const result = await next(e)
192 await refreshLive($, e)
193 await askLedger($)
194 return result
195 })
196
197 // A compaction empties the window, which no measurement reports until the next response.
198 // A precompute leaves the conversation as it is, and a subagent's compacts only its own.
199 on('session.compact', async ($, e, next) => {
200 const result = await next(e)
201 if (result.skip === undefined && e.trigger !== 'precompute' && e.agentId === undefined) {
202 await refreshLive($)
203 }
204 return result
205 })
206
207 on('classic.PostModelSwitch', async ($, e, next) => {
208 await update($, live, prev => (prev === null ? null : { ...prev, model: e.to_model }))
209 return next(e)
210 }).catch(($, e, next) => next(e))
211
212 // The effort a main-thread request is actually sent with, after any downgrade for the model,
213 // and what the cache served of its prompt.
214 on('turn.step', async function* ($, e, next) {
215 if (e.agentId === undefined) {
216 const sent = e.effort === undefined ? null : String(e.effort)
217 if ((await read($, effort)) !== sent) {
218 await update($, effort, () => sent)
219 }
220 }
221 const result = yield* next(e)
222 const usage = result.usage
223 if (e.agentId === undefined && usage !== null) {
224 const reading = { read: usage.cache_read_input_tokens, written: usage.cache_creation_input_tokens, uncached: usage.input_tokens }
225 await update($, cacheReadings, list => [...list, reading].slice(-CACHE_READINGS))
226 }
227 return result
228 })
229
230 // Three columns, divided, each a head over its gauge: context (the model, its effort, the cache),
231 // the 5-hour window (its pace or when it runs out, and its reset), and the week with the money.
232 // Quiet until something needs saying: colour is kept for a limit past 80%, a pace that runs
233 // out, a cold cache, a heavy day, and a week with less than a day's share to spare — or, the
234 // one colour for good news, a day's share or more.
235 // Whatever other bands draw goes above, so these rows stay next to the prompt whichever hook runs first.
236 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
237 const below = await next(e)
238 const l = await read($, live)
239 if (e.props.hasSurvey || l === null) {
240 return below
241 }
242
243 const eff = await read($, effort)
244 const led = await read($, ledger)
245 const samples = await read($, fiveSamples)
246 const now = await $.clock.now()
247 const { Box, Text } = $.ui.resolve(e)
248
249 // A piece of a row: its text and how it is drawn.
250 type Seg = { text: string; color?: string; bold?: boolean; dim?: boolean }
251 const draw = (segs: Seg[]) => segs.map(g => <Text color={g.color} bold={g.bold} dimColor={g.dim}>{g.text}</Text>)
252 // A column's head, cut or padded to the gauge's width so the dividers line up.
253 const fit = (segs: Seg[], n: number): Seg[] => {
254 const out: Seg[] = []
255 let used = 0
256 for (const g of segs) {
257 const take = [...g.text].slice(0, Math.max(0, n - used)).join('')
258 if (take !== '') out.push({ ...g, text: take })
259 used += [...take].length
260 }
261 return used < n ? [...out, { text: ' '.repeat(n - used) }] : out
262 }
263 const dot: Seg = { text: ' · ', dim: true }
264
265 // The heads.
266 const hit = cacheHit(await read($, cacheReadings))
267 const contextHead: Seg[] = [
268 { text: modelLabel(l.model), color: FIGURE_COLOR.model, bold: true },
269 ...(eff !== null ? [{ text: ` ${eff}`, dim: true }] : []),
270 ...(hit !== null ? [dot, { text: 'cache ', dim: true }, { text: `${hit}%`, color: hit >= 80 ? undefined : cacheLevel(hit) }] : []),
271 ]
272 const five = fiveOf(l)
273 const rate = five ? fiveHourRate(samples, five.percentUsed, five.resetsAt, now) : null
274 const outAt = five && rate !== null ? runsOutAt(rate, five.percentUsed, five.resetsAt, now) : null
275 // Pieces of a head, a dot between those that say something.
276 const join = (...parts: Seg[][]): Seg[] => parts.filter(p => p.length > 0).flatMap((p, i) => (i === 0 ? p : [dot, ...p]))
277 // A limit's pace leads its head: the share used over the share of its window gone, quiet up to 80%.
278 const pace = (used: number, resetsAt: string | null, windowMs: number): Seg[] => {
279 const p = paceOf(used, resetsAt, windowMs, now)
280 if (p === null) return []
281 const lv = paceLevel(p)
282 return [{ text: `${p}% pace`, bold: true, ...(lv === 'success' ? {} : { color: lv }) }]
283 }
284 const fiveHead: Seg[] | null =
285 five === undefined ? null
286 : join(
287 pace(five.percentUsed, five.resetsAt, WINDOW_MS.fiveHour),
288 outAt !== null ? [{ text: `out at ${clockOf(outAt)}`, color: 'error', bold: true }] : [],
289 five.resetsAt != null ? [{ text: `resets ${clockOf(Date.parse(five.resetsAt))}`, dim: true }] : [],
290 )
291 // The week: what it has left over the days left, today counted whole.
292 const seven = l.rateLimits.find(r => r.kind === 'seven_day')
293 // A week just started over has its seven days ahead, whenever the next reset falls.
294 const share = !seven || seven.percentUsed >= 100 ? null
295 : seven.isReset ? dailyShare(0, new Date(now + WINDOW_MS.week).toISOString(), now)
296 : dailyShare(seven.percentUsed, seven.resetsAt, now)
297 const shareLv = share === null ? null : shareLevel(share.basis)
298 const weekLead: Seg[] = share === null ? [] : [{ text: `${share.perDay.toFixed(1)}%/day`, bold: true, ...(shareLv === null ? {} : { color: shareLv }) }]
299 const moneyHead: Seg[] = [
300 ...(led?.today == null ? []
301 : isTodayUnpriced(led, l) ? [{ text: 'today $0 · model not priced in ccusage', color: 'warning' }]
302 : [{ text: 'today ', dim: true }, { text: usd(led.today), ...(led.today >= TODAY_LOUD_USD ? { color: 'warning', bold: true } : {}) }]),
303 ...(led?.burnPerHour != null ? [...(led.today == null ? [] : [dot]), { text: `${usd(led.burnPerHour)}/h`, dim: five !== undefined }] : []),
304 ]
305
306 // A login's limit with no reading yet (a new session, before its first response) keeps its
307 // column, empty and waiting; an API key has none, and its columns go.
308 const isLogin = (await read($, credential)) === 'bearer'
309 const waiting = (label: string) => ({ label, used: null, mark: null, head: [{ text: 'no reading yet', dim: true }] })
310 // The gauges: the 5-hour one marked where an even pace would have it; the week's has no mark.
311 const gauges: { label: string; used: number | null; mark: number | null; head: Seg[] }[] = [
312 { label: 'ctx', used: contextUsed(l.context), mark: null, head: contextHead },
313 ...(five ? [{ label: '5h', used: five.percentUsed, mark: evenPace(five.resetsAt, WINDOW_MS.fiveHour, now), head: fiveHead ?? [] }]
314 : isLogin ? [waiting('5h')] : []),
315 ...(seven ? [{ label: 'wk', used: seven.percentUsed, mark: null, head: weekLead }]
316 : isLogin ? [waiting('wk')] : []),
317 ]
318 // The money goes after the last head: the week's share, or whatever column comes last.
319 const last = gauges[gauges.length - 1]
320 if (last) last.head = join(last.head, moneyHead)
321
322 const each = gaugeWidth(e.props.bodyColumns - LEFT - RIGHT, gauges.length, DIVIDER.length)
323 const divider = <Text dimColor>{DIVIDER}</Text>
324 const top = (
325 <Text wrap="truncate-end">
326 {gauges.map((g, i) => (
327 <Text>
328 {i > 0 && divider}
329 {draw(fit(g.head, each))}
330 </Text>
331 ))}
332 </Text>
333 )
334 const bottom = (
335 <Text wrap="truncate-end">
336 {gauges.map((g, i) => {
337 const figure = ` ${(g.used === null ? '–' : String(g.used)).padStart(3)}%`
338 const cells = gaugeCells(Math.max(4, each - GAUGE_LABEL - figure.length), g.used ?? 0, g.mark)
339 const loud = g.used !== null && isLoud(g.used) ? levelOf(g.used) : undefined
340 return (
341 <Text>
342 {i > 0 && divider}
343 <Text dimColor>{g.label.padEnd(GAUGE_LABEL)}</Text>
344 {cells.map(c => (c === 'mark' ? <Text bold>┊</Text> : c === 'fill' ? <Text color={loud}>━</Text> : <Text dimColor>─</Text>))}
345 <Text bold color={loud}>{figure}</Text>
346 </Text>
347 )
348 })}
349 </Text>
350 )
351
352 return (
353 <Box flexDirection="column">
354 {below}
355 <Box flexDirection="column" paddingLeft={LEFT} paddingRight={RIGHT}>
356 {top}
357 {bottom}
358 </Box>
359 </Box>
360 )
361 })
362}
363hooks/format.ts 255 lines1import type { FiveSample, Ledger, Live, RateWindow } from '../types'
2
3export type Level = 'success' | 'warning' | 'error'
4
5/** 80% warns, 90% is critical; below that a figure stays quiet. */
6export const levelOf = (used: number): Level =>
7 used >= 90 ? 'error' : used >= 80 ? 'warning' : 'success'
8
9export const isLoud = (used: number): boolean => used >= 80
10
11/** Percent of the context window used; 0 before the first response reports a fill. */
12export const contextUsed = (context: Live['context']): number => {
13 if (context.percent !== null) return context.percent
14 if (context.tokens === null || context.window === 0) return 0
15 return Math.round((context.tokens / context.window) * 100)
16}
17
18// `claude-haiku-4-5-20251001` → haiku 4.5; a trailing date or `[1m]` is not a minor version.
19const MODEL_ID = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?!\d)/
20
21export const modelLabel = (id: string): string => {
22 const m = MODEL_ID.exec(id)
23 if (!m || !m[1] || !m[2]) return id.toLowerCase()
24 return `${m[1]} ${m[2]}${m[3] ? `.${m[3]}` : ''}`
25}
26
27/** The one colour the band keeps while quiet: the model's, from the Claude Code theme. */
28export const FIGURE_COLOR = { model: 'claude' } as const
29
30export const usd = (n: number): string => `$${n.toFixed(2)}`
31
32/**
33 * The effort settings name for a model, before any request has said what it was sent
34 * with: `modelSettings[<model>].effortLevel`, else `effortLevel`. The model id's
35 * trailing `[1m]` and the like are not part of the settings key.
36 */
37export const effortFromSettings = (settings: Readonly<Record<string, unknown>>, model: string): string | null => {
38 const id = model.replace(/\[.*\]$/, '')
39 const perModel = (settings.modelSettings as Record<string, { effortLevel?: unknown }> | undefined)?.[id]?.effortLevel
40 const level = perModel ?? settings.effortLevel
41 return typeof level === 'string' ? level : null
42}
43
44/** The figure today's cost is loud past. */
45export const TODAY_LOUD_USD = 100
46
47/** ccusage prices from a bundled table; a model missing from it costs $0, silently. */
48export const isTodayUnpriced = (ledger: Ledger, live: Live): boolean =>
49 ledger.today === 0 && (live.usd ?? 0) > 0
50
51/** `ccusage blocks --active --json`: the active block's cost per hour. */
52export const parseBurn = (stdout: string): number | null => {
53 const blocks = (JSON.parse(stdout) as { blocks?: { isActive?: boolean; burnRate?: { costPerHour?: number } | null }[] }).blocks
54 const active = blocks?.find(b => b.isActive)
55 return active?.burnRate?.costPerHour ?? null
56}
57
58/**
59 * `ccusage daily --json`: the latest day's total. The query starts a day back
60 * (`sinceArg`) so no time zone's today is cut off; until today's first response
61 * anywhere on this machine the latest day is still yesterday, a window this
62 * accepts rather than guessing the local date in an environment with no zone.
63 */
64export const parseToday = (stdout: string): number | null => {
65 const daily = (JSON.parse(stdout) as { daily?: { totalCost?: number }[] }).daily ?? []
66 const last = daily.at(-1)
67 return last ? (last.totalCost ?? 0) : null
68}
69
70/** `--since` for the daily query: yesterday in UTC, which no time zone's today precedes. */
71export const sinceArg = (now: number): string =>
72 new Date(now - 86_400_000).toISOString().slice(0, 10).replaceAll('-', '')
73
74// --- the 5-hour window's pace ---------------------------------------------------
75
76const HOUR = 3_600_000
77const WINDOW = 5 * HOUR
78/** The trailing stretch %/h is measured over. */
79const TRAIL = HOUR
80/** Below this much history, the window's own average stands in for the trailing rate. */
81const MIN_SPAN = 15 * 60_000
82
83/**
84 * The window's history with one more reading: a new window (a later reset time, or
85 * a fall in use) starts it over; an unchanged reading adds nothing.
86 */
87export const recordFive = (
88 samples: readonly FiveSample[],
89 percentUsed: number,
90 resetsAt: string | null,
91 previousResetsAt: string | null,
92 now: number,
93): FiveSample[] => {
94 const last = samples.at(-1)
95 const isNewWindow = resetsAt !== previousResetsAt || (last !== undefined && percentUsed < last.percentUsed)
96 if (isNewWindow || last === undefined) return [{ at: now, percentUsed }]
97 if (last.percentUsed === percentUsed) return [...samples]
98 return [...samples.filter(x => now - x.at <= TRAIL + MIN_SPAN), { at: now, percentUsed }]
99}
100
101/**
102 * How fast the 5-hour window is being used, in percent per hour: the rise over the
103 * last hour, measured to now so an idle stretch brings it down. With under 15
104 * minutes of history it is the window's average so far, which needs no history.
105 * Null when neither can be told (no reset time, or the window only just began).
106 */
107export const fiveHourRate = (
108 samples: readonly FiveSample[],
109 percentUsed: number,
110 resetsAt: string | null,
111 now: number,
112): number | null => {
113 const base = samples.find(x => now - x.at <= TRAIL)
114 if (base !== undefined && now - base.at >= MIN_SPAN) {
115 return Math.max(0, ((percentUsed - base.percentUsed) / (now - base.at)) * HOUR)
116 }
117 if (resetsAt === null) return null
118 const elapsed = now - (Date.parse(resetsAt) - WINDOW)
119 if (Number.isNaN(elapsed) || elapsed < 10 * 60_000) return null
120 return (percentUsed / elapsed) * HOUR
121}
122
123/** How long each limit's window runs before it resets. */
124export const WINDOW_MS = { fiveHour: WINDOW, week: 7 * 24 * HOUR } as const
125
126/**
127 * A reading with the limits it no longer reports carried on: the engine drops a limit once its
128 * reset time passes with no response since, so one seen before with its reset now past (or
129 * carried already) has started over, at 0%. One gone before its reset is dropped.
130 */
131export const carryResets = (previous: readonly RateWindow[], next: readonly RateWindow[], now: number): RateWindow[] => [
132 ...next,
133 ...previous
134 .filter(p => !next.some(n => n.kind === p.kind))
135 .filter(p => p.isReset === true || (p.resetsAt !== null && Date.parse(p.resetsAt) <= now))
136 .map(p => ({ kind: p.kind, percentUsed: 0, resetsAt: null, isReset: true as const })),
137]
138
139/**
140 * Where a limit's bar would end at an even pace: the share of its window already
141 * gone, in percent. Null when the reset time is unknown or past.
142 */
143export const evenPace = (resetsAt: string | null, windowMs: number, now: number): number | null => {
144 if (resetsAt === null) return null
145 const left = Date.parse(resetsAt) - now
146 if (!(left > 0)) return null
147 return Math.min(100, Math.max(0, ((windowMs - left) / windowMs) * 100))
148}
149
150/**
151 * A limit's pace: the share used over the share of its window gone, in percent. 100 runs
152 * out exactly at the reset, above it sooner. Null at the window's very start (nothing gone
153 * to divide by) and when the reset time is unknown or past.
154 */
155export const paceOf = (percentUsed: number, resetsAt: string | null, windowMs: number, now: number): number | null => {
156 const gone = evenPace(resetsAt, windowMs, now)
157 if (gone === null || gone === 0) return null
158 return Math.round((percentUsed / gone) * 100)
159}
160
161/** A pace's colour: past 80% warns, past 100% (out before the reset) is red, below that it stays quiet. */
162export const paceLevel = (pace: number): Level => (pace > 100 ? 'error' : pace > 80 ? 'warning' : 'success')
163
164// --- the week's daily share --------------------------------------------------------
165
166const DAY = 24 * HOUR
167const WEEK_DAYS = 7
168
169/** An even day's share of the week, in percent: what each day would get were nothing used yet. */
170export const DAY_SHARE = 100 / WEEK_DAYS
171
172/** What the week has left for each of its days. */
173export type DailyShare = {
174 /** Days to the reset, today counted whole: a day runs 24 hours from the reset's time of day. */
175 daysLeft: number
176 /** What is left over the days left, in percent of the week a day. */
177 perDay: number
178 /**
179 * What the colour is judged on: the same split with today's use already taken out of the
180 * days after, so a day that has used its share stays at it; on the last day, what is left.
181 */
182 basis: number
183}
184
185/**
186 * What is left of the week over the days left in it, today counted whole. Only the account's
187 * use, the reset time and now go in, so every machine shows the same and nothing is kept.
188 * Null when the reset time is unknown or past.
189 */
190export const dailyShare = (percentUsed: number, resetsAt: string | null, now: number): DailyShare | null => {
191 if (resetsAt === null) return null
192 const left = Date.parse(resetsAt) - now
193 if (!(left > 0)) return null
194 const daysLeft = Math.min(WEEK_DAYS, Math.ceil(left / DAY))
195 const rest = Math.max(0, 100 - percentUsed)
196 return { daysLeft, perDay: rest / daysLeft, basis: daysLeft > 1 ? rest / (daysLeft - 1) : rest }
197}
198
199/**
200 * A day's share or more to spare is green: the one colour that says there is plenty. Down to
201 * 80% of it the figure stays quiet, down to half it warns, below that it is red.
202 */
203export const shareLevel = (basis: number): Level | null =>
204 basis >= DAY_SHARE - 1e-9 ? 'success' : basis >= DAY_SHARE * 0.8 ? null : basis >= DAY_SHARE * 0.5 ? 'warning' : 'error'
205
206// --- the forecast and the cache -----------------------------------------------------
207
208/**
209 * When the 5-hour limit runs out at this pace, if that comes before the window
210 * resets; null when it holds until the reset, or the pace or the reset is unknown.
211 */
212export const runsOutAt = (rate: number, percentUsed: number, resetsAt: string | null, now: number): number | null => {
213 if (resetsAt === null || !(rate > 0)) return null
214 const reset = Date.parse(resetsAt)
215 if (!(reset > now)) return null
216 const at = now + ((100 - percentUsed) / rate) * HOUR
217 return at < reset ? at : null
218}
219
220/** `16:27`, the engine's local time of day. */
221export const clockOf = (at: number): string => {
222 const d = new Date(at)
223 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
224}
225
226/** The cache hit rate is taken over this many of the latest requests. */
227export const CACHE_READINGS = 10
228
229/** Percent of the prompt tokens the cache served over these requests; null before any request. */
230export const cacheHit = (readings: readonly { read: number; written: number; uncached: number }[]): number | null => {
231 const total = readings.reduce((n, r) => n + r.read + r.written + r.uncached, 0)
232 if (total === 0) return null
233 return Math.round((readings.reduce((n, r) => n + r.read, 0) / total) * 100)
234}
235
236/** A hit rate's colour: most of the prompt served from the cache is the healthy case. */
237export const cacheLevel = (percent: number): Level => (percent >= 80 ? 'success' : percent >= 50 ? 'warning' : 'error')
238
239// --- the gauges ------------------------------------------------------------------
240
241/** What each cell of a gauge holds: used, not yet used, or the even-pace mark. */
242export type GaugeCell = 'fill' | 'empty' | 'mark'
243
244/** A gauge `width` cells long filled to `used`%, with the mark (when given) over whatever cell it lands on. */
245export const gaugeCells = (width: number, used: number, mark: number | null): GaugeCell[] => {
246 const filled = Math.round((Math.min(100, Math.max(0, used)) / 100) * width)
247 const at = mark === null ? -1 : Math.min(width - 1, Math.round((mark / 100) * width))
248 return Array.from({ length: width }, (_, i): GaugeCell => (i === at ? 'mark' : i < filled ? 'fill' : 'empty'))
249}
250
251/** The cells each of `count` gauges gets once `room` holds them and the gaps between them. */
252export const gaugeWidth = (room: number, count: number, gap: number): number =>
253 Math.floor((room - gap * (count - 1)) / count)
254
255types/index.d.ts 52 lines1export type RateWindow = {
2 kind: string
3 percentUsed: number
4 resetsAt: string | null
5 /**
6 * The engine no longer reports it because its reset time passed with no response since:
7 * the window has started over, at 0%, its next reset unknown until a response says it.
8 */
9 isReset?: true
10}
11
12/** The session's credential, as `$.session.authorize()` names it: a login (`bearer`) has plan limits. */
13export type Credential = 'bearer' | 'api-key' | null
14
15/** What the engine measures for this session. */
16export type Live = {
17 model: string
18 context: { tokens: number | null; window: number; percent: number | null }
19 rateLimits: RateWindow[]
20 usd: number | null
21}
22
23/** What ccusage reads from every transcript on this machine. */
24export type Ledger = {
25 /** The active 5-hour block's cost per hour; null when no block is active. */
26 burnPerHour: number | null
27 /** Today's total across all sessions; null when ccusage reported no day. */
28 today: number | null
29}
30
31/** One main-thread request's prompt, as the API reported it: what the cache served, what it wrote, what neither. */
32export type CacheReading = { read: number; written: number; uncached: number }
33
34/** One reading of the 5-hour window: when it was taken, and how much was used. */
35export type FiveSample = { at: number; percentUsed: number }
36
37declare module 'claude-code' {
38 interface PluginState {
39 'usage-band': {
40 live: Live | null
41 effort: string | null
42 ledger: Ledger | null
43 /** The current 5-hour window's readings, oldest first: what %/h is measured from. */
44 fiveSamples: FiveSample[]
45 /** The latest main-thread requests' prompt tokens, oldest first: what the cache hit rate is taken over. */
46 cacheReadings: CacheReading[]
47 /** Which credential the session holds: a login expects the 5-hour and weekly limits, a key neither. */
48 credential: Credential
49 }
50 }
51}
52