---
name: cusage
description: Write, check, test and price usage-based pricing as cusage .usage schemas (usage events, meters, metrics, plans, limits, tests) with the `cusage` compiler CLI, and generate typed Python, Go and TypeScript clients. Use when someone wants to model or change usage-based pricing, edit or debug a .usage file, find out what some usage costs on a plan, run or fix schema tests, or generate a cusage client. Installs the CLI from the livesession/cusage GitHub release when it isn't on PATH.
---

# cusage

cusage is a compiled language for usage-based billing. One `.usage` file declares the usage
events a product sends (`struct`), closed sets of values (`type`), rate tables, meters (how
events add up), metrics (formulas over meters), plans (prices and limits) and tests (made-up
months and the numbers they must produce). The `cusage` CLI compiles it: names, types and units
are checked, every rate table must price every value, and money is exact (18 decimal places,
never floats).

## 1. Make sure the CLI is there

```bash
cusage --version
```

If that fails, install it:

- **Inside the cusage repository** (it has `crates/usage-cli/`): `cargo build --release -p usage-cli`,
  then use `./target/release/cusage`.
- **Anywhere else** (macOS or Linux), install the latest release. It downloads `cusage` and
  `usage-server` for this machine, checks the SHA-256 and puts them in `~/.local/bin`:

```bash
set -euo pipefail
REPO="${CUSAGE_REPO:-livesession/cusage}"
DIR="${CUSAGE_INSTALL_DIR:-$HOME/.local/bin}"
case "$(uname -s)-$(uname -m)" in
  Darwin-arm64)              TARGET=aarch64-apple-darwin ;;
  Darwin-x86_64)             TARGET=x86_64-apple-darwin ;;
  Linux-x86_64)              TARGET=x86_64-unknown-linux-musl ;;
  Linux-aarch64|Linux-arm64) TARGET=aarch64-unknown-linux-musl ;;
  *) echo "No cusage build for $(uname -s) $(uname -m): build it from the repository with cargo." >&2; exit 1 ;;
esac
ASSET="cusage-$TARGET.tar.gz"
TMP="$(mktemp -d)"
# gh works for private repositories too; curl only for public ones.
if command -v gh >/dev/null && gh auth status >/dev/null 2>&1; then
  gh release download --repo "$REPO" --pattern "$ASSET" --pattern "$ASSET.sha256" --dir "$TMP"
else
  curl -fsSL "https://github.com/$REPO/releases/latest/download/$ASSET" -o "$TMP/$ASSET"
  curl -fsSL "https://github.com/$REPO/releases/latest/download/$ASSET.sha256" -o "$TMP/$ASSET.sha256"
fi
cd "$TMP"
if command -v sha256sum >/dev/null; then sha256sum -c "$ASSET.sha256"; else shasum -a 256 -c "$ASSET.sha256"; fi
tar -xzf "$ASSET"
mkdir -p "$DIR"
install -m 755 "cusage-$TARGET/cusage" "cusage-$TARGET/usage-server" "$DIR/"
"$DIR/cusage" --version
case ":$PATH:" in *":$DIR:"*) ;; *) echo "Note: $DIR is not on PATH; call $DIR/cusage, or add it to PATH." ;; esac
```

If `curl` gets a 404, the repository is private: sign in with `gh auth login` (an account with
access to the repository) and run it again. On Windows, download
`cusage-x86_64-pc-windows-msvc.zip` from the latest release
(`gh release download --repo livesession/cusage --pattern "*windows*"`) and put `cusage.exe` on PATH.

## 2. How to work on a schema

```bash
cusage check pricing.usage      # names, types and units; errors like rustc's, with a hint
cusage test pricing.usage       # every test block's expectations
cusage scenarios pricing.usage  # each test priced on every plan, as JSON (invoice lines, limits)
cusage info pricing.usage       # the compiled schema as JSON
```

