SLOPSHOPPER

cache-clock

Band line showing whether Claude's prompt cache is still warm. TTL, expiry, and hit ratio come from Claude Code's prompt_cache when /cache-clock setup is…

bandcommandtoastprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cache-clock
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /cache-clock ⎿ cache-clock: cache-clock: on ⎿ cache-clock: Cache: no cache activity yet ⎿ cache-clock: Session reads 0, writes 0, fresh input 0 (subagents included) ⎿ cache-clock: Saved ≈ $0.00 by cache reads vs uncached input ⎿ cache-clock: Dollar figures are estimates from list prices. A "?" on the band means the TTL is assumed, not reported by Cla ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

lchase

Lawrence Chase's Claude Code marketplace: code review, diagram, test-evidence and software factory skills, plus a set of small Claude Code mods that add band lines and panes to the terminal UI.

/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase
/plugin install test-drive@lchase
/plugin install cache-clock@lchase
/plugin install usage-gauge@lchase
/plugin install auto-handoff@lchase
/plugin install agent-watch@lchase
/plugin install recording-mode@lchase
/plugin install factory@lchase

Each plugin is independent; install only what you want. @lchase is the marketplace name (from .claude-plugin/marketplace.json), not the GitHub slug.

Updating

New versions ship whenever the version string in a plugin's manifest changes. Claude Code refreshes marketplaces in the background by default, so you normally pick up updates without doing anything. To pull them right now:

/plugin marketplace update lchase      # refresh this marketplace's manifest
/plugin update smart-review@lchase     # apply a pending update to one plugin
/plugin update tldraw@lchase

/plugin marketplace update (no name) refreshes every marketplace. From a shell: claude plugin marketplace update lchase and claude plugin update <plugin>@lchase.

Reinstalling

If a plugin gets into a bad state (stale cached script, half-applied update), do a clean reinstall:

/plugin uninstall tldraw
/plugin marketplace update lchase
/plugin install tldraw@lchase

Nuclear option, re-register the whole marketplace:

/plugin marketplace remove lchase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

Migrating from the old layout

Before this repo became a multi-plugin marketplace it published one plugin from the repo root under a marketplace named chase. If you installed it back then, clear the old registration first:

/plugin uninstall smart-review
/plugin uninstall tldraw            # only if you installed the short-lived tldraw@chase
/plugin marketplace remove chase
/plugin marketplace add lchase/coding-agent-plugins
/plugin install smart-review@lchase
/plugin install tldraw@lchase

The tldraw skill's command also changed: /tldraw:tldraw → /tldraw:diagram.

PluginWhat it doesSkills / commandsHarnesses
smart-reviewEnsemble code review: six specialized lenses over a diff, merged into one deduplicated, severity-ranked verdict/smart-review:{review,min,max,add-pr-review,review-pr-comments} + auto-triggerClaude Code, Cursor, Codex, Gemini CLI, any AGENTS.md agent
tldrawNatural-language description → editable tldraw document (.tldr) + rendered PNG/SVG/tldraw:diagram + auto-triggerClaude Code only (needs Node + npx)
test-driveBefore/after evidence of a UI or API change: record the app before you edit, replay the same scripted scenario after, with a deterministic verdict/test-drive:{baseline,compare} + auto-triggerClaude Code only (needs Node; UI also needs Playwright and ffmpeg)
cache-clockMod: band line showing whether the prompt cache is warm. TTL, expiry, hit ratio, and re-cache size come from Claude Code when the status-line bridge is installed; otherwise the countdown is a marked estimateCompact button (warm only), /cache-clockClaude Code only
usage-gaugeMod: band line with plan usage windows (5-hour, weekly, spend limit), reset times, pace warning, session cost on API billing, threshold toasts/usage-gauge (detail pane)Claude Code only
auto-handoffMod: band line showing how full the chat is; saves a HANDOFF.md at a threshold (auto or on request), then clear and continue or resume in a new session/auto-handoffClaude Code only
agent-watchMod: band line showing who is doing the work this turn (main chat, helper agents, models, tasks, status, skills), plus a pane with per-agent blocks, per-model totals, timeline/agent-watchClaude Code only
recording-modeMod: screen-record without leaking secrets; tells the model to keep keys, emails, private words off screen and masks them in the transcript display only, red REC chip/recClaude Code only
factorySoftware factory: a feature or bug goes through spec-writer, builder, four parallel reviewers and an approver on its own branch, then merges to main or waits for you; live dashboard/factory <input>, /factory {setup,next,approve,rework,serve}Claude Code only (dashboard needs Bun)

smart-review

An ensemble code review: several specialized lenses, one merged verdict, not another pile of comments.

Most code review, human or AI, is one reviewer making a single pass and leaving a list of comments. This runs six specialized lenses instead (spec-conformance, correctness, security, performance, design, and tests), then merges the results into one verdict: duplicates collapsed, findings that several lenses independently raise weighted up, conflicting advice reconciled, severity rolled up, structural problems first, nits capped. The merge is the point. An ensemble without it is just louder, and a longer checklist handed to one reviewer only dilutes its attention and repeats its own misses.

Two modes: a fast single pass (min) for tight loops, and an orchestrated ensemble (max) for pre-merge review. Auto-routing picks between them by change size and sensitivity.

The skill lives in plugins/smart-review/skills/smart-review/ as harness-neutral markdown. Each harness gets a thin manifest pointing at that same directory, so no skill content is copied or forked.

HarnessInstallminmaxSlash commands / auto-trigger
Claude Code/plugin marketplace add lchase/coding-agent-plugins then /plugin install smart-review@lchase✅✅ isolated parallel subagents✅
Cursorpoint Cursor at plugins/smart-review/.cursor-plugin/✅✅ sequential ensemblevia session-start hook
Codexplugins/smart-review/.codex-plugin/ manifest✅✅ sequential ensembleno
Gemini CLIgemini extensions install https://github.com/lchase/coding-agent-plugins (reads root gemini-extension.json)✅✅ sequential ensemblevia GEMINI.md
Any AGENTS.md agentreads root AGENTS.md✅✅ sequential ensembleno

max's isolated parallel subagents are a Claude Code capability. A model panel (plugins/smart-review/skills/smart-review/references/ensemble.md, off by default) rides on top when the harness can route more than one model. Otherwise max is single-model. Elsewhere max runs the same spec-gate, six lenses, and merge as a disciplined sequential walk. Design and internals: plugins/smart-review/SMART-REVIEW.md.

Claude Code slash commands:

  • /smart-review:review: auto (routes to min or max by size + sensitivity)
  • /smart-review:min: fast single-pass review
  • /smart-review:max: orchestrated ensemble review
  • /smart-review:add-pr-review <PR number or URL>: reviews a GitHub PR and, after you confirm what to publish, posts the findings as PR comments
  • /smart-review:review-pr-comments <PR number or URL>: triages a PR's existing unresolved review comments, fixes or explains each after your approval, replies, and resolves the thread

