Metadata-Version: 2.5
Name: rebill
Version: 0.1.3
Summary: Re-bill coding-agent sessions: exact token cost from local transcripts, and what it would have cost under a different model or policy.
Project-URL: Homepage, https://github.com/driftwright/rebill
Project-URL: Issues, https://github.com/driftwright/rebill/issues
Project-URL: Changelog, https://github.com/driftwright/rebill/blob/main/CHANGELOG.md
Author: driftwright
License-Expression: MIT
License-File: LICENSE
Keywords: claude-code,codex,cost,finops,llm,prompt-caching,tokens
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Utilities
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: tomli>=1.1; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# rebill

Re-bill coding-agent sessions from the transcripts they already leave on disk.

**New here? Start with the [5-minute quickstart](docs/quickstart.md).**

Usage dashboards tell you what your Claude Code or Codex sessions cost. `rebill`
is for the next question: **what would the same work have cost under a different
setup?** Another model for the main thread, a cheaper one for subagents, a
1-hour cache instead of a 5-minute one, an earlier compaction point, capped tool
output. You answer that from your own history instead of a guess, and every
number traces back to a request in a transcript and a dated line in a price
table.

Status: early development. Billing, model swaps, cache-lifetime replays,
tool-output caps, compaction replays and side-by-side comparisons work today for
Claude Code, Codex CLI, OpenCode, Gemini CLI and DeepSeek Harness (`dsh`), with
session totals from GitHub Copilot CLI, and for your own Anthropic, OpenAI and
Google SDK calls once you log them. See [ROADMAP.md](ROADMAP.md).

Example output in this README uses illustrative numbers. For real output of
`rebill report` and `rebill gate` on sample transcripts, see
[docs/examples.md](docs/examples.md).

## Install

```bash
pip install rebill
```

Python 3.10+, no runtime dependencies beyond `tomli` on Python 3.10. Nothing leaves your machine: `rebill`
reads local files and makes no network calls.

## Bill what happened

```console
$ rebill bill --by model
model                      reqs  input  cache rd  cache wr  output    cost
-------------------------  ----  -----  --------  --------  ------  ------
claude-opus-4-5-20251101    412   9.8k     61.2M      4.1M    310k  $73.04
claude-haiku-4-5-20251001   188   402k      8.9M      1.2M     95k   $3.74
gpt-5.1-codex                96   1.3M      7.7M         0     88k   $3.51
-------------------------  ----  -----  --------  --------  ------  ------
total                       696   1.7M     77.8M      5.3M    493k  $80.29

Merged 1,204 repeated usage record(s).
List prices as of 2026-12-03; cache writes priced per lifetime.
```