- After every edit run `cusage check`, then `cusage test`. A schema isn't done until both pass.
  `cusage check pricing.usage --json` gives the diagnostics as JSON.
- Never work out a price by hand. To answer "what would this cost", write the usage as a
  `test` (events, and the plan), run `cusage scenarios`, and read the invoice from the JSON; or
  write the expected total as an `expect` and run `cusage test`.
- When prices change, update the tests' expected totals in the same change, and say which
  invoices moved and by how much (`cusage scenarios` before and after).
- Fix errors with the compiler's hint; it usually names the missing rate, the right unit or
  the field that was meant.

## 3. The language

A complete schema (it compiles and its tests pass):

```
unit token, credit, seat
currency USD

/** The models we sell: every rate table has to price each one. */
type Model = "gpt-4o" | "small"

/** One LLM call: the usage event a service sends. */
struct llm_call {
    model: Model
    input_tokens: int<token>
    output_tokens: int<token>
    /** Prompt-cache hit: billed at 10%. */
    cached: bool = false
    user_id: string
}

table input_rate[Model]: credit/token {
    "gpt-4o": 0.0025
    "small": 0.0002
}

table output_rate[Model]: credit/token {
    "gpt-4o": 0.01
    "small": 0.0008
}

meter credits: credit = sum(
    (input_tokens * input_rate[model] + output_tokens * output_rate[model]) * (cached ? 0.1 : 1)
) from llm_call by model

meter seats: seat = count_distinct(user_id) from llm_call

/** The first 1,000 credits each month are free. */
metric billable_credits: credit = max(credits - 1000 credit, 0 credit)

plan starter "Starter" {
    charge billable_credits "AI credits" { price 0.002 USD/credit }
    charge seats "Seats" { price 8 USD/seat }
    limit credits 200000 credit per month
}

plan team "Team" {
    fee "Team plan" 49 USD
    charge credits "AI credits" {
        included 50000 credit
        tiered graduated {
            up to 500000 credit at 0.0015 USD/credit
            above at 0.001 USD/credit
        }
    }
    charge seats "Seats" { price 5 USD/seat }
    minimum 99 USD
}

test "a small month on starter" {
    plan starter
    events {
        llm_call { model: "gpt-4o", input_tokens: 12000, output_tokens: 3000, user_id: "ana" } x 40
        llm_call { model: "small", input_tokens: 2000, output_tokens: 500, user_id: "ben" } x 200
    }
    expect credits == 2560 credit
    expect seats == 2 seat
    expect charge billable_credits == 3.12 USD
    expect total == 19.12 USD
}

test "a quiet month on team is topped up to the minimum" {
    plan team
    events {
        llm_call { model: "small", input_tokens: 2000, output_tokens: 500, user_id: "cy" } x 100
    }
    expect subtotal == 54 USD
    expect total == 99 USD
}
```

