-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add AI usage tracking and reporting CLI #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
172d94c
feat: add AI usage tracking and reporting functionality
valuecodes 07940dd
fix: skip synthetic entries in usage records filtering
valuecodes 734d987
feat: add dynamic column width calculation for output formatting
valuecodes 75a6686
feat: deduplicate token_count events in usage record parsing
valuecodes 7e1d6f5
refactor: simplify totalTokens calculation in aggregate method
valuecodes 2cdc248
docs: add README for AI Usage CLI with usage instructions and examples
valuecodes 7af5767
feat: add AI usage summary CLI and enhance token aggregation
valuecodes 03e64c3
feat: implement usage pipeline for data collection and reporting
valuecodes 1339d4f
feat: enhance Claude and Codex log readers with improved filtering an…
valuecodes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| # AI Usage CLI | ||
|
|
||
| Summarize Claude and Codex token usage for a repo, including estimated costs from | ||
| `ai-usage.pricing.json`. | ||
|
|
||
| ## Run | ||
|
|
||
| ```bash | ||
| # Default: last 7 days for current git repo (or cwd if not in git) | ||
| pnpm ai:usage | ||
|
|
||
| # With options | ||
| pnpm ai:usage --since 24h | ||
| pnpm ai:usage --since 30d --repo /path/to/repo | ||
| pnpm ai:usage --json | ||
| pnpm ai:usage --debug | ||
| ``` | ||
|
|
||
| ## Arguments | ||
|
|
||
| - `--since` (optional): time window to include. One of `1h`, `24h`, `7d`, `30d`. | ||
| - `--repo` (optional): path to repo to match against log cwd. | ||
| - `--json` (optional): emit JSON instead of the summary + table. | ||
| - `--debug` (optional): verbose logging about discovery and filtering. | ||
|
|
||
| ## Log Sources | ||
|
|
||
| - **Claude:** `~/.claude/projects/<encoded-repo>/` JSONL logs | ||
| - **Codex:** `$CODEX_HOME/sessions` or `~/.codex/sessions` (YYYY/MM/DD folders) | ||
|
|
||
| Only entries whose `cwd` matches the repo path are counted. | ||
|
|
||
| ## Output | ||
|
|
||
| - Summary by provider and by model. | ||
| - Markdown table with input/output/cache tokens, totals, and estimated cost. | ||
| - If a model is missing from `ai-usage.pricing.json`, cost is `0` and a warning is printed. | ||
|
|
||
| ## Internals | ||
|
|
||
| - `UsagePipeline` owns repo resolution, log collection, aggregation, and formatting. | ||
| - `OutputFormatter` returns strings (summary/table/JSON); `main.ts` prints the report. | ||
|
|
||
| ## Flow | ||
|
|
||
| ```mermaid | ||
| flowchart TD | ||
| A[Discover logs] --> B[Filter by repo + since] | ||
| B --> C[Aggregate tokens] | ||
| C --> D[Apply pricing] | ||
| D --> E[Render summary + table] | ||
| ``` | ||
|
|
||
| ## Example Result | ||
|
|
||
| ```text | ||
| AI Usage Summary (Last 30d) | ||
|
|
||
| By Provider: | ||
| claude: 216,462,575 tokens ($224.87) | ||
| codex: 73,995,660 tokens ($82.01) | ||
|
|
||
| By Model: | ||
| claude-opus-4-5-20251101: 216,462,575 tokens ($224.87) | ||
| gpt-5.2-codex: 73,370,636 tokens ($81.89) | ||
| gpt-5.1-codex-mini: 625,024 tokens ($0.12) | ||
|
|
||
| | Provider | Model | Input | Output | Cache R | Cache W | Total | Est. Cost | | ||
| |----------|--------------------------|------------|---------|-------------|------------|-------------|-----------| | ||
| | claude | claude-opus-4-5-20251101 | 267,949 | 47,358 | 204,118,277 | 12,028,991 | 216,462,575 | $224.87 | | ||
| | codex | gpt-5.2-codex | 37,768,935 | 691,877 | 34,909,824 | 0 | 73,370,636 | $81.89 | | ||
| | codex | gpt-5.1-codex-mini | 430,304 | 5,280 | 189,440 | 0 | 625,024 | $0.12 | | ||
| |----------|--------------------------|------------|---------|-------------|------------|-------------|-----------| | ||
| | TOTAL | | 38,467,188 | 744,515 | 239,217,541 | 12,028,991 | 290,458,235 | $306.89 | | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| { | ||
| "unit": "per_1m_tokens", | ||
| "models": { | ||
| "claude-opus-4-5-20251101": { | ||
| "input": 5.0, | ||
| "output": 25.0, | ||
| "cacheRead": 0.5, | ||
| "cacheWrite": 10.0 | ||
| }, | ||
| "claude-sonnet-4": { | ||
| "input": 3.0, | ||
| "output": 15.0, | ||
| "cacheRead": 0.3, | ||
| "cacheWrite": 6.0 | ||
| }, | ||
| "claude-haiku-4-5": { | ||
| "input": 1.0, | ||
| "output": 5.0, | ||
| "cacheRead": 0.1, | ||
| "cacheWrite": 2.0 | ||
| }, | ||
| "gpt-5.2-codex": { | ||
| "input": 1.75, | ||
| "cacheRead": 0.175, | ||
| "output": 14.0 | ||
| }, | ||
| "gpt-5-mini": { | ||
| "input": 0.25, | ||
| "cacheRead": 0.025, | ||
| "output": 2.0 | ||
| }, | ||
| "gpt-5.1-codex-mini": { | ||
| "input": 0.25, | ||
| "output": 2.0, | ||
| "cacheRead": 0.025 | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import fs from "node:fs/promises"; | ||
| import path from "node:path"; | ||
| import { TMP_ROOT } from "~tools/utils/fs"; | ||
| import { afterEach, describe, expect, it } from "vitest"; | ||
|
|
||
| import { ClaudeLogReader } from "./claude-log-reader"; | ||
|
|
||
| const mockLogger = { | ||
| debug: () => { | ||
| /* empty */ | ||
| }, | ||
| } as never; | ||
|
|
||
| const encodeRepoPath = (repoPath: string) => | ||
| repoPath.replace(/\\/g, "/").replace(/\//g, "-"); | ||
|
|
||
| const since = new Date("2024-01-01T00:00:00.000Z"); | ||
| const repoPath = "/repo"; | ||
|
|
||
| const buildEntry = (overrides: Record<string, unknown> = {}) => ({ | ||
| type: "assistant", | ||
| timestamp: "2025-01-01T00:00:00.000Z", | ||
| message: { | ||
| model: "claude-3", | ||
| usage: { | ||
| input_tokens: 1, | ||
| output_tokens: 2, | ||
| cache_creation_input_tokens: 0, | ||
| cache_read_input_tokens: 0, | ||
| }, | ||
| }, | ||
| ...overrides, | ||
| }); | ||
|
|
||
| const writeLogFile = async (lines: unknown[]) => { | ||
| await fs.mkdir(TMP_ROOT, { recursive: true }); | ||
| const baseDir = await fs.mkdtemp(path.join(TMP_ROOT, "vitest-claude-")); | ||
| const projectDir = path.join(baseDir, encodeRepoPath(repoPath)); | ||
| await fs.mkdir(projectDir, { recursive: true }); | ||
| const filePath = path.join(projectDir, "session.jsonl"); | ||
| const content = lines.map((line) => JSON.stringify(line)).join("\n"); | ||
| await fs.writeFile(filePath, content, "utf8"); | ||
| return baseDir; | ||
| }; | ||
|
|
||
| describe("ClaudeLogReader cwd filtering", () => { | ||
| let baseDir = ""; | ||
|
|
||
| afterEach(async () => { | ||
| if (baseDir) { | ||
| await fs.rm(baseDir, { recursive: true, force: true }); | ||
| baseDir = ""; | ||
| } | ||
| }); | ||
|
|
||
| it("skips entries missing cwd", async () => { | ||
| baseDir = await writeLogFile([buildEntry()]); | ||
| const reader = new ClaudeLogReader({ | ||
| logger: mockLogger, | ||
| basePath: baseDir, | ||
| }); | ||
| const records = await reader.getUsage({ since, repoPath }); | ||
| expect(records).toHaveLength(0); | ||
| }); | ||
|
|
||
| it("skips entries with mismatched cwd", async () => { | ||
| baseDir = await writeLogFile([buildEntry({ cwd: "/other" })]); | ||
| const reader = new ClaudeLogReader({ | ||
| logger: mockLogger, | ||
| basePath: baseDir, | ||
| }); | ||
| const records = await reader.getUsage({ since, repoPath }); | ||
| expect(records).toHaveLength(0); | ||
| }); | ||
|
|
||
| it("keeps entries with matching cwd", async () => { | ||
| baseDir = await writeLogFile([buildEntry({ cwd: "/repo/project" })]); | ||
| const reader = new ClaudeLogReader({ | ||
| logger: mockLogger, | ||
| basePath: baseDir, | ||
| }); | ||
| const records = await reader.getUsage({ since, repoPath }); | ||
| expect(records).toHaveLength(1); | ||
| expect(records[0]?.inputTokens).toBe(1); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The PR description contains contradictory statements about dependencies. It first says "added. (New dependencies for logging and argument parsing.)" but then later states "No new dependencies and no network calls." Looking at the package.json, no new dependencies were actually added. Consider updating the PR description to remove the contradictory statement about new dependencies being added.