SLOPSHOPPER

session-meter

A band above the prompt: context against the auto-compact window and turns left to it, prompt cache countdown, rate limits with their pace, a cache hit…

bandcommandtoaststatusprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-meter
› 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 › /meter ⎿ session-meter: ☁ 多云 上下文 49% 97k/200k │ ❄ 缓存 – │ 5小时 ▰▰▱▱▱ 31% 09:53重置 │ $0.42 ⎿ session-meter: ⎿ session-meter: 提示缓存:主线程还没有响应 ⎿ session-meter: 上下文:97k / 200k(49%) ⎿ session-meter: 压缩窗口:读不到,按 200k 算;模型窗口 200k ⎿ session-meter: 额度 5小时:已用 31%,09:53 重置 ☁ 多云 上下文 49% 97k/200k │ ❄ 缓存 – │ 5小时 ▰▰▱▱▱ 31% 09:53重置 │ $0.42 │ 已坐 0m ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
☁ 多云 上下文 49% 97k/200k │ ❄ 缓存 – │ 5小时 ▰▰▱▱▱ 31% 09:53重置 │ $0.42 │ 已坐 0m ⟨Claude Code's own drawing⟩
README

claude-mods

Claude Code mods (function-hook plugins). The UI text is in Simplified Chinese.

Claude Code 的 mod 合集(function-hook 插件)。界面文字为简体中文。

session-meter

A band above the prompt that answers "what should I do now?":

