Compare commits

..

10 Commits

Author SHA1 Message Date
Claude
b3930433ec Add Apache 2.0 LICENSE to session-report plugin 2026-04-08 17:10:13 +00:00
Thariq Shihipar
62f2063abc Merge pull request #1293 from anthropics/thariq/session-report-plugin
Add session-report plugin
2026-04-08 09:35:14 -07:00
Thariq Shihipar
66ca8fc540 Sort session-report plugin into marketplace order 2026-04-08 09:31:35 -07:00
Thariq Shihipar
147ddf8ee3 Add session-report plugin
Generates an explorable HTML report of Claude Code session usage from
local ~/.claude/projects transcripts: total tokens, cache efficiency,
per-project/subagent/skill breakdowns, most expensive prompts with
transcript context, and cache breaks. Terminal-styled, single-file
output with sortable tables and expandable drill-downs.
2026-04-07 17:40:13 -07:00
Sarah Deaton
104d39be10 Merge pull request #885 from anthropics/sarah/restore-reload-plugins-readme
Restore /reload-plugins step in telegram/discord READMEs
2026-04-03 11:44:30 -07:00
Bryan Thompson
decc737a56 Add sonarqube-agent-plugins plugin (#1085)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 10:13:39 -05:00
Bryan Thompson
0484869680 remove(plugin-json): zoominfo — Cowork-only plugin (#1204)
ZoomInfo submitted with platform "Claude Cowork" on their form (2/24/2026)
and is correctly listed on knowledge-work-plugins. This entry was swept
into -official via staging merge PR #730 but should not be on the Claude
Code plugin marketplace.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 08:06:01 -05:00
Bryan Thompson
b091cb4179 Merge pull request #1188 from anthropics/tobinsouth-patch-1
Removing posthog pin
2026-03-31 17:15:14 -05:00
Sarah Deaton
92d061553f Drop tab-complete check, keep just /reload-plugins line 2026-03-21 20:18:35 -07:00
Sarah Deaton
b4f0bdd93a Restore /reload-plugins step in telegram/discord READMEs
Partially reverts #758. The reload step is not redundant: the configure
skill runs before the restart step, so it is not loaded yet when the user
types /telegram:configure. CLI prints 'Run /reload-plugins to activate.'
after install (pluginInstallationHelpers.ts:529). Mintlify reports
confirm users hit 'Unknown skill: discord:configure' at step 3.
2026-03-21 20:17:33 -07:00
7 changed files with 1561 additions and 24 deletions

View File

@@ -53,7 +53,7 @@
},
{
"name": "aikido",
"description": "Aikido Security scanning for Claude Code \u2014 SAST, secrets, and IaC vulnerability detection powered by the Aikido MCP server.",
"description": "Aikido Security scanning for Claude Code SAST, secrets, and IaC vulnerability detection powered by the Aikido MCP server.",
"source": {
"source": "url",
"url": "https://github.com/AikidoSec/aikido-claude-plugin.git",
@@ -243,7 +243,7 @@
},
{
"name": "cockroachdb",
"description": "CockroachDB plugin for Claude Code \u2014 explore schemas, write optimized SQL, debug queries, and manage distributed database clusters directly from your AI coding agent.",
"description": "CockroachDB plugin for Claude Code explore schemas, write optimized SQL, debug queries, and manage distributed database clusters directly from your AI coding agent.",
"source": {
"source": "url",
"url": "https://github.com/cockroachdb/claude-plugin.git",
@@ -275,7 +275,7 @@
},
{
"name": "coderabbit",
"description": "Your code review partner. CodeRabbit provides external validation using a specialized AI architecture and 40+ integrated static analyzers\u2014offering a different perspective that catches bugs, security vulnerabilities, logic errors, and edge cases. Context-aware analysis via AST parsing and codegraph relationships. Automatically incorporates CLAUDE.md and project coding guidelines into reviews. Useful after writing or modifying code, before commits, when implementing complex or security-sensitive logic, or when a second opinion would increase confidence in the changes. Returns specific findings with suggested fixes that can be applied immediately. Free to use.",
"description": "Your code review partner. CodeRabbit provides external validation using a specialized AI architecture and 40+ integrated static analyzersoffering a different perspective that catches bugs, security vulnerabilities, logic errors, and edge cases. Context-aware analysis via AST parsing and codegraph relationships. Automatically incorporates CLAUDE.md and project coding guidelines into reviews. Useful after writing or modifying code, before commits, when implementing complex or security-sensitive logic, or when a second opinion would increase confidence in the changes. Returns specific findings with suggested fixes that can be applied immediately. Free to use.",
"category": "productivity",
"source": {
"source": "url",
@@ -365,7 +365,7 @@
},
{
"name": "elixir-ls-lsp",
"description": "Elixir language server (ElixirLS) for Claude Code \u2014 provides code intelligence and diagnostics for .ex, .exs, and .heex files.",
"description": "Elixir language server (ElixirLS) for Claude Code provides code intelligence and diagnostics for .ex, .exs, and .heex files.",
"source": {
"source": "url",
"url": "https://github.com/MikaelFangel/claude-elixir-ls-lsp.git",
@@ -542,7 +542,7 @@
},
{
"name": "helius",
"description": "Build on Solana with Helius \u2014 live blockchain tools, expert coding patterns, and autonomous account signup",
"description": "Build on Solana with Helius live blockchain tools, expert coding patterns, and autonomous account signup",
"source": {
"source": "git-subdir",
"url": "helius-labs/core-ai",
@@ -775,7 +775,7 @@
},
{
"name": "netlify-skills",
"description": "Netlify platform skills for Claude Code \u2014 functions, edge functions, blobs, database, image CDN, forms, config, CLI, frameworks, caching, AI gateway, and deployment.",
"description": "Netlify platform skills for Claude Code functions, edge functions, blobs, database, image CDN, forms, config, CLI, frameworks, caching, AI gateway, and deployment.",
"category": "development",
"source": {
"source": "url",
@@ -795,7 +795,7 @@
},
{
"name": "nimble",
"description": "Nimble web data toolkit \u2014 search, extract, map, crawl the web and work with structured data agents",
"description": "Nimble web data toolkit search, extract, map, crawl the web and work with structured data agents",
"source": {
"source": "url",
"url": "https://github.com/Nimbleway/agent-skills.git",
@@ -815,7 +815,7 @@
},
{
"name": "opsera-devsecops",
"description": "Opsera DevSecOps Agent \u2014 AI-powered architecture analysis, security scanning, compliance auditing, and SQL security for your codebase. Free trial included.",
"description": "Opsera DevSecOps Agent AI-powered architecture analysis, security scanning, compliance auditing, and SQL security for your codebase. Free trial included.",
"source": {
"source": "url",
"url": "https://github.com/opsera-agents/opsera-devsecops.git",
@@ -825,7 +825,7 @@
},
{
"name": "optibot",
"description": "AI code review that catches production-breaking bugs, business logic issues, and security vulnerabilities \u2014 directly in Claude Code.",
"description": "AI code review that catches production-breaking bugs, business logic issues, and security vulnerabilities directly in Claude Code.",
"source": {
"source": "url",
"url": "https://github.com/Optimal-AI/optibot-skill.git",
@@ -890,7 +890,7 @@
},
{
"name": "playground",
"description": "Creates interactive HTML playgrounds \u2014 self-contained single-file explorers with visual controls, live preview, and prompt output with copy button. Includes templates for design playgrounds, data explorers, concept maps, and document critique.",
"description": "Creates interactive HTML playgrounds self-contained single-file explorers with visual controls, live preview, and prompt output with copy button. Includes templates for design playgrounds, data explorers, concept maps, and document critique.",
"author": {
"name": "Anthropic",
"email": "support@anthropic.com"
@@ -971,7 +971,7 @@
},
{
"name": "product-tracking-skills",
"description": "AI agent skills that make SaaS products data-ready for product analytics \u2014 from codebase scan to tracking plan to working instrumentation code.",
"description": "AI agent skills that make SaaS products data-ready for product analytics from codebase scan to tracking plan to working instrumentation code.",
"source": {
"source": "url",
"url": "https://github.com/Accoil/product-tracking-skills.git",
@@ -1005,7 +1005,7 @@
},
{
"name": "qodo-skills",
"description": "Qodo Skills provides a curated library of reusable AI agent capabilities that extend Claude's functionality for software development workflows. Each skill is designed to integrate seamlessly into your development process, enabling tasks like code quality checks, automated testing, security scanning, and compliance validation. Skills operate across your entire SDLC\u2014from IDE to CI/CD\u2014ensuring consistent standards and catching issues early.",
"description": "Qodo Skills provides a curated library of reusable AI agent capabilities that extend Claude's functionality for software development workflows. Each skill is designed to integrate seamlessly into your development process, enabling tasks like code quality checks, automated testing, security scanning, and compliance validation. Skills operate across your entire SDLCfrom IDE to CI/CDensuring consistent standards and catching issues early.",
"category": "development",
"source": {
"source": "url",
@@ -1129,7 +1129,7 @@
},
{
"name": "searchfit-seo",
"description": "Free AI-powered SEO toolkit \u2014 audit websites, plan content strategy, optimize pages, generate schema markup, cluster keywords, and track AI visibility. Works with any website or codebase.",
"description": "Free AI-powered SEO toolkit audit websites, plan content strategy, optimize pages, generate schema markup, cluster keywords, and track AI visibility. Works with any website or codebase.",
"source": {
"source": "url",
"url": "https://github.com/searchfit/searchfit-seo.git",
@@ -1179,6 +1179,17 @@
"community-managed"
]
},
{
"name": "session-report",
"description": "Generate an explorable HTML report of Claude Code session usage — tokens, cache efficiency, subagents, skills, and the most expensive prompts — from local ~/.claude/projects transcripts.",
"author": {
"name": "Anthropic",
"email": "support@anthropic.com"
},
"source": "./plugins/session-report",
"category": "productivity",
"homepage": "https://github.com/anthropics/claude-plugins-official/tree/main/plugins/session-report"
},
{
"name": "skill-creator",
"description": "Create new skills, improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, update or optimize an existing skill, run evals to test a skill, or benchmark skill performance with variance analysis.",
@@ -1200,6 +1211,17 @@
},
"homepage": "https://github.com/slackapi/slack-mcp-plugin/tree/main"
},
{
"name": "sonarqube-agent-plugins",
"description": "Integrate SonarQube code quality and security analysis into Claude Code: namespaced slash commands, a guided skill to setup the SonarQube CLI, and a startup check for CLI wiring. MCP server registration and secrets-scanning hooks are installed by the SonarQube CLI as part of setup.",
"category": "security",
"source": {
"source": "url",
"url": "https://github.com/SonarSource/sonarqube-agent-plugins.git",
"sha": "0cae644cee9318e6245b62ca779abdc60e6daa49"
},
"homepage": "https://github.com/SonarSource/sonarqube-agent-plugins"
},
{
"name": "sonatype-guide",
"description": "Sonatype Guide MCP server for software supply chain intelligence and dependency security. Analyze dependencies for vulnerabilities, get secure version recommendations, and check component quality metrics.",
@@ -1431,17 +1453,6 @@
"sha": "b93007e9a726c6ee93c57a949e732744ef5acbfd"
},
"homepage": "https://github.com/zapier/zapier-mcp/tree/main/plugins/zapier"
},
{
"name": "zoominfo",
"description": "Search companies and contacts, enrich leads, find lookalikes, and get AI-ranked contact recommendations. Pre-built skills chain multiple ZoomInfo tools into complete B2B sales workflows.",
"category": "productivity",
"source": {
"source": "url",
"url": "https://github.com/Zoominfo/zoominfo-mcp-plugin.git",
"sha": "0705316ef8a2d0c64f81e50d4612ccc6a74edf03"
},
"homepage": "https://zoominfo.com"
}
]
}

View File

@@ -47,6 +47,7 @@ These are Claude Code commands — run `claude` to start a session first.
Install the plugin:
```
/plugin install discord@claude-plugins-official
/reload-plugins
```
**5. Give the server the token.**

View File

@@ -27,6 +27,7 @@ These are Claude Code commands — run `claude` to start a session first.
Install the plugin:
```
/plugin install telegram@claude-plugins-official
/reload-plugins
```
**3. Give the server the token.**

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,42 @@
---
name: session-report
description: Generate an explorable HTML report of Claude Code session usage (tokens, cache, subagents, skills, expensive prompts) from ~/.claude/projects transcripts.
---
# Session Report
Produce a self-contained HTML report of Claude Code usage and save it to the current working directory.
## Steps
1. **Get data.** Run the bundled analyzer (default window: last 7 days; honor a different range if the user passed one, e.g. `24h`, `30d`, or `all`). The script `analyze-sessions.mjs` lives in the same directory as this SKILL.md — use its absolute path:
```sh
node <skill-dir>/analyze-sessions.mjs --json --since 7d > /tmp/session-report.json
```
For all-time, omit `--since`.
2. **Read** `/tmp/session-report.json`. Skim `overall`, `by_project`, `by_subagent_type`, `by_skill`, `cache_breaks`, `top_prompts`.
3. **Copy the template** (also bundled alongside this SKILL.md) to the output path in the current working directory:
```sh
cp <skill-dir>/template.html ./session-report-$(date +%Y%m%d-%H%M).html
```
4. **Edit the output file** (use Edit, not Write — preserve the template's JS/CSS):
- Replace the contents of `<script id="report-data" type="application/json">` with the full JSON from step 1. The page's JS renders the hero total, all tables, bars, and drill-downs from this blob automatically.
- Fill the `<!-- AGENT: anomalies -->` block with **35 one-line findings**. Express figures as a **% of total tokens** wherever possible (total = `overall.input_tokens.total + overall.output_tokens`). One line per finding, exact markup:
```html
<div class="take bad"><div class="fig">41.2%</div><div class="txt"><b>cc-monitor</b> consumed 41% of the week across just 3 sessions</div></div>
```
Classes: `.take bad` for waste/anomalies (red), `.take good` for healthy signals (green), `.take info` for neutral facts (blue). The `.fig` is one short number (a %, a count, or a multiplier like `12×`). The `.txt` is one plain-English sentence naming the project/skill/prompt; wrap the subject in `<b>`. Look for: a project or skill eating a disproportionate share, cache-hit <85%, a single prompt >2% of total, subagent types averaging >1M tokens/call, cache breaks clustering.
- Fill the `<!-- AGENT: optimizations -->` block (at the **bottom** of the page) with 14 `<div class="callout">` suggestions tied to specific rows (e.g. "`/weekly-status` spawned 7 subagents for 8.1% of total — scope it to fewer parallel agents").
- Do not restructure existing sections.
5. **Report** the saved file path to the user. Do not open it or render it.
## Notes
- The template is the source of interactivity (sorting, expand/collapse, block-char bars). Your job is data + narrative, not markup.
- Keep commentary terse and specific — reference actual project names, numbers, timestamps from the JSON.
- `top_prompts` already includes subagent tokens and rolls task-notification continuations into the originating prompt.
- If the JSON is >2MB, trim `top_prompts` to 100 entries and `cache_breaks` to 100 before embedding (they should already be capped).

View File

@@ -0,0 +1,816 @@
#!/usr/bin/env node
/* eslint-disable */
/**
* analyze-sessions.js
*
* Scans ~/.claude/projects/**.jsonl transcript files and reports token usage,
* message counts, runtime, cache breaks, subagent and skill activity.
*
* Output is human-readable text by default; pass --json for machine-readable.
*
* Usage:
* node scripts/analyze-sessions.js [--dir <projects-dir>] [--json] [--since <ISO|7d|24h>] [--top N]
*
* Notes on JSONL structure (discovered empirically):
* - One API response is split into MULTIPLE `type:"assistant"` entries (one per
* content block). They share the same `requestId` / `message.id`, and only the
* LAST one carries the final `output_tokens`. We dedupe by requestId and keep
* the max output_tokens to avoid 3-10x overcounting.
* - `type:"user"` entries include tool_result messages, interrupt markers,
* compact summaries and meta-injected text. A "human" message is one where
* isSidechain/isMeta/isCompactSummary are falsy and the content is a plain
* string (or text block) that isn't a tool_result or interrupt marker.
* - Subagent transcripts live in <project>/<sessionId>/subagents/*.jsonl with a
* sibling *.meta.json containing {agentType}. When meta is absent we fall back
* to the filename label (`agent-a<label>-<hash>.jsonl` → label) or "fork".
* - Resumed sessions can re-serialize prior entries into a new file; we dedupe
* globally by entry `uuid` so replayed history isn't double-counted.
*/
import fs from 'fs'
import os from 'os'
import path from 'path'
import readline from 'readline'
// ---------------------------------------------------------------------------
// CLI args
// ---------------------------------------------------------------------------
const argv = process.argv.slice(2)
function flag(name, dflt) {
const i = argv.indexOf(name)
if (i === -1) return dflt
const v = argv[i + 1]
return v === undefined || v.startsWith('--') ? true : v
}
const ROOT = flag('--dir', path.join(os.homedir(), '.claude', 'projects'))
const AS_JSON = argv.includes('--json')
const TOP_N = parseInt(flag('--top', '15'), 10)
const SINCE = parseSince(flag('--since', null))
const CACHE_BREAK_THRESHOLD = parseInt(flag('--cache-break', '100000'), 10)
const IDLE_GAP_MS = 5 * 60 * 1000 // gaps >5min don't count toward "active" time
function parseSince(s) {
if (!s) return null
const m = /^(\d+)([dh])$/.exec(s)
if (m) {
const ms = m[2] === 'd' ? 86400000 : 3600000
return new Date(Date.now() - parseInt(m[1], 10) * ms)
}
const d = new Date(s)
return isNaN(d) ? null : d
}
// ---------------------------------------------------------------------------
// Stats container
// ---------------------------------------------------------------------------
function newStats() {
return {
sessions: new Set(),
apiCalls: 0,
inputUncached: 0, // usage.input_tokens
inputCacheCreate: 0, // usage.cache_creation_input_tokens
inputCacheRead: 0, // usage.cache_read_input_tokens
outputTokens: 0,
humanMessages: 0,
wallClockMs: 0,
activeMs: 0,
cacheBreaks: [], // [{ts, session, project, uncached, total}]
subagentCalls: 0,
subagentTokens: 0, // total (in+out) inside subagent transcripts
skillInvocations: {}, // name -> count
firstTs: null,
lastTs: null,
}
}
function addUsage(s, u) {
s.apiCalls++
s.inputUncached += u.input_tokens || 0
s.inputCacheCreate += u.cache_creation_input_tokens || 0
s.inputCacheRead += u.cache_read_input_tokens || 0
s.outputTokens += u.output_tokens || 0
}
// ---------------------------------------------------------------------------
// File discovery
// ---------------------------------------------------------------------------
function* walk(dir) {
let ents
try {
ents = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return
}
for (const e of ents) {
const p = path.join(dir, e.name)
if (e.isDirectory()) yield* walk(p)
else if (e.isFile() && e.name.endsWith('.jsonl')) yield p
}
}
function classifyFile(p) {
// returns { project, sessionId, kind, agentId?, agentTypeHint? }
// agentTypeHint is from meta.json or filename label; final type is resolved
// in main() after the parent-transcript map is built.
const rel = path.relative(ROOT, p)
const parts = rel.split(path.sep)
const project = parts[0]
const subIdx = parts.indexOf('subagents')
if (subIdx !== -1) {
const sessionId = parts[subIdx - 1]
const base = path.basename(p, '.jsonl')
const agentId = base.replace(/^agent-/, '')
return {
project,
sessionId,
kind: 'subagent',
agentId,
agentTypeHint:
inferAgentTypeFromMeta(p) || inferAgentTypeFromFilename(base),
}
}
if (parts.includes('workflows')) {
const sessionId = parts[1]
return { project, sessionId, kind: 'subagent', agentTypeHint: 'workflow' }
}
const sessionId = path.basename(p, '.jsonl')
return { project, sessionId, kind: 'main' }
}
function inferAgentTypeFromMeta(jsonlPath) {
const metaPath = jsonlPath.replace(/\.jsonl$/, '.meta.json')
try {
const m = JSON.parse(fs.readFileSync(metaPath, 'utf8'))
if (m && typeof m.agentType === 'string') return m.agentType
} catch {
/* no meta */
}
return null
}
function inferAgentTypeFromFilename(base) {
// agentId = 'a' + hex16 OR 'a' + label + '-' + hex16 (src/utils/uuid.ts)
const m = /^agent-a([a-zA-Z_][\w-]*?)-[0-9a-f]{6,}$/.exec(base)
if (m) return m[1] // internal background fork label
return null // unlabeled — resolve via agentIdToType map or default to 'fork'
}
// ---------------------------------------------------------------------------
// Per-file streaming parse
// ---------------------------------------------------------------------------
const seenUuids = new Set() // global dedupe across resumed sessions
const seenRequestIds = new Set() // global dedupe for usage accounting
const toolUseIdToType = new Map() // tool_use id -> subagent_type (from Agent/Task tool_use)
const agentIdToType = new Map() // agentId -> subagent_type (linked via tool_result)
const toolUseIdToPrompt = new Map() // tool_use id -> promptKey (Agent spawned during this prompt)
const agentIdToPrompt = new Map() // agentId -> promptKey
const prompts = new Map() // promptKey -> { text, ts, project, sessionId, ...usage }
const sessionTurns = new Map() // sessionId -> [promptKey, ...] in transcript order
function promptRecord(key, init) {
let r = prompts.get(key)
if (!r) {
r = {
text: init.text,
ts: init.ts,
project: init.project,
sessionId: init.sessionId,
apiCalls: 0,
subagentCalls: 0,
inputUncached: 0,
inputCacheCreate: 0,
inputCacheRead: 0,
outputTokens: 0,
}
prompts.set(key, r)
}
return r
}
async function processFile(p, info, buckets) {
const rl = readline.createInterface({
input: fs.createReadStream(p, { encoding: 'utf8' }),
crlfDelay: Infinity,
})
// Per-file: dedupe API calls by requestId, keep the one with max output_tokens.
// We collect first, then commit, because earlier blocks have stale output counts.
const fileApiCalls = new Map() // key -> {usage, ts}
let firstTs = null
let lastTs = null
let prevTs = null
let activeMs = 0
let currentSkill = null // skill attribution for this turn
// Prompt attribution: in main files this is set on each human message; in
// subagent files it's inherited from the spawning prompt (via agentIdToPrompt).
let currentPrompt =
info.kind === 'subagent' && info.agentId
? agentIdToPrompt.get(info.agentId) || null
: null
const project = buckets.project
const overall = buckets.overall
const subagent = buckets.subagent // may be null
const skillStats = buckets.skillStats // map name -> stats
for await (const line of rl) {
if (!line) continue
let e
try {
e = JSON.parse(line)
} catch {
continue
}
// global uuid dedupe (resumed sessions replay history)
if (e.uuid) {
if (seenUuids.has(e.uuid)) continue
seenUuids.add(e.uuid)
}
// timestamp tracking
if (e.timestamp) {
const ts = Date.parse(e.timestamp)
if (!isNaN(ts)) {
if (SINCE && ts < SINCE.getTime()) continue
if (firstTs === null) firstTs = ts
if (prevTs !== null) {
const gap = ts - prevTs
if (gap > 0 && gap < IDLE_GAP_MS) activeMs += gap
}
prevTs = ts
lastTs = ts
}
}
if (e.type === 'user') {
// Link Agent tool_result -> agentId for type + prompt attribution.
const tur = e.toolUseResult
if (tur && tur.agentId) {
const c0 = Array.isArray(e.message?.content)
? e.message.content[0]
: null
const tuid = c0 && c0.tool_use_id
if (tuid) {
const st = toolUseIdToType.get(tuid)
if (st) agentIdToType.set(tur.agentId, st)
const pk = toolUseIdToPrompt.get(tuid)
if (pk) {
agentIdToPrompt.set(tur.agentId, pk)
const r = prompts.get(pk)
if (r) r.subagentCalls++
}
}
}
handleUser(
e,
info,
{ project, overall, subagent },
v => {
currentSkill = v
},
pk => {
currentPrompt = pk
},
)
continue
}
if (e.type === 'assistant') {
const msg = e.message || {}
const usage = msg.usage
// detect Skill / Agent tool calls in content
if (Array.isArray(msg.content)) {
for (const c of msg.content) {
if (c && c.type === 'tool_use') {
if (c.name === 'Skill' && c.input && c.input.skill) {
const sk = String(c.input.skill)
bumpSkill(overall, sk)
bumpSkill(project, sk)
if (subagent) bumpSkill(subagent, sk)
currentSkill = sk
}
if (c.name === 'Agent' || c.name === 'Task') {
if (c.input && c.input.subagent_type) {
toolUseIdToType.set(c.id, String(c.input.subagent_type))
}
if (currentPrompt) toolUseIdToPrompt.set(c.id, currentPrompt)
}
}
}
}
if (!usage) continue
const key =
e.requestId ||
(msg.id && msg.id.startsWith('msg_0') && msg.id.length > 10
? msg.id
: null) ||
`${p}:${e.uuid || ''}`
const prev = fileApiCalls.get(key)
if (
!prev ||
(usage.output_tokens || 0) >= (prev.usage.output_tokens || 0)
) {
fileApiCalls.set(key, {
usage,
ts: e.timestamp,
skill: currentSkill,
prompt: currentPrompt,
})
}
continue
}
}
// commit timestamps
if (firstTs !== null && lastTs !== null) {
const wall = lastTs - firstTs
for (const s of [overall, project, subagent].filter(Boolean)) {
s.wallClockMs += wall
s.activeMs += activeMs
if (!s.firstTs || firstTs < s.firstTs) s.firstTs = firstTs
if (!s.lastTs || lastTs > s.lastTs) s.lastTs = lastTs
}
}
// commit API calls
for (const [key, { usage, ts, skill, prompt }] of fileApiCalls) {
if (key && seenRequestIds.has(key)) continue
seenRequestIds.add(key)
const targets = [overall, project]
if (subagent) targets.push(subagent)
if (skill && skillStats) {
if (!skillStats.has(skill)) skillStats.set(skill, newStats())
targets.push(skillStats.get(skill))
}
for (const s of targets) addUsage(s, usage)
if (prompt) {
const r = prompts.get(prompt)
if (r) {
r.apiCalls++
r.inputUncached += usage.input_tokens || 0
r.inputCacheCreate += usage.cache_creation_input_tokens || 0
r.inputCacheRead += usage.cache_read_input_tokens || 0
r.outputTokens += usage.output_tokens || 0
}
}
// subagent token accounting on parent buckets
if (info.kind === 'subagent') {
const tot =
(usage.input_tokens || 0) +
(usage.cache_creation_input_tokens || 0) +
(usage.cache_read_input_tokens || 0) +
(usage.output_tokens || 0)
overall.subagentTokens += tot
project.subagentTokens += tot
if (subagent) subagent.subagentTokens += tot
}
// cache break detection
const uncached =
(usage.input_tokens || 0) + (usage.cache_creation_input_tokens || 0)
if (uncached > CACHE_BREAK_THRESHOLD) {
const total = uncached + (usage.cache_read_input_tokens || 0)
const cb = {
ts,
session: info.sessionId,
project: info.project,
uncached,
total,
kind: info.kind,
agentType: info.agentType,
prompt,
}
overall.cacheBreaks.push(cb)
project.cacheBreaks.push(cb)
if (subagent) subagent.cacheBreaks.push(cb)
}
}
// only count this file toward session/subagent tallies if it had in-range entries
if (firstTs !== null || fileApiCalls.size > 0) {
for (const s of [overall, project, subagent].filter(Boolean)) {
s.sessions.add(info.sessionId)
}
if (info.kind === 'subagent') {
overall.subagentCalls++
project.subagentCalls++
if (subagent) subagent.subagentCalls++
}
}
}
function handleUser(
e,
info,
{ project, overall, subagent },
setSkill,
setPrompt,
) {
if (e.isMeta || e.isCompactSummary) return
const content = e.message && e.message.content
let isToolResult = false
let text = null
if (typeof content === 'string') {
text = content
} else if (Array.isArray(content)) {
const first = content[0]
if (first && first.type === 'tool_result') isToolResult = true
else if (first && first.type === 'text') text = first.text || ''
}
if (isToolResult) return
let slashCmd = null
if (text) {
// Auto-continuations (task notifications, scheduled wakeups) are not new
// human prompts; keep attributing to the previously active prompt.
if (
text.startsWith('<task-notification') ||
text.startsWith('<scheduled-wakeup') ||
text.startsWith('<background-task')
) {
return
}
const m = /<command-(?:name|message)>\/?([^<]+)<\/command-/.exec(text)
if (m) {
slashCmd = m[1].trim()
bumpSkill(overall, slashCmd)
bumpSkill(project, slashCmd)
if (subagent) bumpSkill(subagent, slashCmd)
setSkill(slashCmd)
} else {
setSkill(null) // plain human message resets skill attribution
}
if (text.startsWith('[Request interrupted')) return
}
// Only count as human message / start a prompt in main (non-sidechain) transcripts
if (info.kind === 'main' && !e.isSidechain) {
overall.humanMessages++
project.humanMessages++
const pk = e.uuid || `${info.sessionId}:${e.timestamp}`
promptRecord(pk, {
text: promptPreview(text, slashCmd),
ts: e.timestamp,
project: info.project,
sessionId: info.sessionId,
})
setPrompt(pk)
let turns = sessionTurns.get(info.sessionId)
if (!turns) sessionTurns.set(info.sessionId, (turns = []))
turns.push(pk)
}
}
function promptPreview(text, slashCmd) {
if (slashCmd) return `/${slashCmd}`
if (!text) return '(non-text)'
const t = text
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim()
return t.length > 240 ? t.slice(0, 237) + '…' : t
}
// ±2 user messages around a given prompt, with the api-call count that
// followed each one. Used for drill-down in the HTML report.
function buildContext(pk) {
const r = prompts.get(pk)
if (!r) return null
const turns = sessionTurns.get(r.sessionId)
if (!turns) return null
const i = turns.indexOf(pk)
if (i === -1) return null
const lo = Math.max(0, i - 2)
const hi = Math.min(turns.length, i + 3)
return turns.slice(lo, hi).map((k, j) => {
const t = prompts.get(k) || {}
return {
text: t.text || '',
ts: t.ts || null,
calls: t.apiCalls || 0,
here: lo + j === i,
}
})
}
function bumpSkill(s, name) {
s.skillInvocations[name] = (s.skillInvocations[name] || 0) + 1
}
const _btCache = new Map()
function birthtime(p) {
let t = _btCache.get(p)
if (t === undefined) {
try {
t = fs.statSync(p).birthtimeMs
} catch {
t = 0
}
_btCache.set(p, t)
}
return t
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main() {
const overall = newStats()
const perProject = new Map() // project -> stats
const perSubagent = new Map() // agentType -> stats
const perSkill = new Map() // skill -> stats (token-attributed)
// Classify, then sort main files before subagent files. Fork-style subagents
// replay parent entries with identical uuids; processing parents first ensures
// the global uuid-dedupe attributes those entries to the parent, not the fork.
// Among subagents, sort by birthtime so a parent subagent is processed before
// any nested children it spawned (needed for prompt-attribution propagation).
const files = [...walk(ROOT)]
.map(p => ({ p, info: classifyFile(p) }))
.sort((a, b) => {
const ka = a.info.kind === 'main' ? 0 : 1
const kb = b.info.kind === 'main' ? 0 : 1
if (ka !== kb) return ka - kb
if (ka === 1) return birthtime(a.p) - birthtime(b.p)
return 0
})
let n = 0
for (const { p, info } of files) {
if (!perProject.has(info.project)) perProject.set(info.project, newStats())
const project = perProject.get(info.project)
let subagent = null
if (info.kind === 'subagent') {
// Resolve agent type: meta.json/filename hint > parent-transcript map > 'fork'
const at =
info.agentTypeHint ||
(info.agentId && agentIdToType.get(info.agentId)) ||
'fork'
info.agentType = at
if (!perSubagent.has(at)) perSubagent.set(at, newStats())
subagent = perSubagent.get(at)
}
await processFile(p, info, {
overall,
project,
subagent,
skillStats: perSkill,
})
n++
if (!AS_JSON && n % 200 === 0) {
process.stderr.write(`\r scanned ${n}/${files.length} files…`)
}
}
if (!AS_JSON)
process.stderr.write(`\r scanned ${n}/${files.length} files.\n`)
// Drop empty buckets (created for files that had no in-range entries under --since)
for (const m of [perProject, perSubagent, perSkill]) {
for (const [k, v] of m) {
if (v.apiCalls === 0 && v.sessions.size === 0) m.delete(k)
}
}
if (AS_JSON) {
printJson({ overall, perProject, perSubagent, perSkill })
} else {
printText({ overall, perProject, perSubagent, perSkill })
}
}
// ---------------------------------------------------------------------------
// Output
// ---------------------------------------------------------------------------
function fmt(n) {
if (n >= 1e9) return (n / 1e9).toFixed(2) + 'B'
if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M'
if (n >= 1e3) return (n / 1e3).toFixed(1) + 'k'
return String(n)
}
function pct(a, b) {
return b > 0 ? ((100 * a) / b).toFixed(1) + '%' : '—'
}
function hrs(ms) {
return (ms / 3600000).toFixed(1)
}
function summarize(s) {
const inTotal = s.inputUncached + s.inputCacheCreate + s.inputCacheRead
return {
sessions: s.sessions.size,
api_calls: s.apiCalls,
input_tokens: {
uncached: s.inputUncached,
cache_create: s.inputCacheCreate,
cache_read: s.inputCacheRead,
total: inTotal,
pct_cached:
inTotal > 0 ? +((100 * s.inputCacheRead) / inTotal).toFixed(1) : 0,
},
output_tokens: s.outputTokens,
human_messages: s.humanMessages,
hours: { wall_clock: +hrs(s.wallClockMs), active: +hrs(s.activeMs) },
cache_breaks_over_100k: s.cacheBreaks.length,
subagent: {
calls: s.subagentCalls,
total_tokens: s.subagentTokens,
avg_tokens_per_call:
s.subagentCalls > 0
? Math.round(s.subagentTokens / s.subagentCalls)
: 0,
},
skill_invocations: s.skillInvocations,
span: s.firstTs
? {
from: new Date(s.firstTs).toISOString(),
to: new Date(s.lastTs).toISOString(),
}
: null,
}
}
function printJson({ overall, perProject, perSubagent, perSkill }) {
const out = {
root: ROOT,
generated_at: new Date().toISOString(),
overall: summarize(overall),
cache_breaks: overall.cacheBreaks
.sort((a, b) => b.uncached - a.uncached)
.slice(0, 100)
.map(({ prompt, ...b }) => ({
...b,
context: prompt ? buildContext(prompt) : null,
})),
by_project: Object.fromEntries(
[...perProject].map(([k, v]) => [k, summarize(v)]),
),
by_subagent_type: Object.fromEntries(
[...perSubagent].map(([k, v]) => [k, summarize(v)]),
),
by_skill: Object.fromEntries(
[...perSkill].map(([k, v]) => [k, summarize(v)]),
),
top_prompts: topPrompts(100),
}
process.stdout.write(JSON.stringify(out, null, 2) + '\n')
}
function promptTotal(r) {
return (
r.inputUncached + r.inputCacheCreate + r.inputCacheRead + r.outputTokens
)
}
function topPrompts(n) {
return [...prompts.entries()]
.filter(([, r]) => r.apiCalls > 0)
.sort((a, b) => promptTotal(b[1]) - promptTotal(a[1]))
.slice(0, n)
.map(([pk, r]) => ({
ts: r.ts,
project: r.project,
session: r.sessionId,
text: r.text,
api_calls: r.apiCalls,
subagent_calls: r.subagentCalls,
total_tokens: promptTotal(r),
input: {
uncached: r.inputUncached,
cache_create: r.inputCacheCreate,
cache_read: r.inputCacheRead,
},
output: r.outputTokens,
context: buildContext(pk),
}))
}
function printText({ overall, perProject, perSubagent, perSkill }) {
const line = (...a) => console.log(...a)
const hr = () => line('─'.repeat(78))
line()
line(`Claude Code session analysis — ${ROOT}`)
if (SINCE) line(`(since ${SINCE.toISOString()})`)
hr()
printBlock('OVERALL', overall)
hr()
line(
`CACHE BREAKS (>${fmt(CACHE_BREAK_THRESHOLD)} uncached input on a single call)`,
)
const breaks = overall.cacheBreaks
.sort((a, b) => b.uncached - a.uncached)
.slice(0, TOP_N)
if (breaks.length === 0) line(' none')
for (const b of breaks) {
line(
` ${fmt(b.uncached).padStart(8)} uncached / ${fmt(b.total).padStart(8)} total ` +
`${(b.ts || '').slice(0, 19)} ${b.project}` +
(b.kind === 'subagent' ? ` [${b.agentType}]` : ''),
)
}
if (overall.cacheBreaks.length > TOP_N)
line(`${overall.cacheBreaks.length - TOP_N} more`)
hr()
line(
'MOST EXPENSIVE PROMPTS (total tokens incl. subagents spawned during the turn)',
)
const top = topPrompts(TOP_N)
if (top.length === 0) line(' none')
for (const r of top) {
const inTot = r.input.uncached + r.input.cache_create + r.input.cache_read
line(
` ${fmt(r.total_tokens).padStart(8)} ` +
`(in ${fmt(inTot)} ${pct(r.input.cache_read, inTot)} cached, out ${fmt(r.output)}) ` +
`${r.api_calls} calls` +
(r.subagent_calls ? `, ${r.subagent_calls} subagents` : '') +
` ${(r.ts || '').slice(0, 16)} ${r.project}`,
)
line(` "${r.text}"`)
}
line(
' (note: internal background forks like task_summary/compact are not attributed to a prompt)',
)
hr()
line('BY PROJECT (top by total input tokens)')
const projects = [...perProject.entries()].sort(
(a, b) => totalIn(b[1]) - totalIn(a[1]),
)
for (const [name, s] of projects.slice(0, TOP_N)) {
printBlock(name, s, ' ')
line()
}
if (projects.length > TOP_N)
line(`${projects.length - TOP_N} more projects`)
hr()
line('BY SUBAGENT TYPE')
const agents = [...perSubagent.entries()].sort(
(a, b) => totalIn(b[1]) - totalIn(a[1]),
)
for (const [name, s] of agents) {
printBlock(name, s, ' ')
line()
}
hr()
line(
'BY SKILL / SLASH COMMAND (tokens attributed = from invocation until next human msg)',
)
const skills = [...perSkill.entries()].sort(
(a, b) => totalIn(b[1]) - totalIn(a[1]),
)
for (const [name, s] of skills.slice(0, TOP_N)) {
printBlock(name, s, ' ')
line()
}
if (skills.length > TOP_N) line(`${skills.length - TOP_N} more`)
line()
}
function totalIn(s) {
return s.inputUncached + s.inputCacheCreate + s.inputCacheRead
}
function printBlock(title, s, indent = '') {
const inTotal = totalIn(s)
console.log(`${indent}${title}`)
console.log(
`${indent} sessions: ${s.sessions.size} api calls: ${s.apiCalls} human msgs: ${s.humanMessages}`,
)
console.log(
`${indent} input: ${fmt(inTotal)} total ` +
`(uncached ${fmt(s.inputUncached)}, cache-create ${fmt(s.inputCacheCreate)}, cache-read ${fmt(s.inputCacheRead)} = ${pct(s.inputCacheRead, inTotal)} cached)`,
)
console.log(`${indent} output: ${fmt(s.outputTokens)}`)
console.log(
`${indent} hours: ${hrs(s.wallClockMs)} wall-clock, ${hrs(s.activeMs)} active (gaps >5m excluded)`,
)
console.log(
`${indent} cache breaks >${fmt(CACHE_BREAK_THRESHOLD)}: ${s.cacheBreaks.length}`,
)
console.log(
`${indent} subagents: ${s.subagentCalls} calls, ${fmt(s.subagentTokens)} tokens, avg ${fmt(
s.subagentCalls ? Math.round(s.subagentTokens / s.subagentCalls) : 0,
)}/call`,
)
const topSkills = Object.entries(s.skillInvocations)
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
if (topSkills.length)
console.log(
`${indent} skills: ${topSkills.map(([k, v]) => `${k}×${v}`).join(', ')}`,
)
}
main().catch(e => {
console.error(e)
process.exit(1)
})

View File

@@ -0,0 +1,464 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>claude usage</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
/* anthropic / claude-code palette */
--ivory: #FAF9F5;
--term-bg: #1a1918;
--term-fg: #d1cfc5;
--titlebar: #252321;
--outline: rgba(255,255,255,0.08);
--hover: rgba(255,255,255,0.035);
--clay: #D97757;
--dim: rgb(136,136,136);
--subtle: rgb(80,80,80);
--green: rgb(78,186,101);
--red: rgb(255,107,128);
--blue: rgb(177,185,249);
--yellow: rgb(255,193,7);
--mono: 'JetBrains Mono', 'SF Mono', ui-monospace, Menlo, Monaco, monospace;
}
* { box-sizing: border-box; }
html { background: var(--ivory); }
body {
margin: 0; padding: 48px 24px 80px;
font: 13px/1.55 var(--mono);
font-variant-numeric: tabular-nums;
color: var(--term-fg);
}
/* ——— terminal window chrome ——— */
.term {
max-width: 1180px; margin: 0 auto;
background: var(--term-bg);
border-radius: 8px;
outline: 1px solid var(--outline);
box-shadow: 0 20px 60px rgba(20,20,19,0.22);
}
.titlebar {
background: var(--titlebar);
border-radius: 8px 8px 0 0;
border-bottom: 1px solid var(--outline);
padding: 11px 14px;
display: flex; align-items: center; gap: 7px;
}
.titlebar .dot { width: 11px; height: 11px; border-radius: 50%; background: #3a3836; }
.titlebar .path { margin-left: 14px; color: var(--dim); font-size: 11px; }
.term-body { padding: 22px 30px 30px; }
/* ——— command + hero ——— */
.cmd { color: var(--dim); margin-bottom: 6px; }
.cmd .prompt { color: var(--clay); }
.cmd .flag { color: var(--blue); }
#meta-line { color: var(--subtle); font-size: 11px; }
#hero { margin: 14px 0 6px; }
#hero-total { font-size: 56px; font-weight: 700; line-height: 1; }
#hero-total .unit { color: var(--clay); }
#hero-total .label { font-size: 18px; font-weight: 400; color: var(--dim); margin-left: 8px; }
#hero-split { color: var(--dim); margin-top: 8px; }
#hero-split b { color: var(--term-fg); font-weight: 500; }
#hero-split .ok { color: var(--green); }
#hero-split .warn { color: var(--yellow); }
/* ——— sections ——— */
section { margin-top: 26px; }
.hr { color: var(--subtle); overflow: hidden; white-space: nowrap;
user-select: none; margin-bottom: 8px; }
.hr::after { content: '────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────'; }
h2 { all: unset; display: block; color: var(--clay); font-weight: 500; }
h2::before { content: '▸ '; }
h2 .hint { color: var(--subtle); font-size: 11px; font-weight: 400; margin-left: 10px; }
.section-body { margin-top: 10px; }
/* ——— overall stat grid ——— */
#overall-grid { display: grid; gap: 4px 28px;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
.stat { padding: 4px 0; }
.stat .label { font-size: 11px; color: var(--dim); }
.stat .val { font-size: 20px; font-weight: 500; }
.stat .detail { font-size: 11px; color: var(--subtle); }
/* ——— takeaways ——— */
.take { display: grid; grid-template-columns: 9ch 1fr; gap: 18px;
padding: 6px 0; align-items: baseline; }
.take .fig { text-align: right; font-weight: 700; font-size: 15px; }
.take .txt { color: var(--dim); }
.take .txt b { color: var(--term-fg); font-weight: 500; }
.take.bad .fig { color: var(--red); }
.take.good .fig { color: var(--green); }
.take.info .fig { color: var(--blue); }
/* ——— callouts (recommendations) ——— */
.callout { padding: 6px 0 6px 14px; border-left: 2px solid var(--subtle);
color: var(--dim); margin: 6px 0; }
.callout b, .callout code { color: var(--term-fg); }
/* ——— block-char bars ——— */
.bar { display: grid; grid-template-columns: 26ch 1fr 8ch; gap: 14px;
padding: 2px 0; align-items: center; }
.bar .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar .blocks { color: var(--clay); white-space: pre; overflow: hidden; }
.bar .blocks .empty { color: var(--subtle); }
.bar .pct { text-align: right; color: var(--dim); }
.bar:hover .name { color: var(--clay); }
/* ——— drill-down lists (top prompts, cache breaks) ——— */
.drill details { border-top: 1px solid var(--outline); }
.drill details:last-of-type { border-bottom: 1px solid var(--outline); }
.drill summary { list-style: none; cursor: pointer;
display: grid; grid-template-columns: 8ch 1fr; gap: 16px;
padding: 9px 4px; align-items: baseline; }
.drill summary::-webkit-details-marker { display: none; }
.drill summary:hover { background: var(--hover); }
.drill .amt { font-weight: 700; text-align: right; color: var(--clay); }
.drill .desc { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.drill .meta { grid-column: 2; font-size: 11px; color: var(--subtle); }
.drill details[open] summary .desc { white-space: normal; }
.drill .body { padding: 4px 4px 14px calc(8ch + 20px); font-size: 12px; color: var(--dim); }
/* ——— transcript context (±2 user msgs) — light inset for legibility ——— */
.ctx { margin: 8px 0 12px; padding: 10px 14px;
background: #F0EEE6; color: #1a1918;
border-radius: 6px; font-size: 12px; }
.ctx-msg { padding: 4px 0; white-space: pre-wrap; }
.ctx-msg .who { color: #87867F; font-size: 11px; }
.ctx-msg .ts { color: #87867F; font-size: 10px; margin-left: 8px; }
.ctx-msg.here { margin: 2px -14px; padding: 6px 11px 6px 14px;
border-left: 3px solid var(--clay);
background: rgba(217,119,87,0.10); }
.ctx-msg.here .who { color: var(--clay); font-weight: 500; }
.ctx-gap { color: #87867F; font-size: 11px; padding: 3px 0 3px 7ch; }
.ctx-gap::before { content: '⟨ '; }
.ctx-gap::after { content: ' ⟩'; }
.ctx-break { margin: 2px -14px; padding: 8px 11px 8px 14px;
border-left: 3px solid #BD5E6D;
background: rgba(189,94,109,0.12); color: #A63244; }
.ctx-break b { color: #1a1918; margin-right: 6px; }
.more-btn { display: block; width: 100%; margin-top: 10px; padding: 9px;
background: none; border: 1px dashed var(--subtle); cursor: pointer;
font: 500 11px/1 var(--mono); letter-spacing: 0.06em;
color: var(--dim); }
.more-btn:hover { border-color: var(--dim); color: var(--term-fg); }
/* ——— tables ——— */
.scroll { max-height: 440px; overflow: auto;
border-top: 1px solid var(--outline); border-bottom: 1px solid var(--outline); }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { text-align: left; padding: 6px 10px; }
td { border-top: 1px solid rgba(255,255,255,0.04); }
th { position: sticky; top: 0; background: var(--term-bg); z-index: 1;
font-weight: 500; font-size: 11px; color: var(--subtle);
cursor: pointer; user-select: none;
border-bottom: 1px solid var(--outline); }
th:hover { color: var(--dim); }
th.sorted { color: var(--clay); }
th.sorted::after { content: ' ↓'; }
th.sorted.asc::after { content: ' ↑'; }
td.num, th.num { text-align: right; }
tbody tr:hover td { background: var(--hover); }
footer { margin-top: 28px; color: var(--subtle); font-size: 11px;
display: flex; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
code { color: var(--blue); }
a { color: var(--clay); }
::selection { background: var(--clay); color: var(--term-bg); }
@media (max-width: 760px) {
body { padding: 20px 12px 48px; }
.term-body { padding: 16px 16px 24px; }
#hero-total { font-size: 40px; }
.bar { grid-template-columns: 14ch 1fr 7ch; gap: 8px; }
.drill summary { grid-template-columns: 6ch 1fr; }
.drill .body { padding-left: 12px; }
.take { grid-template-columns: 7ch 1fr; gap: 12px; }
}
</style>
</head>
<body>
<div class="term">
<div class="titlebar">
<span class="dot"></span><span class="dot"></span><span class="dot"></span>
<span class="path" id="title-path">~/.claude — session-report</span>
</div>
<div class="term-body">
<div class="cmd"><span class="prompt">&gt;</span> claude usage <span id="cmd-flags"></span></div>
<div id="meta-line">loading…</div>
<div id="hero">
<div id="hero-total"></div>
<div id="hero-split"></div>
</div>
<!-- ====================================================================
FINDINGS — agent fills this. 35 one-line takeaways. Use .bad for
waste/anomalies, .good for healthy signals, .info for neutral.
==================================================================== -->
<section>
<div class="hr"></div>
<h2>findings</h2>
<div class="section-body" id="takeaways">
<!-- AGENT: anomalies -->
<div class="take"><div class="fig"></div><div class="txt">No findings generated yet.</div></div>
<!-- /AGENT -->
</div>
</section>
<!-- ====================================================================
Everything below renders automatically from #report-data.
==================================================================== -->
<section>
<div class="hr"></div>
<h2>summary</h2>
<div class="section-body" id="overall-grid"></div>
</section>
<section>
<div class="hr"></div>
<h2>tokens by project<span class="hint">share of total</span></h2>
<div class="section-body" id="project-bars"></div>
</section>
<section>
<div class="hr"></div>
<h2>most expensive prompts<span class="hint">click to expand context</span></h2>
<div class="section-body drill" id="top-prompts"></div>
</section>
<section>
<div class="hr"></div>
<h2>cache breaks<span class="hint">&gt;100k uncached · click for context</span></h2>
<div class="section-body drill" id="cache-breaks"></div>
</section>
<section>
<div class="hr"></div>
<h2>projects</h2>
<div class="section-body scroll"><table id="tbl-projects"></table></div>
</section>
<section>
<div class="hr"></div>
<h2>subagent types</h2>
<div class="section-body scroll"><table id="tbl-subagents"></table></div>
</section>
<section>
<div class="hr"></div>
<h2>skills &amp; slash commands</h2>
<div class="section-body scroll"><table id="tbl-skills"></table></div>
</section>
<section>
<div class="hr"></div>
<h2>recommendations</h2>
<div class="section-body">
<!-- AGENT: optimizations -->
<div class="callout">No suggestions generated yet.</div>
<!-- /AGENT -->
</div>
</section>
<footer>
<span id="foot-gen"></span>
<span id="foot-stats"></span>
</footer>
</div>
</div>
<!-- ========================================================================
DATA — agent replaces the {} below with the full --json output.
======================================================================== -->
<script id="report-data" type="application/json">{}</script>
<script>
(function() {
const DATA = JSON.parse(document.getElementById('report-data').textContent || '{}');
const $ = id => document.getElementById(id);
const fmt = n => n>=1e9 ? (n/1e9).toFixed(2)+'B' : n>=1e6 ? (n/1e6).toFixed(2)+'M'
: n>=1e3 ? (n/1e3).toFixed(1)+'k' : String(n);
const pct = (a,b) => b>0 ? ((100*a/b).toFixed(1)+'%') : '—';
const esc = s => String(s).replace(/[&<>"]/g, c =>
({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
const short = p => String(p||'').replace(/^-Users-[^-]+-/,'').replace(/^code-/,'');
const MON = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const niceDate = iso => { const d = new Date(iso); return isNaN(d) ? '' :
`${MON[d.getMonth()]} ${d.getDate()} · ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`; };
if (!DATA.overall) { $('meta-line').textContent = 'no data — embed JSON in #report-data.'; return; }
// header + hero
const o = DATA.overall, it = o.input_tokens;
const GRAND = it.total + o.output_tokens;
const share = n => GRAND>0 ? (100*n/GRAND).toFixed(1)+'%' : '—';
const span = o.span;
$('cmd-flags').innerHTML = DATA.since
? `<span class="flag">--since</span> ${esc(DATA.since)}` : '';
$('meta-line').textContent =
(span ? `${span.from.slice(0,10)}${span.to.slice(0,10)}` : '') +
` · ${DATA.root || ''}`;
$('foot-gen').textContent = `generated ${DATA.generated_at?.slice(0,16).replace('T',' ') || ''}`;
$('foot-stats').textContent =
`${o.sessions} sessions · ${o.api_calls} api calls · ${o.human_messages} prompts`;
const num = fmt(GRAND), m = num.match(/^([\d.]+)([A-Za-z]*)$/);
$('hero-total').innerHTML =
`${m?m[1]:num}<span class="unit">${m?m[2]:''}</span><span class="label">tokens</span>`;
const cacheCls = it.pct_cached>=85 ? 'ok' : 'warn';
$('hero-split').innerHTML =
`<b>${fmt(it.total)}</b> input <span class="${cacheCls}">(${it.pct_cached}% cache-read)</span> · `+
`<b>${fmt(o.output_tokens)}</b> output · all figures below are % of this total`;
// overall stat grid
$('overall-grid').innerHTML = [
['sessions', o.sessions],
['api calls', o.api_calls],
['human msgs', o.human_messages],
['active hours', o.hours.active, `${o.hours.wall_clock} wall-clock`],
['cache breaks', o.cache_breaks_over_100k, '>100k uncached'],
['subagent calls', o.subagent.calls, `avg ${fmt(o.subagent.avg_tokens_per_call)}`],
].map(([l,v,d]) =>
`<div class="stat"><div class="label">${l}</div>`+
`<div class="val">${typeof v==='number'&&v>=1e4?fmt(v):v}</div>`+
(d?`<div class="detail">${d}</div>`:'')+`</div>`).join('');
// block-char project bars
(function() {
const W = 48;
const rows = Object.entries(DATA.by_project||{})
.map(([k,v]) => [k, v.input_tokens.total + v.output_tokens])
.sort((a,b)=>b[1]-a[1]).slice(0,15);
const max = rows[0]?.[1] || 1;
$('project-bars').innerHTML = rows.map(([k,v]) => {
const n = Math.max(1, Math.round(W*v/max));
return `<div class="bar"><span class="name" title="${esc(k)}${fmt(v)}">${esc(short(k))}</span>`+
`<span class="blocks">${'█'.repeat(n)}<span class="empty">${'░'.repeat(W-n)}</span></span>`+
`<span class="pct">${share(v)}</span></div>`;
}).join('');
})();
// ±2 user-message transcript context
function renderContext(ctx, mark) {
if (!ctx || !ctx.length) return '<div class="ctx-gap">no transcript context available</div>';
let h = '<div class="ctx">';
ctx.forEach((m, i) => {
const who = m.here ? '&gt; user' : ' user';
h += `<div class="ctx-msg${m.here?' here':''}">`+
`<span class="who">${who}</span> ${esc(m.text||'(non-text)')}`+
`<span class="ts">${niceDate(m.ts)}</span></div>`;
if (m.here && mark) h += mark;
if (i < ctx.length-1 || m.here)
h += `<div class="ctx-gap">${m.calls} api call${m.calls===1?'':'s'}</div>`;
});
return h + '</div>';
}
// top prompts — share of grand total
(function() {
const ps = (DATA.top_prompts||[]).slice(0,100);
const SHOW = 5;
const row = p => {
const inTot = p.input.uncached+p.input.cache_create+p.input.cache_read;
return `<details><summary>`+
`<span class="amt">${share(p.total_tokens)}</span>`+
`<span class="desc">${esc(p.text)}</span>`+
`<span class="meta">${niceDate(p.ts)} · ${esc(short(p.project))} · ${p.api_calls} calls`+
(p.subagent_calls?` · ${p.subagent_calls} subagents`:'')+
` · ${pct(p.input.cache_read,inTot)} cached</span>`+
`</summary><div class="body">`+
renderContext(p.context)+
`<div>session <code>${esc(p.session)}</code></div>`+
`<div>in: uncached ${fmt(p.input.uncached)} · cache-create ${fmt(p.input.cache_create)} · `+
`cache-read ${fmt(p.input.cache_read)} · out ${fmt(p.output)}</div>`+
`</div></details>`;
};
const head = ps.slice(0,SHOW).map(row).join('');
const rest = ps.slice(SHOW).map(row).join('');
$('top-prompts').innerHTML = ps.length
? head + (rest
? `<div id="tp-rest" hidden>${rest}</div>`+
`<button id="tp-more" class="more-btn">show ${ps.length-SHOW} more</button>`
: '')
: '<div class="callout">No prompts in range.</div>';
const btn = $('tp-more');
if (btn) btn.onclick = () => {
const r = $('tp-rest'); r.hidden = !r.hidden;
btn.textContent = r.hidden ? `show ${ps.length-SHOW} more` : 'show less';
};
})();
// cache breaks
(function() {
const bs = (DATA.cache_breaks||[]).slice(0,100);
$('cache-breaks').innerHTML = bs.map(b =>
`<details><summary>`+
`<span class="amt">${fmt(b.uncached)}</span>`+
`<span class="desc">${esc(short(b.project))} · `+
`${b.kind==='subagent'?esc(b.agentType||'subagent'):'main'}</span>`+
`<span class="meta">${niceDate(b.ts)} · ${pct(b.uncached,b.total)} of ${fmt(b.total)} uncached</span>`+
`</summary><div class="body">`+
renderContext(b.context,
`<div class="ctx-break"><b>${fmt(b.uncached)}</b> uncached `+
`(${pct(b.uncached,b.total)} of ${fmt(b.total)}) — cache break here</div>`)+
`<div>session <code>${esc(b.session)}</code></div>`+
`</div></details>`
).join('') || '<div class="callout">No cache breaks over threshold.</div>';
})();
// sortable table
function table(el, cols, rows) {
let sortIdx = cols.findIndex(c=>c.sort), asc = false;
function render() {
const sorted = rows.slice().sort((a,b)=>{
const va=a[sortIdx], vb=b[sortIdx];
return (asc?1:-1)*(typeof va==='number' ? va-vb : String(va).localeCompare(String(vb)));
});
el.innerHTML = `<thead><tr>${cols.map((c,i)=>
`<th class="${c.num?'num':''} ${i===sortIdx?'sorted'+(asc?' asc':''):''}" data-i="${i}">${c.h}</th>`
).join('')}</tr></thead><tbody>${sorted.map(r=>
`<tr>${r.map((v,i)=>`<td class="${cols[i].num?'num':''}">${
cols[i].fmt?cols[i].fmt(v):esc(v)}</td>`).join('')}</tr>`
).join('')}</tbody>`;
el.querySelectorAll('th').forEach(th=>th.onclick=()=>{
const i=+th.dataset.i; if(i===sortIdx)asc=!asc; else{sortIdx=i;asc=false;} render();
});
}
render();
}
function statRows(obj) {
return Object.entries(obj||{}).map(([k,v])=>[
short(k), GRAND>0 ? 100*(v.input_tokens.total+v.output_tokens)/GRAND : 0,
v.sessions, v.api_calls, v.human_messages,
v.input_tokens.total, v.input_tokens.pct_cached, v.output_tokens,
v.hours.active, v.cache_breaks_over_100k,
v.subagent.calls, v.subagent.avg_tokens_per_call,
]);
}
const statCols = [
{h:'name'},{h:'% total',num:1,sort:1,fmt:v=>v.toFixed(1)+'%'},
{h:'sess',num:1},{h:'calls',num:1},{h:'msgs',num:1},
{h:'input',num:1,fmt:fmt},{h:'%cached',num:1,fmt:v=>v+'%'},
{h:'output',num:1,fmt:fmt},{h:'active h',num:1},{h:'breaks',num:1},
{h:'subagents',num:1},{h:'avg sub tok',num:1,fmt:fmt},
];
table($('tbl-projects'), statCols, statRows(DATA.by_project));
table($('tbl-subagents'), statCols, statRows(DATA.by_subagent_type));
table($('tbl-skills'), statCols, statRows(DATA.by_skill));
})();
</script>
</body>
</html>