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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,18 @@ sections above.
`.meta.json`), next to a `(main session)` row; *Launches* counts `Agent`
tool calls by requested `subagent_type`. The *Agents* column in period
reports is the number of launches.
- **Usage limits** – the error message Claude Code writes when a plan's usage
limit stops a request (`isApiErrorMessage`, `error: "rate_limit"`,
`apiError: "usage_limit_reached"`), deduplicated by uuid. The limit type
(5-hour, weekly, weekly Opus / Sonnet, extra usage) and reset time come from
its `rate_limit_info`, or from the message text in versions that don't log
them; older versions' `Claude AI usage limit reached|<reset>` and team or
enterprise spend limits count too. Short capacity 429s that Claude Code
retries on its own (`apiErrorIsTransient`) are not usage limits. When a limit
was hit, the summary and period reports add a *Usage limits* table (hits,
sessions, last hit, median time to reset) and a summary line; JSON output
always has `usageLimits`. For Copilot: `session.error` events of type
`quota` (premium requests used up) and `rate_limit`. Cursor logs no errors.
- **Cost** – estimated per request at Claude API list prices, parsed from
Anthropic's [pricing page](https://platform.claude.com/docs/en/about-claude/pricing)
and cached for 24h in `%LOCALAPPDATA%\ccreports` / `~/.cache/ccreports`;
Expand Down
10 changes: 9 additions & 1 deletion bin/ccreports.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { INTENTS } from '../src/intent.mjs';
import { buildRecommendations } from '../src/recommendations.mjs';
import { openFile, FORMAT_EXTENSIONS } from '../src/open.mjs';
import { loadPlugins, loadCopilotPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs';
import { limitStats, limitParts, limitsJSON } from '../src/limits.mjs';
import { VERSION } from '../src/version.mjs';

const HELP = `ccreports - Claude Code (and GitHub Copilot, Cursor) tool, skill, slash-command and token usage
Expand Down Expand Up @@ -278,6 +279,11 @@ if (report === 'recommendations' || opts.recommendations) {
};
}

// Usage-limit hits, in the summary and the period reports.
const usageLimits = ['adoption', 'recommendations'].includes(report)
? null
: limitStats(data, { since, until, project: opts.project, timeZone: opts.timezone });

let output;
if (format === 'json') {
const meta = { report, source, since, until, pricingSource, ccreportsVersion: VERSION };
Expand Down Expand Up @@ -311,6 +317,7 @@ if (format === 'json') {
} else {
json = { ...meta, rows: result.buckets.map(toJSON), totals: toJSON(result.totals), plugins: pluginsJSON(plugins) };
}
if (usageLimits) json.usageLimits = limitsJSON(usageLimits);
if (adoptionJson && report !== 'adoption') json.adoption = adoptionJson;
if (advice && report !== 'recommendations') json.recommendations = advice.items;
output = JSON.stringify(json, null, 2) + '\n';
Expand All @@ -320,7 +327,8 @@ if (format === 'json') {
const own = { adoption, intents: intentDoc, recommendations: advice }[report];
let doc = own ?? (report === 'summary' ? buildSummary(result, docOpts) : buildPeriodReport(report, result, docOpts));
// Appended parts: their summary lines on top, their sections after the report's own.
for (const part of [adoption, advice]) {
const limitDoc = usageLimits && limitParts(usageLimits, { timeZone: opts.timezone });
for (const part of [limitDoc, adoption, advice]) {
if (!part || part === doc) continue;
doc = { ...doc, summary: [...(doc.summary ?? []), ...part.summary], sections: [...doc.sections, ...part.sections] };
}
Expand Down
4 changes: 4 additions & 0 deletions skills/report/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ the request:
| The user wants | Command |
|---|---|
| an overview, totals, top tools / skills / commands / hooks / models | `summary` (default) |
| how often they hit a usage limit (5-hour, weekly, Copilot quota) | `summary`, or `daily` / `weekly` for when; `-j` for each hit |
| which plugins are installed (version, enabled) and whether they're used | any report (its *Installed plugins* table), e.g. `summary` |
| a trend over time | `daily`, `weekly` or `monthly` |
| per conversation or per repository | `session` or `project` |
Expand Down Expand Up @@ -107,6 +108,9 @@ of every table. Keep these caveats in mind and mention them when relevant:
- Tokens per tool / skill (shown with `~`) are reconstructed from context growth
and include re-reads of the result in later requests; subagent tokens are exact.
- Context size counts the main conversation only.
- Usage limits (the *Usage limits* table, `usageLimits` in JSON) count the times
a plan's 5-hour, weekly or spend limit, or Copilot's premium request quota or
rate limit, stopped a session. The table only appears when one was hit.
- The adoption phases are per session, from the user's own logs; PRs are those
Claude Code created.
- Session intent (bug fix, new development, refactoring, ...) comes from rules
Expand Down
13 changes: 12 additions & 1 deletion src/copilot.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { FileAttribution, createCalibration, charsPerToken, resolveTokens } from
import { shellCommands } from './shell.mjs';
import { errorLine, normalizeSkillName, patchFiles } from './loader.mjs';
import { promptText, workMessages } from './intent.mjs';
import { copilotLimit } from './limits.mjs';

const NANO_AIU_PER_USD = 1e11;
const SHELLS = { powershell: 'PowerShell', bash: 'Bash' };
Expand Down Expand Up @@ -112,6 +113,7 @@ export async function loadCopilotRecords({ dirs = defaultCopilotDirs(), includeS
const skills = new Map();
const commands = new Map();
const hooks = new Map();
const limits = new Map(); // event id -> usage-limit hit
const titles = new Map();
const sessions = new Map();
const psNames = new Map();
Expand Down Expand Up @@ -188,6 +190,13 @@ export async function loadCopilotRecords({ dirs = defaultCopilotDirs(), includeS
if (d.agentId) agentTypes.set(d.agentId, data.agentType || data.agentName || 'general-purpose');
break;

case 'session.error': {
// Premium request quota used up (402) or rate limited (429): the request is not answered.
const hit = copilotLimit(data);
if (hit) limits.set(d.id ?? `${id}:${d.timestamp}`, { ...base(), ...hit });
break;
}

case 'session.compaction_complete':
if (data.success === false) break;
attributionOf(d.agentId).compact();
Expand Down Expand Up @@ -431,6 +440,7 @@ export async function loadCopilotRecords({ dirs = defaultCopilotDirs(), includeS
skills: [...skills.values()],
commands: [...commands.values()],
hooks: [...hooks.values()],
limits: [...limits.values()],
titles,
};
}
Expand All @@ -447,11 +457,12 @@ export function mergeData(...parts) {
skills: [...first.skills],
commands: [...first.commands],
hooks: [...first.hooks],
limits: [...(first.limits ?? [])],
events: [...(first.events ?? [])],
};
for (const p of rest) {
out.files += p.files;
for (const k of ['usage', 'tools', 'skills', 'commands', 'hooks', 'events']) out[k].push(...(p[k] ?? []));
for (const k of ['usage', 'tools', 'skills', 'commands', 'hooks', 'events', 'limits']) out[k].push(...(p[k] ?? []));
for (const [k, v] of p.sessions) out.sessions.set(k, v);
for (const [k, v] of p.titles) out.titles.set(k, v);
}
Expand Down
1 change: 1 addition & 0 deletions src/cursor.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ export async function loadCursorRecords({ dirs = defaultCursorDirs(), userDirs =
skills,
commands,
hooks: [],
limits: [], // Cursor logs no errors
events,
titles,
};
Expand Down
129 changes: 129 additions & 0 deletions src/limits.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Usage limits: the times a session was stopped because the plan's usage limit
// was reached (Claude Code's 5-hour or weekly limits, a spend limit; Copilot's
// premium request quota or its rate limit). Short capacity hiccups the client
// retries on its own are not usage limits and are left out.

import { recordFilter, dateFormatter } from './aggregate.mjs';

export const LIMIT_KINDS = {
five_hour: '5-hour limit',
seven_day: 'Weekly limit',
seven_day_opus: 'Weekly Opus limit',
seven_day_sonnet: 'Weekly Sonnet limit',
seven_day_overage_included: 'Weekly limit (with extra usage)',
overage: 'Extra usage limit',
spend: 'Spend limit',
quota: 'Premium request quota',
rate_limit: 'Rate limit',
unknown: 'Usage limit',
};

const USAGE_TEXT = /usage limit|limit reached|hit your [\w -]*limit|limit (will )?resets?|resets? (at|in) /i;
const LEGACY = /^Claude AI usage limit reached\|(\d{9,})/; // older Claude Code: "…|<reset epoch seconds>"

function kindFromText(text) {
if (/opus/i.test(text) && /week|7-day/i.test(text)) return 'seven_day_opus';
if (/sonnet/i.test(text) && /week|7-day/i.test(text)) return 'seven_day_sonnet';
if (/week|7-day/i.test(text)) return 'seven_day';
if (/5-hour|five-hour|session limit/i.test(text)) return 'five_hour';
return 'unknown';
}

const isoFromEpoch = (seconds) => {
const n = Number(seconds);
if (!Number.isFinite(n) || n <= 0) return null;
return new Date(n < 1e12 ? n * 1000 : n).toISOString();
};

/**
* A Claude Code transcript line that reports a usage limit: { kind, resetsAt }
* or null. `text` is the message's text.
*/
export function claudeLimit(d, text) {
const legacy = LEGACY.exec(text);
if (legacy) return { kind: 'five_hour', resetsAt: isoFromEpoch(legacy[1]) };
if (!d?.isApiErrorMessage) return null;
if (d.error === 'billing_error' && /spend limit|monthly (spend|usage) limit/i.test(text)) return { kind: 'spend', resetsAt: null };
const info = d.apiErrorParams?.rate_limit_info;
const usage = d.apiError === 'usage_limit_reached' || (d.error === 'rate_limit' && !d.apiErrorIsTransient && USAGE_TEXT.test(text));
if (!usage) return null;
const kind = info?.rateLimitType in LIMIT_KINDS ? info.rateLimitType : /spend limit/i.test(text) ? 'spend' : kindFromText(text);
return { kind, resetsAt: isoFromEpoch(info?.resetsAt) };
}

/** A Copilot session.error event's data that reports a usage limit: { kind, resetsAt } or null. */
export function copilotLimit(data) {
if (data?.errorType === 'quota' || data?.statusCode === 402) return { kind: 'quota', resetsAt: null };
if (data?.errorType === 'rate_limit') return { kind: 'rate_limit', resetsAt: null };
return null;
}

const median = (values) => {
if (!values.length) return null;
const v = [...values].sort((a, b) => a - b);
const mid = Math.floor(v.length / 2);
return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
};

/** Usage-limit hits in the selected range, per kind. */
export function limitStats(data, { since, until, project, timeZone } = {}) {
const inRange = recordFilter({ since, until, project, timeZone });
const hits = (data.limits ?? []).filter((h) => inRange(h)).sort((a, b) => (a.timestamp < b.timestamp ? -1 : 1));
const kinds = new Map();
for (const h of hits) {
const k = kinds.get(h.kind) ?? { kind: h.kind, title: LIMIT_KINDS[h.kind] ?? LIMIT_KINDS.unknown, hits: 0, sessions: new Set(), lastHit: null, waits: [] };
k.hits += 1;
k.sessions.add(h.sessionId);
k.lastHit = h.timestamp;
if (h.resetsAt && h.resetsAt > h.timestamp) k.waits.push(Date.parse(h.resetsAt) - Date.parse(h.timestamp));
kinds.set(h.kind, k);
}
const byKind = [...kinds.values()]
.sort((a, b) => b.hits - a.hits)
.map(({ waits, sessions, ...k }) => ({ ...k, sessions: sessions.size, medianWaitMs: median(waits) }));
return { hits, byKind, sessions: new Set(hits.map((h) => h.sessionId)).size };
}

/** "2h 15m", "3d 4h", "40m". */
export function duration(ms) {
if (ms == null) return '';
const m = Math.round(ms / 60000);
if (m < 60) return `${m}m`;
const h = Math.floor(m / 60);
if (h < 48) return m % 60 ? `${h}h ${m % 60}m` : `${h}h`;
return `${Math.floor(h / 24)}d ${h % 24}h`;
}

const right = (title) => ({ title, align: 'right' });
const left = (title) => ({ title, align: 'left' });

/** Report sections and summary line; nothing when no limit was hit. */
export function limitParts(stats, { timeZone } = {}) {
if (!stats.hits.length) return { summary: [], sections: [] };
const day = dateFormatter(timeZone);
const last = stats.hits.at(-1);
const times = stats.hits.length === 1 ? 'once' : `${stats.hits.length} times`;
return {
summary: [
`A usage limit stopped ${stats.sessions} session${stats.sessions === 1 ? '' : 's'} ${times}; the last was a ${LIMIT_KINDS[last.kind]?.toLowerCase() ?? 'usage limit'} on ${day(last.timestamp)}.`,
],
sections: [
{
title: 'Usage limits',
note: 'times a session was stopped until the limit reset',
columns: [left('Limit'), right('Hits'), right('Sessions'), left('Last hit'), right('Median time to reset')],
rows: stats.byKind.map((k) => ({ cells: [k.title, k.hits, k.sessions, day(k.lastHit), duration(k.medianWaitMs)] })),
},
],
};
}

/** For --json. */
export function limitsJSON(stats) {
return {
hits: stats.hits.length,
sessions: stats.sessions,
byKind: stats.byKind,
events: stats.hits.map(({ timestamp, sessionId, project, agent, source, kind, resetsAt }) => ({ timestamp, sessionId, project, agent, source, kind, resetsAt })),
};
}
10 changes: 9 additions & 1 deletion src/loader.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import path from 'node:path';
import { FileAttribution, createCalibration, charsPerToken, resolveTokens } from './attribution.mjs';
import { SHELL_TOOLS, shellCommands } from './shell.mjs';
import { promptText, workMessages } from './intent.mjs';
import { claudeLimit } from './limits.mjs';

const SKILL_CONTENT_PREFIX = 'Base directory for this skill';
const COMMAND_RE = /<command-name>([^<]+)<\/command-name>/;
Expand Down Expand Up @@ -111,6 +112,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent
const skills = new Map(); // tool_use id | user-message uuid -> record
const commands = new Map(); // user-message uuid -> record
const hooks = new Map(); // attachment uuid -> record
const limits = new Map(); // error-message uuid -> usage-limit hit
const titles = new Map(); // sessionId -> ai title
// sessionId -> { entrypoint, prompts: Set<uuid>, prs: Set<url>, compactions: Set<uuid>, modes: Set<permission mode>,
// branches: Set<name>, firstPrompt, workMessages: Map<tool id, commit / PR titles> } (adoption / recommendations)
Expand Down Expand Up @@ -244,6 +246,11 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent
}

if (d.type === 'assistant') {
// A usage limit stopped the request: Claude Code writes its own error message.
if (d.isApiErrorMessage || d.message?.model === '<synthetic>') {
const hit = claudeLimit(d, textOf(d.message?.content));
if (hit) limits.set(d.uuid ?? `${file}:${base.timestamp}`, { ...base, source: 'claude', ...hit });
}
const m = d.message ?? {};
const u = m.usage;
const key = m.id ? `${m.id}:${d.requestId ?? ''}` : d.uuid;
Expand Down Expand Up @@ -350,7 +357,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent
attributed.push(...attribution.finish());
}

for (const map of [usage, tools, skills, commands, hooks]) {
for (const map of [usage, tools, skills, commands, hooks, limits]) {
for (const rec of map.values()) rec.project = sessionStart.get(rec.sessionId)?.cwd ?? rec.project;
}

Expand Down Expand Up @@ -380,6 +387,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent
skills: [...skills.values()],
commands: [...commands.values()],
hooks: [...hooks.values()],
limits: [...limits.values()],
titles,
};
}
Loading
Loading