ShowsWhy
☁ 多云 上下文 53% 210k/400kContext size against the auto-compact window Claude Code uses (autoCompactWindow, else the model's window; 400k when it cannot be read)
约 6 轮后自动压缩Turns left before auto-compaction, from the recent growth per turn
❄ 缓存 57:42Prompt cache countdown (1h / 5m, from the cacheTtl option, else inferred from your plan)
5小时 ▰▰▰▱▱ 67% 预计14:20用完 15:10重置Rate-limit windows, with a run-out forecast from the last 30 minutes of use
命中 40% 缓存可能失效Cache hit rate, only when it looks broken
已坐 47mStand-up reminder: a pixel figure, a rotating tip and two buttons after 60 minutes

Toasts, each sent once: cache about to expire (only when the rewrite is costly and you are at the desk), a rate-limit window running out before its reset, time to stand up, and a late-night nudge from 23:00. Reminders about you never interrupt a running turn. No toast about the context: Claude Code compacts on its own. A session shown nowhere (claude -p, a scheduled task) runs no tick and sends no toast. /meter prints every figure in full (the command works in the terminal; the desktop app does not route mod commands).

Install

Needs a Claude Code build with function-hook plugins (developed against 2.1.288–2.1.291).

claude plugin marketplace add feizaodemon/claude-mods
claude plugin install session-meter@feizao-mods

Or clone this repo and list the folder in CLAUDE_CODE_PLUGIN_DIRS (;-separated on Windows, : elsewhere) in ~/.claude/settings.json:

{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-mods/mods/session-meter" } }

Options

OptionDefault
cacheTtlautoauto, 1h or 5m; set it to match if you fix the TTL with an environment variable or promptCacheTtl
standupMinutes60Stand-up reminder interval; 10 minutes without a prompt counts as a break; 0 off
bedtimeHour23Late-night reminder from this hour to 5 am; 0 off

What the hooks do

The mod only reads: it never changes what other code sends, and it sends nothing off the machine.

HookWhat it does
prompt.submitNotes the time: a turn has started (stand-up and late-night reminders wait for it to end), and a prompt you typed means you are at the desk. Passes the prompt on unchanged.
turn.stepAfter each main-thread response, records when it landed, its cache hit rate and the cache TTL it got. Passes the result on unchanged.
turn.completeMarks the main turn over, records the context size for the turns-left estimate, and reads the auto-compact window again (a local estimate, no request).
session.start / session.endRegisters /meter; in a session shown somewhere, reads the auto-compact window and starts the once-a-second tick. Stops the tick and clears the per-conversation figures on /clear.
session.attachStarts the tick when a client attaches to a session that started headless.
ui.render (AbovePrompt)Draws the band, and the stand-up panel while it is due. What others draw there is kept.
command.run (meter)Prints every figure in full.

It reads nothing from the environment or settings.json itself: the auto-compact window comes from Claude Code's context breakdown, and /meter names where it was set. If you fix the cache TTL there, set cacheTtl to match. Its sitting clock and late-night flag live in the plugin's own store.

Develop

claude plugin validate mods/session-meter
claude plugin test mods/session-meter

Layout: hooks/format.ts (the band's figures), hooks/alerts.ts (every toast rule, pure), hooks/standup.ts (sitting clock, pixel figure), hooks/register.tsx (the once-a-second tick and the drawing).

License

MIT

Source 5 files
hooks/register.tsx 339 lines
1// session-meter: a band above the prompt with the context forecast and turns left, the prompt cache
2// countdown, the rate-limit windows and their pace, a cache-hit warning, the session cost, and
3// stand-up / late-night reminders, fitted to the band's width. /meter prints the figures in full.
4//
5// Once a second the tick reads the engine, works out what the band shows (a View in $.state, which
6// redraws its readers when it changes) and which toasts are due (alerts.ts). Drawing only reads.
7import type { EngineInterface, Register, SessionContextBreakdown, SessionUsage, Timer } from 'claude-code'
8
9import type { View } from '../types'
10import type { Memo, Snapshot } from './alerts'
11import { EMPTY_MEMO, decideToasts } from './alerts'
12import type { Compact, Judge, Sample } from './format'
13import { SEP, WARN_MS, WINDOW_LABEL, cacheDetail, chips, contextScale, exhaustsAt, hhmm, hhmmAt, hitPercent, kCount, layout, line, recentRate, stepTtl, ttlFor } from './format'
14import type { Standup } from './standup'
15import { IDLE_RESET_MS, advice, done, duration, figure, lateNight, nudgeKey, onActivity, parse, phase, snooze, standupChip } from './standup'
16
17const HISTORY = 12
18const STANDUP_KEY = 'standup' // in $.store: one sitting clock shared by every session
19const BEDTIME_KEY = 'bedtime' // in $.store: the night the late-hour reminder last went out for
20const STORE_SYNC_MS = 15_000 // how stale the stand-up clock may be before it is read again
21const SAMPLE_EVERY_MS = 60_000 // how often a rate-limit reading is kept for the recent pace
22const RUNNING_MAX_MS = 30 * 60_000 // a turn that never reported its end stops counting as running
23const FAILING_AFTER = 3 // ticks failed in a row before the band says its figures may be stale
24
25// This mod's values in $.state, each read and written with $.state.get / $.state.set.
26const LAST = { plugin: 'session-meter', key: 'last' } as const
27const READINGS = { plugin: 'session-meter', key: 'readings' } as const
28const VIEW = { plugin: 'session-meter', key: 'view' } as const
29
30// The options' defaults, as the manifest gives them; set again on each (re)load.
31const DEFAULTS = { standupMinutes: 60, bedtimeHour: 23 }
32const num = (v: unknown, d: number) => (typeof v === 'number' ? v : d)
33const cfg = { ttlOption: 'auto' as unknown, standupMs: DEFAULTS.standupMinutes * 60_000, bedtimeHour: DEFAULTS.bedtimeHour }
34
35// What this module remembers between ticks; a reload starts it over.
36// runningSince: when the main conversation's current turn began (0: idle); standup / standupReadAt:
37// this session's copy of the shared clock and when it was read; samples: each window's readings for
38// the recent pace, kept for the reset they belong to; nightChecked: the night whose shared flag was
39// read; compact: the auto-compact window, read once per main turn; ticker: the once-a-second tick,
40// run only in a session shown somewhere; viewKey: the View last written; failures / lastError: the
41// tick's failures in a row.
42const fresh = () => ({
43  memo: { ...EMPTY_MEMO } as Memo,
44  runningSince: 0,
45  standup: undefined as Standup | undefined,
46  standupReadAt: 0,
47  samples: {} as Record<string, { resetsAt: string; list: Sample[] }>,
48  sampledAt: 0,
49  nightChecked: '',
50  compact: undefined as Compact | undefined,
51  ticker: undefined as Timer | undefined,
52  viewKey: '',
53  failures: 0,
54  lastError: '',
55})
56let mem = fresh()
57
58const compactOf = (b: SessionContextBreakdown | undefined): Compact | undefined =>
59  b && b.rawMaxTokens > 0 ? { window: b.rawMaxTokens, source: b.autocompactSource, threshold: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined } : undefined
60
61// The breakdown is estimated locally, but not worth a call a second: once per main turn and at start.
62async function readCompact($: EngineInterface) {
63  const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => undefined)
64  if (usage) mem.compact = compactOf(usage.context.breakdown)
65  return usage
66}
67
68const isRunning = (now: number) => mem.runningSince > 0 && now - mem.runningSince < RUNNING_MAX_MS
69
70// Keeps a reading of each window once a minute; a new reset starts its list over.
71function sample(now: number, usage: SessionUsage) {
72  if (now - mem.sampledAt < SAMPLE_EVERY_MS) return
73  mem.sampledAt = now
74  for (const r of usage.rateLimits) {
75    const held = mem.samples[r.kind]
76    const list = held && held.resetsAt === (r.resetsAt ?? '') ? held.list : []
77    mem.samples[r.kind] = { resetsAt: r.resetsAt ?? '', list: [...list, { t: now, pct: r.percentUsed }].slice(-40) }
78  }
79}
80
81function judge(now: number): Judge {
82  const rates: Record<string, number | undefined> = {}
83  for (const [kind, held] of Object.entries(mem.samples)) rates[kind] = recentRate(held.list, now)
84  return { compact: mem.compact, rates }
85}
86
87// Read from $.store at most every 15 s: the band redraws every second, the clock moves by minutes.
88async function loadStandup($: EngineInterface, now: number): Promise<Standup> {
89  if (mem.standup && now - mem.standupReadAt < STORE_SYNC_MS) return mem.standup
90  mem.standup = parse(await $.store.get(STANDUP_KEY).catch(() => undefined), now)
91  mem.standupReadAt = now
92  return mem.standup
93}
94
95async function saveStandup($: EngineInterface, s: Standup) {
96  mem.standup = s
97  await $.store.set(STANDUP_KEY, s).catch(() => {}) // the clock still runs in this session
98}
99
100// One second of the meter: the View the band draws, and the toasts now due.
101async function tick($: EngineInterface) {
102  const now = await $.clock.now()
103  const [last, usage, readings] = await Promise.all([$.state.get(LAST), $.session.usage(), $.state.get(READINGS)])
104  const step = last.value ?? null
105  const ttl = stepTtl(step)
106  sample(now, usage)
107  const j = judge(now)
108
109  const s = await loadStandup($, now)
110  const p = cfg.standupMs > 0 ? phase(s, now, cfg.standupMs) : undefined
111  const upChip = p ? standupChip(p) : undefined
112  const isDue = p?.phase === 'due'
113
114  const next: View = {
115    chips: [...chips(step, now, ttl, usage, readings.value ?? [], j), ...(upChip ? [upChip] : [])],
116    ...(isDue ? { standup: { tips: advice(s, p.sat, now), frame: Math.floor(now / 1000) % 2 } } : {}),
117  }
118  const key = JSON.stringify(next)
119  if (key !== mem.viewKey) {
120    mem.viewKey = key
121    await $.state.set(VIEW, next)
122  }
123
124  // The shared flags the toasts depend on: the sitting reminded, the night reminded.
125  const night = lateNight(now, cfg.bedtimeHour)
126  if (night && mem.nightChecked !== night) {
127    mem.nightChecked = night
128    const sent = await $.store.get(BEDTIME_KEY).catch(() => night) // unreadable: count it as sent
129    mem.memo.night = typeof sent === 'string' ? sent : ''
130  }
131  mem.memo.nudged = s.nudged
132
133  const snap: Snapshot = {
134    running: isRunning(now),
135    away: now - s.lastActiveAt >= IDLE_RESET_MS,
136    cache: step ? { at: step.at, left: step.at + ttl - now, warnMs: WARN_MS } : undefined,
137    context: { tokens: usage.context.tokens },
138    pace: usage.rateLimits.flatMap(r => {
139      const at = r.percentUsed >= 50 ? exhaustsAt(r, now, j.rates?.[r.kind]) : undefined
140      return at === undefined ? [] : [{ key: `${r.kind}:${r.resetsAt ?? ''}`, label: WINDOW_LABEL[r.kind] ?? r.kind, at: hhmmAt(at, now) ?? '', reset: hhmm(r.resetsAt, now) ?? undefined }]
141    }),
142    standup: isDue ? { key: nudgeKey(s), sat: duration(p.sat) } : undefined,
143    night: night ? { key: night, time: hhmmAt(now) ?? '' } : undefined,
144  }
145  const { toasts, memo } = decideToasts(snap, mem.memo)
146  if (memo.nudged !== mem.memo.nudged) await saveStandup($, { ...s, nudged: memo.nudged })
147  if (memo.night !== mem.memo.night) await $.store.set(BEDTIME_KEY, memo.night).catch(() => {})
148  mem.memo = memo
149  for (const t of toasts) $.ui.toast(t)
150}
151
152// The tick, with its failures counted rather than swallowed: after a few in a row the band says so
153// (its figures may be stale) and /meter names the last error. A session shown nowhere skips it.
154async function refresh($: EngineInterface) {
155  if (!mem.ticker) return
156  try {
157    await tick($)
158    if (mem.failures >= FAILING_AFTER) await setFailing($, false)
159    mem.failures = 0
160  } catch (error) {
161    mem.failures += 1
162    mem.lastError = error instanceof Error ? error.message : String(error)
163    if (mem.failures === FAILING_AFTER) await setFailing($, true).catch(() => {})
164  }
165}
166
167async function setFailing($: EngineInterface, failing: boolean) {
168  const v = (await $.state.get(VIEW)).value
169  if (v) await $.state.set(VIEW, { ...v, failing })
170}
171
172// A press on the stand-up panel's buttons: done or snooze the shared clock, then redraw.
173async function pressStandup($: EngineInterface, change: (s: Standup, t: number) => Standup) {
174  const t = await $.clock.now()
175  await saveStandup($, change(await loadStandup($, t), t))
176  await refresh($)
177}
178
179// Each mod carries its own copy (ADR-0001): a session shown on no surface (`claude -p`, a scheduled
180// task) is headless, and draws no band nor sends a toast.
181async function isShown($: EngineInterface): Promise<boolean> {
182  return (await $.session.surfaces()).length > 0
183}
184
185// Starts the once-a-second tick, once: at start in a shown session, else when a client attaches.
186async function startTicking($: EngineInterface) {
187  if (mem.ticker) return
188  mem.ticker = $.clock.every(1000, () => void refresh($))
189  await readCompact($)
190  await refresh($)
191}
192
193const FAILING_CHIP = { key: 'failing', text: '⚠ meter 数据可能过期(/meter 看原因)', short: '⚠ meter', color: 'yellow', rank: 2 }
194
195export const register: Register = (on, options) => {
196  cfg.ttlOption = options.cacheTtl
197  cfg.standupMs = num(options.standupMinutes, DEFAULTS.standupMinutes) * 60_000
198  cfg.bedtimeHour = num(options.bedtimeHour, DEFAULTS.bedtimeHour)
199  mem = fresh()
200
201  // Any prompt starts a main-thread turn; one the person sent is also the sign they are at the desk.
202  // (turn.start cannot mark it: it does not say whose turn, and a subagent's would never be cleared.)
203  on('prompt.submit', async ($, e, next) => {
204    const now = await $.clock.now()
205    mem.runningSince = now
206    if (e.origin.kind === 'composer' || e.origin.kind === 'bridge') {
207      await saveStandup($, onActivity(await loadStandup($, now), now)).catch(() => {})
208    }
209    return next(e)
210  })
211
212  on('session.start', async ($, e, next) => {
213    const r = await next(e)
214    $.ui.status(undefined) // the band replaces the status line an older version wrote
215    await $.command.register({ name: 'meter', description: '查看缓存、上下文、额度和费用明细' }).catch(() => {})
216    if (await isShown($)) await startTicking($)
217    return r
218  })
219
220  on('session.attach', async ($, e, next) => {
221    const r = await next(e)
222    await startTicking($)
223    return r
224  })
225
226  // Main-thread responses only: a subagent's requests keep a cache of their own.
227  on('turn.step', async function* ($, e, next) {
228    const result = yield* next(e)
229    if (e.agentId === undefined && result.usage) {
230      const at = await $.clock.now()
231      const hit = hitPercent(result.usage)
232      const { rateLimits } = await $.session.usage()
233      const { ttl, source } = ttlFor(cfg.ttlOption, rateLimits)
234      await $.state.set(LAST, { at, hitPercent: hit, ttl, ttlSource: source })
235      await refresh($)
236    }
237    return result
238  })
239
240  // The main conversation's turn is over; one reading of the context, for the turns left, and of
241  // the auto-compact window (a /model switch or a settings change moves it).
242  on('turn.complete', async ($, e, next) => {
243    const r = await next(e)
244    if (!e.agentId) {
245      mem.runningSince = 0
246      const { context } = (mem.ticker ? await readCompact($) : undefined) ?? (await $.session.usage())
247      if (context.tokens !== undefined) {
248        const held = (await $.state.get(READINGS)).value ?? []
249        await $.state.set(READINGS, [...held, { tokens: context.tokens }].slice(-HISTORY))
250      }
251      await refresh($)
252    }
253    return r
254  })
255
256  on('session.end', async ($, e, next) => {
257    await $.state.set(LAST, null) // /clear starts a fresh prefix
258    await $.state.set(READINGS, [])
259    mem.ticker?.cancel() // the next session.start starts it again, if shown
260    mem.ticker = undefined
261    mem.viewKey = ''
262    return next(e)
263  })
264
265  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
266    const rest = await next(e) // what other mods and Claude Code draw here stays
267    const v = (await $.state.get(VIEW)).value ?? null
268    if (e.props.hasSurvey || !v) return rest
269    const { Box, Text, Button } = $.ui.resolve(e)
270    const all = v.failing ? [...v.chips, FAILING_CHIP] : v.chips
271    const rows = layout(all, Math.max(10, e.props.bodyColumns - 2), Math.min(2, Math.max(1, e.props.maxRows)))
272
273    return (
274      <Box flexDirection="column">
275        {v.standup && (
276          <Box key="standup" flexDirection="row" columnGap={2} paddingX={1}>
277            <Box flexDirection="column">
278              {figure(v.standup.frame).map((r, i) => (
279                <Text key={`px${i}`} color="green">{r}</Text>
280              ))}
281            </Box>
282            <Box flexDirection="column">
283              {v.standup.tips.map((t, i) => (
284                <Text key={`tip${i}`} color={i === 0 ? 'yellow' : undefined} bold={i === 0}>{t}</Text>
285              ))}
286              <Box flexDirection="row" columnGap={1}>
287                <Button key="moved" label="已活动" variant="primary" onPress={() => pressStandup($, done)} />
288                <Button key="later" label="10 分钟后提醒" onPress={() => pressStandup($, snooze)} />
289              </Box>
290            </Box>
291          </Box>
292        )}
293        {rows.map((row, i) => (
294          <Box key={`row${i}`} flexDirection="row" paddingX={1}>
295            {row.flatMap((it, j) => [
296              j > 0 ? <Text key={`sep:${it.chip.key}`} dimColor>{SEP}</Text> : null,
297              <Text key={it.chip.key} color={it.chip.color} dimColor={it.chip.dim} bold={it.chip.key === 'context'} wrap="truncate">
298                {it.label}
299              </Text>,
300            ])}
301          </Box>
302        ))}
303        {rest}
304      </Box>
305    )
306  })
307
308  on('command.run', { command: 'meter' }, async $ => {
309    const now = await $.clock.now()
310    const step = (await $.state.get(LAST)).value ?? null
311    const usage = (await readCompact($)) ?? (await $.session.usage())
312    const { context, rateLimits, cost } = usage
313    const j = judge(now)
314    const out: string[] = [line(step, now, stepTtl(step), usage, (await $.state.get(READINGS)).value ?? [], j), '']
315    out.push(cacheDetail(step, now))
316    const { window, percent } = contextScale(context, mem.compact)
317    out.push(`上下文:${context.tokens !== undefined ? kCount(context.tokens) : '–'} / ${kCount(window)}(${percent ?? '–'}%)`)
318    const cw = mem.compact
319    out.push(cw
320      ? `压缩窗口:${kCount(cw.window)}(来源 ${cw.source}),${cw.threshold !== undefined ? `${kCount(cw.threshold)} 时自动压缩` : '自动压缩已关'};模型窗口 ${kCount(context.window)}`
321      : `压缩窗口:读不到,按 ${kCount(window)} 算;模型窗口 ${kCount(context.window)}`)
322    for (const c of context.breakdown?.categories ?? []) {
323      if (c.tokens > 0) out.push(`  ${c.name}: ${kCount(c.tokens)}${c.isDeferred ? '(按需加载)' : ''}`)
324    }
325    for (const r of rateLimits) {
326      const runsOut = exhaustsAt(r, now, j.rates?.[r.kind])
327      const reset = hhmm(r.resetsAt, now)
328      out.push(`额度 ${WINDOW_LABEL[r.kind] ?? r.kind}:已用 ${r.percentUsed}%${reset ? `,${reset} 重置` : ''}${runsOut ? `;按当前速度约 ${hhmmAt(runsOut, now)} 用完` : ''}`)
329    }
330    if (cost) out.push(`本会话费用:$${cost.usd.toFixed(2)}`)
331    if (cfg.standupMs > 0) {
332      const p = phase(await loadStandup($, now), now, cfg.standupMs)
333      out.push(p.phase === 'away' ? '久坐:超过 10 分钟没发消息,下次发消息时重新计时' : `久坐:已坐 ${duration(p.sat)},每 ${cfg.standupMs / 60_000} 分钟提醒一次`)
334    }
335    if (mem.failures > 0) out.push(`刷新失败 ${mem.failures} 次,最后一次:${mem.lastError}`)
336    return { text: out.join('\n') }
337  })
338}
339
hooks/alerts.ts 59 lines
1// Every toast the meter sends, decided in one place from one snapshot, so the rules (once each,
2// never mid-turn for the person, never to an empty desk for the cache) are written once and tested.
3import { clock, kCount } from './format'
4
5export const CHEAP_REWRITE = 20_000 // context tokens under which a cache rewrite is not worth a toast
6
7export type Snapshot = {
8  /** A main-thread turn is under way: reminders about the person wait for it to end. */
9  running: boolean
10  /** Ten minutes without a prompt: nobody is there to act on a cache warning. */
11  away: boolean
12  /** The last main-thread response's `at`, and how long its cache has left. */
13  cache?: { at: number; left: number; warnMs: number }
14  context: { tokens?: number }
15  /** Windows the current pace runs out before their reset; `key` is the window and its reset. */
16  pace: { key: string; label: string; at: string; reset?: string }[]
17  /** The stand-up reminder while due; `key` is the sitting and snooze it is for. */
18  standup?: { key: string; sat: string }
19  /** The late-hour night we are in, and the clock time. */
20  night?: { key: string; time: string }
21}
22
23// What has been sent already. `nudged` and `night` are shared across sessions through $.store.
24export type Memo = { cacheFor: number; pace: string[]; nudged: string; night: string }
25export const EMPTY_MEMO: Memo = { cacheFor: 0, pace: [], nudged: '', night: '' }
26
27export function decideToasts(s: Snapshot, m: Memo): { toasts: string[]; memo: Memo } {
28  const toasts: string[] = []
29  const memo = { ...m }
30
31  // The cache: worth a toast only when the rewrite costs something (its price is the whole
32  // context) and someone is there to send the next message.
33  const tokens = s.context.tokens ?? 0
34  if (s.cache && s.cache.at !== m.cacheFor && tokens >= CHEAP_REWRITE && !s.away && s.cache.left > 0 && s.cache.left <= s.cache.warnMs) {
35    memo.cacheFor = s.cache.at
36    toasts.push(`提示缓存还剩 ${clock(s.cache.left)} 过期:现在发下一条消息,否则要重新写入约 ${kCount(tokens)} token`)
37  }
38
39  // The rate limits: once per window and reset.
40  for (const p of s.pace) {
41    if (memo.pace.includes(p.key)) continue
42    memo.pace = [...memo.pace, p.key].slice(-8)
43    toasts.push(`${p.label}额度按当前速度约 ${p.at} 用完${p.reset ? `(${p.reset} 重置)` : ''}:可以降低 effort 或换小一点的模型`)
44  }
45
46  // The person: never in the middle of a turn.
47  if (!s.running) {
48    if (s.standup && s.standup.key !== m.nudged) {
49      memo.nudged = s.standup.key
50      toasts.push(`已经连续坐了 ${s.standup.sat},起来活动 3 分钟吧`)
51    }
52    if (s.night && s.night.key !== m.night) {
53      memo.night = s.night.key
54      toasts.push(`已经 ${s.night.time} 了:收个尾,早点休息`)
55    }
56  }
57  return { toasts, memo }
58}
59
hooks/format.ts 242 lines
1import type { ModelUsage, SessionUsage } from 'claude-code'
2
3import type { Chip, LastStep, Reading } from '../types'
4
5export const WARN_MS = 60_000 // the cache line turns to a warning this long before expiry
6
7export function ttlMs(option: unknown): number {
8  return option === '5m' ? 5 * 60_000 : 60 * 60_000
9}
10
11// The TTL a cache write gets now and why: this plugin's `cacheTtl` option when it is `1h` or `5m`,
12// else inferred from the plan. A subscription gets 1h within plan usage and 5m on usage credits,
13// and a rate-limit window at 100% stands for the latter. The mod reads nothing from the
14// environment or settings.json: whoever fixes the TTL there sets `cacheTtl` to match.
15export function ttlFor(option: unknown, rateLimits: readonly { percentUsed: number }[]): { ttl: number; source: string } {
16  if (option === '1h' || option === '5m') return { ttl: ttlMs(option), source: '插件设置' }
17  return rateLimits.some(r => r.percentUsed >= 100)
18    ? { ttl: ttlMs('5m'), source: '推断:额度已用满,按超额 5 分钟' }
19    : { ttl: ttlMs('1h'), source: '推断:额度内 1 小时' }
20}
21
22// Share of the prompt the cache served: read / (uncached + read + written).
23export function hitPercent(u: ModelUsage): number | null {
24  const total = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
25  return total > 0 ? Math.round((u.cache_read_input_tokens / total) * 100) : null
26}
27
28export function clock(ms: number): string {
29  const s = Math.max(0, Math.ceil(ms / 1000))
30  const h = Math.floor(s / 3600)
31  const m = Math.floor((s % 3600) / 60)
32  const ss = String(s % 60).padStart(2, '0')
33  return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
34}
35
36export function kCount(n: number): string {
37  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
38  return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
39}
40
41const WEEKDAY = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
42
43// A local clock time, with its weekday when it is not today (a weekly window resets days away),
44// or its month and day when it is six days or more off. `now` absent: the time alone.
45export function hhmm(iso: string | undefined, now?: number): string | null {
46  if (!iso) return null
47  const d = new Date(iso)
48  if (Number.isNaN(d.getTime())) return null
49  const time = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
50  if (now === undefined || d.toDateString() === new Date(now).toDateString()) return time
51  return Math.abs(d.getTime() - now) < 6 * 24 * 3600_000 ? `${WEEKDAY[d.getDay()]}${time}` : `${d.getMonth() + 1}/${d.getDate()} ${time}`
52}
53
54export const hhmmAt = (ms: number, now?: number) => hhmm(new Date(ms).toISOString(), now)
55
56export const WINDOW_LABEL: Record<string, string> = { five_hour: '5小时', seven_day: '7天', spend_limit: '额度' }
57
58// The context forecast (from token-weather): icon, word and color by how full the window is.
59const FORECAST = [
60  { upTo: 25, icon: '☀', word: '晴', color: 'yellow' },
61  { upTo: 50, icon: '☁', word: '多云', color: 'cyan' },
62  { upTo: 75, icon: '☂', word: '阵雨', color: 'blue' },
63  { upTo: 90, icon: '⛈', word: '雷雨', color: 'magenta' },
64  { upTo: Infinity, icon: '⚠', word: '该压缩了', color: 'red' },
65] as const
66export const forecast = (percent: number) => FORECAST.find(f => percent < f.upTo) ?? FORECAST[4]
67
68// The auto-compact window Claude Code uses (`autoCompactWindow`, else the model's) and where
69// auto-compaction runs (absent when it is off), as the context breakdown reports them.
70export type Compact = { window: number; source: string; threshold?: number }
71
72const FALLBACK_WINDOW = 400_000 // the scale when the breakdown cannot be read, at most the model's window
73
74// The window the context is measured against, its share of it, and where the turns left count to:
75// auto-compaction, else the full window. Claude Code compacts on its own, so nothing warns.
76export function contextScale(context: SessionUsage['context'], compact?: Compact): { window: number; percent?: number; target: number; compacts: boolean } {
77  const window = compact && compact.window > 0 ? compact.window : Math.min(FALLBACK_WINDOW, context.window || FALLBACK_WINDOW)
78  const percent = context.tokens !== undefined ? Math.round((context.tokens / window) * 100) : undefined
79  const compacts = compact?.threshold !== undefined
80  return { window, percent, target: compact?.threshold ?? window, compacts }
81}
82
83// How many more turns, at the recent average growth, until the context reaches `target` tokens.
84// Only growth counts: a /compact or /clear shrinks the context but says nothing about the pace.
85export function turnsLeft(history: readonly Reading[], target: number | undefined): number | undefined {
86  const grows = history.slice(-7).flatMap((r, i, a) => (i > 0 && r.tokens > (a[i - 1]?.tokens ?? 0) ? [r.tokens - (a[i - 1]?.tokens ?? 0)] : []))
87  const now = history.at(-1)?.tokens
88  if (grows.length === 0 || now === undefined || target === undefined) return undefined
89  const room = target - now
90  if (room <= 0) return undefined
91  return Math.ceil(room / (grows.reduce((a, b) => a + b, 0) / grows.length))
92}
93
94const WINDOW_MS: Record<string, number> = { five_hour: 5 * 3600_000, seven_day: 7 * 24 * 3600_000 }
95const RECENT_MS = 30 * 60_000 // the stretch the recent pace is read over
96const RECENT_MIN_MS = 10 * 60_000 // less than this of it says too little
97
98export type Sample = { t: number; pct: number }
99
100// Percent per millisecond over the last half hour of samples, or undefined with under ten minutes
101// of them. Zero when nothing was used: at that pace the window never runs out.
102export function recentRate(samples: readonly Sample[], now: number): number | undefined {
103  const recent = samples.filter(s => s.t >= now - RECENT_MS)
104  const first = recent[0]
105  const lastOne = recent.at(-1)
106  if (!first || !lastOne || lastOne.t - first.t < RECENT_MIN_MS) return undefined
107  return Math.max(0, (lastOne.pct - first.pct) / (lastOne.t - first.t))
108}
109
110// When a rate-limit window runs out, if that comes before its reset: at the recent pace (`rate`,
111// percent per ms) when there is one, else at the window's average pace so far, which needs a
112// tenth of the window behind it. Undefined for a window with no known length.
113export function exhaustsAt(r: { kind: string; percentUsed: number; resetsAt?: string }, now: number, rate?: number): number | undefined {
114  const length = WINDOW_MS[r.kind]
115  const reset = r.resetsAt ? Date.parse(r.resetsAt) : NaN
116  if (!length || Number.isNaN(reset) || r.percentUsed <= 0 || r.percentUsed >= 100) return undefined
117  let at: number
118  if (rate !== undefined) {
119    if (rate <= 0) return undefined
120    at = now + (100 - r.percentUsed) / rate
121  } else {
122    const elapsed = length - (reset - now)
123    if (elapsed < length / 10) return undefined
124    at = now + ((100 - r.percentUsed) / r.percentUsed) * elapsed
125  }
126  return at < reset ? at : undefined
127}
128
129// A rate-limit window as a five-cell meter.
130export function meter(percent: number, width = 5): string {
131  const full = Math.min(width, Math.round((percent / 100) * width))
132  return '▰'.repeat(full) + '▱'.repeat(width - full)
133}
134
135// Cells a string takes: CJK, fullwidth forms and the weather symbols count two.
136export function cells(text: string): number {
137  let n = 0
138  for (const ch of text) n += /[ᄀ-ᅟ☀-➿⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(ch) ? 2 : 1
139  return n
140}
141
142export function cacheChip(last: LastStep | null, now: number, ttl: number): Chip {
143  if (last === null) return { key: 'cache', text: '❄ 缓存 –', short: '❄ –', dim: true, rank: 2 }
144  const left = last.at + ttl - now
145  if (left <= 0) return { key: 'cache', text: '❄ 缓存已过期', short: '❄ 过期', color: 'red', rank: 2 }
146  const isSoon = left <= WARN_MS
147  return { key: 'cache', text: `❄ 缓存 ${clock(left)}${isSoon ? ' 快过期' : ''}`, short: `❄ ${clock(left)}`, color: isSoon ? 'yellow' : 'cyan', rank: 2 }
148}
149
150// What the chips are judged against: the auto-compact window when it is known, and each rate-limit
151// window's recent pace (percent per ms) where one is known.
152export type Judge = { compact?: Compact; rates?: Readonly<Record<string, number | undefined>> }
153export const DEFAULT_JUDGE: Judge = {}
154
155// Every part the engine has a figure for, in the order the band shows them.
156export function chips(last: LastStep | null, now: number, ttl: number, usage: SessionUsage, history: readonly Reading[] = [], judge: Judge = DEFAULT_JUDGE): Chip[] {
157  const out: Chip[] = []
158  const { context, rateLimits, cost } = usage
159  const { window, percent, target, compacts } = contextScale(context, judge.compact)
160  if (percent !== undefined && context.tokens !== undefined) {
161    const f = forecast(percent)
162    out.push({
163      key: 'context', rank: 1, color: f.color,
164      text: `${f.icon} ${f.word} 上下文 ${percent}% ${kCount(context.tokens)}/${kCount(window)}`,
165      short: `${f.icon} ${kCount(context.tokens)}`,
166    })
167  }
168  out.push(cacheChip(last, now, ttl))
169  for (const r of rateLimits) {
170    const pct = Math.round(r.percentUsed)
171    const label = WINDOW_LABEL[r.kind] ?? r.kind
172    const reset = hhmm(r.resetsAt, now)
173    const runsOut = exhaustsAt(r, now, judge.rates?.[r.kind])
174    out.push({
175      key: `limit:${r.kind}`, rank: 3, color: pct >= 90 ? 'red' : pct >= 70 || runsOut ? 'yellow' : undefined,
176      text: `${label} ${meter(pct)} ${pct}%${runsOut ? ` 预计${hhmmAt(runsOut, now)}用完` : ''}${reset ? ` ${reset}重置` : ''}`,
177      short: `${label} ${pct}%${runsOut ? '!' : ''}`,
178    })
179  }
180  // Turns until auto-compaction (or a full window), in place of a sparkline that took reading.
181  const left = turnsLeft(history, target)
182  if (left !== undefined) out.push({ key: 'turns', text: compacts ? `约 ${left} 轮后自动压缩` : `约 ${left} 轮到 ${kCount(target)}`, short: `${left}轮`, color: left <= 3 ? 'yellow' : undefined, dim: left > 3, rank: 5 })
183  // The hit rate needs no action while the cache works; it shows only when it looks broken.
184  if (last?.hitPercent != null && last.hitPercent < 70) out.push({ key: 'hit', text: `命中 ${last.hitPercent}% 缓存可能失效`, short: `命中${last.hitPercent}%`, color: 'yellow', rank: 4 })
185  // A subscription's figure in API prices: informative, never a reason to act, so last to go.
186  if (cost) out.push({ key: 'cost', text: `$${cost.usd.toFixed(2)}`, short: `$${cost.usd.toFixed(2)}`, dim: true, rank: 8 })
187  return out
188}
189
190export const SEP = ' │ '
191
192// Fits the chips into at most `maxRows` rows of `columns` cells: full text where everything fits,
193// the short forms where it does not, then the lowest-ranked chips dropped until it fits.
194export function layout(all: readonly Chip[], columns: number, maxRows = 2): { chip: Chip; label: string }[][] {
195  const pack = (items: { chip: Chip; label: string }[]) => {
196    const rows: { chip: Chip; label: string }[][] = []
197    let used = 0
198    for (const it of items) {
199      const w = cells(it.label)
200      const row = rows.at(-1)
201      if (row && used + cells(SEP) + w <= columns) {
202        row.push(it)
203        used += cells(SEP) + w
204      } else {
205        rows.push([it])
206        used = w
207      }
208    }
209    return rows
210  }
211  let kept = [...all]
212  for (;;) {
213    for (const useShort of [false, true]) {
214      const rows = pack(kept.map(chip => ({ chip, label: useShort ? chip.short : chip.text })))
215      if (rows.length <= maxRows) return rows
216    }
217    if (kept.length <= 1) return pack(kept.map(chip => ({ chip, label: chip.short })))
218    const worst = Math.max(...kept.map(c => c.rank))
219    const at = kept.map(c => c.rank).lastIndexOf(worst)
220    kept = kept.filter((_, i) => i !== at)
221  }
222}
223
224// The whole meter as one plain line: /meter's first line.
225export function line(last: LastStep | null, now: number, ttl: number, usage: SessionUsage, history: readonly Reading[] = [], judge: Judge = DEFAULT_JUDGE): string {
226  return chips(last, now, ttl, usage, history, judge).map(c => c.text).join(SEP)
227}
228
229// A step stored by an older version and kept across a reload has no TTL of its own: it counts down 1h.
230export function stepTtl(step: LastStep | null): number {
231  return step?.ttl ?? ttlMs('1h')
232}
233
234// /meter's cache line; an older step (see stepTtl) names no source.
235export function cacheDetail(step: LastStep | null, now: number): string {
236  if (!step) return '提示缓存:主线程还没有响应'
237  const ttl = stepTtl(step)
238  const source = step.ttlSource ? `(${step.ttlSource})` : ''
239  const left = step.at + ttl - now
240  return `提示缓存:上次主线程响应在 ${clock(now - step.at)} 前,TTL ${ttl / 60_000} 分钟${source},${left > 0 ? `还剩 ${clock(left)}` : '已过期'};命中率 ${step.hitPercent ?? '–'}%`
241}
242
hooks/standup.ts 127 lines
1// Stand-up reminder: how long the person has sat at Claude Code, kept in $.store so every open
2// session shares one clock. Ten minutes with no prompt counts as a break and starts it over.
3import type { Chip } from '../types'
4
5const MINUTE = 60_000
6export const IDLE_RESET_MS = 10 * MINUTE // no prompt this long: they were away, the next prompt restarts the clock
7export const SNOOZE_MS = 10 * MINUTE
8const SOON_MS = 10 * MINUTE // the chip turns yellow this long before the reminder
9
10// `day` / `breaks`: the local date and how many breaks were taken on it, for the encouragement line.
11export type Standup = { since: number; lastActiveAt: number; snoozeUntil: number; nudged: string; day: string; breaks: number }
12export type Phase = 'away' | 'ok' | 'soon' | 'due'
13
14/** The local calendar date, `YYYY-MM-DD`. */
15export function dayOf(now: number): string {
16  const d = new Date(now)
17  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
18}
19
20export const fresh = (now: number): Standup => ({ since: now, lastActiveAt: now, snoozeUntil: 0, nudged: '', day: dayOf(now), breaks: 0 })
21
22/** A stored value as a Standup; anything else (nothing stored yet, an older shape) starts fresh. */
23export function parse(value: unknown, now: number): Standup {
24  const v = value as Partial<Standup> | undefined
25  const isOk = v && typeof v.since === 'number' && typeof v.lastActiveAt === 'number'
26  if (!isOk) return fresh(now)
27  return { since: v.since!, lastActiveAt: v.lastActiveAt!, snoozeUntil: v.snoozeUntil ?? 0, nudged: v.nudged ?? '', day: v.day ?? dayOf(now), breaks: v.breaks ?? 0 }
28}
29
30/** A new sitting after a break, counting the break toward today. */
31function afterBreak(s: Standup, now: number): Standup {
32  const today = dayOf(now)
33  return { ...fresh(now), breaks: (s.day === today ? s.breaks : 0) + 1 }
34}
35
36/** A prompt from the person: after a break (ten minutes without one) the clock starts over. */
37export function onActivity(s: Standup, now: number): Standup {
38  return now - s.lastActiveAt >= IDLE_RESET_MS ? afterBreak(s, now) : { ...s, lastActiveAt: now }
39}
40
41/** Breaks taken today; a count from an earlier day is none. */
42export const breaksToday = (s: Standup, now: number) => (s.day === dayOf(now) ? s.breaks : 0)
43
44export const done = (s: Standup, now: number): Standup => afterBreak(s, now)
45export const snooze = (s: Standup, now: number): Standup => ({ ...s, snoozeUntil: now + SNOOZE_MS })
46
47export function phase(s: Standup, now: number, intervalMs: number): { phase: Phase; sat: number } {
48  const sat = Math.max(0, now - s.since)
49  if (now - s.lastActiveAt >= IDLE_RESET_MS) return { phase: 'away', sat }
50  if (sat >= intervalMs && now >= s.snoozeUntil) return { phase: 'due', sat }
51  if (sat >= intervalMs - SOON_MS) return { phase: 'soon', sat } // also while snoozed
52  return { phase: 'ok', sat }
53}
54
55/** The one reminder per sitting (and per snooze) the toast goes out for. */
56export const nudgeKey = (s: Standup) => `${s.since}:${s.snoozeUntil}`
57
58export function duration(ms: number): string {
59  const m = Math.floor(ms / MINUTE)
60  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
61}
62
63export function standupChip(p: { phase: Phase; sat: number }): Chip | undefined {
64  const d = duration(p.sat)
65  if (p.phase === 'away') return undefined
66  if (p.phase === 'due') return { key: 'standup', text: `起来活动下!已坐 ${d}`, short: `起来!${d}`, color: 'red', rank: 1 }
67  if (p.phase === 'soon') return { key: 'standup', text: `已坐 ${d} 快该起来了`, short: `坐${d}`, color: 'yellow', rank: 3 }
68  return { key: 'standup', text: `已坐 ${d}`, short: `坐${d}`, dim: true, rank: 7 }
69}
70
71// Two frames of an 8×6 pixel figure: arms down, then stretching up. '#' is a lit pixel.
72const FRAMES: readonly (readonly string[])[] = [
73  ['...##...', '...##...', '..####..', '.#.##.#.', '..#..#..', '..#..#..'],
74  ['.#.##.#.', '.#.##.#.', '..####..', '...##...', '..#..#..', '.#....#.'],
75]
76
77/** Pixel rows two at a time as half blocks: one text row shows two pixel rows. */
78export function halfBlocks(grid: readonly string[]): string[] {
79  const out: string[] = []
80  for (let y = 0; y < grid.length; y += 2) {
81    const top = grid[y] ?? ''
82    const bottom = grid[y + 1] ?? ''
83    let row = ''
84    for (let x = 0; x < Math.max(top.length, bottom.length); x++) {
85      const t = top[x] === '#'
86      const b = bottom[x] === '#'
87      row += t && b ? '█' : t ? '▀' : b ? '▄' : ' '
88    }
89    out.push(row)
90  }
91  return out
92}
93
94// The frames never change: drawn once, not on every redraw.
95const FIGURES = FRAMES.map(halfBlocks)
96export const figure = (frame: number): string[] => FIGURES[frame % FIGURES.length] ?? FIGURES[0]!
97
98// One suggestion per sitting, in turn: the same sentence every hour soon goes unread.
99const TIPS = [
100  '站起来走两步,伸个懒腰,3 分钟就够。',
101  '看向 6 米外的地方 20 秒,让眼睛放松。',
102  '去倒杯水,顺便走动一下。',
103  '转转脖子、耸耸肩,放松肩颈。',
104  '站起来做 10 个深蹲,或者原地踏步一分钟。',
105] as const
106
107/** The words beside the figure, so the picture is never the only message. */
108export function advice(s: Standup, sat: number, now: number): string[] {
109  const n = breaksToday(s, now)
110  return [
111    `你已经连续坐了 ${duration(sat)}。`,
112    TIPS[Math.floor(s.since / MINUTE) % TIPS.length] ?? TIPS[0],
113    ...(n > 0 ? [`今天已经活动了 ${n} 次,继续保持。`] : []),
114  ]
115}
116
117/**
118 * The night a late-hour reminder belongs to (the evening's date), or undefined outside the late
119 * hours: from `hour` until 5 in the morning. `hour` 0 turns it off.
120 */
121export function lateNight(now: number, hour: number): string | undefined {
122  if (hour <= 0 || hour > 23) return undefined
123  const h = new Date(now).getHours()
124  if (h >= hour) return dayOf(now)
125  return h < 5 ? dayOf(now - 24 * 3600_000) : undefined
126}
127
types/index.d.ts 21 lines
1// The last main-thread response: when it finished, how much of its prompt the cache served,
2// and the TTL its cache write got (fixed at that moment: a later overage does not shorten it).
3// `ttl` / `ttlSource` are absent on a step stored by an older version and kept across a reload.
4export type LastStep = { at: number; hitPercent: number | null; ttl?: number; ttlSource?: string }
5// Context tokens after each main-thread turn, newest last, for the turns-left estimate.
6export type Reading = { tokens: number }
7
8// One piece of the band. `short` is what it says when room runs out; `rank` 1 is kept longest.
9export type Chip = { key: string; text: string; short: string; color?: string; dim?: boolean; rank: number }
10
11// What the band shows, worked out once a second by the tick and only read while drawing.
12// `standup`: the reminder panel while it is due, with the figure's frame; `failing`: the tick has
13// failed several times in a row, so the figures may be stale.
14export type View = { chips: Chip[]; standup?: { tips: string[]; frame: number }; failing?: boolean }
15
16declare module 'claude-code' {
17  interface PluginState {
18    'session-meter': { last: LastStep | null; readings: Reading[]; view: View | null }
19  }
20}
21