Skip to content

Commit 1322e4c

Browse files
jay-tauCopilot
andcommitted
feat(adapter/copilot): add --mode credits for GitHub AI Credits
After June 1, 2026 GitHub Copilot bills usage in AI Credits at $0.01/credit instead of premium-request multipliers. The Copilot CLI already reports `totalNanoAiu` (nano AI Units = 10^-9 credits) per `session.shutdown` event. This adds `--mode credits` as a fourth global cost mode that bills directly from the credit counts Copilot ships, bypassing LiteLLM token pricing. Newer Copilot model variants that aren't yet in the LiteLLM dataset now report correct cost in credits mode. Cross-crate scope (per plan ccusage#1174) * `CostMode::Credits` added to `ccusage-cli/src/types.rs:171`, parsed by `parse_cost_mode` and surfaced in `--mode` choices alongside the existing trio. * `ConfigCostMode::Credits` added to `config_schema.rs:466` + `From` impl at `config.rs:459-464`. Regenerated `apps/ccusage/config-schema.json` (snapshot accepted). * `cost.rs::calculate_cost_for_usage` has a new `Credits` arm that falls back to `Auto` semantics, used by non-Copilot adapters; they have no credit channel so token pricing remains the right answer when a user passes `--mode credits` to a non-Copilot report. * `gemini`, `kilo`, `kimi` exhaustive `match mode` sites updated to the same fall-back behavior. Copilot loader * Per-model `totalNanoAiu` and aggregate `data.totalNanoAiu` parsed from session-state shutdowns and surfaced as `CopilotUsageEntry.nano_aiu`. * `LoadedEntry.credits` populated from `nano_aiu / 1e9` regardless of selected mode, so JSON output always carries the raw credit count. * In `Credits` mode, `LoadedEntry.cost = credits × $0.01` and the Copilot-local `missing_pricing_model_for_usage` call is suppressed - api-equivalent pricing is irrelevant in this mode. The suppression is Copilot-local rather than global in `cost.rs` to avoid hiding legitimate missing-pricing warnings for other adapters whose `--mode credits` falls back to `Auto`. Empirical fixes (plan rounds 12-15) * Skip rule relaxed: zero-token zero-request rows are now kept when `metrics.totalNanoAiu > 0`. Real local data has 4 such credit-only rows in `1135875b-...` and `76dc438a-...` (~$5.30 total) that would otherwise be silently dropped. * Content-based dedup key (`credit-shutdown:{session}:{model}:{naiu}`) for credit-only rows. The 4 real-data rows are actually 2 unique snapshots x 2 duplicates each (identical event-IDs would have produced $2.65 of inflation under the plain `shutdown:{event.id}:{model}` key); the content-based key collapses exact duplicates via the loader-side HashMap dedup added in Piece A. * Synthetic aggregate-only credit entry (forward-compat guard) emits when `data.totalNanoAiu` is non-null but no per-model row carries it. Not observed in 200-file local corpus today; suppressed when per-model AIU is also present so we never double-count. Tests * 13 new parser tests cover `totalNanoAiu` parsing, credit-only row retention, content-based dedup, token-bearing event-id stability, aggregate-only synthetic entries, and pre-AIU legacy schema returning `None`. * 5 new loader tests cover end-to-end `--mode credits` cost math, credit-only row carrying $1.54 from real-data sample, duplicate-row collapse to one entry, `Auto` mode still using token pricing when AIU is present, and aggregate-only synthetic entry billing. Docs * `docs/guide/cost-modes.md`: new `credits` section with how-it-works, example output, and explicit non-Copilot fallback semantics. * `docs/guide/cli-options.md`: cross-link to cost-modes for the new mode. * `docs/guide/copilot/index.md`: new 'Pricing modes' section explaining the credit math and skip-rule relaxation. Smoke test on real local data (73 days, 7.56B tokens, 23 unique models): Credits-mode: $5,003.02 total, 500,302.25 credits aggregated. Auto-mode (Piece A baseline): $6,577.77 api-equivalent. Pieces A (events.jsonl reader) and B (credits mode) are now both shipped. Piece C (`--mode api-equiv` alias) remains optional per the plan. Refs ccusage#1174 Co-authored-by: Copilot <[email protected]>
1 parent 4c2f433 commit 1322e4c

18 files changed

Lines changed: 1555 additions & 191 deletions

File tree

‎apps/ccusage/config-schema.json‎

Lines changed: 746 additions & 148 deletions
Large diffs are not rendered by default.

