Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

docs(cost): document usage reports, cache reports and attribution

Steven Enamakel8bc67d5c7ad0
diff --git a/crates/openhuman-core/src/platform/cost/README.md b/crates/openhuman-core/src/platform/cost/README.md
index 763804a90f..14e6fcbbb9 100644
--- a/crates/openhuman-core/src/platform/cost/README.md
+++ b/crates/openhuman-core/src/platform/cost/README.md
@@ -25,6 +25,8 @@ Local API-usage cost tracking for the agent. Records per-call token usage and co
| `crates/openhuman-core/src/platform/cost/tracker_tests.rs` | Sibling test suite for `tracker.rs` (`#[path]`-included). |
| `crates/openhuman-core/src/platform/cost/catalog.rs` | Static per-model pricing + context-window catalog (`ModelPrice`, `lookup`, `estimate_cost_usd`, `PRICING_AS_OF`) and the tinyagents model-catalog adapters. |
| `crates/openhuman-core/src/platform/cost/route.rs` | `CostRoute` / `route_for_model`: derives from the model id whether a record counts against OpenHuman-managed credits or is BYOK/local (#5016). |
+| `crates/openhuman-core/src/platform/cost/scope.rs` | `UsageScope::ambient`: a record's attribution (thread, origin, agent definition, sub-agent task, embedded/SaaS user agent, provider) read from the recording task's turn origin, memory identity and `CoreContext`. |
+| `crates/openhuman-core/src/platform/cost/report.rs` | Pure usage reports over ledger records: `build_report` (group by day/week/month/model/provider/route/agent/thread/origin/session_agent; tokens, charged vs estimated cost, cache-hit ratio) and `build_cache_report` (per-call hits, cold calls, uncached premium). |
| `crates/openhuman-core/src/platform/cost/tools.rs` | Read-only, default-on LLM tools (`cost_get_dashboard`, `cost_get_daily_history`, …) re-exported through `crates/openhuman-core/src/tools/mod.rs`. |
## Public surface
@@ -48,6 +50,12 @@ Namespace `cost` (methods `openhuman.cost_*` via the registry):
| `cost_get_daily_history` | `days?` (u32, default 7, clamped `[1, 366]`) | Ordered daily entries, oldest first, gaps zero-filled. |
| `cost_get_summary` | none | Live session / daily / monthly cost summary. |
| `cost_get_usage_log` | `days?`, `limit?` | Recent local records, newest first, bounded to 1,000 rows. |
+| `cost_report` | `days?`, `groupBy?`, `filter?` | Totals plus one row per group (most expensive first): calls, input/output/cached/cache-write/reasoning tokens, `cost_usd` split into `charged_usd` / `estimated_usd`, `cache_hit_ratio`. |
+| `cost_cache_report` | `days?`, `filter?`, `limit?` | Per-call prompt-cache hits (newest `limit`), overall `cache_hit_ratio`, `cold_calls` (a repeat call in a thread with no cache read) and `uncached_premium_usd`. |
+
+Both reports are also CLI commands: `openhuman-core cost report --days 7 --groupBy '["day","agent"]'`, `openhuman-core cost cache_report --filter '{"thread_id":"…"}'`.
+
+**Attribution.** Every recorded call carries an optional `scope` (`UsageScope`): the thread, what started the turn, the agent definition (or the delegated sub-agent and its task), the embedded/SaaS user agent and the provider. The event bridge passes the provider and sub-agent, and the rest comes from the recording task. Records written before attribution have no `scope` and group as `unknown`.
Handlers load config via `config_rpc::load_config_with_timeout`, then delegate to `rpc.rs`. RPC DTOs (`CostDashboardDto`, `DailyCostEntryDto`, `ModelStatsDto`, `CostSummaryDto`, `UsageLogRecordDto`) add presentation fields not on the domain types: `provider` (derived from the `provider/model` prefix), `percent_of_total`, and dashboard threshold/`enabled` flags from `cost.dashboard`. Usage-log records preserve the persisted token provenance fields (`cached_input_tokens`, `cache_creation_tokens`, `reasoning_tokens`, `cost_source`) for migration audit callers for the dedicated usage-log tab.
diff --git a/crates/openhuman-core/src/platform/cost/report.rs b/crates/openhuman-core/src/platform/cost/report.rs
index 3c58b337d9..34a4a08a66 100644
--- a/crates/openhuman-core/src/platform/cost/report.rs
+++ b/crates/openhuman-core/src/platform/cost/report.rs
@@ -205,7 +205,11 @@ pub fn build_report(
filter: &ReportFilter,
) -> UsageReport {
let mut seen = HashSet::new();
- let group_by: Vec<GroupKey> = group_by.iter().copied().filter(|k| seen.insert(*k)).collect();
+ let group_by: Vec<GroupKey> = group_by
+ .iter()
+ .copied()
+ .filter(|k| seen.insert(*k))
+ .collect();
let mut totals = ReportRow::default();
let mut groups: HashMap<Vec<String>, ReportRow> = HashMap::new();
for record in records.iter().filter(|r| filter.admits(r)) {
diff --git a/crates/openhuman-core/src/platform/cost/report_tests.rs b/crates/openhuman-core/src/platform/cost/report_tests.rs
index c23a2bea7a..8b3cec7d50 100644
--- a/crates/openhuman-core/src/platform/cost/report_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/report_tests.rs
@@ -40,10 +40,46 @@ fn window() -> (DateTime<Utc>, DateTime<Utc>) {
fn sample() -> Vec<CostRecord> {
vec![
- record((1, 9), "anthropic/claude-sonnet-4-5", Some("t1"), Some("orchestrator"), 1000, 0, 0.50, true),
- record((1, 10), "anthropic/claude-sonnet-4-5", Some("t1"), Some("orchestrator"), 1000, 800, 0.20, true),
- record((2, 9), "openai/gpt-5-mini", Some("t2"), Some("planner"), 500, 100, 0.05, false),
- record((2, 10), "openai/gpt-5-mini", None, None, 100, 0, 0.01, false),
+ record(
+ (1, 9),
+ "anthropic/claude-sonnet-4-5",
+ Some("t1"),
+ Some("orchestrator"),
+ 1000,
+ 0,
+ 0.50,
+ true,
+ ),
+ record(
+ (1, 10),
+ "anthropic/claude-sonnet-4-5",
+ Some("t1"),
+ Some("orchestrator"),
+ 1000,
+ 800,
+ 0.20,
+ true,
+ ),
+ record(
+ (2, 9),
+ "openai/gpt-5-mini",
+ Some("t2"),
+ Some("planner"),
+ 500,
+ 100,
+ 0.05,
+ false,
+ ),
+ record(
+ (2, 10),
+ "openai/gpt-5-mini",
+ None,
+ None,
+ 100,
+ 0,
+ 0.01,
+ false,
+ ),
]
}
@@ -65,7 +101,13 @@ fn totals_cover_every_admitted_call() {
#[test]
fn groups_by_agent_most_expensive_first() {
let (from, to) = window();
- let report = build_report(&sample(), from, to, &[GroupKey::Agent], &ReportFilter::default());
+ let report = build_report(
+ &sample(),
+ from,
+ to,
+ &[GroupKey::Agent],
+ &ReportFilter::default(),
+ );
let agents: Vec<_> = report.rows.iter().map(|r| r.key["agent"].clone()).collect();
assert_eq!(agents, vec!["orchestrator", "planner", UNKNOWN]);
let orchestrator = &report.rows[0];
@@ -107,18 +149,29 @@ fn filters_match_every_set_field() {
thread_id: Some("t1".into()),
..ReportFilter::default()
};
- assert_eq!(build_report(&sample(), from, to, &[], &only_t1).totals.calls, 2);
+ assert_eq!(
+ build_report(&sample(), from, to, &[], &only_t1)
+ .totals
+ .calls,
+ 2
+ );
let none = ReportFilter {
thread_id: Some("t1".into()),
agent_id: Some("planner".into()),
..ReportFilter::default()
};
- assert_eq!(build_report(&sample(), from, to, &[], &none).totals.calls, 0);
+ assert_eq!(
+ build_report(&sample(), from, to, &[], &none).totals.calls,
+ 0
+ );
let model = ReportFilter {
model: Some("openai/gpt-5-mini".into()),
..ReportFilter::default()
};
- assert_eq!(build_report(&sample(), from, to, &[], &model).totals.calls, 2);
+ assert_eq!(
+ build_report(&sample(), from, to, &[], &model).totals.calls,
+ 2
+ );
}
#[test]
@@ -126,7 +179,13 @@ fn records_from_before_attribution_group_as_unknown() {
let mut old = sample().remove(0);
old.usage.scope = UsageScope::default();
let (from, to) = window();
- let report = build_report(&[old], from, to, &[GroupKey::Thread], &ReportFilter::default());
+ let report = build_report(
+ &[old],
+ from,
+ to,
+ &[GroupKey::Thread],
+ &ReportFilter::default(),
+ );
assert_eq!(report.rows[0].key["thread"], UNKNOWN);
}
@@ -134,24 +193,47 @@ fn records_from_before_attribution_group_as_unknown() {
fn a_repeat_call_without_a_cache_hit_is_cold() {
let (from, to) = window();
let mut records = sample();
- records.push(record((3, 9), "anthropic/claude-sonnet-4-5", Some("t1"), Some("orchestrator"), 1000, 0, 0.5, true));
+ records.push(record(
+ (3, 9),
+ "anthropic/claude-sonnet-4-5",
+ Some("t1"),
+ Some("orchestrator"),
+ 1000,
+ 0,
+ 0.5,
+ true,
+ ));
let report = build_cache_report(&records, from, to, &ReportFilter::default());
let cold: Vec<_> = report.calls.iter().filter(|c| c.cold).collect();
assert_eq!(report.cold_calls, 1, "{:?}", report.calls);
assert_eq!(cold[0].timestamp.day(), 3);
- assert!(!report.calls[0].cold, "the first call of a thread cannot hit");
+ assert!(
+ !report.calls[0].cold,
+ "the first call of a thread cannot hit"
+ );
assert!(report.calls[1].cache_hit_ratio > 0.79);
}
#[test]
fn cache_report_prices_the_uncached_premium_for_known_models() {
let (from, to) = window();
- let records = vec![record((1, 9), "anthropic/claude-sonnet-4-5", Some("t1"), None, 1_000_000, 0, 3.0, true)];
+ let records = vec![record(
+ (1, 9),
+ "anthropic/claude-sonnet-4-5",
+ Some("t1"),
+ None,
+ 1_000_000,
+ 0,
+ 3.0,
+ true,
+ )];
let report = build_cache_report(&records, from, to, &ReportFilter::default());
let price = crate::platform::cost::catalog::lookup("anthropic/claude-sonnet-4-5");
match price {
Some(p) => assert!(
- (report.uncached_premium_usd - (p.input_per_mtok_usd - p.cached_input_per_mtok_usd)).abs() < 1e-9
+ (report.uncached_premium_usd - (p.input_per_mtok_usd - p.cached_input_per_mtok_usd))
+ .abs()
+ < 1e-9
),
None => assert_eq!(report.uncached_premium_usd, 0.0),
}
diff --git a/crates/openhuman-core/src/platform/cost/rpc_tests.rs b/crates/openhuman-core/src/platform/cost/rpc_tests.rs
index 937e0720c7..b410f2be70 100644
--- a/crates/openhuman-core/src/platform/cost/rpc_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/rpc_tests.rs
@@ -336,7 +336,11 @@ fn report_rpc_groups_attributed_usage_and_reports_cache_hits() {
)
.expect("cache report resolves");
let value = cache.value;
- assert_eq!(value["calls"].as_array().unwrap().len(), 1, "limit keeps the newest");
+ assert_eq!(
+ value["calls"].as_array().unwrap().len(),
+ 1,
+ "limit keeps the newest"
+ );
assert_eq!(value["input_tokens"], 2000, "totals cover every call");
assert_eq!(value["cold_calls"], 0);
}
diff --git a/crates/openhuman-core/src/platform/cost/schemas.rs b/crates/openhuman-core/src/platform/cost/schemas.rs
index fd867e3286..06f0ff2702 100644
--- a/crates/openhuman-core/src/platform/cost/schemas.rs
+++ b/crates/openhuman-core/src/platform/cost/schemas.rs
@@ -156,7 +156,8 @@ fn schema_for(function: &str) -> ControllerSchema {
"cost_report" => ControllerSchema {
namespace: "cost",
function: "report",
- description: "Usage report over the last `days`: calls, input/output/cached/cache-write/\
+ description:
+ "Usage report over the last `days`: calls, input/output/cached/cache-write/\
reasoning tokens, cost split into provider-charged and estimated, and \
the prompt-cache hit ratio — in total and grouped by any of day, week, \
month, model, provider, route, agent, thread, origin, session_agent.",
diff --git a/crates/openhuman-core/src/platform/cost/scope.rs b/crates/openhuman-core/src/platform/cost/scope.rs
index 61c7179073..e5995a864f 100644
--- a/crates/openhuman-core/src/platform/cost/scope.rs
+++ b/crates/openhuman-core/src/platform/cost/scope.rs
@@ -16,10 +16,7 @@ use super::types::UsageScope;
impl UsageScope {
/// The scope of the calling task, with `provider` and the sub-agent (its
/// definition and task id) supplied by the recording site.
- pub fn ambient(
- provider: Option<&str>,
- subagent: Option<(&str, &str)>,
- ) -> Self {
+ pub fn ambient(provider: Option<&str>, subagent: Option<(&str, &str)>) -> Self {
let origin = crate::agent::turn_origin::current();
let (thread_id, origin) = describe_origin(origin.as_ref());
let definition = crate::memory::scope::current().and_then(|identity| identity.agent_id);
diff --git a/crates/openhuman-core/src/platform/cost/scope_tests.rs b/crates/openhuman-core/src/platform/cost/scope_tests.rs
index cfed322b51..bd7060c926 100644
--- a/crates/openhuman-core/src/platform/cost/scope_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/scope_tests.rs
@@ -17,15 +17,24 @@ fn each_origin_maps_to_its_thread_and_label() {
reply_target: "r".into(),
message_id: "m".into(),
};
- assert_eq!(describe_origin(Some(&channel)).1.as_deref(), Some("channel:telegram"));
+ assert_eq!(
+ describe_origin(Some(&channel)).1.as_deref(),
+ Some("channel:telegram")
+ );
let cron = AgentTurnOrigin::TrustedAutomation {
job_id: "j".into(),
source: TrustedAutomationSource::Cron,
};
assert_eq!(describe_origin(Some(&cron)).1.as_deref(), Some("cron"));
- assert_eq!(describe_origin(Some(&AgentTurnOrigin::Cli)).1.as_deref(), Some("cli"));
+ assert_eq!(
+ describe_origin(Some(&AgentTurnOrigin::Cli)).1.as_deref(),
+ Some("cli")
+ );
assert_eq!(describe_origin(None), (None, None));
- assert_eq!(describe_origin(Some(&AgentTurnOrigin::Unknown)), (None, None));
+ assert_eq!(
+ describe_origin(Some(&AgentTurnOrigin::Unknown)),
+ (None, None)
+ );
}
#[tokio::test]