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/doctor.py ADDED
@@ -0,0 +1,292 @@
1
+ """Why am I hitting my limit? One report: what cost the most, which prompts, and what to change.
2
+
3
+ Read from your own transcripts, nothing estimated from benchmarks:
4
+
5
+ * **Coming back after a break.** Claude Code caches the conversation. Once the cache expires
6
+ (1 hour on Claude plans, 5 minutes on an API key by default), the next call writes the whole
7
+ conversation again, at 1.25x (5 min) or 2x (1 hour) the input price.
8
+ * **The most expensive prompts,** with every model call each one led to (``prompts``).
9
+ * **Re-reading context.** Every call reads the cached conversation again. Cheap per token, large
10
+ in total for long sessions.
11
+ * **Output, and shell output.** What output-style tools (caveman) and shell-output tools (RTK)
12
+ can shrink at most.
13
+
14
+ All of it comes from one pass over the transcripts (``prompts.find``), so the break share in the
15
+ headline and in "Where your usage goes" is the same number. Usage is priced at Anthropic API
16
+ list rates, so every row is comparable. On a Claude plan it is the share of your limit, not a
17
+ bill.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import glob
23
+ import json
24
+ import os
25
+ import re
26
+ import textwrap
27
+ import time
28
+ from dataclasses import dataclass, field
29
+
30
+ from . import savers
31
+ from .cost import breakdown
32
+ from .prices import CACHE_WRITE_1H, CACHE_WRITE_5M, price_for, write_tokens
33
+ from .prompts import Call, Prompt, find, prompt_lines
34
+ from .transcript import Response
35
+
36
+ IDLE_COMPACTION = (2, 1, 299) # Claude Code compacts idle sessions before the cache expires
37
+ LEAD_SHARE = 0.10 # breaks lead the report when they are at least this share of usage
38
+ RTK_CMD = re.compile(
39
+ r"^\s*(git|ls|cat|head|tail|grep|rg|find|tree|wc|pytest|python3? -m pytest|npm|npx|pnpm|yarn|"
40
+ r"bun|cargo|go (test|build)|tsc|eslint|jest|vitest|make|docker|kubectl|curl)\b"
41
+ )
42
+
43
+
44
+ @dataclass
45
+ class Diagnosis:
46
+ days: int
47
+ sessions: int
48
+ cost: dict # cost.breakdown() over all model calls
49
+ rebuy_usd: float # cache writes of the calls that came back to an expired cache
50
+ rebuys: int
51
+ worst_rebuy_usd: float
52
+ saved_usd: float # estimated saving had you run /compact before each of those breaks
53
+ cache_writes_5m: int
54
+ cache_writes_1h: int
55
+ tool_chars: int
56
+ rtk_chars: int
57
+ version: tuple[int, ...] | None
58
+ active_savers: list[str]
59
+ top: list[Prompt] = field(default_factory=list)
60
+ prompts: list[Prompt] = field(default_factory=list)
61
+
62
+
63
+ def _write_usd(call: Call) -> float:
64
+ w5m, w1h = write_tokens(call.usage)
65
+ return (w5m * CACHE_WRITE_5M + w1h * CACHE_WRITE_1H) * price_for(call.model)[0]["input"] / 1e6
66
+
67
+
68
+ def _scan_tools(path: str, seen: set[str]) -> tuple[int, int, tuple[int, ...] | None]:
69
+ """Tool output chars, the part from RTK-compactable shell commands, newest Claude Code version.
70
+
71
+ ``seen`` holds tool_use ids already counted in another file (forked sessions copy them).
72
+ """
73
+ bash: dict[str, str] = {}
74
+ total = rtk = 0
75
+ version = None
76
+ with open(path, encoding="utf-8", errors="ignore") as f:
77
+ for raw in f:
78
+ try:
79
+ o = json.loads(raw)
80
+ except ValueError:
81
+ continue
82
+ m = re.match(r"(\d+)\.(\d+)\.(\d+)", o.get("version") or "")
83
+ if m:
84
+ version = max(version or (0,), tuple(int(x) for x in m.groups()))
85
+ content = (o.get("message") or {}).get("content")
86
+ for b in content if isinstance(content, list) else []:
87
+ if not isinstance(b, dict):
88
+ continue
89
+ if b.get("type") == "tool_use" and b.get("name") == "Bash":
90
+ bash[b.get("id", "")] = str((b.get("input") or {}).get("command", ""))
91
+ elif b.get("type") == "tool_result":
92
+ tid = b.get("tool_use_id", "")
93
+ if tid in seen:
94
+ continue
95
+ seen.add(tid)
96
+ c = b.get("content")
97
+ n = (
98
+ len(c)
99
+ if isinstance(c, str)
100
+ else sum(len(x.get("text", "")) for x in c or [] if isinstance(x, dict))
101
+ )
102
+ total += n
103
+ if RTK_CMD.match(bash.get(b.get("tool_use_id", ""), "")):
104
+ rtk += n
105
+ return total, rtk, version
106
+
107
+
108
+ def diagnose(projects_dir: str, days: int = 7, cwd: str | None = None, top: int = 3) -> Diagnosis:
109
+ worst, prompts = find(projects_dir, days, top)
110
+ calls = [c for p in prompts for c in p.calls]
111
+ expired = [c for c in calls if c.expired]
112
+ w5 = w1 = 0
113
+ for c in calls:
114
+ a, b = write_tokens(c.usage)
115
+ w5 += a
116
+ w1 += b
117
+ cutoff = time.time() - days * 86400
118
+ tool_chars = rtk_chars = 0
119
+ version = None
120
+ seen: set[str] = set()
121
+ for path in sorted(glob.glob(os.path.join(projects_dir, "*", "*.jsonl")), key=os.path.getmtime):
122
+ if os.path.getmtime(path) < cutoff:
123
+ continue
124
+ n, k, v = _scan_tools(path, seen)
125
+ tool_chars += n
126
+ rtk_chars += k
127
+ if v and (version is None or v > version):
128
+ version = v
129
+ responses = [Response(c.model, c.usage, c.usage.get("speed"), c.sub) for c in calls]
130
+ return Diagnosis(
131
+ days=days,
132
+ sessions=len({p.session for p in prompts}),
133
+ cost=breakdown(responses),
134
+ rebuy_usd=sum(_write_usd(c) for c in expired),
135
+ rebuys=len(expired),
136
+ worst_rebuy_usd=max((_write_usd(c) for c in expired), default=0.0),
137
+ saved_usd=sum(c.cost - c.before for c in expired),
138
+ cache_writes_5m=w5,
139
+ cache_writes_1h=w1,
140
+ tool_chars=tool_chars,
141
+ rtk_chars=rtk_chars,
142
+ version=version,
143
+ active_savers=savers.detect(cwd),
144
+ top=worst,
145
+ prompts=prompts,
146
+ )
147
+
148
+
149
+ def render(
150
+ d: Diagnosis,
151
+ redact: bool = False,
152
+ color: bool = False,
153
+ ascii_only: bool = False,
154
+ in_plugin: bool = True,
155
+ ) -> str:
156
+ c = d.cost
157
+ total = c["cost_usd"]
158
+ if total <= 0:
159
+ return f"No Claude Code usage found in the last {d.days} days."
160
+
161
+ def paint(code: str, s: str) -> str:
162
+ return f"\033[{code}m{s}\033[0m" if color else s
163
+
164
+ def pct(x: float) -> str:
165
+ return f"{100 * x / total:.0f}%"
166
+
167
+ old_version = bool(d.version and d.version < IDLE_COMPACTION)
168
+ break_fix = (
169
+ "Update Claude Code: v2.1.299+ compacts idle sessions before the cache expires."
170
+ if old_version
171
+ else f"/compact before you step away would have saved ~{pct(d.saved_usd)}."
172
+ )
173
+ out = [
174
+ "",
175
+ paint("1", " Why am I hitting my limit?")
176
+ + paint(
177
+ "2",
178
+ f" (last {d.days} days, {d.sessions} sessions, {len(d.prompts):,} prompts, "
179
+ f"${total:,.0f} at API list prices)",
180
+ ),
181
+ "",
182
+ ]
183
+ lead = d.rebuy_usd / total >= LEAD_SHARE
184
+ if lead:
185
+ out += [
186
+ " "
187
+ + paint("1;31", pct(d.rebuy_usd))
188
+ + paint("1", " of your Claude usage went to coming back after a break."),
189
+ f" {d.rebuys} times the cache had expired, so Claude re-paid for the whole"
190
+ " conversation.",
191
+ " " + paint("1;32", break_fix),
192
+ "",
193
+ ]
194
+ if d.top:
195
+ share = sum(p.cost for p in d.top) / total
196
+ out += [
197
+ paint(
198
+ "1",
199
+ " Your most expensive prompt"
200
+ if len(d.top) == 1
201
+ else f" Your {len(d.top)} most expensive prompts",
202
+ )
203
+ + paint("2", f" ({pct(share * total)} of usage)"),
204
+ "",
205
+ ]
206
+ out += prompt_lines(d.top, redact, color, ascii_only)
207
+
208
+ growth = max(0.0, c["cost_cache_write"] - d.rebuy_usd)
209
+ rows = [
210
+ ("Coming back after breaks (cache re-written)", d.rebuy_usd),
211
+ ("Re-reading context every call", c["cost_cache_read"]),
212
+ ("Caching new context", growth),
213
+ ("Claude's output", c["cost_output"]),
214
+ ("Uncached input", c["cost_input"]),
215
+ ]
216
+ out.append(paint("1", " Where your usage goes"))
217
+ out += [f" {pct(v):>4} {name}" for name, v in sorted(rows, key=lambda x: -x[1])]
218
+ sub = c["subagent_responses"]
219
+ if sub:
220
+ out.append(
221
+ paint("2", f" ({sub:,} of {c['responses']:,} model calls were subagents)")
222
+ )
223
+
224
+ fixes = []
225
+ if not lead and d.rebuy_usd / total >= 0.05: # when breaks lead, the headline says this
226
+ fixes.append(
227
+ f"Breaks cost you {pct(d.rebuy_usd)}: {d.rebuys} times you came back to an expired "
228
+ f"cache (worst: ${d.worst_rebuy_usd:.2f} for one call). {break_fix}"
229
+ )
230
+ if c["cost_cache_read"] / total >= 0.3:
231
+ fixes.append(
232
+ f"Re-reading is {pct(c['cost_cache_read'])}: every call reads the whole conversation "
233
+ "again, so long sessions cost more per message. Use /clear when you switch to an "
234
+ "unrelated task."
235
+ )
236
+ if d.cache_writes_5m > d.cache_writes_1h:
237
+ fixes.append(
238
+ "Your cache expires after 5 minutes (API-key default), so short pauses re-buy "
239
+ 'context too. Set "promptCacheTtl": "1h" in ~/.claude/settings.json.'
240
+ )
241
+ out_share = c["cost_output"] / total
242
+ caveman = "caveman" in d.active_savers
243
+ fixes.append(
244
+ f"Output is {100 * out_share:.0f}% of your usage, so a terse-output tool like caveman can "
245
+ f"save at most that{' (and about 8.5% of it in practice)' if out_share else ''}. "
246
+ + (
247
+ "Keep it for readability, not for your limit."
248
+ if caveman and out_share < 0.2
249
+ else "Not worth installing for your limit."
250
+ if out_share < 0.2
251
+ else "Worth a test."
252
+ )
253
+ )
254
+ if d.tool_chars:
255
+ share = d.rtk_chars / d.tool_chars
256
+ rtk = "rtk" in d.active_savers
257
+ fixes.append(
258
+ f"{100 * share:.0f}% of the tool output Claude read came from shell commands RTK can "
259
+ "compact (Read and Grep bypass it). "
260
+ + (
261
+ "Small: RTK can't move your limit much."
262
+ if share < 0.2
263
+ else "Large enough that RTK may help: test it."
264
+ if not rtk
265
+ else "RTK fits your work."
266
+ )
267
+ )
268
+ out += ["", paint("1", " What to change")]
269
+ for i, f in enumerate(fixes, 1):
270
+ out += textwrap.wrap(f, 98, initial_indent=f" {i}. ", subsequent_indent=" ")
271
+ warn = (
272
+ [" Warn me before the next one: /tokenops:saver on"]
273
+ if in_plugin
274
+ else [
275
+ " Warn me before the next one, in Claude Code:",
276
+ " /plugin marketplace add theagentplane/tokenops, then /tokenops:saver on",
277
+ ]
278
+ )
279
+ out += [
280
+ "",
281
+ paint(
282
+ "2",
283
+ " Dollars are API list prices; on a Claude plan they are usage against your limit.",
284
+ ),
285
+ paint(
286
+ "2",
287
+ " 5-hour windows are estimated from your first prompt in each, not read from Anthropic.",
288
+ ),
289
+ *(paint("2", w) for w in warn),
290
+ "",
291
+ ]
292
+ return "\n".join(out)
tokenops_cc/guard.py ADDED
@@ -0,0 +1,91 @@
1
+ """Resume guard: hold the first message to a session whose prompt cache has expired.
2
+
3
+ After a break longer than the cache lifetime (1 hour on Claude plans, 5 minutes on an API key by
4
+ default), the next message writes the whole conversation to the cache again, at 2x (1 hour) or
5
+ 1.25x (5 minutes) the input price. The guard holds that message once, says what it will cost and
6
+ offers cheaper ways on. Sending it again goes through, so it never traps anyone.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import datetime as dt
12
+ import json
13
+ import os
14
+ import time
15
+
16
+ from . import settings
17
+ from .prices import CACHE_WRITE_1H, CACHE_WRITE_5M, price_for
18
+
19
+ TAIL_BYTES = 4_000_000
20
+ MIN_CONTEXT_TOKENS = int(os.environ.get("TOKENOPS_GUARD_MIN_TOKENS", "50000"))
21
+
22
+
23
+ def last_response(transcript_path: str) -> dict | None:
24
+ """The newest main-thread response: timestamp, model, context size, cache lifetime."""
25
+ try:
26
+ with open(transcript_path, "rb") as f:
27
+ f.seek(max(0, os.path.getsize(transcript_path) - TAIL_BYTES))
28
+ lines = f.read().splitlines()
29
+ except OSError:
30
+ return None
31
+ for raw in reversed(lines):
32
+ try:
33
+ o = json.loads(raw)
34
+ except ValueError:
35
+ continue
36
+ msg = o.get("message") or {}
37
+ usage = msg.get("usage")
38
+ if o.get("type") != "assistant" or o.get("isSidechain") or not usage:
39
+ continue
40
+ if msg.get("model") == "<synthetic>":
41
+ continue
42
+ cc = usage.get("cache_creation") or {}
43
+ context = sum(
44
+ usage.get(k) or 0
45
+ for k in ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")
46
+ )
47
+ try:
48
+ ts = dt.datetime.fromisoformat(o["timestamp"].replace("Z", "+00:00")).timestamp()
49
+ except (KeyError, ValueError):
50
+ return None
51
+ # The cache this session writes to: 5 minutes only when the last write was a 5m write.
52
+ five_min = (cc.get("ephemeral_5m_input_tokens") or 0) > 0 and not cc.get(
53
+ "ephemeral_1h_input_tokens"
54
+ )
55
+ ttl = 300 if five_min else 3600
56
+ return {"ts": ts, "model": msg.get("model", ""), "context": context, "ttl": ttl}
57
+ return None
58
+
59
+
60
+ def check(payload: dict, now: float | None = None) -> dict | None:
61
+ """UserPromptSubmit handler. Returns a block decision, or None to let the prompt through."""
62
+ if not settings.load_config().get("saver"):
63
+ return None
64
+ last = last_response(payload.get("transcript_path") or "")
65
+ now = time.time() if now is None else now
66
+ if not last or last["context"] < MIN_CONTEXT_TOKENS or now - last["ts"] <= last["ttl"]:
67
+ return None
68
+ sid = payload.get("session_id") or "unknown"
69
+ state = settings.load_session(sid)
70
+ if state.get("guard_warned_for") == last["ts"]:
71
+ return None # second send: the user chose to go on
72
+ state["guard_warned_for"] = last["ts"]
73
+ settings.save_session(sid, state)
74
+
75
+ p, _ = price_for(last["model"])
76
+ write = CACHE_WRITE_1H if last["ttl"] == 3600 else CACHE_WRITE_5M
77
+ cold = last["context"] * p["input"] * write / 1e6
78
+ warm = last["context"] * p["cache_read"] / 1e6
79
+ hours = (now - last["ts"]) / 3600
80
+ away = f"{hours:.1f} h" if hours >= 1 else f"{(now - last['ts']) / 60:.0f} min"
81
+ return {
82
+ "decision": "block",
83
+ "reason": (
84
+ f"TokenOps: this session's cache expired ({away} since the last reply). Sending now "
85
+ f"re-reads {last['context'] / 1000:,.0f}k tokens at the cache-write price: about "
86
+ f"${cold:.2f} API-equivalent, against ${warm:.2f} while the cache was warm.\n"
87
+ " - Send the same message again to continue anyway.\n"
88
+ " - Or run /compact first: it keeps the gist in far fewer tokens.\n"
89
+ " - Or /clear and paste a 3-line summary of where you were (cheapest)."
90
+ ),
91
+ }
@@ -0,0 +1,97 @@
1
+ {
2
+ "_generated": "by scripts/sync-claude-prices.py from tokenops.framework.pricing; USD per 1M tokens",
3
+ "cache_write_5m": 1.25,
4
+ "cache_write_1h": 2.0,
5
+ "models": {
6
+ "claude-fable-5": {
7
+ "input": 10.0,
8
+ "output": 50.0,
9
+ "cache_read": 1.0
10
+ },
11
+ "claude-fable-5-1": {
12
+ "input": 10.0,
13
+ "output": 50.0,
14
+ "cache_read": 0.25
15
+ },
16
+ "claude-fable-5-2": {
17
+ "input": 8.0,
18
+ "output": 40.0,
19
+ "cache_read": 0.2
20
+ },
21
+ "claude-haiku-4-5": {
22
+ "input": 1.0,
23
+ "output": 5.0,
24
+ "cache_read": 0.1
25
+ },
26
+ "claude-haiku-5-5": {
27
+ "input": 0.1,
28
+ "output": 0.5,
29
+ "cache_read": 0.01
30
+ },
31
+ "claude-mythos-5": {
32
+ "input": 10.0,
33
+ "output": 50.0,
34
+ "cache_read": 1.0
35
+ },
36
+ "claude-mythos-5-1": {
37
+ "input": 10.0,
38
+ "output": 50.0,
39
+ "cache_read": 0.25
40
+ },
41
+ "claude-mythos-5-2": {
42
+ "input": 8.0,
43
+ "output": 40.0,
44
+ "cache_read": 0.2
45
+ },
46
+ "claude-opus-4-5": {
47
+ "input": 5.0,
48
+ "output": 25.0,
49
+ "cache_read": 0.5
50
+ },
51
+ "claude-opus-4-6": {
52
+ "input": 5.0,
53
+ "output": 25.0,
54
+ "cache_read": 0.5
55
+ },
56
+ "claude-opus-4-7": {
57
+ "input": 5.0,
58
+ "output": 25.0,
59
+ "cache_read": 0.5
60
+ },
61
+ "claude-opus-4-8": {
62
+ "input": 5.0,
63
+ "output": 25.0,
64
+ "cache_read": 0.5
65
+ },
66
+ "claude-opus-5": {
67
+ "input": 5.0,
68
+ "output": 25.0,
69
+ "cache_read": 0.5
70
+ },
71
+ "claude-opus-5-5": {
72
+ "input": 4.0,
73
+ "output": 20.0,
74
+ "cache_read": 0.2
75
+ },
76
+ "claude-sonnet-4-5": {
77
+ "input": 3.0,
78
+ "output": 15.0,
79
+ "cache_read": 0.3
80
+ },
81
+ "claude-sonnet-4-6": {
82
+ "input": 3.0,
83
+ "output": 15.0,
84
+ "cache_read": 0.3
85
+ },
86
+ "claude-sonnet-5": {
87
+ "input": 2.0,
88
+ "output": 10.0,
89
+ "cache_read": 0.2
90
+ },
91
+ "claude-sonnet-5-5": {
92
+ "input": 2.0,
93
+ "output": 10.0,
94
+ "cache_read": 0.1
95
+ }
96
+ }
97
+ }
tokenops_cc/prices.py ADDED
@@ -0,0 +1,51 @@
1
+ """Claude prices (USD per million tokens) and the cost of one response's usage.
2
+
3
+ Rates come from ``prices.json``, generated from ``tokenops.framework.pricing`` by
4
+ ``scripts/sync-claude-prices.py`` (one price source, ADR 0009). Cache writes are priced as a
5
+ multiple of the input rate; fast mode bills 2x. Unknown models are priced at Opus 5.5 rates and
6
+ flagged, so a report never silently shows $0.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+
14
+ _DATA = json.loads((Path(__file__).with_name("prices.json")).read_text(encoding="utf-8"))
15
+ PRICES: dict[str, dict[str, float]] = _DATA["models"]
16
+ CACHE_WRITE_5M: float = _DATA["cache_write_5m"]
17
+ CACHE_WRITE_1H: float = _DATA["cache_write_1h"]
18
+ FAST_MULTIPLIER = 2.0
19
+ DEFAULT_MODEL = "claude-opus-5-5"
20
+
21
+
22
+ def price_for(model: str) -> tuple[dict[str, float], bool]:
23
+ """(price row, known). Accepts date-suffixed ids such as ``claude-haiku-4-5-20251001``."""
24
+ m = (model or "").strip()
25
+ for key in sorted(PRICES, key=len, reverse=True):
26
+ if m == key or m.startswith(key + "-"):
27
+ return PRICES[key], True
28
+ return PRICES[DEFAULT_MODEL], False
29
+
30
+
31
+ def write_tokens(usage: dict) -> tuple[int, int]:
32
+ """(5-minute, 1-hour) cache-write tokens; untyped writes count as 5-minute."""
33
+ cc = usage.get("cache_creation") or {}
34
+ w1h = cc.get("ephemeral_1h_input_tokens") or 0
35
+ w5m = cc.get("ephemeral_5m_input_tokens")
36
+ if w5m is None:
37
+ w5m = max(0, (usage.get("cache_creation_input_tokens") or 0) - w1h)
38
+ return w5m, w1h
39
+
40
+
41
+ def usage_cost(model: str, usage: dict, speed: str | None = None) -> tuple[float, bool]:
42
+ """Cost in USD of one response's usage block, and whether the model's price was known."""
43
+ p, known = price_for(model)
44
+ w5m, w1h = write_tokens(usage)
45
+ cost = (
46
+ (usage.get("input_tokens") or 0) * p["input"]
47
+ + (usage.get("output_tokens") or 0) * p["output"]
48
+ + (usage.get("cache_read_input_tokens") or 0) * p["cache_read"]
49
+ + (w5m * CACHE_WRITE_5M + w1h * CACHE_WRITE_1H) * p["input"]
50
+ ) / 1e6
51
+ return cost * (FAST_MULTIPLIER if speed == "fast" else 1.0), known