The skill also triggers automatically when you ask Claude to review a diff, PR, or branch.


tldraw

Turn a described diagram (flowchart, architecture / system diagram, process map, decision tree, state machine) into two artifacts: an editable .tldr document (opens at tldraw.com or in the tldraw editor) and a rendered PNG/SVG for docs and PRs.

Claude writes a {nodes, edges} spec from your description; a bundled Node script does a simple layered auto-layout, emits the .tldr, and renders images by loading it into a headless-Chromium tldraw instance via @kitschpatrol/tldraw-cli (first run downloads Chromium, ~1 min, cached).

/plugin install tldraw@lchase

Claude Code only. Skill: /tldraw:diagram (also auto-triggers on "draw this diagram", "diagram this flow", "make a tldraw of…"). Details: plugins/tldraw/skills/diagram/SKILL.md.


test-drive

A test drive is an e2e test that happens to produce video, and the "before" is part of the process rather than something reconstructed later. Run /test-drive:baseline before you edit: it writes a short browser scenario and records the app as it stands. Make the change, then run /test-drive:compare: it replays the identical scenario with Playwright and composes a labeled side-by-side MP4. The pass/warn/fail verdict comes from the scenario's assertions, not from reading the video.

Backend changes work the same way with "kind": "api": the scenario is a list of HTTP steps (method, path, body, expected status, JSON fields, and server-log lines to expect or avoid). There is nothing to screen-record, so each step captures the request, the response, and the server log lines it produced, and compare writes a before/after report.md instead of a video. Secrets are redacted from the stored transcript (best effort, extendable per scenario with redact), and the finished report is scanned and flagged if anything still looks secret.

/plugin install test-drive@lchase

Claude Code only. UI scenarios need ffmpeg and Playwright in the repo under test; API scenarios need only Node 18+. Only the working tree is ever run, so there is no second checkout to boot. Details: baseline and compare.


Claude Code mods

Five small plugins that change Claude Code's own interface instead of adding a task skill. Each draws a band line above the prompt (some add a side pane or slash command), is independent of the others, and works on Claude Code only.

  • cache-clock: is the prompt cache still warm? After /cache-clock setup, the countdown, TTL, hit ratio, re-cache size, and last miss cause come from Claude Code's own prompt_cache (v2.1.251+). Without that, the band uses your promptCacheTtl or cache environment variables, and only then a fallback (cacheMinutes, default 5) marked with ?. Compact is offered only while the cache is warm. Dollar figures stay hand-kept list-price estimates.
  • usage-gauge: plan usage windows (5-hour, weekly, spend limit) with reset times and a pace warning; session cost on API billing; threshold toasts. /usage-gauge opens a detail pane.
  • auto-handoff: watches context fill and saves a HANDOFF.md at a threshold (automatically or on request), then clears and continues, or resumes in a new session. /auto-handoff.
  • agent-watch: who is doing the work this turn: main chat, helper agents, models, tasks, status, skills. /agent-watch opens a pane with per-agent blocks, per-model totals, and a timeline.
  • recording-mode: for screen recordings. Tells the model to keep keys, emails, and private words off screen and masks them in the transcript display only (the underlying transcript is untouched). Red REC chip, /rec to toggle.
/plugin install cache-clock@lchase    # or usage-gauge, auto-handoff, agent-watch, recording-mode

cache-clock and the status line

Claude Code tells a status-line script whether the prompt cache is warm, when it expires, and the session hit ratio (prompt_cache on the status-line JSON, v2.1.251 or later). A plugin cannot register a status line, and the mods API does not include those fields, so cache-clock reads them through a small bridge.

In Claude Code, run:

/cache-clock setup

That edits your user settings (~/.claude/settings.json, or $CLAUDE_CONFIG_DIR/settings.json when that variable is set). It saves whatever statusLine was there and points statusLine at cache-clock/bridge.mjs, which still runs your previous status line and writes Claude Code's prompt_cache for the band to read. /cache-clock remove puts the previous value back. node must be on PATH. Setup refuses to edit a status line that comes from managed settings, --settings, or a project or local settings file.

The same edit by hand, when you have no status line yet:

{
  "statusLine": {
    "type": "command",
    "command": "node ~/.claude/cache-clock/bridge.mjs"
  }
}

Run /cache-clock setup once so the script is copied into that folder. After the next reply the band's TTL and expiry are Claude Code's figures, not a guess. The band redraws every 30 seconds from the last expires_at. Claude Code also re-runs the status line on its own events, and when a warm cache reaches expires_at.

Until the bridge is installed, the band still works. It follows this order: prompt_cache if the bridge has written it, then FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting, ENABLE_PROMPT_CACHING_1H, then the cacheMinutes option (5 or 60, default 5). Only that last step is marked with ?. A subscription within plan usage is often 60 minutes and an API key, cloud provider, or usage-credit session is often

  1. The option cannot see a mid-session change; the bridge can.

/cache-clock status names which of those sources the band is using.


factory

A small, visual software factory. /factory <input> takes a feature or bug as text, a path to a requirements .md, an issue key or URL, or a GitHub issue, and runs it through a fixed loop: spec-writer writes a spec with testable acceptance criteria, builder implements it in its own git worktree (via the Orca CLI when present, so .env and setup hooks come along, else plain git worktree), four reviewers (security, ux, ui, code) run in parallel and each writes a VERDICT: PASS | CHANGES file, the builder is resumed while any review says CHANGES (max two rounds), then an approver writes APPROVE or ESCALATE. APPROVE merges to main locally; ESCALATE parks the job as needs-human.

/plugin install factory@lchase

Then, in a repo:

/factory setup                          # once per repo: profiles it into .factory/repo.md, review that file
/factory <text | path.md | KEY-123 | #123>
/factory next                           # first unchecked item in .factory/backlog.md
/factory approve <job-id>               # merge a needs-human job
/factory rework <job-id> <note>         # send it back to the builder with your note
/factory serve                          # live board at http://localhost:8765 (needs Bun)

Nothing repo-specific is baked in: commands, conventions, commit rules, issue tracker and the approver's never-auto-merge list all come from .factory/repo.md, which /factory setup drafts and you edit. Job state is .factory/jobs/<id>/ (gitignored), one folder of markdown per job, so several sessions can run jobs at once and the dashboard shows them all.

Claude Code only. Dashboard needs Bun. Full guide, including what happens when a job stops for you: plugins/factory/README.md.


Token-savings benchmark

benchmarks/token-savings/ compares stock Claude Code with plugins and settings that claim to cut tokens or cost. It is not a marketplace plugin. Click 8.5.0 is fetched at a pinned commit when you run it. The full matrix calls the Anthropic API and has a hard ceiling of $600 at the default per-session cap. Read the benchmark README before you run it. ./benchmarks/token-savings/check.sh is the offline check and does not spend API money.

