Skip to content

Commit ca81a8d

Browse files
onot957claude
andcommitted
feat: implement 5-hour session window tracking (#23)
Add 5-hour session window tracking to monitor Claude Code usage against plan limits. - Add --windows flag to show 5-hour session statistics - Add --session-limit flag with default value of 50 (Claude Max plan) - Track sessions per calendar month (UTC) with visual warnings - Show usage percentage and remaining sessions - Support JSON output for window statistics Sessions are grouped into UTC-based 5-hour windows (00:00, 05:00, 10:00, 15:00, 20:00). This helps users track their usage against Claude's session-based billing limits. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 486b74d commit ca81a8d

7 files changed

Lines changed: 889 additions & 3 deletions

File tree

‎CLAUDE.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
2121
- `bun run start daily` - Show daily usage report
2222
- `bun run start monthly` - Show monthly usage report
2323
- `bun run start session` - Show session-based usage report
24+
- `bun run start session --windows` - Show 5-hour session window statistics
2425
- `bun run start daily --json` - Show daily usage report in JSON format
2526
- `bun run start monthly --json` - Show monthly usage report in JSON format
2627
- `bun run start session --json` - Show session usage report in JSON format
@@ -56,6 +57,8 @@ This is a CLI tool that analyzes Claude Code usage data from local JSONL files s
5657
- Raw usage data is parsed from JSONL with timestamp, token counts, and pre-calculated costs
5758
- Data is aggregated into daily summaries, monthly summaries, or session summaries
5859
- Sessions are identified by directory structure: `projects/{project}/{session}/{file}.jsonl`
60+
- 5-hour window tracking: Usage is grouped into UTC-based 5-hour windows (00:00, 05:00, 10:00, 15:00, 20:00)
61+
- Session limits: Monthly session usage is tracked and compared against plan limits (e.g., 50 for Max plan)
5962

6063
**External Dependencies:**
6164

‎README.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ This tool helps you understand the value you're getting from your subscription b
4141
- 📊 **Daily Report**: View token usage and costs aggregated by date
4242
- 📅 **Monthly Report**: View token usage and costs aggregated by month
4343
- 💬 **Session Report**: View usage grouped by conversation sessions
44+
- ⏰ **5-Hour Window Tracking**: Track usage in Claude's 5-hour session windows with `--windows` flag
4445
- 🤖 **Model Tracking**: See which Claude models you're using (Opus, Sonnet, etc.)
4546
- 📊 **Model Breakdown**: View per-model cost breakdown with `--breakdown` flag
4647
- 📅 **Date Filtering**: Filter reports by date range using `--since` and `--until`
@@ -51,6 +52,7 @@ This tool helps you understand the value you're getting from your subscription b
5152
- 🔄 **Cache Token Support**: Tracks and displays cache creation and cache read tokens separately
5253
- 🌐 **Offline Mode**: Use pre-cached pricing data without network connectivity with `--offline` (Claude models only)
5354
- 📏 **Responsive Tables**: Automatic table width adjustment for narrow terminals with intelligent word wrapping
55+
- 🚨 **Session Limit Warnings**: Monitor your monthly session usage against plan limits
5456

5557
## Important Disclaimer
5658

@@ -228,6 +230,10 @@ ccusage session --breakdown # Show cost breakdown by model
228230
# Use offline mode (no network required)
229231
ccusage session --offline # Use pre-cached pricing data
230232
ccusage session -O # Short alias for --offline
233+
234+
# Show 5-hour session window statistics
235+
ccusage session --windows # Show usage grouped by 5-hour windows with monthly limits
236+
ccusage session --windows --session-limit 100 # Specify custom session limit (default: 50)
231237
```
232238

233239
### Options
@@ -246,6 +252,13 @@ All commands support the following options:
246252
- `-h, --help`: Display help message
247253
- `-v, --version`: Display version
248254

255+
#### Session-specific Options
256+
257+
The `session` command has additional options for 5-hour window tracking:
258+
259+
- `-w, --windows`: Show 5-hour session window statistics instead of regular session report
260+
- `-l, --session-limit <number>`: Session limit for your plan (default: 50 for Claude Max plan)
261+
249262
#### Cost Calculation Modes
250263

251264
- **`auto`** (default): Uses pre-calculated `costUSD` values when available, falls back to calculating costs from token counts using model pricing

‎src/commands/session.ts‎

Lines changed: 296 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { CostMode } from '../types.internal.ts';
12
import process from 'node:process';
23
import { define } from 'gunshi';
34
import pc from 'picocolors';
@@ -6,17 +7,47 @@ import {
67
createTotalsObject,
78
getTotalTokens,
89
} from '../calculate-cost.ts';
9-
import { formatDateCompact, getDefaultClaudePath, loadSessionData } from '../data-loader.ts';
10+
import {
11+
calculateWindowStatistics,
12+
formatDateCompact,
13+
getDefaultClaudePath,
14+
groupWindowsByMonth,
15+
loadSessionData,
16+
type SessionUsage,
17+
type UsageData,
18+
} from '../data-loader.ts';
1019
import { detectMismatches, printMismatchReport } from '../debug.ts';
1120
import { log, logger } from '../logger.ts';
1221
import { sharedCommandConfig } from '../shared-args.internal.ts';
13-
import { formatCurrency, formatModelsDisplay, formatNumber, pushBreakdownRows } from '../utils.internal.ts';
22+
import {
23+
formatCurrency,
24+
formatDuration,
25+
formatModelsDisplay,
26+
formatNumber,
27+
getWindowStartTime,
28+
pushBreakdownRows,
29+
} from '../utils.internal.ts';
1430
import { ResponsiveTable } from '../utils.table.ts';
1531

1632
export const sessionCommand = define({
1733
name: 'session',
1834
description: 'Show usage report grouped by conversation session',
1935
...sharedCommandConfig,
36+
args: {
37+
...sharedCommandConfig.args,
38+
windows: {
39+
type: 'boolean',
40+
short: 'w',
41+
description: 'Show 5-hour session window statistics',
42+
default: false,
43+
},
44+
sessionLimit: {
45+
type: 'number',
46+
short: 'l',
47+
description: 'Session limit for your plan (e.g., 50 for Max plan)',
48+
default: 50,
49+
},
50+
},
2051
async run(ctx) {
2152
if (ctx.values.json) {
2253
logger.level = 0;
@@ -41,6 +72,14 @@ export const sessionCommand = define({
4172
process.exit(0);
4273
}
4374

75+
// Check if windows mode is requested
76+
if (ctx.values.windows) {
77+
// Window statistics mode
78+
await displayWindowStatistics(sessionData, ctx.values);
79+
return;
80+
}
81+
82+
// Regular session mode continues below
4483
// Calculate totals
4584
const totals = calculateTotals(sessionData);
4685

@@ -159,3 +198,258 @@ export const sessionCommand = define({
159198
}
160199
},
161200
});
201+
202+
/**
203+
* Display 5-hour window statistics
204+
*/
205+
async function displayWindowStatistics(
206+
sessionData: SessionUsage[],
207+
options: {
208+
json?: boolean;
209+
sessionLimit?: number;
210+
order?: string;
211+
mode?: string;
212+
since?: string;
213+
until?: string;
214+
debug?: boolean;
215+
debugSamples?: number;
216+
},
217+
): Promise<void> {
218+
// Extract all entries from session data to calculate windows
219+
// We need to reconstruct the raw entries since sessionData is already aggregated
220+
// For now, we'll load the data again with raw entries
221+
const allEntries: Array<{
222+
data: UsageData;
223+
timestamp: string;
224+
cost: number;
225+
sessionKey: string;
226+
model: string | undefined;
227+
}> = [];
228+
229+
// Load raw data to get all entries
230+
// This is a temporary solution - ideally we'd refactor loadSessionData to return raw entries
231+
const claudePath = getDefaultClaudePath();
232+
const path = await import('node:path');
233+
const claudeDir = path.join(claudePath, 'projects');
234+
const { glob } = await import('tinyglobby');
235+
const files = await glob(['**/*.jsonl'], {
236+
cwd: claudeDir,
237+
absolute: true,
238+
});
239+
240+
// Load and parse all entries
241+
const { readFile } = await import('node:fs/promises');
242+
const v = await import('valibot');
243+
const { PricingFetcher } = await import('../pricing-fetcher.ts');
244+
const { UsageDataSchema, calculateCostForEntry } = await import('../data-loader.ts');
245+
246+
const mode = options.mode ?? 'auto';
247+
using fetcher = mode === 'display' ? null : new PricingFetcher();
248+
249+
for (const file of files) {
250+
const content = await readFile(file, 'utf-8');
251+
const lines = content
252+
.trim()
253+
.split('\n')
254+
.filter(line => line.length > 0);
255+
256+
// Extract session info from file path
257+
const relativePath = path.relative(claudeDir, file);
258+
const parts = relativePath.split(path.sep);
259+
const sessionId = parts[parts.length - 2] ?? 'unknown';
260+
const joinedPath = parts.slice(0, -2).join(path.sep);
261+
const projectPath = joinedPath.length > 0 ? joinedPath : 'Unknown Project';
262+
const sessionKey = `${projectPath}/${sessionId}`;
263+
264+
for (const line of lines) {
265+
try {
266+
const parsed = JSON.parse(line) as unknown;
267+
const result = v.safeParse(UsageDataSchema, parsed);
268+
if (!result.success) {
269+
continue;
270+
}
271+
const data = result.output;
272+
273+
const cost = fetcher != null
274+
? await calculateCostForEntry(data, mode as CostMode, fetcher)
275+
: data.costUSD ?? 0;
276+
277+
allEntries.push({
278+
data,
279+
timestamp: data.timestamp,
280+
cost,
281+
sessionKey,
282+
model: data.message.model,
283+
});
284+
}
285+
catch {
286+
// Skip invalid lines
287+
}
288+
}
289+
}
290+
291+
// Calculate window statistics
292+
const windowMap = calculateWindowStatistics(allEntries);
293+
const monthlySummaries = groupWindowsByMonth(windowMap, {
294+
sessionLimit: options.sessionLimit,
295+
});
296+
297+
// Filter by date range if specified
298+
const filteredSummaries = monthlySummaries.filter((summary) => {
299+
if ((options.since !== undefined && options.since !== '') || (options.until !== undefined && options.until !== '')) {
300+
const monthNum = summary.month.replace('-', '');
301+
if (options.since !== undefined && options.since !== '' && monthNum < options.since.substring(0, 6)) {
302+
return false;
303+
}
304+
if (options.until !== undefined && options.until !== '' && monthNum > options.until.substring(0, 6)) {
305+
return false;
306+
}
307+
}
308+
return true;
309+
});
310+
311+
if (options.json === true) {
312+
// JSON output
313+
const jsonOutput = {
314+
monthlySummaries: filteredSummaries.map(summary => ({
315+
month: summary.month,
316+
windowCount: summary.windowCount,
317+
sessionLimit: summary.sessionLimit,
318+
remainingSessions: summary.remainingSessions,
319+
utilizationPercent: summary.utilizationPercent,
320+
totalCost: summary.totalCost,
321+
totalTokens: summary.totalTokens,
322+
windows: summary.windows.map(window => ({
323+
windowId: window.windowId,
324+
startTime: window.startTimestamp,
325+
endTime: window.endTimestamp,
326+
duration: window.duration,
327+
messageCount: window.messageCount,
328+
sessionCount: window.sessionCount,
329+
inputTokens: window.inputTokens,
330+
outputTokens: window.outputTokens,
331+
cacheCreationTokens: window.cacheCreationTokens,
332+
cacheReadTokens: window.cacheReadTokens,
333+
totalCost: window.totalCost,
334+
modelsUsed: window.modelsUsed,
335+
})),
336+
})),
337+
};
338+
log(JSON.stringify(jsonOutput, null, 2));
339+
return;
340+
}
341+
342+
// Table output
343+
logger.box('Claude Code 5-Hour Session Windows');
344+
345+
for (const summary of filteredSummaries) {
346+
// Monthly header
347+
let header = `\n${pc.bold(summary.month)}: ${summary.windowCount} sessions`;
348+
349+
if (summary.sessionLimit != null) {
350+
const utilPercent = summary.utilizationPercent ?? 0;
351+
const utilColor = utilPercent >= 90
352+
? pc.red
353+
: utilPercent >= 80
354+
? pc.yellow
355+
: pc.green;
356+
357+
header += ` used (${utilColor(`${summary.utilizationPercent?.toFixed(1)}%`)} of ${summary.sessionLimit} limit)`;
358+
359+
log(header);
360+
361+
const remaining = summary.remainingSessions ?? 0;
362+
if (remaining <= 5 && remaining > 0) {
363+
log(pc.yellow(`[WARNING] Only ${summary.remainingSessions} sessions remaining`));
364+
}
365+
else if (summary.remainingSessions === 0) {
366+
log(pc.red('[LIMIT REACHED] Session limit reached'));
367+
}
368+
else {
369+
log(pc.green(`[OK] ${summary.remainingSessions} sessions remaining`));
370+
}
371+
}
372+
else {
373+
log(header);
374+
}
375+
376+
log(pc.dim('Note: Sessions are counted per calendar month (UTC).'));
377+
log(pc.dim('Your actual billing cycle may differ.\n'));
378+
379+
// Create window table
380+
const table = new ResponsiveTable({
381+
head: [
382+
'Window Start',
383+
'Duration',
384+
'Messages',
385+
'Sessions',
386+
'Tokens',
387+
'Cost',
388+
],
389+
style: {
390+
head: ['cyan'],
391+
},
392+
colAligns: [
393+
'left',
394+
'right',
395+
'right',
396+
'right',
397+
'right',
398+
'right',
399+
],
400+
dateFormatter: formatDateCompact,
401+
});
402+
403+
// Show top 10 windows
404+
const windowsToShow = summary.windows.slice(0, 10);
405+
406+
for (const window of windowsToShow) {
407+
const startTime = getWindowStartTime(window.windowId);
408+
const localTime = startTime.toLocaleString();
409+
const duration = formatDuration(window.duration);
410+
const totalTokens = window.inputTokens + window.outputTokens
411+
+ window.cacheCreationTokens + window.cacheReadTokens;
412+
413+
table.push([
414+
localTime,
415+
duration,
416+
formatNumber(window.messageCount),
417+
formatNumber(window.sessionCount),
418+
formatNumber(totalTokens),
419+
formatCurrency(window.totalCost),
420+
]);
421+
}
422+
423+
if (summary.windows.length > 10) {
424+
table.push([
425+
pc.dim(`... and ${summary.windows.length - 10} more windows`),
426+
'',
427+
'',
428+
'',
429+
'',
430+
'',
431+
]);
432+
}
433+
434+
// Add totals row
435+
table.push([
436+
'─'.repeat(19),
437+
'─'.repeat(8),
438+
'─'.repeat(8),
439+
'─'.repeat(8),
440+
'─'.repeat(12),
441+
'─'.repeat(10),
442+
]);
443+
444+
table.push([
445+
pc.yellow('Total'),
446+
'',
447+
'',
448+
formatNumber(summary.windowCount),
449+
formatNumber(summary.totalTokens),
450+
formatCurrency(summary.totalCost),
451+
]);
452+
453+
log(table.toString());
454+
}
455+
}

0 commit comments

Comments
 (0)