tokenreach 0.5.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.
tokenreach/__init__.py ADDED
@@ -0,0 +1,75 @@
1
+ """tokenreach: from your own Claude Code logs, see how big the part each token-saving tool works on really is."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ from .data import DataError, load_prices, load_tools, rtk_rules
10
+ from .logs import find_logs, scan
11
+ from .report import render_text, summarize
12
+
13
+ DEFAULT_PATH = Path.home() / ".claude" / "projects"
14
+ MAX_DAYS = 3650
15
+
16
+
17
+ def days_type(text):
18
+ """--days must be a whole number from 1 to 3650; anything else is a usage error (exit code 2)."""
19
+ try:
20
+ days = int(text)
21
+ except ValueError:
22
+ days = 0
23
+ if not 1 <= days <= MAX_DAYS:
24
+ raise argparse.ArgumentTypeError(f"must be a whole number from 1 to {MAX_DAYS}")
25
+ return days
26
+
27
+
28
+ def build_parser():
29
+ parser = argparse.ArgumentParser(prog="tokenreach", description=__doc__)
30
+ sub = parser.add_subparsers(dest="command", required=True)
31
+ rep = sub.add_parser("report", help="print a short summary of cost and the part each kind of tool works on")
32
+ rep.add_argument("--path", type=Path, default=DEFAULT_PATH,
33
+ help="log directory, or one .jsonl file (a single file is read whatever its date)")
34
+ rep.add_argument("--days", type=days_type, default=30,
35
+ help=f"in a directory, only files modified in the last N days (1 to {MAX_DAYS}, default 30)")
36
+ rep.add_argument("--full", action="store_true", help="print every breakdown and the known tools")
37
+ rep.add_argument("--json", action="store_true", help="print JSON instead of text")
38
+ rep.add_argument("--data", type=Path, help="extra tools file (distributed separately), same format as tools.toml")
39
+ rep.add_argument("--debug", action="store_true", help="show full details if something unexpected fails")
40
+ return parser
41
+
42
+
43
+ def run(args, parser):
44
+ path = args.path.expanduser()
45
+ if not path.exists():
46
+ parser.error("--path does not exist")
47
+ tools = load_tools(args.data)
48
+ days = None if path.is_file() else args.days
49
+ files, unlisted = ([path], 0) if days is None else find_logs(path, days)
50
+ tally = scan(files, load_prices(), rtk_rules(tools))
51
+ summary = summarize(tally, len(files), unlisted, days, tools)
52
+ if hasattr(sys.stdout, "reconfigure"): # legacy Windows code pages cannot print some characters in tool data
53
+ sys.stdout.reconfigure(errors="replace")
54
+ if args.json:
55
+ summary["generated_at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
56
+ print(json.dumps(summary, indent=2))
57
+ else:
58
+ print(render_text(summary, full=args.full))
59
+ return 0
60
+
61
+
62
+ def main(argv=None):
63
+ parser = build_parser()
64
+ args = parser.parse_args(argv)
65
+ try:
66
+ return run(args, parser)
67
+ except DataError as e:
68
+ print(f"tokenreach: --data file: {e}", file=sys.stderr)
69
+ return 2
70
+ except Exception as e: # last line of defence: print no paths and no traceback unless asked
71
+ if args.debug:
72
+ raise
73
+ print(f"tokenreach: unexpected error ({type(e).__name__}). Run again with --debug for details.",
74
+ file=sys.stderr)
75
+ return 1
tokenreach/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from tokenreach import main
4
+
5
+ sys.exit(main())
tokenreach/data.py ADDED
@@ -0,0 +1,142 @@
1
+ """Bundled data (price ratios, known tools) and the optional --data file of extra tools."""
2
+
3
+ import tomllib
4
+ from pathlib import Path
5
+
6
+ from .logs import COST_PARTS, PROMPT_PARTS
7
+
8
+ DATA_DIR = Path(__file__).resolve().parent
9
+ # Which part of your logs a tool works on. Shown next to the tool; see report.part_shares.
10
+ PARTS = ("shell_output", "rtk_commands", "ai_output", "file_reads", "tool_results", "fixed_and_other", "input_side",
11
+ "none")
12
+ STATUSES = ("verified", "secondary")
13
+ TOOL_FIELDS = {
14
+ "name": str, "url": str, "kind": str, "part": str, "claimed": str, "touches": str, "note": str,
15
+ "independent_note": str, "covers": list, "covers_source": list, "measurement": list,
16
+ }
17
+ REQUIRED_TOOL_FIELDS = ("name", "url", "kind", "part")
18
+ MEASUREMENT_FIELDS = {"value": str, "how": str, "source": str, "date": str, "status": str}
19
+ REQUIRED_MEASUREMENT_FIELDS = ("value", "source", "status")
20
+
21
+
22
+ class DataError(Exception):
23
+ """A tools file that does not follow the format. The message says where."""
24
+
25
+
26
+ class Prices:
27
+ def __init__(self, data):
28
+ self.source = data["source"]
29
+ self.checked = data["checked"]
30
+ self.multipliers = data["multipliers"]
31
+ self.models = sorted(data["model"], key=lambda m: -len(m["prefix"]))
32
+
33
+ def ratios(self, model):
34
+ """(price entry, per-part multipliers) for a model id, or (None, None) when it has no price entry."""
35
+ entry = next((m for m in self.models if model.startswith(m["prefix"])), None)
36
+ if entry is None:
37
+ return None, None
38
+ return entry, {k: entry.get(k, self.multipliers[k]) for k in COST_PARTS}
39
+
40
+ def cost(self, model, parts):
41
+ """Relative cost per part in price units (not printed), or None for models without a price entry."""
42
+ entry, ratios = self.ratios(model)
43
+ if entry is None:
44
+ return None
45
+ price = entry["input_price"]
46
+ if "long_prompt_over" in entry and sum(parts[k] for k in PROMPT_PARTS) > entry["long_prompt_over"]:
47
+ price = entry["long_input_price"]
48
+ return {k: parts[k] * ratios[k] * price for k in COST_PARTS}
49
+
50
+
51
+ def load_prices():
52
+ with open(DATA_DIR / "weights.toml", "rb") as fh:
53
+ return Prices(tomllib.load(fh))
54
+
55
+
56
+ def _line_of(lines, start, field):
57
+ """Line number of `field = ...` inside the [[tool]] block that starts at `start` (0-based), else the block."""
58
+ for i in range(start + 1, len(lines)):
59
+ stripped = lines[i].strip()
60
+ if stripped == "[[tool]]":
61
+ break
62
+ if stripped.split("=", 1)[0].strip() == field:
63
+ return i + 1
64
+ return start + 1
65
+
66
+
67
+ def _check_fields(table, fields, required):
68
+ """Name of the first bad field and what is wrong with it, or None."""
69
+ for field in required:
70
+ if field not in table:
71
+ return field, "is missing"
72
+ for field, value in table.items():
73
+ if field not in fields:
74
+ return field, "is not a known field"
75
+ if not isinstance(value, fields[field]):
76
+ return field, f"must be a {fields[field].__name__}"
77
+ return None
78
+
79
+
80
+ def _check_tool(tool):
81
+ problem = _check_fields(tool, TOOL_FIELDS, REQUIRED_TOOL_FIELDS)
82
+ if problem:
83
+ return problem
84
+ if tool["part"] not in PARTS:
85
+ return "part", f"must be one of: {', '.join(PARTS)}"
86
+ if tool["part"] == "rtk_commands" and not tool.get("covers"):
87
+ return "covers", "is required when part is rtk_commands"
88
+ for field in ("covers", "covers_source"):
89
+ if not all(isinstance(x, str) and x.strip() for x in tool.get(field, [])):
90
+ return field, "must be a list of non-empty strings"
91
+ return _check_measurements(tool.get("measurement", []))
92
+
93
+
94
+ def _check_measurements(measurements):
95
+ for m in measurements:
96
+ if not isinstance(m, dict):
97
+ return "measurement", "must be a list of tables"
98
+ problem = _check_fields(m, MEASUREMENT_FIELDS, REQUIRED_MEASUREMENT_FIELDS)
99
+ if problem:
100
+ return f"measurement.{problem[0]}", problem[1]
101
+ if m["status"] not in STATUSES:
102
+ return "measurement.status", f"must be one of: {', '.join(STATUSES)}"
103
+ return None
104
+
105
+
106
+ def parse_tools(text):
107
+ """Validated list of tools from the text of a tools file. Raises DataError naming the line and field."""
108
+ try:
109
+ data = tomllib.loads(text)
110
+ except tomllib.TOMLDecodeError as e:
111
+ raise DataError(f"not valid TOML: {e}") from None
112
+ tools = data.get("tool")
113
+ if not isinstance(tools, list) or not tools:
114
+ raise DataError("no [[tool]] entries found")
115
+ lines = text.splitlines()
116
+ starts = [i for i, line in enumerate(lines) if line.strip() == "[[tool]]"]
117
+ for n, tool in enumerate(tools):
118
+ problem = _check_tool(tool)
119
+ if problem:
120
+ field = problem[0].split(".")[-1]
121
+ line = _line_of(lines, starts[n], field) if n < len(starts) else 0
122
+ raise DataError(f"line {line}, tool #{n + 1}, field '{problem[0]}' {problem[1]}")
123
+ return tools
124
+
125
+
126
+ def load_tools(extra_path=None):
127
+ """Bundled tools, plus tools from an extra file. A tool with the same name in the extra file wins."""
128
+ tools = parse_tools((DATA_DIR / "tools.toml").read_text(encoding="utf-8"))
129
+ if extra_path is None:
130
+ return tools
131
+ try:
132
+ text = Path(extra_path).read_text(encoding="utf-8")
133
+ except (OSError, UnicodeDecodeError) as e:
134
+ raise DataError(f"could not be read ({type(e).__name__})") from None
135
+ extra = {t["name"]: t for t in parse_tools(text)}
136
+ merged = [extra.pop(t["name"], t) for t in tools]
137
+ return merged + list(extra.values())
138
+
139
+
140
+ def rtk_rules(tools):
141
+ """Command prefixes from the tool whose part is rtk_commands (RTK)."""
142
+ return [rule.split() for t in tools if t["part"] == "rtk_commands" for rule in t.get("covers", [])]
tokenreach/logs.py ADDED
@@ -0,0 +1,425 @@
1
+ """Read Claude Code logs line by line: usage, tool results, and what each API call re-reads."""
2
+
3
+ import json
4
+ import re
5
+ import time
6
+ from datetime import datetime
7
+
8
+ USAGE_KEYS = ("input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")
9
+ COST_PARTS = ("input", "cache_write_5m", "cache_write_1h", "cache_read", "output")
10
+ PROMPT_PARTS = ("input", "cache_write_5m", "cache_write_1h", "cache_read")
11
+ SHELL_TOOLS = ("Bash", "PowerShell")
12
+ TOOL_GROUPS = ("Bash", "PowerShell", "Read", "Grep", "Glob", "WebFetch", "Other")
13
+ POWERSHELL_FAMILY = "powershell cmdlets and variables"
14
+ SHELL_FAMILIES = {
15
+ "git": {"git"},
16
+ "gh": {"gh"},
17
+ "test/build/lint": {"pytest", "vitest", "jest", "cargo", "go", "make", "ruff", "mypy", "tsc", "eslint", "tox"},
18
+ "python": {"python", "python3", "py", "pip", "uv", "uvx"},
19
+ "node/npm/npx": {"node", "npm", "npx", "pnpm", "yarn", "bun", "deno"},
20
+ "ls/find/cat/head/tail/wc/diff": {"ls", "find", "cat", "head", "tail", "wc", "tree", "diff", "du", "stat", "file"},
21
+ "grep/rg": {"grep", "rg"},
22
+ "sed/awk/tr/sort": {"sed", "awk", "tr", "cut", "sort", "uniq", "jq"},
23
+ "shell builtins and utils": {
24
+ "for", "while", "until", "if", "export", "echo", "printf", "date", "mkdir", "cp", "mv", "rm", "sleep",
25
+ "bash", "sh", "timeout", "touch", "source", "test", "true", "cmp", "sha256sum", "chmod", "xargs", "tee",
26
+ "which", "env", "set", "ps", "kill", "unzip", "tar", "schtasks",
27
+ },
28
+ POWERSHELL_FAMILY: {"powershell", "pwsh", "cmd", "foreach", "%"},
29
+ "curl/wget": {"curl", "wget"},
30
+ "docker/kubectl": {"docker", "docker-compose", "kubectl"},
31
+ }
32
+ FAMILY_ORDER = (*SHELL_FAMILIES, "other")
33
+ CMDLET = re.compile(r"[a-z]+-[a-z]+")
34
+ SKIP_FIRST = {"cd", "set-location", "pushd", "&"}
35
+ AI_ROWS = ("AI text", "AI thinking", "AI tool calls")
36
+ TOOL_ROWS = (*(f"Shell: {f}" for f in FAMILY_ORDER), "Read", "Grep", "Glob", "WebFetch", "Other tools")
37
+ CONTEXT_ROWS = (*TOOL_ROWS, *AI_ROWS, "User messages")
38
+ RTK_KEY = "_rtk"
39
+ # Official model ids look like claude-opus-4-6 or claude-opus-5-5-20261101; anything else is reported as "other".
40
+ MODEL_ID = re.compile(r"claude-(?:fable|mythos|opus|sonnet|haiku)-\d{1,2}(?:-\d{1,2})?(?=$|-|\[)")
41
+ CALIBRATION_MIN_CHARS = 300
42
+ MAX_TOKENS = 10**15 # far above any real request; larger values would overflow float math
43
+
44
+
45
+ class BadRecord(Exception):
46
+ """A JSON line whose fields have types the log format does not use."""
47
+
48
+
49
+ def _int(value):
50
+ if value is None:
51
+ return 0
52
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= MAX_TOKENS:
53
+ raise BadRecord
54
+ return value
55
+
56
+
57
+ def _str(value):
58
+ if value is None:
59
+ return ""
60
+ if not isinstance(value, str):
61
+ raise BadRecord
62
+ return value
63
+
64
+
65
+ def _dict(value):
66
+ if value is None:
67
+ return {}
68
+ if not isinstance(value, dict):
69
+ raise BadRecord
70
+ return value
71
+
72
+
73
+ def _list(value):
74
+ if value is None:
75
+ return []
76
+ if not isinstance(value, list):
77
+ raise BadRecord
78
+ return value
79
+
80
+
81
+ def date_of(timestamp):
82
+ """YYYY-MM-DD of an ISO timestamp, or None when it cannot be read as a date (the line still counts)."""
83
+ if not isinstance(timestamp, str):
84
+ return None
85
+ try:
86
+ return datetime.fromisoformat(timestamp).date().isoformat()
87
+ except ValueError:
88
+ return None
89
+
90
+
91
+ def normalize_model(model):
92
+ match = MODEL_ID.match(model)
93
+ return match.group(0) if match else "other"
94
+
95
+
96
+ def command_words(command):
97
+ """Words of the first real command. Skips `cd ...` segments, comments, `&` and VAR=value prefixes."""
98
+ for segment in re.split(r"&&|\|\||;|\n", command):
99
+ words = segment.split()
100
+ while words and ("=" in words[0] and not words[0].startswith("=") or words[0] == "&"):
101
+ words.pop(0)
102
+ if not words or words[0].lower() in SKIP_FIRST or words[0].startswith("#"):
103
+ continue
104
+ words[0] = words[0].strip("\"'").replace("\\", "/").rsplit("/", 1)[-1].lower().removesuffix(".exe")
105
+ return words
106
+ return []
107
+
108
+
109
+ def shell_family(words):
110
+ head = "pytest" if words[1:3] == ["-m", "pytest"] else (words[0] if words else "")
111
+ for family, names in SHELL_FAMILIES.items():
112
+ if head in names:
113
+ return family
114
+ if head.startswith("$") or CMDLET.fullmatch(head):
115
+ return POWERSHELL_FAMILY
116
+ return "other"
117
+
118
+
119
+ def rtk_covered(words, rules):
120
+ return any(words[: len(rule)] == rule for rule in rules)
121
+
122
+
123
+ def split_chars(text):
124
+ """(ASCII characters, non-ASCII characters)."""
125
+ ascii_count = len(text.encode("ascii", "ignore"))
126
+ return ascii_count, len(text) - ascii_count
127
+
128
+
129
+ def parse_usage(usage):
130
+ """Token counts per billing part, and cache-write tokens that had no 5m/1h split (counted as 5m)."""
131
+ usage = _dict(usage)
132
+ written = _int(usage.get("cache_creation_input_tokens"))
133
+ split = usage.get("cache_creation")
134
+ one_hour = 0 if split is None else min(_int(_dict(split).get("ephemeral_1h_input_tokens")), written)
135
+ parts = {
136
+ "input": _int(usage.get("input_tokens")),
137
+ "cache_write_5m": written - one_hour,
138
+ "cache_write_1h": one_hour,
139
+ "cache_read": _int(usage.get("cache_read_input_tokens")),
140
+ "output": _int(usage.get("output_tokens")),
141
+ }
142
+ return parts, (written if split is None else 0)
143
+
144
+
145
+ def parse_ai_blocks(content):
146
+ if isinstance(content, str):
147
+ return [("text", content)]
148
+ blocks = []
149
+ for block in _list(content):
150
+ block = _dict(block)
151
+ kind = block.get("type")
152
+ if kind == "text":
153
+ blocks.append(("text", _str(block.get("text"))))
154
+ elif kind == "thinking":
155
+ blocks.append(("thinking", _str(block.get("thinking"))))
156
+ elif kind == "tool_use":
157
+ name, tool_input = _str(block.get("name")), _dict(block.get("input"))
158
+ command = _str(tool_input.get("command")) if name in SHELL_TOOLS else ""
159
+ text = name + json.dumps(tool_input, ensure_ascii=False)
160
+ blocks.append(("tool_use", _str(block.get("id")), name, text, command))
161
+ return blocks
162
+
163
+
164
+ def result_text(content):
165
+ """Text of a tool_result, and whether it was plain text. Images and other non-text blocks are not counted."""
166
+ if isinstance(content, str):
167
+ return content, True
168
+ texts = [_str(_dict(b).get("text")) for b in _list(content) if _dict(b).get("type") == "text"]
169
+ return "".join(texts), False
170
+
171
+
172
+ def parse_user_blocks(content):
173
+ if isinstance(content, str):
174
+ return [("text", content)]
175
+ blocks = []
176
+ for block in _list(content):
177
+ block = _dict(block)
178
+ if block.get("type") == "tool_result":
179
+ blocks.append(("result", _str(block.get("tool_use_id")), *result_text(block.get("content"))))
180
+ elif block.get("type") == "text":
181
+ blocks.append(("text", _str(block.get("text"))))
182
+ return blocks
183
+
184
+
185
+ class Calibration:
186
+ """Chars-to-tokens rate from the logs: prompt growth between two API calls when only a tool call
187
+ and its plain-text result were added in between."""
188
+
189
+ def __init__(self):
190
+ self.ascii = [0, 0, 0] # [token growth, ASCII chars, pairs] for pairs with ASCII text only
191
+ self.mixed = [0, 0, 0, 0] # [token growth, ASCII chars, non-ASCII chars, pairs], mostly non-ASCII text
192
+ self.pending = None # [prompt tokens of the last call, still clean, ASCII chars, non-ASCII chars]
193
+
194
+ def next_call(self, prompt):
195
+ p = self.pending
196
+ if p and p[1] and p[2] + p[3] > CALIBRATION_MIN_CHARS and prompt > p[0]:
197
+ growth = prompt - p[0]
198
+ if p[3] == 0:
199
+ self.ascii = [self.ascii[0] + growth, self.ascii[1] + p[2], self.ascii[2] + 1]
200
+ elif p[3] > 0.3 * (p[2] + p[3]):
201
+ m = self.mixed
202
+ self.mixed = [m[0] + growth, m[1] + p[2], m[2] + p[3], m[3] + 1]
203
+ self.pending = [prompt, True, 0, 0]
204
+
205
+ def add(self, ascii_chars, other_chars):
206
+ if self.pending:
207
+ self.pending[2] += ascii_chars
208
+ self.pending[3] += other_chars
209
+
210
+ def dirty(self):
211
+ if self.pending:
212
+ self.pending[1] = False
213
+
214
+ def reset(self):
215
+ self.pending = None
216
+
217
+
218
+ class Tally:
219
+ def __init__(self, prices, rtk_rules):
220
+ self.prices = prices
221
+ self.rtk_rules = rtk_rules
222
+ self.usage = dict.fromkeys(USAGE_KEYS, 0)
223
+ self.messages = 0
224
+ self.tool_chars = dict.fromkeys(TOOL_GROUPS, 0)
225
+ self.shell_chars = dict.fromkeys(FAMILY_ORDER, 0)
226
+ self.tool_results = 0
227
+ self.unreadable = {}
228
+ self.unreadable_files = 0
229
+ self.compactions = 0
230
+ self.first = None
231
+ self.last = None
232
+ self.models = {}
233
+ self.unpriced_messages = 0
234
+ self.assumed_5m_tokens = 0
235
+ self.reads = {k: [0, 0] for k in (*CONTEXT_ROWS, RTK_KEY)} # [ASCII chars, non-ASCII chars] re-read
236
+ self.input_side = 0
237
+ self.calibration = Calibration()
238
+ self._seen_messages = set()
239
+ self._seen_results = set()
240
+ self._tool_uses = {}
241
+ self.start_conversation()
242
+
243
+ def start_conversation(self):
244
+ """One log file is one conversation: context starts empty."""
245
+ self._context = {k: [0, 0] for k in (*CONTEXT_ROWS, RTK_KEY)}
246
+ self._in_file = set()
247
+ self.calibration.reset()
248
+
249
+ def add_line(self, raw):
250
+ if not raw.strip():
251
+ return
252
+ try:
253
+ rec = json.loads(raw)
254
+ except UnicodeDecodeError:
255
+ self._bad("invalid text encoding")
256
+ return
257
+ except RecursionError:
258
+ self._bad("nested too deeply")
259
+ return
260
+ except ValueError:
261
+ self._bad("invalid JSON")
262
+ return
263
+ try:
264
+ self._add_record(rec)
265
+ except BadRecord:
266
+ self._bad("unexpected field type")
267
+
268
+ def _bad(self, reason):
269
+ self.unreadable[reason] = self.unreadable.get(reason, 0) + 1
270
+
271
+ def _add_record(self, rec):
272
+ """Parses the whole line first, so a bad line changes no counts."""
273
+ rec = _dict(rec)
274
+ kind = rec.get("type")
275
+ if kind == "system" and rec.get("subtype") == "compact_boundary":
276
+ self.compactions += 1
277
+ self._context = {k: [0, 0] for k in self._context}
278
+ self.calibration.reset()
279
+ return
280
+ if kind == "attachment":
281
+ self.calibration.dirty()
282
+ if kind not in ("assistant", "user"):
283
+ return
284
+ msg = rec.get("message")
285
+ if not isinstance(msg, dict):
286
+ raise BadRecord
287
+ timestamp = date_of(rec.get("timestamp"))
288
+ if kind == "assistant":
289
+ mid = _str(msg.get("id")) or _str(rec.get("uuid"))
290
+ model = normalize_model(_str(msg.get("model")))
291
+ parts, assumed = parse_usage(msg.get("usage"))
292
+ blocks = parse_ai_blocks(msg.get("content"))
293
+ self._note_time(timestamp)
294
+ self._apply_assistant(mid, model, parts, assumed, blocks)
295
+ else:
296
+ blocks = parse_user_blocks(msg.get("content"))
297
+ self._note_time(timestamp)
298
+ self._apply_user(blocks)
299
+
300
+ def _note_time(self, ts):
301
+ if ts is None:
302
+ return
303
+ if self.first is None or ts < self.first:
304
+ self.first = ts
305
+ if self.last is None or ts > self.last:
306
+ self.last = ts
307
+
308
+ def _enter(self, row, text, rtk=False):
309
+ """Text that joins the conversation context and is re-read by every later API call."""
310
+ ascii_chars, other_chars = split_chars(text)
311
+ for key in (row, RTK_KEY) if rtk else (row,):
312
+ self._context[key][0] += ascii_chars
313
+ self._context[key][1] += other_chars
314
+ return ascii_chars, other_chars
315
+
316
+ def _apply_assistant(self, mid, model, parts, assumed, blocks):
317
+ # One API call is written as several lines (one per content block) with the same id and usage.
318
+ if mid not in self._in_file:
319
+ self._in_file.add(mid)
320
+ self.calibration.next_call(sum(parts[k] for k in PROMPT_PARTS))
321
+ if mid not in self._seen_messages:
322
+ self._seen_messages.add(mid)
323
+ self._count_call(model, parts, assumed)
324
+ for block in blocks:
325
+ self._apply_ai_block(block)
326
+
327
+ def _count_call(self, model, parts, assumed):
328
+ self.messages += 1
329
+ self.usage["input_tokens"] += parts["input"]
330
+ self.usage["output_tokens"] += parts["output"]
331
+ self.usage["cache_read_input_tokens"] += parts["cache_read"]
332
+ self.usage["cache_creation_input_tokens"] += parts["cache_write_5m"] + parts["cache_write_1h"]
333
+ self.assumed_5m_tokens += assumed
334
+ self._add_cost(model, parts)
335
+ self.input_side += sum(parts[k] for k in PROMPT_PARTS)
336
+ for key, (ascii_chars, other_chars) in self._context.items():
337
+ self.reads[key][0] += ascii_chars
338
+ self.reads[key][1] += other_chars
339
+
340
+ def _add_cost(self, model, parts):
341
+ if not any(parts.values()):
342
+ return
343
+ cost = self.prices.cost(model, parts)
344
+ if cost is None:
345
+ self.unpriced_messages += 1
346
+ return
347
+ entry = self.models.setdefault(model, {"messages": 0, "cost": dict.fromkeys(COST_PARTS, 0.0)})
348
+ entry["messages"] += 1
349
+ for key in COST_PARTS:
350
+ entry["cost"][key] += cost[key]
351
+
352
+ def _apply_ai_block(self, block):
353
+ if block[0] in ("text", "thinking"):
354
+ self._enter("AI text" if block[0] == "text" else "AI thinking", block[1])
355
+ self.calibration.dirty()
356
+ return
357
+ _, tid, name, text, command = block
358
+ if ("use", tid) in self._in_file:
359
+ return
360
+ self._in_file.add(("use", tid))
361
+ self.calibration.add(*self._enter("AI tool calls", text))
362
+ if tid in self._tool_uses:
363
+ return
364
+ group = name if name in TOOL_GROUPS else "Other"
365
+ family, rtk = None, False
366
+ if name in SHELL_TOOLS:
367
+ words = command_words(command)
368
+ family, rtk = shell_family(words), name == "Bash" and rtk_covered(words, self.rtk_rules)
369
+ self._tool_uses[tid] = (group, family, rtk)
370
+
371
+ def _apply_user(self, blocks):
372
+ for block in blocks:
373
+ if block[0] == "text":
374
+ self._enter("User messages", block[1])
375
+ self.calibration.dirty()
376
+ else:
377
+ self._apply_result(*block[1:])
378
+
379
+ def _apply_result(self, rid, text, plain):
380
+ if ("result", rid) in self._in_file:
381
+ return
382
+ self._in_file.add(("result", rid))
383
+ group, family, rtk = self._tool_uses.get(rid, ("Other", None, False))
384
+ row = f"Shell: {family}" if family else ("Other tools" if group == "Other" else group)
385
+ counts = self._enter(row, text, rtk)
386
+ if plain:
387
+ self.calibration.add(*counts)
388
+ else:
389
+ self.calibration.dirty()
390
+ if rid in self._seen_results:
391
+ return
392
+ self._seen_results.add(rid)
393
+ self.tool_results += 1
394
+ self.tool_chars[group] += len(text)
395
+ if family:
396
+ self.shell_chars[family] += len(text)
397
+
398
+
399
+ def find_logs(path, days, now=None):
400
+ """Log files modified in the last `days` days, and how many entries could not be checked."""
401
+ candidates = [path] if path.is_file() else sorted(path.rglob("*.jsonl"))
402
+ cutoff = (now if now is not None else time.time()) - days * 86400
403
+ files, failed = [], 0
404
+ for f in candidates:
405
+ try:
406
+ modified = f.stat().st_mtime
407
+ except OSError:
408
+ failed += 1
409
+ continue
410
+ if modified >= cutoff:
411
+ files.append(f)
412
+ return files, failed
413
+
414
+
415
+ def scan(files, prices, rtk_rules):
416
+ tally = Tally(prices, rtk_rules)
417
+ for f in files:
418
+ tally.start_conversation()
419
+ try:
420
+ with open(f, "rb") as fh:
421
+ for raw in fh:
422
+ tally.add_line(raw)
423
+ except OSError:
424
+ tally.unreadable_files += 1
425
+ return tally