claude-token-saver 2.7.1 → 2.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.en.md +148 -0
  2. package/README.md +53 -422
  3. package/package.json +3 -2
package/README.en.md ADDED
@@ -0,0 +1,148 @@
1
+ [한국어](./README.md) · **English**
2
+
3
+ # claude-token-saver
4
+
5
+ > Renamed from `claude-cache-monitor` in v2.0. Existing users — see [Migration](#migration-from-claude-cache-monitor).
6
+
7
+ A CLI to **diagnose and save tokens on Claude Code**. Cache hit rate, TTL countdown, 1M-context detection, 5h/7d cap warnings — all in one statusline chip.
8
+
9
+ 📺 [Launch Short (60s)](https://www.youtube.com/shorts/RaD8qMsPTnA)
10
+
11
+ ---
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ # 1. (existing users) remove the old package
17
+ npm uninstall -g claude-cache-monitor
18
+
19
+ # 2. install
20
+ npm i -g claude-token-saver
21
+
22
+ # 3. wire into Claude Code (Skill + statusline guidance)
23
+ claude-token-saver install
24
+ ```
25
+
26
+ Or run once with no install: `npx claude-token-saver`.
27
+
28
+ ## What you see after install
29
+
30
+ **(A) One-shot report** — `claude-token-saver`:
31
+
32
+ ```
33
+ Claude token saver — Last 30 days
34
+ Context window: 200k ✓ standard
35
+ Cache hit rate: 98.2% | Total input: 1957.94M tokens
36
+ TTL Breakdown / Cost Impact / Daily Trend ...
37
+ ```
38
+
39
+ If a session spiked, a `⚠ Spike detected` block leads the report with root cause + a paste-ready remediation command.
40
+
41
+ **(B) Statusline chip** — once wired into `~/.claude/settings.json`:
42
+
43
+ ```
44
+ 🧠 97.5% · ⏳ 1h 42:15 · 💰 $4.8K · 🤖 Opus 4.7 · ✦ 5H 47% · 📅 7D 9%
45
+ ```
46
+
47
+ Risk chips lead when something's wrong: `🚨 5H 94%`, `⚠ 1M ON`, `⚠ Cache miss`, `⚠ 5m TTL`.
48
+
49
+ ## Wire up the statusline
50
+
51
+ ```json
52
+ {
53
+ "statusLine": {
54
+ "type": "command",
55
+ "command": "claude-token-saver --statusline --icon",
56
+ "refreshInterval": 1
57
+ }
58
+ }
59
+ ```
60
+
61
+ `refreshInterval: 1` keeps the TTL countdown ticking while idle (Claude Code's statusline is otherwise event-driven). For Windows PowerShell, see `examples/statusline-command.ps1`.
62
+
63
+ ## Commands
64
+
65
+ | Command | What it does |
66
+ |---|---|
67
+ | `claude-token-saver` | Last 30 days diagnostic report |
68
+ | `claude-token-saver --days 7` | Change window |
69
+ | `claude-token-saver --statusline --icon` | One-line statusline output |
70
+ | `claude-token-saver install` | Register Claude Code Skill (auto-activates on chip wording) |
71
+ | `claude-token-saver history` | Last 7 days of chip transitions (1M ON, Cache miss, cap, …) |
72
+ | `claude-token-saver handoff` | Back current work up to `HANDOFF-YYYY-MM-DD-HHMM.md` before a cap blocks you |
73
+ | `claude-token-saver --install-hook` | Auto-log cache stats on every tool call |
74
+
75
+ ## Options
76
+
77
+ | Flag | Description | Default |
78
+ |------|-------------|---------|
79
+ | `--days, -d` | Analysis period in days | 30 |
80
+ | `--format, -f` | `table` / `json` / `csv` | table |
81
+ | `--project, -p` | Filter by project directory | all |
82
+ | `--threshold` | Hit-rate alert threshold (0.0–1.0) | 0.7 |
83
+ | `--statusline` | One-line statusline output | – |
84
+ | `--icon` | Use 🧠 / ⏳ / 💰 / 📦 icons | text |
85
+ | `--verbose` | Longer labels | – |
86
+ | `--no-timer` | Hide TTL countdown | show |
87
+ | `--no-color` | Strip ANSI codes | – |
88
+ | `--segments=…` | Limit statusline segments (e.g. `model,five_hour,seven_day,saved`) | all |
89
+ | `--install-hook` / `--uninstall-hook` | Manage the PostToolUse hook | – |
90
+
91
+ ## Spike issue codes
92
+
93
+ | Code | Meaning |
94
+ |---|---|
95
+ | `LARGE_INPUT_PER_REQUEST` | single request > 250k tokens → 1M context likely |
96
+ | `LOW_HIT_RATE` | cache hit rate < 50% |
97
+ | `BUCKET_5M_DOMINANT` | > 70% of cache writes hit the 5m bucket |
98
+ | `HIGH_OUTPUT_RATIO` | output/input > 0.15 (output is 5× input price) |
99
+ | `HIGH_REQUEST_COUNT` | session made 3×+ your median (tool loop?) |
100
+ | `FREQUENT_CACHE_REBUILD` | `cache_creation` > `cache_read` |
101
+
102
+ Remediation commands are OS-aware (`~/.zshrc` for macOS/Linux/WSL, `setx` for Windows).
103
+
104
+ ## Migration from claude-cache-monitor
105
+
106
+ ```bash
107
+ npm uninstall -g claude-cache-monitor
108
+ npm i -g claude-token-saver
109
+ ```
110
+
111
+ Then update `~/.claude/settings.json` — change `claude-cache-monitor …` to `claude-token-saver …`. The v2.0 alias bin was dropped because it caused `EEXIST` on global installs.
112
+
113
+ ## How it works
114
+
115
+ Claude Code logs every API call to `~/.claude/projects/<dir>/<session>.jsonl`. This tool dedupes streaming chunks by `requestId` and aggregates `cache_read_input_tokens` / `cache_creation.ephemeral_5m_input_tokens` / `cache_creation.ephemeral_1h_input_tokens` by day and session.
116
+
117
+ ## Pricing (Apr 2026)
118
+
119
+ | Tier | Models | Input | 5m Write | 1h Write | Read | Output |
120
+ |---|---|---|---|---|---|---|
121
+ | `claude-opus-new` | Opus 4.5 / 4.6 / 4.7 | $5 | $6.25 | $10 | $0.50 | $25 |
122
+ | `claude-opus-legacy` | Opus 4 / 4.1 / 3 | $15 | $18.75 | $30 | $1.50 | $75 |
123
+ | `claude-sonnet` | Sonnet 3.7 / 4 / 4.5 / 4.6 | $3 | $3.75 | $6 | $0.30 | $15 |
124
+ | `claude-haiku-4-5` | Haiku 4.5 | $1 | $1.25 | $2 | $0.10 | $5 |
125
+
126
+ Source: [Anthropic pricing docs](https://docs.claude.com/en/docs/about-claude/pricing). Versions ≤ 1.0.x over-estimated Opus 4.5+ by ~3× — upgrade if you're below 1.1.0.
127
+
128
+ ## Cache TTL by plan
129
+
130
+ | Plan | TTL | Controlled by |
131
+ |---|---|---|
132
+ | Max ($100–200/mo) | **1h auto** | `tengu_prompt_cache_1h_config` flag |
133
+ | Pro ($20/mo) | **5m fixed** | not configurable |
134
+ | API key | 5m default (1h via beta header) | `cache_control.ttl` |
135
+
136
+ ## Environment
137
+
138
+ Node.js ≥ 18 · macOS / Windows / Linux / WSL · zero dependencies.
139
+
140
+ ## Background
141
+
142
+ - [GitHub Issue #46829](https://github.com/anthropics/claude-code/issues/46829) — cache TTL regression
143
+ - [HN discussion](https://news.ycombinator.com/item?id=47736476) — 168 points, 142 comments
144
+ - [HNPulse KR](https://www.youtube.com/@HNPulseKR) — Korean HN tech deep-dives
145
+
146
+ ## License
147
+
148
+ MIT
package/README.md CHANGED
@@ -1,477 +1,108 @@
1
- # claude-token-saver
2
-
3
- > **Renamed from `claude-cache-monitor` in v2.0.** The old npm package is deprecated and points here. The `claude-cache-monitor` binary is gone — use `claude-token-saver` instead. See [migration notes](#migration-from-claude-cache-monitor).
4
-
5
- > 📺 **HNPulse Shorts** — 이 도구가 만들어진 배경 (캐시 TTL 1h→5m 변경 이슈):
6
- > **[▶ Watch the Short](https://www.youtube.com/shorts/oSx2sg935nI)** · [All HNPulse Shorts](https://www.youtube.com/@HNPulseKR/shorts)
7
- >
8
- > [![HNPulse Short](https://img.youtube.com/vi/oSx2sg935nI/hqdefault.jpg)](https://www.youtube.com/shorts/oSx2sg935nI)
9
-
10
- **Save tokens on Claude Code.** Catch the session that suddenly burned 10× your usual input, figure out *why*, and get a one-line remediation you can paste.
11
-
12
- **Why I built this.** I'm on the Max plan. On Opus 4.6 I never hit the *current-session* cap. After Opus 4.7 rolled out, I started hitting it on the same workflow — repeatedly. The official token statistics didn't match what I was actually feeling, and Claude Code's UI doesn't show prompt-cache health. This tool is what let me see *why*: low cache hit rate, 5m TTL writes that should have been 1h, 1M context auto-promoted in the background.
1
+ **한국어** · [English](./README.en.md)
13
2
 
14
- v2.1 (2026-04) adds the workflow that follows the diagnosis:
15
- - **`claude-token-saver install`** — one command writes a Claude Code Skill that auto-activates when you mention "cache hit rate" / "1M context" / "5H cap" — no slash command needed.
16
- - **`claude-token-saver history`** — every warning chip transition is auto-logged to a daily Markdown file, so you can answer "when did this start" without grepping logs.
17
- - **Cross-platform paths** — Windows (`%APPDATA%`), macOS (`~/Library/Application Support`), Linux (`~/.config` / XDG) all handled.
3
+ # claude-token-saver
18
4
 
19
- v1.5 adds three things on top of the original `claude-cache-monitor`:
20
- - **Spike diagnosis** — detect recent sessions whose input tokens exploded vs. your own baseline, and name the cause (1M context, 5m TTL churn, cache rebuild, chatty output).
21
- - **1M-context detection** — Opus 4.7+ auto-enables 1M context on Max plans, silently. This tool surfaces it on the statusline as `Ctx 1M` (red) vs. `Ctx 200k` (green), with the OS-specific command to turn it off.
22
- - **Actionable advice** — OS-aware remediation (`~/.zshrc` vs. `setx`) and the warning for the known `/model` toggle bug ([anthropics/claude-code#31640](https://github.com/anthropics/claude-code/issues/31640)).
5
+ > v2.0에서 `claude-cache-monitor` `claude-token-saver`로 이름이 바뀌었습니다. 기존 사용자는 [마이그레이션](#마이그레이션-claude-cache-monitor에서) 참고.
23
6
 
24
- The original functionality still works: cache hit rate, TTL breakdown, cost impact vs. no-cache, TTL countdown timer, and Claude Code statusline integration.
7
+ Claude Code의 **토큰 사용량을 진단·절약**하는 CLI. 캐시 히트율, TTL 카운트다운, 1M 컨텍스트 감지, 5h/7d 한도 경고를 statusline 줄로 보여줍니다.
25
8
 
26
- **Run it standalone or wire it into Claude Code's statusline.** Use `npx claude-token-saver` as a one-shot report, or wire it into Claude Code's native statusline for an always-on chip. See [Two Ways to Use It](#two-ways-to-use-it).
9
+ 📺 [출시 영상 (60초)](https://www.youtube.com/shorts/RaD8qMsPTnA)
27
10
 
28
11
  ---
29
12
 
30
- **Claude Code 토큰 아껴쓰기 도구.** 평소보다 10배 토큰을 태운 세션을 찾고, *왜 튀었는지* 진단하고, 붙여넣을 수 있는 한 줄 해결책까지 내줍니다.
31
-
32
- v1.5 신규:
33
- - **토큰 급증 진단** — 최근 세션 중 내 평소 기준보다 입력 토큰이 폭증한 세션을 찾아 원인까지 분류 (1M 컨텍스트 / 5분 TTL 반복 쓰기 / 캐시 재작성 / 출력 과다).
34
- - **1M 컨텍스트 감지** — Opus 4.7부터 Max 플랜은 1M 컨텍스트가 자동 ON. Statusline에 `Ctx 1M`(빨강) / `Ctx 200k`(초록)으로 표시하고, OS별 OFF 명령까지 안내.
35
- - **실행 가능한 권장 액션** — macOS/Linux/WSL는 `~/.zshrc`, Windows는 `setx` 명령. [`/model`로 200k 선택해도 1M에 머무는 알려진 버그](https://github.com/anthropics/claude-code/issues/31640)에 대한 경고 포함.
36
-
37
- 기존 기능(캐시 히트율·TTL 분포·비용 절감·TTL 카운트다운·statusline)은 그대로 유지됩니다.
38
-
39
- **단독 도구로도, Claude Code statusline 통합으로도 동작합니다.** `npx claude-token-saver` 한 줄로 진단 리포트만 보거나, 내장 statusline에 연결해 상시 표시할 수 있습니다. 자세한 용법은 [Two Ways to Use It](#two-ways-to-use-it) 참고.
40
-
41
- ## Quick Start
13
+ ## 설치
42
14
 
43
15
  ```bash
44
- # Run instantly (no install required)
45
- npx claude-token-saver
46
-
47
- # Last 7 days only
48
- npx claude-token-saver --days 7
16
+ # 1. (기존 사용자) 구 패키지 제거
17
+ npm uninstall -g claude-cache-monitor
49
18
 
50
- # JSON output (for pipelines)
51
- npx claude-token-saver --format json
19
+ # 2. 설치
20
+ npm i -g claude-token-saver
52
21
 
53
- # CSV output (for spreadsheets)
54
- npx claude-token-saver --format csv
22
+ # 3. Claude Code 통합 (Skill + statusline 안내)
23
+ claude-token-saver install
55
24
  ```
56
25
 
57
- > **Upgrading from `claude-cache-monitor`?** Uninstall the old package first, then install the new one and update your settings command name:
58
- > ```bash
59
- > npm uninstall -g claude-cache-monitor && npm i -g claude-token-saver
60
- > ```
61
- > After upgrading, change any `claude-cache-monitor …` invocations (including `statusLine.command` in `~/.claude/settings.json`) to `claude-token-saver …`. See [Migration](#migration-from-claude-cache-monitor).
26
+ 설치 없이 번만 실행하려면 `npx claude-token-saver`.
62
27
 
63
- ## Spike Diagnosis (new in v1.5.0)
28
+ ## 설치 보이는
64
29
 
65
- When you run `npx claude-token-saver`, sessions from the last 24 hours whose total input tokens are **≥ 3× your p95 baseline** (or whose single-request context exceeds 250k, indicating 1M context) appear at the top of the report with root causes and remediation commands. Example output:
30
+ **(A) 단발 리포트** `claude-token-saver` 실행 시:
66
31
 
67
32
  ```
68
- 토큰 급증 감지
69
- ──────────────────────────────────────────────────
70
- 컨텍스트 모드 추정: 1M (최근 단일 요청 최대 480k 토큰)
71
-
72
- • a1b2c3d4 [myproject] 총 입력 320.45M (5.2× p95, 요청 142회)
73
- 단일 요청 최대 컨텍스트: 480k 토큰
74
- · 요청당 입력 토큰이 평소보다 매우 큽니다 (1M 컨텍스트 의심)
75
-
76
- 권장 액션
77
- ──────────────────────────────────────────────────
78
- ▸ 요청당 입력 토큰이 평소보다 매우 큽니다 (1M 컨텍스트 의심)
79
- Opus 4.7부터 1M 컨텍스트가 표준 가격으로 풀리면서 Max 플랜은 자동으로 1M로 승격됩니다 ...
80
- - 1M 컨텍스트 OFF (환경변수)
81
- echo 'export CLAUDE_CODE_DISABLE_1M_CONTEXT=1' >> ~/.zshrc && source ~/.zshrc
82
- - 세션 내 토글
83
- 단축키 ⌥ P (mac) / Alt + P (linux) 로 즉시 On/Off
84
- - ⚠ 알려진 버그 #31640
85
- /model 로 200k 선택해도 컨텍스트가 1M에 머무는 케이스가 있습니다.
86
- 확실히 끄려면 위 환경변수를 설정한 뒤 Claude Code를 재시작하세요.
33
+ Claude 토큰 아껴쓰기 — Last 30 days
34
+ Context window: 200k ✓ 표준
35
+ Cache hit rate: 98.2% | Total input: 1957.94M tokens
36
+ TTL Breakdown / Cost Impact / Daily Trend ...
87
37
  ```
88
38
 
89
- Issue codes detected:
90
-
91
- | Code | Meaning |
92
- |---|---|
93
- | `LARGE_INPUT_PER_REQUEST` | avg input/request is 8×+ your baseline, or a single request > 250k tokens → 1M context likely |
94
- | `LOW_HIT_RATE` | cache hit rate < 50% and materially below your baseline |
95
- | `BUCKET_5M_DOMINANT` | > 70% of cache writes land in the 5m bucket (Pro plan, or Max users getting downgraded) |
96
- | `HIGH_OUTPUT_RATIO` | output/input > 0.15 (output is 5× input price — matters a lot) |
97
- | `HIGH_REQUEST_COUNT` | session made 3×+ your median request count (tool-loop suspect) |
98
- | `FREQUENT_CACHE_REBUILD` | `cache_creation` > `cache_read` (cache being made, not reused) |
99
-
100
- Remediation commands are chosen from `process.platform` — macOS/Linux/WSL get `~/.zshrc` snippets, Windows gets `setx` and the PowerShell equivalent.
101
-
102
- ## Two Ways to Use It
39
+ 급증 세션이 있으면 상단에 `⚠ 토큰 급증 감지` 블록과 원인·해결 명령이 함께 출력됩니다.
103
40
 
104
- | Mode | What you run | When to pick this |
105
- |---|---|---|
106
- | **1. Standalone CLI report** | `npx claude-token-saver` | One-off diagnosis. Prints the full report (spikes + cache + cost + trend). Zero setup. |
107
- | **2. Claude Code statusline** | `claude-token-saver --statusline` wired via `~/.claude/settings.json` | You want the chip (hit rate · TTL countdown · Ctx 200k/1M · spike) visible all the time. |
41
+ **(B) statusline 줄** `~/.claude/settings.json`에 등록 시:
108
42
 
109
- Detail for each mode below.
110
-
111
- ## Statusline Mode (new in v1.2.0)
112
-
113
- Always-on one-line display in Claude Code's native statusline — no need to run commands manually.
114
-
115
- Claude Code 내장 statusline에 한 줄로 상시 표시. 커맨드 수동 실행 불필요.
116
-
117
- ```bash
118
- # Preview (prints one line — text mode, default)
119
- npx claude-token-saver --statusline
120
- # → Cache hit 97.5% · Expires 1h 42:15 · Cost saved $4.8K · Ctx 200k · 7d
121
-
122
- # When 1M context is silently on and a session is spiking:
123
- # → Cache hit 88.0% · Expires 1h 42:15 · Cost saved $4.8K · Ctx 1M · ⚠ 1M컨텍스트 · 7d
124
-
125
- # Icon mode (🧠 / ⏳ / 💰 / 📦)
126
- npx claude-token-saver --statusline --icon
127
- # → 🧠 97.5% · ⏳ 1h 42:15 · 💰 $4.8K · 📦 200k · 7d
128
-
129
- # Verbose (longer labels; combines with --icon too)
130
- npx claude-token-saver --statusline --verbose
131
- # → Cache hit 97.5% · 1h bucket · expires in 42:15 · Cost saved $4.8K · last 7d
132
-
133
- npx claude-token-saver --statusline --icon --verbose
134
- # → 🧠 Cache hit 97.5% · ⏳ Expires 1h 42:15 · 💰 Cost saved $4.8K · last 7d
135
-
136
- # Hide the TTL countdown
137
- npx claude-token-saver --statusline --no-timer
138
-
139
- # No ANSI color (plain text)
140
- npx claude-token-saver --statusline --no-color
141
43
  ```
142
-
143
- ### TTL countdown (v1.2.1+)
144
-
145
- Your subscription plan fixes the TTL bucket (5m for Pro, 1h for Max) — the actionable number isn't the bucket, it's **how much time is left on your last API call's cache entry**. The `TTL 1h MM:SS` segment is a live stopwatch against the dominant bucket:
146
-
147
- 구독 플랜이 TTL 값(Pro = 5분, Max = 1시간)을 고정하므로 의미 있는 수치는 "버킷"이 아니라 "마지막 API 호출의 캐시가 만료되기까지 몇 초"입니다. `TTL 1h MM:SS` 세그먼트가 그 스톱워치입니다 (앞쪽이 버킷, 뒤쪽이 남은 시간):
148
-
149
- - 🟢 &gt;30% remaining — plenty of time to send the next prompt within TTL
150
- - 🟡 10–30% remaining — consider firing a cheap prompt soon to keep prefix cached
151
- - 🔴 &lt;10% remaining or `EXPIRED` — next prompt will pay cache-write cost again
152
-
153
- This enables the "5-minute rule" in practice: a quick dummy question before the timer hits zero resets the TTL and preserves the prefix cache.
154
-
155
- ### Enable in Claude Code
156
-
157
- The Claude Code statusline is event-driven — it only re-renders on assistant messages / mode changes. To keep the countdown ticking while you're idle, set `refreshInterval: 1` alongside the `statusLine` command.
158
-
159
- #### macOS / Linux / WSL
160
-
161
- ```json
162
- {
163
- "statusLine": {
164
- "type": "command",
165
- "command": "claude-token-saver --statusline --icon",
166
- "refreshInterval": 1
167
- }
168
- }
44
+ 🧠 97.5% · ⏳ 1h 42:15 · 💰 $4.8K · 🤖 Opus 4.7 · ✦ 5H 47% · 📅 7D 9%
169
45
  ```
170
46
 
171
- Or combine with an existing statusline script see [`examples/statusline-command.sh`](examples/statusline-command.sh) for a drop-in that prints `user@host:cwd | <token-saver segment>`.
172
-
173
- #### Windows (native PowerShell, not WSL)
47
+ 위험 상황에서는 칩이 앞으로 튀어나옵니다 `🚨 5H 94%`, `⚠ 1M ON`, `⚠ Cache miss`, `⚠ 5m TTL` 등.
174
48
 
175
- Use the PowerShell example in [`examples/statusline-command.ps1`](examples/statusline-command.ps1):
49
+ ## statusline 등록
176
50
 
177
51
  ```json
178
52
  {
179
53
  "statusLine": {
180
54
  "type": "command",
181
- "command": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File %USERPROFILE%\\.claude\\statusline-command.ps1",
55
+ "command": "claude-token-saver --statusline --icon",
182
56
  "refreshInterval": 1
183
57
  }
184
58
  }
185
59
  ```
186
60
 
187
- Works best in **Windows Terminal** or **PowerShell 7+** (ANSI color + emoji). Classic `conhost cmd` may garble emoji — prefer `--no-icon`-style plain text or use Windows Terminal.
188
-
189
- #### Windows (WSL)
190
-
191
- Same as Linux — install the package in your WSL Node.js and point to the POSIX sh script.
192
-
193
- Claude Code calls this every ~300ms on events, plus once per `refreshInterval` second while idle. Colors are emitted when the terminal supports them:
194
-
195
- - **Hit rate** — 🟢 ≥85% · 🟡 70–85% · 🔴 <70%
196
- - **TTL bucket** — 🟢 1h (good) · 🟡 5m (warning)
197
- - **Countdown** — 🟢 >30% remaining · 🟡 10–30% · 🔴 <10% or EXPIRED
198
- - **Context window** — 🟢 `Ctx 200k` (standard) · 🔴 `Ctx 1M` (Opus 4.7+ Max auto-enabled — expensive if unintended)
199
- - **Spike chip** — appears only when the current session is flagged (e.g. `⚠ 1M컨텍스트`, `⚠ 5m TTL`, `⚠ 캐시미스`, `⚠ 입력폭주`)
200
-
201
- Statusline mode uses the last 7 days by default (override with `--days N`) and never emits multi-line errors, so your statusline stays clean even when there's no session data yet.
202
-
203
- ## Claude Code integration (`install`) — new in v2.1
204
-
205
- One command wires up everything else this README mentions:
206
-
207
- ```bash
208
- claude-token-saver install
209
- ```
210
-
211
- This writes one file under your Claude user dir:
212
- - `~/.claude/skills/claude-token-saver/SKILL.md` — auto-activates whenever you mention chip wording ("⚠ 1M ON", "cache miss", "5H cap", etc.) or ask for a token report. Claude Code will then read `claude-token-saver last`, drill into history if needed, and explain the warning.
213
-
214
- If you previously installed v2.5.x or earlier, `install` also removes the now-redundant legacy `~/.claude/commands/token-monitor.md` slash command — its workflow is fully absorbed into the skill (same behavior, triggered by intent rather than typing `/token-monitor`).
215
-
216
- Re-run with `--force` to overwrite the skill file.
217
-
218
- ## Warning history (`history`) — new in v2.1
219
-
220
- The statusline path auto-logs every chip transition (none → ⚠, ⚠ A → ⚠ B, ⚠ → resolved) to a daily Markdown file. Read it back with:
221
-
222
- ```bash
223
- claude-token-saver history # last 7 days
224
- claude-token-saver history --days 30 # wider window
225
- claude-token-saver history --list # just list available dates
226
- ```
227
-
228
- Sample output:
229
-
230
- ```
231
- # Token Monitor — 2026-04-25
232
-
233
- ## Events
234
- - 09:14:02 ⚠ 1M ON — Context auto-promoted to 1M (max single-request 280k tokens)
235
- - 09:42:18 ⚠ 1M ON → ⚠ Cache miss — session abc12345: LOW_HIT_RATE
236
- - 10:05:47 ✓ resolved (was ⚠ Cache miss)
237
- ```
238
-
239
- Storage paths (cross-platform):
240
- - **Windows**: `%APPDATA%\claude-token-saver\history\YYYY-MM-DD.md`
241
- - **macOS**: `~/Library/Application Support/claude-token-saver/history/YYYY-MM-DD.md`
242
- - **Linux**: `$XDG_CONFIG_HOME/claude-token-saver/history/YYYY-MM-DD.md` (or `~/.config/...`)
243
-
244
- Each day's file is plain Markdown — open it in any editor. Transitions are deduped, so the 1Hz statusline refresh doesn't spam.
245
-
246
- ## Model + /usage segments (new in v2.3, generic in v2.4)
247
-
248
- Three more segments mirror the data Claude Code's `/usage` slash command shows, so you don't have to slash for it every few minutes:
249
-
250
- | Segment | Icon mode example | Source |
251
- | ----------- | --------------------- | ------------------------------- |
252
- | `model` | `🤖 Opus 4.7` | stdin `model.display_name` |
253
- | `five_hour` | `✦ current ███▒░░ 47% 🔄 21:10` | stdin `rate_limits.five_hour` |
254
- | `seven_day` | `📅 weekly ▒░░░░░ 9% 🔄 Thu 13:00` | stdin `rate_limits.seven_day` |
255
-
256
- The window segments stay quiet under 70% (calm emerald), warm to amber at 70–89%, and yield to the leading `🚨 5H █████▓ 94%` / `🚨 7D █████▒ 92%` cap-warn chip at 90%+ — so you never see the same window twice. The gauge is 6 cells wide using a single density family (`█▓▒░`), so the fill→empty boundary reads as one smooth gradient instead of an awkward step between fractional and shaded glyphs. Colors render as a Tailwind-inspired muted palette (emerald-400 / amber-400 / rose-400) on truecolor terminals (`COLORTERM=truecolor`), with a graceful fallback to 8-color ANSI elsewhere. Filter the layout with `--segments=` if you only want a subset:
257
-
258
- ```bash
259
- claude-token-saver --statusline --icon --segments=model,five_hour,seven_day,saved
260
- ```
261
-
262
- `5h` and `7d` are kept as aliases for the older config files. Any new `rate_limits.*` window Anthropic ships (e.g. a Sonnet-only weekly bucket) renders automatically with a derived label — no config or version bump needed. As of 2026-04-25 the stdin contract exposes only `five_hour` + `seven_day`; the third row in `/usage` ("Current week — Sonnet only") is not in the payload yet, so we mirror what's there.
263
-
264
- ## Cap-warn + handoff (new in v2.2)
265
-
266
- Claude Code's statusline payload now includes rate-limit usage (`rate_limits.five_hour.used_percentage`, `rate_limits.seven_day.used_percentage`). claude-token-saver leads the statusline with a `🚨 5H 94%` (or `🚨 7D 92%`) chip the moment either window crosses **90%**, and writes the transition into history:
267
-
268
- ```
269
- - 14:32:08 🚨 5H 94% cap warning (resets in 1h 38m)
270
- - 16:10:21 ✓ 5H cap warning resolved
271
- ```
272
-
273
- When you see the chip, back up the work in flight before the cap blocks you:
274
-
275
- ```bash
276
- claude-token-saver handoff
277
- ```
278
-
279
- That writes `./HANDOFF-YYYY-MM-DD-HHMM.md` in the current directory with:
280
-
281
- - timestamp, cwd, git branch / HEAD / dirty file list
282
- - the 5h/7d cap snapshot (and "resets in Hh Mm")
283
- - empty fillable sections for *what I just did*, *TODO*, *where to pick up next*, *gotchas*
284
- - a one-line resume prompt for a fresh Claude Code session:
285
-
286
- ```
287
- Read the most recent HANDOFF-*.md in this directory and continue the work.
288
- ```
289
-
290
- The handoff write is also recorded in history (`📝 handoff written: …`), so `claude-token-saver history` and the auto-skill show both the cap-warn and the backup event next to each other.
291
-
292
- ## Hook Setup
293
-
294
- Automatically logs cache stats on every tool call and alerts when hit rate drops below a threshold.
295
-
296
- 매 도구 호출마다 자동으로 캐시 통계를 기록하고, 히트율이 임계값 이하로 떨어지면 경고합니다.
297
-
298
- ```bash
299
- # Install hook (default threshold 70%)
300
- npx claude-token-saver --install-hook
301
-
302
- # Custom threshold
303
- npx claude-token-saver --install-hook --threshold 0.8
304
-
305
- # Remove hook
306
- npx claude-token-saver --uninstall-hook
307
- ```
308
-
309
- When the hook is installed:
310
- - Session-level stats are automatically recorded to `~/.claude/cache-stats.jsonl`
311
- - A warning is displayed in Claude Code when hit rate falls below the threshold
312
-
313
- ## Output Example
314
-
315
- ```
316
- Claude 토큰 아껴쓰기 — Last 30 days
317
- (claude-token-saver v2.0.1)
318
- ══════════════════════════════════════════════════
319
-
320
- Context window: 200k ✓ 200k 컨텍스트 (표준)
321
- (최근 단일 요청 최대 83k 토큰)
322
-
323
- Summary
324
- Sessions: 380 | API calls: 10,813 | Model: claude-opus-new
325
- Cache hit rate: 98.2% | Total input: 1957.94M tokens
326
-
327
- TTL Breakdown
328
- ┌────────────────────┬──────────────────┬──────────────────┐
329
- │ │ 5m Ephemeral │ 1h Extended │
330
- ├────────────────────┼──────────────────┼──────────────────┤
331
- │ Cache writes │ 167.7K (0.5%) │ 34.8M (99.5%) │
332
- └────────────────────┴──────────────────┴──────────────────┘
333
-
334
- Cost Impact (estimated)
335
- ┌──────────────────────────┬──────────────┐
336
- │ Actual cost │ $793.93 │
337
- │ Without cache │ $5958.52 │
338
- ├──────────────────────────┼──────────────┤
339
- │ Savings │ $5164.6 (86.7%) │
340
- │ Extra cost if 5m-only │ +$239.99 │
341
- └──────────────────────────┴──────────────┘
342
-
343
- Daily Trend
344
- ┌────────────┬──────────┬─────────┬────────────┬────────────┬───────┐
345
- │ Date │ HitRate │ Calls │ Read │ Write │ 5m% │
346
- ├────────────┼──────────┼─────────┼────────────┼────────────┼───────┤
347
- │ 2026-04-10 │ 98.5% │ 341 │ 88.98M │ 1.35M │ 0.0% │
348
- │ 2026-04-11 │ 97.1% │ 118 │ 9.51M │ 0.27M │ 0.0% │
349
- │ 2026-04-12 │ 91.7% │ 77 │ 2.69M │ 0.22M │ 0.0% │
350
- └────────────┴──────────┴─────────┴────────────┴────────────┴───────┘
351
- ```
352
-
353
- ## Options
354
-
355
- | Flag | Description | Default |
356
- |------|-------------|---------|
357
- | `--days, -d` | Analysis period in days | 30 |
358
- | `--format, -f` | Output format: `table`, `json`, `csv` | table |
359
- | `--project, -p` | Filter by project directory | all |
360
- | `--threshold` | Cache hit rate alert threshold (0.0-1.0) | 0.7 |
361
- | `--install-hook` | Install Claude Code PostToolUse hook | - |
362
- | `--uninstall-hook` | Remove hook | - |
363
- | `--statusline` | Emit one-line output for Claude Code statusline API | - |
364
- | `--icon` | (with `--statusline`) use 🧠 / ⏳ / 💰 icons instead of word labels | text |
365
- | `--verbose` | (with `--statusline`) use longer labels | - |
366
- | `--no-timer` | (with `--statusline`) hide the TTL countdown | show |
367
- | `--no-color` | Strip ANSI escape codes | - |
368
-
369
- Statusline segments always include the context-window chip (`Ctx 200k`/`Ctx 1M` or `📦 200k`/`📦 1M` in `--icon` mode). A spike chip is appended only when the most recent session is diagnosed as a spike.
370
-
371
- ## How It Works
372
-
373
- Claude Code logs usage data for every API call into session JSONL files:
374
-
375
- ```
376
- ~/.claude/projects/<project-dir>/<session-id>.jsonl
377
- ```
378
-
379
- Each API response contains these fields:
380
- - `cache_read_input_tokens` — tokens read from cache (cheap, 0.1x)
381
- - `cache_creation_input_tokens` — tokens written to cache (expensive, 1.25x~2x)
382
- - `cache_creation.ephemeral_5m_input_tokens` — tokens created with 5-minute TTL
383
- - `cache_creation.ephemeral_1h_input_tokens` — tokens created with 1-hour TTL
384
-
385
- This tool deduplicates streaming chunks by `requestId` and aggregates by day/session.
386
-
387
- ## Key Findings
388
-
389
- Cache TTL is determined by your subscription plan, not by user choice:
390
-
391
- | Plan | Cache TTL | Controlled by |
392
- |------|-----------|---------------|
393
- | **Max** ($100~200/mo) | **1h automatic** | `tengu_prompt_cache_1h_config` feature flag |
394
- | **Pro** ($20/mo) | **5m fixed** | Not configurable |
395
- | **API key** | **5m default** (1h via beta header) | `cache_control.ttl` parameter |
396
-
397
- ## Pricing (updated 2026-04 for Opus 4.7)
398
-
399
- Cost estimates use current Anthropic pricing, auto-detected from the model id in session logs:
400
-
401
- | Tier (internal id) | Matching models | Input | 5m Cache Write | 1h Cache Write | Cache Read | Output |
402
- |---|---|---|---|---|---|---|
403
- | `claude-opus-new` | Opus **4.5 / 4.6 / 4.7** | $5 | $6.25 | $10 | $0.50 | $25 |
404
- | `claude-opus-legacy` | Opus 4 / 4.1 / 3 | $15 | $18.75 | $30 | $1.50 | $75 |
405
- | `claude-sonnet` | Sonnet 3.7 / 4 / 4.5 / 4.6 | $3 | $3.75 | $6 | $0.30 | $15 |
406
- | `claude-haiku-4-5` | Haiku 4.5 | $1 | $1.25 | $2 | $0.10 | $5 |
407
- | `claude-haiku-3-5` | Haiku 3.5 | $0.80 | $1 | $1.6 | $0.08 | $4 |
408
- | `claude-haiku-3` | Haiku 3 | $0.25 | $0.30 | $0.50 | $0.03 | $1.25 |
409
-
410
- 5m and 1h cache writes are now billed at separate rates (previously applied a single blended rate). Prior versions (≤ 1.0.x) used legacy Opus 4 pricing for all Opus models, over-estimating Opus 4.5+ costs by ~3x — **upgrade to 1.1.0 if you run Opus 4.5 or newer**.
411
-
412
- Source: [Anthropic pricing documentation](https://docs.claude.com/en/docs/about-claude/pricing)
61
+ `refreshInterval: 1`은 TTL 카운트다운이 idle 상태에서도 1초마다 갱신되게 합니다. Windows(PowerShell) `examples/statusline-command.ps1` 참고.
413
62
 
414
- ## Platform Support
63
+ ## 주요 명령
415
64
 
416
- Works on **macOS**, **Windows**, and **Linux**. Requires Node.js >= 18.
417
-
418
- Zero dependencies.
419
-
420
- ## Background
421
-
422
- - [GitHub Issue #46829](https://github.com/anthropics/claude-code/issues/46829): Cache TTL regression analysis
423
- - [HN Discussion](https://news.ycombinator.com/item?id=47736476): Community reaction (168 points, 142 comments)
424
- - [HNPulse KR](https://www.youtube.com/@HNPulseKR): Hacker News tech deep-dives in Korean ([Shorts](https://www.youtube.com/@HNPulseKR/shorts))
425
-
426
- ## Migration from claude-cache-monitor
427
-
428
- v2.0 renamed the package to reflect the expanded scope (spike diagnosis + 1M-context detection + remediation, not just cache monitoring).
65
+ | 명령 | 설명 |
66
+ |---|---|
67
+ | `claude-token-saver` | 최근 30일 진단 리포트 |
68
+ | `claude-token-saver --days 7` | 기간 변경 |
69
+ | `claude-token-saver --statusline --icon` | statusline용 한 줄 |
70
+ | `claude-token-saver install` | Claude Code Skill 자동 등록 (칩 단어 언급 시 자동 활성) |
71
+ | `claude-token-saver history` | 최근 7일간 칩 전이 로그 (1M ON, Cache miss, cap 등) |
72
+ | `claude-token-saver handoff` | 현재 작업을 `HANDOFF-YYYY-MM-DD-HHMM.md`로 백업 (cap 임박 시) |
73
+ | `claude-token-saver --install-hook` | 도구 호출마다 캐시 통계 자동 로깅 |
429
74
 
430
- ### New users
75
+ 전체 옵션은 `--help` 또는 [영문 README](./README.en.md#options).
431
76
 
432
- ```bash
433
- npm i -g claude-token-saver
434
- # or, no install:
435
- npx claude-token-saver
436
- ```
77
+ ## 진단되는 급증 원인
437
78
 
438
- Skip the rest of this section.
79
+ | 코드 | 의미 |
80
+ |---|---|
81
+ | `LARGE_INPUT_PER_REQUEST` | 단일 요청 250k+ → 1M 컨텍스트 의심 |
82
+ | `LOW_HIT_RATE` | 캐시 히트율 < 50% |
83
+ | `BUCKET_5M_DOMINANT` | 캐시 쓰기의 70%+가 5분 버킷 (Pro 플랜 또는 Max 다운그레이드) |
84
+ | `HIGH_OUTPUT_RATIO` | 출력/입력 > 0.15 (출력은 입력의 5배 가격) |
85
+ | `FREQUENT_CACHE_REBUILD` | 캐시 재작성이 읽기보다 많음 |
439
86
 
440
- ### Upgrading from `claude-cache-monitor` v1.x
87
+ 코드마다 OS별 해결 명령(`~/.zshrc` / `setx`)이 함께 출력됩니다.
441
88
 
442
- Two steps:
89
+ ## 마이그레이션 (claude-cache-monitor에서)
443
90
 
444
91
  ```bash
445
- # 1. Remove the old package (its claude-cache-monitor bin is now obsolete).
446
92
  npm uninstall -g claude-cache-monitor
447
-
448
- # 2. Install the new one.
449
93
  npm i -g claude-token-saver
450
94
  ```
451
95
 
452
- Then update any `claude-cache-monitor …` references. The main one is `statusLine.command` in `~/.claude/settings.json`:
96
+ `~/.claude/settings.json`의 `statusLine.command`를 `claude-cache-monitor …` `claude-token-saver …`로 교체하세요. v2.0 이전의 `claude-cache-monitor` 바이너리 별칭은 npm 충돌(EEXIST) 때문에 제거됐습니다.
453
97
 
454
- ```jsonc
455
- // before
456
- "command": "claude-cache-monitor --statusline --icon"
98
+ ## 동작 원리
457
99
 
458
- // after
459
- "command": "claude-token-saver --statusline --icon"
460
- ```
100
+ Claude Code는 모든 API 응답을 `~/.claude/projects/<dir>/<session>.jsonl`에 기록합니다. 이 도구는 `cache_read_input_tokens`, `cache_creation.ephemeral_5m/1h_input_tokens` 등을 `requestId`로 중복 제거 후 일·세션 단위로 집계합니다.
461
101
 
462
- ### Why we dropped the `claude-cache-monitor` bin alias
102
+ ## 환경
463
103
 
464
- Earlier v2.0 releases shipped a `claude-cache-monitor` bin alongside `claude-token-saver` so existing settings would keep working without edits. In practice this caused an `EEXIST: file already exists` error on `npm i -g claude-token-saver` when v1.x was still installed — and that collision forced the uninstall step anyway. Dropping the alias makes the upgrade path a clean two-liner and lets `npm i -g claude-token-saver` succeed directly if you've never installed the old one.
104
+ Node.js 18 · macOS / Linux / Windows / WSL · 의존성 0.
465
105
 
466
- ### Zero-install (npx)
467
-
468
- ```bash
469
- npx claude-token-saver@latest --statusline --icon
470
- ```
471
-
472
- No uninstall needed; npm just fetches the new name.
473
-
474
- ## License
106
+ ## 라이선스
475
107
 
476
108
  MIT
477
-
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-token-saver",
3
- "version": "2.7.1",
3
+ "version": "2.7.3",
4
4
  "description": "Save tokens on Claude Code — spike diagnosis, 1M-context detection, TTL countdown, statusline. (formerly claude-cache-monitor)",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,7 +10,8 @@
10
10
  "bin/",
11
11
  "src/",
12
12
  "examples/",
13
- "README.md"
13
+ "README.md",
14
+ "README.en.md"
14
15
  ],
15
16
  "engines": {
16
17
  "node": ">=18"