‎docs/guide/cli-options.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,13 @@ ccusage daily --mode calculate
5151

5252
# Display mode - only show pre-calculated costUSD
5353
ccusage daily --mode display
54+
55+
# Credits mode (Copilot-specific) - bill from GitHub Copilot AI Credits
56+
ccusage copilot daily --mode credits
5457
```
5558

59+
See [Cost Modes](/guide/cost-modes) for a full breakdown of each mode.
60+
5661
### Sort Order
5762

5863
Control the ordering of results:

‎docs/guide/copilot/index.md‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,29 @@ Without these variables, ccusage relies on the session-state source — which is
6666

6767
These views support `--json` for structured output, `--compact` for narrow terminals, and `--offline` for cached pricing data.
6868

69+
## Pricing modes
70+
71+
`ccusage copilot` supports the standard cost modes (`auto`, `calculate`, `display`) plus a Copilot-specific `credits` mode:
72+
73+
```bash
74+
# Default: API-equivalent cost from LiteLLM token pricing.
75+
ccusage copilot daily
76+
77+
# Credits mode: bill from GitHub Copilot's AI Credit counts ($0.01/credit).
78+
ccusage copilot daily --mode credits
79+
```
80+
81+
In credits mode, ccusage reads `totalNanoAiu` from each `session.shutdown` event and converts directly to USD (`credits × $0.01`). No LiteLLM token pricing lookup happens, so newer Copilot model variants that aren't yet in the LiteLLM dataset still report correct cost. The `credits` field is also exposed in `--json` output regardless of the selected mode, so you can run with `--mode auto` and still see the raw credit counts.
82+
83+
Credit-only `session.shutdown` rows (zero tokens, zero requests, non-null `totalNanoAiu`) are kept even when the default skip rule would otherwise discard them. Identical duplicate credit-only snapshots within the same session are collapsed via content-based deduplication.
84+
6985
## What Gets Calculated
7086

7187
- **Token usage** — for session-state, `inputTokens` in the source schema already includes both cache reads and cache writes, so ccusage subtracts both to recover the "fresh" input bucket. For OTel, chat spans are preferred with inference logs and agent-turn logs as fallbacks.
7288
- **Cache tokens** — cache read and cache creation token attributes are counted from `cacheReadTokens` / `cacheWriteTokens` (session-state) or the corresponding `gen_ai.usage.cache_*` attributes (OTel).
7389
- **Reasoning tokens** — provider-dependent. For OpenAI (`gpt-*`) and Anthropic (`claude-*`) models reasoning is already inside `outputTokens` and is not double-counted. For Google (`gemini-*`) models reasoning is reported separately and is summed into the output cost bucket.
74-
- **Pricing** — costs are calculated from LiteLLM pricing data using a normalized form of the model name. The raw name (e.g. `claude-opus-4.7-1m-internal`) is preserved in JSON, the table's `Models` column, and `modelsUsed`.
90+
- **Credits** — when present, `totalNanoAiu` is divided by 10⁹ to get the AI Credit count (`1 credit = $0.01`). Always surfaced in JSON; becomes the primary cost basis under `--mode credits`.
91+
- **Pricing** — for non-credits modes, costs are calculated from LiteLLM pricing data using a normalized form of the model name. The raw name (e.g. `claude-opus-4.7-1m-internal`) is preserved in JSON, the table's `Models` column, and `modelsUsed`.
7592

7693
## Source coexistence (OTel + session-state)
7794

‎docs/guide/cost-modes.md‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Cost Modes
22

3-
ccusage supports three different cost calculation modes to handle various scenarios and data sources. Understanding these modes helps you get the most accurate cost estimates for your usage analysis.
3+
ccusage supports four cost calculation modes to handle various scenarios and data sources. Understanding these modes helps you get the most accurate cost estimates for your usage analysis.
44

55
## Overview
66

@@ -9,6 +9,7 @@ Claude Code stores usage data in JSONL files with both token counts and pre-calc
99
- **`auto`** - Smart mode using the best available data
1010
- **`calculate`** - Always calculate from token counts
1111
- **`display`** - Only show pre-calculated costs
12+
- **`credits`** - Bill from GitHub Copilot's AI Credit counts at `1 credit = $0.01` (Copilot-specific; other adapters fall back to `auto`)
1213

1314
## Mode Details
1415

@@ -117,6 +118,58 @@ ccusage session --mode display --json
117118
└──────────────┴─────────────┴────────┴─────────┴────────────┘
118119
```
119120

