tokenops 0.2.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.
tokenops_cc/prompts.py ADDED
@@ -0,0 +1,362 @@
1
+ """Your prompts, each with every model call it led to, read once for the whole doctor report.
2
+
3
+ One prompt you type can make many model calls (tool use, subagents). This groups the calls
4
+ under the prompt that started them, prices each call, marks the ones that came back to an
5
+ expired prompt cache, and tags each prompt's cause from the largest share of its cost:
6
+
7
+ * ``CACHE EXPIRED`` you came back after the prompt cache expired, so one call wrote the whole
8
+ conversation to the cache again (2x the input price on the 1-hour cache).
9
+ * ``HUGE CONTEXT`` the conversation is so long that re-reading it on every call dominates.
10
+ * ``LONG LOOP`` Claude made many calls for one prompt, each re-reading the conversation.
11
+ * ``BIG NEW INPUT`` a large file or tool output entered the context.
12
+ * ``LONG REPLY`` most of the cost was Claude's own output.
13
+
14
+ Counterfactuals are estimates from the same price table (ADR 0009) and only re-price the calls
15
+ that a break made expensive. Forked sessions copy their parent's history into a new file, so
16
+ each call is counted once across all files.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import bisect
22
+ import datetime as dt
23
+ import glob
24
+ import json
25
+ import os
26
+ import re
27
+ import statistics
28
+ import time
29
+ from dataclasses import dataclass, field
30
+
31
+ from .prices import CACHE_WRITE_1H, CACHE_WRITE_5M, price_for, usage_cost, write_tokens
32
+
33
+ WINDOW_S = 5 * 3600 # Claude plans meter usage in 5-hour windows
34
+ FRESH_TOKENS = 30_000 # context after /clear: system prompt, tools, a short note
35
+ SUMMARY_OUT = 3_000 # tokens /compact writes as its summary
36
+ BIG_WRITE = 20_000
37
+ HUGE_CONTEXT = 150_000
38
+ _NOISE = ("<", "Caveat:", "This session is being continued", "[Request interrupted")
39
+ _SECRET = re.compile(r"\b(?=[A-Za-z0-9_\-]*\d)[A-Za-z0-9_\-]{24,}\b")
40
+ _TAG = re.compile(r"<([a-z][\w-]*)\b[^>]*>.*?</\1>", re.S)
41
+ _COLOR = {
42
+ "CACHE EXPIRED": "31",
43
+ "HUGE CONTEXT": "33",
44
+ "LONG LOOP": "33",
45
+ "BIG NEW INPUT": "35",
46
+ "LONG REPLY": "36",
47
+ }
48
+
49
+
50
+ @dataclass
51
+ class Call:
52
+ """One model call: one request to Claude and its reply."""
53
+
54
+ ts: float
55
+ cost: float
56
+ model: str
57
+ usage: dict
58
+ gap: float | None # seconds since the previous call in the same transcript
59
+ sub: bool = False # made by a subagent
60
+ ctx: int = 0 # tokens of conversation this call sent
61
+ expired: bool = False # the cache had expired, so the conversation was written again
62
+ ttl: int = 3600
63
+ before: float = 0.0 # this call's estimated cost had you run /compact before the break
64
+ fresh: float = 0.0 # ... had you run /clear and pasted a short note
65
+
66
+
67
+ @dataclass
68
+ class Prompt:
69
+ """Something you typed, and every model call it led to (subagents included)."""
70
+
71
+ ts: float | None
72
+ text: str
73
+ project: str
74
+ session: str = "" # the transcript file the prompt was typed in
75
+ calls: list[Call] = field(default_factory=list)
76
+ cause: str = ""
77
+ detail: list[str] = field(default_factory=list)
78
+ better: str = ""
79
+ window_share: float = 0.0
80
+ times_median: float = 0.0
81
+
82
+ @property
83
+ def cost(self) -> float:
84
+ return sum(c.cost for c in self.calls)
85
+
86
+ @property
87
+ def avoidable(self) -> float:
88
+ return sum(c.cost - c.before for c in self.calls if c.expired)
89
+
90
+
91
+ def _epoch(ts: str | None) -> float | None:
92
+ try:
93
+ return dt.datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp() if ts else None
94
+ except ValueError:
95
+ return None
96
+
97
+
98
+ def _typed_text(o: dict) -> str | None:
99
+ """The text a person typed, or None for tool results, meta and system lines."""
100
+ if o.get("type") != "user" or o.get("isMeta") or o.get("isCompactSummary"):
101
+ return None
102
+ if o.get("isSidechain"):
103
+ return None
104
+ c = (o.get("message") or {}).get("content")
105
+ if isinstance(c, list):
106
+ if any(isinstance(b, dict) and b.get("type") == "tool_result" for b in c):
107
+ return None
108
+ c = " ".join(b.get("text", "") for b in c if isinstance(b, dict))
109
+ raw = str(c or "")
110
+ if "<task-notification>" in raw:
111
+ return "(a background task finished)"
112
+ cmd = re.search(r"<command-name>\s*(/[\w:-]+)", raw)
113
+ text = " ".join(_TAG.sub(" ", raw).split()) # drop reminders and other blocks the app adds
114
+ if not text and cmd:
115
+ return cmd.group(1)
116
+ if not text and "<pasted_content" in raw:
117
+ return "(pasted text)"
118
+ return None if not text or text.startswith(_NOISE) else text
119
+
120
+
121
+ def _project(cwd: str | None, path: str) -> str:
122
+ if cwd:
123
+ return os.path.basename(cwd.rstrip("\\/")) or cwd
124
+ folder = os.path.basename(os.path.dirname(path)) # e.g. C--Users-me-src-myapp
125
+ return folder.rsplit("-", 1)[-1] or folder
126
+
127
+
128
+ def _price(call: Call) -> None:
129
+ p, _ = price_for(call.model)
130
+ u = call.usage
131
+ w5, w1 = write_tokens(u)
132
+ write = w5 + w1
133
+ call.ctx = write + (u.get("cache_read_input_tokens") or 0) + (u.get("input_tokens") or 0)
134
+ call.ttl = 3600 if w1 >= w5 else 300
135
+ call.expired = bool(
136
+ call.gap and call.gap > call.ttl and write >= BIG_WRITE and write >= 0.5 * call.ctx
137
+ )
138
+ if call.expired:
139
+ mult = CACHE_WRITE_1H if w1 >= w5 else CACHE_WRITE_5M
140
+ out = (u.get("output_tokens") or 0) * p["output"] / 1e6
141
+ call.fresh = min(call.ctx, FRESH_TOKENS) * mult * p["input"] / 1e6 + out
142
+ call.before = call.fresh + call.ctx * p["cache_read"] / 1e6
143
+ call.before += SUMMARY_OUT * p["output"] / 1e6
144
+
145
+
146
+ def _calls(path: str, seen: set[str], sub: bool) -> tuple[list, str | None]:
147
+ """[(prompt index, prompt line, Call)] for calls not counted yet, and the session's cwd."""
148
+ found: dict[str, list] = {}
149
+ order: list[str] = []
150
+ prompts: list[tuple[float | None, str]] = []
151
+ cwd = None
152
+ with open(path, encoding="utf-8", errors="ignore") as f:
153
+ for raw in f:
154
+ try:
155
+ o = json.loads(raw)
156
+ except ValueError:
157
+ continue
158
+ cwd = cwd or o.get("cwd")
159
+ typed = None if sub else _typed_text(o)
160
+ if typed is not None:
161
+ prompts.append((_epoch(o.get("timestamp")), typed))
162
+ continue
163
+ m = o.get("message") or {}
164
+ mid, usage = m.get("id"), m.get("usage")
165
+ if o.get("type") != "assistant" or not mid or not usage:
166
+ continue
167
+ if m.get("model") == "<synthetic>":
168
+ continue
169
+ if mid not in found:
170
+ order.append(mid)
171
+ found[mid] = [o.get("timestamp"), m.get("model") or "", usage, len(prompts) - 1]
172
+ found[mid][2] = usage # the last line of a response carries its final usage
173
+ out, prev = [], None
174
+ for mid in order:
175
+ ts_raw, model, usage, i = found[mid]
176
+ t = _epoch(ts_raw)
177
+ if t is None:
178
+ continue
179
+ gap = t - prev if prev else None
180
+ prev = t
181
+ if mid in seen: # copied history from a parent session: timing only
182
+ continue
183
+ seen.add(mid)
184
+ call = Call(t, usage_cost(model, usage, usage.get("speed"))[0], model, usage, gap, sub)
185
+ _price(call)
186
+ out.append((i, prompts[i] if i >= 0 else (None, ""), call))
187
+ return out, cwd
188
+
189
+
190
+ def _session(main: str, subs: list[str], seen: set[str]) -> list[Prompt]:
191
+ calls, cwd = _calls(main, seen, sub=False)
192
+ project = _project(cwd, main)
193
+ by_index: dict[int, Prompt] = {}
194
+ for i, (ts, text), call in calls:
195
+ p = by_index.setdefault(i, Prompt(ts, text, project, main))
196
+ p.calls.append(call)
197
+ prompts = sorted(by_index.values(), key=lambda p: p.ts or p.calls[0].ts)
198
+ for p in prompts:
199
+ p.ts = p.ts or p.calls[0].ts
200
+ starts = [p.ts for p in prompts]
201
+ for path in subs:
202
+ for _, _, call in _calls(path, seen, sub=True)[0]:
203
+ k = bisect.bisect_right(starts, call.ts) - 1
204
+ if k < 0: # a subagent with no prompt before it in this session
205
+ prompts.insert(0, Prompt(call.ts, "", project, main))
206
+ starts.insert(0, call.ts)
207
+ k = 0
208
+ prompts[k].calls.append(call)
209
+ return prompts
210
+
211
+
212
+ def _explain(p: Prompt) -> None:
213
+ buckets = {"CACHE EXPIRED": 0.0, "reads": 0.0, "LONG REPLY": 0.0, "BIG NEW INPUT": 0.0}
214
+ read_tokens = 0
215
+ for c in p.calls:
216
+ if c.expired:
217
+ buckets["CACHE EXPIRED"] += c.cost
218
+ continue
219
+ price, _ = price_for(c.model)
220
+ reads = (c.usage.get("cache_read_input_tokens") or 0) * price["cache_read"] / 1e6
221
+ out = (c.usage.get("output_tokens") or 0) * price["output"] / 1e6
222
+ read_tokens += c.usage.get("cache_read_input_tokens") or 0
223
+ buckets["reads"] += reads
224
+ buckets["LONG REPLY"] += out
225
+ buckets["BIG NEW INPUT"] += max(0.0, c.cost - reads - out)
226
+ cause = max(buckets, key=lambda b: buckets[b])
227
+ n = len(p.calls)
228
+ peak = max(c.ctx for c in p.calls)
229
+ if cause == "CACHE EXPIRED":
230
+ e = max((c for c in p.calls if c.expired), key=lambda c: c.cost)
231
+ mult = "2x" if e.ttl == 3600 else "1.25x"
232
+ p.detail = [
233
+ f"away {_dur(e.gap or 0)}, past the {_dur(e.ttl)} cache: one call re-wrote your",
234
+ f"whole {_k(e.ctx)}-token conversation to the cache at {mult} the input price",
235
+ ]
236
+ compact = p.cost - sum(c.cost - c.before for c in p.calls if c.expired)
237
+ clear = p.cost - sum(c.cost - c.fresh for c in p.calls if c.expired)
238
+ times = f" ({p.cost / compact:,.0f}x less)" if p.cost >= 2 * compact > 0 else ""
239
+ p.better = f"/compact before leaving ~${compact:,.2f}{times} | /clear + note ~${clear:,.2f}"
240
+ elif cause == "reads" and peak >= HUGE_CONTEXT:
241
+ cause = "HUGE CONTEXT"
242
+ price, _ = price_for(p.calls[0].model)
243
+ after = p.cost - buckets["reads"] + n * FRESH_TOKENS * price["cache_read"] / 1e6
244
+ p.detail = [f"every call re-read a conversation of up to {_k(peak)} tokens"]
245
+ p.better = f"the same calls after /compact ~${after:,.2f}"
246
+ elif cause == "reads":
247
+ cause = "LONG LOOP"
248
+ p.detail = [f"{n} calls for one prompt, each re-reading the conversation"]
249
+ p.better = "ask for one step at a time, or say when to stop"
250
+ elif cause == "LONG REPLY":
251
+ out = sum(c.usage.get("output_tokens") or 0 for c in p.calls)
252
+ p.detail = [f"Claude wrote {_k(out)} tokens of output"]
253
+ p.better = "ask for a shorter answer, or lower the effort level"
254
+ else:
255
+ new = sum(sum(write_tokens(c.usage)) for c in p.calls if not c.expired)
256
+ p.detail = [f"{_k(new)} new tokens entered the context"]
257
+ p.better = "read part of a large file or log (head, grep) instead of all of it"
258
+ p.cause = cause
259
+
260
+
261
+ def _k(tokens: int) -> str:
262
+ return f"{tokens / 1000:,.0f}k"
263
+
264
+
265
+ def _n(count: int, noun: str) -> str:
266
+ return f"{count:,} {noun}{'' if count == 1 else 's'}"
267
+
268
+
269
+ def _dur(s: float) -> str:
270
+ h, m = divmod(int(s) // 60, 60)
271
+ if h and m:
272
+ return f"{h}h {m:02d}m"
273
+ return f"{h}h" if h else f"{m}m"
274
+
275
+
276
+ def find(projects_dir: str, days: int = 7, top: int = 3) -> tuple[list[Prompt], list[Prompt]]:
277
+ """(top prompts by cost, all prompts with calls) for the last ``days`` days."""
278
+ cutoff = time.time() - days * 86400
279
+ seen: set[str] = set()
280
+ sessions = []
281
+ leftover = set(glob.glob(os.path.join(projects_dir, "*", "*", "subagents", "*.jsonl")))
282
+ for main in glob.glob(os.path.join(projects_dir, "*", "*.jsonl")):
283
+ subs = sorted(glob.glob(os.path.join(main[:-6], "subagents", "*.jsonl")))
284
+ leftover -= set(subs)
285
+ newest = max([os.path.getmtime(main)] + [os.path.getmtime(s) for s in subs])
286
+ if newest >= cutoff:
287
+ sessions.append((os.path.getmtime(main), main, subs))
288
+ prompts: list[Prompt] = []
289
+ for _, main, subs in sorted(sessions): # parents before their forks
290
+ prompts += _session(main, subs, seen)
291
+ for path in sorted(leftover, key=os.path.getmtime): # subagents whose session is gone
292
+ if os.path.getmtime(path) >= cutoff:
293
+ calls, cwd = _calls(path, seen, sub=True)
294
+ if calls:
295
+ p = Prompt(calls[0][2].ts, "", _project(cwd, os.path.dirname(path)), path)
296
+ p.calls = [c for _, _, c in calls]
297
+ prompts.append(p)
298
+ for p in prompts:
299
+ p.calls = [c for c in p.calls if c.ts >= cutoff]
300
+ prompts = sorted((p for p in prompts if p.calls), key=lambda p: p.ts or 0)
301
+ if not prompts:
302
+ return [], []
303
+ median = statistics.median(p.cost for p in prompts) or 1e-9
304
+ windows: list[list[Prompt]] = []
305
+ for p in prompts:
306
+ if not windows or (p.ts or 0) - (windows[-1][0].ts or 0) > WINDOW_S:
307
+ windows.append([])
308
+ windows[-1].append(p)
309
+ for w in windows:
310
+ total = sum(p.cost for p in w) or 1e-9
311
+ for p in w:
312
+ p.window_share = p.cost / total
313
+ p.times_median = p.cost / median
314
+ for p in prompts:
315
+ _explain(p)
316
+ return sorted(prompts, key=lambda p: p.cost, reverse=True)[:top], prompts
317
+
318
+
319
+ def _clip(prompt: str, redact: bool, width: int = 40) -> str:
320
+ if redact or not prompt:
321
+ return "(prompt hidden)" if prompt else "(no typed prompt)"
322
+ p = _SECRET.sub("***", prompt)
323
+ return '"' + (p if len(p) <= width else p[: width - 3].rstrip() + "...") + '"'
324
+
325
+
326
+ def prompt_lines(
327
+ worst: list[Prompt], redact: bool = False, color: bool = False, ascii_only: bool = False
328
+ ) -> list[str]:
329
+ """The report lines for the most expensive prompts, one block each."""
330
+
331
+ def c(code: str, s: str) -> str:
332
+ return f"[{code}m{s}" if color else s
333
+
334
+ full, empty = ("#", ".") if ascii_only else ("█", "░")
335
+ names: dict[str, str] = {}
336
+ for p in worst: # with --redact, projects become "project A", "project B", ...
337
+ names.setdefault(p.project, f"project {chr(65 + len(names) % 26)}")
338
+ label = {k: (v if redact else k[:18]) for k, v in names.items()}
339
+ pad = max((len(v) for v in label.values()), default=0)
340
+ lines: list[str] = []
341
+ for i, p in enumerate(worst, 1):
342
+ when = dt.datetime.fromtimestamp(p.ts or 0).strftime("%a %H:%M")
343
+ filled = max(1, round(20 * p.window_share))
344
+ bar = full * filled + empty * (20 - filled)
345
+ subs = sum(x.sub for x in p.calls)
346
+ calls = _n(len(p.calls), "model call")
347
+ if subs:
348
+ calls += f" ({subs} by subagents)"
349
+ tag = _COLOR[p.cause]
350
+ lines += [
351
+ f" {c('1', f'#{i}')} {c('2', when)} {c('34', label[p.project].ljust(pad))}"
352
+ f" {_clip(p.text, redact)}",
353
+ f" {c(tag, bar)} {c('1', f'{100 * p.window_share:.0f}%')} of that 5-hour window"
354
+ f" {c('2', '|')} {p.times_median:,.0f}x your typical prompt",
355
+ f" {c(tag + ';1', p.cause)} {p.detail[0]}",
356
+ ]
357
+ lines += [f" {' ' * len(p.cause)} {d}" for d in p.detail[1:]]
358
+ lines += [
359
+ f" {c('2', f'{calls}, paid ${p.cost:,.2f} -> ')}{c('32', p.better)}",
360
+ "",
361
+ ]
362
+ return lines
tokenops_cc/rtk.py ADDED
@@ -0,0 +1,96 @@
1
+ """Smart RTK: compact shell output with RTK only where Claude does not need it verbatim.
2
+
3
+ RTK (rtk-ai/rtk) rewrites a shell command to its compact form (``git status`` -> ``rtk git
4
+ status``). TokenOps asks the installed ``rtk`` for that rewrite (``rtk rewrite``, the call RTK's
5
+ own hook makes) and applies it, except for:
6
+
7
+ * reads of a file (``cat``, ``head``, ``tail``, ``sed -n``, ``nl``) and ``git diff``/``git show``:
8
+ Claude often edits next and needs the exact text;
9
+ * a test run right after a test run that failed: Claude needs the full failure.
10
+
11
+ RTK stays its own install (its engine is BSL 1.1; TokenOps never bundles it). When RTK's own
12
+ hook is installed, smart RTK stays off so a command is never rewritten twice.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import re
19
+ import shlex
20
+ import shutil
21
+ import subprocess
22
+
23
+ from . import savers, settings
24
+
25
+ VERBATIM = re.compile(r"^\s*(cat|head|tail|less|nl|sed\s+-n|git\s+(diff|show))\b")
26
+ TEST = re.compile(r"\b(pytest|jest|vitest|go\s+test|cargo\s+test|npm\s+(run\s+)?test|tox)\b")
27
+ FAILED = re.compile(r"\b(\d+\s+failed|FAILED|FAIL:|Traceback|Error:)", re.IGNORECASE)
28
+
29
+
30
+ def rtk_command() -> list[str] | None:
31
+ """How to run rtk: ``$TOKENOPS_RTK`` (for tests) or ``rtk`` on PATH."""
32
+ custom = os.environ.get("TOKENOPS_RTK")
33
+ if custom:
34
+ return [part.strip('"') for part in shlex.split(custom, posix=False)]
35
+ found = shutil.which("rtk")
36
+ return [found] if found else None
37
+
38
+
39
+ def status() -> str:
40
+ if rtk_command() is None:
41
+ return "off (rtk not found; install it from github.com/rtk-ai/rtk to use it)"
42
+ if "rtk" in savers.detect():
43
+ return "off (RTK's own hook is installed; remove it from your Claude Code settings first)"
44
+ return "on (compacts shell output, keeps file reads, diffs and failing tests verbatim)"
45
+
46
+
47
+ def rewrite(command: str, last_test_failed: bool) -> str | None:
48
+ if VERBATIM.match(command) or (last_test_failed and TEST.search(command)):
49
+ return None
50
+ rtk = rtk_command()
51
+ if rtk is None:
52
+ return None
53
+ try:
54
+ r = subprocess.run([*rtk, "rewrite", command], capture_output=True, text=True, timeout=5)
55
+ except (OSError, subprocess.TimeoutExpired):
56
+ return None
57
+ new = r.stdout.strip()
58
+ if r.returncode not in (0, 3) or not new or new == command.strip():
59
+ return None # 1: nothing to rewrite, 2: denied
60
+ return new
61
+
62
+
63
+ def _active() -> bool:
64
+ return bool(settings.load_config().get("saver")) and status().startswith("on")
65
+
66
+
67
+ def pre_tool_use(payload: dict) -> dict | None:
68
+ """Rewrite a Bash command to its RTK form when that is safe."""
69
+ tool_input = payload.get("tool_input") or {}
70
+ command = str(tool_input.get("command") or "")
71
+ sid = payload.get("session_id") or "unknown"
72
+ if payload.get("tool_name") != "Bash" or not command or not _active():
73
+ return None
74
+ if settings.load_session(sid).get("arms", {}).get("rtk") is False:
75
+ return None # the A/B test has RTK off in this session
76
+ new = rewrite(command, settings.load_session(sid).get("last_test_failed", False))
77
+ if new is None:
78
+ return None
79
+ return {
80
+ "hookSpecificOutput": {
81
+ "hookEventName": "PreToolUse",
82
+ "updatedInput": {**tool_input, "command": new},
83
+ }
84
+ }
85
+
86
+
87
+ def post_tool_use(payload: dict) -> None:
88
+ """Remember whether the last test run failed, so the next one is shown in full."""
89
+ command = str((payload.get("tool_input") or {}).get("command") or "")
90
+ if payload.get("tool_name") != "Bash" or not TEST.search(command):
91
+ return None
92
+ sid = payload.get("session_id") or "unknown"
93
+ state = settings.load_session(sid)
94
+ state["last_test_failed"] = bool(FAILED.search(str(payload.get("tool_response") or "")))
95
+ settings.save_session(sid, state)
96
+ return None
tokenops_cc/savers.py ADDED
@@ -0,0 +1,53 @@
1
+ """Detect which token savers are active, so sessions can be compared with and without them.
2
+
3
+ Read-only: looks at Claude Code settings files, never changes them.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+
12
+ KNOWN = {
13
+ "caveman": ("caveman",),
14
+ "rtk": ("rtk ", "rtk-", "/rtk", "rtk.exe", "rtk hook", "rtk rewrite"),
15
+ "headroom": ("headroom",),
16
+ "context-mode": ("context-mode", "context_mode"),
17
+ "claude-mem": ("claude-mem",),
18
+ "ponytail": ("ponytail",),
19
+ }
20
+
21
+
22
+ def _read(p: Path) -> dict:
23
+ try:
24
+ return json.loads(p.read_text(encoding="utf-8"))
25
+ except (OSError, ValueError):
26
+ return {}
27
+
28
+
29
+ def _settings_files(cwd: str | None) -> list[Path]:
30
+ home = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
31
+ files = [home / "settings.json", home / "settings.local.json"]
32
+ if cwd:
33
+ files += [
34
+ Path(cwd) / ".claude" / "settings.json",
35
+ Path(cwd) / ".claude" / "settings.local.json",
36
+ ]
37
+ return files
38
+
39
+
40
+ def detect(cwd: str | None = None) -> list[str]:
41
+ blob = ""
42
+ for f in _settings_files(cwd):
43
+ s = _read(f)
44
+ if not s:
45
+ continue
46
+ enabled = s.get("enabledPlugins") or {}
47
+ if isinstance(enabled, dict):
48
+ blob += " ".join(k for k, v in enabled.items() if v) + " "
49
+ elif isinstance(enabled, list):
50
+ blob += " ".join(map(str, enabled)) + " "
51
+ blob += json.dumps(s.get("hooks") or {}) + " " + json.dumps(s.get("mcpServers") or {}) + " "
52
+ blob = blob.lower()
53
+ return sorted(name for name, needles in KNOWN.items() if any(n in blob for n in needles))
@@ -0,0 +1,59 @@
1
+ """Local settings and per-session state, in Claude Code's plugin data folder.
2
+
3
+ ``$CLAUDE_PLUGIN_DATA`` when Claude Code provides it, else ``~/.tokenops/claude-code``. Nothing
4
+ here leaves the machine.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import re
12
+ from pathlib import Path
13
+
14
+
15
+ def data_dir() -> Path:
16
+ d = os.environ.get("TOKENOPS_DATA") or os.environ.get("CLAUDE_PLUGIN_DATA")
17
+ path = Path(d) if d else Path.home() / ".tokenops" / "claude-code"
18
+ path.mkdir(parents=True, exist_ok=True)
19
+ return path
20
+
21
+
22
+ def _read(path: Path) -> dict:
23
+ try:
24
+ return json.loads(path.read_text(encoding="utf-8"))
25
+ except (OSError, ValueError):
26
+ return {}
27
+
28
+
29
+ def _write(path: Path, data: dict) -> None:
30
+ tmp = path.with_suffix(".tmp")
31
+ tmp.write_text(json.dumps(data), encoding="utf-8")
32
+ os.replace(tmp, path)
33
+
34
+
35
+ def load_config() -> dict:
36
+ return _read(data_dir() / "config.json")
37
+
38
+
39
+ def save_config(config: dict) -> None:
40
+ _write(data_dir() / "config.json", config)
41
+
42
+
43
+ def _session_path(session_id: str) -> Path:
44
+ safe = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "unknown")[:128]
45
+ (data_dir() / "sessions").mkdir(exist_ok=True)
46
+ return data_dir() / "sessions" / f"{safe}.json"
47
+
48
+
49
+ def load_session(session_id: str) -> dict:
50
+ return _read(_session_path(session_id))
51
+
52
+
53
+ def save_session(session_id: str, state: dict) -> None:
54
+ _write(_session_path(session_id), state)
55
+
56
+
57
+ def all_sessions() -> list[dict]:
58
+ folder = data_dir() / "sessions"
59
+ return [_read(p) for p in folder.glob("*.json")] if folder.exists() else []
@@ -0,0 +1,99 @@
1
+ """Incremental reader for Claude Code session transcripts (JSONL).
2
+
3
+ Claude Code writes one line per content block, so one API response appears on several lines
4
+ that repeat the same ``message.id`` and usage. Summing every line over-counts (in a real
5
+ session: 4,441 assistant lines, 1,944 unique responses). We keep the *last* line per
6
+ ``message.id``, which carries the final usage.
7
+
8
+ Subagent work is logged in ``<session dir>/subagents/*.jsonl`` next to the main transcript and
9
+ is billed too, so it is read the same way.
10
+
11
+ The reader is incremental: it remembers a byte offset per file and only parses new complete
12
+ lines, so a hook stays fast on long sessions.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import glob
18
+ import json
19
+ import os
20
+ from dataclasses import dataclass, field
21
+
22
+
23
+ @dataclass
24
+ class Response:
25
+ model: str
26
+ usage: dict
27
+ speed: str | None
28
+ sidechain: bool
29
+ ts: str | None = None
30
+
31
+
32
+ @dataclass
33
+ class TranscriptState:
34
+ offsets: dict[str, int] = field(default_factory=dict)
35
+ responses: dict[str, Response] = field(default_factory=dict)
36
+
37
+
38
+ _KEEP = (
39
+ "input_tokens",
40
+ "output_tokens",
41
+ "cache_read_input_tokens",
42
+ "cache_creation_input_tokens",
43
+ "cache_creation",
44
+ )
45
+
46
+
47
+ def transcript_files(transcript_path: str) -> list[str]:
48
+ files = [transcript_path] if transcript_path and os.path.exists(transcript_path) else []
49
+ if transcript_path:
50
+ base = os.path.splitext(transcript_path)[0]
51
+ files += sorted(glob.glob(os.path.join(base, "subagents", "*.jsonl")))
52
+ return files
53
+
54
+
55
+ def update(state: TranscriptState, transcript_path: str) -> int:
56
+ """Read new lines from the transcript and its subagent files. Returns new responses seen."""
57
+ new = 0
58
+ for path in transcript_files(transcript_path):
59
+ start = state.offsets.get(path, 0)
60
+ try:
61
+ size = os.path.getsize(path)
62
+ except OSError:
63
+ continue
64
+ if size < start: # file replaced or truncated: read again from the top
65
+ start = 0
66
+ if size == start:
67
+ continue
68
+ with open(path, "rb") as f:
69
+ f.seek(start)
70
+ chunk = f.read()
71
+ end = chunk.rfind(b"\n")
72
+ if end < 0:
73
+ continue # no complete line yet
74
+ for raw in chunk[: end + 1].splitlines():
75
+ if not raw.strip():
76
+ continue
77
+ try:
78
+ o = json.loads(raw)
79
+ except ValueError:
80
+ continue
81
+ if o.get("type") != "assistant":
82
+ continue
83
+ msg = o.get("message") or {}
84
+ mid = msg.get("id") or o.get("requestId") or o.get("uuid")
85
+ usage = msg.get("usage")
86
+ model = msg.get("model") or ""
87
+ if not mid or not usage or model == "<synthetic>":
88
+ continue
89
+ if mid not in state.responses:
90
+ new += 1
91
+ state.responses[mid] = Response(
92
+ model=model,
93
+ usage={k: usage.get(k) for k in _KEEP if usage.get(k) is not None},
94
+ speed=usage.get("speed"),
95
+ sidechain=bool(o.get("isSidechain")) or path != transcript_path,
96
+ ts=o.get("timestamp"),
97
+ )
98
+ state.offsets[path] = start + end + 1
99
+ return new