Repo layout

.claude-plugin/marketplace.json   # the "lchase" marketplace: 9 plugin entries
AGENTS.md                         # repo-level agent pointer (→ smart-review)
gemini-extension.json + GEMINI.md # Gemini CLI installs the repo as an extension (→ smart-review)

plugins/smart-review/             # plugin 1, multi-harness code review
  .claude-plugin/plugin.json
  skills/smart-review/            # the harness-neutral core (SKILL.md + references/)
  agents/ commands/ hooks/        # Claude Code packaging
  .cursor-plugin/ .codex-plugin/  # thin per-harness manifests
  scripts/                        # validate-adapters.sh, bump-version.sh
  evals/                          # dev-only eval kit (not shipped to installers)
  SMART-REVIEW.md                 # design writeup

plugins/tldraw/                   # plugin 2, Claude Code only
  .claude-plugin/plugin.json
  skills/diagram/                 # SKILL.md + scripts/build-tldr.mjs + references/

plugins/test-drive/               # plugin 3, Claude Code only
  .claude-plugin/plugin.json
  skills/{baseline,compare}/      # SKILL.md each
  scripts/{lib.mjs,record.mjs,record-api.mjs,redact.mjs,verdict.mjs,compose.sh,report.mjs}   # shared by both skills
  references/                     # UI and API scenario schemas + examples

plugins/factory/                  # plugin 4, Claude Code only
  .claude-plugin/plugin.json
  skills/factory/SKILL.md         # the orchestrator loop, commands, setup, job.json and repo.md schemas
  agents/                         # spec-writer, builder, review-{security,ux,ui,code}, approver, repo-profiler
  dashboard/                      # dashboard.html + serve.ts (Bun) + example/ dummy jobs

plugins/{cache-clock,usage-gauge,auto-handoff,agent-watch,recording-mode}/   # plugins 5-9, Claude Code mods
  .claude-plugin/plugin.json      # each with its own version
  hooks/                          # register.tsx (the mod) + hooks.json, tests where present
  types/                          # mod API typings

benchmarks/token-savings/         # paired Claude Code cost benchmark (not a plugin)

Developing

claude plugin validate .                                # marketplace + all plugins
./plugins/smart-review/scripts/validate-adapters.sh      # smart-review's per-harness manifests
./benchmarks/token-savings/check.sh                      # benchmark lint and graders; no API spend
claude plugin test plugins/cache-clock                   # mod tests, including the native prompt_cache path
node --test plugins/cache-clock/statusline/bridge.test.mjs

Releasing: users only get an update when a plugin's version string changes, so bump it on every user-facing change and push to main.

  • smart-review: version is pinned across all its manifests; bump them together with ./plugins/smart-review/scripts/bump-version.sh <version>.
  • tldraw, test-drive, factory, and each mod: version independently; edit that plugin's .claude-plugin/plugin.json.

Once pushed, installed clients pick it up on their next background marketplace refresh, or immediately with /plugin marketplace update lchase.

