SLOPSHOPPER

mods

Claude Code interface mods by kadragon. Claude Code only; built on the early-access function-hooks API.

bandprocesstimer
★ 1v0.4.3MITupdated 2026-10-26kadragon/agent-toolkit/mods
A shopper browsing a rack in a slop shop
README

kadragon/agent-toolkit

Personal agent plugin marketplace by kadragon.

Three plugins:

dev — development

SkillDescriptionClaude CodeCodex
harness-initBootstraps agent infrastructure (AGENTS.md, docs/, hooks)✅❌
task-reviewOrchestrates Claude/Antigravity/Codex reviewers, merges✅❌
harness-curateMines transcripts to manage harness assets✅❌
repo-dependabotBulk Dependabot PR operations✅⚠️

Commands:

CommandDescriptionClaude CodeCodex
/security-overviewScans GitHub security alerts (Dependabot, Code Scanning, Secret Scanning) across owned repos, writes per-repo plan.md✅❌

prod — document authoring

SkillDescriptionClaude CodeCodex
hwpxKorean HWPX document creation and editing✅✅
persona-debateStructured debate among Korean personas✅⚠️

mods — Claude Code interface mods

Claude Code only. Built on the early-access function-hooks API, so it needs a recent Claude Code build and may break on an update; dev and prod do not depend on it.

ModDescriptionSetting
status-bandTwo rows above the prompt, each figure in its own color: model and effort, directory and git branch, session time, prompt-cache time left, hook count and skill count with the size of the skill listing, then context fill and the 5-hour and 7-day rate limits with their resets. A figure the engine has no reading for is left out.Status band (on by default), Status band cache TTL (minutes) (60)

status-band shows what a statusLine command such as claude-hud (github.com/jarrodwatts/claude-hud, whose layout it follows) shows, so running both draws the same figures twice: remove the statusLine entry from your settings.json if you switch. The mod never edits your settings. It redraws once a minute and after each turn.

The cache figure is an estimate: the engine tells a mod neither the cache's lifetime nor what is left of it, so the band counts the setting's minutes down from the last main-thread response. Set it to 5 where your session runs on the short cache. The hook count is the hook handlers in your merged settings plus those of every enabled plugin, read off the files that declare them; hooks modules such as this one's are not counted. Both counts are read again after each turn. A branch name over 24 characters is cut so the figures after it stay on the row, and a blank row keeps the band off the line above it.

Installation

Migrating from toolkit@kadragon? The former single plugin is now split into dev@kadragon and prod@kadragon. Remove the old plugin (claude plugin uninstall toolkit@kadragon) and install both below. Also update any SessionStart hook that referenced toolkit:harness-maintenance — maintenance now runs inside the dev plugin's single SessionStart dispatcher (hooks/session-start/run.sh).

npx skills

# All skills
npx skills add kadragon/agent-toolkit

# Specific skills
npx skills add kadragon/agent-toolkit --skill hwpx
npx skills add kadragon/agent-toolkit --skill persona-debate
npx skills add kadragon/agent-toolkit --skill task-review
npx skills add kadragon/agent-toolkit --skill task-review-cycle  # required — task-review only forwards to it
npx skills add kadragon/agent-toolkit --skill harness-init

Claude Code

claude plugin marketplace add kadragon/agent-toolkit
claude plugin install dev@kadragon
claude plugin install prod@kadragon
claude plugin install mods@kadragon   # optional

Via ~/.claude/settings.json:

{
  "enabledPlugins": {
    "dev@kadragon": true,
    "prod@kadragon": true
  },
  "extraKnownMarketplaces": {
    "kadragon": {
      "source": {
        "source": "github",
        "repo": "kadragon/agent-toolkit"
      },
      "autoUpdate": true
    }
  }
}

Codex

Codex uses .agents/plugins/marketplace.json and .codex-plugin/plugin.json manifests:

codex plugin marketplace add kadragon/agent-toolkit
codex plugin add dev@kadragon
codex plugin add prod@kadragon

Install only ✅/⚠️ skills from table above.

Prerequisites

License

MIT

