rebill 0.1.0__tar.gz

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.
Files changed (75) hide show
  1. rebill-0.1.0/.gitignore +8 -0
  2. rebill-0.1.0/CHANGELOG.md +51 -0
  3. rebill-0.1.0/LICENSE +21 -0
  4. rebill-0.1.0/PKG-INFO +511 -0
  5. rebill-0.1.0/README.md +481 -0
  6. rebill-0.1.0/docs/examples/gate/after/requests.jsonl +18 -0
  7. rebill-0.1.0/docs/examples/gate/before/requests.jsonl +18 -0
  8. rebill-0.1.0/docs/examples.md +121 -0
  9. rebill-0.1.0/docs/json.md +99 -0
  10. rebill-0.1.0/pyproject.toml +59 -0
  11. rebill-0.1.0/scripts/check_prices.py +522 -0
  12. rebill-0.1.0/scripts/make_examples.py +109 -0
  13. rebill-0.1.0/src/rebill/__init__.py +7 -0
  14. rebill-0.1.0/src/rebill/__main__.py +3 -0
  15. rebill-0.1.0/src/rebill/bill.py +156 -0
  16. rebill-0.1.0/src/rebill/calibrate.py +151 -0
  17. rebill-0.1.0/src/rebill/cli.py +870 -0
  18. rebill-0.1.0/src/rebill/data/prices.json +2402 -0
  19. rebill-0.1.0/src/rebill/gate.py +192 -0
  20. rebill-0.1.0/src/rebill/importers/__init__.py +104 -0
  21. rebill-0.1.0/src/rebill/importers/_common.py +116 -0
  22. rebill-0.1.0/src/rebill/importers/claude_code.py +177 -0
  23. rebill-0.1.0/src/rebill/importers/codex.py +180 -0
  24. rebill-0.1.0/src/rebill/importers/copilot_cli.py +136 -0
  25. rebill-0.1.0/src/rebill/importers/gemini_cli.py +181 -0
  26. rebill-0.1.0/src/rebill/importers/opencode.py +267 -0
  27. rebill-0.1.0/src/rebill/importers/sdk_log.py +184 -0
  28. rebill-0.1.0/src/rebill/model.py +142 -0
  29. rebill-0.1.0/src/rebill/policies.py +414 -0
  30. rebill-0.1.0/src/rebill/pricing.py +324 -0
  31. rebill-0.1.0/src/rebill/py.typed +0 -0
  32. rebill-0.1.0/src/rebill/record.py +351 -0
  33. rebill-0.1.0/src/rebill/report.py +430 -0
  34. rebill-0.1.0/src/rebill/scenarios.py +284 -0
  35. rebill-0.1.0/src/rebill/sizing.py +91 -0
  36. rebill-0.1.0/src/rebill/timeline.py +91 -0
  37. rebill-0.1.0/tests/conftest.py +8 -0
  38. rebill-0.1.0/tests/fixtures/claude_code/-home-dev-blog.jsonl +1 -0
  39. rebill-0.1.0/tests/fixtures/claude_code/-home-dev-shop/7f3c2a10/subagents/agent-b81e.jsonl +1 -0
  40. rebill-0.1.0/tests/fixtures/claude_code/-home-dev-shop/7f3c2a10.jsonl +9 -0
  41. rebill-0.1.0/tests/fixtures/codex/2026/11/29/rollout-2026-11-29T16-00-00-019abc00.jsonl +12 -0
  42. rebill-0.1.0/tests/fixtures/codex/2026/11/29/rollout-sep.jsonl +3 -0
  43. rebill-0.1.0/tests/fixtures/copilot_cli/session-state/7e2a4c10-0000-4000-8000-0000000c0001/events.jsonl +7 -0
  44. rebill-0.1.0/tests/fixtures/copilot_cli/session-state/7e2a4c10-0000-4000-8000-0000000c0001/workspace.yaml +2 -0
  45. rebill-0.1.0/tests/fixtures/gemini_cli/9c1e5f0a/chats/4b7d2e90-0000-4000-8000-00000000aa01/5c8e3fa1-0000-4000-8000-00000000bb02.jsonl +2 -0
  46. rebill-0.1.0/tests/fixtures/gemini_cli/9c1e5f0a/chats/session-2026-10-02T08-00-legacy00.json +29 -0
  47. rebill-0.1.0/tests/fixtures/gemini_cli/9c1e5f0a/chats/session-2026-11-30T10-00-4b7d2e90.jsonl +10 -0
  48. rebill-0.1.0/tests/fixtures/pricing/anthropic.md +23 -0
  49. rebill-0.1.0/tests/fixtures/pricing/google.md +135 -0
  50. rebill-0.1.0/tests/fixtures/pricing/openai.md +36 -0
  51. rebill-0.1.0/tests/test_bill.py +89 -0
  52. rebill-0.1.0/tests/test_calibrate.py +65 -0
  53. rebill-0.1.0/tests/test_check_prices.py +202 -0
  54. rebill-0.1.0/tests/test_claude_code.py +117 -0
  55. rebill-0.1.0/tests/test_codex.py +111 -0
  56. rebill-0.1.0/tests/test_compact.py +149 -0
  57. rebill-0.1.0/tests/test_copilot_cli.py +63 -0
  58. rebill-0.1.0/tests/test_examples.py +22 -0
  59. rebill-0.1.0/tests/test_gate.py +161 -0
  60. rebill-0.1.0/tests/test_gemini_cli.py +79 -0
  61. rebill-0.1.0/tests/test_json_format.py +185 -0
  62. rebill-0.1.0/tests/test_model.py +32 -0
  63. rebill-0.1.0/tests/test_modes.py +97 -0
  64. rebill-0.1.0/tests/test_opencode.py +215 -0
  65. rebill-0.1.0/tests/test_pricing.py +251 -0
  66. rebill-0.1.0/tests/test_ranges.py +98 -0
  67. rebill-0.1.0/tests/test_record_streams.py +177 -0
  68. rebill-0.1.0/tests/test_release.py +37 -0
  69. rebill-0.1.0/tests/test_report.py +125 -0
  70. rebill-0.1.0/tests/test_scenarios.py +124 -0
  71. rebill-0.1.0/tests/test_sdk_log.py +315 -0
  72. rebill-0.1.0/tests/test_sizing.py +78 -0
  73. rebill-0.1.0/tests/test_timeline.py +158 -0
  74. rebill-0.1.0/tests/test_tool_cap.py +89 -0
  75. rebill-0.1.0/tests/test_whatif.py +113 -0
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
@@ -0,0 +1,51 @@
1
+ # Changelog
2
+
3
+ All notable changes to rebill. The `--json` output follows its own `format`
4
+ number, described in [docs/json.md](docs/json.md); a change to it is called out
5
+ here.
6
+
7
+ ## 0.1.0 (2026-12-03)
8
+
9
+ First release.
10
+
11
+ ### Readers
12
+
13
+ - Claude Code, Codex CLI, OpenCode and Gemini CLI transcripts, request by
14
+ request; GitHub Copilot CLI per-model session totals.
15
+ - Opt-in request logs for your own Anthropic, OpenAI and Google SDK calls
16
+ (`rebill.record`), sync, async and streamed.
17
+ Gemini calls are billed in the tier Google says served them (the
18
+ `x-gemini-service-tier` header), else the tier they asked for; Gemini
19
+ Interactions API calls are read too.
20
+ - Repeated usage records merged, subagents kept as sidechains, cache writes
21
+ split by lifetime, served mode (batch, flex, fast, ultrafast) and US-only
22
+ inference read where the transcript records them.
23
+
24
+ ### Commands
25
+
26
+ - `bill`: cost at list prices by session, model, day, agent or mode, checked
27
+ against any cost the agent recorded.
28
+ - `whatif`: another model, cache lifetime, tool-output cap, compaction point,
29
+ mode or region, with what was held fixed and a range when estimates feed it.
30
+ - `compare`: several what-ifs side by side from a policy file or sweeps.
31
+ - `report`: Markdown or HTML bills with a drill-down per session.
32
+ - `gate`: fail CI when cost per session rose between two transcript sets, with a
33
+ bootstrap interval and a breakdown by model or agent.
34
+ - `timeline`, `check`, `prices`.
35
+
36
+ ### Prices
37
+
38
+ - Bundled, dated, sourced price table for Anthropic, OpenAI and Google models,
39
+ including long-context tiers, per-model fast and ultrafast rates, OpenAI's pro
40
+ models, and Gemini's per-model batch, flex and priority rates.
41
+ - `scripts/check_prices.py` compares it with the providers' pricing pages; a
42
+ weekly workflow runs it.
43
+
44
+ ### JSON
45
+
46
+ - `--json` output is `format` 1, documented in docs/json.md and pinned by tests.
47
+
48
+ ### Docs
49
+
50
+ - docs/examples.md: real `report` and `gate` output on sample transcripts,
51
+ regenerated by scripts/make_examples.py and checked by the tests.
rebill-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 driftwright
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
rebill-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,511 @@
1
+ Metadata-Version: 2.5
2
+ Name: rebill
3
+ Version: 0.1.0
4
+ Summary: Re-bill coding-agent sessions: exact token cost from local transcripts, and what it would have cost under a different model or policy.
5
+ Project-URL: Homepage, https://github.com/driftwright/rebill
6
+ Project-URL: Issues, https://github.com/driftwright/rebill/issues
7
+ Project-URL: Changelog, https://github.com/driftwright/rebill/blob/main/CHANGELOG.md
8
+ Author: driftwright
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: claude-code,codex,cost,finops,llm,prompt-caching,tokens
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: Utilities
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: tomli>=1.1; python_version < '3.11'
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=7; extra == 'dev'
28
+ Requires-Dist: ruff>=0.6; extra == 'dev'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # rebill
32
+
33
+ Re-bill coding-agent sessions from the transcripts they already leave on disk.
34
+
35
+ Usage dashboards tell you what your Claude Code or Codex sessions cost. `rebill`
36
+ is for the next question: **what would the same work have cost under a different
37
+ setup?** Another model for the main thread, a cheaper one for subagents, a
38
+ 1-hour cache instead of a 5-minute one, an earlier compaction point, capped tool
39
+ output. You answer that from your own history instead of a guess, and every
40
+ number traces back to a request in a transcript and a dated line in a price
41
+ table.
42
+
43
+ Status: early development. Billing, model swaps, cache-lifetime replays,
44
+ tool-output caps, compaction replays and side-by-side comparisons work today for
45
+ Claude Code, Codex CLI, OpenCode and Gemini CLI, with session totals from GitHub
46
+ Copilot CLI, and for your own Anthropic, OpenAI and Google SDK calls once you log
47
+ them. See [ROADMAP.md](ROADMAP.md).
48
+
49
+ Example output in this README uses illustrative numbers. For real output of
50
+ `rebill report` and `rebill gate` on sample transcripts, see
51
+ [docs/examples.md](docs/examples.md).
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install git+https://github.com/driftwright/rebill
57
+ ```
58
+
59
+ Not on PyPI yet. Python 3.10+, no runtime dependencies beyond `tomli` on Python 3.10. Nothing leaves your machine: `rebill`
60
+ reads local files and makes no network calls.
61
+
62
+ ## Bill what happened
63
+
64
+ ```console
65
+ $ rebill bill --by model
66
+ model reqs input cache rd cache wr output cost
67
+ ------------------------- ---- ----- -------- -------- ------ ------
68
+ claude-opus-4-5-20251101 412 9.8k 61.2M 4.1M 310k $73.04
69
+ claude-haiku-4-5-20251001 188 402k 8.9M 1.2M 95k $3.74
70
+ gpt-5.1-codex 96 1.3M 7.7M 0 88k $3.51
71
+ ------------------------- ---- ----- -------- -------- ------ ------
72
+ total 696 1.7M 77.8M 5.3M 493k $80.29
73
+
74
+ Merged 1,204 repeated usage record(s).
75
+ List prices as of 2026-12-03; cache writes priced per lifetime.
76
+ ```
77
+
78
+ With no paths, `rebill` reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`),
79
+ `~/.codex/sessions` (or `$CODEX_HOME`) and OpenCode's
80
+ `~/.local/share/opencode/opencode.db` (or under `$XDG_DATA_HOME`) and Gemini CLI's
81
+ `~/.gemini/tmp/*/chats` (or under `$GEMINI_CLI_HOME`), and Copilot CLI's
82
+ `~/.copilot/session-state` (or `$COPILOT_HOME`). Pass files or directories to
83
+ read something else; the format is detected per file. Group with `--by
84
+ session|model|day|agent|mode|total`, filter with `--since YYYY-MM-DD`, and add
85
+ `--json` for scripts.
86
+
87
+ ## Ask what it would have cost
88
+
89
+ ```console
90
+ $ rebill whatif --model claude-sonnet-4-6 --only-model 'claude-opus-*' --by model
91
+ model reqs recorded what-if change %
92
+ ------------------------- ---- -------- ------- ------- ------
93
+ claude-opus-4-5-20251101 412 $73.04 $43.82 -$29.22 -40.0%
94
+ claude-haiku-4-5-20251001 188 $3.74 $3.74 +$0.00 +0.0%
95
+ gpt-5.1-codex 96 $3.51 $3.51 +$0.00 +0.0%
96
+ ------------------------- ---- -------- ------- ------- ------
97
+ total 696 $80.29 $51.07 -$29.22 -36.4%
98
+
99
+ Re-billed 412 of 696 request(s) as claude-sonnet-4-6.
100
+ Same requests, same cache hits; only the price per token changes.
101
+ ```
102
+
103
+ `--scope main|subagents` limits the swap to the main thread or to subagent
104
+ requests. `--token-scale 1.3` multiplies token counts, for a target model whose
105
+ tokenizer emits more tokens for the same text (Anthropic documents about 30%
106
+ more for Claude 4.7 and later).
107
+
108
+ A model swap holds the work fixed: the same requests with the same contents and
109
+ the same cache hits, priced at different rates. A different model would have
110
+ taken a different path, so treat the result as the price of the work you
111
+ actually did, not a forecast.
112
+
113
+ ## See where the cache missed
114
+
115
+ ```console
116
+ $ rebill timeline 7f3c
117
+ session 7f3c2a10 (claude-code) /home/dev/shop
118
+
119
+ [main]
120
+ time gap kind prompt read write out cost model
121
+ 09:00:04 - first 18.0k 0 18.0k 310 $0.19 claude-opus-4-5-20251101
122
+ 09:00:12 8s hit 20.5k 18.0k 2.5k 120 $0.04 claude-opus-4-5-20251101
123
+ 09:14:40 14.5m idle-rebuild 21.1k 0 21.0k 95 $0.21 claude-opus-4-5-20251101
124
+ ...
125
+ ```
126
+
127
+ Each request is compared with the previous one in the same thread (main or a
128
+ given subagent): a `hit` read back what was cached, an `idle-rebuild` missed
129
+ because the gap outlived the cache lifetime, a `model-switch` missed because
130
+ caches don't carry across models, and a `rebuild` missed for another reason
131
+ such as compaction.
132
+
133
+ ## Replay a different cache lifetime
134
+
135
+ ```console
136
+ $ rebill whatif --cache-ttl 1h
137
+ ```
138
+
139
+ With a longer lifetime, an idle rebuild whose gap fits inside it reads back what
140
+ the previous request had cached instead of writing it again; with a shorter one,
141
+ a hit after a long gap becomes a write. Every write is billed at the new
142
+ lifetime's rate (Anthropic charges 1.25x input for 5-minute writes and 2x for
143
+ 1-hour ones), so a longer cache only pays off when you actually pause between
144
+ requests. `--cache-ttl` and `--model` can be combined.
145
+
146
+ ## Cap tool output
147
+
148
+ ```console
149
+ $ rebill whatif --cap-tool-output 4000
150
+ ```
151
+
152
+ A large tool result (a full file read, a long test log) is written to the cache
153
+ once and then read back by every later request in the thread until the
154
+ conversation is compacted. `--cap-tool-output N` replays the thread as if each
155
+ result had been cut to N tokens and removes the excess from all of those
156
+ requests. It works on Claude Code, Codex, OpenCode and Gemini CLI transcripts.
157
+
158
+ Result sizes start as a text estimate (four characters per token) and are then
159
+ corrected per session: in a tool loop the real prompt grows by about the previous
160
+ response plus the tool output, so the median ratio of real growth to estimated
161
+ size over a session's tool steps gives its correction factor (`rebill timeline`
162
+ prints it). On one real OpenCode history of 350 sessions the factor was 1.18
163
+ (quartiles 1.10 to 1.29). The replay doesn't add the requests an agent might make
164
+ to recover truncated output, so read the saving as an upper bound.
165
+
166
+ Because the sizes are estimates, the what-if also prints a range: the same replay
167
+ with each session's 25th and 75th percentile ratio in place of its median. A
168
+ session with fewer than three usable tool steps can't be calibrated; its sizes
169
+ are used as estimated, and the output says how many such sessions there were.
170
+
171
+ ```console
172
+ Range: $36.90 to $38.71, with tool-output sizes from the 25th to the 75th percentile of each calibration.
173
+ ```
174
+
175
+ ## Compact earlier
176
+
177
+ ```console
178
+ $ rebill whatif --compact-at 60k
179
+ total reqs recorded what-if change %
180
+ total 9417 $39.73 $38.14 -$1.58 -4.0%
181
+
182
+ What-if: compaction at 60,000 prompt tokens. ...
183
+ Range: $37.61 to $39.19, with summaries of 2,000 to 8,000 tokens.
184
+ Replayed 85 compaction(s), each adding a summary request of 4,000 output tokens.
185
+ ```
186
+
187
+ Every request in a long thread re-sends the whole history, mostly as cache
188
+ reads, so a thread that runs to 300k tokens pays for that history on each
189
+ turn. `--compact-at N` replays each thread with a compaction whenever its prompt
190
+ would pass N tokens:
191
+
192
+ - a summary request is added, which re-sends the history (from the cache when
193
+ it is still warm, uncached when it had expired) and writes a summary of
194
+ `--summary-tokens` (default 4k);
195
+ - the request restarts from the thread's opening prompt (system prompt, tools,
196
+ first message) plus the summary plus what was new in it, written to the cache;
197
+ - every later request carries the shorter history forward.
198
+
199
+ Compacting too often costs more than it saves: on the history above a 20k
200
+ threshold was 27% more expensive, 60k saved 4% and 100k saved 1.7%. How long
201
+ the agent's summaries really are is a guess, so the range printed under the
202
+ result replays half and double `--summary-tokens`. Only
203
+ compacting earlier than the agent did can be replayed (compactions it really did
204
+ are kept), and the re-reads an agent makes after losing detail to a summary are
205
+ not modelled.
206
+
207
+ ## Price fast mode, batch and US-only inference
208
+
209
+ Requests are billed in the mode they were served in, when the transcript says:
210
+ Claude Code records `speed` (`/fast`), `service_tier` and `inference_geo` with
211
+ every response, and Codex records its service tier (`priority` in fast mode, or
212
+ `flex`) whenever the thread's settings change. OpenCode records neither.
213
+
214
+ ```console
215
+ $ rebill bill --by mode
216
+ mode reqs input cache rd cache wr output cost
217
+ -------- ---- ----- -------- -------- ------ -----
218
+ fast 4 800 190.0k 20.0k 6.0k $0.52
219
+ standard 2 400 125.0k 10.0k 3.0k $0.14
220
+ $ rebill whatif --mode standard
221
+ total reqs recorded what-if change %
222
+ ----- ---- -------- ------- ------ ------
223
+ total 6 $0.66 $0.40 -$0.26 -39.6%
224
+ ```
225
+
226
+ `--mode` (`standard`, `batch`, `flex`, `priority`, `fast`, `ultrafast`) and `--geo` (`us`, or
227
+ `global` for default routing) bill every request that way with the same tokens;
228
+ both work as `compare` settings too (`--sweep mode=standard,fast`). The Codex tier
229
+ is the one Codex asked for; the rollout doesn't say which one OpenAI served.
230
+
231
+ ## Compare several setups at once
232
+
233
+ `rebill compare` bills the recorded sessions once and then each scenario, one
234
+ row per scenario. Sweep a setting:
235
+
236
+ ```console
237
+ $ rebill compare --sweep compact-at=20k,40k,60k,100k
238
+ scenario reqs cost change %
239
+ --------------- ----- ------ ------- ------
240
+ recorded 9417 $39.73
241
+ compact-at=20k 11116 $50.37 +$10.65 +26.8% 1699 compactions
242
+ compact-at=40k 9716 $37.85 -$1.88 -4.7% 299 compactions, cheapest
243
+ compact-at=60k 9502 $38.14 -$1.58 -4.0% 85 compactions
244
+ compact-at=100k 9437 $39.05 -$0.67 -1.7% 20 compactions
245
+ ```
246
+
247
+ or describe scenarios in a TOML file, each starting from an optional `[base]`:
248
+
249
+ ```toml
250
+ [base]
251
+ cache_ttl = "1h"
252
+
253
+ [scenario.sonnet-main]
254
+ model = "claude-sonnet-4-6"
255
+ scope = "main"
256
+
257
+ [scenario.tight]
258
+ compact_at = "60k"
259
+ cap_tool_output = "4k"
260
+ ```
261
+
262
+ ```console
263
+ $ rebill compare --policies setups.toml --sweep summary-tokens=2k,8k
264
+ ```
265
+
266
+ Settings are the `whatif` options (`model`, `only_model`, `scope`, `token_scale`,
267
+ `cache_ttl`, `cap_tool_output`, `compact_at`, `summary_tokens`, `mode`, `geo`); dashes and
268
+ underscores both work. Repeated `--sweep` flags are crossed with each other and
269
+ with every scenario in the file. Within a scenario the policies always apply in
270
+ the same order: tool-output cap, compaction, cache lifetime, model, mode and geo.
271
+
272
+ ## Write a report for a pull request or wiki
273
+
274
+ ```console
275
+ $ rebill report --since 2026-11-01 > cost.md
276
+ $ rebill report --compact-at 60k --format html -o compact-60k.html
277
+ ```
278
+
279
+ `rebill report` writes the bill as Markdown (default) or one self-contained HTML
280
+ page with no scripts or external files. It opens with a summary, then a table
281
+ of the most expensive sessions (`--top`, default 20; `0` for all), and under it
282
+ one collapsible `<details>` section per session with its tokens and cost by
283
+ model. GitHub and GitLab render those sections in issues, pull requests and
284
+ wikis.
285
+
286
+ It takes every `whatif` option. With one, each session and model shows both
287
+ costs, the summary says what was held fixed, and a what-if that rests on
288
+ estimates gets a range for the total and for each session:
289
+
290
+ ```markdown
291
+ ## What-if report
292
+
293
+ 212 session(s), 9,417 request(s), $39.73 at list prices as of 2026-12-03.
294
+ What-if (compaction at 60,000 prompt tokens): $38.14, -$1.58 (-4.0%).
295
+ Range $37.61 to $39.19, with summaries of 2,000 to 8,000 tokens.
296
+ ```
297
+
298
+ Session start times are in UTC. Session ids and working directories appear as
299
+ written in the transcripts, so check a report before posting it somewhere
300
+ public.
301
+
302
+ ## Fail CI when sessions got more expensive
303
+
304
+ ```console
305
+ $ rebill gate runs/before runs/after --max-increase 10
306
+ sessions requests cost mean per session
307
+ before 12 341 $4.18 $0.35
308
+ after 12 366 $5.07 $0.42
309
+
310
+ Change in mean cost per session: +21.3% (90% interval +6.0% to +38.2%); limit +10%.
311
+
312
+ FAIL: cost per session rose past +10%.
313
+ ```
314
+
315
+ Run the same tasks before and after a change (a new system prompt, another
316
+ model, a different tool setup), keep both sets of transcripts, and `rebill gate`
317
+ prices them with the same table and compares cost per session. It exits 1 when
318
+ the increase passes `--max-increase` (in percent, default 10) and 0 otherwise.
319
+
320
+ - Session costs are skewed and CI samples are small, so the gate also prints a
321
+ 90% bootstrap interval for the change, with a fixed seed so reruns agree.
322
+ `--confident` fails only when the low end of the interval passes the limit.
323
+ - `--metric median` ignores one runaway session; `--per request` compares cost
324
+ per request instead of per session.
325
+ - It exits 2 (can't judge) when a set is empty, has fewer than `--min-sessions`
326
+ (default 3), or has requests on a model with no price, which would otherwise
327
+ count as free and make a switch to an unknown model look cheaper.
328
+ `--allow-unpriced` overrides that last check.
329
+ - `--by model` or `--by agent` adds a table of where the mean cost per session
330
+ moved: each model's (or agent's) cost on each side divided by that side's
331
+ session count, so the rows add up to the change in the mean.
332
+ - `--format markdown` writes a table for a job summary; `--json` for scripts.
333
+
334
+ ```yaml
335
+ - run: pip install git+https://github.com/driftwright/rebill
336
+ - run: rebill gate baseline/ runs/ --confident --format markdown >> "$GITHUB_STEP_SUMMARY"
337
+ ```
338
+
339
+ ## How it counts
340
+
341
+ - **One request, one bill.** Claude Code writes a JSONL line per content block
342
+ and repeats the response's usage on each, so summing lines overcounts by the
343
+ number of blocks. Requests are keyed by `message.id` and merged. Codex repeats
344
+ `token_count` frames; a frame only counts when the running total moved.
345
+ - **Disjoint buckets.** Every request is stored as uncached input, cache reads,
346
+ cache writes per lifetime (`5m`, `1h`, `30m`, `12h`) and output. OpenAI's
347
+ `input_tokens` includes its cached tokens and cache writes, so the Codex reader
348
+ splits both out (writes as 30-minute ones, OpenAI's default); Gemini's
349
+ prompt count includes its cached tokens and leaves out thinking tokens, which
350
+ are billed as output.
351
+ - **Totals where that's all there is.** Copilot CLI only writes per-model session
352
+ totals (at shutdown), not each request. Those bill and swap models fine, with
353
+ the long-context tier chosen from the average prompt, but cache, compaction and
354
+ tool-output replays leave them as recorded. Copilot plans bill premium
355
+ requests; rebill shows what the tokens cost at API list prices.
356
+ - **Billed means billed.** A Gemini CLI rewind hides messages from the
357
+ conversation, but those requests were made and paid for, so they stay.
358
+ - **Tiers per request.** Long-context rates (Anthropic's 200k and 100k lines,
359
+ OpenAI's 272k) are chosen per request from its whole prompt, cache reads and
360
+ writes included, the way the providers bill them.
361
+ - **Dated prices.** A model's price can change on a date; each request is priced
362
+ with the period in force when it was made.
363
+ - **Served how, and where.** A request run in batch, flex, priority, fast or ultrafast mode,
364
+ or pinned to US-only inference, is priced that way when the transcript says so.
365
+ Fast and ultrafast have their own per-model rates (cache multipliers on top);
366
+ Anthropic and OpenAI batch and flex are half price on every bucket, while Gemini
367
+ lists batch, flex and priority per model (batch and flex often halve input and
368
+ output but keep the standard cache price; priority is listed at 1.8x standard);
369
+ Anthropic's US-only inference is
370
+ 1.1x on top of everything. A mode with no listed price for that model is priced
371
+ at standard with a note, not guessed.
372
+ - **No silent zeros.** A request on a model with no price is counted and flagged,
373
+ never billed as $0. Add prices with `--prices my-prices.json`; the file uses the
374
+ same format as [the bundled table](src/rebill/data/prices.json) and wins over it.
375
+ - **Checked against the agent.** When a transcript records its own cost, `rebill`
376
+ prices the same requests and prints the gap.
377
+
378
+ `rebill prices [MODEL]` prints the table in use.
379
+
380
+ The bundled table is checked against the providers' published pricing pages by
381
+ `scripts/check_prices.py`, weekly in CI and by hand before a release. It reads
382
+ the Markdown version of each page, compares standard, long-context, fast and
383
+ ultrafast prices, Gemini's batch and flex prices, and the batch and flex
384
+ multipliers model by model, and prints
385
+ what differs with the page it came from. `--apply` writes the differing prices
386
+ into the table, so an update is an ordinary diff to review; new models and
387
+ announced future prices are listed for a person to decide on.
388
+
389
+ ## Check prices against what the agent recorded
390
+
391
+ OpenCode (and older Claude Code) store a dollar cost per request. `rebill check`
392
+ compares it with the list price per model and lists the requests that disagree
393
+ most. For a model with no list price, such as a self-hosted or resold one, it
394
+ solves the recorded costs for the per-token rates the agent was using:
395
+
396
+ ```console
397
+ $ rebill check --infer-prices my-prices.json
398
+ glm-5.3: 457 request(s), agent recorded $8.11; no price here.
399
+ implied $/MTok: input 1.4 output 4.4 cache_read 0.26 (fits recorded total within 0.00%)
400
+
401
+ Wrote inferred prices for unpriced models to my-prices.json.
402
+ $ rebill bill --prices my-prices.json
403
+ ```
404
+
405
+ A bucket that never appears in the recorded requests is left out of the inferred
406
+ price rather than set to zero.
407
+
408
+ ## Log your own SDK calls
409
+
410
+ Scripts and apps that call the Anthropic, OpenAI or Google GenAI SDKs leave no
411
+ transcript, so `rebill` ships a small opt-in recorder. Wrap a client and every
412
+ `create`, `parse` or `generate_content` result appends one JSON line with the
413
+ model, the response id, the service tier and the provider's raw `usage`:
414
+
415
+ ```python
416
+ import anthropic
417
+ from rebill.record import recording
418
+
419
+ client = recording(anthropic.Anthropic(), session="nightly-triage")
420
+ client.messages.create(model="claude-opus-5-5", max_tokens=1024, messages=[...])
421
+ ```
422
+
423
+ Or record one response: `rebill.record.record(response, session="...")`. Lines go
424
+ to `$REBILL_LOG` if set, else `~/.rebill/requests/<date>.jsonl`, and `rebill bill`
425
+ reads them along with the agents' transcripts. Prompts and outputs are never
426
+ written, and the SDKs are not dependencies.
427
+
428
+ Async clients and streams are recorded too. A `stream=True` call or
429
+ `generate_content_stream` is handed back as is and logged once, when it ends or
430
+ is closed, with the usage the stream reported up to then. OpenAI's Chat
431
+ Completions streams only report usage when asked
432
+ (`stream_options={"include_usage": True}`). The `.stream()` helpers aren't
433
+ wrapped; record their final message (`record(stream.get_final_message())`).
434
+ Pass `thread="..."` for a subagent so it bills as a sidechain.
435
+
436
+ Gemini calls are billed in the tier that served them. Google returns it in an
437
+ `x-gemini-service-tier` response header, which the GenAI SDK keeps on
438
+ `response.sdk_http_response.headers`; the recorder logs it as `service_tier`,
439
+ and the tier the call asked for (`config=GenerateContentConfig(service_tier=...)`)
440
+ as `requested_service_tier`. A line with no served tier is billed in the
441
+ requested one. That is exact for Flex, which Google never moves to another
442
+ tier, but a Priority request can be served, and billed, at Standard when Google
443
+ is congested, so those lines are billed as Priority with a warning. When you
444
+ call `record()` yourself, pass the tier you asked for as `requested_tier=`.
445
+
446
+ Calls on Google's Interactions API (`client.interactions.create`, streamed or
447
+ not) are read too. Their response has a `service_tier` field rather than the
448
+ header, and the recorder takes it as the served tier.
449
+
450
+ ## Known assumptions
451
+
452
+ Some transcripts leave out a detail the bill depends on. Where they do, `rebill`
453
+ assumes the following. Each is checked against the agent's source, not yet
454
+ against logs from many users; a transcript that shows otherwise is a bug report
455
+ we want.
456
+
457
+ - **Codex cache writes are 30-minute writes.** The rollout records how many
458
+ tokens were written to the cache but not the lifetime requested; 30 minutes is
459
+ OpenAI's default.
460
+ - **Copilot CLI cache writes are 5-minute writes.** Its shutdown totals count
461
+ cache writes without saying which lifetime; 5 minutes is the common default.
462
+ - **The last Copilot CLI shutdown covers the whole session.** A resumed session
463
+ writes another `session.shutdown`; its per-model totals are read as cumulative,
464
+ so only the last one counts. A reply on the Copilot CLI tracker says usage survives a
465
+ resume, but at least one other tool reads each shutdown as covering only the
466
+ time since the last resume. If that's right, resumed sessions are undercounted
467
+ here; a resumed `events.jsonl` with its counts would settle it.
468
+ - **Gemini's output count leaves thinking tokens out.** Thinking tokens are added
469
+ to output unless the recorded total shows they were already in it.
470
+ - **A Gemini SDK call without the tier header ran in the tier it asked for.**
471
+ Only the header says which tier served a call. Without it, Flex is billed as
472
+ Flex (Google doesn't move Flex requests) and Priority as Priority, with a
473
+ warning, since congestion can serve Priority at Standard prices.
474
+ - **A Gemini interaction's `service_tier` is the tier that served it.** Google
475
+ doesn't say whether the field reports the tier used or echoes the one asked
476
+ for. An agent interaction that ran several model steps is billed as one
477
+ request on its total tokens, so its long-context tier is judged on the total.
478
+ - **SDK logs say which provider.** When a line has no `provider`, it's guessed
479
+ from the shape of `usage`.
480
+
481
+ ## How this differs from usage trackers
482
+
483
+ Tools such as ccusage, tokscale and toktrack aggregate what sessions cost across
484
+ many agents and are the right choice for a daily spend view. Single-purpose
485
+ analyzers flag wasteful turns or simulate one compaction setting. `rebill` is a
486
+ library and CLI built around one model of a request (its buckets, tiers, cache
487
+ lifetimes and timing) so that any policy can be replayed against your history
488
+ and priced in dollars with the rules each provider actually applies.
489
+
490
+ ## Library use
491
+
492
+ ```python
493
+ from rebill.importers import load_any
494
+ from rebill.bill import compare
495
+ from rebill.policies import SwapModel
496
+ from rebill.pricing import PriceBook
497
+
498
+ sessions = load_any().sessions
499
+ rows, total = compare(sessions, PriceBook.default(), SwapModel("claude-sonnet-4-6"), group="day")
500
+ print(f"{total.change_pct:+.1f}%")
501
+ ```
502
+
503
+ ## Scripting against the output
504
+
505
+ Every command that takes `--json` prints a versioned document (`"format": 1`)
506
+ whose fields are listed in [docs/json.md](docs/json.md) and pinned by tests;
507
+ fields are only added within a format. Changes are in [CHANGELOG.md](CHANGELOG.md).
508
+
509
+ ## License
510
+
511
+ MIT