Skip to content

Commit cc8ded1

Browse files
committed
feat: add statusline command for Claude Code status bar integration
Adds a new statusline command that displays compact usage information designed for Claude Code status line feature. Features: - Shows current session cost, today total, and active block status - Color-coded burn rate indicator (green/yellow/red) using picocolors - Reads session data from stdin as per Claude Code hook protocol - Compact single-line output optimized for status bar display - Test scripts and dummy test file included for easy testing Output format: 🤖 Model | 💰 $X.XX session / $X.XX today / $X.XX block (Xh Xm left) | 🔥 $X.XX/hr This is a Beta feature with more customization options planned.
1 parent 6f4d7ac commit cc8ded1

7 files changed

Lines changed: 319 additions & 0 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
2222
- `bun run start monthly` - Show monthly usage report
2323
- `bun run start session` - Show session-based usage report
2424
- `bun run start blocks` - Show 5-hour billing blocks usage report
25+
- `bun run start statusline` - Show compact status line (Beta)
2526
- `bun run start daily --json` - Show daily usage report in JSON format
2627
- `bun run start monthly --json` - Show monthly usage report in JSON format
2728
- `bun run start session --json` - Show session usage report in JSON format

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ ccusage daily # Daily token usage and costs
5555
ccusage monthly # Monthly aggregated report
5656
ccusage session # Usage by conversation session
5757
ccusage blocks # 5-hour billing windows
58+
ccusage statusline # Compact status line for hooks (Beta)
5859

5960
# Live monitoring
6061
ccusage blocks --live # Real-time usage dashboard
@@ -79,6 +80,7 @@ ccusage daily --instances --project myproject --json # Combined usage
7980
- 💬 **Session Report**: View usage grouped by conversation sessions
8081
- ⏰ **5-Hour Blocks Report**: Track usage within Claude's billing windows with active block monitoring
8182
- 📈 **Live Monitoring**: Real-time dashboard showing active session progress, token burn rate, and cost projections with `blocks --live`
83+
- 🚀 **Statusline Integration**: Compact usage display for Claude Code status bar hooks (Beta)
8284
- 🤖 **Model Tracking**: See which Claude models you're using (Opus, Sonnet, etc.)
8385
- 📊 **Model Breakdown**: View per-model cost breakdown with `--breakdown` flag
8486
- 📅 **Date Filtering**: Filter reports by date range using `--since` and `--until`

‎docs/guide/statusline.md‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Statusline Integration (Beta) 🚀
2+
3+
Display real-time usage statistics in your Claude Code status line.
4+
5+
## Overview
6+
7+
The `statusline` command provides a compact, real-time view of your Claude Code usage, designed to integrate with Claude Code's status line hooks. It shows:
8+
9+
- 💬 **Current session cost** - Cost for your active conversation session
10+
- 💰 **Today's total cost** - Your cumulative spending for the current day
11+
- 🚀 **Current session block** - Cost and time remaining in your active 5-hour billing block
12+
- 🔥 **Burn rate** - Token consumption rate with visual indicators
13+
- 🤖 **Active model** - The Claude model you're currently using
14+
15+
## Setup
16+
17+
### Configure settings.json
18+
19+
Add this to your `~/.claude/settings.json` or `~/.config/claude/settings.json`:
20+
21+
```json
22+
{
23+
"statusLine": {
24+
"type": "command",
25+
"command": "ccusage statusline",
26+
"padding": 0 // Optional: set to 0 to let status line go to edge
27+
}
28+
}
29+
```
30+
31+
### Prerequisites
32+
33+
Ensure `ccusage` is installed globally or available in your PATH:
34+
35+
```bash
36+
npm install -g ccusage
37+
# or
38+
bun install -g ccusage
39+
```
40+
41+
**Note**: The status line command receives session information as JSON via stdin from Claude Code.
42+
43+
## Output Format
44+
45+
The statusline displays a compact, single-line summary:
46+
47+
```
48+
🤖 Opus | 💰 $0.23 session / $1.23 today / $0.45 block (2h 45m left) | 🔥 $0.12/hr
49+
```
50+
51+
### Components Explained
52+
53+
- **Model** (`🤖 Opus`): Currently active Claude model
54+
- **Session Cost** (`💰 $0.23 session`): Cost for the current conversation session
55+
- **Today's Cost** (`$1.23 today`): Total cost for the current day across all sessions
56+
- **Session Block** (`$0.45 block (2h 45m left)`): Current 5-hour block cost with remaining time
57+
- **Burn Rate** (`🔥 $0.12/hr`): Cost burn rate per hour with color-coded indicators:
58+
- Green text: Normal (< 2,000 tokens/min)
59+
- Yellow text: Moderate (2,000-5,000 tokens/min)
60+
- Red text: High (> 5,000 tokens/min)
61+
62+
When no active block exists:
63+
```
64+
🤖 Opus | 💰 $0.00 session / $0.00 today / No active block
65+
```
66+
67+
## Technical Details
68+
69+
The statusline command:
70+
- Reads session information from stdin (provided by Claude Code hooks)
71+
- Identifies the active 5-hour billing block
72+
- Calculates real-time burn rates and projections
73+
- Outputs a single line suitable for status bar display
74+
75+
## Beta Notice
76+
77+
⚠️ This feature is currently in **beta**. More customization options and features are coming soon:
78+
79+
- Custom format templates
80+
- Configurable burn rate thresholds
81+
- Additional metrics display options
82+
- Session-specific cost tracking
83+
84+
## Troubleshooting
85+
86+
### No Output Displayed
87+
88+
If the statusline doesn't show:
89+
1. Verify `ccusage` is in your PATH
90+
2. Check Claude Code logs for any errors
91+
3. Ensure you have valid usage data in your Claude data directory
92+
93+
### Incorrect Costs
94+
95+
If costs seem incorrect:
96+
- The command uses the same cost calculation as other ccusage commands
97+
- Verify with `ccusage daily` or `ccusage blocks` for detailed breakdowns
98+
99+
## Related Commands
100+
101+
- [`blocks`](./blocks-reports.md) - Detailed 5-hour billing block analysis
102+
- [`daily`](./daily-reports.md) - Daily usage reports
103+
- [`session`](./session-reports.md) - Session-based usage analysis