Source 6 files
hooks/register.ts 12 lines
1import type { Register } from 'claude-code'
2
3import { register as band } from './band'
4import { register as statusBand } from './status-band/register'
5
6// The engine loads one hooks module per plugin, so every mod registers here.
7// Each is called by name: the loader refuses a callee it cannot trace to a file.
8export const register: Register = (on, options) => {
9  statusBand(on, options)
10  band(on, options)
11}
12
hooks/band.tsx 38 lines
1import { atom, read } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { ASCII, setupSegments, UNICODE } from './status-band/format'
5import { statusRows } from './status-band/register'
6
7// The same value the mod writes: the loader reads an atom's key off the file
8// that uses it, so it is spelled again here.
9const statusBand = atom({ plugin: 'mods', key: 'statusBand' } as const, null)
10
11// The engine takes one hook per plugin on the band above the prompt, so a mod
12// that draws there hands its rows over here.
13// The status rows are three, or two with the setup on the headline where the
14// band has no third; under a blank one where another row fits.
15const STATUS_ROWS = 3
16const MIN_STATUS_ROWS = 2
17
18export const register: Register = (on, options) => {
19  // `$.state` outlives a reload, so a mod switched off mid-session still has its
20  // last value there: the option decides, not the value.
21  if (options.statusBandEnabled === false) return
22
23  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
24    if (e.props.hasSurvey || MIN_STATUS_ROWS > e.props.maxRows) return next(e)
25
26    const status = await read($, statusBand)
27
28    if (status === null) return next(e)
29
30    const glyphs = options.statusBandAscii === true ? ASCII : UNICODE
31    const isSplit = STATUS_ROWS <= e.props.maxRows
32    // A setup with no figure read yet draws no row, leaving room for the blank one.
33    const rows = isSplit && setupSegments(status, glyphs).length > 0 ? STATUS_ROWS : MIN_STATUS_ROWS
34
35    return statusRows($.ui.resolve(e), status, { hasMargin: rows < e.props.maxRows, isSplit, glyphs })
36  })
37}
38
hooks/status-band/register.tsx 529 lines
1import { atom, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderElement } from 'claude-code'
3
4import type { StatusBand } from '../../types'
5import {
6  connectedServers,
7  enabledPlugins,
8  hookCommands,
9  hooksFileCommands,
10  installPaths,
11  manifestHooks,
12  under,
13} from './count'
14import {
15  contextText,
16  curateText,
17  headlineSegments,
18  levelOf,
19  limitsSegments,
20  mergedSegments,
21  setupSegments,
22  UNICODE,
23} from './format'
24import type { Glyphs, Segment } from './format'
25
26// Layout after the claude-hud status line (github.com/jarrodwatts/claude-hud).
27// The elapsed time and the reset countdowns read in minutes.
28const TICK_MS = 60_000
29const GIT_TIMEOUT_MS = 2000
30const MINUTE_MS = 60_000
31const DEFAULT_CACHE_TTL_MINUTES = 60
32// The dev plugin's session-start hook nudges about a due harness-curate run
33// once a day; the band keeps it in sight, asking the same script.
34const CURATE_PLUGIN = 'dev@kadragon'
35const CURATE_SCRIPT = 'skills/harness-curate/scripts/record_run.py'
36const CURATE_DUE_PREFIX = 'HARNESS-CURATE DUE'
37const CURATE_EVERY_MS = 10 * MINUTE_MS
38const CURATE_TIMEOUT_MS = 10_000
39// The surfaces the engine raises the band above the prompt on.
40const BAND_SURFACES: readonly string[] = ['terminal', 'desktop']
41
42const statusBand = atom({ plugin: 'mods', key: 'statusBand' } as const, null)
43
44// What one load of the module keeps between hooks.
45type Live = {
46  effort: StatusBand['effort']
47  // True from a main-loop step until the next read: that effort is the model's now.
48  isEffortFresh: boolean
49  tick?: { cancel: () => void }
50  asked: number
51  drawn: number
52  // Null once the session ended or the model changed: nothing is cached.
53  cacheExpiresAt?: number | null
54  cacheModel?: string
55  // The counts of what the session is set up with, as last read.
56  setup: Setup
57  // False until this load read or reset them: a reload keeps what is drawn.
58  hasSetup: boolean
59  // Raised by a reset, so a read that started before it is dropped.
60  setupEpoch: number
61  setupRead?: Promise<void>
62  // When the curate check last ran; unset, the next read runs it.
63  curateCheckedAt?: number
64  curateRead?: Promise<void>
65}
66
67type Setup = Pick<StatusBand, 'hooks' | 'skills' | 'mcp' | 'curateDue'>
68
69// The handlers a plugin's default hooks file, its manifest and the files the
70// manifest names add; a file that is not there adds none.
71const pluginHooks = async ($: EngineInterface, root: string): Promise<number> => {
72  const { files, inline } = await $.fs
73    .read(under(root, '.claude-plugin/plugin.json'))
74    .then(manifestHooks)
75    .catch(() => manifestHooks('{}'))
76  const counts = await Promise.all(
77    files.map(file =>
78      $.fs
79        .read(under(root, file))
80        .then(hooksFileCommands)
81        .catch(() => 0),
82    ),
83  )
84
85  return counts.reduce((total, count) => total + count, inline)
86}
87
88// Where the installed-plugins file says each plugin's directory is.
89const readInstallPaths = async ($: EngineInterface): Promise<Record<string, string>> => {
90  const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
91  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
92
93  const claudeDir = configDir ?? (home === undefined ? undefined : under(home, '.claude'))
94
95  if (claudeDir === undefined) throw new Error('no home directory')
96
97  return installPaths(
98    await $.fs.read(under(claudeDir, 'plugins/installed_plugins.json')),
99    await $.session.cwd(),
100  )
101}
102
103// Whether a harness-curate run is due here, judged as the session-start hook
104// judges it: only in a harness repo, by the installed dev plugin's own script.
105const readCurateDue = async ($: EngineInterface): Promise<boolean> => {
106  if (!enabledPlugins(await $.settings.read()).includes(CURATE_PLUGIN)) return false
107
108  const cwd = await $.session.cwd()
109
110  if (!(await $.fs.exists(under(cwd, 'AGENTS.md')))) return false
111
112  const root = (await readInstallPaths($))[CURATE_PLUGIN]
113
114  if (root === undefined) return false
115
116  const args = [under(root, CURATE_SCRIPT), '--check-due', '--project', cwd]
117  const init = { timeoutMs: CURATE_TIMEOUT_MS }
118  // As the hook does: `python3`, else `python` where only that is installed.
119  const { exitCode, stdout } = await $.process
120    .run(['python3', ...args], init)
121    .catch(() => $.process.run(['python', ...args], init))
122
123  return exitCode === 0 && stdout.startsWith(CURATE_DUE_PREFIX)
124}
125
126// The hook handlers in force: the settings' own and every enabled plugin's.
127// The engine lists none, so they are counted off the files that declare them.
128const countHooks = async ($: EngineInterface): Promise<number> => {
129  const settings = await $.settings.read()
130
131  if (settings.disableAllHooks === true) return 0
132
133  if (settings.allowManagedHooksOnly === true) {
134    return hookCommands((await $.settings.read({ source: 'policy' })).hooks)
135  }
136
137  const own = hookCommands(settings.hooks)
138  const enabled = enabledPlugins(settings)
139
140  if (enabled.length === 0) return own
141
142  const paths = await readInstallPaths($)
143  const counts = await Promise.all(
144    enabled.map(id => (paths[id] === undefined ? 0 : pluginHooks($, paths[id]))),
145  )
146
147  return counts.reduce((total, count) => total + count, own)
148}
149
150// The skill listing and the MCP servers as /context counts them, estimated
151// locally: no request is sent.
152const readContext = async ($: EngineInterface): Promise<Pick<StatusBand, 'skills' | 'mcp'>> => {
153  const { context } = await $.session.usage({ breakdown: 'summary' })
154  const breakdown = context.breakdown
155
156  if (breakdown === undefined) return {}
157
158  const skills = breakdown.skills
159
160  return {
161    skills: skills === undefined ? undefined : { count: skills.totalSkills, tokens: skills.tokens },
162    mcp: connectedServers(breakdown.mcpTools),
163  }
164}
165
166// Reads the counts apart from the other figures, which must not wait for the
167// files: one read at a time, and a count that cannot be read keeps the last
168// one this session gave.
169const loadSetup = ($: EngineInterface, live: Live): void => {
170  if (live.setupRead !== undefined) return
171
172  const epoch = live.setupEpoch
173
174  live.setupRead = (async () => {
175    const [hooks, context] = await Promise.all([
176      countHooks($).catch(() => undefined),
177      readContext($).catch(() => undefined),
178    ])
179
180    if (epoch !== live.setupEpoch) return
181
182    const setup = {
183      hooks: hooks ?? live.setup.hooks,
184      skills: context?.skills ?? live.setup.skills,
185      mcp: context?.mcp ?? live.setup.mcp,
186    }
187
188    live.setup = { ...live.setup, ...setup }
189    live.hasSetup = true
190    await update($, statusBand, current => (current === null ? null : { ...current, ...setup }))
191  })()
192    .catch(() => undefined)
193    .finally(() => {
194      live.setupRead = undefined
195      // A reset came while this read ran: the counts are the new session's to read.
196      if (epoch !== live.setupEpoch) loadSetup($, live)
197    })
198}
199
200// The curate check spawns a scan, so it runs apart from the counts and at most
201// once in a while; between runs, or when a run fails, the last answer stands.
202const loadCurate = ($: EngineInterface, live: Live): void => {
203  if (live.curateRead !== undefined) return
204
205  const epoch = live.setupEpoch
206
207  live.curateRead = (async () => {
208    const now = await $.clock.now()
209
210    if (epoch !== live.setupEpoch) return
211    if (live.curateCheckedAt !== undefined && now - live.curateCheckedAt < CURATE_EVERY_MS) return
212
213    live.curateCheckedAt = now
214    const curateDue = await readCurateDue($).catch(() => undefined)
215
216    if (epoch !== live.setupEpoch || curateDue === undefined) return
217
218    live.setup = { ...live.setup, curateDue }
219    live.hasSetup = true
220    await update($, statusBand, current => (current === null ? null : { ...current, curateDue }))
221  })()
222    .catch(() => undefined)
223    .finally(() => {
224      live.curateRead = undefined
225      // A reset came while this read ran: the new session asks again.
226      if (epoch !== live.setupEpoch) loadCurate($, live)
227    })
228}
229
230// The counts were another session's: they are left out until read again.
231const resetSetup = (live: Live): void => {
232  live.setup = {}
233  live.hasSetup = true
234  live.setupEpoch += 1
235  // A run in the last session stamped its record: ask again.
236  live.curateCheckedAt = undefined
237}
238
239// Only a response that read or wrote the prompt cache renews it.
240const isCached = (usage: { cache_read_input_tokens: number; cache_creation_input_tokens: number } | null): boolean =>
241  usage !== null && usage.cache_read_input_tokens + usage.cache_creation_input_tokens > 0
242
243// The band is a convenience: a figure the engine cannot give is left out or
244// kept as last read, and nothing here may fail a hook.
245const refresh = async ($: EngineInterface, live: Live): Promise<void> => {
246  live.asked += 1
247  const order = live.asked
248
249  try {
250    const [model, cwd, usage, turns, now, git] = await Promise.all([
251      $.session.model().catch(() => ''),
252      $.session.cwd().catch(() => ''),
253      $.session.usage().catch(() => null),
254      $.session.turns().catch(() => null),
255      $.clock.now(),
256      $.process
257        .run(['git', 'branch', '--show-current'], { timeoutMs: GIT_TIMEOUT_MS })
258        .catch(() => null),
259    ])
260    // Git answering with no name (no repository, a detached HEAD) is a reading.
261    const branch = git === null ? null : git.exitCode === 0 ? git.stdout.trim() : ''
262
263    // What the write decided, kept for after it: the engine may run the
264    // function again, so it reads `live` and leaves it as it is.
265    const before = { effort: live.effort, isFresh: live.isEffortFresh, cache: live.cacheExpiresAt }
266    let decided: { effort: StatusBand['effort']; isForfeit: boolean } | undefined
267
268    await update($, statusBand, current => {
269      decided = undefined
270
271      // A read that started earlier and ended later must not undo a newer one.
272      if (order < live.drawn) return current
273
274      live.drawn = order
275      const name = model === '' ? (current?.model ?? '') : model
276      let effort = before.effort
277
278      if (before.isFresh) {
279        // The step that reported it ran under this model.
280      } else if (current !== null && current.model !== name) {
281        // The effort was the last model's; the next step reports this one's.
282        effort = undefined
283      } else if (effort === undefined) {
284        // A reload starts the module over; the session's value is still good.
285        effort = current?.effort
286      }
287
288      // The cache was the model's that made it: a switch forfeits it.
289      const cacheModel = live.cacheModel ?? current?.cacheModel
290      const isForfeit = cacheModel !== undefined && name !== '' && cacheModel !== name
291      const isCacheGone = isForfeit || live.cacheExpiresAt === null
292
293      decided = { effort, isForfeit }
294
295      return {
296        model: name,
297        effort,
298        cwd: cwd === '' ? (current?.cwd ?? '') : cwd,
299        branch: branch === null ? current?.branch : branch === '' ? undefined : branch,
300        startedAt: usage?.startedAt ?? current?.startedAt,
301        now,
302        // Before the first prompt nothing is in the window: that 0 is a reading.
303        contextPercent:
304          usage === null
305            ? current?.contextPercent
306            : (usage.context.percent ?? (turns === 0 ? 0 : undefined)),
307        rateLimits: usage?.rateLimits ?? current?.rateLimits ?? [],
308        cacheExpiresAt: isCacheGone
309          ? undefined
310          : (live.cacheExpiresAt ?? current?.cacheExpiresAt),
311        cacheModel: isCacheGone ? undefined : cacheModel,
312        hooks: live.hasSetup ? live.setup.hooks : current?.hooks,
313        skills: live.hasSetup ? live.setup.skills : current?.skills,
314        mcp: live.hasSetup ? live.setup.mcp : current?.mcp,
315        curateDue: live.hasSetup ? live.setup.curateDue : current?.curateDue,
316      }
317    })
318
319    if (decided !== undefined) {
320      // A step that reported meanwhile is newer than what this read decided.
321      if (live.effort === before.effort) live.effort = decided.effort
322      if (before.isFresh) live.isEffortFresh = false
323
324      if (decided.isForfeit && live.cacheExpiresAt === before.cache) {
325        live.cacheExpiresAt = null
326        live.cacheModel = undefined
327      }
328    }
329  } catch {
330    // Keeps what was last drawn.
331  }
332}
333
334// Reads the figures and keeps the minute tick, where a surface draws the band.
335const watch = async ($: EngineInterface, live: Live): Promise<void> => {
336  try {
337    const surfaces = await $.session.surfaces()
338
339    if (!surfaces.some(surface => BAND_SURFACES.includes(surface))) {
340      live.tick?.cancel()
341      live.tick = undefined
342
343      return
344    }
345
346    live.tick ??= $.clock.every(TICK_MS, () => void refresh($, live))
347    loadSetup($, live)
348    loadCurate($, live)
349    await refresh($, live)
350  } catch {
351    // Nothing to draw on.
352  }
353}
354
355export const register: Register = (on, options) => {
356  if (options.statusBandEnabled === false) return
357
358  const ttl = options.statusBandCacheTtlMinutes
359  const cacheTtlMs =
360    (typeof ttl === 'number' && ttl > 0 ? ttl : DEFAULT_CACHE_TTL_MINUTES) * MINUTE_MS
361  const live: Live = {
362    effort: undefined,
363    isEffortFresh: false,
364    asked: 0,
365    drawn: 0,
366    setup: {},
367    hasSetup: false,
368    setupEpoch: 0,
369  }
370
371  // Neither hook waits for the read: a slow git must not hold the session.
372  on('session.start', async ($, e, next) => {
373    const result = await next(e)
374
375    resetSetup(live)
376    void watch($, live)
377
378    return result
379  })
380
381  // Raised after each main-thread turn too, which may have switched the branch;
382  // a surface that attached after the start gets its tick here.
383  on('session.measure', ($, e, next) => {
384    void watch($, live)
385
386    return next(e)
387  })
388
389  // The band follows the surfaces: one that attaches gets it at once, and the
390  // tick stops when the last one that draws it leaves.
391  on('session.attach', async ($, e, next) => {
392    const result = await next(e)
393
394    void watch($, live)
395
396    return result
397  })
398
399  on('session.detach', async ($, e, next) => {
400    const result = await next(e)
401
402    void watch($, live)
403
404    return result
405  })
406
407  // A `/clear` empties the window and starts the timer over; no measure follows it.
408  // Whatever ends the session, the conversation that follows has its own cache
409  // and its own counts, and where the process goes on the band shows it at once.
410  on('session.end', async ($, e, next) => {
411    const result = await next(e)
412
413    live.cacheExpiresAt = null
414    live.cacheModel = undefined
415    resetSetup(live)
416    void watch($, live)
417
418    return result
419  })
420
421  // The request is passed on untouched: only its effort is read, and a
422  // response of the main loop renews the prompt cache from when it was sent.
423  on('turn.step', async function* ($, e, next) {
424    if (e.agentId === undefined) live.isEffortFresh = true
425
426    if (e.agentId === undefined && e.effort !== live.effort) {
427      const effort = e.effort
428
429      live.effort = effort
430      await update($, statusBand, current =>
431        current === null ? null : { ...current, effort },
432      ).catch(() => undefined)
433    }
434
435    const sentAt = e.agentId === undefined ? $.clock.now().catch(() => undefined) : undefined
436    const result = yield* next(e)
437
438    // The step does not wait for the band: the countdown is written behind it.
439    if (sentAt !== undefined && isCached(result.usage)) {
440      void sentAt
441        .then(async at => {
442          if (at === undefined) return
443
444          const cacheExpiresAt = at + cacheTtlMs
445          const model = await $.session.model().catch(() => '')
446          const cacheModel = model === '' ? undefined : model
447
448          live.cacheExpiresAt = cacheExpiresAt
449          live.cacheModel = cacheModel
450          await update($, statusBand, current =>
451            current === null ? null : { ...current, cacheExpiresAt, cacheModel },
452          )
453        })
454        .catch(() => undefined)
455    }
456
457    return result
458  })
459}
460
461type BandElements = Pick<Elements['terminal'], 'Box' | 'Text'>
462
463const runs = ({ Text }: BandElements, segments: Segment[]): RenderElement[] =>
464  segments.map((segment, index) => (
465    <Text
466      key={`run-${index}`}
467      color={segment.color}
468      bold={segment.isBold}
469      dimColor={segment.isDim}
470    >
471      {segment.text}
472    </Text>
473  ))
474
475// This mod's rows of the band above the prompt, under a blank row that keeps
476// them off the line above where the band has a row to spare. The setup gets a
477// row of its own where `isSplit`, else it rides on the headline; `glyphs` is
478// the set the rows draw beyond plain letters. `hooks/band.tsx`
479// draws them: the engine takes one band hook per plugin, and `$` stays in that
480// hook's file.
481export const statusRows = (
482  elements: BandElements,
483  status: StatusBand,
484  {
485    hasMargin,
486    isSplit,
487    glyphs = UNICODE,
488  }: { hasMargin: boolean; isSplit: boolean; glyphs?: Glyphs },
489): RenderElement => {
490  const { Box, Text } = elements
491  const setup = isSplit ? setupSegments(status, glyphs) : []
492  const context = contextText(status, glyphs)
493  const limits = limitsSegments(status, glyphs)
494  const curate = curateText(status)
495
496  return (
497    <Box key="status-band" flexDirection="column" marginTop={hasMargin ? 1 : 0}>
498      <Text wrap="truncate-end">
499        {runs(
500          elements,
501          isSplit ? headlineSegments(status, glyphs) : mergedSegments(status, glyphs),
502        )}
503      </Text>
504      {setup.length === 0 ? null : <Text wrap="truncate-end">{runs(elements, setup)}</Text>}
505      {context === '' && limits.length === 0 && curate === '' ? null : (
506        <Box>
507          {context === '' ? null : <Text color={levelOf(status.contextPercent)}>{context}</Text>}
508          {limits.length === 0 ? null : (
509            <Text wrap="truncate-end">
510              {context === '' ? null : <Text dimColor>{glyphs.separator}</Text>}
511              {runs(elements, limits)}
512            </Text>
513          )}
514          {curate === '' ? null : (
515            <Box>
516              {context === '' && limits.length === 0 ? null : (
517                <Text dimColor>{glyphs.separator}</Text>
518              )}
519              <Text color="warning" wrap="truncate-end">
520                {curate}
521              </Text>
522            </Box>
523          )}
524        </Box>
525      )}
526    </Box>
527  )
528}
529
hooks/status-band/format.ts 224 lines
1// Pure status text: no engine types, so it runs and tests without `$`.
2
3import type { StatusBand } from '../../types'
4
5const BAR_CELLS = 10
6// A longer branch name is cut, so it does not push the figures after it off the row.
7const BRANCH_CELLS = 24
8const MINUTE_MS = 60_000
9const HOUR_MS = 60 * MINUTE_MS
10const DAY_MS = 24 * HOUR_MS
11
12// What the rows draw beyond plain letters. Some terminals (Wave on Windows)
13// advance a box-drawing, block or geometric glyph by a cell other than the one
14// the engine counts, and a redraw then leaves cells behind: `ASCII` draws none.
15export type Glyphs = {
16  separator: string
17  effort: Record<string, string>
18  filled: string
19  empty: string
20  ellipsis: string
21}
22
23export const UNICODE: Glyphs = {
24  separator: ' │ ',
25  effort: { low: '○', medium: '◔', high: '◑', xhigh: '◕', max: '●' },
26  filled: '█',
27  empty: '░',
28  ellipsis: '…',
29}
30
31export const ASCII: Glyphs = {
32  separator: ' | ',
33  effort: {},
34  filled: '#',
35  empty: '-',
36  ellipsis: '~',
37}
38// The windows the band names, in the order it draws them.
39const WINDOWS: readonly (readonly [kind: string, label: string])[] = [
40  ['five_hour', '5h'],
41  ['seven_day', '7d'],
42]
43
44export type Level = 'success' | 'warning' | 'error'
45
46// One run of a row drawn in its own color; `color` is a theme key.
47export type Segment = { text: string; color?: string; isBold?: boolean; isDim?: boolean }
48
49// `claude-opus-5-5` reads as `Opus 5.5`; a name of any other shape is kept.
50export const modelLabel = (model: string): string => {
51  const match = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[[^\]]+\])?$/.exec(model.trim())
52
53  if (match === null) return model.trim()
54
55  const [, family = '', major = '', minor, suffix] = match
56  const version = minor === undefined ? major : `${major}.${minor}`
57
58  return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${version}${suffix ?? ''}`
59}
60
61export const clampPercent = (percent: number | undefined): number =>
62  percent === undefined || Number.isNaN(percent) ? 0 : Math.min(100, Math.max(0, percent))
63
64export const bar = (percent: number | undefined, glyphs: Glyphs = UNICODE): string => {
65  const filled = Math.round((clampPercent(percent) / 100) * BAR_CELLS)
66
67  return glyphs.filled.repeat(filled) + glyphs.empty.repeat(BAR_CELLS - filled)
68}
69
70export const levelOf = (percent: number | undefined): Level => {
71  const used = clampPercent(percent)
72
73  if (used >= 90) return 'error'
74
75  return used >= 70 ? 'warning' : 'success'
76}
77
78// The two largest units, so a week reads `6d 7h` and an hour `2h 4m`.
79export const duration = (ms: number): string => {
80  if (ms < MINUTE_MS) return '<1m'
81
82  const days = Math.floor(ms / DAY_MS)
83  const hours = Math.floor((ms % DAY_MS) / HOUR_MS)
84  const minutes = Math.floor((ms % HOUR_MS) / MINUTE_MS)
85
86  if (days > 0) return `${days}d ${hours}h`
87
88  return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`
89}
90
91const modelSegment = (status: StatusBand, glyphs: Glyphs): string => {
92  const name = modelLabel(status.model)
93
94  if (status.effort === undefined) return `[${name}]`
95
96  const glyph = glyphs.effort[String(status.effort)]
97
98  return glyph === undefined ? `[${name} ${status.effort}]` : `[${name} ${glyph} ${status.effort}]`
99}
100
101const basename = (path: string): string => path.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? ''
102
103const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`
104
105// `4200` reads as `4.2k`; under a thousand the count is kept.
106export const tokens = (count: number): string =>
107  count < 1000 ? String(Math.round(count)) : `${(count / 1000).toFixed(1)}k`
108
109// What is left of the prompt cache, counted from the last response.
110export const cacheText = (status: StatusBand): string => {
111  if (status.cacheExpiresAt === undefined) return ''
112
113  const left = status.cacheExpiresAt - status.now
114
115  if (left <= 0) return 'cache expired'
116
117  // Whole minutes alone, so a full hour reads `60m`, not `1h 0m`.
118  return left < MINUTE_MS ? 'cache <1m' : `cache ${Math.floor(left / MINUTE_MS)}m`
119}
120
121const joined = (groups: Segment[][], separator: string): Segment[] =>
122  groups
123    .filter(group => group.length > 0)
124    .flatMap((group, index) =>
125      index === 0 ? group : [{ text: separator, isDim: true }, ...group],
126    )
127
128// A figure the engine has no reading for is left out, with its separator.
129export const headlineSegments = (status: StatusBand, glyphs: Glyphs = UNICODE): Segment[] => {
130  const dir = basename(status.cwd)
131  const place: Segment[] = dir === '' ? [] : [{ text: dir, color: 'suggestion', isBold: true }]
132
133  if (status.branch !== undefined) {
134    const branch =
135      status.branch.length > BRANCH_CELLS
136        ? `${status.branch.slice(0, BRANCH_CELLS - 1)}${glyphs.ellipsis}`
137        : status.branch
138
139    place.push({ text: `${dir === '' ? '' : ' '}git:(${branch})`, color: 'autoAccept' })
140  }
141
142  return joined(
143    [
144      status.model === '' ? [] : [{ text: modelSegment(status, glyphs), color: 'claude', isBold: true }],
145      place,
146      status.startedAt === undefined
147        ? []
148        : [{ text: `up ${duration(status.now - status.startedAt)}` }],
149    ],
150    glyphs.separator,
151  )
152}
153
154// The cache countdown and what the session is set up with, on a row of their own.
155export const setupSegments = (status: StatusBand, glyphs: Glyphs = UNICODE): Segment[] => {
156  const cache = cacheText(status)
157
158  return joined(
159    [
160      cache === ''
161        ? []
162        : [{ text: cache, color: cache === 'cache expired' ? 'warning' : 'planMode' }],
163      status.hooks === undefined
164        ? []
165        : [{ text: plural(status.hooks, 'hook'), color: 'permission' }],
166      status.skills === undefined
167        ? []
168        : [
169            { text: plural(status.skills.count, 'skill'), color: 'remember' },
170            { text: ` (${tokens(status.skills.tokens)})`, isDim: true },
171          ],
172      // No server is no figure: the row keeps its room.
173      status.mcp === undefined || status.mcp === 0
174        ? []
175        : [{ text: `${status.mcp} mcp`, color: 'ide' }],
176    ],
177    glyphs.separator,
178  )
179}
180
181// Where the band has no row to spare, the setup rides on the headline.
182export const mergedSegments = (status: StatusBand, glyphs: Glyphs = UNICODE): Segment[] =>
183  joined([headlineSegments(status, glyphs), setupSegments(status, glyphs)], glyphs.separator)
184
185const textOf = (segments: Segment[]): string => segments.map(segment => segment.text).join('')
186
187export const headline = (status: StatusBand): string => textOf(headlineSegments(status))
188
189export const setupText = (status: StatusBand): string => textOf(setupSegments(status))
190
191// A fill the engine has no reading for is left out, never drawn as 0%.
192export const contextText = (status: StatusBand, glyphs: Glyphs = UNICODE): string =>
193  status.contextPercent === undefined
194    ? ''
195    : `Context ${bar(status.contextPercent, glyphs)} ${Math.round(clampPercent(status.contextPercent))}%`
196
197// A window the engine has no reading for is left out, never drawn as 0%.
198export const limitsSegments = (status: StatusBand, glyphs: Glyphs = UNICODE): Segment[] =>
199  joined(
200    WINDOWS.map(([kind, label]): Segment[] => {
201      const limit = status.rateLimits.find(candidate => candidate.kind === kind)
202
203      if (limit === undefined) return []
204
205      const resetsAt = limit.resetsAt === undefined ? Number.NaN : Date.parse(limit.resetsAt)
206      const left = resetsAt - status.now
207      const used: Segment[] = [
208        { text: `${label}: `, isDim: true },
209        { text: `${Math.round(limit.percentUsed)}%`, color: levelOf(limit.percentUsed) },
210      ]
211
212      return Number.isNaN(left) || left <= 0
213        ? used
214        : [...used, { text: ` (${duration(left)})`, isDim: true }]
215    }),
216    glyphs.separator,
217  )
218
219// A harness-curate run the dev plugin judges due; nothing otherwise.
220export const curateText = (status: StatusBand): string =>
221  status.curateDue === true ? 'harness-curate due' : ''
222
223export const limitsText = (status: StatusBand): string => textOf(limitsSegments(status))
224
hooks/status-band/count.ts 108 lines
1// Pure hook counting: no engine types, so it runs and tests without `$`.
2
3const DEFAULT_HOOKS_FILE = 'hooks/hooks.json'
4
5const isRecord = (value: unknown): value is Record<string, unknown> =>
6  typeof value === 'object' && value !== null && !Array.isArray(value)
7
8// The handlers under a settings.json `hooks` value, of whatever type: a
9// matcher that runs two counts as two.
10export const hookCommands = (hooks: unknown): number => {
11  if (!isRecord(hooks)) return 0
12
13  return Object.values(hooks).reduce<number>((total, groups) => {
14    if (!Array.isArray(groups)) return total
15
16    return groups.reduce<number>(
17      (sum, group) => sum + (isRecord(group) && Array.isArray(group.hooks) ? group.hooks.length : 0),
18      total,
19    )
20  }, 0)
21}
22
23// A hooks file wraps the same value in `hooks`; a function-hooks file has none.
24export const hooksFileCommands = (text: string): number => {
25  const file: unknown = JSON.parse(text)
26
27  return isRecord(file) ? hookCommands(file.hooks) : 0
28}
29
30// The plugins the settings switch on, by their `<name>@<marketplace>` id.
31export const enabledPlugins = (settings: Record<string, unknown>): string[] =>
32  isRecord(settings.enabledPlugins)
33    ? Object.entries(settings.enabledPlugins).flatMap(([id, isOn]) => (isOn === true ? [id] : []))
34    : []
35
36// How much of `cwd` a project path covers, in characters; 0 when it is not
37// that directory or one beneath it. Either separator ends a segment.
38const covered = (projectPath: unknown, cwd: string): number => {
39  if (typeof projectPath !== 'string') return 0
40
41  const root = projectPath.replace(/[\\/]+$/, '')
42  const isWithin = cwd === root || (cwd.startsWith(root) && /[\\/]/.test(cwd.charAt(root.length)))
43
44  return isWithin ? root.length + 1 : 0
45}
46
47// Where the installed-plugins file says each plugin's directory is. A plugin
48// installed more than once is read from the install made for the nearest
49// project around `cwd`, else the user's own, else the first listed.
50export const installPaths = (text: string, cwd: string): Record<string, string> => {
51  const file: unknown = JSON.parse(text)
52  const plugins = isRecord(file) && isRecord(file.plugins) ? file.plugins : {}
53
54  return Object.fromEntries(
55    Object.entries(plugins).flatMap(([id, listed]) => {
56      const installs = (Array.isArray(listed) ? listed : []).filter(
57        (install): install is Record<string, unknown> & { installPath: string } =>
58          isRecord(install) && typeof install.installPath === 'string',
59      )
60      const nearest = installs.reduce<(typeof installs)[number] | undefined>(
61        (best, candidate) =>
62          covered(candidate.projectPath, cwd) > covered(best?.projectPath, cwd) ? candidate : best,
63        undefined,
64      )
65      const install =
66        nearest ?? installs.find(candidate => candidate.projectPath === undefined) ?? installs[0]
67
68      return install === undefined ? [] : [[id, install.installPath]]
69    }),
70  )
71}
72
73// The tools a server that needs a sign-in offers in place of its own. Read off
74// the name's end: the prefix carries the server's name normalized
75// (`mcp__claude_ai_Asana__`), not as /mcp lists it.
76const SIGN_IN_TOOL = /__(?:authenticate|complete_authentication)$/
77
78// The MCP servers connected, by the tools the context carries: a server counts
79// once, however many tools it has, and not at all while it offers only its
80// sign-in. A connected server whose only tools bear those names reads as not.
81export const connectedServers = (tools: readonly { name: string; serverName: string }[]): number =>
82  new Set(tools.filter(tool => !SIGN_IN_TOOL.test(tool.name)).map(tool => tool.serverName)).size
83
84const relative = (path: string): string => path.replace(/^\.\//, '')
85
86// `path` beneath `base`, in the separator `base` is written with: a Windows
87// home or install path keeps its backslashes all the way down.
88export const under = (base: string, path: string): string =>
89  base.includes('\\') && !base.includes('/')
90    ? `${base}\\${path.replace(/\//g, '\\')}`
91    : `${base}/${path}`
92
93// What a plugin's manifest adds to its default hooks file: the files it names,
94// and the hooks it carries inline. The engine loads both together.
95export const manifestHooks = (text: string): { files: string[]; inline: number } => {
96  const manifest: unknown = JSON.parse(text)
97  const named = isRecord(manifest) ? manifest.hooks : undefined
98  const files = new Set([DEFAULT_HOOKS_FILE])
99  let inline = 0
100
101  for (const entry of Array.isArray(named) ? named : [named]) {
102    if (typeof entry === 'string') files.add(relative(entry))
103    else if (isRecord(entry)) inline += hookCommands(isRecord(entry.hooks) ? entry.hooks : entry)
104  }
105
106  return { files: [...files], inline }
107}
108
types/index.d.ts 27 lines
1export type StatusBand = {
2  model: string
3  effort?: string | number
4  cwd: string
5  branch?: string
6  startedAt?: number
7  now: number
8  contextPercent?: number
9  rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[]
10  // When the prompt cache lapses unless a response renews it first.
11  cacheExpiresAt?: number
12  // The model that cache was made under: a switch forfeits it.
13  cacheModel?: string
14  hooks?: number
15  skills?: { count: number; tokens: number }
16  // The MCP servers connected: one that needs a sign-in is not counted.
17  mcp?: number
18  // A harness-curate run is due in this repo, as the dev plugin judges it.
19  curateDue?: boolean
20}
21
22declare module 'claude-code' {
23  interface PluginState {
24    mods: { statusBand: StatusBand | null }
25  }
26}
27