With no paths, `rebill` reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`),
`~/.codex/sessions` (or `$CODEX_HOME`) and OpenCode's
`~/.local/share/opencode/opencode.db` (or under `$XDG_DATA_HOME`) and Gemini CLI's
`~/.gemini/tmp/*/chats` (or under `$GEMINI_CLI_HOME`), and Copilot CLI's
`~/.copilot/session-state` (or `$COPILOT_HOME`), and DeepSeek Harness's
`~/.dsh/sessions` (or `$DSH_HOME`). Pass files or directories to
read something else; the format is detected per file. Group with `--by
session|model|day|agent|mode|total`, filter with `--since YYYY-MM-DD` and
`--until YYYY-MM-DD` (inclusive, UTC days), and add
`--json` for scripts.

## Ask what it would have cost

```console
$ rebill whatif --model claude-sonnet-4-6 --only-model 'claude-opus-*' --by model
model                      reqs  recorded  what-if   change       %
-------------------------  ----  --------  -------  -------  ------
claude-opus-4-5-20251101    412    $73.04   $43.82  -$29.22  -40.0%
claude-haiku-4-5-20251001   188     $3.74    $3.74   +$0.00   +0.0%
gpt-5.1-codex                96     $3.51    $3.51   +$0.00   +0.0%
-------------------------  ----  --------  -------  -------  ------
total                       696    $80.29   $51.07  -$29.22  -36.4%

Re-billed 412 of 696 request(s) as claude-sonnet-4-6.
Same requests, same cache hits; only the price per token changes.
```

`--scope main|subagents` limits the swap to the main thread or to subagent
requests. `--token-scale 1.3` multiplies token counts, for a target model whose
tokenizer emits more tokens for the same text (Anthropic documents about 30%
more for Claude 4.7 and later).

A model swap holds the work fixed: the same requests with the same contents and
the same cache hits, priced at different rates. A different model would have
taken a different path, so treat the result as the price of the work you
actually did, not a forecast.

## See where the cache missed

```console
$ rebill timeline 7f3c
session 7f3c2a10 (claude-code) /home/dev/shop

[main]
time         gap  kind           prompt     read    write     out      cost  model
09:00:04       -  first           18.0k        0    18.0k     310     $0.19  claude-opus-4-5-20251101
09:00:12      8s  hit             20.5k    18.0k     2.5k     120     $0.04  claude-opus-4-5-20251101
09:14:40   14.5m  idle-rebuild    21.1k        0    21.0k      95     $0.21  claude-opus-4-5-20251101
...
```

Each request is compared with the previous one in the same thread (main or a
given subagent): a `hit` read back what was cached, an `idle-rebuild` missed
because the gap outlived the cache lifetime, a `model-switch` missed because
caches don't carry across models, and a `rebuild` missed for another reason
such as compaction.

## Replay a different cache lifetime

```console
$ rebill whatif --cache-ttl 1h
```

With a longer lifetime, an idle rebuild whose gap fits inside it reads back what
the previous request had cached instead of writing it again; with a shorter one,
a hit after a long gap becomes a write. Every write is billed at the new
lifetime's rate (Anthropic charges 1.25x input for 5-minute writes and 2x for
1-hour ones), so a longer cache only pays off when you actually pause between
requests. `--cache-ttl` and `--model` can be combined.

## Cap tool output

```console
$ rebill whatif --cap-tool-output 4000
```

A large tool result (a full file read, a long test log) is written to the cache
once and then read back by every later request in the thread until the
conversation is compacted. `--cap-tool-output N` replays the thread as if each
result had been cut to N tokens and removes the excess from all of those
requests. It works on Claude Code, Codex, OpenCode and Gemini CLI transcripts.

Result sizes start as a text estimate (four characters per token) and are then
corrected per session: in a tool loop the real prompt grows by about the previous
response plus the tool output, so the median ratio of real growth to estimated
size over a session's tool steps gives its correction factor (`rebill timeline`
prints it). On one real OpenCode history of 350 sessions the factor was 1.18
(quartiles 1.10 to 1.29). The replay doesn't add the requests an agent might make
to recover truncated output, so read the saving as an upper bound.

Because the sizes are estimates, the what-if also prints a range: the same replay
with each session's 25th and 75th percentile ratio in place of its median. A
session with fewer than three usable tool steps can't be calibrated; its sizes
are used as estimated, and the output says how many such sessions there were.

```console
Range: $36.90 to $38.71, with tool-output sizes from the 25th to the 75th percentile of each calibration.
```

## Compact earlier

```console
$ rebill whatif --compact-at 60k
total  reqs  recorded  what-if  change      %
total  9417    $39.73   $38.14  -$1.58  -4.0%

What-if: compaction at 60,000 prompt tokens. ...
Range: $37.61 to $39.19, with summaries of 2,000 to 8,000 tokens.
Replayed 85 compaction(s), each adding a summary request of 4,000 output tokens.
```

Every request in a long thread re-sends the whole history, mostly as cache
reads, so a thread that runs to 300k tokens pays for that history on each
turn. `--compact-at N` replays each thread with a compaction whenever its prompt
would pass N tokens:

- a summary request is added, which re-sends the history (from the cache when
  it is still warm, uncached when it had expired) and writes a summary of
  `--summary-tokens` (default 4k);
- the request restarts from the thread's opening prompt (system prompt, tools,
  first message) plus the summary plus what was new in it, written to the cache;
- every later request carries the shorter history forward.

Compacting too often costs more than it saves: on the history above a 20k
threshold was 27% more expensive, 60k saved 4% and 100k saved 1.7%. How long
the agent's summaries really are is a guess, so the range printed under the
result replays half and double `--summary-tokens`. Only
compacting earlier than the agent did can be replayed (compactions it really did
are kept), and the re-reads an agent makes after losing detail to a summary are
not modelled.

## Price fast mode, batch and US-only inference

Requests are billed in the mode they were served in, when the transcript says:
Claude Code records `speed` (`/fast`), `service_tier` and `inference_geo` with
every response, and Codex records its service tier (`priority` in fast mode, or
`flex`) whenever the thread's settings change. OpenCode records neither.

```console
$ rebill bill --by mode
mode      reqs  input  cache rd  cache wr  output   cost
--------  ----  -----  --------  --------  ------  -----
fast         4    800    190.0k     20.0k    6.0k  $0.52
standard     2    400    125.0k     10.0k    3.0k  $0.14
$ rebill whatif --mode standard
total  reqs  recorded  what-if  change       %
-----  ----  --------  -------  ------  ------
total     6     $0.66    $0.40  -$0.26  -39.6%
```

`--mode` (`standard`, `batch`, `flex`, `priority`, `fast`, `ultrafast`) and `--geo` (`us`, or
`global` for default routing) bill every request that way with the same tokens;
both work as `compare` settings too (`--sweep mode=standard,fast`). The Codex tier
is the one Codex asked for; the rollout doesn't say which one OpenAI served.

## Compare several setups at once

`rebill compare` bills the recorded sessions once and then each scenario, one
row per scenario. Sweep a setting:

```console
$ rebill compare --sweep compact-at=20k,40k,60k,100k
scenario          reqs    cost   change       %
---------------  -----  ------  -------  ------
recorded          9417  $39.73
compact-at=20k   11116  $50.37  +$10.65  +26.8%  1699 compactions
compact-at=40k    9716  $37.85   -$1.88   -4.7%  299 compactions, cheapest
compact-at=60k    9502  $38.14   -$1.58   -4.0%  85 compactions
compact-at=100k   9437  $39.05   -$0.67   -1.7%  20 compactions
```

or describe scenarios in a TOML file, each starting from an optional `[base]`:

```toml
[base]
cache_ttl = "1h"

[scenario.sonnet-main]
model = "claude-sonnet-4-6"
scope = "main"

[scenario.tight]
compact_at = "60k"
cap_tool_output = "4k"
```

```console
$ rebill compare --policies setups.toml --sweep summary-tokens=2k,8k
```

Settings are the `whatif` options (`model`, `only_model`, `scope`, `token_scale`,
`cache_ttl`, `cap_tool_output`, `compact_at`, `summary_tokens`, `mode`, `geo`); dashes and
underscores both work. Repeated `--sweep` flags are crossed with each other and
with every scenario in the file. Within a scenario the policies always apply in
the same order: tool-output cap, compaction, cache lifetime, model, mode and geo.

## Write a report for a pull request or wiki

```console
$ rebill report --since 2026-11-01 > cost.md
$ rebill report --compact-at 60k --format html -o compact-60k.html
```

`rebill report` writes the bill as Markdown (default) or one self-contained HTML
page with no scripts or external files. It opens with a summary, then a table
of the most expensive sessions (`--top`, default 20; `0` for all), and under it
one collapsible `<details>` section per session with its tokens and cost by
model. GitHub and GitLab render those sections in issues, pull requests and
wikis.

It takes every `whatif` option. With one, each session and model shows both
costs, the summary says what was held fixed, and a what-if that rests on
estimates gets a range for the total and for each session:

```markdown
## What-if report

212 session(s), 9,417 request(s), $39.73 at list prices as of 2026-12-03.
What-if (compaction at 60,000 prompt tokens): $38.14, -$1.58 (-4.0%).
Range $37.61 to $39.19, with summaries of 2,000 to 8,000 tokens.
```

Session start times are in UTC. Session ids and working directories appear as
written in the transcripts, so check a report before posting it somewhere
public.

## Fail CI when sessions got more expensive

```console
$ rebill gate runs/before runs/after --max-increase 10
        sessions  requests    cost  mean per session
before        12       341   $4.18             $0.35
after         12       366   $5.07             $0.42

Change in mean cost per session: +21.3% (90% interval +6.0% to +38.2%); limit +10%.

FAIL: cost per session rose past +10%.
```

Run the same tasks before and after a change (a new system prompt, another
model, a different tool setup), keep both sets of transcripts, and `rebill gate`
prices them with the same table and compares cost per session. It exits 1 when
the increase passes `--max-increase` (in percent, default 10) and 0 otherwise.

- Session costs are skewed and CI samples are small, so the gate also prints a
  90% bootstrap interval for the change, with a fixed seed so reruns agree.
  `--confident` fails only when the low end of the interval passes the limit.
- `--metric median` ignores one runaway session; `--per request` compares cost
  per request instead of per session.
- It exits 2 (can't judge) when a set is empty, has fewer than `--min-sessions`
  (default 3), or has requests on a model with no price, which would otherwise
  count as free and make a switch to an unknown model look cheaper.
  `--allow-unpriced` overrides that last check.
- `--by model` or `--by agent` adds a table of where the mean cost per session
  moved: each model's (or agent's) cost on each side divided by that side's
  session count, so the rows add up to the change in the mean.
- `--format markdown` writes a table for a job summary; `--json` for scripts.
- When both sides live in one store, `--before-since`, `--before-until`,
  `--after-since` and `--after-until` narrow each side to a range of UTC days, so
  two days in OpenCode's database can be compared in place.

```yaml
- run: pip install rebill
- run: rebill gate baseline/ runs/ --confident --format markdown >> "$GITHUB_STEP_SUMMARY"
```

## How it counts

- **One request, one bill.** Claude Code writes a JSONL line per content block
  and repeats the response's usage on each, so summing lines overcounts by the
  number of blocks. Requests are keyed by `message.id` and merged. Codex repeats
  `token_count` frames; a frame only counts when the running total moved.
- **Disjoint buckets.** Every request is stored as uncached input, cache reads,
  cache writes per lifetime (`5m`, `1h`, `30m`, `12h`) and output. OpenAI's
  `input_tokens` includes its cached tokens and cache writes, so the Codex reader
  splits both out (writes as 30-minute ones, OpenAI's default); Gemini's
  prompt count includes its cached tokens and leaves out thinking tokens, which
  are billed as output.
- **Totals where that's all there is.** Copilot CLI only writes per-model session
  totals (at shutdown), not each request. Those bill and swap models fine, with
  the long-context tier chosen from the average prompt, but cache, compaction and
  tool-output replays leave them as recorded. Copilot plans bill premium
  requests; rebill shows what the tokens cost at API list prices.
- **Billed means billed.** A Gemini CLI rewind hides messages from the
  conversation, but those requests were made and paid for, so they stay.
- **Tiers per request.** Long-context rates (Anthropic's 200k and 100k lines,
  OpenAI's 272k) are chosen per request from its whole prompt, cache reads and
  writes included, the way the providers bill them.
- **Dated prices.** A model's price can change on a date; each request is priced
  with the period in force when it was made.
- **Served how, and where.** A request run in batch, flex, priority, fast or ultrafast mode,
  or pinned to US-only inference, is priced that way when the transcript says so.
  Fast and ultrafast have their own per-model rates (cache multipliers on top);
  Anthropic and OpenAI batch and flex are half price on every bucket, while Gemini
  lists batch, flex and priority per model (batch and flex often halve input and
  output but keep the standard cache price; priority is listed at 1.8x standard);
  Anthropic's US-only inference is
  1.1x on top of everything. A mode with no listed price for that model is priced
  at standard with a note, not guessed.
- **Peak and off-peak.** DeepSeek bills half price outside peak hours (01:00-04:00
  and 06:00-10:00 UTC, Monday to Friday, except Chinese public holidays). Its
  entries in the price table list the peak prices as standard and the off-peak
  prices as an `off-peak` mode, with a `schedule` that picks between them from
  the request's UTC time. The holiday list covers 2026 and 2027; after that, a
  request in a peak window is priced at peak with a note. A request with no
  timestamp is priced at peak, with a note.
- **DeepSeek Harness.** dsh stores one log per session under
  `~/.dsh/sessions/<project>/<session>/`, compressed with Zstandard by default.
  Requests come from `assistant/message` usage (or the last usage chunk in its
  embedded stream), from `assistant/attempt` for failed or retried attempts, and
  from `compaction/summary`. A repeat of the same step replaces the earlier
  sample unless `llm/retry-started` came between them, in which case the retry
  adds a request, the same way dsh's token meter counts. History a fork copied
  from its parent is skipped. Only the newest log format generation in a session
  directory is read.
- **No silent zeros.** A request on a model with no price is counted and flagged,
  never billed as $0. Add prices with `--prices my-prices.json`; the file uses the
  same format as [the bundled table](src/rebill/data/prices.json) and wins over it.
- **Checked against the agent.** When a transcript records its own cost, `rebill`
  prices the same requests and prints the gap.

`rebill prices [MODEL]` prints the table in use.

The bundled table is checked against the providers' published pricing pages by
`scripts/check_prices.py`, weekly in CI and by hand before a release. It reads
the Markdown version of each page, compares standard, long-context, fast and
ultrafast prices, Gemini's batch and flex prices, and the batch and flex
multipliers model by model, and prints
what differs with the page it came from. `--apply` writes the differing prices
into the table, so an update is an ordinary diff to review; new models and
announced future prices are listed for a person to decide on.

## Check prices against what the agent recorded

OpenCode (and older Claude Code) store a dollar cost per request. `rebill check`
compares it with the list price per model and lists the requests that disagree
most. For a model with no list price, such as a self-hosted or resold one, it
solves the recorded costs for the per-token rates the agent was using:

```console
$ rebill check --infer-prices my-prices.json
glm-5.3: 457 request(s), agent recorded $8.11; no price here.
    implied $/MTok: input 1.4  output 4.4  cache_read 0.26 (fits recorded total within 0.00%)

Wrote inferred prices for unpriced models to my-prices.json.
$ rebill bill --prices my-prices.json
```

A bucket that never appears in the recorded requests is left out of the inferred
price rather than set to zero.

## Log your own SDK calls

Scripts and apps that call the Anthropic, OpenAI or Google GenAI SDKs leave no
transcript, so `rebill` ships a small opt-in recorder. Wrap a client and every
`create`, `parse` or `generate_content` result appends one JSON line with the
model, the response id, the service tier and the provider's raw `usage`:

```python
import anthropic
from rebill.record import recording

client = recording(anthropic.Anthropic(), session="nightly-triage")
client.messages.create(model="claude-opus-5-5", max_tokens=1024, messages=[...])
```

Or record one response: `rebill.record.record(response, session="...")`. Lines go
to `$REBILL_LOG` if set, else `~/.rebill/requests/<date>.jsonl`, and `rebill bill`
reads them along with the agents' transcripts. Prompts and outputs are never
written, and the SDKs are not dependencies.

Async clients and streams are recorded too. A `stream=True` call or
`generate_content_stream` is handed back as is and logged once, when it ends or
is closed, with the usage the stream reported up to then. OpenAI's Chat
Completions streams only report usage when asked
(`stream_options={"include_usage": True}`). The `.stream()` helpers aren't
wrapped; record their final message (`record(stream.get_final_message())`).
Pass `thread="..."` for a subagent so it bills as a sidechain.

Gemini calls are billed in the tier that served them. Google returns it in an
`x-gemini-service-tier` response header, which the GenAI SDK keeps on
`response.sdk_http_response.headers`; the recorder logs it as `service_tier`,
and the tier the call asked for (`config=GenerateContentConfig(service_tier=...)`)
as `requested_service_tier`. A line with no served tier is billed in the
requested one. That is exact for Flex, which Google never moves to another
tier, but a Priority request can be served, and billed, at Standard when Google
is congested, so those lines are billed as Priority with a warning. When you
call `record()` yourself, pass the tier you asked for as `requested_tier=`.

Calls on Google's Interactions API (`client.interactions.create`, streamed or
not) are read too. Their response has a `service_tier` field rather than the
header, and the recorder takes it as the served tier.

## Known assumptions

Some transcripts leave out a detail the bill depends on. Where they do, `rebill`
assumes the following. Each is checked against the agent's source, not yet
against logs from many users; a transcript that shows otherwise is a bug report
we want.

- **Codex cache writes are 30-minute writes.** The rollout records how many
  tokens were written to the cache but not the lifetime requested; 30 minutes is
  OpenAI's default.
- **Copilot CLI cache writes are 5-minute writes.** Its shutdown totals count
  cache writes without saying which lifetime; 5 minutes is the common default.
- **The last Copilot CLI shutdown covers the whole session.** A resumed session
  writes another `session.shutdown`; its per-model totals are read as cumulative,
  so only the last one counts. A reply on the Copilot CLI tracker says usage survives a
  resume, but at least one other tool reads each shutdown as covering only the
  time since the last resume. If that's right, resumed sessions are undercounted
  here; a resumed `events.jsonl` with its counts would settle it.
- **Gemini's output count leaves thinking tokens out.** Thinking tokens are added
  to output unless the recorded total shows they were already in it.
- **A Gemini SDK call without the tier header ran in the tier it asked for.**
  Only the header says which tier served a call. Without it, Flex is billed as
  Flex (Google doesn't move Flex requests) and Priority as Priority, with a
  warning, since congestion can serve Priority at Standard prices.
- **A Gemini interaction's `service_tier` is the tier that served it.** Google
  doesn't say whether the field reports the tier used or echoes the one asked
  for. An agent interaction that ran several model steps is billed as one
  request on its total tokens, so its long-context tier is judged on the total.
- **SDK logs say which provider.** When a line has no `provider`, it's guessed
  from the shape of `usage`.

## How this differs from usage trackers

Tools such as ccusage, tokscale and toktrack aggregate what sessions cost across
many agents and are the right choice for a daily spend view. Single-purpose
analyzers flag wasteful turns or simulate one compaction setting. `rebill` is a
library and CLI built around one model of a request (its buckets, tiers, cache
lifetimes and timing) so that any policy can be replayed against your history
and priced in dollars with the rules each provider actually applies.

## Library use

```python
from rebill.importers import load_any
from rebill.bill import compare
from rebill.policies import SwapModel
from rebill.pricing import PriceBook

sessions = load_any().sessions
rows, total = compare(sessions, PriceBook.default(), SwapModel("claude-sonnet-4-6"), group="day")
print(f"{total.change_pct:+.1f}%")
```

## Scripting against the output

Every command that takes `--json` prints a versioned document (`"format": 1`)
whose fields are listed in [docs/json.md](docs/json.md) and pinned by tests;
fields are only added within a format. Changes are in [CHANGELOG.md](CHANGELOG.md).

## License

MIT
