-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathctx
More file actions
executable file
·224 lines (191 loc) · 7.54 KB
/
Copy pathctx
File metadata and controls
executable file
·224 lines (191 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python3
"""
ctx — read Claude Code's own session transcripts as live local telemetry.
Reports context depth (the number that predicts compaction), deduplicated
token usage, and current activity. No API calls, no network, no auth: it
reads files Claude Code already writes to ~/.claude.
Usage:
./ctx newest session
./ctx --all every session, newest first
./ctx --limit 200000 set the context window for the fill bar
./ctx --cost add a cost ESTIMATE (see README caveats)
./ctx --watch refresh every 5s
"""
import json, glob, os, sys, time, argparse
CLAUDE = os.path.expanduser("~/.claude")
# Per-million-token rates. Cache write = 1.25x input, cache read = 0.1x input.
# These are approximate and change; --cost output is an ESTIMATE.
RATES = {
"haiku": (0.80, 4.0, 1.00, 0.08),
"sonnet": (3.00, 15.0, 3.75, 0.30),
"opus": (15.00, 75.0, 18.75, 1.50),
}
def rate_for(model):
m = (model or "").lower()
if "haiku" in m: return RATES["haiku"]
if "opus" in m: return RATES["opus"]
return RATES["sonnet"]
def transcripts():
"""All session JSONLs, newest first."""
pat = os.path.join(CLAUDE, "projects", "**", "*.jsonl")
files = glob.glob(pat, recursive=True)
return sorted(files, key=os.path.getmtime, reverse=True)
def read_session(path):
"""
Parse one transcript.
THE TRAP: Claude Code writes one JSONL line per *content block*, so a
single API response (one message.id) spans several assistant lines that
each repeat the SAME message.usage. Summing every line inflates totals
by ~2.5-3x. Usage must be counted once per message.id.
"""
by_id = {} # message.id -> (usage, model, timestamp)
order = [] # preserves first-seen order of ids
raw_lines = 0
synthetic = 0
with open(path, errors="ignore") as fh:
for line in fh:
if '"usage"' not in line:
continue
try:
d = json.loads(line)
except Exception:
continue
if d.get("type") != "assistant":
continue
msg = d.get("message")
if not isinstance(msg, dict):
continue
u = msg.get("usage")
if not isinstance(u, dict):
continue
raw_lines += 1
mid = msg.get("id")
if not isinstance(mid, str) or not mid:
synthetic += 1
mid = "__line_%d" % synthetic
if mid not in by_id:
order.append(mid)
by_id[mid] = (u, msg.get("model"), d.get("timestamp"))
turns = [by_id[i] for i in order]
return turns, raw_lines
def totals(turns):
t = {"input_tokens": 0, "output_tokens": 0,
"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}
cost = 0.0
for u, model, _ in turns:
for k in t:
t[k] += int(u.get(k, 0) or 0)
i, o, cw, cr = rate_for(model)
cost += (int(u.get("input_tokens", 0) or 0) * i
+ int(u.get("output_tokens", 0) or 0) * o
+ int(u.get("cache_creation_input_tokens", 0) or 0) * cw
+ int(u.get("cache_read_input_tokens", 0) or 0) * cr) / 1e6
return t, cost
def context_depth(turns):
"""
Context depth ~= what the model re-read this turn.
cache_read_input_tokens is the prefix served from cache; adding this
turn's cache_creation gives the working context size. This is the
number that predicts compaction, and nothing surfaces it.
"""
series = []
for u, _, _ in turns:
cr = int(u.get("cache_read_input_tokens", 0) or 0)
cw = int(u.get("cache_creation_input_tokens", 0) or 0)
series.append(cr + cw)
return series
def bar(frac, width=34):
frac = max(0.0, min(1.0, frac))
n = int(frac * width)
return "█" * n + "░" * (width - n)
def activity():
p = os.path.join(CLAUDE, "bash-commands.log")
try:
with open(p, "rb") as fh:
fh.seek(0, os.SEEK_END)
fh.seek(max(0, fh.tell() - 8192))
tail = fh.read().decode("utf-8", "ignore")
except Exception:
return None
lines = [l for l in tail.split("\n") if "] " in l]
if not lines:
return None
line = lines[-1].split("] ", 1)[-1].replace("\n", " ").strip()
return line[:70] + ("…" if len(line) > 70 else "")
def human(n):
for unit, div in (("B", 1e9), ("M", 1e6), ("K", 1e3)):
if n >= div:
return f"{n/div:,.2f}{unit}"
return f"{n:,}"
def report(path, args):
turns, raw = read_session(path)
if not turns:
print(f" {os.path.basename(path)}: no usage records")
return
tot, cost = totals(turns)
depth = context_depth(turns)
cur = depth[-1] if depth else 0
peak = max(depth) if depth else 0
limit = args.limit or (1_000_000 if peak > 200_000 else 200_000)
inferred = " (inferred)" if not args.limit else ""
# growth per turn over the last 20 turns
growth = 0
if len(depth) > 5:
span = depth[-1] - depth[-min(20, len(depth))]
growth = span / max(1, min(20, len(depth)) - 1)
remaining = (limit - cur) / growth if growth > 0 else float("inf")
print()
print(f" \033[1m{os.path.basename(path).split('.')[0][:8]}\033[0m"
f" {len(turns)} turns ({raw} raw lines, {raw/len(turns):.2f}x dedup)")
print(" " + "─" * 62)
print(" CONTEXT")
print(f" depth now {human(cur):>12} of {human(limit)}{inferred}")
print(f" {bar(cur/limit)} {cur/limit*100:.0f}%")
print(f" peak {human(peak):>12}")
if growth > 0:
print(f" growth {human(growth):>12} / turn")
if remaining != float("inf") and remaining < 10_000:
warn = "\033[31m" if remaining < 20 else ("\033[33m" if remaining < 60 else "")
print(f" {warn}headroom {remaining:>12,.0f} turns\033[0m")
# Each turn you continue re-reads the whole prefix; a fresh session
# would not. That difference is the concrete cost of not restarting.
if cur > 50_000:
avoided = int(remaining) * max(0, cur - 2_000)
print(f" \033[1msaved by restarting {human(avoided):>12} tokens\033[0m")
else:
print(" growth flat / shrinking")
print()
print(" TOKENS (deduplicated by message.id)")
for k, label in (("output_tokens", "output"),
("cache_creation_input_tokens", "cache write"),
("cache_read_input_tokens", "cache read"),
("input_tokens", "input")):
print(f" {label:<16} {human(tot[k]):>12}")
if args.cost:
print(f"\n cost estimate {'$%.2f' % cost:>12} approximate — see README")
act = activity()
if act:
print(f"\n NOW {act}")
print()
def main():
ap = argparse.ArgumentParser(add_help=True)
ap.add_argument("--all", action="store_true")
ap.add_argument("--limit", type=int, default=None)
ap.add_argument("--cost", action="store_true")
ap.add_argument("--watch", action="store_true")
args = ap.parse_args()
files = transcripts()
if not files:
print("no Claude Code transcripts found under ~/.claude/projects")
sys.exit(1)
targets = files if args.all else files[:1]
while True:
if args.watch:
os.system("clear")
for f in targets:
report(f, args)
if not args.watch:
break
time.sleep(5)
if __name__ == "__main__":
main()