tokenwise-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tokenwise/__init__.py +1 -0
- tokenwise/analyzer.py +216 -0
- tokenwise/cli.py +218 -0
- tokenwise/dashboard.py +193 -0
- tokenwise/parser.py +166 -0
- tokenwise/pricing.py +76 -0
- tokenwise/security.py +153 -0
- tokenwise/storage.py +46 -0
- tokenwise_cli-0.1.0.dist-info/METADATA +203 -0
- tokenwise_cli-0.1.0.dist-info/RECORD +13 -0
- tokenwise_cli-0.1.0.dist-info/WHEEL +4 -0
- tokenwise_cli-0.1.0.dist-info/entry_points.txt +2 -0
- tokenwise_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
tokenwise/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
tokenwise/analyzer.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import date, datetime, timezone
|
|
5
|
+
|
|
6
|
+
from .parser import Session
|
|
7
|
+
from .pricing import compute_cost
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class SessionStats:
|
|
12
|
+
session_id: str
|
|
13
|
+
project_slug: str
|
|
14
|
+
project_name: str
|
|
15
|
+
model: str
|
|
16
|
+
start_time: datetime | None
|
|
17
|
+
input_tokens: int
|
|
18
|
+
output_tokens: int
|
|
19
|
+
cache_write_tokens: int
|
|
20
|
+
cache_read_tokens: int
|
|
21
|
+
cost_usd: float
|
|
22
|
+
turns: int
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def total_tokens(self) -> int:
|
|
26
|
+
return (
|
|
27
|
+
self.input_tokens
|
|
28
|
+
+ self.output_tokens
|
|
29
|
+
+ self.cache_write_tokens
|
|
30
|
+
+ self.cache_read_tokens
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def waste_ratio(self) -> float:
|
|
35
|
+
"""High ratio = lots of context for little output (potentially wasteful)."""
|
|
36
|
+
if self.output_tokens == 0:
|
|
37
|
+
return 0.0
|
|
38
|
+
return (self.input_tokens + self.cache_read_tokens) / max(self.output_tokens, 1)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class ProjectStats:
|
|
43
|
+
project_name: str
|
|
44
|
+
project_slug: str
|
|
45
|
+
sessions: int = 0
|
|
46
|
+
input_tokens: int = 0
|
|
47
|
+
output_tokens: int = 0
|
|
48
|
+
cache_write_tokens: int = 0
|
|
49
|
+
cache_read_tokens: int = 0
|
|
50
|
+
cost_usd: float = 0.0
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def total_tokens(self) -> int:
|
|
54
|
+
return (
|
|
55
|
+
self.input_tokens
|
|
56
|
+
+ self.output_tokens
|
|
57
|
+
+ self.cache_write_tokens
|
|
58
|
+
+ self.cache_read_tokens
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class DailySummary:
|
|
64
|
+
date: date
|
|
65
|
+
sessions: int = 0
|
|
66
|
+
input_tokens: int = 0
|
|
67
|
+
output_tokens: int = 0
|
|
68
|
+
cache_write_tokens: int = 0
|
|
69
|
+
cache_read_tokens: int = 0
|
|
70
|
+
cost_usd: float = 0.0
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def total_tokens(self) -> int:
|
|
74
|
+
return (
|
|
75
|
+
self.input_tokens
|
|
76
|
+
+ self.output_tokens
|
|
77
|
+
+ self.cache_write_tokens
|
|
78
|
+
+ self.cache_read_tokens
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class AnalysisResult:
|
|
84
|
+
all_sessions: list[SessionStats]
|
|
85
|
+
by_project: dict[str, ProjectStats]
|
|
86
|
+
by_day: dict[date, DailySummary]
|
|
87
|
+
total_cost_usd: float
|
|
88
|
+
total_tokens: int
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _session_to_stats(session: Session) -> SessionStats:
|
|
92
|
+
model = session.primary_model
|
|
93
|
+
cost = compute_cost(
|
|
94
|
+
model,
|
|
95
|
+
session.total_input,
|
|
96
|
+
session.total_output,
|
|
97
|
+
session.total_cache_write,
|
|
98
|
+
session.total_cache_read,
|
|
99
|
+
)
|
|
100
|
+
return SessionStats(
|
|
101
|
+
session_id=session.session_id,
|
|
102
|
+
project_slug=session.project_slug,
|
|
103
|
+
project_name=session.project_name,
|
|
104
|
+
model=model,
|
|
105
|
+
start_time=session.start_time,
|
|
106
|
+
input_tokens=session.total_input,
|
|
107
|
+
output_tokens=session.total_output,
|
|
108
|
+
cache_write_tokens=session.total_cache_write,
|
|
109
|
+
cache_read_tokens=session.total_cache_read,
|
|
110
|
+
cost_usd=cost,
|
|
111
|
+
turns=len(session.turns),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def analyze(sessions: list[Session]) -> AnalysisResult:
|
|
116
|
+
all_stats: list[SessionStats] = []
|
|
117
|
+
by_project: dict[str, ProjectStats] = {}
|
|
118
|
+
by_day: dict[date, DailySummary] = {}
|
|
119
|
+
|
|
120
|
+
for session in sessions:
|
|
121
|
+
stats = _session_to_stats(session)
|
|
122
|
+
all_stats.append(stats)
|
|
123
|
+
|
|
124
|
+
# Per-project
|
|
125
|
+
key = stats.project_slug
|
|
126
|
+
if key not in by_project:
|
|
127
|
+
by_project[key] = ProjectStats(
|
|
128
|
+
project_name=stats.project_name,
|
|
129
|
+
project_slug=stats.project_slug,
|
|
130
|
+
)
|
|
131
|
+
p = by_project[key]
|
|
132
|
+
p.sessions += 1
|
|
133
|
+
p.input_tokens += stats.input_tokens
|
|
134
|
+
p.output_tokens += stats.output_tokens
|
|
135
|
+
p.cache_write_tokens += stats.cache_write_tokens
|
|
136
|
+
p.cache_read_tokens += stats.cache_read_tokens
|
|
137
|
+
p.cost_usd += stats.cost_usd
|
|
138
|
+
|
|
139
|
+
# Per-day
|
|
140
|
+
if stats.start_time:
|
|
141
|
+
day = stats.start_time.astimezone(timezone.utc).date()
|
|
142
|
+
if day not in by_day:
|
|
143
|
+
by_day[day] = DailySummary(date=day)
|
|
144
|
+
d = by_day[day]
|
|
145
|
+
d.sessions += 1
|
|
146
|
+
d.input_tokens += stats.input_tokens
|
|
147
|
+
d.output_tokens += stats.output_tokens
|
|
148
|
+
d.cache_write_tokens += stats.cache_write_tokens
|
|
149
|
+
d.cache_read_tokens += stats.cache_read_tokens
|
|
150
|
+
d.cost_usd += stats.cost_usd
|
|
151
|
+
|
|
152
|
+
total_cost = sum(s.cost_usd for s in all_stats)
|
|
153
|
+
total_tokens = sum(s.total_tokens for s in all_stats)
|
|
154
|
+
|
|
155
|
+
return AnalysisResult(
|
|
156
|
+
all_sessions=all_stats,
|
|
157
|
+
by_project=by_project,
|
|
158
|
+
by_day=by_day,
|
|
159
|
+
total_cost_usd=total_cost,
|
|
160
|
+
total_tokens=total_tokens,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def filter_by_date_range(
|
|
165
|
+
result: AnalysisResult,
|
|
166
|
+
start: date,
|
|
167
|
+
end: date,
|
|
168
|
+
) -> AnalysisResult:
|
|
169
|
+
filtered = [
|
|
170
|
+
s
|
|
171
|
+
for s in result.all_sessions
|
|
172
|
+
if s.start_time and start <= s.start_time.astimezone(timezone.utc).date() <= end
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
# Re-aggregate from filtered sessions
|
|
176
|
+
by_project: dict[str, ProjectStats] = {}
|
|
177
|
+
by_day: dict[date, DailySummary] = {}
|
|
178
|
+
|
|
179
|
+
for stats in filtered:
|
|
180
|
+
key = stats.project_slug
|
|
181
|
+
if key not in by_project:
|
|
182
|
+
by_project[key] = ProjectStats(
|
|
183
|
+
project_name=stats.project_name,
|
|
184
|
+
project_slug=stats.project_slug,
|
|
185
|
+
)
|
|
186
|
+
p = by_project[key]
|
|
187
|
+
p.sessions += 1
|
|
188
|
+
p.input_tokens += stats.input_tokens
|
|
189
|
+
p.output_tokens += stats.output_tokens
|
|
190
|
+
p.cache_write_tokens += stats.cache_write_tokens
|
|
191
|
+
p.cache_read_tokens += stats.cache_read_tokens
|
|
192
|
+
p.cost_usd += stats.cost_usd
|
|
193
|
+
|
|
194
|
+
if stats.start_time:
|
|
195
|
+
day = stats.start_time.astimezone(timezone.utc).date()
|
|
196
|
+
if day not in by_day:
|
|
197
|
+
by_day[day] = DailySummary(date=day)
|
|
198
|
+
d = by_day[day]
|
|
199
|
+
d.sessions += 1
|
|
200
|
+
d.input_tokens += stats.input_tokens
|
|
201
|
+
d.output_tokens += stats.output_tokens
|
|
202
|
+
d.cache_write_tokens += stats.cache_write_tokens
|
|
203
|
+
d.cache_read_tokens += stats.cache_read_tokens
|
|
204
|
+
d.cost_usd += stats.cost_usd
|
|
205
|
+
|
|
206
|
+
return AnalysisResult(
|
|
207
|
+
all_sessions=filtered,
|
|
208
|
+
by_project=by_project,
|
|
209
|
+
by_day=by_day,
|
|
210
|
+
total_cost_usd=sum(s.cost_usd for s in filtered),
|
|
211
|
+
total_tokens=sum(s.total_tokens for s in filtered),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def top_wasteful_sessions(result: AnalysisResult, n: int = 10) -> list[SessionStats]:
|
|
216
|
+
return sorted(result.all_sessions, key=lambda s: s.waste_ratio, reverse=True)[:n]
|
tokenwise/cli.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import sys
|
|
5
|
+
from datetime import date, timedelta
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
|
|
10
|
+
from .analyzer import AnalysisResult, analyze, filter_by_date_range, top_wasteful_sessions
|
|
11
|
+
from .dashboard import (
|
|
12
|
+
build_daily_table,
|
|
13
|
+
build_projects_table,
|
|
14
|
+
build_summary_panel,
|
|
15
|
+
build_waste_table,
|
|
16
|
+
console,
|
|
17
|
+
live_dashboard,
|
|
18
|
+
)
|
|
19
|
+
from .parser import CLAUDE_PROJECTS_DIR, parse_all_sessions
|
|
20
|
+
from .security import assert_no_network_imports
|
|
21
|
+
|
|
22
|
+
# Fail fast if any of our modules somehow imported a network stack.
|
|
23
|
+
assert_no_network_imports()
|
|
24
|
+
|
|
25
|
+
_err = Console(stderr=True)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _load() -> AnalysisResult:
|
|
29
|
+
if not CLAUDE_PROJECTS_DIR.exists():
|
|
30
|
+
_err.print(
|
|
31
|
+
"[yellow]Warning:[/yellow] ~/.claude/projects/ not found. Is Claude Code installed?"
|
|
32
|
+
)
|
|
33
|
+
sys.exit(1)
|
|
34
|
+
sessions = parse_all_sessions()
|
|
35
|
+
return analyze(sessions)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@click.group(invoke_without_command=True)
|
|
39
|
+
@click.pass_context
|
|
40
|
+
def main(ctx: click.Context) -> None:
|
|
41
|
+
"""Track and reduce your Claude/Anthropic API costs."""
|
|
42
|
+
if ctx.invoked_subcommand is None:
|
|
43
|
+
# Default: live dashboard
|
|
44
|
+
live_dashboard(_load)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@main.command()
|
|
48
|
+
def today() -> None:
|
|
49
|
+
"""Show today's token usage and cost."""
|
|
50
|
+
result = _load()
|
|
51
|
+
today_date = date.today()
|
|
52
|
+
filtered = filter_by_date_range(result, today_date, today_date)
|
|
53
|
+
|
|
54
|
+
console.print(build_summary_panel(filtered, label="Today"))
|
|
55
|
+
console.print()
|
|
56
|
+
console.print(build_projects_table(filtered))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@main.command()
|
|
60
|
+
def week() -> None:
|
|
61
|
+
"""Show last 7 days of usage."""
|
|
62
|
+
result = _load()
|
|
63
|
+
start = date.today() - timedelta(days=6)
|
|
64
|
+
filtered = filter_by_date_range(result, start, date.today())
|
|
65
|
+
|
|
66
|
+
console.print(build_summary_panel(filtered, label="Last 7 Days"))
|
|
67
|
+
console.print()
|
|
68
|
+
console.print(build_daily_table(filtered, days=7))
|
|
69
|
+
console.print()
|
|
70
|
+
console.print(build_projects_table(filtered))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@main.command()
|
|
74
|
+
@click.argument("name")
|
|
75
|
+
def project(name: str) -> None:
|
|
76
|
+
"""Drill into a specific project by name."""
|
|
77
|
+
result = _load()
|
|
78
|
+
|
|
79
|
+
matches = {
|
|
80
|
+
slug: stats
|
|
81
|
+
for slug, stats in result.by_project.items()
|
|
82
|
+
if name.lower() in stats.project_name.lower() or name.lower() in slug.lower()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if not matches:
|
|
86
|
+
_err.print(f"[red]No project matching '{name}' found.[/red]")
|
|
87
|
+
available = ", ".join(s.project_name for s in result.by_project.values())
|
|
88
|
+
_err.print(f"Available: {available}")
|
|
89
|
+
sys.exit(1)
|
|
90
|
+
|
|
91
|
+
for slug, stats in matches.items():
|
|
92
|
+
sessions = [s for s in result.all_sessions if s.project_slug == slug]
|
|
93
|
+
sessions.sort(key=lambda s: s.start_time or date.min, reverse=True)
|
|
94
|
+
|
|
95
|
+
from rich import box
|
|
96
|
+
from rich.table import Table
|
|
97
|
+
|
|
98
|
+
table = Table(
|
|
99
|
+
title=f"[bold]{stats.project_name}[/bold] — {len(sessions)} sessions",
|
|
100
|
+
box=box.SIMPLE_HEAD,
|
|
101
|
+
header_style="bold cyan",
|
|
102
|
+
)
|
|
103
|
+
table.add_column("Date")
|
|
104
|
+
table.add_column("Model")
|
|
105
|
+
table.add_column("Turns", justify="right")
|
|
106
|
+
table.add_column("Input", justify="right")
|
|
107
|
+
table.add_column("Output", justify="right")
|
|
108
|
+
table.add_column("Cache↓", justify="right")
|
|
109
|
+
table.add_column("Cost", justify="right")
|
|
110
|
+
|
|
111
|
+
from .dashboard import _fmt_cost, _fmt_tokens
|
|
112
|
+
|
|
113
|
+
for s in sessions[:20]:
|
|
114
|
+
date_str = s.start_time.strftime("%Y-%m-%d %H:%M") if s.start_time else "—"
|
|
115
|
+
model_short = s.model.replace("claude-", "").replace("-20", " '")
|
|
116
|
+
table.add_row(
|
|
117
|
+
date_str,
|
|
118
|
+
model_short,
|
|
119
|
+
str(s.turns),
|
|
120
|
+
_fmt_tokens(s.input_tokens),
|
|
121
|
+
_fmt_tokens(s.output_tokens),
|
|
122
|
+
_fmt_tokens(s.cache_read_tokens),
|
|
123
|
+
_fmt_cost(s.cost_usd),
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
console.print(table)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@main.command()
|
|
130
|
+
@click.option("--top", default=10, show_default=True, help="Number of sessions to show.")
|
|
131
|
+
def waste(top: int) -> None:
|
|
132
|
+
"""Find sessions that burned tokens with little output."""
|
|
133
|
+
result = _load()
|
|
134
|
+
wasteful = top_wasteful_sessions(result, n=top)
|
|
135
|
+
|
|
136
|
+
if not wasteful:
|
|
137
|
+
console.print("[green]No wasteful sessions detected.[/green]")
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
console.print(build_waste_table(wasteful, n=top))
|
|
141
|
+
console.print()
|
|
142
|
+
console.print(
|
|
143
|
+
"[dim]Tip: A high ratio means a large context window was sent for very little output.\n"
|
|
144
|
+
"Consider breaking large sessions into smaller focused tasks.[/dim]"
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@main.command()
|
|
149
|
+
@click.option("--csv", "as_csv", is_flag=True, help="Output as CSV.")
|
|
150
|
+
def export(as_csv: bool) -> None:
|
|
151
|
+
"""Export raw session data."""
|
|
152
|
+
result = _load()
|
|
153
|
+
sessions = sorted(
|
|
154
|
+
result.all_sessions,
|
|
155
|
+
key=lambda s: s.start_time or date.min,
|
|
156
|
+
reverse=True,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if as_csv:
|
|
160
|
+
writer = csv.writer(sys.stdout)
|
|
161
|
+
writer.writerow(
|
|
162
|
+
[
|
|
163
|
+
"date",
|
|
164
|
+
"project",
|
|
165
|
+
"session_id",
|
|
166
|
+
"model",
|
|
167
|
+
"input_tokens",
|
|
168
|
+
"output_tokens",
|
|
169
|
+
"cache_write_tokens",
|
|
170
|
+
"cache_read_tokens",
|
|
171
|
+
"total_tokens",
|
|
172
|
+
"cost_usd",
|
|
173
|
+
]
|
|
174
|
+
)
|
|
175
|
+
for s in sessions:
|
|
176
|
+
writer.writerow(
|
|
177
|
+
[
|
|
178
|
+
s.start_time.date() if s.start_time else "",
|
|
179
|
+
s.project_name,
|
|
180
|
+
s.session_id,
|
|
181
|
+
s.model,
|
|
182
|
+
s.input_tokens,
|
|
183
|
+
s.output_tokens,
|
|
184
|
+
s.cache_write_tokens,
|
|
185
|
+
s.cache_read_tokens,
|
|
186
|
+
s.total_tokens,
|
|
187
|
+
f"{s.cost_usd:.6f}",
|
|
188
|
+
]
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
from rich import box
|
|
192
|
+
from rich.table import Table
|
|
193
|
+
|
|
194
|
+
from .dashboard import _fmt_cost, _fmt_tokens
|
|
195
|
+
|
|
196
|
+
table = Table(box=box.SIMPLE_HEAD, header_style="bold cyan")
|
|
197
|
+
table.add_column("Date")
|
|
198
|
+
table.add_column("Project")
|
|
199
|
+
table.add_column("Total Tokens", justify="right")
|
|
200
|
+
table.add_column("Cost", justify="right")
|
|
201
|
+
for s in sessions[:50]:
|
|
202
|
+
table.add_row(
|
|
203
|
+
str(s.start_time.date()) if s.start_time else "—",
|
|
204
|
+
s.project_name,
|
|
205
|
+
_fmt_tokens(s.total_tokens),
|
|
206
|
+
_fmt_cost(s.cost_usd),
|
|
207
|
+
)
|
|
208
|
+
console.print(table)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@main.command("update-prices")
|
|
212
|
+
def update_prices() -> None:
|
|
213
|
+
"""[stub] Update pricing data from Anthropic's website."""
|
|
214
|
+
console.print(
|
|
215
|
+
"[yellow]update-prices is not yet implemented.[/yellow]\n"
|
|
216
|
+
"To update prices manually, edit [bold]src/tokenwise/pricing.py[/bold].\n"
|
|
217
|
+
"Current prices: https://www.anthropic.com/pricing"
|
|
218
|
+
)
|
tokenwise/dashboard.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from datetime import date, datetime, timedelta
|
|
6
|
+
|
|
7
|
+
from rich import box
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.panel import Panel
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
|
|
12
|
+
from .analyzer import AnalysisResult, DailySummary, SessionStats, filter_by_date_range
|
|
13
|
+
|
|
14
|
+
console = Console()
|
|
15
|
+
|
|
16
|
+
_COST_COLOR = "green"
|
|
17
|
+
_WARN_COLOR = "yellow"
|
|
18
|
+
_HOT_COLOR = "red"
|
|
19
|
+
_DIM = "dim"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _fmt_cost(usd: float) -> str:
|
|
23
|
+
if usd < 0.01:
|
|
24
|
+
return f"[{_DIM}]< $0.01[/{_DIM}]"
|
|
25
|
+
if usd >= 1.0:
|
|
26
|
+
return f"[bold {_HOT_COLOR}]${usd:.2f}[/bold {_HOT_COLOR}]"
|
|
27
|
+
return f"[{_COST_COLOR}]${usd:.4f}[/{_COST_COLOR}]"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _fmt_tokens(n: int) -> str:
|
|
31
|
+
if n >= 1_000_000:
|
|
32
|
+
return f"{n / 1_000_000:.1f}M"
|
|
33
|
+
if n >= 1_000:
|
|
34
|
+
return f"{n / 1_000:.1f}k"
|
|
35
|
+
return str(n)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _sparkline(values: list[float], width: int = 8) -> str:
|
|
39
|
+
bars = " ▁▂▃▄▅▆▇█"
|
|
40
|
+
if not values or max(values) == 0:
|
|
41
|
+
return " " * width
|
|
42
|
+
hi = max(values)
|
|
43
|
+
return "".join(bars[int(v / hi * 8)] for v in values[-width:])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def build_summary_panel(result: AnalysisResult, label: str = "All Time") -> Panel:
|
|
47
|
+
today = date.today()
|
|
48
|
+
today_result = filter_by_date_range(result, today, today)
|
|
49
|
+
week_start = today - timedelta(days=6)
|
|
50
|
+
week_result = filter_by_date_range(result, week_start, today)
|
|
51
|
+
|
|
52
|
+
rows = [
|
|
53
|
+
("Today", today_result.total_cost_usd, today_result.total_tokens),
|
|
54
|
+
("This Week", week_result.total_cost_usd, week_result.total_tokens),
|
|
55
|
+
("All Time", result.total_cost_usd, result.total_tokens),
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
table = Table(box=None, padding=(0, 2), show_header=False)
|
|
59
|
+
table.add_column("Period", style="bold")
|
|
60
|
+
table.add_column("Cost", justify="right")
|
|
61
|
+
table.add_column("Tokens", justify="right")
|
|
62
|
+
|
|
63
|
+
for period, cost, tokens in rows:
|
|
64
|
+
table.add_row(period, _fmt_cost(cost), f"[cyan]{_fmt_tokens(tokens)}[/cyan]")
|
|
65
|
+
|
|
66
|
+
return Panel(table, title="[bold]Cost Summary[/bold]", border_style="blue", padding=(0, 1))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build_projects_table(result: AnalysisResult, top_n: int = 10) -> Table:
|
|
70
|
+
projects = sorted(result.by_project.values(), key=lambda p: p.cost_usd, reverse=True)[:top_n]
|
|
71
|
+
|
|
72
|
+
table = Table(
|
|
73
|
+
title="[bold]Projects[/bold]",
|
|
74
|
+
box=box.SIMPLE_HEAD,
|
|
75
|
+
border_style="bright_black",
|
|
76
|
+
header_style="bold cyan",
|
|
77
|
+
show_lines=False,
|
|
78
|
+
)
|
|
79
|
+
table.add_column("Project", min_width=18)
|
|
80
|
+
table.add_column("Sessions", justify="right")
|
|
81
|
+
table.add_column("Input", justify="right")
|
|
82
|
+
table.add_column("Output", justify="right")
|
|
83
|
+
table.add_column("Cache↑", justify="right")
|
|
84
|
+
table.add_column("Cache↓", justify="right")
|
|
85
|
+
table.add_column("Cost", justify="right")
|
|
86
|
+
|
|
87
|
+
for p in projects:
|
|
88
|
+
table.add_row(
|
|
89
|
+
f"[bold]{p.project_name}[/bold]",
|
|
90
|
+
str(p.sessions),
|
|
91
|
+
_fmt_tokens(p.input_tokens),
|
|
92
|
+
_fmt_tokens(p.output_tokens),
|
|
93
|
+
_fmt_tokens(p.cache_write_tokens),
|
|
94
|
+
_fmt_tokens(p.cache_read_tokens),
|
|
95
|
+
_fmt_cost(p.cost_usd),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
return table
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def build_daily_table(result: AnalysisResult, days: int = 7) -> Table:
|
|
102
|
+
today = date.today()
|
|
103
|
+
dates = [today - timedelta(days=i) for i in range(days - 1, -1, -1)]
|
|
104
|
+
|
|
105
|
+
table = Table(
|
|
106
|
+
title=f"[bold]Last {days} Days[/bold]",
|
|
107
|
+
box=box.SIMPLE_HEAD,
|
|
108
|
+
border_style="bright_black",
|
|
109
|
+
header_style="bold cyan",
|
|
110
|
+
)
|
|
111
|
+
table.add_column("Date")
|
|
112
|
+
table.add_column("Sessions", justify="right")
|
|
113
|
+
table.add_column("Tokens", justify="right")
|
|
114
|
+
table.add_column("Trend", justify="left")
|
|
115
|
+
table.add_column("Cost", justify="right")
|
|
116
|
+
|
|
117
|
+
daily_costs = [result.by_day.get(d, DailySummary(date=d)).cost_usd for d in dates]
|
|
118
|
+
sparkline_data = daily_costs
|
|
119
|
+
|
|
120
|
+
for i, d in enumerate(dates):
|
|
121
|
+
summary = result.by_day.get(d, DailySummary(date=d))
|
|
122
|
+
label = "Today" if d == today else d.strftime("%a %b %d")
|
|
123
|
+
style = "bold" if d == today else ""
|
|
124
|
+
spark = _sparkline(sparkline_data[: i + 1])
|
|
125
|
+
table.add_row(
|
|
126
|
+
f"[{style}]{label}[/{style}]" if style else label,
|
|
127
|
+
str(summary.sessions) if summary.sessions else "[dim]—[/dim]",
|
|
128
|
+
_fmt_tokens(summary.total_tokens) if summary.total_tokens else "[dim]—[/dim]",
|
|
129
|
+
f"[bright_black]{spark}[/bright_black]",
|
|
130
|
+
_fmt_cost(summary.cost_usd) if summary.cost_usd else "[dim]—[/dim]",
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return table
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def build_waste_table(sessions: list[SessionStats], n: int = 10) -> Table:
|
|
137
|
+
table = Table(
|
|
138
|
+
title="[bold]Top Wasteful Sessions[/bold] [dim](high context : low output)[/dim]",
|
|
139
|
+
box=box.SIMPLE_HEAD,
|
|
140
|
+
border_style="bright_black",
|
|
141
|
+
header_style="bold cyan",
|
|
142
|
+
)
|
|
143
|
+
table.add_column("Project")
|
|
144
|
+
table.add_column("Date")
|
|
145
|
+
table.add_column("Input+Cache↓", justify="right")
|
|
146
|
+
table.add_column("Output", justify="right")
|
|
147
|
+
table.add_column("Ratio", justify="right")
|
|
148
|
+
table.add_column("Cost", justify="right")
|
|
149
|
+
|
|
150
|
+
for s in sessions[:n]:
|
|
151
|
+
ratio = s.waste_ratio
|
|
152
|
+
ratio_str = f"{ratio:.0f}x"
|
|
153
|
+
color = _HOT_COLOR if ratio > 100 else _WARN_COLOR if ratio > 30 else "white"
|
|
154
|
+
date_str = s.start_time.strftime("%b %d") if s.start_time else "—"
|
|
155
|
+
table.add_row(
|
|
156
|
+
s.project_name,
|
|
157
|
+
date_str,
|
|
158
|
+
_fmt_tokens(s.input_tokens + s.cache_read_tokens),
|
|
159
|
+
_fmt_tokens(s.output_tokens),
|
|
160
|
+
f"[{color}]{ratio_str}[/{color}]",
|
|
161
|
+
_fmt_cost(s.cost_usd),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
return table
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def render_dashboard(result: AnalysisResult) -> None:
|
|
168
|
+
|
|
169
|
+
console.clear()
|
|
170
|
+
now = datetime.now().strftime("%H:%M:%S")
|
|
171
|
+
console.print(
|
|
172
|
+
Panel(
|
|
173
|
+
f"[bold cyan]tokenwise[/bold cyan] [dim]last updated {now}[/dim]",
|
|
174
|
+
border_style="bright_black",
|
|
175
|
+
padding=(0, 1),
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
console.print(build_summary_panel(result))
|
|
179
|
+
console.print()
|
|
180
|
+
console.print(build_projects_table(result))
|
|
181
|
+
console.print()
|
|
182
|
+
console.print(build_daily_table(result))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def live_dashboard(loader: Callable[[], AnalysisResult], refresh_seconds: int = 5) -> None:
|
|
186
|
+
try:
|
|
187
|
+
while True:
|
|
188
|
+
result = loader()
|
|
189
|
+
render_dashboard(result)
|
|
190
|
+
time.sleep(refresh_seconds)
|
|
191
|
+
console.clear()
|
|
192
|
+
except KeyboardInterrupt:
|
|
193
|
+
console.print("\n[dim]Goodbye.[/dim]")
|
tokenwise/parser.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, Field
|
|
9
|
+
|
|
10
|
+
from .security import open_readonly, safe_read_path
|
|
11
|
+
|
|
12
|
+
CLAUDE_PROJECTS_DIR = Path.home() / ".claude" / "projects"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TokenUsage(BaseModel):
|
|
16
|
+
input_tokens: int = 0
|
|
17
|
+
output_tokens: int = 0
|
|
18
|
+
cache_creation_input_tokens: int = 0
|
|
19
|
+
cache_read_input_tokens: int = 0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AssistantTurn(BaseModel):
|
|
23
|
+
uuid: str
|
|
24
|
+
session_id: str
|
|
25
|
+
project_slug: str
|
|
26
|
+
timestamp: datetime
|
|
27
|
+
model: str
|
|
28
|
+
usage: TokenUsage
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Session(BaseModel):
|
|
32
|
+
session_id: str
|
|
33
|
+
project_slug: str
|
|
34
|
+
project_path: str = "" # real path from cwd field on user messages
|
|
35
|
+
turns: list[AssistantTurn] = Field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def project_name(self) -> str:
|
|
39
|
+
if self.project_path:
|
|
40
|
+
return Path(self.project_path).name
|
|
41
|
+
# Fallback: last dash-separated token of slug
|
|
42
|
+
return self.project_slug.rstrip("-").rsplit("-", 1)[-1] or self.project_slug
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def start_time(self) -> datetime | None:
|
|
46
|
+
return self.turns[0].timestamp if self.turns else None
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def end_time(self) -> datetime | None:
|
|
50
|
+
return self.turns[-1].timestamp if self.turns else None
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def total_input(self) -> int:
|
|
54
|
+
return sum(t.usage.input_tokens for t in self.turns)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def total_output(self) -> int:
|
|
58
|
+
return sum(t.usage.output_tokens for t in self.turns)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def total_cache_write(self) -> int:
|
|
62
|
+
return sum(t.usage.cache_creation_input_tokens for t in self.turns)
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def total_cache_read(self) -> int:
|
|
66
|
+
return sum(t.usage.cache_read_input_tokens for t in self.turns)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def total_tokens(self) -> int:
|
|
70
|
+
return self.total_input + self.total_output + self.total_cache_write + self.total_cache_read
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def primary_model(self) -> str:
|
|
74
|
+
if not self.turns:
|
|
75
|
+
return "unknown"
|
|
76
|
+
counts: dict[str, int] = {}
|
|
77
|
+
for t in self.turns:
|
|
78
|
+
if t.model and t.model != "<synthetic>":
|
|
79
|
+
counts[t.model] = counts.get(t.model, 0) + 1
|
|
80
|
+
return max(counts, key=lambda m: counts[m]) if counts else "unknown"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _parse_jsonl(path: Path) -> Iterator[dict]:
|
|
84
|
+
safe_read_path(path) # path-safety guard — raises if path escapes allowed roots
|
|
85
|
+
with open_readonly(path) as f:
|
|
86
|
+
for line in f:
|
|
87
|
+
line = line.strip()
|
|
88
|
+
if not line:
|
|
89
|
+
continue
|
|
90
|
+
try:
|
|
91
|
+
yield json.loads(line)
|
|
92
|
+
except json.JSONDecodeError:
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def parse_session(jsonl_path: Path, project_slug: str) -> Session:
|
|
97
|
+
session_id = jsonl_path.stem
|
|
98
|
+
session = Session(session_id=session_id, project_slug=project_slug)
|
|
99
|
+
|
|
100
|
+
for record in _parse_jsonl(jsonl_path):
|
|
101
|
+
rtype = record.get("type")
|
|
102
|
+
|
|
103
|
+
# Pick up real working directory from any user message
|
|
104
|
+
if rtype == "user" and not session.project_path:
|
|
105
|
+
cwd = record.get("cwd", "")
|
|
106
|
+
if cwd:
|
|
107
|
+
session.project_path = cwd
|
|
108
|
+
|
|
109
|
+
elif rtype == "assistant":
|
|
110
|
+
msg = record.get("message", {})
|
|
111
|
+
raw_usage = msg.get("usage")
|
|
112
|
+
model = msg.get("model", "")
|
|
113
|
+
|
|
114
|
+
# Skip synthetic/empty turns
|
|
115
|
+
if not raw_usage or model == "<synthetic>":
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
# Skip if all counts are zero
|
|
119
|
+
input_tok = raw_usage.get("input_tokens", 0) or 0
|
|
120
|
+
output_tok = raw_usage.get("output_tokens", 0) or 0
|
|
121
|
+
cache_create = raw_usage.get("cache_creation_input_tokens", 0) or 0
|
|
122
|
+
cache_read = raw_usage.get("cache_read_input_tokens", 0) or 0
|
|
123
|
+
|
|
124
|
+
if input_tok == output_tok == cache_create == cache_read == 0:
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
ts_str = record.get("timestamp", "")
|
|
128
|
+
try:
|
|
129
|
+
ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
|
|
130
|
+
except (ValueError, AttributeError):
|
|
131
|
+
ts = datetime.now(tz=timezone.utc)
|
|
132
|
+
|
|
133
|
+
turn = AssistantTurn(
|
|
134
|
+
uuid=record.get("uuid", ""),
|
|
135
|
+
session_id=session_id,
|
|
136
|
+
project_slug=project_slug,
|
|
137
|
+
timestamp=ts,
|
|
138
|
+
model=model,
|
|
139
|
+
usage=TokenUsage(
|
|
140
|
+
input_tokens=input_tok,
|
|
141
|
+
output_tokens=output_tok,
|
|
142
|
+
cache_creation_input_tokens=cache_create,
|
|
143
|
+
cache_read_input_tokens=cache_read,
|
|
144
|
+
),
|
|
145
|
+
)
|
|
146
|
+
session.turns.append(turn)
|
|
147
|
+
|
|
148
|
+
return session
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def parse_all_sessions(projects_dir: Path | None = None) -> list[Session]:
|
|
152
|
+
root = projects_dir or CLAUDE_PROJECTS_DIR
|
|
153
|
+
if not root.exists():
|
|
154
|
+
return []
|
|
155
|
+
|
|
156
|
+
sessions: list[Session] = []
|
|
157
|
+
for project_dir in sorted(root.iterdir()):
|
|
158
|
+
if not project_dir.is_dir():
|
|
159
|
+
continue
|
|
160
|
+
slug = project_dir.name
|
|
161
|
+
for jsonl_file in sorted(project_dir.glob("*.jsonl")):
|
|
162
|
+
session = parse_session(jsonl_file, slug)
|
|
163
|
+
if session.turns: # skip empty sessions
|
|
164
|
+
sessions.append(session)
|
|
165
|
+
|
|
166
|
+
return sessions
|
tokenwise/pricing.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Anthropic model pricing — last verified 2026-04-29.
|
|
3
|
+
Prices are per 1 million tokens (USD).
|
|
4
|
+
Source: https://www.anthropic.com/pricing
|
|
5
|
+
Run `tokenwise update-prices` stub when Anthropic updates their page.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class ModelPrice:
|
|
15
|
+
input: float # $/MTok
|
|
16
|
+
output: float # $/MTok
|
|
17
|
+
cache_write: float # $/MTok (prompt cache write)
|
|
18
|
+
cache_read: float # $/MTok (prompt cache read)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _p(i: float, o: float, cw: float, cr: float) -> ModelPrice:
|
|
22
|
+
return ModelPrice(input=i, output=o, cache_write=cw, cache_read=cr)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# fmt: off
|
|
26
|
+
PRICES: dict[str, ModelPrice] = {
|
|
27
|
+
# Claude 4.x ────────────────────────────── input output cw cr
|
|
28
|
+
"claude-opus-4-7": _p(15.00, 75.00, 18.75, 1.50),
|
|
29
|
+
"claude-sonnet-4-6": _p( 3.00, 15.00, 3.75, 0.30),
|
|
30
|
+
"claude-haiku-4-5": _p( 0.80, 4.00, 1.00, 0.08),
|
|
31
|
+
"claude-haiku-4-5-20251001": _p( 0.80, 4.00, 1.00, 0.08),
|
|
32
|
+
|
|
33
|
+
# Claude 3.x ────────────────────────────── input output cw cr
|
|
34
|
+
"claude-3-5-sonnet-20241022": _p( 3.00, 15.00, 3.75, 0.30),
|
|
35
|
+
"claude-3-5-sonnet-20240620": _p( 3.00, 15.00, 3.75, 0.30),
|
|
36
|
+
"claude-3-5-haiku-20241022": _p( 0.80, 4.00, 1.00, 0.08),
|
|
37
|
+
"claude-3-opus-20240229": _p(15.00, 75.00, 18.75, 1.50),
|
|
38
|
+
"claude-3-haiku-20240307": _p( 0.25, 1.25, 0.30, 0.03),
|
|
39
|
+
"claude-3-sonnet-20240229": _p( 3.00, 15.00, 3.75, 0.30),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
# Fallback for unknown / future model names — matched by prefix
|
|
43
|
+
_PREFIX_FALLBACKS: list[tuple[str, ModelPrice]] = [
|
|
44
|
+
("claude-opus", PRICES["claude-opus-4-7"]),
|
|
45
|
+
("claude-sonnet", PRICES["claude-sonnet-4-6"]),
|
|
46
|
+
("claude-haiku", PRICES["claude-haiku-4-5"]),
|
|
47
|
+
]
|
|
48
|
+
# fmt: on
|
|
49
|
+
|
|
50
|
+
_MTok = 1_000_000
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_price(model: str) -> ModelPrice:
|
|
54
|
+
if model in PRICES:
|
|
55
|
+
return PRICES[model]
|
|
56
|
+
for prefix, price in _PREFIX_FALLBACKS:
|
|
57
|
+
if model.startswith(prefix):
|
|
58
|
+
return price
|
|
59
|
+
# Unknown model — use Sonnet as a conservative estimate
|
|
60
|
+
return PRICES["claude-sonnet-4-6"]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def compute_cost(
|
|
64
|
+
model: str,
|
|
65
|
+
input_tokens: int,
|
|
66
|
+
output_tokens: int,
|
|
67
|
+
cache_write_tokens: int,
|
|
68
|
+
cache_read_tokens: int,
|
|
69
|
+
) -> float:
|
|
70
|
+
p = get_price(model)
|
|
71
|
+
return (
|
|
72
|
+
input_tokens * p.input / _MTok
|
|
73
|
+
+ output_tokens * p.output / _MTok
|
|
74
|
+
+ cache_write_tokens * p.cache_write / _MTok
|
|
75
|
+
+ cache_read_tokens * p.cache_read / _MTok
|
|
76
|
+
)
|
tokenwise/security.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Runtime security guarantees for tokenwise.
|
|
3
|
+
|
|
4
|
+
All checks here are designed to be fast, fail loudly, and be auditable by
|
|
5
|
+
anyone reading the source — no clever tricks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import IO
|
|
14
|
+
|
|
15
|
+
# Modules that would imply network access — none of these should ever appear
|
|
16
|
+
# in tokenwise's own code.
|
|
17
|
+
_FORBIDDEN_NETWORK_MODULES = frozenset(
|
|
18
|
+
{
|
|
19
|
+
"socket",
|
|
20
|
+
"ssl",
|
|
21
|
+
"urllib",
|
|
22
|
+
"urllib.request",
|
|
23
|
+
"urllib.parse",
|
|
24
|
+
"requests",
|
|
25
|
+
"httpx",
|
|
26
|
+
"aiohttp",
|
|
27
|
+
"http.client",
|
|
28
|
+
"http.server",
|
|
29
|
+
"ftplib",
|
|
30
|
+
"smtplib",
|
|
31
|
+
"xmlrpc",
|
|
32
|
+
"xmlrpc.client",
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
# The only two directory trees tokenwise is allowed to read or write.
|
|
37
|
+
_ALLOWED_READ_ROOTS = (Path.home() / ".claude" / "projects",)
|
|
38
|
+
_ALLOWED_WRITE_ROOTS = (Path.home() / ".tokenwise",)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---------------------------------------------------------------------------
|
|
42
|
+
# Network check
|
|
43
|
+
# ---------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def assert_no_network_imports() -> None:
|
|
47
|
+
"""Raise if any network-capable module was imported by our own code.
|
|
48
|
+
|
|
49
|
+
We check sys.modules at startup, after our own imports have settled.
|
|
50
|
+
Third-party libraries (click, rich, pydantic) importing socket internally
|
|
51
|
+
is out of our control and is not flagged — we only refuse to import those
|
|
52
|
+
modules ourselves.
|
|
53
|
+
"""
|
|
54
|
+
# Collect modules imported by tokenwise source files only.
|
|
55
|
+
tokenwise_modules = {name for name in sys.modules if name.startswith("tokenwise.")}
|
|
56
|
+
|
|
57
|
+
# Walk each tokenwise module's __file__ and check its source-level imports.
|
|
58
|
+
# This is a best-effort lint; the grep CI check is the authoritative gate.
|
|
59
|
+
# Here we just ensure nothing snuck into sys.modules *under our name*.
|
|
60
|
+
loaded_network = _FORBIDDEN_NETWORK_MODULES & set(sys.modules.keys())
|
|
61
|
+
if loaded_network:
|
|
62
|
+
# Only raise if WE (tokenwise) imported them — check by seeing if any
|
|
63
|
+
# tokenwise module directly references them.
|
|
64
|
+
for mod_name in list(tokenwise_modules):
|
|
65
|
+
mod = sys.modules.get(mod_name)
|
|
66
|
+
if mod is None:
|
|
67
|
+
continue
|
|
68
|
+
src = getattr(mod, "__file__", None) or ""
|
|
69
|
+
if not src:
|
|
70
|
+
continue
|
|
71
|
+
try:
|
|
72
|
+
source_text = Path(src).read_text(encoding="utf-8")
|
|
73
|
+
except OSError:
|
|
74
|
+
continue
|
|
75
|
+
for forbidden in loaded_network:
|
|
76
|
+
if f"import {forbidden}" in source_text or f"from {forbidden}" in source_text:
|
|
77
|
+
raise RuntimeError(
|
|
78
|
+
f"Security violation: tokenwise module '{mod_name}' imports "
|
|
79
|
+
f"network module '{forbidden}'. tokenwise must never make "
|
|
80
|
+
f"network calls. File: {src}"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ---------------------------------------------------------------------------
|
|
85
|
+
# Path safety
|
|
86
|
+
# ---------------------------------------------------------------------------
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def safe_read_path(p: Path | str) -> Path:
|
|
90
|
+
"""Resolve `p` and assert it sits inside an allowed read root.
|
|
91
|
+
|
|
92
|
+
Raises ValueError for paths outside the allowed trees or for symlinks
|
|
93
|
+
that escape them (resolving follows the link before checking).
|
|
94
|
+
"""
|
|
95
|
+
resolved = Path(p).resolve()
|
|
96
|
+
for root in _ALLOWED_READ_ROOTS:
|
|
97
|
+
allowed = root.resolve()
|
|
98
|
+
if resolved == allowed or _is_relative_to(resolved, allowed):
|
|
99
|
+
return resolved
|
|
100
|
+
raise ValueError(
|
|
101
|
+
f"Path '{p}' resolves to '{resolved}', which is outside the allowed "
|
|
102
|
+
f"read roots: {[str(r) for r in _ALLOWED_READ_ROOTS]}"
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def safe_write_path(p: Path | str) -> Path:
|
|
107
|
+
"""Resolve `p` and assert it sits inside an allowed write root."""
|
|
108
|
+
resolved = Path(p).resolve()
|
|
109
|
+
for root in _ALLOWED_WRITE_ROOTS:
|
|
110
|
+
allowed = root.resolve()
|
|
111
|
+
if resolved == allowed or _is_relative_to(resolved, allowed):
|
|
112
|
+
return resolved
|
|
113
|
+
raise ValueError(
|
|
114
|
+
f"Path '{p}' resolves to '{resolved}', which is outside the allowed "
|
|
115
|
+
f"write roots: {[str(r) for r in _ALLOWED_WRITE_ROOTS]}"
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _is_relative_to(child: Path, parent: Path) -> bool:
|
|
120
|
+
# Path.is_relative_to() was added in 3.9; replicate for safety.
|
|
121
|
+
try:
|
|
122
|
+
child.relative_to(parent)
|
|
123
|
+
return True
|
|
124
|
+
except ValueError:
|
|
125
|
+
return False
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------------------
|
|
129
|
+
# Read-only open helper
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def open_readonly(path: Path | str) -> IO[str]:
|
|
134
|
+
"""Open a file strictly read-only. Never call this with a write mode."""
|
|
135
|
+
resolved = Path(path).resolve()
|
|
136
|
+
return open(resolved, encoding="utf-8") # noqa: WPS515 — intentional
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ---------------------------------------------------------------------------
|
|
140
|
+
# Cache directory / file permissions
|
|
141
|
+
# ---------------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def ensure_cache_dir(cache_dir: Path) -> None:
|
|
145
|
+
"""Create cache directory with user-only permissions (0o700)."""
|
|
146
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
147
|
+
os.chmod(cache_dir, 0o700)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def set_cache_file_permissions(cache_file: Path) -> None:
|
|
151
|
+
"""Set cache file to user-read/write only (0o600)."""
|
|
152
|
+
if cache_file.exists():
|
|
153
|
+
os.chmod(cache_file, 0o600)
|
tokenwise/storage.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .security import ensure_cache_dir, safe_write_path, set_cache_file_permissions
|
|
8
|
+
|
|
9
|
+
CACHE_DIR = Path.home() / ".tokenwise"
|
|
10
|
+
CACHE_FILE = CACHE_DIR / "cache.json"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_cache() -> dict[str, Any]:
|
|
14
|
+
if not CACHE_FILE.exists():
|
|
15
|
+
return {}
|
|
16
|
+
try:
|
|
17
|
+
with open(CACHE_FILE, encoding="utf-8") as f:
|
|
18
|
+
data: dict[str, Any] = json.load(f)
|
|
19
|
+
return data
|
|
20
|
+
except (json.JSONDecodeError, OSError):
|
|
21
|
+
return {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def save_cache(data: dict[str, Any]) -> None:
|
|
25
|
+
safe_write_path(CACHE_FILE) # path-safety guard before any write
|
|
26
|
+
ensure_cache_dir(CACHE_DIR)
|
|
27
|
+
with open(CACHE_FILE, "w", encoding="utf-8") as f:
|
|
28
|
+
json.dump(data, f, indent=2, default=str)
|
|
29
|
+
set_cache_file_permissions(CACHE_FILE)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_file_mtime(path: Path) -> float:
|
|
33
|
+
try:
|
|
34
|
+
return path.stat().st_mtime
|
|
35
|
+
except OSError:
|
|
36
|
+
return 0.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_cache_valid(cache: dict[str, Any], jsonl_path: Path) -> bool:
|
|
40
|
+
key = str(jsonl_path)
|
|
41
|
+
cached_mtime: float = cache.get("mtimes", {}).get(key, 0.0)
|
|
42
|
+
return cached_mtime == get_file_mtime(jsonl_path)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def update_cache_mtime(cache: dict[str, Any], jsonl_path: Path) -> None:
|
|
46
|
+
cache.setdefault("mtimes", {})[str(jsonl_path)] = get_file_mtime(jsonl_path)
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tokenwise-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Track and reduce your Claude/Anthropic API costs from the terminal
|
|
5
|
+
Project-URL: Homepage, https://github.com/sowmithkuppa/tokenwise
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/sowmithkuppa/tokenwise/issues
|
|
7
|
+
License: MIT License
|
|
8
|
+
|
|
9
|
+
Copyright (c) 2026 Sowmith Kuppa
|
|
10
|
+
|
|
11
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
+
in the Software without restriction, including without limitation the rights
|
|
14
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
+
furnished to do so, subject to the following conditions:
|
|
17
|
+
|
|
18
|
+
The above copyright notice and this permission notice shall be included in all
|
|
19
|
+
copies or substantial portions of the Software.
|
|
20
|
+
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
27
|
+
SOFTWARE.
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Python: >=3.10
|
|
30
|
+
Requires-Dist: click<9,>=8.1
|
|
31
|
+
Requires-Dist: pydantic<3,>=2.0
|
|
32
|
+
Requires-Dist: rich<14,>=13.7
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: bandit<2,>=1.7; extra == 'dev'
|
|
35
|
+
Requires-Dist: mypy<2,>=1.10; extra == 'dev'
|
|
36
|
+
Requires-Dist: pip-audit<3,>=2.7; extra == 'dev'
|
|
37
|
+
Requires-Dist: pytest-cov<6,>=5.0; extra == 'dev'
|
|
38
|
+
Requires-Dist: pytest<10,>=9.0; extra == 'dev'
|
|
39
|
+
Requires-Dist: ruff<1,>=0.4; extra == 'dev'
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
|
|
42
|
+
# tokenwise
|
|
43
|
+
|
|
44
|
+
> **See exactly where your Claude tokens go — and stop wasting them.**
|
|
45
|
+
|
|
46
|
+
[](https://github.com/sowmithkuppa/tokenwise/actions/workflows/ci.yml)
|
|
47
|
+
[](https://github.com/sowmithkuppa/tokenwise/actions/workflows/codeql.yml)
|
|
48
|
+
[](https://securityscorecards.dev/viewer/?uri=github.com/sowmithkuppa/tokenwise)
|
|
49
|
+
[](https://pypi.org/project/tokenwise/)
|
|
50
|
+
[](https://pypi.org/project/tokenwise/)
|
|
51
|
+
[](LICENSE)
|
|
52
|
+
|
|
53
|
+
<!-- GIF placeholder -->
|
|
54
|
+

|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Security
|
|
59
|
+
|
|
60
|
+
> **tokenwise makes zero network calls. It only reads Claude Code's local logs. Audit it in 5 minutes.**
|
|
61
|
+
|
|
62
|
+
This tool reads sensitive data (your Claude session logs). Here is exactly what it does and does not do:
|
|
63
|
+
|
|
64
|
+
| Guarantee | How it's enforced |
|
|
65
|
+
|---|---|
|
|
66
|
+
| No network calls | Runtime assertion checks `sys.modules` at startup; grep CI check |
|
|
67
|
+
| Read-only on `~/.claude/` | Only `open(path, 'r')` touches that directory; unit tested |
|
|
68
|
+
| No `eval` / `exec` / `pickle` / `subprocess` | Grep CI check on every push |
|
|
69
|
+
| No telemetry or "phone home" | See above — no network stack imported |
|
|
70
|
+
| Cache stored with `0o700` / `0o600` perms | Enforced in `storage.py` |
|
|
71
|
+
| JSON-only serialization | No pickle, no exec of user-controlled data |
|
|
72
|
+
|
|
73
|
+
**Audit it yourself** — paste these into your terminal after cloning:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
# Should return nothing (no network imports)
|
|
77
|
+
grep -rE "import (requests|urllib|httpx|socket|http\.client)" src/
|
|
78
|
+
|
|
79
|
+
# Should return nothing (no code execution)
|
|
80
|
+
grep -rE "\b(eval|exec|pickle|subprocess|os\.system)\b" src/
|
|
81
|
+
|
|
82
|
+
# Should return nothing (no writes to the Claude log directory)
|
|
83
|
+
grep -rE 'open\(.*["\'][wa+]' src/
|
|
84
|
+
|
|
85
|
+
# Confirm all file reads go through our safe_path() check
|
|
86
|
+
grep -rn "safe_path" src/tokenwise/
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
See [`THREAT_MODEL.md`](THREAT_MODEL.md) for the full analysis.
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## What is tokenwise?
|
|
94
|
+
|
|
95
|
+
`tokenwise` reads your local Claude Code logs (`~/.claude/projects/`) and gives you a beautiful terminal breakdown of **exactly** how many tokens you've burned — by project, session, and day — with cost estimates and waste warnings.
|
|
96
|
+
|
|
97
|
+
Zero cloud sync. Zero telemetry. Pure read-only.
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## Features
|
|
102
|
+
|
|
103
|
+
- **Live dashboard** — real-time token + cost view across all projects
|
|
104
|
+
- **Daily / weekly reports** — `tokenwise today`, `tokenwise week`
|
|
105
|
+
- **Per-project drill-down** — `tokenwise project <name>`
|
|
106
|
+
- **Waste detector** — `tokenwise waste` flags sessions with huge context for tiny output
|
|
107
|
+
- **CSV export** — `tokenwise export --csv`
|
|
108
|
+
- **Cache-aware cost** — distinguishes input, output, cache-write, and cache-read pricing
|
|
109
|
+
- Works **offline**, reads logs directly — no API key needed
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## Install
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
pip install tokenwise
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Or with [pipx](https://pypa.github.io/pipx/) (recommended for CLI tools):
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
pipx install tokenwise
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Requirements
|
|
126
|
+
|
|
127
|
+
Python **3.10 or later** is required. Check your version:
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
python3 --version
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
**Development setup** (for contributors):
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
git clone https://github.com/sowmithkuppa/tokenwise.git
|
|
137
|
+
cd tokenwise
|
|
138
|
+
python3.13 -m venv .venv # or python3.10 / 3.11 / 3.12
|
|
139
|
+
source .venv/bin/activate
|
|
140
|
+
pip install -e ".[dev]"
|
|
141
|
+
make verify # runs tests + all security checks
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## Quickstart
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
# Live dashboard (updates every 5 seconds)
|
|
150
|
+
tokenwise
|
|
151
|
+
|
|
152
|
+
# Today's usage
|
|
153
|
+
tokenwise today
|
|
154
|
+
|
|
155
|
+
# Last 7 days
|
|
156
|
+
tokenwise week
|
|
157
|
+
|
|
158
|
+
# Drill into a project
|
|
159
|
+
tokenwise project myapp
|
|
160
|
+
|
|
161
|
+
# Find wasteful sessions
|
|
162
|
+
tokenwise waste
|
|
163
|
+
|
|
164
|
+
# Export raw data
|
|
165
|
+
tokenwise export --csv > usage.csv
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
## How it works
|
|
171
|
+
|
|
172
|
+
Claude Code writes JSONL logs to `~/.claude/projects/<project-slug>/<session-id>.jsonl`. Each assistant message includes a `usage` object with `input_tokens`, `output_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`. `tokenwise` parses these, applies current Anthropic pricing, and aggregates the results.
|
|
173
|
+
|
|
174
|
+
Parsed data is cached in `~/.tokenwise/cache.json` (permissions `0o600`) so repeated runs are instant.
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Comparison to `ccusage`
|
|
179
|
+
|
|
180
|
+
| Feature | tokenwise | ccusage |
|
|
181
|
+
|---|---|---|
|
|
182
|
+
| Live dashboard | ✅ | ❌ |
|
|
183
|
+
| Waste detection | ✅ | ❌ |
|
|
184
|
+
| Cache-aware cost | ✅ | partial |
|
|
185
|
+
| Per-session drill-down | ✅ | ✅ |
|
|
186
|
+
| CSV export | ✅ | ✅ |
|
|
187
|
+
| No API key required | ✅ | ✅ |
|
|
188
|
+
| Formal threat model | ✅ | ❌ |
|
|
189
|
+
| Runtime no-network assertion | ✅ | ❌ |
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## Contributing
|
|
194
|
+
|
|
195
|
+
See [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
|
196
|
+
|
|
197
|
+
Pricing data lives in `src/tokenwise/pricing.py`. If Anthropic updates their prices, PRs to update that file are very welcome.
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT © Sowmith Kuppa
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
tokenwise/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
tokenwise/analyzer.py,sha256=8CieUOuziHlpPz1YtRTD4Q61Y5mVb3LB9kcDJllQE58,6271
|
|
3
|
+
tokenwise/cli.py,sha256=yiOLi_KgRYBvBUh9rtGscDOinSVlzAnkJKzXtxqAIB4,6784
|
|
4
|
+
tokenwise/dashboard.py,sha256=rz2r3mQVreEWMfyzDQieMj6JGI4wNhGLdBenx5j7HqE,6403
|
|
5
|
+
tokenwise/parser.py,sha256=lqXXmqsUk7e_fZE3-LL8L1nHNz2pi3jdbgQlCiKsYbw,5277
|
|
6
|
+
tokenwise/pricing.py,sha256=Ns9ldsC-oSAExj0jEpv90ch_Ng_bPSmwFtqtkTDcHwE,2589
|
|
7
|
+
tokenwise/security.py,sha256=09jmPxFCVII-WP2cRm89jUT6QaBpd7l_WOP0_z2eTAQ,5416
|
|
8
|
+
tokenwise/storage.py,sha256=uWFy9GRFiW_sTzopzLZGnmvIMfHm1myR3lOMv5psE8M,1340
|
|
9
|
+
tokenwise_cli-0.1.0.dist-info/METADATA,sha256=t7QOJEVfZnarjdN9RI39bdhf_DhImwM0_iDjENc0c7o,7057
|
|
10
|
+
tokenwise_cli-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
11
|
+
tokenwise_cli-0.1.0.dist-info/entry_points.txt,sha256=dgpmKX2NKowSTR9x9QWuL7UFaz7I8DPkRD-9NopwsEg,49
|
|
12
|
+
tokenwise_cli-0.1.0.dist-info/licenses/LICENSE,sha256=TwHlnShlCeqaMooTGMBAWDKX7lINzkXTKbDYkBB4Xqg,1070
|
|
13
|
+
tokenwise_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sowmith Kuppa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|