Skip to content

Commit 2248106

Browse files
ryoppippiigorovh
andauthored
fix(opencode): exclude Claude Agent turns by default in focused reports (#2022)
* fix(opencode): count Claude Agent turns once in `ccusage opencode` Tools that read each source separately, such as tokenmaxxing, add `ccusage claude` and `ccusage opencode` together. Since #2007 only unified reports skipped the OpenCode copy of Claude Agent turns, so those tools still counted every turn twice, once priced from the `opus` alias. `ccusage opencode` now goes through `ccusage_adapter_all::run_opencode` and skips the same rows as the unified report, so the focused reports add up to `ccusage daily`. Claude is read only when a loaded row carries a native Claude session, and an unreadable Claude source counts nothing, so the rows stay. `--include-claude-agent` keeps every row, as before. Refs #2004 * docs(opencode): document Claude Agent turns in `ccusage opencode` Refs #2004 * fix(opencode): match focused session reports by session day `ccusage claude session` counts only the in-window days of a session, while the unified session report keeps a whole session only when its last activity is in the window. Matching focused OpenCode session rows against the unified set kept the rows of a Claude session that ran past `--until`, so `ccusage claude session` and `ccusage opencode session` still counted its in-window turns twice. Focused OpenCode reports now match every report kind by session day, so the two focused session reports add up to the focused daily totals. Refs #2004 * docs(opencode): note session-day matching in `ccusage opencode` Refs #2004 * fix(opencode): load Claude session days without pricing or swallowing errors `ccusage opencode` loads the Claude source only to learn which session days it counts, so it can skip the `claude-agent` turns Claude already reports. That load inherited the caller's cost mode, so in auto or calculate mode it fetched LiteLLM pricing and priced all Claude history just to read session IDs and dates. Force `CostMode::Display` for this load. It also mapped every Claude load error to an empty session set, so a real I/O or parse failure, or an invalid CLAUDE_CONFIG_DIR, silently kept every `claude-agent` row and double-counted them against `ccusage claude`. Missing Claude directories already load as no usage, so the only errors left are real ones; propagate them, matching the unified report. Co-authored-by: igorovh <[email protected]> --------- Co-authored-by: igorovh <[email protected]>
1 parent 2a323ac commit 2248106

16 files changed

Lines changed: 281 additions & 20 deletions

File tree

‎docs/guide/all-reports.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ ccusage detects local usage files from Claude Code, Codex, OpenCode, Amp, Droid,
4646

4747
Unified tables include an **Agent** column so you can compare sources in one view. Focused views remove that comparison layer and show the selected source in more detail where applicable.
4848

49-
When one tool runs another, usage can be logged by both. OpenCode's Claude Agent provider is one example: unified views skip the OpenCode copy of turns that Claude Code's own log has, matching them by session and, in daily views, by day, so a turn that runs across midnight can still be counted twice or partly left out. See [OpenCode](./opencode/#claude-agent-provider).
49+
When one tool runs another, usage can be logged by both. OpenCode's Claude Agent provider is one example: unified views and `ccusage opencode` skip the OpenCode copy of turns that Claude Code's own log has, matching them by session and, in daily views, by day, so a turn that runs across midnight can still be counted twice or partly left out. See [OpenCode](./opencode/#claude-agent-provider).
5050

5151
## Supported Sources
5252

@@ -79,6 +79,7 @@ Use a source namespace when you want source-specific options or when you are deb
7979
ccusage codex daily --speed fast
8080
ccusage claude daily --mode display
8181
ccusage opencode session --json
82+
ccusage opencode daily --include-claude-agent
8283
ccusage amp monthly --compact
8384
ccusage droid session
8485
ccusage codebuff daily

‎docs/guide/opencode/index.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,15 @@ ccusage matches OpenCode rows to Claude usage by Claude Code session, not by ind
7979
- **Daily, weekly, and monthly reports** skip an OpenCode `claude-agent` row when the Claude source counted usage from the same Claude Code session on the row's date, in the Claude source's timezone. Rows still count when the Claude Code log is gone, holds no usage for that day, holds only subagent usage, or falls outside the Claude source's date range.
8080
- **Session reports** match whole Claude Code sessions, because a Claude session row holds all of its usage, including days outside the Claude source's date range. Resumed and forked transcripts repeat earlier turns, and ccusage keeps one copy of each repeated turn. The OpenCode rows of a session whose own main-thread turns survive are skipped when every transcript holding them is included. The rows of a session whose turns all survive under other sessions are skipped only when every transcript holding those copies is included. When all transcripts are included, which one keeps a repeated turn does not affect the total. When the Claude window includes only some of them, a repeated turn can be left out, if a session's rows are skipped while its kept copy is in an excluded transcript, or counted twice, if the turns that decide whether a session's rows are skipped (its own surviving main-thread turns, or its kept copies when it has none) span included and excluded transcripts, since its rows are then kept.
8181

82-
Because OpenCode dates a turn by when it started and Claude Code dates each model call, a turn that runs across midnight can be off in the daily family. It is counted twice when Claude has no usage from that session on the day the turn started. With `--until` on that day, the calls Claude logs after midnight are left out, even though OpenCode dates the whole turn on the earlier day. `ccusage opencode` always shows every `claude-agent` row.
82+
Because OpenCode dates a turn by when it started and Claude Code dates each model call, a turn that runs across midnight can be off in the daily family. It is counted twice when Claude has no usage from that session on the day the turn started. With `--until` on that day, the calls Claude logs after midnight are left out, even though OpenCode dates the whole turn on the earlier day.
83+
84+
`ccusage opencode` skips the rows that `ccusage claude` counts. Every `ccusage opencode` report, session reports included, matches them by Claude Code session and date, because `ccusage claude` counts only usage dated inside its date range. This way the totals of `ccusage claude` and `ccusage opencode` for the same range add up to the matching unified report, such as `ccusage daily`, and tools that read each source separately count these turns once. These turns appear under Claude. Pass `--include-claude-agent` to show every `claude-agent` row in the OpenCode report:
85+
86+
```bash
87+
ccusage opencode daily --include-claude-agent
88+
```
89+
90+
Those rows are priced from the `opus` alias, so their cost can differ from the Claude report.
8391

8492
## Environment Variables
8593

‎rust/adapters/opencode/src/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ SQLite databases are the primary source. Legacy JSON messages under `storage/mes
1616

1717
OpenCode v2 forks copy the parent's `session_message` rows with new ids but the same `seq`. When `session_v2.fork_session_id` and `fork_boundary` resolve against the parent's rows, fork rows at or below the last copied `seq` (the boundary for `through`, the parent's last row before it for `before`) are skipped as inherited history. The fork's `session_v2` counters start at zero and hold only fork-local usage, so they remain a valid session fallback. Unresolvable boundaries and pre-`seq` schemas keep every row.
1818

19-
The Claude Agent provider (`claude-agent`) runs Claude Code, which also writes its own transcript. Its v2 rows record that Claude Code session as `content[].native.sessionID`, which `load_entries_with_native_sessions` returns with each entry. Unified daily-family reports drop a row when the Claude source counted main-thread usage of that session on the row's date, in the Claude source's timezone and date range; session reports match whole sessions, since a Claude session row holds all of its usage, using the session ID the transcript records rather than its file name. A resumed or forked transcript repeats earlier turns, sometimes under the original session ID, and Claude's dedup keeps one copy of each. `should_replace_deduped_entry` prefers main-thread copies, then more tokens, then a copy with speed metadata over one without (the daily loader's `should_replace_deduped_daily_entry` compares cost before speed); only among copies equal on all of these does the first read win, with files sorted by path and named by UUID, so which transcript keeps a turn is effectively arbitrary; when all of them are reported, the choice does not affect the total. A session with surviving main-thread usage under its own recorded ID counts as included when the report includes every transcript holding that usage; copies it lost to other sessions are not consulted. A session with no surviving main-thread usage of its own counts as included when every transcript holding its kept copies is included. When a Claude date window includes only some of the transcripts involved, a repeated turn can go either way: a skipped session's rows for it are dropped although its kept copy is in an excluded transcript, or a session keeps its rows when the usage that decides it (its own surviving main-thread usage, or its kept copies when it has none) spans included and excluded transcripts, so the turns Claude counts in the included transcript are counted twice. The usage is then priced by the resolved model ID rather than the `opus`/`sonnet` alias OpenCode stores. The match is per session or session day, not per turn: `native.messageID` is the transcript line `uuid`, and one OpenCode row sums several API calls, so rows do not map one-to-one to Claude entries. This relies on the transcript holding every main-thread turn OpenCode records for that session; it also holds turns OpenCode drops, such as interrupted steps saved with `tokens: null`. A row is dated by its turn's start while Claude dates each call, so in daily-family reports a turn that crosses midnight in the Claude source's timezone is counted by both sources when Claude has no usage of that session on the earlier day, and with `--until` on that day the calls Claude logs after midnight are left out although OpenCode dates the whole turn on the earlier day. Only v2 `session_message` rows can carry the link: OpenCode added the provider after moving to SQLite v2, so legacy JSON messages and the v1 `message` table hold no `claude-agent` rows. `ccusage opencode` keeps every row.
19+
The Claude Agent provider (`claude-agent`) runs Claude Code, which also writes its own transcript. Its v2 rows record that Claude Code session as `content[].native.sessionID`, which `load_entries_with_native_sessions` returns with each entry. Unified daily-family reports drop a row when the Claude source counted main-thread usage of that session on the row's date, in the Claude source's timezone and date range; session reports match whole sessions, since a Claude session row holds all of its usage, using the session ID the transcript records rather than its file name. A resumed or forked transcript repeats earlier turns, sometimes under the original session ID, and Claude's dedup keeps one copy of each. `should_replace_deduped_entry` prefers main-thread copies, then more tokens, then a copy with speed metadata over one without (the daily loader's `should_replace_deduped_daily_entry` compares cost before speed); only among copies equal on all of these does the first read win, with files sorted by path and named by UUID, so which transcript keeps a turn is effectively arbitrary; when all of them are reported, the choice does not affect the total. A session with surviving main-thread usage under its own recorded ID counts as included when the report includes every transcript holding that usage; copies it lost to other sessions are not consulted. A session with no surviving main-thread usage of its own counts as included when every transcript holding its kept copies is included. When a Claude date window includes only some of the transcripts involved, a repeated turn can go either way: a skipped session's rows for it are dropped although its kept copy is in an excluded transcript, or a session keeps its rows when the usage that decides it (its own surviving main-thread usage, or its kept copies when it has none) spans included and excluded transcripts, so the turns Claude counts in the included transcript are counted twice. The usage is then priced by the resolved model ID rather than the `opus`/`sonnet` alias OpenCode stores. The match is per session or session day, not per turn: `native.messageID` is the transcript line `uuid`, and one OpenCode row sums several API calls, so rows do not map one-to-one to Claude entries. This relies on the transcript holding every main-thread turn OpenCode records for that session; it also holds turns OpenCode drops, such as interrupted steps saved with `tokens: null`. A row is dated by its turn's start while Claude dates each call, so in daily-family reports a turn that crosses midnight in the Claude source's timezone is counted by both sources when Claude has no usage of that session on the earlier day, and with `--until` on that day the calls Claude logs after midnight are left out although OpenCode dates the whole turn on the earlier day. Only v2 `session_message` rows can carry the link: OpenCode added the provider after moving to SQLite v2, so legacy JSON messages and the v1 `message` table hold no `claude-agent` rows. `ccusage opencode` runs through `ccusage_adapter_all::run_opencode`, which matches by session day in every report kind, as `ccusage claude session` counts only in-window days, so focused reports add up to the unified daily one; it reads Claude only when a loaded row carries a native session, treats an unreadable Claude source as counting nothing, and `--include-claude-agent` keeps every row. `opencode::run` keeps every row.
2020

2121
Token mapping:
2222

‎rust/adapters/opencode/src/lib.rs‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,20 @@ pub fn has_data() -> bool {
2525
paths::paths().is_ok_and(|paths| paths.iter().any(|path| loader::has_source(path)))
2626
}
2727

28+
/// Runs the OpenCode report over every row, `claude-agent` turns included.
29+
/// The CLI goes through `ccusage_adapter_all::run_opencode`, which can drop
30+
/// the turns the Claude source already counts.
2831
pub fn run(args: AgentCommandArgs) -> Result<()> {
32+
let entries = loader::load_entries(&args.shared, args.kind)?;
33+
print_report(&args, entries)
34+
}
35+
36+
/// Prints the OpenCode report for already loaded entries.
37+
pub fn print_report(args: &AgentCommandArgs, mut entries: Vec<LoadedEntry>) -> Result<()> {
2938
let kind = args.kind;
30-
let shared = args.shared;
31-
let mut entries = loader::load_entries(&shared, kind)?;
32-
filter_loaded_entries_by_date(&mut entries, &shared);
33-
if wants_json(&shared) {
39+
let shared = &args.shared;
40+
filter_loaded_entries_by_date(&mut entries, shared);
41+
if wants_json(shared) {
3442
return print_json_or_jq(
3543
report_json(&entries, kind, &shared.order)?,
3644
shared.jq.as_deref(),
@@ -43,7 +51,7 @@ pub fn run(args: AgentCommandArgs) -> Result<()> {
4351
"OpenCode Token Usage Report",
4452
first_column(kind),
4553
&rows,
46-
&shared,
54+
shared,
4755
false,
4856
None,
4957
)?;

‎rust/crates/ccusage-adapter-all/src/lib.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,14 @@ pub fn run(args: AgentCommandArgs) -> Result<()> {
7575
report::print_table(&result.rows, kind, &shared, &result.detected_agents)
7676
}
7777

78+
/// Runs `ccusage opencode`, leaving Claude Agent turns to the Claude source
79+
/// unless `--include-claude-agent` keeps them.
80+
pub fn run_opencode(args: AgentCommandArgs) -> Result<()> {
81+
let entries =
82+
loader::load_opencode_entries(&args.shared, args.kind, args.include_claude_agent)?;
83+
adapter::opencode::print_report(&args, entries)
84+
}
85+
7886
fn print_warnings(warnings: &[String]) {
7987
warnings.iter().for_each(|warning| eprintln!("{warning}"));
8088
}

‎rust/crates/ccusage-adapter-all/src/loader.rs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,33 @@ impl ClaudeCounted {
853853
}
854854
}
855855

856+
/// Loads `ccusage opencode` entries. The `claude-agent` turns the Claude
857+
/// source counts are left to it unless `include_claude_agent` is set, so the
858+
/// focused reports add up to the unified one.
859+
pub(super) fn load_opencode_entries(
860+
shared: &SharedArgs,
861+
kind: AgentReportKind,
862+
include_claude_agent: bool,
863+
) -> Result<Vec<LoadedEntry>> {
864+
let entries = opencode::load_entries_with_native_sessions(shared, kind)?;
865+
if include_claude_agent || entries.iter().all(|(_, session)| session.is_none()) {
866+
return Ok(entries.into_iter().map(|(entry, _)| entry).collect());
867+
}
868+
let claude_shared = SharedArgs {
869+
json: true,
870+
mode: CostMode::Display,
871+
..shared.clone()
872+
};
873+
// Focused Claude reports, sessions included, count only in-window days, so match by
874+
// session day. Missing Claude directories load as no session days, so those turns stay.
875+
let (_, claude_counted) = load_claude_rows(AgentReportKind::Daily, &claude_shared, None)?;
876+
Ok(without_turns_counted_by_claude(
877+
entries,
878+
&claude_counted,
879+
&claude_shared,
880+
))
881+
}
882+
856883
/// Claude rows plus the usage they count.
857884
fn load_claude_rows(
858885
kind: AgentReportKind,

0 commit comments

Comments
 (0)