入力欄の下に 5h / 週 / Fable の上限とコンテキスト使用率を % で表示する

curl -fsSL https://raw.githubusercontent.com/tett23/dotfiles/HEAD/install.sh | sh
これだけで以下が完了します (冪等。失敗したら同じコマンドを再実行)。
~/dotfiles への clone (HTTPS)bootstrap.sh: Nix → nix-darwin / home-manager / GUI アプリ / dotfiles のリンク (途中で sudo のパスワードを聞かれます)mise install: 言語 / ツールDOTFILES / DOTFILES_REPO / DOTFILES_BRANCH / DOTFILES_REMOTE 環境変数で clone 先などを上書きできます。 DOTFILES_SKIP_HASKELL=1 で、ghcup での ghc・cabal のインストール (大きい) を省けます。
clone は SSH 鍵が無くてもできるよう HTTPS で行い、その後 origin を SSH の URL (git@github.com:tett23/dotfiles.git) に切り替えます。手元で git pull / push するには SSH 鍵の設定が必要です (install.sh の再実行は SSH 鍵が無くても動きます)。
コミット済みの ADR の変更を防ぐ git の hook (adr-guard。mise install で入る) を有効にします。
git config core.hooksPath .githooks
テストはツールごとに置き場所が違います。CI (.github/workflows/ci.yml) では zsh のテストを実行します。
| 対象 | 置き場所 | 実行コマンド | ||
|---|---|---|---|---|
| zsh | zsh/tests/ | `for t in zsh/tests/*.test.zsh; do zsh $t \ | \ | echo "FAIL $t"; done (1 つだけなら zsh zsh/tests/<名前>.test.zsh`) |
| usage-hint (Claude Code の mod) | .claude/mods/usage-hint/tests/ | claude plugin test .claude/mods/usage-hint |
usage-hint の型検査は、.claude/mods/usage-hint で tsc --noEmit -p . を実行します (tsc は mise で入れる TypeScript 7。 型定義は Claude Code が mod を読み込んだときに生成します)。
現在の仕様は docs/specifications.md、依存の一覧は dependencies.md、 設計判断は docs/adr を参照。
hooks/register.tsx 248 lines1import { atom, read, update } from 'claude-code'
2import type {
3 ElementConstructor,
4 EngineInterface,
5 Register,
6 RenderElement,
7 SessionRateLimit,
8 TextProps,
9 Timer,
10} from 'claude-code'
11
12import type { Limit, Snapshot } from '../types'
13import type { Level, Segment } from './format'
14import {
15 SEPARATOR,
16 estimatePercent,
17 fableFromUsage,
18 keepFable,
19 parseLimits,
20 restoreLimits,
21 usageSegments,
22 withLimit,
23} from './format'
24
25const EMPTY: Snapshot = { contextPercent: null, rateLimits: [] }
26
27const snapshot = atom({ plugin: 'usage-hint', key: 'snapshot' } as const, EMPTY)
28
29const STORE_KEY = 'rateLimits'
30
31const toLimits = (rateLimits: readonly SessionRateLimit[]): Limit[] =>
32 rateLimits.map(({ kind, percentUsed, resetsAt }) => ({ kind, percentUsed, resetsAt }))
33
34// 最初の API 応答の前は、窓を前回保存した値から、コンテキストをローカルの推定から作る
35// (docs/adr/0008)
36const initialSnapshot = async ($: EngineInterface): Promise<Snapshot> => {
37 const { context, rateLimits } = await $.session.usage()
38 const contextPercent =
39 context.percent ??
40 (await $.session
41 .usage({ breakdown: 'summary' })
42 .then(({ context: estimated }) =>
43 estimated.breakdown
44 ? estimatePercent(estimated.breakdown.totalTokens, estimated.window)
45 : null,
46 )
47 .catch(() => null))
48 const limits =
49 rateLimits.length > 0
50 ? toLimits(rateLimits)
51 : restoreLimits(parseLimits(await $.store.get(STORE_KEY)), await $.clock.now())
52
53 return { contextPercent, rateLimits: limits }
54}
55
56// 表示の値を session.usage() から作りなおす。窓が空なら直前の窓を使い、どちらもリセット時刻を
57// 過ぎた窓は 0% にする。読み取りに失敗したときは直前の表示を残す。保存はしない (docs/adr/0063)
58const refresh = async ($: EngineInterface): Promise<void> => {
59 const usage = await $.session.usage().catch(() => undefined)
60 if (!usage) {
61 return
62 }
63 const now = await $.clock.now()
64 await update($, snapshot, previous => ({
65 contextPercent: usage.context.percent ?? previous.contextPercent,
66 rateLimits: restoreLimits(
67 usage.rateLimits.length > 0
68 ? keepFable(toLimits(usage.rateLimits), previous.rateLimits)
69 : previous.rateLimits,
70 now,
71 ),
72 }))
73}
74
75// Claude Code の /usage と同じ使用量の API。Fable の週のウィンドウは、API の応答 (session.measure) には
76// Fable にリクエストしたときしか入らないので、ここから取る (docs/adr/0074)
77const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
78
79const parseJson = (text: string): unknown => {
80 try {
81 return JSON.parse(text)
82 } catch {
83 return undefined
84 }
85}
86
87// 使用量の API から Fable のウィンドウを取り、表示と保存に反映する。認証の handle が無い・失敗・形が違うときは何もしない
88const refreshFable = async ($: EngineInterface): Promise<void> => {
89 const authorization = await $.session.authorize().catch(() => null)
90 if (!authorization) {
91 return
92 }
93 const response = await $.http
94 .fetch(USAGE_URL, { auth: authorization.handle })
95 .catch(() => undefined)
96 const fable = response?.ok ? fableFromUsage(parseJson(response.text)) : undefined
97 if (!fable) {
98 return
99 }
100 const now = await $.clock.now()
101 await update($, snapshot, previous => ({
102 ...previous,
103 rateLimits: restoreLimits(withLimit(previous.rateLimits, fable), now),
104 }))
105 await $.store.set(STORE_KEY, (await read($, snapshot)).rateLimits)
106}
107
108const REFRESH_INTERVAL_MS = 60_000
109// 使用量の API は、1 分ごとの更新の 5 回に 1 回 (5 分ごと) だけ問い合わせる (docs/adr/0074)
110const FABLE_EVERY = 5
111
112// 1 分ごとの更新。どの画面も表示していない間は更新しない (docs/adr/0063)
113const refreshIfShown = async ($: EngineInterface, withFable: boolean): Promise<void> => {
114 const surfaces = await $.session.surfaces().catch(() => [])
115 if (surfaces.length > 0) {
116 await refresh($)
117 if (withFable) {
118 await refreshFable($)
119 }
120 }
121}
122
123let refreshTimer: Timer | undefined
124let refreshTicks = 0
125
126const stopRefresh = () => {
127 refreshTimer?.cancel()
128 refreshTimer = undefined
129}
130
131// warning は暗めの黄色、danger は暗めの赤、それ以外は dim (docs/adr/0005, 0060)。ラベルは太字 (docs/adr/0006)
132const LEVEL_PROPS: Record<Level, TextProps> = {
133 normal: { dimColor: true },
134 warning: { color: '#b39020' },
135 danger: { color: '#b5403a' },
136}
137
138const toText =
139 (Text: ElementConstructor<TextProps>) =>
140 ({ label, value, level }: Segment): RenderElement => (
141 <Text {...LEVEL_PROPS[level]}>
142 <Text bold>{label}</Text>
143 {` ${value}`}
144 </Text>
145 )
146
147const interleave = <T,>(items: readonly T[], separator: T): T[] =>
148 items.flatMap((item, index) => (index === 0 ? [item] : [separator, item]))
149
150export const register: Register = on => {
151 on('session.start', async ($, e, next) => {
152 await $.command.register({
153 name: 'usage-hint',
154 description: 'usage-hint が受け取ったレートリミット窓をそのまま表示する',
155 })
156
157 const result = await next(e)
158 const initial = await initialSnapshot($).catch(() => undefined)
159 if (initial) {
160 await update($, snapshot, () => initial)
161 }
162 await refresh($)
163 await refreshFable($)
164 stopRefresh()
165 refreshTicks = 0
166 refreshTimer = $.clock.every(REFRESH_INTERVAL_MS, () => {
167 refreshTicks += 1
168 void refreshIfShown($, refreshTicks % FABLE_EVERY === 0)
169 })
170
171 return result
172 })
173
174 // /clear は会話が終わるだけで、同じプロセスで次の会話が続き session.start は来ないので止めない (docs/adr/0065)
175 on('session.end', async ($, e, next) => {
176 if (e.reason !== 'clear') {
177 stopRefresh()
178 }
179
180 return next(e)
181 })
182
183 on('session.measure', async ($, e, next) => {
184 // 窓が空の報告では直前の窓を残す (docs/adr/0008)。Fable が無ければ直前の Fable を残す (docs/adr/0074)
185 const previous = await read($, snapshot)
186 const rateLimits =
187 e.rateLimits.length > 0
188 ? keepFable(toLimits(e.rateLimits), previous.rateLimits)
189 : previous.rateLimits
190 if (e.rateLimits.length > 0) {
191 await $.store.set(STORE_KEY, rateLimits)
192 }
193 await update($, snapshot, () => ({
194 contextPercent: e.context.percent ?? null,
195 rateLimits,
196 }))
197
198 return next(e)
199 })
200
201 on('command.run', { command: 'usage-hint' }, async $ => {
202 const { rateLimits, contextPercent } = await read($, snapshot)
203 const rows = rateLimits.map(
204 ({ kind, percentUsed, resetsAt }) =>
205 `- ${kind}: ${percentUsed}%${resetsAt ? ` (reset ${resetsAt})` : ''}`,
206 )
207
208 return {
209 text: [
210 `context: ${contextPercent ?? '--'}%`,
211 rows.length === 0 ? 'rateLimits: (まだ受信していません)' : 'rateLimits:',
212 ...rows,
213 ].join('\n'),
214 }
215 })
216
217 // terminal: 項目ごとに色を付けるため tail ではなくヒント行ごと描く (docs/adr/0005)
218 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
219 if (e.surface !== 'terminal') {
220 return next(e)
221 }
222 const { Box, Text } = $.ui.resolve(e)
223 const segments = usageSegments(await read($, snapshot))
224 const hint = e.props.hint === '' ? [] : [<Text dimColor>{e.props.hint}</Text>]
225
226 return (
227 <Box flexDirection="row">
228 {interleave([...hint, ...segments.map(toText(Text))], <Text dimColor>{SEPARATOR}</Text>)}
229 </Box>
230 )
231 })
232
233 // desktop は PromptHint を描かないため、入力欄のすぐ上の帯に出す (docs/adr/0004)
234 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
235 if (e.surface === 'terminal' || e.props.hasSurvey) {
236 return next(e)
237 }
238 const { Box, Text } = $.ui.resolve(e)
239 const segments = usageSegments(await read($, snapshot))
240
241 return (
242 <Box flexDirection="row">
243 {interleave(segments.map(toText(Text)), <Text dimColor>{SEPARATOR}</Text>)}
244 </Box>
245 )
246 })
247}
248hooks/format.ts 119 lines1import type { Limit, Snapshot } from '../types'
2
3export const SEPARATOR = ' · '
4
5// 75% を超えると warning、90% を超えると danger (docs/adr/0005, 0060)
6const WARNING_PERCENT = 75
7const DANGER_PERCENT = 90
8
9export type Level = 'normal' | 'warning' | 'danger'
10
11export type Segment = { label: string; value: string; level: Level }
12
13const levelOf = (value: number): Level =>
14 value > DANGER_PERCENT ? 'danger' : value > WARNING_PERCENT ? 'warning' : 'normal'
15
16const byKind =
17 (kind: string) =>
18 (limits: readonly Limit[]): Limit | undefined =>
19 limits.find(limit => limit.kind === kind)
20
21// Fable の込み使用量は Fable へのリクエスト時だけ API が返す
22// seven_day_overage_included 窓と推定する。fable を含む kind があればそちらを優先する
23// (docs/adr/0004)
24export const fableLimit = (limits: readonly Limit[]): Limit | undefined =>
25 limits.find(limit => limit.kind.includes('fable')) ??
26 byKind('seven_day_overage_included')(limits)
27
28const segment = (label: string, value: number | null | undefined): Segment =>
29 value === null || value === undefined
30 ? { label, value: '--', level: 'normal' }
31 : { label, value: `${Math.round(value)}%`, level: levelOf(value) }
32
33// Fable の週のウィンドウの kind。Claude Code 本体もこの kind を「Fable limit」と表示する (docs/adr/0074)
34export const FABLE_KIND = 'seven_day_overage_included'
35
36const isRecord = (value: unknown): value is Record<string, unknown> =>
37 typeof value === 'object' && value !== null
38
39const toFable = (percent: unknown, resetsAt: unknown): Limit | undefined =>
40 typeof percent !== 'number'
41 ? undefined
42 : {
43 kind: FABLE_KIND,
44 percentUsed: percent,
45 ...(typeof resetsAt === 'string' ? { resetsAt } : {}),
46 }
47
48const isFableScope = (entry: Record<string, unknown>): boolean => {
49 const scope = isRecord(entry.scope) ? entry.scope : {}
50 const model = isRecord(scope.model) ? scope.model : {}
51
52 return typeof model.display_name === 'string' && model.display_name.toLowerCase() === 'fable'
53}
54
55// 使用量の API (/api/oauth/usage) の応答から Fable の週のウィンドウを取り出す。limits[] のモデル名が Fable のものを優先し、
56// 無ければ seven_day_overage_included を使う。応答の形は公開されていないので、形が違えば無しにする (docs/adr/0074)
57export const fableFromUsage = (body: unknown): Limit | undefined => {
58 if (!isRecord(body)) {
59 return undefined
60 }
61 const entry = (Array.isArray(body.limits) ? body.limits : [])
62 .filter(isRecord)
63 .find(isFableScope)
64 const overage = isRecord(body[FABLE_KIND]) ? body[FABLE_KIND] : undefined
65
66 return (
67 (entry && toFable(entry.percent, entry.resets_at)) ??
68 (overage && toFable(overage.utilization, overage.resets_at))
69 )
70}
71
72// 新しいウィンドウに Fable が無ければ、直前の Fable を残す。Fable は API の応答に入らないことが多い (docs/adr/0074)
73export const keepFable = (next: readonly Limit[], previous: readonly Limit[]): Limit[] => {
74 const kept = byKind(FABLE_KIND)(previous)
75
76 return kept && !byKind(FABLE_KIND)(next) ? [...next, kept] : [...next]
77}
78
79// limits の同じ kind のウィンドウを limit で置き換える (無ければ足す)
80export const withLimit = (limits: readonly Limit[], limit: Limit): Limit[] => [
81 ...limits.filter(({ kind }) => kind !== limit.kind),
82 limit,
83]
84
85export const usageSegments =({ contextPercent, rateLimits }: Snapshot): Segment[] => [
86 segment('5h', byKind('five_hour')(rateLimits)?.percentUsed),
87 segment('7d', byKind('seven_day')(rateLimits)?.percentUsed),
88 segment('Fable', fableLimit(rateLimits)?.percentUsed),
89 segment('ctx', contextPercent),
90]
91
92const isLimit = (value: unknown): value is Limit => {
93 if (typeof value !== 'object' || value === null) {
94 return false
95 }
96 const { kind, percentUsed, resetsAt } = value as Record<string, unknown>
97
98 return (
99 typeof kind === 'string' &&
100 typeof percentUsed === 'number' &&
101 (resetsAt === undefined || typeof resetsAt === 'string')
102 )
103}
104
105// $.store の値は unknown なので、形の正しい窓だけを取り出す
106export const parseLimits = (stored: unknown): Limit[] =>
107 Array.isArray(stored) ? stored.filter(isLimit) : []
108
109// リセット時刻を過ぎた窓は使用量 0、次のリセット時刻は不明として扱う (docs/adr/0008)
110export const restoreLimits = (limits: readonly Limit[], now: number): Limit[] =>
111 limits.map(limit =>
112 limit.resetsAt !== undefined && Date.parse(limit.resetsAt) <= now
113 ? { kind: limit.kind, percentUsed: 0 }
114 : limit,
115 )
116
117export const estimatePercent = (tokens: number, window: number): number | null =>
118 window > 0 ? Math.round((tokens / window) * 100) : null
119types/index.d.ts 13 lines1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3export type Snapshot = {
4 contextPercent: number | null
5 rateLimits: Limit[]
6}
7
8declare module 'claude-code' {
9 interface PluginState {
10 'usage-hint': { snapshot: Snapshot }
11 }
12}
13