| Declaration | Form | Notes |
|---|---|---|
| `unit` | `unit token, credit, seat` | Units numbers carry. Checked like dimensions: `credit/token × token` is `credit`. A bare `0` fits any unit. |
| `currency` | `currency USD`, `currency JPY(0)` | The money unit; `(n)` sets its minor units (default 2). |
| `type` | `type Model = "a" \| "b"` | A closed set of string values; an enum in generated clients. |
| `struct` | `struct name { field: type }` | A usage event. Field types: `int`, `decimal`, `string`, `bool` or a declared `type`; units as `int<token>`, `decimal<GB>`; defaults as `= value` (optional in clients). |
| `table` | `table rate[Model]: credit/token { "a": 0.5  default: 1 }` | Rates keyed by a type. Every value needs a rate, or a `default`. |
| `meter` | `meter m: unit = agg(expr) from s [where cond] [by field]` | `sum`, `count()`, `count_distinct(field)`, `max`, `min`, `avg`, `latest`. `from a \| b` or `from *` reads several structs. `by` breaks the result down. |
| `metric` | `metric m: unit = expr` | A formula over meters; `max(a, b)` and `min(a, b)` work here. |
| `plan` | `plan name "Label" { ... }` | `fee "label" 49 USD`, `charge`, `minimum 99 USD` (the invoice is topped up to it), `limit`. |
| `charge` | `charge q "Label" { ... }` | `price 0.002 USD/credit`; `package 1000 request at 0.40 USD` (per started package); `tiered graduated { up to N unit at R; above at R }` (each tier its own rate) or `tiered volume { ... }` (all units at the rate of the tier the total lands in); `included N unit` (free first); `minimum`, `maximum` per charge. |
| `limit` | `limit q 600 request per minute` | Per `minute`, `hour`, `day` or `month` (UTC calendar windows); without `per`, over the whole history. Enforced when services reserve before the work; recorded usage is never refused. |
| `test` | `test "name" { plan p  events { s { f: v } x N }  expect ... }` | `expect q == N unit`, `expect charge q == X USD`, `expect total == X USD`, `expect subtotal == X USD`. `x N` repeats an event cheaply (it weights, it doesn't copy). |

Expressions: `+ - * /`, `== != < <= > >=`, `&& || !`, `cond ? a : b`, `field in ["a", "b"]`,
`table[field]`, and numbers with units (`10 GB`, `0.002 USD/credit`). Comments are `//` and
`/* */`; `/** */` before a declaration is its doc, which clients and tools show.

Money: each invoice line is rounded to the currency's minor units, half away from zero; the
total is the sum of the rounded lines, then the plan minimum.

## 4. Errors you will see

| Compiler says | Fix |
|---|---|
| ``cannot add `credit` and `seat` `` | Both sides need the same unit; convert one with a rate (`seats * 10 credit/seat`). |
| ``table `input_rate` has no rate for "small"`` | Add the value to the table, or a `default: N` line. |
| ``price of `credits` must be in `USD/credit`, got `USD` `` | Price per unit of what the charge counts: `price 0.002 USD/credit`. |
| ``unknown field `user_idd` on `activity` `` (hint: did you mean `user_id`?) | Use the field the hint names. |
| `expected a declaration (unit, currency, type, struct, table, meter, metric, plan or test), found ...` | Stray text at the top level, or a missing `}` above it. |
| `test has no expectations` (a warning) | Add at least `expect total == ... USD`. |
| A failing test: `total: expected 19 USD, got 19.12 USD` | Either the expectation or the pricing is wrong; check which with `cusage scenarios`. |

## 5. Clients and servers

```bash
cusage gen-client pricing.usage --lang ts     --out usage.ts               # also writes usage.proto next to it
cusage gen-client pricing.usage --lang python --out usage_client.py
cusage gen-client pricing.usage --lang go     --out usage/usage.go --package usage
usage-server pricing.usage --addr 127.0.0.1:50051   # gRPC; refuses to start if a test fails
```

Clients get a method per struct and the schema's types and plans as types, so a value the
schema doesn't allow fails before anything is sent. They talk to one gRPC API
(`usage.v1.UsageService`: Ingest, GetUsage, GetInvoice, CheckLimits, Reserve, Commit,
Estimate...) that doesn't change when the schema does. Quotas: `reserve` before the work and
`commit` after (exact), or a `limiter` with leases (fast); a refused reservation raises
`QuotaExceeded` with the blocking limits and `retry_at`.

## 6. Good habits

- One struct per kind of event, named for what happened (`llm_call`, `message_sent`); fields
  carry units (`int<token>`, `decimal<GB>`) so the compiler can check every formula.
- Closed sets (`type`) for anything a rate depends on: models, countries, sizes.
- Meters count, metrics derive, plans price. Put allowances in metrics (`max(x - 1000 credit, 0 credit)`)
  or in `included`, not in the events.
- Keep at least one test per plan, with `expect total`, so a pricing change shows which invoices moved.
- Names in `snake_case`, types in `PascalCase`, plan labels in quotes (`plan pro "Pro"`).