Source 4 files
hooks/register.tsx 471 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Last, Totals } from '../types'
5import { MIN, bar, coldCost, coldPenalty, mins, reusedPct, savedBy, tok, usd } from './cache'
6import {
7  bridgeDirectory,
8  causeLabel,
9  claudeConfigDir,
10  envBlock,
11  isOlderThan,
12  leftMs,
13  nativeFile,
14  parseBridge,
15  pickTtl,
16  str,
17  versionText,
18} from './native'
19import type { NativeCache, TtlSource } from './native'
20
21// lastCache is the fallback clock only: milliseconds when the request STARTED.
22// Native expires_at wins whenever the status-line bridge has written one.
23// nativeAfter ignores bridge files written before the last compaction or new conversation.
24const lastCache = atom({ plugin: 'cache-clock', key: 'lastCache' } as const, 0)
25const toastedFor = atom({ plugin: 'cache-clock', key: 'toastedFor' } as const, 0)
26const lastStep = atom({ plugin: 'cache-clock', key: 'last' } as const, null as Last | null)
27const totals = atom({ plugin: 'cache-clock', key: 'totals' } as const, { reads: 0, writes: 0, fresh: 0, saved: 0, unpricedReads: 0 } as Totals)
28const isOn = atom({ plugin: 'cache-clock', key: 'isOn' } as const, true)
29const nativeAfter = atom({ plugin: 'cache-clock', key: 'nativeAfter' } as const, 0)
30
31// 7 cells, the length of 'handoff', so stacked bands line up
32const LABEL_W = 7
33const GREEN = '#22c55e'
34const AMBER = '#f59e0b'
35const RED = '#ef4444'
36const BRIDGE = 'cache-clock/bridge.mjs'
37const MIN_VERSION = [2, 1, 251] as const // first Claude Code that sends prompt_cache to the status line
38
39// The loader cancels timers when this module reloads (mods API: "Timers stop when the module
40// reloads"). session.start then fires again. This flag lives on the module, so a reload resets
41// it and the new module arms one timer. A $.state flag would survive the reload and skip that.
42let clockOn = false
43
44const cost = (c: number | null) => (c === null ? '≈ ?' : `≈ ${usd(c)}`)
45
46type View = {
47  left: number
48  ttlMinutes: number
49  source: TtlSource
50  cached: number | null
51  native: NativeCache | null
52  model: string | null
53  last: Last | null
54}
55
56const tokensOf = (v: View) => (v.last ? v.last.reads + v.last.writes + v.last.fresh : (v.cached ?? 0))
57
58const penalty = (v: View) => (v.model && v.cached !== null ? coldPenalty(v.model, v.cached, tokensOf(v), v.ttlMinutes) : null)
59
60const rewrite = (v: View) => (v.model && v.cached !== null ? coldCost(v.model, v.cached, tokensOf(v), v.ttlMinutes) : null)
61
62async function configOf($: EngineInterface): Promise<string | null> {
63  return claudeConfigDir(await $.env.get('CLAUDE_CONFIG_DIR'), await $.env.get('HOME'))
64}
65
66async function readNative($: EngineInterface, now: number, floor: number) {
67  const config = await configOf($)
68  if (!config) return null
69  const id = await $.session.id()
70  const file = nativeFile(bridgeDirectory(config), String(id ?? ''))
71  if (!file) return null
72  const text = await $.fs.read(file).catch(() => null)
73  return parseBridge(typeof text === 'string' ? text : null, now, floor)
74}
75
76async function chosen($: EngineInterface, fallbackMinutes: number) {
77  const settings = await $.settings.read().catch(() => ({}))
78  const env = envBlock(settings)
79  const prompt = settings && typeof settings === 'object' ? (settings as { promptCacheTtl?: unknown }).promptCacheTtl : undefined
80  return pickTtl({
81    force5m: await $.env.get('FORCE_PROMPT_CACHING_5M'),
82    envTtl: await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'),
83    enable1h: await $.env.get('ENABLE_PROMPT_CACHING_1H'),
84    fileForce5m: str(env, 'FORCE_PROMPT_CACHING_5M'),
85    fileEnvTtl: str(env, 'CLAUDE_CODE_PROMPT_CACHE_TTL'),
86    fileEnable1h: str(env, 'ENABLE_PROMPT_CACHING_1H'),
87    promptCacheTtl: typeof prompt === 'string' ? prompt : undefined,
88    fallbackMinutes,
89  })
90}
91
92async function view($: EngineInterface, fallbackMinutes: number): Promise<View | null> {
93  const [at, last, floor, now] = await Promise.all([read($, lastCache), read($, lastStep), read($, nativeAfter), $.clock.now()])
94  const bridge = await readNative($, now, floor)
95  const native = bridge?.cache ?? null
96  if (!native && (!at || !last)) return null
97  const picked = native?.ttl ? { minutes: native.ttl === '1h' ? 60 : 5, source: 'native' as const } : await chosen($, fallbackMinutes)
98  const cached = native && native.recache_tokens_if_cold !== undefined ? native.recache_tokens_if_cold : last ? last.reads + last.writes : null
99  return {
100    left: leftMs(native, at, picked.minutes, now),
101    ttlMinutes: picked.minutes,
102    source: picked.source,
103    cached,
104    native,
105    model: last?.model ?? bridge?.model ?? null,
106    last,
107  }
108}
109
110async function tick($: EngineInterface, fallbackMinutes: number) {
111  $.ui.invalidate('ui.render')
112  if (!(await read($, isOn))) return
113  const v = await view($, fallbackMinutes)
114  if (!v) return
115  const key = v.native?.expires_at ?? (await read($, lastCache))
116  // a 5-minute cache is at 5 minutes left the moment it is written, so warn at 1 minute there
117  const warnAt = v.ttlMinutes > 5 ? 5 * MIN : MIN
118  if (v.left <= 0 || v.left > warnAt || (await read($, toastedFor)) === key) return
119  await update($, toastedFor, () => key)
120  const size = v.cached === null ? 'size pending' : `${tok(v.cached)} tokens cached`
121  $.ui.toast(
122    `Cache goes cold in ${mins(v.left)}: ${size}, going cold costs ${cost(penalty(v))} extra (estimate). Send anything to keep it warm.`,
123    { timeoutMs: 10000 },
124  )
125}
126
127async function reset($: EngineInterface) {
128  const now = await $.clock.now()
129  await update($, lastCache, () => 0)
130  await update($, lastStep, () => null)
131  await update($, toastedFor, () => 0)
132  await update($, nativeAfter, () => now)
133}
134
135const ttlLine = (v: View) => {
136  if (v.source === 'native') return `TTL ${v.ttlMinutes}m (from Claude Code's prompt_cache)`
137  if (v.source === 'settings') return `TTL ${v.ttlMinutes}m (from your promptCacheTtl setting)`
138  if (v.source === 'env') return `TTL ${v.ttlMinutes}m (from your prompt-cache environment)`
139  return `TTL ${v.ttlMinutes}m (ASSUMED from the cacheMinutes option; /cache-clock setup reads Claude Code's prompt_cache)`
140}
141
142const bandDetail = (v: View) => {
143  const parts: string[] = []
144  if (typeof v.native?.hit_ratio === 'number') parts.push(`${Math.round(v.native.hit_ratio * 100)}% hit`)
145  else if (v.last) parts.push(`${reusedPct(v.last.reads, v.last.writes, v.last.fresh)}% reused`)
146  parts.push(v.cached === null ? 'size pending' : `${tok(v.cached)} cached`)
147  parts.push(`cold costs ${cost(penalty(v))} extra`)
148  if (v.left <= 0) {
149    const cause = v.native?.last_miss_cause?.causes[0]?.replaceAll('_', ' ')
150    if (cause) parts.push(cause)
151  }
152  return ` ${parts.join(' · ')} `
153}
154
155export const register: Register = (on, options) => {
156  // 5 when we must guess: a 60-minute guess shows "warm" on a cache that died at 5.
157  const fallbackMinutes = options?.cacheMinutes === '60' ? 60 : 5
158
159  on('session.start', async ($, e, next) => {
160    if (!clockOn) {
161      clockOn = true
162      $.clock.every(30000, () => tick($, fallbackMinutes))
163    }
164    await refreshBridge($).catch(() => {})
165    await $.command
166      .register({
167        name: 'cache-clock',
168        description: 'Prompt cache clock: on | off | status | setup | remove',
169        argumentHint: '[on|off|status|setup|remove]',
170      })
171      .catch(() => {})
172    return next(e)
173  })
174
175  on('turn.step', async function* ($, e, next) {
176    // The API measures TTL from the start of the request, not from the end of the response.
177    const startedAt = e.agentId ? 0 : await $.clock.now()
178    const result = yield* next(e)
179    const u = result?.usage
180    if (!u) return result
181    const reads = u.cache_read_input_tokens
182    const writes = u.cache_creation_input_tokens
183    const fresh = u.input_tokens
184    const saved = savedBy(u.model, reads, reads + writes + fresh)
185    await update($, totals, t => ({
186      reads: t.reads + reads,
187      writes: t.writes + writes,
188      fresh: t.fresh + fresh,
189      saved: t.saved + (saved ?? 0),
190      unpricedReads: t.unpricedReads + (saved === null ? reads : 0),
191    }))
192    // only a main-loop step that touched the cache restarts the fallback countdown
193    if (!e.agentId && reads + writes > 0) {
194      await update($, lastCache, () => startedAt)
195      await update($, lastStep, () => ({ reads, writes, fresh, model: u.model }))
196      $.ui.invalidate('ui.render')
197    }
198    return result
199  })
200
201  // /compact is about to drop the old prefix. Clear derived state before it runs.
202  // A compact this mod starts itself is a re-entry, so this hook is skipped and the button resets.
203  on('session.compact', async ($, e, next) => {
204    await reset($)
205    return next(e)
206  }).catch(passOn)
207
208  // A new conversation, or the SessionStart that follows compaction. `compact` is a documented source.
209  on('classic.SessionStart', { source: ['clear', 'resume', 'fork', 'compact'] }, async ($, e, next) => {
210    await reset($)
211    return next(e)
212  }).catch(passOn)
213
214  on('command.run', { command: 'cache-clock' }, async ($, e) => {
215    const arg = e.args.trim().toLowerCase()
216    if (arg === 'on' || arg === 'off') {
217      await update($, isOn, () => arg === 'on')
218      $.ui.invalidate('ui.render')
219      return { text: `cache-clock ${arg}.` }
220    }
221    if (arg === 'setup' || arg === 'remove') {
222      try {
223        return { text: arg === 'setup' ? await setup($) : await remove($) }
224      } catch (err) {
225        return { text: `cache-clock ${arg} failed: ${String((err as Error)?.message ?? err).slice(0, 200)}` }
226      }
227    }
228    if (arg !== '' && arg !== 'status') return { text: 'Usage: /cache-clock on | off | status | setup | remove' }
229
230    const [on_, t] = await Promise.all([read($, isOn), read($, totals)])
231    const v = await view($, fallbackMinutes)
232    const lines = [`cache-clock: ${on_ ? 'on' : 'off'}`]
233    if (!v) lines.push('Cache: no cache activity yet')
234    else {
235      lines.push(ttlLine(v))
236      lines.push(v.left > 0 ? `Cache: warm, ${mins(v.left)} left` : 'Cache: COLD')
237      if (typeof v.native?.hit_ratio === 'number') {
238        lines.push(`Claude Code: ${Math.round(v.native.hit_ratio * 100)}% of input from cache, ${v.native.misses ?? 0} misses`)
239      } else if (v.last) {
240        lines.push(`Reused ${reusedPct(v.last.reads, v.last.writes, v.last.fresh)}% on the last main step`)
241      }
242      const causes = causeLabel(v.native?.last_miss_cause?.causes)
243      if (causes) lines.push(`Last miss: ${causes}`)
244      const size = v.cached === null ? 'size pending' : `${tok(v.cached)} cached`
245      lines.push(`Going cold costs ${cost(penalty(v))} extra for ${size} (full rewrite ${cost(rewrite(v))})`)
246    }
247    lines.push(`Session reads ${tok(t.reads)}, writes ${tok(t.writes)}, fresh input ${tok(t.fresh)} (subagents included)`)
248    lines.push(
249      `Saved ${t.unpricedReads > 0 ? 'at least ' : ''}≈ ${usd(t.saved)} by cache reads vs uncached input` +
250        (t.unpricedReads > 0 ? ` (${tok(t.unpricedReads)} read tokens on models with no known price)` : ''),
251    )
252    lines.push('Dollar figures are estimates from list prices. A "?" on the band means the TTL is assumed, not reported by Claude Code.')
253    return { text: lines.join('\n') }
254  })
255
256  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
257    const active = await read($, isOn)
258    if (e.props.hasSurvey || !active) return next(e)
259    const v = await view($, fallbackMinutes)
260    if (!v) return next(e)
261
262    let below: Awaited<ReturnType<typeof next>> | undefined
263    try {
264      below = await next(e)
265    } catch {
266      below = undefined
267    }
268
269    const { Box, Text, Button } = $.ui.resolve(e)
270    const ttl = v.ttlMinutes * MIN
271    const color = v.left <= 0 ? RED : v.left <= ttl / 4 ? AMBER : GREEN
272    const mark = v.source === 'assumed' ? '?' : ''
273    const compact = async () => {
274      try {
275        const r = await $.session.compact()
276        // This call re-enters session.compact, so the hook above is skipped. Reset here.
277        if (!r.skip) await reset($)
278        $.ui.toast(
279          r.skip
280            ? `Compact skipped: ${r.skip}`
281            : r.tokensBefore !== undefined && r.tokensAfter !== undefined
282              ? `Compacted: ${tok(r.tokensBefore)} to ${tok(r.tokensAfter)} tokens.`
283              : 'Compacted.',
284        )
285      } catch (err) {
286        $.ui.toast(`Compact failed: ${String((err as Error)?.message ?? err).slice(0, 100)}`)
287      }
288    }
289
290    // proportional fonts collapse the padded label, │ and ▰▱ cells: a gapped row with an Svg meter
291    const desktop = () => {
292      if (e.surface === 'terminal') return null
293      const { Svg } = $.ui.resolve(e)
294      const fill = Math.round(Math.max(0, Math.min(1, v.left / ttl)) * 56)
295      return (
296        <Box flexDirection="row" alignItems="center">
297          <Box width={9} flexShrink={0}><Text dimColor bold>cache</Text></Box>
298          <Box flexDirection="row" alignItems="center" flexWrap="wrap" flexGrow={1} gap={1}>
299          <Text bold color={color}>{v.left > 0 ? `warm ${mins(v.left)}${mark}` : 'COLD'}</Text>
300          <Svg
301            source={`<svg xmlns="http://www.w3.org/2000/svg" width="56" height="8" viewBox="0 0 56 8"><rect width="56" height="8" rx="4" fill="#8080804d"/><rect width="${fill}" height="8" rx="4" fill="${color}"/></svg>`}
302            alt={v.left > 0 ? `${mins(v.left)} left` : 'cold'}
303            width={56}
304            height={8}
305          />
306          <Text dimColor>{bandDetail(v).trim()}</Text>
307          {/* native buttons stand taller than a text row: keep them at the trailing edge */}
308          <Box flexGrow={1} />
309          {v.left > 0 ? <Button key="compact" label="Compact" onPress={compact} /> : null}
310          </Box>
311        </Box>
312      )
313    }
314
315    // filled cells in the state color, empty cells dim
316    const cells = bar(v.left, ttl)
317    const line = desktop() ?? (
318      <Box>
319        <Text dimColor>{'cache'.padStart(LABEL_W)}</Text>
320        <Text dimColor>{' │ '}</Text>
321        <Text bold color={color}>
322          {v.left > 0 ? `warm ${mins(v.left)}${mark} ` : 'COLD '}
323        </Text>
324        <Text color={color}>{cells.replace(/▱/g, '')}</Text>
325        <Text dimColor>{cells.replace(/▰/g, '')}</Text>
326        <Text dimColor>{bandDetail(v)}</Text>
327        {/* Compacting a cold cache re-reads the history uncached. Offer it only while warm. */}
328        {v.left > 0 ? <Button key="compact" plain label="[ Compact ]" onPress={compact} /> : null}
329      </Box>
330    )
331    if (!below) return line
332    return (
333      <Box flexDirection="column">
334        {line}
335        {below}
336      </Box>
337    )
338  })
339}
340
341// A throw in reset must not block compaction or a new conversation. Re-entry (the Compact
342// button calling $.session.compact) skips the hook; calling next again would compact twice.
343async function passOn(_$: EngineInterface, e: unknown, next: ((event: unknown) => Promise<unknown>) & { called?: boolean; error?: { kind?: string } }) {
344  if (next.error?.kind === 're-entry' || next.called) return
345  return next(e)
346}
347
348// ---- /cache-clock setup | remove -------------------------------------------------------
349// Plugins cannot ship a statusLine. Setup edits the user settings file only, saves the
350// previous command, and points statusLine at statusline/bridge.mjs. A status line that
351// comes from managed settings, --settings, or project/local settings is reported and left alone.
352
353type StatusLine = { type?: string; command?: string; [key: string]: unknown }
354
355function asStatusLine(value: unknown): StatusLine | null {
356  return value && typeof value === 'object' && !Array.isArray(value) ? (value as StatusLine) : null
357}
358
359function fnv(s: string) {
360  let h = 0x811c9dc5
361  for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193) >>> 0
362  return h.toString(16).padStart(8, '0')
363}
364
365function shellQuoted(path: string) {
366  return path.replace(/["\\$`]/g, c => `\\${c}`)
367}
368
369async function readJson($: EngineInterface, file: string): Promise<Record<string, unknown>> {
370  if (!(await $.fs.exists(file))) return {}
371  const text = await $.fs.read(file)
372  if (!text.trim()) return {}
373  let parsed: unknown
374  try {
375    parsed = JSON.parse(text)
376  } catch {
377    throw new Error(`${file} is not valid JSON, so it was left as it is.`)
378  }
379  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`${file} does not hold a settings object.`)
380  return parsed as Record<string, unknown>
381}
382
383async function copyBridge($: EngineInterface, dir: string) {
384  await $.fs.write(`${dir}/bridge.mjs`, await $.fs.read(`${$.plugin.root}/statusline/bridge.mjs`))
385}
386
387async function refreshBridge($: EngineInterface) {
388  const settings = await $.settings.read({ source: 'user' }).catch(() => null)
389  const command = asStatusLine((settings as { statusLine?: unknown } | null)?.statusLine)?.command
390  if (typeof command !== 'string' || !command.includes(BRIDGE)) return
391  const config = await configOf($)
392  if (!config) return
393  const dir = bridgeDirectory(config)
394  const fresh = await $.fs.read(`${$.plugin.root}/statusline/bridge.mjs`)
395  const copy = await $.fs.read(`${dir}/bridge.mjs`).catch(() => null)
396  if (copy !== fresh) await $.fs.write(`${dir}/bridge.mjs`, fresh)
397}
398
399async function higherStatusLine($: EngineInterface): Promise<string | null> {
400  for (const source of ['policy', 'flag', 'local', 'project'] as const) {
401    const settings = await $.settings.read({ source }).catch(() => ({}))
402    if (asStatusLine((settings as { statusLine?: unknown })?.statusLine)) return source
403  }
404  return null
405}
406
407async function nodeWarning($: EngineInterface): Promise<string> {
408  const node = await $.process.run(['node', '--version'], { timeoutMs: 5000 }).catch(() => null)
409  if (!node || node.exitCode !== 0) return ' Warning: node is not on PATH, and the bridge needs it.'
410  return ''
411}
412
413async function setup($: EngineInterface): Promise<string> {
414  const reported = await $.session.version().catch(() => null)
415  const text = versionText(reported)
416  if (!text) return "Could not read Claude Code's version, so nothing was changed."
417  if (isOlderThan(text, MIN_VERSION)) {
418    return `Claude Code ${text} does not send prompt_cache to the status line (needs 2.1.251+). Nothing changed.`
419  }
420  const blocked = await higherStatusLine($)
421  if (blocked) {
422    const where = blocked === 'policy' ? 'managed settings' : blocked === 'flag' ? '--settings' : `${blocked} settings`
423    return `Your status line comes from ${where}, which this setup does not edit. Nothing changed.`
424  }
425  const config = await configOf($)
426  if (!config) return 'HOME is not set, so the Claude config folder is unknown. Nothing changed.'
427  const dir = bridgeDirectory(config)
428  const file = `${config}/settings.json`
429  const settings = await readJson($, file)
430  const current = asStatusLine(settings.statusLine)
431  if (typeof current?.command === 'string' && current.command.includes(BRIDGE)) {
432    await copyBridge($, dir)
433    return 'cache-clock is already set up. The bridge script is up to date.'
434  }
435  const key = fnv(file)
436  const wrapped = typeof current?.command === 'string' && current.command.trim() ? current.command : null
437  await copyBridge($, dir)
438  await $.fs.write(`${dir}/setup-${key}.json`, JSON.stringify({ file, previous: current ?? null, wrapped }, null, 2) + '\n')
439  settings.statusLine = { ...(current ?? {}), type: 'command', command: `node "${shellQuoted(`${dir}/bridge.mjs`)}" ${key}` }
440  await $.fs.write(file, JSON.stringify(settings, null, 2) + '\n')
441  const kept = wrapped ? ' Your status line still prints as before.' : ''
442  return `cache-clock bridge set up in ${file}.${kept} The band uses Claude Code's own TTL after the next reply.${await nodeWarning($)} /cache-clock remove puts it back.`
443}
444
445async function remove($: EngineInterface): Promise<string> {
446  const config = await configOf($)
447  if (!config) return 'HOME is not set. Nothing changed.'
448  const dir = bridgeDirectory(config)
449  const file = `${config}/settings.json`
450  const key = fnv(file)
451  const savedText = await $.fs.read(`${dir}/setup-${key}.json`).catch(() => null)
452  let saved: { previous?: unknown } | null = null
453  if (typeof savedText === 'string' && savedText.trim()) {
454    try {
455      saved = JSON.parse(savedText)
456    } catch {
457      saved = null
458    }
459  }
460  const settings = await readJson($, file)
461  const current = asStatusLine(settings.statusLine)
462  if (!(typeof current?.command === 'string' && current.command.includes(BRIDGE))) {
463    return 'cache-clock bridge is not set up in your user settings. Nothing changed.'
464  }
465  if (saved?.previous) settings.statusLine = saved.previous
466  else delete settings.statusLine
467  await $.fs.write(file, JSON.stringify(settings, null, 2) + '\n')
468  await $.fs.write(`${dir}/setup-${key}.json`, '{}\n')
469  return 'cache-clock bridge removed. The band falls back to your settings or env TTL, or to the cacheMinutes option (marked as an estimate).'
470}
471
hooks/cache.ts 98 lines
1export const MIN = 60000
2
3// USD per million tokens, global standard list prices from
4// https://platform.claude.com/docs/en/about-claude/pricing (checked 2026-10-18).
5// No Claude Code API gives a mod per-model prices (modelPricing is managed-scope only),
6// so this table stays hand-kept. Re-check it on every release.
7// US-only inference is 1.1x and fast mode is a separate card; neither is applied here.
8// write5 / write60 are the 5-minute (1.25x input) and 1-hour (2x input) cache-write prices.
9// Sonnet 5.5 cache reads are $0.10 (0.05x), halved from $0.20 on 2026-10-07.
10export type Rates = { input: number; write5: number; write60: number; read: number }
11
12const TABLE: Record<string, Rates> = {
13  'claude-fable-5-1': { input: 10, write5: 12.5, write60: 20, read: 0.25 },
14  'claude-mythos-5-1': { input: 10, write5: 12.5, write60: 20, read: 0.25 },
15  'claude-fable-5': { input: 10, write5: 12.5, write60: 20, read: 1 },
16  'claude-mythos-5': { input: 10, write5: 12.5, write60: 20, read: 1 },
17  'claude-opus-5-5': { input: 4, write5: 5, write60: 8, read: 0.2 },
18  'claude-opus-5': { input: 5, write5: 6.25, write60: 10, read: 0.5 },
19  'claude-opus-4-8': { input: 5, write5: 6.25, write60: 10, read: 0.5 },
20  'claude-opus-4-7': { input: 5, write5: 6.25, write60: 10, read: 0.5 },
21  'claude-opus-4-6': { input: 5, write5: 6.25, write60: 10, read: 0.5 },
22  'claude-opus-4-5': { input: 5, write5: 6.25, write60: 10, read: 0.5 },
23  // Retired on the first-party API, still listed for Bedrock / Google Cloud.
24  'claude-opus-4-1': { input: 15, write5: 18.75, write60: 30, read: 1.5 },
25  'claude-opus-4': { input: 15, write5: 18.75, write60: 30, read: 1.5 },
26  'claude-sonnet-5-5': { input: 2, write5: 2.5, write60: 4, read: 0.1 },
27  'claude-sonnet-5': { input: 2, write5: 2.5, write60: 4, read: 0.2 },
28  'claude-sonnet-4-6': { input: 3, write5: 3.75, write60: 6, read: 0.3 },
29  'claude-sonnet-4-5': { input: 3, write5: 3.75, write60: 6, read: 0.3 },
30  'claude-sonnet-4': { input: 3, write5: 3.75, write60: 6, read: 0.3 },
31  'claude-haiku-4-5': { input: 1, write5: 1.25, write60: 2, read: 0.1 },
32  'claude-3-5-haiku': { input: 0.8, write5: 1, write60: 1.6, read: 0.08 },
33}
34
35// Haiku 5.5 has two rate cards chosen by prompt length: 100K tokens or fewer, or longer.
36const HAIKU_55_SHORT: Rates = { input: 0.1, write5: 0.125, write60: 0.2, read: 0.01 }
37const HAIKU_55_LONG: Rates = { input: 0.5, write5: 0.625, write60: 1, read: 0.05 }
38
39// Strips a context-window suffix, a cloud-provider prefix, a Bedrock version, and a snapshot date.
40// `us.anthropic.claude-sonnet-4-5-20250929-v1:0` and `claude-sonnet-4-5@20250929` both become
41// `claude-sonnet-4-5`. Anything left that is not in the table stays unpriced.
42export const canonical = (id: string) =>
43  id
44    .trim()
45    .replace(/\[1m\]$/, '')
46    .replace(/^(?:[a-z0-9-]+\.)?anthropic\./, '')
47    .replace(/-v\d+(?::\d+)?$/, '')
48    .replace(/@\d{8}$/, '')
49    .replace(/-latest$/, '')
50    .replace(/-\d{8}$/, '')
51
52export function rates(model: string, promptTokens: number): Rates | null {
53  const id = canonical(model)
54  if (id === 'claude-haiku-5-5') return promptTokens > 100000 ? HAIKU_55_LONG : HAIKU_55_SHORT
55  return TABLE[id] ?? null
56}
57
58const writeRate = (r: Rates, ttlMinutes: number) => (ttlMinutes > 5 ? r.write60 : r.write5)
59
60// What letting the cache go cold costs EXTRA on the next turn: the write price minus the read
61// price that same prefix would have cost while warm. Null when the model has no known price.
62export function coldPenalty(model: string, cached: number, promptTokens: number, ttlMinutes: number): number | null {
63  const r = rates(model, promptTokens)
64  if (!r) return null
65  return (cached * (writeRate(r, ttlMinutes) - r.read)) / 1e6
66}
67
68// What rewriting `cached` tokens into a cold cache costs, or null when the model has no known price.
69export function coldCost(model: string, cached: number, promptTokens: number, ttlMinutes: number): number | null {
70  const r = rates(model, promptTokens)
71  if (!r) return null
72  return (cached * writeRate(r, ttlMinutes)) / 1e6
73}
74
75// What the cache reads saved against paying the full input price, or null when the model has no known price.
76export function savedBy(model: string, reads: number, promptTokens: number): number | null {
77  const r = rates(model, promptTokens)
78  if (!r) return null
79  return (reads * (r.input - r.read)) / 1e6
80}
81
82export const reusedPct = (reads: number, writes: number, fresh: number) => {
83  const total = reads + writes + fresh
84  return total > 0 ? Math.round((reads / total) * 100) : 0
85}
86
87export const tok = (n: number) =>
88  n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(n >= 1e5 ? 0 : 1)}k` : String(n)
89
90export const usd = (n: number) => (n > 0 && n < 0.005 ? '<$0.01' : `$${n.toFixed(2)}`)
91
92export const mins = (ms: number) => `${Math.max(1, Math.ceil(ms / MIN))}m`
93
94export const bar = (left: number, ttl: number, cells = 6) => {
95  const filled = ttl > 0 ? Math.max(0, Math.min(cells, Math.floor((left / ttl) * cells))) : 0
96  return '▰'.repeat(filled) + '▱'.repeat(cells - filled)
97}
98
hooks/native.ts 170 lines
1import { MIN } from './cache'
2
3// Facts the band can know, best source first:
4//   1. Claude Code's prompt_cache (status line stdin, bridged by statusline/bridge.mjs).
5//      TTL, expiry, warm, hit ratio, misses, miss cause, re-cache size. Main conversation only.
6//   2. The TTL the user chose: FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL,
7//      settings promptCacheTtl, ENABLE_PROMPT_CACHING_1H. Blind to the subscription-vs-API
8//      default and to a mid-session drop onto usage credits.
9//   3. The plugin's cacheMinutes option. A guess. The band marks it with "?".
10// Docs: https://code.claude.com/docs/en/statusline#prompt-cache-fields
11//       https://code.claude.com/docs/en/prompt-caching#choose-the-ttl-yourself
12
13export type NativeCache = {
14  warm?: boolean
15  caching_observed?: boolean
16  ttl?: '5m' | '1h'
17  expires_at?: number | null // epoch seconds
18  hit_ratio?: number | null
19  misses?: number
20  last_miss_cause?: { causes: string[] } | null
21  // undefined: the field was absent (fall back to the last step). null: Claude Code
22  // says the size is not known yet (right after compaction or tool-result clearing).
23  recache_tokens_if_cold?: number | null
24}
25
26export type Bridge = { cache: NativeCache; model: string | null; writtenAt: number }
27
28export type TtlSource = 'native' | 'env' | 'settings' | 'assumed'
29
30export type TtlPick = { minutes: number; source: TtlSource }
31
32export type TtlInput = {
33  force5m?: string
34  envTtl?: string
35  fileForce5m?: string
36  fileEnvTtl?: string
37  promptCacheTtl?: string
38  enable1h?: string
39  fileEnable1h?: string
40  fallbackMinutes: number
41}
42
43// Ignore a bridge file nobody has refreshed in 2 hours (old session, bridge removed).
44export const STALE_MS = 2 * 60 * MIN
45
46export const asMinutes = (v: unknown): 5 | 60 | null => (v === '1h' ? 60 : v === '5m' ? 5 : null)
47
48export function claudeConfigDir(custom: string | undefined, home: string | undefined): string | null {
49  const picked = custom?.trim().replace(/\/+$/, '')
50  if (picked) return picked
51  const root = home?.trim().replace(/\/+$/, '')
52  return root ? `${root}/.claude` : null
53}
54
55export const bridgeDirectory = (config: string) => `${config}/cache-clock`
56
57// Session ids are UUIDs. Reject anything else so a bridge filename cannot escape the directory.
58export function nativeFile(dir: string, sessionId: string): string | null {
59  if (!/^[\w-]+$/.test(sessionId)) return null
60  return `${dir}/native-${sessionId}.json`
61}
62
63const asBool = (v: unknown): boolean | undefined => (typeof v === 'boolean' ? v : undefined)
64
65const asCause = (v: unknown): { causes: string[] } | null => {
66  if (!v || typeof v !== 'object') return null
67  const raw = (v as { causes?: unknown }).causes
68  if (!Array.isArray(raw)) return null
69  const causes = raw.filter((c): c is string => typeof c === 'string' && c.length > 0)
70  return causes.length ? { causes } : null
71}
72
73export function asCache(v: unknown): NativeCache | null {
74  if (!v || typeof v !== 'object' || Array.isArray(v)) return null
75  const o = v as Record<string, unknown>
76  const ttl = o.ttl === '5m' || o.ttl === '1h' ? o.ttl : undefined
77  const expires = typeof o.expires_at === 'number' ? o.expires_at : o.expires_at === null ? null : undefined
78  const hit = typeof o.hit_ratio === 'number' ? o.hit_ratio : o.hit_ratio === null ? null : undefined
79  const misses = typeof o.misses === 'number' ? o.misses : undefined
80  let recache: number | null | undefined
81  if ('recache_tokens_if_cold' in o) {
82    recache = typeof o.recache_tokens_if_cold === 'number' ? o.recache_tokens_if_cold : null
83  }
84  return {
85    warm: asBool(o.warm),
86    caching_observed: asBool(o.caching_observed),
87    ttl,
88    expires_at: expires,
89    hit_ratio: hit,
90    misses,
91    last_miss_cause: asCause(o.last_miss_cause),
92    recache_tokens_if_cold: recache,
93  }
94}
95
96// prompt_cache for this session as the status line last wrote it, or null when missing or stale.
97export function parseBridge(text: string | null, now: number, floor: number): Bridge | null {
98  if (!text) return null
99  let parsed: unknown
100  try {
101    parsed = JSON.parse(text)
102  } catch {
103    return null
104  }
105  if (!parsed || typeof parsed !== 'object') return null
106  const rec = parsed as { writtenAt?: unknown; prompt_cache?: unknown; model?: unknown }
107  const writtenAt = typeof rec.writtenAt === 'number' ? rec.writtenAt : 0
108  if (writtenAt < floor || now - writtenAt > STALE_MS) return null
109  const cache = asCache(rec.prompt_cache)
110  if (!cache) return null
111  return { cache, model: typeof rec.model === 'string' ? rec.model : null, writtenAt }
112}
113
114// The user-chosen main-conversation TTL, in Claude Code's precedence, or the fallback guess.
115// https://code.claude.com/docs/en/prompt-caching#choose-the-ttl-yourself
116export function pickTtl(input: TtlInput): TtlPick {
117  const force = input.force5m === '1' || input.fileForce5m === '1'
118  if (force) return { minutes: 5, source: 'env' }
119  const env = asMinutes(input.envTtl) ?? asMinutes(input.fileEnvTtl)
120  if (env) return { minutes: env, source: 'env' }
121  const setting = asMinutes(input.promptCacheTtl)
122  if (setting) return { minutes: setting, source: 'settings' }
123  if (input.enable1h === '1' || input.fileEnable1h === '1') return { minutes: 60, source: 'env' }
124  return { minutes: input.fallbackMinutes, source: 'assumed' }
125}
126
127export function envBlock(settings: unknown): Record<string, unknown> {
128  if (!settings || typeof settings !== 'object') return {}
129  const env = (settings as { env?: unknown }).env
130  if (!env || typeof env !== 'object' || Array.isArray(env)) return {}
131  return env as Record<string, unknown>
132}
133
134export const str = (obj: Record<string, unknown>, key: string): string | undefined =>
135  typeof obj[key] === 'string' ? (obj[key] as string) : undefined
136
137// Milliseconds of warmth left. Native expires_at when we have it (Claude Code already
138// measured from the request start). Otherwise the stamp taken before the request went out.
139export function leftMs(native: NativeCache | null, stampedAt: number, ttlMinutes: number, now: number): number {
140  if (native && typeof native.expires_at === 'number') return native.expires_at * 1000 - now
141  if (native && native.warm === false) return 0
142  if (!stampedAt) return 0
143  return ttlMinutes * MIN - (now - stampedAt)
144}
145
146export const causeLabel = (causes: string[] | undefined): string | undefined =>
147  causes && causes.length > 0 ? causes.join(', ').replaceAll('_', ' ') : undefined
148
149// `base` is the semver Claude Code reports (2.1.302). `version` is the same string on
150// current builds. An unparsable value does not block setup.
151export function isOlderThan(version: string, min: readonly number[]): boolean {
152  const parts = version.split(/[.-]/).slice(0, min.length).map(Number)
153  if (parts.length < min.length || parts.some(n => Number.isNaN(n))) return false
154  for (let i = 0; i < min.length; i++) {
155    const part = parts[i] ?? 0
156    const want = min[i] ?? 0
157    if (part !== want) return part < want
158  }
159  return false
160}
161
162export function versionText(value: unknown): string {
163  if (typeof value === 'string') return value
164  if (!value || typeof value !== 'object') return ''
165  const o = value as { base?: unknown; version?: unknown }
166  if (typeof o.base === 'string' && o.base) return o.base
167  if (typeof o.version === 'string') return o.version
168  return ''
169}
170
types/index.d.ts 9 lines
1export type Last = { reads: number; writes: number; fresh: number; model: string }
2export type Totals = { reads: number; writes: number; fresh: number; saved: number; unpricedReads: number }
3
4declare module 'claude-code' {
5  interface PluginState {
6    'cache-clock': { lastCache: number; toastedFor: number; last: Last | null; totals: Totals; isOn: boolean; nativeAfter: number }
7  }
8}
9