Skip to content
Merged
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
66 changes: 65 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ccreports

Reports Claude Code **tool calls, skills, slash commands, subagents, token usage and cost** from
Reports Claude Code (and [GitHub Copilot](#github-copilot)) **tool calls, skills, slash commands, subagents, token usage and cost** from
the local session transcripts in `~/.claude/projects`. Inspired by
[ccusage](https://github.com/ccusage/ccusage), which covers tokens and cost;
ccreports adds what you actually *did* with those tokens.
Expand Down Expand Up @@ -199,8 +199,72 @@ byte order mark so Excel shows non-ASCII characters correctly.
| `--no-subagents` | Exclude subagent transcripts |
| `--compact` | Hide cache token columns (automatic below 120 columns) |
| `--dir <path>` | Projects directory (repeatable). Default: `CLAUDE_CONFIG_DIR` (comma-separated) or `~/.claude` / `~/.config/claude` |
| `--source <src>` | `claude` (default), `copilot` or `all` - see [GitHub Copilot](#github-copilot) |
| `--copilot-dir <path>` | Copilot session-state directory (repeatable). Default: `COPILOT_HOME` or `~/.copilot`, then `session-state` |
| `-v, --version` | Print the ccreports version. Reports name it too: in the HTML header line, as a footer in table and Markdown output, and as `ccreportsVersion` in JSON |

### GitHub Copilot

`--source copilot` reports GitHub Copilot instead, from the session logs in
`~/.copilot/session-state/<id>/events.jsonl`. The Copilot CLI writes them,
and so does Copilot's agent in VS Code. `--source all` combines both tools in
one report. Every report works for Copilot, including `recommendations`.

```sh
node bin/ccreports.mjs --source copilot # summary
node bin/ccreports.mjs weekly -b --source copilot
node bin/ccreports.mjs --source all -a -f html -o both.html
```

How the Copilot logs map onto the reports:

- **Tokens.** Recent Copilot versions log usage per request
(`session.usage_record`). Older sessions only have totals per model for each
run, written at shutdown. These count as that many requests, at the time of
shutdown, and have no context size. Sessions that never shut down cleanly
have no token counts. Copilot's input tokens include cached tokens, so the
cached tokens are subtracted to match Claude's *Input* column.
- **Cost** is what Copilot billed in AI credits (1 AIU = $0.01). Requests
without AI credits are priced at Claude API rates when the model is a
Claude model; other models (GPT and local ones) are reported as unpriced.
The summary also shows the **premium requests** used.
- **Tools** keep Copilot's names (`view`, `powershell`, `apply_patch`, …).
MCP tools are named `mcp__<server>__<tool>`. `task` calls are subagent
launches. `-x` breaks down `powershell` / `bash` commands.
- **Tokens per tool** are estimates, as for Claude Code. Copilot logs few
requests that can be measured, and it trims old tool output, so a
session's estimates are scaled down to at most its total input. *Cost (est.)*
is the matching share of what the session was billed. Sessions without
token counts get no estimates.
- **Skills, slash commands, hooks, compactions and prompts** come from their
own events. Hooks are named by event (`PreToolUse`), since Copilot doesn't
log the command. **Pull requests** are the PR links in the output of
`gh pr create` or a `create_pull_request` MCP call.
- Installed plugins are listed for Claude Code only.

**Recommendations** run the same checks as for Claude Code. Their advice
names Copilot's own levers: `.github/copilot-instructions.md` / `AGENTS.md`,
custom agents (`.github/agents/`), skills, the `explore` agent, `/compact`,
`/clear`, `/context`, `/model`, `/mcp`, and plan mode and autopilot. Some
checks work differently for Copilot:

- **Long contexts and prompt-cache rebuilds** use only the requests logged one
by one. Shutdown totals have no context size.
- **Delegating exploration** is judged by the share of sessions that launched
a subagent. Older Copilot logs count subagents' tokens as the main
session's, so token shares can't show delegation.
- **The step-by-step coding check** also says how many coding sessions used
plan mode and autopilot.
- **Cheaper models for subagents** is skipped, since Copilot bills at its
own rates and premium-request multipliers.
- **Running work in parallel** looks at background agents only, since
Copilot has no worktree isolation.
- **Failing hooks:** a hook that errors counts as failed, even though Copilot
also denies the tool call it guarded.

With `--source all`, each product gets its own recommendations, weighed
against its own cost, and in JSON every recommendation has a `source`.

## What is counted

- **Tokens** – `usage` from each assistant message, deduplicated per
Expand Down
50 changes: 43 additions & 7 deletions bin/ccreports.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os';
import path from 'node:path';
import { parseArgs } from 'node:util';
import { loadRecords, defaultProjectDirs } from '../src/loader.mjs';
import { loadCopilotRecords, defaultCopilotDirs, mergeData } from '../src/copilot.mjs';
import { aggregate, parseDateArg, toJSON, REPORTS } from '../src/aggregate.mjs';
import { buildPeriodReport, buildSummary } from '../src/report.mjs';
import { FORMATS, toTerminal, toMarkdown, toCsv, toHtml } from '../src/formats.mjs';
Expand All @@ -14,7 +15,7 @@ import { openFile, FORMAT_EXTENSIONS } from '../src/open.mjs';
import { loadPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs';
import { VERSION } from '../src/version.mjs';

const HELP = `ccreports - Claude Code tool, skill, slash-command and token usage
const HELP = `ccreports - Claude Code (and GitHub Copilot) tool, skill, slash-command and token usage

Usage: ccreports [report] [options]

Expand All @@ -30,6 +31,7 @@ Reports:
recommendations Best-practice recommendations based on your usage, with the cost at stake

Options:
--source <src> claude (default), copilot (GitHub Copilot CLI / VS Code agent) or all
-s, --since <date> Include from this date (YYYYMMDD or YYYY-MM-DD)
-u, --until <date> Include up to and including this date
-p, --project <text> Only projects whose path contains <text> (case-insensitive)
Expand All @@ -51,6 +53,7 @@ Options:
--compact Hide cache token columns (table format)
--no-color Disable colors (also honors NO_COLOR)
--dir <path> Projects directory to scan (repeatable; default from CLAUDE_CONFIG_DIR or ~/.claude)
--copilot-dir <path> Copilot session-state directory (repeatable; default from COPILOT_HOME or ~/.copilot)
-v, --version Show the ccreports version
-h, --help Show this help
`;
Expand Down Expand Up @@ -86,6 +89,8 @@ try {
compact: { type: 'boolean' },
'no-color': { type: 'boolean' },
dir: { type: 'string', multiple: true },
source: { type: 'string' },
'copilot-dir': { type: 'string', multiple: true },
version: { type: 'boolean', short: 'v' },
help: { type: 'boolean', short: 'h' },
},
Expand All @@ -108,6 +113,8 @@ const report = positionals[0] ?? 'summary';
if (!REPORTS.includes(report)) fail(`unknown report "${report}". Expected one of: ${REPORTS.join(', ')}`);
if (positionals.length > 1) fail(`unexpected argument "${positionals[1]}"`);
if (opts.order && !['asc', 'desc'].includes(opts.order)) fail('--order must be asc or desc');
const source = (opts.source ?? 'claude').toLowerCase();
if (!['claude', 'copilot', 'all'].includes(source)) fail('--source must be claude, copilot or all');

let format = opts.json ? 'json' : (opts.format ?? 'table').toLowerCase();
if (format === 'md') format = 'markdown';
Expand Down Expand Up @@ -137,9 +144,17 @@ if (opts.timezone) {

const toTTY = !opts.output && !opts.open && process.stdout.isTTY;

const includeSubagents = !opts['no-subagents'];
const dirs = opts.dir?.length ? opts.dir : defaultProjectDirs();
const data = await loadRecords({ dirs, includeSubagents: !opts['no-subagents'] });
if (data.files === 0) fail(`no transcripts found in: ${dirs.join(', ')}`);
const copilotDirs = opts['copilot-dir']?.length ? opts['copilot-dir'] : defaultCopilotDirs();
const claudeData = source !== 'copilot' ? await loadRecords({ dirs, includeSubagents }) : null;
const copilotData = source !== 'claude' ? await loadCopilotRecords({ dirs: copilotDirs, includeSubagents }) : null;
const data = claudeData && copilotData ? mergeData(claudeData, copilotData) : claudeData ?? copilotData;
if (data.files === 0) {
const scanned = [...(claudeData ? dirs : []), ...(copilotData ? copilotDirs : [])];
fail(`no ${source === 'copilot' ? 'sessions' : 'transcripts'} found in: ${scanned.join(', ')}`);
}
const product = { claude: 'Claude Code', copilot: 'GitHub Copilot', all: 'Claude Code and GitHub Copilot' }[source];

const showCost = !opts['no-cost'];
let pricer, pricingSource;
Expand All @@ -162,7 +177,8 @@ if (showCost) {
}

// Installed plugins and what of each was used, in every report.
const plugins = pluginRows(await loadPlugins(dirs), result.totals, { project: opts.project });
// (Claude Code plugins only.)
const plugins = claudeData ? pluginRows(await loadPlugins(dirs), result.totals, { project: opts.project }) : [];

// Only the terminal table hides columns to fit the screen.
const compact = format === 'table' && (opts.compact || (toTTY && process.stdout.columns < 120));
Expand All @@ -178,16 +194,36 @@ const docOpts = {
project: opts.project,
pricer,
plugins,
product,
};

// The adoption assessment and recommendations: their own reports, or appended
// to another with --adoption / --recommendations.
const adoption = report === 'adoption' || opts.adoption ? buildAdoption(data, docOpts) : null;
const advice = report === 'recommendations' || opts.recommendations ? buildRecommendations(data, docOpts) : null;
// Recommendations per product: each names its own settings and commands, and
// is weighed against that product's own cost.
let advice = null;
if (report === 'recommendations' || opts.recommendations) {
const parts = [
['claude', claudeData],
['copilot', copilotData],
]
.filter(([, d]) => d?.files)
.map(([src, d]) => ({ src, doc: buildRecommendations(d, { ...docOpts, source: src }) }));
advice =
parts.length === 1
? { ...parts[0].doc, items: parts[0].doc.items.map((i) => ({ ...i, source: parts[0].src })) }
: {
title: `${product} recommendations`,
summary: parts.filter((p) => !p.doc.items.length).map((p) => `${p.doc.title.replace(/ recommendations.*/, '')}: ${p.doc.summary[0]}`),
sections: parts.flatMap((p) => p.doc.sections.map((s) => ({ ...s, title: p.doc.title }))),
items: parts.flatMap((p) => p.doc.items.map((i) => ({ ...i, source: p.src }))),
};
}

let output;
if (format === 'json') {
const meta = { report, since, until, pricingSource, ccreportsVersion: VERSION };
const meta = { report, source, since, until, pricingSource, ccreportsVersion: VERSION };
const adoptionJson = adoption && {
summary: adoption.summary,
phases: PHASES,
Expand Down Expand Up @@ -221,7 +257,7 @@ if (format === 'json') {
table: () => toTerminal(doc, { color: toTTY && !opts['no-color'] && !process.env.NO_COLOR, version: VERSION }) + '\n',
markdown: () => toMarkdown(doc, { version: VERSION }),
csv: () => toCsv(doc),
html: () => toHtml(doc, { pricingSource, version: VERSION }),
html: () => toHtml(doc, { pricingSource, version: VERSION, copilot: !!copilotData }),
}[format]();
}

Expand Down
17 changes: 15 additions & 2 deletions skills/report/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: report
description: Report the user's own Claude Code usage from their local session logs (~/.claude/projects) - tokens and estimated API cost, tool / skill / slash-command / hook / subagent counts and the tokens each consumed, context size, sessions, an adoption assessment (chat, assisted, agent-first, multi-agent) and best-practice recommendations backed by their data. Use when the user asks how much they used or spent, which tools or skills they use most, what consumes their tokens, how their usage trends per day/week/month/project/session, how far they have adopted agentic workflows, how to use Claude Code more effectively or cheaply, or wants such a report as a table, Markdown, CSV, JSON or HTML page.
description: Report the user's own Claude Code usage from their local session logs (~/.claude/projects), and their GitHub Copilot CLI / VS Code agent usage (~/.copilot/session-state) - tokens and estimated API cost, tool / skill / slash-command / hook / subagent counts and the tokens each consumed, context size, sessions, an adoption assessment (chat, assisted, agent-first, multi-agent) and best-practice recommendations backed by their data. Use when the user asks how much they used or spent, which tools or skills they use most, what consumes their tokens, how their usage trends per day/week/month/project/session, how far they have adopted agentic workflows, how to use Claude Code or Copilot more effectively or cheaply, how their Claude Code and Copilot usage compare, or wants such a report as a table, Markdown, CSV, JSON or HTML page.
argument-hint: "[summary|daily|weekly|monthly|session|project|adoption|recommendations] [options]"
---

Expand All @@ -14,7 +14,7 @@ absolute path from the "Base directory for this skill" line, quoted:
node "<base directory>/../../bin/ccreports.mjs" [report] [options]
```

It only reads local transcripts; the one network call fetches Anthropic's public
It only reads local session logs; the one network call fetches Anthropic's public
pricing page for cost estimates (cached for a day; `--offline` skips it).

## Choosing the command
Expand All @@ -32,6 +32,8 @@ the request:
| which programs / CLI commands Bash and PowerShell calls ran | add `-x` (`--shell`) to `summary` or a period report |
| an adoption / maturity assessment | `adoption`, or `-a` to add it to another report |
| advice: how to use Claude Code better or cheaper | `recommendations`, or `-r` to add it to another report |
| the same for GitHub Copilot (CLI or VS Code agent) | any of the above with `--source copilot` |
| Claude Code and Copilot together, or compared | any of the above with `--source all` (recommendations get a section per product) |

Useful options: `-s/--since` and `-u/--until` (`YYYYMMDD`), `-p/--project <text>`,
`-n/--top <n>`, `--compact`, `--no-cost`, `-f/--format table|json|csv|markdown|html`,
Expand Down Expand Up @@ -62,3 +64,14 @@ of every table. Keep these caveats in mind and mention them when relevant:
- Context size counts the main conversation only.
- The adoption phases are per session, from the user's own logs; PRs are those
Claude Code created.

With `--source copilot` or `all`, also keep in mind:

- Copilot cost is what it billed in AI credits (1 AIU = $0.01); where nothing
was billed, Claude models are priced at API rates and other models (GPT,
local) show as unpriced. The summary also lists premium requests.
- Older Copilot sessions only log totals per run at shutdown: no context size,
and subagent tokens are folded into the main session. Sessions that never
shut down cleanly have no token counts.
- Copilot's tokens per tool are rougher than Claude Code's: they are scaled
down to at most what each session sent.
11 changes: 7 additions & 4 deletions src/adoption.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ const SURFACES = {
'sdk-ts': 'Agent SDK',
'sdk-py': 'Agent SDK',
remote: 'Web',
'copilot-cli': 'Copilot CLI',
'copilot-vscode': 'Copilot in VS Code',
};

/** Places one session's stats in a phase (first matching rule wins). */
Expand Down Expand Up @@ -57,12 +59,13 @@ export function sessionStats(data, { since, until, project, timeZone, pricer } =
for (const t of data.tools) {
if (!inRange.has(t.sessionId)) continue;
const c = counts.get(t.sessionId) ?? { edits: 0, backgroundAgents: 0, worktrees: 0, agentMessages: 0, mcpCalls: 0, webCalls: 0 };
if (EDIT_TOOLS.has(t.name)) c.edits += 1;
// edit / web: flags set by the GitHub Copilot loader, whose tools have other names.
if (EDIT_TOOLS.has(t.name) || t.edit) c.edits += 1;
if (t.background) c.backgroundAgents += 1;
if (t.worktree) c.worktrees += 1;
if (t.name === 'SendMessage') c.agentMessages += 1;
if (t.name.startsWith('mcp__')) c.mcpCalls += 1;
if (t.name === 'WebSearch' || t.name === 'WebFetch') c.webCalls += 1;
if (t.name === 'WebSearch' || t.name === 'WebFetch' || t.web) c.webCalls += 1;
counts.set(t.sessionId, c);
}
return buckets.map((b) => {
Expand Down Expand Up @@ -220,10 +223,10 @@ export function buildAdoption(data, opts) {

const range = opts.since || opts.until ? ` (${opts.since ?? '…'} → ${opts.until ?? 'today'})` : '';
return {
title: `Claude Code adoption${range}`,
title: `${opts.product ?? 'Claude Code'} adoption${range}`,
summary: assess(stats, byPhase),
sections: [
{ title: 'Adoption cohorts', note: 'sessions by how they used Claude Code', cards: true, columns: cohortColumns, rows: cohortRows },
{ title: 'Adoption cohorts', note: `sessions by how they used ${opts.product ?? 'Claude Code'}`, cards: true, columns: cohortColumns, rows: cohortRows },
{
title: 'Phase mix per week',
note: 'by the week a session started',
Expand Down
21 changes: 14 additions & 7 deletions src/aggregate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ function newBucket(key) {
totalTokens: 0,
costUSD: 0,
requests: 0,
premiumRequests: 0, // GitHub Copilot
toolCalls: 0,
skillCalls: 0,
commandCount: 0,
Expand Down Expand Up @@ -138,7 +139,9 @@ function addUsage(entry, t, costUSD, f = 1) {

/** Prices an attributed item: tool input as output, then cache writes and re-reads. */
function attributedCost(t, pricer) {
if (!pricer || !t.model) return 0;
if (!pricer) return 0;
if (t.costUSD != null) return t.costUSD; // a share of billed GitHub Copilot cost
if (!t.model) return 0;
return (
pricer({
model: t.model,
Expand Down Expand Up @@ -197,9 +200,12 @@ export function aggregate(data, { report = 'summary', since, until, project, tim
if (!buckets) continue;
const total = rec.inputTokens + rec.outputTokens + rec.cacheCreationTokens + rec.cacheReadTokens;
const context = rec.inputTokens + rec.cacheCreationTokens + rec.cacheReadTokens;
const cost = pricer?.(rec) ?? 0;
// Copilot records carry their billed cost; the rest are priced here.
const cost = pricer ? rec.costUSD ?? pricer(rec) ?? 0 : 0;
// A record summing several requests (Copilot without per-request usage) has no context size.
const requests = rec.requests ?? 1;
for (const b of buckets) {
if (rec.agent == null) {
if (rec.agent == null && !rec.aggregated) {
b.contextTokensSum += context;
b.contextRequests += 1;
if (context > (b.sessionPeaks.get(rec.sessionId) ?? 0)) b.sessionPeaks.set(rec.sessionId, context);
Expand All @@ -210,15 +216,16 @@ export function aggregate(data, { report = 'summary', since, until, project, tim
b.cacheReadTokens += rec.cacheReadTokens;
b.totalTokens += total;
b.costUSD += cost;
b.requests += 1;
if (pricer && !pricer.isPriced(rec.model)) b.unpricedModels.add(rec.model);
b.requests += requests;
b.premiumRequests += rec.premiumRequests ?? 0;
if (pricer && rec.costUSD == null && !pricer.isPriced(rec.model)) b.unpricedModels.add(rec.model);
const m = b.models.get(rec.model) ?? { requests: 0, totalTokens: 0, costUSD: 0 };
m.requests += 1;
m.requests += requests;
m.totalTokens += total;
m.costUSD += cost;
b.models.set(rec.model, m);
const a = agentEntry(b, rec.agent);
a.requests += 1;
a.requests += requests;
a.inputTokens += rec.inputTokens;
a.outputTokens += rec.outputTokens;
a.cacheCreationTokens += rec.cacheCreationTokens;
Expand Down
Loading
Loading