One line under the prompt: the model and its effort, how full the context is, the plan's 5-hour and 7-day use with their resets, and what other mods put on it…

<img alt="claude-modpack: eight Claude Code mods, each measured on real tasks before it shipped, built to work together. statusline, smart-compact, delegate, cells, eta, seek, draft, route." src="assets/banner-light.svg" width="880">
<h3>Install in Claude Code</h3>
/plugin install modpack --marketplace HarzerHeribert/claude-modpack
Answer y, then run /modpack:setup to set everything up step by step.<br> Or from your terminal, guided through both steps: bash <(curl -fsSL https://raw.githubusercontent.com/HarzerHeribert/claude-modpack/main/install.sh) (read it first).<br> Prefer doing it by hand? SETUP.md has every step.
Eight free add-ons that work on their own. One command installs them, and there is nothing new to learn.<br> Every number on this page was measured, including where it doesn't help.
Install · What you get · Honest numbers · The site: ideas and evidence · Lab notes · Questions
<img alt="Animated: the cost per job with and without the pack, as bars that grow: in a long session $0.44 against $0.29 (−33%), bigger jobs in a fresh session $0.55 against $0.51 (−8%), quick questions in a fresh session $0.23 against $0.24 (+2%, about even); then what was measured since: −17% on 12 jobs beyond code with the pack as 0.7.0 ships it, −22% on a feature a cheaper model builds from your plan, −11% writing to a word limit in one draft, and compacting a 70k-token session in 4 ms instead of 15 s with the summary written ahead; then 2,550 graded runs, no quality loss seen." src="assets/numbers.gif" width="880">
Every time Claude takes a step (reads a file, makes an edit, runs the tests), it reads your whole conversation again. That re-reading is most of what a session costs, and it grows the longer you work. So the cheapest step is the one Claude never has to take.
The pack takes out steps that need no thinking. Several edits and their test run as one step. A search for a name in your code comes back with the exact answer. And when you approve a plan, a cheaper model does the building while Claude checks the result. The work comes out the same; Claude just gets there in fewer round trips.
<img alt="A real Claude Code session with the pack, six moments cut together, each with a caption: a bar and a finish time for long jobs (eta); several edits and the test run in one step (cells); an approved plan built by a cheaper model and checked (delegate); asked for at most 300 words, one draft that fits (draft); compacted at once, its summary written ahead, with that setting on (smart-compact); every mod with a switch that acts at once (/mods). Under the prompt throughout, the status line: model, context, the plan's 5-hour and weekly use." src="assets/demo-tour.gif" width="880">
One line under the prompt: the model, how full the conversation is, and how much of your plan's 5-hour and weekly limits you have used, with when each one resets. Long jobs get a progress bar and a finish time above the prompt. And when you step away, your session is kept ready, or tidied up before it goes cold, whichever costs less; the line tells you which.
These are the statusline, eta and smart-compact mods.
When a conversation fills up, Claude Code summarizes it so the work can go on, and you wait while it writes: 15 seconds at 67k tokens and 102 seconds at 436k in our sessions. Turn on compacting after a turn (afterTurnPayback) and smart-compact compacts a long conversation shortly after a turn ends, when that pays back soon. Its summary is written in the background as the turn ends, so the compaction itself takes 3 to 5 ms. Against /compact from the same session, the next job cost 14% less, at full marks in 16 of 18 runs against 14 of 18 (lab note 15).
That's the smart-compact mod (compacting after a turn is off until you turn it on).
Claude makes several edits and runs the tests as one step, and you watch each part happen in a live card. Every edit still goes through Claude Code's own edit tool: you see each change, and /rewind undoes it.
That's the cells mod.
When you approve a plan, Claude hands the building to Sonnet, a cheaper model, and checks its work before reporting back. In our tests that made a feature 22% cheaper and new tests 26% cheaper, with every result correct (corrected 16 Oct: worker costs were undercounted; it was 27% and 33%). You can watch the helper work in its card, and /delegate shows every step it took.
That's the delegate mod.
An optional mod, off until you turn it on, and the one that needs an outside classifier model: an API key for TypeSafe's Jev or ScaleDown. That classifier reads each prompt you send. Only when it is feature or test work is Claude told to hand it straight to delegate's worker: the worker reads the code and builds, delegate checks the result itself, and Claude reports after two steps of its own. On a TypeScript feature that made the job 51% cheaper and 42% faster than the pack alone, with every result correct (corrected 16 Oct: worker costs were undercounted; it was 57%); everything else stays with Claude. The classifier is an outside service (TypeSafe's Jev or ScaleDown), so this is off until you turn it on and give it a key: from then on, the start of each prompt goes to it, in the US, to be classified. In real sessions it saves less than on the benchmark: in the author's, the turns it would hand off were 13% of the spend, so at most 4 to 7% saved, nearer 3 to 6% with the hand-offs that were not feature or test work; more if most of your work is building features, and less if you already plan in plan mode, where delegate hands an approved plan to the worker without route.
That's the route mod (optional; it needs an outside classifier and its key).
Before Claude changes anything, it looks around your code, and everything it reads stays in the conversation, read again with every later step. Beside the first prompt you send in a session, and again as the session grows, the pack passes on your preference to look around in few, lean steps: the searches it can already name in one go, the lines that matter rather than whole files, nothing read twice. Against the pack without it, that made jobs 12% cheaper in a fresh session, 16% on a TypeScript library and 10 to 16% in long sessions, at the same quality. It runs on your machine and sends nothing anywhere.
That's the seek mod.
Ask for a text of at most so many words, and Claude tends to write all of it, count, find it a third too long, and write all of it again, several times. With a limit in your prompt, the pack passes on your preference to give each part its share and aim a little under, to keep every fact you asked for (and say so if they cannot all fit), and after each write it shows the word count and, when the text is well over, each section's target, so one more write lands it. On six writing tasks that made them 11% cheaper at the same quality. Without a word limit in your prompt it does nothing.
That's the draft mod.
/mods lists the eight and turns any of them on or off, right away, with a click or by typing, such as /mods statusline off. When something can't fully work on your computer, the pack tells you once, with the command that fixes it. When another plugin's permission or notification hook hangs (Warp's does outside the Warp terminal), the pack stops waiting for it after 10 seconds, so Claude Code can't freeze, and tells you which one it was. It keeps itself up to date (or only lets you know, if you prefer).
That's the modpack plugin, which installs the other eight.
In Claude Code, type:
/plugin install modpack --marketplace HarzerHeribert/claude-modpack
Answer y to add the marketplace, then pick where to install it. That installs all eight. Then, in the project you work in:
/modpack:setup
It checks your machine, asks once what you want on (route stays off unless you say yes), sets each mod up in order, and checks that each one works. Done. /mods shows what's on.
By hand instead: SETUP.md has every step.
Each mod installs on its own the same way, for example /plugin install smart-compact --marketplace HarzerHeribert/claude-modpack. delegate and cells use a language server where you have one installed and work without it: Language servers.
We measured the pack on Claude Opus 5.5 doing seven real jobs in an open-source project (click), from a one-line lookup to building a feature, on two days, 13 and 15 October. Every result was checked by hidden tests. The same jobs ran with the pack and without it, and we compared what they cost at API prices.
| Cost per job | Without | With the pack | |
|---|---|---|---|
| In a long session (Claude has already read the whole project) | $0.44 | $0.29 | −33% |
| Bigger jobs in a long session (a feature, tests, a rename) | $0.91 | $0.57 | −37% |
| In a fresh session | $0.37 | $0.35 | −4% |
| Bigger jobs in a fresh session | $0.55 | $0.51 | −8%, and 15% faster |
| Quick questions in a fresh session | $0.23 | $0.24 | +2%, about even |
<img alt="Cost per task, plain Claude Code against the modpack, in a fresh session and in a session already holding 216k tokens." src="assets/cost-light.svg" width="880">
<img alt="Model requests per task, plain Claude Code against the modpack: 3.2 against 5.6 in a session already holding 216k tokens." src="assets/requests-light.svg" width="880">
<img alt="Cost per task, Opus alone against a plan handed to a worker: feature work 22% less, tests 26% less." src="assets/delegate-light.svg" width="880">
How we measured, every run's record, and the scripts to run it all again are in benchmarks/, starting with SUITE.md. What we tried that did not make it is in the lab notes (as Markdown), among it a 10,000-star code graph, Trail-Code, which installed into Claude Code saved nothing we could measure: alone −1.8% against plain Claude Code (−5.9% to +2.7%), beside the pack +13% (lab notes 3). Not measured: what smart-compact saves you while you're away (worked out from prices, not tested) and Windows.
Will Claude's work get worse? Not that we have seen. Every run is graded by hidden tests or fixed rules, and the same jobs run with the pack and without it. In the batches that did both, 6 of 349 runs without the pack and 8 of 407 with it fell short of full marks. Of all 2,586 graded runs that ship with this release, 96 fell short: seven on one TypeScript explanation whose answers sometimes leave out one term of its list, with the pack and without; five with Trail-Code, whose hook replaced the answer; seven with Haiku as the main model, in two experiments we dropped; one TypeScript type question; and six on PocketBase. There, two questions left out terms of their answer key in both arms, and plain Claude Code missed one term of a third. On that third question the pack scored 0: lsp-plus held a search while Go's language server was still loading, Claude Code moved it to the background, and Claude's last message answered the notice that followed instead of the question. lsp-plus 0.4.2 then gave the language server 8 seconds at most, and lsp-plus has since left the pack. Seven more are 0.7.0's: five on one prose revision whose checks are strict, in every arm, plain Claude Code too; one runbook and one rename. And 22 are 0.8.0's: nine in the writing tasks, three with draft and three without in one batch and three more with draft in the next (a removed command named as current, a follow-up missing from a brief); thirteen in the compaction benchmark, spread over every arm, ten of them one option check of one task and three a rename that kept a deprecated alias of the old name. Six are 0.9.0's, from the benchmark of the summary written ahead against /compact: five that same option check, two with the summary written ahead and three with /compact, and one rename under /compact that left the old name in one file. And 29 ship with the lab notes of 19 October: 28 from draft's first writing batches, with draft and without, graded before three of their graders were fixed (a removed command named in a history sentence, a code-span check, a stale base; lab note 13), and one with steer, a system-prompt experiment we did not ship. And six ship with 0.9.3, from the next-task benchmark of two shorter summaries, three each: the same option check three times, and the rename three times (twice a docstring note naming the old name, once the old name left in one file). Apart from the PocketBase run, the pack changes how many steps Claude takes, not whether it gets there.
Where did lsp-plus go? It left the pack in 0.7.0. Measured twice, 120 runs on renames and traces in click, a TypeScript library and a React app and on web, operating and prose work, the pack cost no more without it (−1.8% and −1.6%, both ranges across zero), and it kept a language server running per language in every session, hundreds of MB each. Its answer to a grep came from the language server, and in untyped code a server finds about half the uses of a name, where a plain word search finds them all (lab notes 12). The update removes it once and says so in one line; installed again on purpose, it stays. Its last version, 0.4.2, is in this repository's v0.6.1 tag.
Is it safe? It's open source (MIT), so every line is here to read. Code that Claude runs inside a cell runs in a sandbox with no network access. Edits go through Claude Code's own edit tool, so your usual permission prompts and /rewind still apply. The pack sends nothing anywhere except a once-a-day check on GitHub for a new release, which you can turn off, and, only if you turn route on, the start of each prompt to the classifier you chose (TypeSafe or ScaleDown).
Does the pack add anything to my prompts? Your prompt itself is never changed. Beside it, Claude can get a short note in your name: seek's setting to look around in few, lean steps (with the first prompt of a session, and again after a compaction), and, only if you turn route on, the order to hand feature or test work to the worker; delegate gives the same order when you approve a plan of 20 lines or more. A subagent Claude starts gets cells' and seek's settings at the end of its task, since your prompts never reach it. /mods seek off and /mods route off stop theirs; subagents: false in cells or seek stops theirs for subagents.
I'm on a Pro or Max plan. Does this help me? You don't pay per job, but every step counts against your 5-hour and weekly limits. We measured cost at API prices, not plan usage, so we can't promise a number. Fewer, lighter steps should leave more of your limits, and the status line shows exactly where you stand.
Does it work in the desktop app? Yes, cards, progress and the status line included. One limit: in auto mode the desktop app doesn't let an add-on start a helper model, so plans aren't handed off there (turn route off there too); in manual mode, or in the terminal, they are. Windows hasn't been tested yet.
How do I turn it off? /mods switches each part off or on, right away. /plugin removes them.
Were any of these numbers wrong? Yes, the hand-off ones. On 16 October we found that our bench had counted a worker's output only as each of its responses began, so every saving that involved a worker came out too large: a planned feature was −27% and is −22%. They are corrected here, the old and new number side by side in CORRECTION-1016.md. The pack-against-plain numbers had no workers and stand.
What does it cost? Nothing. It's free and open source.
One line under the prompt, drawn in Claude Code's own hint row so the mode indicator and the status share it:
⏵⏵ auto mode on Opus 5.5 xhigh 412k ━━━━━━────── 5h 34% ↺2h14 7d 12% ↺3d ● ready · cold in 44m
$.statusline.set({ id, priority, parts, short?, side? }) and lists statusline among its dependencies. A part is text, a countdown ({ until, prefix?, warnMs? }, counted by the line) or a spinner ({ spin: true }), so a mod sends a segment when it changes, not every second. $.statusline.remove({ id }) takes it off./rc) from the desktop app, the web or the phone gets no mod drawing and no status text as of Claude Code 2.1.296.| Option | Default | |
|---|---|---|
enabled | true | false turns the mod off; /mods does it for all of the pack. |
placement | line | tail: appended dim to Claude Code's hint. band: above the prompt. off. |
limits | always | half: a plan window only once it is half used. off: never. |
animate | true | The highlight along the gauge. |
An idle session's prompt cache expires after its TTL: 1 hour on a subscription, 5 minutes in ove
hooks/register.tsx 441 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, Timer } from 'claude-code'
3
4import type { StatuslineArtifact, StatuslineSegment, StatuslineWorld } from '../types'
5import { isPagePublish, parsePublish, shortUrl, titleOf, upsert } from './artifacts'
6import {
7 COLORS,
8 PLAIN_SEPARATOR,
9 SEPARATOR,
10 artifactsLabel,
11 buildSegments,
12 buildUncalm,
13 condenseHint,
14 fit,
15 isMoving,
16 plain,
17 rowLead,
18 width,
19} from './line'
20import type { LimitsShown, Segment } from './line'
21
22type Engine = EngineInterface
23type Placement = 'line' | 'tail' | 'band' | 'off'
24type Options = { placement: Placement; limits: LimitsShown; animate: boolean }
25
26const INITIAL_WORLD: StatuslineWorld = { isWorking: false, window: 200_000, limits: [] }
27
28const SEGMENTS = atom({ plugin: 'statusline', key: 'segments' } as const, {} as Record<string, StatuslineSegment>)
29const WORLD = atom({ plugin: 'statusline', key: 'world' } as const, INITIAL_WORLD)
30const ARTIFACTS = atom({ plugin: 'statusline', key: 'artifacts' } as const, [] as StatuslineArtifact[])
31const ARTIFACTS_OPEN = atom({ plugin: 'statusline', key: 'isArtifactsOpen' } as const, false)
32
33/** The glint's frame rate while Claude works; a turning or blinking segment's. */
34const GLINT_MS = 50
35const MOVE_MS = 125
36
37function pick<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
38 return typeof value === 'string' && (allowed as readonly string[]).includes(value) ? (value as T) : fallback
39}
40
41function readOptions(o: PluginOptions): Options {
42 return {
43 placement: pick<Placement>(o.placement, ['line', 'tail', 'band', 'off'], 'line'),
44 limits: pick<LimitsShown>(o.limits, ['always', 'half', 'off'], 'always'),
45 animate: o.animate !== false,
46 }
47}
48
49let options: Options = readOptions({})
50/** The permission mode, as hooks last reported it: the engine labels the hint's row with it. */
51let permissionMode: string | undefined
52let frames: Timer | undefined
53let framesMs = 0
54let mirrored = false
55let lastMirror = 0
56
57function setWorld($: Engine, change: (w: StatuslineWorld) => Partial<StatuslineWorld>) {
58 return update($, WORLD, w => ({ ...w, ...change(w) }))
59}
60
61/** Redraws at the rate something on the line moves at: the glint, a spinner or a blink; else not at all. */
62async function animate($: Engine) {
63 const now = await $.clock.now()
64 const world = await read($, WORLD)
65 const given = Object.values(await read($, SEGMENTS))
66 const want = options.placement === 'off' ? 0 : world.isWorking && options.animate ? GLINT_MS : given.some(s => isMoving(s, now)) ? MOVE_MS : 0
67 if (want === framesMs) return
68 frames?.cancel()
69 frames = want > 0 ? $.clock.every(want, () => $.ui.invalidate('ui.render')) : undefined
70 framesMs = want
71}
72
73/** A segment as another mod gave it, checked: an id, a priority, parts of text, countdowns or spinners. */
74function isSegment(s: unknown): s is StatuslineSegment {
75 if (s === null || typeof s !== 'object') return false
76 const seg = s as Record<string, unknown>
77 const isPart = (p: unknown) =>
78 p !== null &&
79 typeof p === 'object' &&
80 (typeof (p as { text?: unknown }).text === 'string' || typeof (p as { until?: unknown }).until === 'number' || (p as { spin?: unknown }).spin === true)
81 return (
82 typeof seg.id === 'string' &&
83 seg.id !== '' &&
84 typeof seg.priority === 'number' &&
85 Array.isArray(seg.parts) &&
86 seg.parts.every(isPart) &&
87 (seg.calm === undefined || typeof seg.calm === 'boolean') &&
88 (seg.short === undefined || (Array.isArray(seg.short) && seg.short.every(isPart)))
89 )
90}
91
92async function refreshWorld($: Engine, isDeep: boolean, isAfterCompact = false) {
93 const usage = await $.session.usage(isDeep || isAfterCompact ? { breakdown: 'summary' } : undefined)
94 const model = await $.session.model().catch(() => undefined)
95 // Before any turn says which effort it ran at, the configured one; the same for the permission
96 // mode until a hook reports it (a reload starts the module over).
97 const settings = isDeep ? await $.settings.read().catch(() => ({}) as Record<string, unknown>) : {}
98 const configured = settings.effortLevel
99 const defaultMode = (settings.permissions as { defaultMode?: unknown } | undefined)?.defaultMode
100 if (permissionMode === undefined && typeof defaultMode === 'string') permissionMode = defaultMode
101 const breakdown = usage.context.breakdown
102
103 await setWorld($, w => ({
104 ...(w.model === undefined && model ? { model } : {}),
105 ...(w.effort === undefined && typeof configured === 'string' ? { effort: configured } : {}),
106 // After a reload or a resume the gauge has a size before any response. After a compaction no response has measured
107 // it yet, and `usage.context.tokens` is still the last one's, from before: /context's estimate stands in.
108 ...(isAfterCompact
109 ? { contextTokens: breakdown?.totalTokens }
110 : w.contextTokens === undefined && usage.context.tokens !== undefined
111 ? { contextTokens: usage.context.tokens }
112 : {}),
113 window: usage.context.window,
114 limits: usage.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt === undefined ? undefined : Date.parse(l.resetsAt) })),
115 ...(breakdown === undefined ? {} : { autoCompactAt: breakdown.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined }),
116 }))
117}
118
119/** Records a page the Artifact tool published, titled by the page itself. */
120async function notePublish($: Engine, input: Record<string, unknown>, text: string, at: number | undefined) {
121 if (!isPagePublish(input)) return
122 const published = parsePublish(text)
123 if (published === undefined) return
124 const html = typeof input.file_path === 'string' ? await $.fs.read(input.file_path).catch(() => undefined) : undefined
125 const title = titleOf(html, input.file_path, input.title)
126 await update($, ARTIFACTS, list => {
127 const before = list.find(a => a.url === published.url)
128 // A reload finds the transcript's publishes oldest first; never let an older one replace a newer.
129 if (before !== undefined && before.version > published.version) return list
130 return upsert(list, { ...published, title, updatedAt: at ?? before?.updatedAt })
131 })
132}
133
134/** Pages published before this load (a resume, a reload), read back from the transcript. */
135async function recoverArtifacts($: Engine) {
136 const messages = await $.session.messages()
137 for (const m of messages) {
138 for (const use of m.toolUses) {
139 if (use.tool === 'Artifact' && !use.isError && use.text) await notePublish($, use.input, use.text, undefined)
140 }
141 }
142}
143
144function ago(ms: number | undefined, now: number): string {
145 if (ms === undefined) return 'earlier'
146 const m = Math.round((now - ms) / 60_000)
147 if (m < 1) return 'just now'
148 if (m < 60) return `${m}m ago`
149 const h = Math.round(m / 60)
150 return h < 48 ? `${h}h ago` : `${Math.round(h / 24)}d ago`
151}
152
153async function segmentsFor($: Engine, isWorking: boolean, columns: number): Promise<Segment[]> {
154 const now = await $.clock.now()
155 const world = await read($, WORLD)
156 const given = Object.values(await read($, SEGMENTS))
157 return buildSegments({ ...world, isWorking }, given, { now, isWorking, columns, limits: options.limits })
158}
159
160/** What the desktop app's line draws: other mods' segments that are not calm. */
161async function desktopSegments($: Engine, isWorking: boolean, columns: number): Promise<Segment[]> {
162 const now = await $.clock.now()
163 const given = Object.values(await read($, SEGMENTS))
164 return buildUncalm(given, { now, isWorking, columns, limits: options.limits })
165}
166
167/** Where no line is drawn (the phone, the IDE), the same line as the session's status text. */
168async function mirror($: Engine) {
169 const surfaces = await $.session.surfaces().catch(() => [] as string[])
170 const isRemote = options.placement !== 'off' && surfaces.some(s => s === 'mobile' || s === 'vscode')
171 const world = await read($, WORLD)
172 const artifacts = isRemote ? await read($, ARTIFACTS) : []
173 const line = isRemote ? plain(fit(await segmentsFor($, world.isWorking, 160), 160)) : ''
174 const text = artifacts.length > 0 ? [artifactsLabel(artifacts.length), line].filter(Boolean).join(PLAIN_SEPARATOR) : line
175 if (text) {
176 $.ui.status(text)
177 mirrored = true
178 } else if (mirrored) {
179 $.ui.status(undefined)
180 mirrored = false
181 }
182}
183
184/** Once a second: countdowns on the line move, and the mirror follows every fifteen. */
185async function tick($: Engine) {
186 const now = await $.clock.now()
187 const given = Object.values(await read($, SEGMENTS))
188 if (given.some(s => s.parts.some(p => 'until' in p))) $.ui.invalidate('ui.render')
189 await animate($)
190 if (now - lastMirror >= 15_000) {
191 lastMirror = now
192 await mirror($).catch(() => undefined)
193 }
194}
195
196export const register: Register = (on, rawOptions) => {
197 options = readOptions(rawOptions)
198 frames = undefined
199 framesMs = 0
200
201 // `$.statusline` for the other mods. The bottom answers nothing; the hooks below are what does.
202 on('engine.create', async ($, e, next) => {
203 const built = await next(e)
204 return {
205 ...built,
206 statusline: {
207 set: async () => ({ isShown: false }),
208 remove: async () => ({ isRemoved: false }),
209 },
210 }
211 })
212
213 // Off: nothing drawn. `$.statusline` stays above, answering that nothing is shown, so the mods that write on it do not fail.
214 if (rawOptions.enabled === false) return
215
216 on('statusline.set', async ($, e) => {
217 if (!isSegment(e)) return { value: { isShown: false } }
218 await update($, SEGMENTS, s => ({ ...s, [e.id]: e }))
219 await animate($)
220 return { value: { isShown: options.placement !== 'off' } }
221 })
222
223 on('statusline.remove', async ($, e) => {
224 const id = typeof e.id === 'string' ? e.id : ''
225 const had = id in (await read($, SEGMENTS))
226 if (had) {
227 await update($, SEGMENTS, s => {
228 const { [id]: _, ...rest } = s
229 return rest
230 })
231 }
232 return { value: { isRemoved: had } }
233 })
234
235 on('session.start', async ($, e, next) => {
236 await refreshWorld($, true).catch(() => undefined)
237 await recoverArtifacts($).catch(() => undefined)
238 $.clock.every(1_000, () => void tick($))
239 return next(e)
240 })
241
242 on('classic.SessionStart', async ($, e, next) => {
243 if (e.permission_mode !== undefined) permissionMode = e.permission_mode
244 if (e.context_tokens) await setWorld($, () => ({ contextTokens: e.context_tokens, ...(e.model ? { model: e.model } : {}) }))
245 return next(e)
246 }).catch(($, e, next) => next(e))
247
248 on('session.end', { reason: 'clear' }, async ($, e, next) => {
249 await setWorld($, () => ({ contextTokens: undefined }))
250 return next(e)
251 })
252
253 on('turn.start', async ($, e, next) => {
254 await setWorld($, () => ({ isWorking: true }))
255 await animate($)
256 return next(e)
257 })
258
259 on('turn.step', async function* ($, e, next) {
260 const result = yield* next(e)
261 if (e.agentId === undefined && result.usage !== null) {
262 const u = result.usage
263 await setWorld($, () => ({
264 model: u.model,
265 contextTokens: u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens,
266 ...(e.effort !== undefined ? { effort: String(e.effort) } : {}),
267 }))
268 }
269 return result
270 })
271
272 on('turn.complete', async ($, e, next) => {
273 const result = await next(e)
274 if (e.agentId !== undefined) return result
275 await setWorld($, () => ({ isWorking: false }))
276 await animate($)
277 await refreshWorld($, false).catch(() => undefined)
278 return result
279 })
280
281 // The plan's windows move between turns too (other sessions use them): the engine says when.
282 on('session.measure', async ($, e, next) => {
283 await setWorld($, () => ({
284 window: e.context.window,
285 limits: e.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt === undefined ? undefined : Date.parse(l.resetsAt) })),
286 }))
287 return next(e)
288 })
289
290 on('session.compact', async ($, e, next) => {
291 const result = await next(e)
292 if (e.agentId !== undefined || e.trigger === 'precompute' || result.skip !== undefined) return result
293 // The window was re-read: the threshold may move with it.
294 await refreshWorld($, true, true).catch(() => undefined)
295 return result
296 }).catch(($, e, next) => next(e))
297
298 // A compaction another mod's hook answered before this one's ran (smart-compact's, with a summary written ahead)
299 // never reaches the hook above; PostCompact follows every compaction, answered by a hook or not.
300 on('classic.PostCompact', async ($, e, next) => {
301 if ((e as { agent_id?: string }).agent_id === undefined) await refreshWorld($, true, true).catch(() => undefined)
302 return next(e)
303 }).catch(($, e, next) => next(e))
304
305 on('tool.call', { tool: 'Artifact' }, async ($, e, next) => {
306 const r = await next(e)
307 if (r.deny === undefined && !r.isError && r.text) {
308 await notePublish($, e as unknown as Record<string, unknown>, r.text, await $.clock.now()).catch(() => undefined)
309 }
310 return r
311 }).catch(($, e, next) => next(e))
312
313 // The mode labels the hint's row; every classic hook reports it, so the line knows its room.
314 on('classic.UserPromptSubmit', async ($, e, next) => {
315 if (e.permission_mode !== undefined) permissionMode = e.permission_mode
316 return next(e)
317 }).catch(($, e, next) => next(e))
318
319 on('classic.Stop', async ($, e, next) => {
320 if (e.permission_mode !== undefined) permissionMode = e.permission_mode
321 return next(e)
322 }).catch(($, e, next) => next(e))
323
324 /** Where the line goes: the desktop app draws no hint row (tried 13 Oct), so there it takes the band above the prompt. */
325 const inBand = (surface: string) => options.placement === 'band' || (options.placement !== 'off' && surface === 'desktop')
326
327 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
328 if ((options.placement !== 'line' && options.placement !== 'tail') || inBand(e.surface)) return next(e)
329
330 const columns = e.viewport?.columns ?? 100
331 const segments = await segmentsFor($, e.props.isWorking, columns)
332
333 if (options.placement === 'tail') {
334 const shown = fit(segments, columns - width(e.props.hint) - 4)
335 if (shown.length === 0) return next(e)
336 return next({ ...e, props: { ...e.props, tail: ` ${plain(shown)}` } })
337 }
338
339 const artifacts = await read($, ARTIFACTS)
340 const isOpen = await read($, ARTIFACTS_OPEN)
341 const hint = condenseHint(e.props.hint, { dropArtifacts: artifacts.length > 0 })
342 const pill = artifacts.length > 0 ? `${artifactsLabel(artifacts.length)} ${isOpen ? '▾' : '▸'}` : ''
343 // The engine draws its indent, mode label ("⏵⏵ auto mode on") and a " · " before this tree, on the
344 // same row. The tree is exactly as wide as what is left: width 100% pushed that dot onto a row of
345 // its own, and the engine's row does not hand a growing tree its free width.
346 const room = Math.max(10, columns - rowLead(permissionMode) - 1)
347 const leftWidth = Math.min(width(hint) + width(pill) + (pill && hint ? 2 : 0), 40)
348 const shown = fit(segments, room - leftWidth - 4)
349 const { Box, Text, Button } = $.ui.resolve(e)
350
351 // With nothing left of the line, the engine's " · " after its mode label would lead nowhere: the
352 // tree starts two cells earlier and covers the dot with blanks.
353 const isBare = !pill && !hint && permissionMode !== 'default'
354 return (
355 <Box flexDirection="row" justifyContent="space-between" width={isBare ? room + 2 : room} marginLeft={isBare ? -2 : 0}>
356 {isBare ? <Text>{' '}</Text> : null}
357 <Box flexShrink={1} marginRight={3}>
358 {pill ? <Button key="artifacts" plain dimColor label={pill} onPress={() => void update($, ARTIFACTS_OPEN, v => !v)} /> : null}
359 {pill && hint ? <Text color={COLORS.faint}>{' '}</Text> : null}
360 <Text color={COLORS.label} wrap="truncate-end">
361 {hint}
362 </Text>
363 </Box>
364 <Box flexShrink={0} marginRight={1}>
365 {shown.flatMap((s, i) => [
366 ...(i > 0 ? [<Text color={COLORS.faint}>{SEPARATOR}</Text>] : []),
367 ...s.parts.map(p =>
368 p.tone === 'glint' ? (
369 <Text color={COLORS.glint} bold>
370 {p.text}
371 </Text>
372 ) : (
373 <Text color={COLORS[p.tone]}>{p.text}</Text>
374 ),
375 ),
376 ])}
377 </Box>
378 </Box>
379 )
380 })
381
382 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
383 if (e.props.hasSurvey) return next(e)
384
385 const published = await read($, ARTIFACTS)
386 const isOpen = await read($, ARTIFACTS_OPEN)
387 // The desktop app shows the essentials itself: there only other mods' segments that are not calm, no pill.
388 const isDesktop = e.surface === 'desktop' && options.placement !== 'off'
389 const artifacts = isOpen && !isDesktop ? published : []
390 const isBand = inBand(e.surface)
391 // Where the band carries the line, the published pages' pill comes with it: there is no hint row to hold it.
392 const pill = isBand && !isDesktop && published.length > 0 ? `${artifactsLabel(published.length)} ${isOpen ? '▾' : '▸'}` : ''
393 const room = e.props.bodyColumns - (pill ? width(pill) + 2 : 0)
394 const segments = isDesktop ? fit(await desktopSegments($, e.props.isWorking, room), room) : isBand ? fit(await segmentsFor($, e.props.isWorking, room), room) : []
395 if (artifacts.length === 0 && segments.length === 0 && !pill) return next(e)
396
397 const now = await $.clock.now()
398 const { Box, Text, Button, Link } = $.ui.resolve(e)
399 const below = await next(e)
400
401 return (
402 <Box flexDirection="column">
403 {artifacts.length > 0 ? (
404 <Box key="artifacts" flexDirection="column">
405 <Box flexDirection="row" justifyContent="space-between">
406 <Text color={COLORS.label}>{artifactsLabel(artifacts.length)} published this session</Text>
407 <Button key="close-artifacts" plain dimColor label="close" onPress={() => void update($, ARTIFACTS_OPEN, () => false)} />
408 </Box>
409 {artifacts.map(a => (
410 <Box key={a.url} flexDirection="row">
411 <Text>{' '}</Text>
412 <Link href={a.url} label={a.title} />
413 <Text color={COLORS.faint}>{` v${a.version} · ${ago(a.updatedAt, now)} `}</Text>
414 <Text color={COLORS.label} wrap="truncate-end">
415 {shortUrl(a.url)}
416 </Text>
417 </Box>
418 ))}
419 </Box>
420 ) : null}
421 {segments.length > 0 || pill ? (
422 <Box key="segments" flexDirection="row" justifyContent={pill ? 'space-between' : 'flex-end'}>
423 {pill ? <Button key="artifacts" plain dimColor label={pill} onPress={() => void update($, ARTIFACTS_OPEN, v => !v)} /> : null}
424 <Box flexDirection="row">
425 {segments.flatMap((s, i) => [
426 ...(i > 0 ? [<Text color={COLORS.faint}>{SEPARATOR}</Text>] : []),
427 ...s.parts.map(p => (
428 <Text color={COLORS[p.tone]} bold={p.tone === 'glint'}>
429 {p.text}
430 </Text>
431 )),
432 ])}
433 </Box>
434 </Box>
435 ) : null}
436 {below ?? null}
437 </Box>
438 )
439 })
440}
441hooks/artifacts.ts 38 lines1// The pages this session published with the Artifact tool, read from what the
2// tool answered, for the status line's artifacts pill and its list.
3
4import type { StatuslineArtifact } from '../types'
5
6/** What a publish answers: the page's link and its version. */
7export function parsePublish(text: string): { url: string; version: number } | undefined {
8 const url = text.match(/\bat (https:\/\/claude\.ai\/(?:code\/)?artifact\/[\w-]+)/)?.[1]
9 if (url === undefined) return undefined
10 return { url, version: Number(text.match(/\(Version (\d+)/)?.[1] ?? 1) }
11}
12
13/** Whether an Artifact call published a page (not an asset upload, a read or a list). */
14export function isPagePublish(input: Record<string, unknown>): boolean {
15 const action = input.action ?? 'publish'
16 return action === 'publish' && input.asset !== true
17}
18
19const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", apos: "'", nbsp: ' ' }
20
21/** A page's own `<title>`, else the title the call gave, else its file's name. */
22export function titleOf(html: string | undefined, filePath: unknown, given: unknown): string {
23 const own = html?.match(/<title[^>]*>([^<]{1,160})<\/title>/i)?.[1]?.trim()
24 if (own) return own.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (_, k: string) => ENTITIES[k] ?? _)
25 if (typeof given === 'string' && given.trim()) return given.trim()
26 const base = typeof filePath === 'string' ? (filePath.split('/').pop() ?? '').replace(/\.(html?|md)$/i, '') : ''
27 return base || 'artifact'
28}
29
30/** Puts a publish first, replacing the same page's earlier entry; keeps twenty. */
31export function upsert(list: readonly StatuslineArtifact[], a: StatuslineArtifact): StatuslineArtifact[] {
32 return [a, ...list.filter(x => x.url !== a.url)].slice(0, 20)
33}
34
35export function shortUrl(url: string): string {
36 return url.replace(/^https:\/\//, '')
37}
38hooks/line.ts 309 lines1// The status line as data: segments of toned parts, fitted to a width by
2// priority. Drawing them (a tree, or a plain tail) is register.tsx's job.
3//
4// The line's own segments say what matters while working: the model and its
5// effort, how full the context is, and how much of the plan's 5-hour and
6// 7-day windows is used. Other mods add theirs through `$.statusline.set`
7// (smart-compact's "● ready · cold in 44m" at the right edge, where the eye
8// lands); a part of theirs may count down or turn, and is resolved here.
9//
10// One palette, from the person's theme: grey labels, the Claude accent for
11// what is live, warning and error only for what needs attention.
12
13import type { Color } from 'claude-code'
14
15import type { StatuslinePart, StatuslineSegment, StatuslineTone, StatuslineWorld } from '../types'
16
17export type Tone = StatuslineTone | 'glint'
18
19export type Part = { text: string; tone: Tone }
20
21/** `short` is what the segment says when the full form does not fit, before it is dropped. */
22export type Segment = { id: string; priority: number; parts: Part[]; short?: Part[] }
23
24export type LimitsShown = 'always' | 'half' | 'off'
25
26export const COLORS: Record<Tone, Color> = {
27 accent: 'claude',
28 good: 'success',
29 text: 'text',
30 // In Claude Code's themes "inactive" is the readable grey and "subtle" the dim one (dark theme:
31 // 246 and 239 of 256): labels read in the first, separators and the empty gauge sit back in the second.
32 label: 'inactive',
33 faint: 'subtle',
34 warn: 'warning',
35 alert: 'error',
36 glint: 'text',
37}
38
39/** Between groups on the drawn line: space, not punctuation. */
40export const SEPARATOR = ' '
41/** Between groups where the line is one plain string (web, mobile). */
42export const PLAIN_SEPARATOR = ' · '
43/** With `limits: half`, a plan window shows from this share used. */
44export const LIMITS_FROM = 50
45
46const SPIN = ['◐', '◓', '◑', '◒'] as const
47
48export type Moment = { now: number; isWorking: boolean; columns: number; limits: LimitsShown }
49
50function part(text: string, tone: Tone): Part {
51 return { text, tone }
52}
53
54export function width(text: string): number {
55 return [...text].length
56}
57
58export function segmentWidth(s: Segment): number {
59 return s.parts.reduce((sum, p) => sum + width(p.text), 0)
60}
61
62function severity(fraction: number): Tone {
63 return fraction >= 0.95 ? 'alert' : fraction >= 0.8 ? 'warn' : 'accent'
64}
65
66export function tokens(n: number): string {
67 if (n < 1_000) return `${n}`
68 if (n < 100_000) return `${(n / 1_000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k`
69 if (n < 1_000_000) return `${Math.round(n / 1_000)}k`
70 return `${(n / 1_000_000).toFixed(2).replace(/0$/, '')}M`
71}
72
73/** `44m`, then `2h14`. */
74function minutes(m: number): string {
75 if (m < 60) return `${m}m`
76 const h = Math.floor(m / 60)
77 return m % 60 === 0 ? `${h}h` : `${h}h${String(m % 60).padStart(2, '0')}`
78}
79
80/** `8:00` under ten minutes, then as `minutes` says it. */
81export function duration(ms: number): string {
82 const s = Math.max(0, Math.round(ms / 1000))
83 return s < 600 ? `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}` : minutes(Math.round(s / 60))
84}
85
86/**
87 * How long until a reset: `5m`, `44m`, `4h40`, days past two. Never seconds, which beside
88 * `12h25` read as a clock (`4:40`); rounded up, so the last minute is `1m`, not `0m`.
89 */
90export function span(ms: number): string {
91 const days = ms / 86_400_000
92 return days >= 2 ? `${Math.round(days)}d` : minutes(Math.max(1, Math.ceil(ms / 60_000)))
93}
94
95/**
96 * A line gauge with half-cell steps. While the model works a glint sweeps
97 * along it, which is what the 20 fps redraw is for.
98 */
99export function gauge(fraction: number, cells: number, tone: Tone, glintAt?: number): Part[] {
100 const halves = Math.round(Math.min(1, Math.max(0, fraction)) * cells * 2)
101 const out: Part[] = []
102
103 for (let i = 0; i < cells; i += 1) {
104 const filled = Math.min(2, Math.max(0, halves - i * 2))
105 const glyph = filled === 2 ? '━' : filled === 1 ? '╸' : '─'
106 const isGlint = glintAt !== undefined && Math.abs(i - glintAt) < 1
107 const cellTone: Tone = isGlint ? (filled > 0 ? 'glint' : 'label') : filled > 0 ? tone : 'faint'
108 const last = out.at(-1)
109
110 if (last && last.tone === cellTone) {
111 last.text += glyph
112 } else {
113 out.push(part(glyph, cellTone))
114 }
115 }
116
117 return out
118}
119
120function contextSegment(world: StatuslineWorld, m: Moment): Segment | undefined {
121 if (world.contextTokens === undefined) return undefined
122 const limit = world.autoCompactAt ?? world.window
123 const fraction = limit > 0 ? world.contextTokens / limit : 0
124 const cells = m.columns >= 110 ? 12 : 8
125 const tone = severity(fraction)
126 const glintAt = m.isWorking ? ((m.now % 1600) / 1600) * (cells + 4) - 2 : undefined
127
128 const size = part(`${tokens(world.contextTokens)} `, tone === 'accent' ? 'label' : tone)
129 return {
130 id: 'context',
131 priority: 1,
132 parts: [size, ...gauge(fraction, cells, tone, glintAt)],
133 short: [{ ...size, text: size.text.trim() }],
134 }
135}
136
137/**
138 * The plan's windows: how much is used and when each resets. Quiet while under half, plain
139 * text past it, warning from 80%. Narrow lines drop the reset first, then the window.
140 */
141function limitSegments(world: StatuslineWorld, m: Moment): Segment[] {
142 const out: Segment[] = []
143 const order = (kind: string) => (kind === 'five_hour' ? 0 : kind === 'seven_day' ? 1 : 2)
144
145 for (const limit of [...world.limits].sort((a, b) => order(a.kind) - order(b.kind))) {
146 const label = limit.kind === 'five_hour' ? '5h' : limit.kind === 'seven_day' ? '7d' : '$'
147 const isPlan = limit.kind === 'five_hour' || limit.kind === 'seven_day'
148 // A spend cap matters once it runs warm; the plan's windows as the person asked.
149 const hidden = isPlan ? m.limits === 'off' || (m.limits === 'half' && limit.percentUsed < LIMITS_FROM) : limit.percentUsed < 70
150 if (hidden) continue
151
152 const fraction = limit.percentUsed / 100
153 const tone: Tone = fraction >= 0.8 ? severity(fraction) : fraction >= 0.5 ? 'text' : 'label'
154 const short = [part(`${label} `, 'label'), part(`${Math.round(limit.percentUsed)}%`, tone)]
155 const parts = [...short]
156 if (limit.resetsAt !== undefined && limit.resetsAt > m.now) parts.push(part(` ↺${span(limit.resetsAt - m.now)}`, 'faint'))
157
158 const priority = limit.kind === 'five_hour' ? 2 : limit.kind === 'seven_day' ? 3 : 4
159 out.push({ id: `limit-${limit.kind}`, priority, parts, short: parts.length > short.length ? short : undefined })
160 }
161
162 return out
163}
164
165/** "Opus 5.5" from an id, a `/model` name or an alias; the alias itself, capitalised, when it names no version. */
166export function modelLabel(model: string): string {
167 const id = model.toLowerCase().replace(/[.\s]/g, '-')
168 const m = /(opus|sonnet|haiku|fable)-(\d+)(?:-(\d{1,2})(?!\d))?/.exec(id)
169 const name = (word: string) => word[0]!.toUpperCase() + word.slice(1)
170 if (m) return m[3] !== undefined ? `${name(m[1]!)} ${m[2]}.${m[3]}` : `${name(m[1]!)} ${m[2]}`
171 const alias = /^(opus|sonnet|haiku|fable)/.exec(id)?.[1]
172 return alias ? name(alias) : model
173}
174
175const EFFORT_TONES: Record<string, Tone> = { low: 'faint', medium: 'label', high: 'text', xhigh: 'accent', max: 'accent' }
176
177/** The model and its effort, the effort coloured by how hard it works. */
178function modelSegment(world: StatuslineWorld): Segment | undefined {
179 if (world.model === undefined) return undefined
180 const parts = [part(modelLabel(world.model), 'label')]
181 if (world.effort !== undefined) parts.push(part(` ${world.effort}`, EFFORT_TONES[world.effort] ?? 'label'))
182 return { id: 'model', priority: 5, parts }
183}
184
185/** A part another mod gave, as it reads now: a countdown counted, a spinner turned, a blink blinked. */
186export function resolvePart(p: StatuslinePart, now: number): Part {
187 if ('spin' in p) return part(SPIN[Math.floor(now / 125) % SPIN.length] ?? '◐', p.tone)
188 if ('until' in p) {
189 const left = p.until - now
190 return part(`${p.prefix ?? ''}${duration(left)}`, p.warnMs !== undefined && left < p.warnMs ? 'warn' : p.tone)
191 }
192 const isOff = p.blink !== undefined && now >= p.blink.from && now < p.blink.to && Math.floor(now / 500) % 2 === 0
193 return part(p.text, isOff ? 'faint' : p.tone)
194}
195
196function resolveSegment(s: StatuslineSegment, now: number): Segment {
197 return {
198 id: s.id,
199 priority: s.priority,
200 parts: s.parts.map(p => resolvePart(p, now)),
201 short: s.short?.map(p => resolvePart(p, now)),
202 }
203}
204
205/** Whether a segment moves by itself: a spinner, or a blink under way. */
206export function isMoving(s: StatuslineSegment, now: number): boolean {
207 return s.parts.some(p => 'spin' in p || ('blink' in p && p.blink !== undefined && now >= p.blink.from && now < p.blink.to))
208}
209
210/**
211 * Every segment, in the order they read: other mods' `start` segments, the model and its effort,
212 * the context, the plan windows, then other mods' `end` segments, the most important rightmost.
213 * Narrow terminals lose the model first, then the windows, then the gauge.
214 */
215export function buildSegments(world: StatuslineWorld, given: readonly StatuslineSegment[], m: Moment): Segment[] {
216 const byPriority = (a: StatuslineSegment, b: StatuslineSegment) => b.priority - a.priority
217 const start = given.filter(s => s.side === 'start').sort(byPriority)
218 const end = given.filter(s => s.side !== 'start').sort(byPriority)
219 return [
220 ...start.map(s => resolveSegment(s, m.now)),
221 modelSegment(world),
222 contextSegment(world, m),
223 ...limitSegments(world, m),
224 ...end.map(s => resolveSegment(s, m.now)),
225 ].filter((s): s is Segment => s !== undefined)
226}
227
228/** Only what other mods gave and is not calm, in the order they read: what the desktop app's line draws. */
229export function buildUncalm(given: readonly StatuslineSegment[], m: Moment): Segment[] {
230 return buildSegments({ isWorking: m.isWorking, window: 0, limits: [] }, given.filter(s => s.calm !== true), m)
231}
232
233/** The artifacts pill's text. */
234export function artifactsLabel(n: number): string {
235 return `${n} artifact${n === 1 ? '' : 's'}`
236}
237
238/**
239 * Makes the segments fit in `room`: the least important first says its short form, if it has
240 * one, and is dropped only when that does not fit either.
241 */
242export function fit(segments: readonly Segment[], room: number): Segment[] {
243 const kept = [...segments]
244 const total = () => kept.reduce((sum, s) => sum + segmentWidth(s), 0) + Math.max(0, kept.length - 1) * width(SEPARATOR)
245
246 while (kept.length > 0 && total() > room) {
247 const worst = kept.reduce((a, b) => (b.priority >= a.priority ? b : a))
248 const at = kept.indexOf(worst)
249 if (worst.short) {
250 kept[at] = { ...worst, parts: worst.short, short: undefined }
251 } else {
252 kept.splice(at, 1)
253 }
254 }
255
256 return kept
257}
258
259export function plain(segments: readonly Segment[], separator = PLAIN_SEPARATOR): string {
260 return segments.map(s => s.parts.map(p => p.text).join('')).join(separator)
261}
262
263/** The width of the drawn line's segments, separators included. */
264export function drawnWidth(segments: readonly Segment[]): number {
265 return segments.reduce((sum, s) => sum + segmentWidth(s), 0) + Math.max(0, segments.length - 1) * width(SEPARATOR)
266}
267
268/**
269 * The engine's own hint, kept to what matters: the permission mode's name
270 * without its key help, and warnings such as `ctrl+c again to exit`. Key help
271 * the person knows by heart goes: `? for shortcuts`, `esc to interrupt`,
272 * `← for agents`.
273 */
274export function condenseHint(hint: string, options: { dropArtifacts?: boolean } = {}): string {
275 return (
276 hint
277 // The engine's artifacts pill ("⧉2", or "⧉ <title>"), when the line draws its own.
278 .replace(options.dropArtifacts ? /⧉[^·]*/g : /$^/g, '')
279 .replace(/\s*\((?:shift\+tab|⇧⇥)[^)]*\)/gi, '')
280 .replace(/\s+mode on\b/gi, '')
281 .replace(/\?\s*for shortcuts/gi, '')
282 .replace(/\besc to interrupt\b/gi, '')
283 .replace(/←\s*for agents/gi, '')
284 .replace(/(\s*·\s*){2,}/g, ' · ')
285 .replace(/^\s*·\s*|\s*·\s*$/g, '')
286 .replace(/\s{2,}/g, ' ')
287 .trim()
288 // Nothing but separators left: nothing.
289 .replace(/^[\s·•|]*$/, '')
290 )
291}
292
293/**
294 * Cells the engine takes on the hint's row before this tree: its indent, the mode label
295 * ("⏵⏵ auto mode on") and the " · " after it. The default mode draws no label; an unknown one is
296 * given room for a long label, so the line falls short of the edge rather than past it.
297 */
298export function rowLead(mode: string | undefined): number {
299 const labels: Record<string, string> = {
300 auto: '⏵⏵ auto mode on',
301 acceptEdits: '⏵⏵ accept edits on',
302 plan: '⏸ plan mode on',
303 bypassPermissions: '⏵⏵ bypass permissions on',
304 }
305 if (mode === 'default') return 2
306 const label = mode === undefined ? undefined : labels[mode]
307 return 2 + (label === undefined ? 24 : width(label)) + 3
308}
309types/index.d.ts 83 lines1/** How a part reads: the line's palette, from the person's theme. */
2export type StatuslineTone = 'accent' | 'good' | 'text' | 'label' | 'faint' | 'warn' | 'alert'
3
4/** Text in a tone; with `blink`, it blinks between those two times (ms since the epoch). */
5export type StatuslineText = { text: string; tone: StatuslineTone; blink?: { from: number; to: number } }
6
7/** The time left until `until` (ms since the epoch), as `8:00`, `44m` or `2h14`; warn-toned in its last `warnMs`. */
8export type StatuslineCountdown = { until: number; tone: StatuslineTone; prefix?: string; warnMs?: number }
9
10/** A spinner that turns while it is shown. */
11export type StatuslineSpinner = { spin: true; tone: StatuslineTone }
12
13export type StatuslinePart = StatuslineText | StatuslineCountdown | StatuslineSpinner
14
15/**
16 * A segment another mod puts on the line. `id` is the mod's and stays the same
17 * (`smart-compact:ready`). A lower `priority` stays longer on a narrow line: the
18 * line's own are the context 1, the 5-hour window 2, the 7-day window 3, a spend
19 * cap 4, the model 5. `short` is what it says before it is dropped. `side: 'end'`
20 * (the default) sits at the right edge, where the eye lands; `'start'` before the model.
21 * `calm` marks a routine state: drawn where the line has room for everything, left out
22 * where the host shows the essentials itself (the desktop app).
23 */
24export type StatuslineSegment = {
25 id: string
26 priority: number
27 parts: StatuslinePart[]
28 short?: StatuslinePart[]
29 side?: 'start' | 'end'
30 calm?: boolean
31}
32
33/** What other mods call: `$.statusline.set(segment)`, `$.statusline.remove({ id })`. */
34export type Statusline = {
35 /** Puts the segment on the line, replacing the one with its id. */
36 set: (segment: StatuslineSegment) => Promise<{ isShown: boolean }>
37 /** Takes the segment with this id off the line. */
38 remove: (args: { id: string }) => Promise<{ isRemoved: boolean }>
39}
40
41export type StatuslineLimit = { kind: string; percentUsed: number; resetsAt?: number }
42
43/** What the line draws of the session itself. */
44export type StatuslineWorld = {
45 isWorking: boolean
46 /** The main loop's model: the last response's, else the session's. */
47 model?: string
48 /** The effort of the last turn, or the configured one before any. */
49 effort?: string
50 /** Prompt tokens of the main thread's last request. */
51 contextTokens?: number
52 window: number
53 /** Where the engine auto-compacts; absent when it does not. */
54 autoCompactAt?: number
55 limits: StatuslineLimit[]
56}
57
58/** A page this session published with the Artifact tool, as the line's pill lists it. */
59export type StatuslineArtifact = {
60 url: string
61 title: string
62 version: number
63 /** When it was last published; absent for one found in the transcript after a reload. */
64 updatedAt?: number
65}
66
67declare module 'claude-code' {
68 interface EngineInterface {
69 statusline: Statusline
70 }
71 interface PluginState {
72 statusline: {
73 /** What other mods put on the line, by id. */
74 segments: Record<string, StatuslineSegment>
75 world: StatuslineWorld
76 /** Newest first. */
77 artifacts: StatuslineArtifact[]
78 /** The artifacts list is open in the band above the prompt. */
79 isArtifactsOpen: boolean
80 }
81 }
82}
83