Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/codex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ npx @ccusage/codex@latest daily --since 20250911 --until 20250917
# JSON output for scripting
npx @ccusage/codex@latest daily --json

# Weekly usage grouped by week
npx @ccusage/codex@latest weekly

# Monthly usage grouped by month
npx @ccusage/codex@latest monthly

Expand All @@ -86,7 +89,7 @@ Useful environment variables:
- 📊 Responsive terminal tables shared with the `ccusage` CLI
- 💵 Offline-first pricing cache with automatic LiteLLM refresh when needed
- 🤖 Per-model token and cost aggregation, including cached token accounting
- 📅 Daily and monthly rollups with identical CLI options
- 📅 Daily, weekly, and monthly rollups with identical CLI options
- 📄 JSON output for further processing or scripting

## Documentation
Expand Down
18 changes: 18 additions & 0 deletions apps/codex/src/_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ export type MonthlyUsageSummary = {
models: Map<string, ModelUsage>;
} & TokenUsageDelta;

export type WeeklyUsageSummary = {
week: string;
firstTimestamp: string;
costUSD: number;
models: Map<string, ModelUsage>;
} & TokenUsageDelta;

export type SessionUsageSummary = {
sessionId: string;
firstTimestamp: string;
Expand Down Expand Up @@ -76,6 +83,17 @@ export type MonthlyReportRow = {
models: Record<string, ModelUsage>;
};

export type WeeklyReportRow = {
week: string;
inputTokens: number;
cachedInputTokens: number;
outputTokens: number;
reasoningOutputTokens: number;
totalTokens: number;
costUSD: number;
models: Record<string, ModelUsage>;
};

export type SessionReportRow = {
sessionId: string;
lastActivity: string;
Expand Down
187 changes: 187 additions & 0 deletions apps/codex/src/commands/weekly.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import process from 'node:process';
import {
addEmptySeparatorRow,
formatCurrency,
formatDateCompact,
formatModelsDisplayMultiline,
formatNumber,
ResponsiveTable,
} from '@ccusage/terminal/table';
import { define } from 'gunshi';
import pc from 'picocolors';
import { DEFAULT_TIMEZONE } from '../_consts.ts';
import { sharedArgs } from '../_shared-args.ts';
import { formatModelsList, splitUsageTokens } from '../command-utils.ts';
import { loadTokenUsageEvents } from '../data-loader.ts';
import { normalizeFilterDate } from '../date-utils.ts';
import { log, logger } from '../logger.ts';
import { CodexPricingSource } from '../pricing.ts';
import { buildWeeklyReport } from '../weekly-report.ts';

const TABLE_COLUMN_COUNT = 8;

export const weeklyCommand = define({
name: 'weekly',
description: 'Show Codex token usage grouped by week',
args: sharedArgs,
async run(ctx) {
const jsonOutput = Boolean(ctx.values.json);
if (jsonOutput) {
logger.level = 0;
}

let since: string | undefined;
let until: string | undefined;

try {
since = normalizeFilterDate(ctx.values.since);
until = normalizeFilterDate(ctx.values.until);
} catch (error) {
logger.error(String(error));
process.exit(1);
}

const { events, missingDirectories } = await loadTokenUsageEvents();

for (const missing of missingDirectories) {
logger.warn(`Codex session directory not found: ${missing}`);
}

if (events.length === 0) {
log(jsonOutput ? JSON.stringify({ weekly: [], totals: null }) : 'No Codex usage data found.');
return;
}

const pricingSource = new CodexPricingSource({
offline: ctx.values.offline,
});

try {
const rows = await buildWeeklyReport(events, {
pricingSource,
timezone: ctx.values.timezone,
locale: ctx.values.locale,
since,
until,
});

if (rows.length === 0) {
log(
jsonOutput
? JSON.stringify({ weekly: [], totals: null })
: 'No Codex usage data found for provided filters.',
);
return;
}

const totals = rows.reduce(
(acc, row) => {
acc.inputTokens += row.inputTokens;
acc.cachedInputTokens += row.cachedInputTokens;
acc.outputTokens += row.outputTokens;
acc.reasoningOutputTokens += row.reasoningOutputTokens;
acc.totalTokens += row.totalTokens;
acc.costUSD += row.costUSD;
return acc;
},
{
inputTokens: 0,
cachedInputTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0,
totalTokens: 0,
costUSD: 0,
},
);

if (jsonOutput) {
log(
JSON.stringify(
{
weekly: rows,
totals,
},
null,
2,
),
);
return;
}

logger.box(
`Codex Token Usage Report - Weekly (Timezone: ${ctx.values.timezone ?? DEFAULT_TIMEZONE})`,
);

const table: ResponsiveTable = new ResponsiveTable({
head: [
'Week',
'Models',
'Input',
'Output',
'Reasoning',
'Cache Read',
'Total Tokens',
'Cost (USD)',
],
colAligns: ['left', 'left', 'right', 'right', 'right', 'right', 'right', 'right'],
compactHead: ['Week', 'Models', 'Input', 'Output', 'Cost (USD)'],
compactColAligns: ['left', 'left', 'right', 'right', 'right'],
compactThreshold: 100,
forceCompact: ctx.values.compact,
style: { head: ['cyan'] },
dateFormatter: (dateStr: string) => formatDateCompact(dateStr),
});

const totalsForDisplay = {
inputTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
cacheReadTokens: 0,
totalTokens: 0,
costUSD: 0,
};

for (const row of rows) {
const split = splitUsageTokens(row);
totalsForDisplay.inputTokens += split.inputTokens;
totalsForDisplay.outputTokens += split.outputTokens;
totalsForDisplay.reasoningTokens += split.reasoningTokens;
totalsForDisplay.cacheReadTokens += split.cacheReadTokens;
totalsForDisplay.totalTokens += row.totalTokens;
totalsForDisplay.costUSD += row.costUSD;

table.push([
row.week,
formatModelsDisplayMultiline(formatModelsList(row.models)),
formatNumber(split.inputTokens),
formatNumber(split.outputTokens),
formatNumber(split.reasoningTokens),
formatNumber(split.cacheReadTokens),
formatNumber(row.totalTokens),
formatCurrency(row.costUSD),
]);
}

addEmptySeparatorRow(table, TABLE_COLUMN_COUNT);
table.push([
pc.yellow('Total'),
'',
pc.yellow(formatNumber(totalsForDisplay.inputTokens)),
pc.yellow(formatNumber(totalsForDisplay.outputTokens)),
pc.yellow(formatNumber(totalsForDisplay.reasoningTokens)),
pc.yellow(formatNumber(totalsForDisplay.cacheReadTokens)),
pc.yellow(formatNumber(totalsForDisplay.totalTokens)),
pc.yellow(formatCurrency(totalsForDisplay.costUSD)),
]);

log(table.toString());

if (table.isCompactMode()) {
logger.info('\nRunning in Compact Mode');
logger.info('Expand terminal width to see cache metrics and total tokens');
}
} finally {
pricingSource[Symbol.dispose]();
}
},
});
11 changes: 11 additions & 0 deletions apps/codex/src/date-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,17 @@ export function isWithinRange(dateKey: string, since?: string, until?: string):
return true;
}

export function toWeekKey(timestamp: string, timezone?: string): string {
const dateKey = toDateKey(timestamp, timezone);
const [yearStr = '0', monthStr = '1', dayStr = '1'] = dateKey.split('-');
const year = Number.parseInt(yearStr, 10);
const month = Number.parseInt(monthStr, 10);
const day = Number.parseInt(dayStr, 10);
const date = new Date(Date.UTC(year, month - 1, day));
date.setUTCDate(date.getUTCDate() - date.getUTCDay());
return date.toISOString().slice(0, 10);
}

export function formatDisplayDate(dateKey: string, locale?: string, _timezone?: string): string {
// dateKey is already computed for the target timezone via toDateKey().
// Treat it as a plain calendar date and avoid shifting it by applying a timezone.
Expand Down
2 changes: 2 additions & 0 deletions apps/codex/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ import { description, name, version } from '../package.json';
import { dailyCommand } from './commands/daily.ts';
import { monthlyCommand } from './commands/monthly.ts';
import { sessionCommand } from './commands/session.ts';
import { weeklyCommand } from './commands/weekly.ts';

const subCommands = new Map([
['daily', dailyCommand],
['weekly', weeklyCommand],
['monthly', monthlyCommand],
['session', sessionCommand],
]);
Expand Down
Loading