‎package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@
5252
"release": "bun lint && bun typecheck && vitest run && bun run build && bumpp",
5353
"start": "bun run ./src/index.ts",
5454
"test": "TZ=UTC vitest",
55+
"test:statusline": "cat test/statusline-test.json | bun run ./src/index.ts statusline",
56+
"test:statusline:dev": "cat test/statusline-test.json | bun run start statusline",
5557
"typecheck": "tsgo --noEmit"
5658
},
5759
"devDependencies": {

‎src/commands/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { dailyCommand } from './daily.ts';
66
import { mcpCommand } from './mcp.ts';
77
import { monthlyCommand } from './monthly.ts';
88
import { sessionCommand } from './session.ts';
9+
import { statuslineCommand } from './statusline.ts';
910
import { weeklyCommand } from './weekly.ts';
1011

1112
/**
@@ -18,6 +19,7 @@ subCommands.set('weekly', weeklyCommand);
1819
subCommands.set('session', sessionCommand);
1920
subCommands.set('blocks', blocksCommand);
2021
subCommands.set('mcp', mcpCommand);
22+
subCommands.set('statusline', statuslineCommand);
2123

2224
/**
2325
* Default command when no subcommand is specified (defaults to daily)

‎src/commands/statusline.ts‎

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
import type { StatuslineHookJson } from '../_types.ts';
2+
import path from 'node:path';
3+
import process from 'node:process';
4+
import { define } from 'gunshi';
5+
import pc from 'picocolors';
6+
import { calculateBurnRate } from '../_session-blocks.ts';
7+
import { statuslineHookJsonSchema } from '../_types.ts';
8+
import { formatCurrency } from '../_utils.ts';
9+
import { calculateTotals } from '../calculate-cost.ts';
10+
import { getClaudePaths, loadDailyUsageData, loadSessionBlockData, loadSessionData } from '../data-loader.ts';
11+
import { log, logger } from '../logger.ts';
12+
13+
/**
14+
* Reads JSON input from stdin
15+
* @returns Parsed StatuslineHookJson or null if invalid
16+
*/
17+
async function readStdinJson(): Promise<StatuslineHookJson | null> {
18+
return new Promise((resolve) => {
19+
let input = '';
20+
process.stdin.on('data', (chunk) => {
21+
input += String(chunk);
22+
});
23+
process.stdin.on('end', () => {
24+
try {
25+
const data = JSON.parse(input) as unknown;
26+
const parsed = statuslineHookJsonSchema.safeParse(data);
27+
if (parsed.success) {
28+
resolve(parsed.data);
29+
}
30+
else {
31+
logger.error('Invalid input JSON:', parsed.error);
32+
resolve(null);
33+
}
34+
}
35+
catch (error) {
36+
logger.error('Failed to parse JSON input:', error);
37+
resolve(null);
38+
}
39+
});
40+
});
41+
}
42+
43+
/**
44+
* Formats the remaining time for display
45+
* @param remaining - Remaining minutes
46+
* @returns Formatted time string
47+
*/
48+
function formatRemainingTime(remaining: number): string {
49+
const remainingHours = Math.floor(remaining / 60);
50+
const remainingMins = remaining % 60;
51+
52+
if (remainingHours > 0) {
53+
return `${remainingHours}h ${remainingMins}m left`;
54+
}
55+
return `${remainingMins}m left`;
56+
}
57+
58+
export const statuslineCommand = define({
59+
name: 'statusline',
60+
description: 'Display compact status line for Claude Code hooks (Beta)',
61+
args: {},
62+
async run() {
63+
// Set logger to silent for statusline output
64+
logger.level = 0;
65+
66+
// Read input from stdin
67+
const hookData = await readStdinJson();
68+
if (hookData == null) {
69+
log('❌ Invalid input');
70+
process.exit(1);
71+
}
72+
73+
// Get Claude paths
74+
const claudePaths = getClaudePaths();
75+
if (claudePaths.length === 0) {
76+
log('❌ No Claude data directory found');
77+
process.exit(1);
78+
}
79+
80+
// Extract session ID from transcript path
81+
// Path format: /path/to/projects/{project}/{session}/transcript.json
82+
const transcriptParts = hookData.transcript_path.split(path.sep);
83+
const sessionId = transcriptParts[transcriptParts.length - 2] ?? '';
84+
85+
// Load current session's cost
86+
let sessionCost = 0;
87+
try {
88+
const sessionData = await loadSessionData({
89+
mode: 'auto',
90+
});
91+
92+
// Find the current session
93+
const currentSession = sessionData.find(s => s.sessionId === sessionId);
94+
if (currentSession != null) {
95+
sessionCost = currentSession.totalCost;
96+
}
97+
}
98+
catch (error) {
99+
logger.error('Failed to load session data:', error);
100+
}
101+
102+
// Load today's usage data
103+
const today = new Date();
104+
const todayStr = today.toISOString().split('T')[0];
105+
106+
let todayCost = 0;
107+
try {
108+
const dailyData = await loadDailyUsageData({
109+
since: todayStr,
110+
until: todayStr,
111+
mode: 'auto',
112+
});
113+
114+
if (dailyData.length > 0) {
115+
const totals = calculateTotals(dailyData);
116+
todayCost = totals.totalCost;
117+
}
118+
}
119+
catch (error) {
120+
logger.error('Failed to load daily data:', error);
121+
}
122+
123+
// Load session block data to find active block
124+
let blockInfo = '';
125+
let burnRateInfo = '';
126+
try {
127+
const blocks = await loadSessionBlockData({
128+
mode: 'auto',
129+
});
130+
131+
// Only identify blocks if we have data
132+
if (blocks.length === 0) {
133+
blockInfo = 'No active block';
134+
}
135+
else {
136+
// Find active block that contains our session
137+
const activeBlock = blocks.find((block) => {
138+
if (!block.isActive) {
139+
return false;
140+
}
141+
142+
// Check if any entry in this block matches our session
143+
// Since we don't have direct session mapping in entries,
144+
// we use the active block that's currently running
145+
return true;
146+
});
147+
148+
if (activeBlock != null) {
149+
const now = new Date();
150+
const remaining = Math.round((activeBlock.endTime.getTime() - now.getTime()) / (1000 * 60));
151+
const blockCost = activeBlock.costUSD;
152+
153+
blockInfo = `${formatCurrency(blockCost)} block (${formatRemainingTime(remaining)})`;
154+
155+
// Calculate burn rate
156+
const burnRate = calculateBurnRate(activeBlock);
157+
if (burnRate != null) {
158+
const costPerHour = burnRate.costPerHour;
159+
const costPerHourStr = `${formatCurrency(costPerHour)}/hr`;
160+
161+
// Apply color based on burn rate (tokens per minute non-cache)
162+
let coloredBurnRate = costPerHourStr;
163+
if (burnRate.tokensPerMinuteForIndicator < 2000) {
164+
coloredBurnRate = pc.green(costPerHourStr); // Normal
165+
}
166+
else if (burnRate.tokensPerMinuteForIndicator < 5000) {
167+
coloredBurnRate = pc.yellow(costPerHourStr); // Moderate
168+
}
169+
else {
170+
coloredBurnRate = pc.red(costPerHourStr); // High
171+
}
172+
173+
burnRateInfo = ` | 🔥 ${coloredBurnRate}`;
174+
}
175+
}
176+
else {
177+
blockInfo = 'No active block';
178+
}
179+
}
180+
}
181+
catch (error) {
182+
logger.error('Failed to load block data:', error);
183+
blockInfo = 'No active block';
184+
}
185+
186+
// Get model display name
187+
const modelName = hookData.model.display_name;
188+
189+
// Format and output the status line
190+
// Format: 🤖 model | 💰 session / today / block | 🔥 burn
191+
const statusLine = `🤖 ${modelName} | 💰 ${formatCurrency(sessionCost)} session / ${formatCurrency(todayCost)} today / ${blockInfo}${burnRateInfo}`;
192+
193+
log(statusLine);
194+
},
195+
});

‎test/statusline-test.json‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"hook_event_name": "Status",
3+
"session_id": "test-session-123",
4+
"transcript_path": "/Users/test/.config/claude/projects/test-project/session-123/transcript.json",
5+
"cwd": "/Users/test/project",
6+
"model": {
7+
"id": "claude-opus-4-1",
8+
"display_name": "Opus"
9+
},
10+
"workspace": {
11+
"current_dir": "/Users/test/project",
12+
"project_dir": "/Users/test/project"
13+
}
14+
}

0 commit comments

Comments
 (0)