Skip to content

Commit ab014fb

Browse files
committed
refactor(adapter): split agent modules
Move the long single-file agent adapters into per-agent module trees with dedicated loader, parser, paths, and report files where applicable. This keeps runtime behavior unchanged while making the new Rust-first adapter surface easier to review and extend. OpenCode summary reporting now lives in its own report module, so the insta snapshot path is updated to match the module boundary. Validated with adapter tests, full repo format/typecheck/test, and JSON parity against latest bunx ccusage through 2026-05-22 for all touched agent reports.
1 parent ab95bab commit ab014fb

68 files changed

Lines changed: 5913 additions & 5504 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎rust/crates/ccusage/src/adapter/amp.rs‎

Lines changed: 0 additions & 501 deletions
This file was deleted.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use crate::{
2+
cli::SharedArgs, collect_files_with_extension, parse_tz, LoadedEntry, PricingMap, Result,
3+
};
4+
5+
use super::{parser, paths};
6+
7+
pub(crate) fn load_entries(shared: &SharedArgs, pricing: &PricingMap) -> Result<Vec<LoadedEntry>> {
8+
crate::progress::track_usage_load(crate::progress::UsageLoadAgent::Amp, shared.json, || {
9+
load_entries_inner(shared, pricing)
10+
})
11+
}
12+
13+
fn load_entries_inner(shared: &SharedArgs, pricing: &PricingMap) -> Result<Vec<LoadedEntry>> {
14+
let mut entries = Vec::new();
15+
let tz = parse_tz(shared.timezone.as_deref());
16+
for path in paths::paths()? {
17+
let threads_dir = path.join("threads");
18+
let mut files = Vec::new();
19+
collect_files_with_extension(&threads_dir, "json", &mut files);
20+
for file in files {
21+
entries.extend(parser::read_thread_file(
22+
&file,
23+
tz.as_ref(),
24+
shared.mode,
25+
Some(pricing),
26+
)?);
27+
}
28+
}
29+
entries.sort_by_key(|entry| entry.timestamp);
30+
Ok(entries)
31+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
mod loader;
2+
mod parser;
3+
mod paths;
4+
mod report;
5+
6+
use crate::{
7+
adapter::opencode, cli::AgentCommandArgs, filter_loaded_entries_by_date, print_json_or_jq,
8+
sort_summaries, wants_json, PricingMap, Result,
9+
};
10+
11+
pub(crate) use loader::load_entries;
12+
#[cfg(test)]
13+
pub(crate) use parser::read_thread_file;
14+
pub(crate) use report::{print_table, print_table_for_agent, report_from_rows, summarize_entries};
15+
16+
pub(crate) fn run(args: AgentCommandArgs) -> Result<()> {
17+
let shared = args.shared;
18+
let pricing = PricingMap::load(shared.offline, crate::log_level() != Some(0));
19+
let mut entries = load_entries(&shared, &pricing)?;
20+
filter_loaded_entries_by_date(&mut entries, &shared);
21+
let mut rows = summarize_entries(&entries, args.kind)?;
22+
sort_summaries(&mut rows, &shared.order, |row| {
23+
opencode::summary_period(row)
24+
});
25+
if wants_json(&shared) {
26+
return print_json_or_jq(report_from_rows(&rows, args.kind), shared.jq.as_deref());
27+
}
28+
report::print_table(args.kind, &rows, &shared)
29+
}
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
use std::{collections::HashMap, fs, path::Path, sync::Arc};
2+
3+
use jiff::tz::TimeZone as JiffTimeZone;
4+
use serde_json::Value;
5+
6+
use crate::{
7+
apply_total_token_fallback, calculate_cost, cli::CostMode, format_date_tz, json_value_u64,
8+
non_empty_json_string, LoadedEntry, PricingMap, Result, TokenUsageRaw, UsageEntry,
9+
UsageMessage,
10+
};
11+
12+
pub(crate) fn read_thread_file(
13+
path: &Path,
14+
tz: Option<&JiffTimeZone>,
15+
mode: CostMode,
16+
pricing: Option<&PricingMap>,
17+
) -> Result<Vec<LoadedEntry>> {
18+
let content = fs::read_to_string(path)?;
19+
let Ok(value) = serde_json::from_str::<Value>(&content) else {
20+
return Ok(Vec::new());
21+
};
22+
let Some(thread_id) = non_empty_json_string(value.get("id")) else {
23+
return Ok(Vec::new());
24+
};
25+
let cache_tokens = cache_tokens_by_message_id(value.get("messages"));
26+
let Some(events) = value
27+
.get("usageLedger")
28+
.and_then(|ledger| ledger.get("events"))
29+
.and_then(Value::as_array)
30+
else {
31+
return Ok(Vec::new());
32+
};
33+
34+
let mut entries = Vec::new();
35+
for event in events {
36+
let Some(timestamp_text) = non_empty_json_string(event.get("timestamp")) else {
37+
continue;
38+
};
39+
let Some(timestamp) = crate::parse_ts_timestamp(&timestamp_text) else {
40+
continue;
41+
};
42+
let Some(model) = non_empty_json_string(event.get("model")) else {
43+
continue;
44+
};
45+
let Some(tokens) = event.get("tokens") else {
46+
continue;
47+
};
48+
let cache = event
49+
.get("toMessageId")
50+
.and_then(Value::as_i64)
51+
.and_then(|id| cache_tokens.get(&id).copied())
52+
.unwrap_or_default();
53+
let usage = TokenUsageRaw {
54+
input_tokens: json_value_u64(tokens.get("input")),
55+
output_tokens: json_value_u64(tokens.get("output")),
56+
cache_creation_input_tokens: cache.0,
57+
cache_read_input_tokens: cache.1,
58+
speed: None,
59+
};
60+
let total_tokens = json_value_u64(tokens.get("total"));
61+
let (usage, extra_total_tokens) = apply_total_token_fallback(usage, 0, total_tokens);
62+
if usage.input_tokens == 0
63+
&& usage.output_tokens == 0
64+
&& usage.cache_creation_input_tokens == 0
65+
&& usage.cache_read_input_tokens == 0
66+
&& extra_total_tokens == 0
67+
{
68+
continue;
69+
}
70+
let data = UsageEntry {
71+
session_id: Some(thread_id.clone()),
72+
timestamp: timestamp_text,
73+
version: None,
74+
message: UsageMessage {
75+
usage,
76+
model: Some(model.clone()),
77+
id: non_empty_json_string(event.get("id")),
78+
},
79+
cost_usd: None,
80+
request_id: None,
81+
is_api_error_message: None,
82+
};
83+
let cost_data = UsageEntry {
84+
message: UsageMessage {
85+
usage: TokenUsageRaw {
86+
output_tokens: data
87+
.message
88+
.usage
89+
.output_tokens
90+
.saturating_add(extra_total_tokens),
91+
..data.message.usage
92+
},
93+
..data.message.clone()
94+
},
95+
..data.clone()
96+
};
97+
let cost = calculate_cost(&cost_data, mode, pricing);
98+
entries.push(LoadedEntry {
99+
date: format_date_tz(timestamp, tz),
100+
timestamp,
101+
project: Arc::from("amp"),
102+
session_id: Arc::from(thread_id.as_str()),
103+
project_path: Arc::from("Amp"),
104+
cost,
105+
extra_total_tokens,
106+
credits: json_value_f64(event.get("credits")),
107+
message_count: None,
108+
model: Some(model),
109+
usage_limit_reset_time: None,
110+
data,
111+
});
112+
}
113+
Ok(entries)
114+
}
115+
116+
fn cache_tokens_by_message_id(messages: Option<&Value>) -> HashMap<i64, (u64, u64)> {
117+
let mut cache_tokens = HashMap::new();
118+
let Some(messages) = messages.and_then(Value::as_array) else {
119+
return cache_tokens;
120+
};
121+
for message in messages {
122+
if message.get("role").and_then(Value::as_str) != Some("assistant") {
123+
continue;
124+
}
125+
let Some(message_id) = message.get("messageId").and_then(Value::as_i64) else {
126+
continue;
127+
};
128+
let usage = message.get("usage");
129+
cache_tokens.insert(
130+
message_id,
131+
(
132+
json_value_u64(usage.and_then(|usage| usage.get("cacheCreationInputTokens"))),
133+
json_value_u64(usage.and_then(|usage| usage.get("cacheReadInputTokens"))),
134+
),
135+
);
136+
}
137+
cache_tokens
138+
}
139+
140+
fn json_value_f64(value: Option<&Value>) -> Option<f64> {
141+
value.and_then(Value::as_f64)
142+
}
143+
144+
#[cfg(test)]
145+
mod tests {
146+
use std::{env, fs, time::SystemTime};
147+
148+
use super::*;
149+
150+
#[test]
151+
fn falls_back_to_total_tokens_when_amp_parts_are_missing() {
152+
let nanos = SystemTime::now()
153+
.duration_since(std::time::UNIX_EPOCH)
154+
.unwrap()
155+
.as_nanos();
156+
let dir = env::temp_dir().join(format!("ccusage-amp-total-{nanos}"));
157+
fs::create_dir_all(&dir).unwrap();
158+
let file = dir.join("thread.json");
159+
fs::write(
160+
&file,
161+
r#"{"id":"thread-a","usageLedger":{"events":[{"id":"event-a","timestamp":"2026-01-02T00:00:00.000Z","model":"gpt-5","tokens":{"total":345}}]}}"#,
162+
)
163+
.unwrap();
164+
165+
let entries = read_thread_file(&file, None, CostMode::Auto, None).unwrap();
166+
fs::remove_dir_all(&dir).unwrap();
167+
168+
assert_eq!(entries.len(), 1);
169+
assert_eq!(entries[0].data.message.usage.output_tokens, 345);
170+
assert_eq!(entries[0].extra_total_tokens, 0);
171+
}
172+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use std::{collections::HashSet, env, path::PathBuf};
2+
3+
use crate::Result;
4+
5+
const AMP_DATA_DIR_ENV: &str = "AMP_DATA_DIR";
6+
7+
pub(super) fn paths() -> Result<Vec<PathBuf>> {
8+
let mut paths = Vec::new();
9+
let mut seen = HashSet::new();
10+
if let Ok(env_paths) = env::var(AMP_DATA_DIR_ENV) {
11+
for raw in env_paths
12+
.split(',')
13+
.map(str::trim)
14+
.filter(|path| !path.is_empty())
15+
{
16+
let path = PathBuf::from(raw);
17+
if path.is_dir() && seen.insert(path.clone()) {
18+
paths.push(path);
19+
}
20+
}
21+
return Ok(paths);
22+
}
23+
24+
let home =
25+
crate::home::home_dir().ok_or_else(|| crate::cli_error("home directory is not set"))?;
26+
let path = home.join(".local/share/amp");
27+
if path.is_dir() && seen.insert(path.clone()) {
28+
paths.push(path);
29+
}
30+
Ok(paths)
31+
}

0 commit comments

Comments
 (0)