121+
### credits (Copilot-specific)
122+
123+
The `credits` mode bills usage from GitHub Copilot's AI Credit counts at the
124+
official `1 credit = $0.01` rate, instead of computing from LiteLLM token
125+
pricing:
126+
127+
```bash
128+
ccusage copilot daily --mode credits
129+
ccusage copilot monthly --mode credits --json
130+
```
131+
132+
#### How it works:
133+
134+
1. **Reads `totalNanoAiu`** from each `session.shutdown` event in
135+
`~/.copilot/session-state/<sessionId>/events.jsonl`.
136+
2. **Converts to USD** using `credits × $0.01` (Copilot's published rate).
137+
3. **No token-based pricing lookup** — the cost is taken directly from the
138+
credit count the CLI itself reported.
139+
4. **Skips the "Missing embedded pricing" warning** even for newer model
140+
variants that aren't yet in LiteLLM, since pricing isn't consulted.
141+
142+
#### Best for:
143+
144+
- ✅ **Copilot CLI billing** — matches what GitHub charges against your AI
145+
Credit allotment.
146+
- ✅ **Newer model variants** — works correctly even when LiteLLM doesn't yet
147+
have an entry for the model.
148+
- ✅ **Aggregate visibility** — the JSON `credits` field reports the raw
149+
credit count alongside `totalCost`.
150+
151+
#### Non-Copilot adapters
152+
153+
`--mode credits` is Copilot-specific. Other adapters (Claude, Codex, Amp, etc.)
154+
do not carry credit counts. When you set `--mode credits` on a non-Copilot
155+
report they fall back to `Auto` semantics — i.e. they continue to compute from
156+
token pricing as if no mode override was set. Cross-source `ccusage all
157+
--mode credits` will use credits for the Copilot rows and tokens for everything
158+
else.
159+
160+
#### Example output:
161+
162+
```
163+
┌──────────────┬──────────────────────────────┬────────┬─────────┬────────────┐
164+
│ Date │ Models │ Input │ Output │ Cost (USD) │
165+
├──────────────┼──────────────────────────────┼────────┼─────────┼────────────┤
166+
│ 2026-05-19 │ • opus-4.7-1m-internal │ 2,944 │ 225,556 │ $10.55 │
167+
└──────────────┴──────────────────────────────┴────────┴─────────┴────────────┘
168+
```
169+
170+
The corresponding JSON row carries `"credits": 1055.18` alongside
171+
`"totalCost": 10.55` so callers can recover the raw credit count.
172+
120173
## Practical Examples
121174

122175
### Scenario 1: Mixed Data Analysis

‎rust/crates/ccusage-cli/src/cli-help.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@
250250
"flags": "-m, --mode [mode]",
251251
"description": "Cost calculation mode",
252252
"default": "auto",
253-
"choices": ["auto", "calculate", "display"]
253+
"choices": ["auto", "calculate", "display", "credits"]
254254
},
255255
{
256256
"flags": "-d, --debug",

‎rust/crates/ccusage-cli/src/help_codegen.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,13 +366,13 @@ mod tests {
366366
"flags": "--mode <MODE>",
367367
"description": "Cost calculation mode",
368368
"default": "auto",
369-
"choices": ["auto", "calculate", "display"]
369+
"choices": ["auto", "calculate", "display", "credits"]
370370
}
371371
]);
372372

373373
let output = render_options(&options);
374374

375375
assert!(output.contains("default: auto"));
376-
assert!(output.contains("choices: auto | calculate | display"));
376+
assert!(output.contains("choices: auto | calculate | display | credits"));
377377
}
378378
}

‎rust/crates/ccusage-cli/src/parser.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,6 +864,7 @@ fn parse_cost_mode(value: &str) -> Result<CostMode, String> {
864864
"auto" => Ok(CostMode::Auto),
865865
"calculate" => Ok(CostMode::Calculate),
866866
"display" => Ok(CostMode::Display),
867+
"credits" => Ok(CostMode::Credits),
867868
_ => Err(format!("Invalid cost mode '{value}'")),
868869
}
869870
}

‎rust/crates/ccusage-cli/src/types.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ pub enum CostMode {
173173
Auto,
174174
Calculate,
175175
Display,
176+
/// Bill from precomputed credit counts (Copilot CLI's AI-credit tracking).
177+
/// Non-Copilot adapters fall back to `Auto` semantics.
178+
Credits,
176179
}
177180

178181
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]

0 commit comments

Comments
 (0)