1+ import type { CostMode } from '../types.internal.ts' ;
12import process from 'node:process' ;
23import { define } from 'gunshi' ;
34import 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' ;
1019import { detectMismatches , printMismatchReport } from '../debug.ts' ;
1120import { log , logger } from '../logger.ts' ;
1221import { 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' ;
1430import { ResponsiveTable } from '../utils.table.ts' ;
1531
1632export 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