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-0.2.0.dist-info/METADATA +165 -0
- tokenops-0.2.0.dist-info/RECORD +19 -0
- tokenops-0.2.0.dist-info/WHEEL +5 -0
- tokenops-0.2.0.dist-info/entry_points.txt +2 -0
- tokenops-0.2.0.dist-info/top_level.txt +2 -0
- tokenops_cc/__init__.py +1 -0
- tokenops_cc/ab.py +147 -0
- tokenops_cc/caveman.py +66 -0
- tokenops_cc/cost.py +45 -0
- tokenops_cc/doctor.py +292 -0
- tokenops_cc/guard.py +91 -0
- tokenops_cc/prices.json +97 -0
- tokenops_cc/prices.py +51 -0
- tokenops_cc/prompts.py +362 -0
- tokenops_cc/rtk.py +96 -0
- tokenops_cc/savers.py +53 -0
- tokenops_cc/settings.py +59 -0
- tokenops_cc/transcript.py +99 -0
- tokenops_cli.py +71 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tokenops
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Which prompts ate your Claude Code limit, and why? Read from your own session logs.
|
|
5
|
+
Author: Susheem Koul, Tisha Chawla
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/theagentplane/tokenops/tree/main/integrations/claude-code
|
|
8
|
+
Project-URL: Repository, https://github.com/theagentplane/tokenops
|
|
9
|
+
Keywords: claude,claude-code,tokens,usage,rate-limit,prompt-cache
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# TokenOps for Claude Code
|
|
17
|
+
|
|
18
|
+
**Why am I hitting my limit?** One command names the prompts that cost you the most, says why,
|
|
19
|
+
and what to change. Read from your own session logs, on your machine.
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
/tokenops:doctor
|
|
23
|
+
|
|
24
|
+
Why am I hitting my limit? (last 7 days, 12 sessions, 304 prompts, $235 at API list prices)
|
|
25
|
+
|
|
26
|
+
37% of your Claude usage went to coming back after a break.
|
|
27
|
+
39 times the cache had expired, so Claude re-paid for the whole conversation.
|
|
28
|
+
/compact before you step away would have saved ~31%.
|
|
29
|
+
|
|
30
|
+
Your 3 most expensive prompts (9% of usage)
|
|
31
|
+
|
|
32
|
+
#2 Wed 21:56 project B (prompt hidden)
|
|
33
|
+
█████████░░░░░░░░░░░ 44% of that 5-hour window | 24x your typical prompt
|
|
34
|
+
CACHE EXPIRED away 4h 45m, past the 1h cache: one call re-wrote your
|
|
35
|
+
whole 965k-token conversation to the cache at 2x the input price
|
|
36
|
+
1 model call, paid $7.41 -> /compact before leaving ~$0.52 (14x less) | /clear + note ~$0.27
|
|
37
|
+
...
|
|
38
|
+
Where your usage goes
|
|
39
|
+
41% Re-reading context every call
|
|
40
|
+
37% Coming back after breaks (cache re-written)
|
|
41
|
+
12% Claude's output
|
|
42
|
+
11% Caching new context
|
|
43
|
+
|
|
44
|
+
What to change
|
|
45
|
+
1. Re-reading is 41%: every call reads the whole conversation again ... Use /clear when you
|
|
46
|
+
switch to an unrelated task.
|
|
47
|
+
2. Output is 12% of your usage, so a terse-output tool like caveman can save at most that ...
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
In Claude Code:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
/plugin marketplace add theagentplane/tokenops
|
|
56
|
+
/plugin install tokenops@tokenops
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Then run `/tokenops:doctor` (last 7 days; `/tokenops:doctor 30` for 30). Needs Python 3.9+ on
|
|
60
|
+
your PATH; nothing to `pip install`.
|
|
61
|
+
|
|
62
|
+
Or, without installing anything, from any terminal with [uv](https://docs.astral.sh/uv/):
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
uvx tokenops doctor
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
(The `tokenops` package on PyPI is this CLI; the agent governance library is `agent-tokenops`.)
|
|
69
|
+
|
|
70
|
+
## Reading the report
|
|
71
|
+
|
|
72
|
+
- **Prompts.** One prompt you type can make many model calls (tool use, subagents). They are all
|
|
73
|
+
counted under the prompt that started them. The doctor shows the 3 most expensive prompts,
|
|
74
|
+
with the project they were typed in.
|
|
75
|
+
- **Tokens** are the size of the whole conversation that one call sent, not a sum over calls.
|
|
76
|
+
Models with a 1M-token context can carry a conversation that long.
|
|
77
|
+
- **CACHE EXPIRED** means the call came more than the cache lifetime (1 hour on a Claude plan,
|
|
78
|
+
5 minutes with an API key) after the previous one, and wrote most of the conversation to the
|
|
79
|
+
cache again at the cache-write price. The headline and the "Coming back after breaks" row are
|
|
80
|
+
the same number: the cache writes of those calls.
|
|
81
|
+
- **5-hour windows** are estimated from your first prompt in each, not read from Anthropic's
|
|
82
|
+
meter. The cheaper costs are estimates: only the calls a break made expensive are re-priced.
|
|
83
|
+
- **Sharing a screenshot?** From a terminal, `uvx tokenops doctor --redact` hides your prompts and
|
|
84
|
+
project names ("project A", "project B").
|
|
85
|
+
|
|
86
|
+
## Saver mode
|
|
87
|
+
|
|
88
|
+
`/tokenops:saver on` lets TokenOps act on what the doctor finds. Off by default; every hook
|
|
89
|
+
fails open.
|
|
90
|
+
|
|
91
|
+
- **Resume guard.** After a break longer than the cache lifetime, your next message re-reads the
|
|
92
|
+
whole conversation at the cache-write price. The guard holds that message once:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
TokenOps: this session's cache expired (1.5 h since the last reply). Sending now re-reads
|
|
96
|
+
433k tokens at the cache-write price: about $3.47 API-equivalent, against $0.09 while the
|
|
97
|
+
cache was warm.
|
|
98
|
+
- Send the same message again to continue anyway.
|
|
99
|
+
- Or run /compact first: it keeps the gist in far fewer tokens.
|
|
100
|
+
- Or /clear and paste a 3-line summary of where you were (cheapest).
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
It only acts when the context is at least 50k tokens (`TOKENOPS_GUARD_MIN_TOKENS`).
|
|
104
|
+
|
|
105
|
+
- **Smart RTK.** With [RTK](https://github.com/rtk-ai/rtk) installed, shell commands Claude runs
|
|
106
|
+
are rewritten to their compact RTK form (`git status` -> `rtk git status`), using RTK's own
|
|
107
|
+
`rtk rewrite`. File reads (`cat`, `head`, `sed -n`), `git diff`/`git show`, and the next test run
|
|
108
|
+
after a failing one stay verbatim, because Claude needs that output exactly. If RTK's own hook
|
|
109
|
+
is installed, smart RTK stays off so nothing is rewritten twice: remove RTK's hook from your
|
|
110
|
+
Claude Code settings to let TokenOps decide.
|
|
111
|
+
|
|
112
|
+
- **Measured, not guessed.** Smart RTK and [caveman](https://github.com/JuliusBrussee/caveman) are
|
|
113
|
+
each switched on in a random half of your sessions. After 10 sessions on and 10 off, the doctor
|
|
114
|
+
shows what each one did to your usage per prompt, and the saver mode keeps it only if it saves:
|
|
115
|
+
|
|
116
|
+
```
|
|
117
|
+
Measured on your sessions (saver mode A/B, usage per prompt)
|
|
118
|
+
Smart RTK -6% usage per prompt (95% range -9% to -2%) -> kept on
|
|
119
|
+
caveman +1% usage per prompt (95% range -3% to +5%) -> turned off
|
|
120
|
+
Usage only: hooks cannot see whether the work went as well.
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
For caveman, set its own default to off (`"defaultMode": "off"` in caveman's config file, or
|
|
124
|
+
`CAVEMAN_DEFAULT_MODE=off`) so TokenOps decides per session.
|
|
125
|
+
|
|
126
|
+
`/tokenops:saver status` shows what is on; `/tokenops:saver off` turns it all off.
|
|
127
|
+
|
|
128
|
+
## How it reads your usage
|
|
129
|
+
|
|
130
|
+
Claude Code writes every model response to `~/.claude/projects/*/*.jsonl`, often on several
|
|
131
|
+
lines with the same message id. The doctor keeps the last line per response, includes subagent
|
|
132
|
+
transcripts, counts a response once even when a forked session copies it, and prices each response at Anthropic's list rates: input, output, cache reads,
|
|
133
|
+
and cache writes (1.25x input for the 5-minute cache, 2x for the 1-hour cache). Prices come from
|
|
134
|
+
TokenOps' price book (`src/tokenops/framework/pricing.py`).
|
|
135
|
+
|
|
136
|
+
- **Coming back after breaks:** a cache write of 20,000+ tokens, at least half the conversation,
|
|
137
|
+
more than the cache lifetime after the previous call. The cache had expired, so the whole
|
|
138
|
+
conversation was written again.
|
|
139
|
+
- **Re-reading context:** cache reads. Every call reads the conversation again.
|
|
140
|
+
- **Caveman and RTK advice** is a ceiling from your own usage mix (what share is output, what
|
|
141
|
+
share of tool output came from shell commands RTK compacts), not a measured A/B.
|
|
142
|
+
|
|
143
|
+
On a Claude plan the dollar figures are API-equivalent: they show your share of usage, not a
|
|
144
|
+
bill. Nothing leaves your machine.
|
|
145
|
+
|
|
146
|
+
## What it runs, reads and stores
|
|
147
|
+
|
|
148
|
+
- **Runs:** `python3` (or `python`) with the scripts in this folder, standard library only. With
|
|
149
|
+
Saver mode on and [RTK](https://github.com/rtk-ai/rtk) installed, it also runs `rtk rewrite
|
|
150
|
+
<command>` to ask RTK how it would compact a shell command. Nothing else.
|
|
151
|
+
- **Reads:** your Claude Code session logs (`~/.claude/projects/*/*.jsonl`), your Claude Code
|
|
152
|
+
settings files (to see which token savers are installed), caveman's installed skill file and
|
|
153
|
+
config (only when caveman is installed), and this plugin's own `prices.json`.
|
|
154
|
+
- **Stores:** a small settings file and one small JSON file per session in Claude Code's plugin
|
|
155
|
+
data folder (`$CLAUDE_PLUGIN_DATA`): whether Saver mode is on, the A/B choices and results.
|
|
156
|
+
- **Sends:** nothing. It makes no network requests and keeps no copy of your prompts or code.
|
|
157
|
+
- **Changes:** with Saver mode on, it can hold one message after a break (you send it again to
|
|
158
|
+
go on) and rewrite a shell command to its RTK form. With Saver mode off, it only reads.
|
|
159
|
+
|
|
160
|
+
## Development
|
|
161
|
+
|
|
162
|
+
```
|
|
163
|
+
python scripts/sync-claude-prices.py # after changing DEFAULT_RATES
|
|
164
|
+
python -m pytest tests/claude_code
|
|
165
|
+
```
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
tokenops_cli.py,sha256=YJwLevoRgrRLdalWSt8jLB1HXlJ0PKjMdGGAdxVQQE0,3013
|
|
2
|
+
tokenops_cc/__init__.py,sha256=NZc03CbXarb-bK94yg197pSGt-Cl3VQXyEv73CDeG4s,79
|
|
3
|
+
tokenops_cc/ab.py,sha256=3UMC2yBdxRrEei0Mk3vKMNEhdE_89v6MKoxCpQKRrMs,5655
|
|
4
|
+
tokenops_cc/caveman.py,sha256=QDIaiLMd8z50z_d0MJxC8-kcgNC0jabU0Z92fu2Ad6o,2362
|
|
5
|
+
tokenops_cc/cost.py,sha256=ZqH34Itmb04pz9tCEc78RL3neg20V0H4J4awXPy38hI,1724
|
|
6
|
+
tokenops_cc/doctor.py,sha256=Gh3zhpkmB4PENxF53ZlYvvjzAha3S79Yv3zxSTlWzz0,11415
|
|
7
|
+
tokenops_cc/guard.py,sha256=NiF6o6D61UBj4QxeKPkM4Botc99XGw4nWlPnkKbAVMQ,3971
|
|
8
|
+
tokenops_cc/prices.json,sha256=PtxiaS9CmOA2Qc13Gvz0WMsG47RpXY-e_x-dPs3BmDQ,1813
|
|
9
|
+
tokenops_cc/prices.py,sha256=Tuu47psoXkVU21PWCHW4LtI7ac9EYigpsK3IkW95i1c,2182
|
|
10
|
+
tokenops_cc/prompts.py,sha256=JqQ5v81ndFsh4h_48WLzosrcvA1L7BVZSLtXqFI9I8w,15375
|
|
11
|
+
tokenops_cc/rtk.py,sha256=YDxmFPS5h3O6pZgllOhmJphNumTvR_aKcCOuu6fwcvU,3913
|
|
12
|
+
tokenops_cc/savers.py,sha256=9SulZolQ1pE2keA8RbS3rgBIjL5jZ8gBID4WbPX3Jq8,1719
|
|
13
|
+
tokenops_cc/settings.py,sha256=v7p9hugGzCl-vj-Ds_qvYoN_w-Iu4DFNIHCcdBLV3MI,1640
|
|
14
|
+
tokenops_cc/transcript.py,sha256=WKbyzUI-wkzRPPoIj-ZkzbGF1YizP97-BemLq_iI6y0,3364
|
|
15
|
+
tokenops-0.2.0.dist-info/METADATA,sha256=-sId3_bNx8qWdTtCfAvhr5mNS5rzQZWV8jI5c0iGnBI,8223
|
|
16
|
+
tokenops-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
tokenops-0.2.0.dist-info/entry_points.txt,sha256=g-R6KmZkkl-9_BI-oZLcwNm3SoiOGkCf_JR3FIMrrXk,47
|
|
18
|
+
tokenops-0.2.0.dist-info/top_level.txt,sha256=ARYLnmXKWtFqBUB0vCLw4SWXAGhD3eu0QxFOp3EUP6Q,25
|
|
19
|
+
tokenops-0.2.0.dist-info/RECORD,,
|
tokenops_cc/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""TokenOps for Claude Code: hooks, cost ledger and reports (stdlib only)."""
|
tokenops_cc/ab.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Saver A/B: turn each saver on in a random half of sessions and keep it only if it saves.
|
|
2
|
+
|
|
3
|
+
At session start, every saver that can be tested (caveman, smart RTK) is switched on or off at
|
|
4
|
+
random and the choice is stored with the session. Comparing usage per prompt between the two
|
|
5
|
+
halves, after at least ``MIN_SESSIONS`` sessions in each, gives the saver's measured effect on
|
|
6
|
+
this user's own work. A saver is kept on when the whole 95% range is a saving, turned off when
|
|
7
|
+
it cannot save 5% or more, and tested further otherwise. Hooks cannot see task quality, so this
|
|
8
|
+
measures usage only.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import random
|
|
16
|
+
|
|
17
|
+
from . import caveman, rtk, settings
|
|
18
|
+
from .cost import breakdown
|
|
19
|
+
from .transcript import TranscriptState, update
|
|
20
|
+
|
|
21
|
+
MIN_SESSIONS = 10
|
|
22
|
+
SAVERS = ("caveman", "rtk")
|
|
23
|
+
NAMES = {"caveman": "caveman", "rtk": "Smart RTK"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def testable() -> dict[str, bool]:
|
|
27
|
+
return {"caveman": caveman.status() == "testable", "rtk": rtk.status().startswith("on")}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def session_start(payload: dict) -> dict | None:
|
|
31
|
+
"""Pick this session's arms (kept on resume and compaction); load caveman when it is on."""
|
|
32
|
+
config = settings.load_config()
|
|
33
|
+
if not config.get("saver"):
|
|
34
|
+
return None
|
|
35
|
+
sid = payload.get("session_id") or "unknown"
|
|
36
|
+
state = settings.load_session(sid)
|
|
37
|
+
if "arms" not in state:
|
|
38
|
+
decided = config.get("decisions", {})
|
|
39
|
+
state["arms"] = {
|
|
40
|
+
saver: decided[saver] == "on" if saver in decided else random.random() < 0.5
|
|
41
|
+
for saver, ok in testable().items()
|
|
42
|
+
if ok
|
|
43
|
+
}
|
|
44
|
+
state["transcript_path"] = payload.get("transcript_path") or ""
|
|
45
|
+
settings.save_session(sid, state)
|
|
46
|
+
if not state["arms"].get("caveman"):
|
|
47
|
+
return None
|
|
48
|
+
return {
|
|
49
|
+
"hookSpecificOutput": {
|
|
50
|
+
"hookEventName": "SessionStart",
|
|
51
|
+
"additionalContext": caveman.rules()[:9500],
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _prompts(path: str) -> int:
|
|
57
|
+
"""Messages the user typed (not tool results, slash-command output or reminders)."""
|
|
58
|
+
n = 0
|
|
59
|
+
with open(path, encoding="utf-8", errors="ignore") as f:
|
|
60
|
+
for raw in f:
|
|
61
|
+
if '"user"' not in raw:
|
|
62
|
+
continue
|
|
63
|
+
try:
|
|
64
|
+
o = json.loads(raw)
|
|
65
|
+
except ValueError:
|
|
66
|
+
continue
|
|
67
|
+
content = (o.get("message") or {}).get("content")
|
|
68
|
+
is_typed = isinstance(content, str) and not content.startswith("<")
|
|
69
|
+
if o.get("type") == "user" and is_typed and not o.get("isMeta"):
|
|
70
|
+
n += 1
|
|
71
|
+
return n
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def usage_per_prompt(path: str) -> float | None:
|
|
75
|
+
if not path or not os.path.exists(path):
|
|
76
|
+
return None
|
|
77
|
+
prompts = _prompts(path)
|
|
78
|
+
if prompts == 0:
|
|
79
|
+
return None
|
|
80
|
+
state = TranscriptState()
|
|
81
|
+
update(state, path)
|
|
82
|
+
return breakdown(state.responses.values())["cost_usd"] / prompts
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _ratio_range(on: list[float], off: list[float], draws: int = 2000) -> tuple[float, float]:
|
|
86
|
+
"""95% bootstrap range of mean(on) / mean(off)."""
|
|
87
|
+
rng = random.Random(0)
|
|
88
|
+
ratios = []
|
|
89
|
+
for _ in range(draws):
|
|
90
|
+
a = [rng.choice(on) for _ in on]
|
|
91
|
+
b = [rng.choice(off) for _ in off]
|
|
92
|
+
ratios.append((sum(a) / len(a)) / (sum(b) / len(b)))
|
|
93
|
+
ratios.sort()
|
|
94
|
+
return ratios[int(0.025 * draws)], ratios[int(0.975 * draws) - 1]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def results() -> dict[str, dict]:
|
|
98
|
+
"""Per saver: sessions on and off, measured change and verdict. Saves decisions to config."""
|
|
99
|
+
groups: dict[str, dict[bool, list[float]]] = {s: {True: [], False: []} for s in SAVERS}
|
|
100
|
+
for state in settings.all_sessions():
|
|
101
|
+
if not state.get("arms"):
|
|
102
|
+
continue
|
|
103
|
+
value = usage_per_prompt(state.get("transcript_path", ""))
|
|
104
|
+
if not value:
|
|
105
|
+
continue
|
|
106
|
+
for saver, on in state["arms"].items():
|
|
107
|
+
groups[saver][on].append(value)
|
|
108
|
+
config = settings.load_config()
|
|
109
|
+
out: dict[str, dict] = {}
|
|
110
|
+
for saver, g in groups.items():
|
|
111
|
+
on, off = g[True], g[False]
|
|
112
|
+
if not on and not off:
|
|
113
|
+
continue
|
|
114
|
+
row: dict = {"on": len(on), "off": len(off), "verdict": "testing"}
|
|
115
|
+
if min(len(on), len(off)) >= MIN_SESSIONS:
|
|
116
|
+
ratio = (sum(on) / len(on)) / (sum(off) / len(off))
|
|
117
|
+
lo, hi = _ratio_range(on, off)
|
|
118
|
+
row.update(change=ratio - 1, low=lo - 1, high=hi - 1)
|
|
119
|
+
if hi < 1:
|
|
120
|
+
row["verdict"] = "on"
|
|
121
|
+
elif lo > 0.95:
|
|
122
|
+
row["verdict"] = "off"
|
|
123
|
+
if row["verdict"] != "testing":
|
|
124
|
+
config.setdefault("decisions", {})[saver] = row["verdict"]
|
|
125
|
+
out[saver] = row
|
|
126
|
+
settings.save_config(config)
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def render(rows: dict[str, dict]) -> str:
|
|
131
|
+
if not rows:
|
|
132
|
+
return ""
|
|
133
|
+
lines = ["", "Measured on your sessions (saver mode A/B, usage per prompt)"]
|
|
134
|
+
for saver, r in rows.items():
|
|
135
|
+
if "change" not in r:
|
|
136
|
+
lines.append(
|
|
137
|
+
f" {NAMES[saver]:10s} testing: {r['on']} sessions on, {r['off']} off "
|
|
138
|
+
f"(decides at {MIN_SESSIONS} each)"
|
|
139
|
+
)
|
|
140
|
+
continue
|
|
141
|
+
verdict = {"on": "kept on", "off": "turned off", "testing": "still testing"}[r["verdict"]]
|
|
142
|
+
lines.append(
|
|
143
|
+
f" {NAMES[saver]:10s} {100 * r['change']:+.0f}% usage per prompt "
|
|
144
|
+
f"(95% range {100 * r['low']:+.0f}% to {100 * r['high']:+.0f}%) -> {verdict}"
|
|
145
|
+
)
|
|
146
|
+
lines.append(" Usage only: hooks cannot see whether the work went as well.")
|
|
147
|
+
return "\n".join(lines)
|
tokenops_cc/caveman.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""caveman adapter: load caveman's own rules in the sessions where the A/B test turns it on.
|
|
2
|
+
|
|
3
|
+
caveman (JuliusBrussee/caveman) stays its own install. TokenOps reads the installed skill file
|
|
4
|
+
and adds it at session start, so it can turn caveman on in some sessions and off in others. For
|
|
5
|
+
that, caveman's own default must be off (``CAVEMAN_DEFAULT_MODE=off``, or ``"defaultMode": "off"``
|
|
6
|
+
in caveman's config file); otherwise caveman is on everywhere and there is nothing to compare.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import glob
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _claude_dir() -> Path:
|
|
18
|
+
return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def skill_file() -> Path | None:
|
|
22
|
+
"""The installed caveman skill, newest first."""
|
|
23
|
+
pattern = str(_claude_dir() / "plugins" / "**" / "skills" / "caveman" / "SKILL.md")
|
|
24
|
+
found = [Path(p) for p in glob.glob(pattern, recursive=True) if "caveman" in p]
|
|
25
|
+
return max(found, key=lambda p: p.stat().st_mtime) if found else None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _config_path() -> Path:
|
|
29
|
+
if os.environ.get("XDG_CONFIG_HOME"):
|
|
30
|
+
return Path(os.environ["XDG_CONFIG_HOME"]) / "caveman" / "config.json"
|
|
31
|
+
if os.name == "nt":
|
|
32
|
+
return (
|
|
33
|
+
Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
|
|
34
|
+
/ "caveman"
|
|
35
|
+
/ "config.json"
|
|
36
|
+
)
|
|
37
|
+
return Path.home() / ".config" / "caveman" / "config.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def default_off() -> bool:
|
|
41
|
+
if os.environ.get("CAVEMAN_DEFAULT_MODE", "").lower() == "off":
|
|
42
|
+
return True
|
|
43
|
+
try:
|
|
44
|
+
config = json.loads(_config_path().read_text(encoding="utf-8-sig"))
|
|
45
|
+
except (OSError, ValueError):
|
|
46
|
+
return False
|
|
47
|
+
return str(config.get("defaultMode", "")).lower() == "off"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def status() -> str:
|
|
51
|
+
if skill_file() is None:
|
|
52
|
+
return "off (caveman not installed)"
|
|
53
|
+
if not default_off():
|
|
54
|
+
return (
|
|
55
|
+
f'off (set caveman\'s default to off first: "defaultMode": "off" in {_config_path()})'
|
|
56
|
+
)
|
|
57
|
+
return "testable"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def rules() -> str:
|
|
61
|
+
"""caveman's skill text without its front matter, as the skill would load it."""
|
|
62
|
+
path = skill_file()
|
|
63
|
+
text = path.read_text(encoding="utf-8") if path else ""
|
|
64
|
+
if text.startswith("---"):
|
|
65
|
+
text = text.split("---", 2)[2]
|
|
66
|
+
return text.strip()
|
tokenops_cc/cost.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Cost breakdown (USD) of a set of responses: by usage type, by model, subagents included."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
|
|
7
|
+
from .prices import CACHE_WRITE_1H, CACHE_WRITE_5M, FAST_MULTIPLIER, price_for, write_tokens
|
|
8
|
+
from .transcript import Response
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def breakdown(responses: Iterable[Response]) -> dict:
|
|
12
|
+
out: dict = {
|
|
13
|
+
"responses": 0,
|
|
14
|
+
"subagent_responses": 0,
|
|
15
|
+
"cost_usd": 0.0,
|
|
16
|
+
"cost_input": 0.0,
|
|
17
|
+
"cost_output": 0.0,
|
|
18
|
+
"cost_cache_read": 0.0,
|
|
19
|
+
"cost_cache_write": 0.0,
|
|
20
|
+
"by_model": {},
|
|
21
|
+
"unpriced_models": [],
|
|
22
|
+
}
|
|
23
|
+
for r in responses:
|
|
24
|
+
u = r.usage
|
|
25
|
+
p, known = price_for(r.model)
|
|
26
|
+
mult = (FAST_MULTIPLIER if r.speed == "fast" else 1.0) / 1e6
|
|
27
|
+
w5m, w1h = write_tokens(u)
|
|
28
|
+
parts = {
|
|
29
|
+
"cost_input": (u.get("input_tokens") or 0) * p["input"] * mult,
|
|
30
|
+
"cost_output": (u.get("output_tokens") or 0) * p["output"] * mult,
|
|
31
|
+
"cost_cache_read": (u.get("cache_read_input_tokens") or 0) * p["cache_read"] * mult,
|
|
32
|
+
"cost_cache_write": (w5m * CACHE_WRITE_5M + w1h * CACHE_WRITE_1H) * p["input"] * mult,
|
|
33
|
+
}
|
|
34
|
+
cost = sum(parts.values())
|
|
35
|
+
for k, v in parts.items():
|
|
36
|
+
out[k] += v
|
|
37
|
+
out["cost_usd"] += cost
|
|
38
|
+
out["responses"] += 1
|
|
39
|
+
out["subagent_responses"] += int(r.sidechain)
|
|
40
|
+
m = out["by_model"].setdefault(r.model, {"responses": 0, "cost_usd": 0.0})
|
|
41
|
+
m["responses"] += 1
|
|
42
|
+
m["cost_usd"] += cost
|
|
43
|
+
if not known and r.model not in out["unpriced_models"]:
|
|
44
|
+
out["unpriced_models"].append(r.model)
|
|
45
|
+
return out
|