The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(cost): add usage and cache report RPCs
Steven Enamakelc362320b713e
diff --git a/crates/openhuman-core/src/platform/cost/mod.rs b/crates/openhuman-core/src/platform/cost/mod.rsindex 8873db7472..9a9a035f83 100644--- a/crates/openhuman-core/src/platform/cost/mod.rs+++ b/crates/openhuman-core/src/platform/cost/mod.rs@@ -1,5 +1,6 @@pub mod catalog;mod global;+pub mod report;pub mod route;mod rpc;mod schemas;diff --git a/crates/openhuman-core/src/platform/cost/rpc.rs b/crates/openhuman-core/src/platform/cost/rpc.rsindex 93bb0709d5..658ce0f907 100644--- a/crates/openhuman-core/src/platform/cost/rpc.rs+++ b/crates/openhuman-core/src/platform/cost/rpc.rs@@ -468,6 +468,70 @@ pub fn usage_log(config: &Config, days: u32, limit: usize) -> Result<Outcome<ValOk(Outcome::new(value, Vec::new()))}+/// The `[now - days, now]` window a report covers; `days` is clamped to+/// `[1, 366]`.+fn report_window(days: u32) -> (chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>) {+ let to = chrono::Utc::now();+ let from = to - chrono::Duration::days(i64::from(days.clamp(1, 366)));+ (from, to)+}++/// Group and total the last `days` of usage (`cost.report`).+pub fn usage_report(+ config: &Config,+ days: u32,+ group_by: &[super::report::GroupKey],+ filter: &super::report::ReportFilter,+) -> Result<Outcome<Value>> {+ log::debug!(target: "cost_rpc", "[cost_rpc] report.entry days={days} group_by={group_by:?}");+ let tracker = resolve_tracker(config)?;+ let (from, to) = report_window(days);+ let records = tracker+ .records_between(from, to)+ .context("cost report query failed")?;+ let report = super::report::build_report(&records, from, to, group_by, filter);+ log::debug!(+ target: "cost_rpc",+ "[cost_rpc] report.exit records={} rows={} calls={}",+ records.len(),+ report.rows.len(),+ report.totals.calls+ );+ let value = serde_json::to_value(report).context("cost report serialize failed")?;+ Ok(Outcome::new(value, Vec::new()))+}++/// Per-call prompt-cache behaviour over the last `days` (`cost.cache_report`).+/// The totals cover every call; `calls` keeps the newest `limit` (clamped to+/// `[1, 1000]`).+pub fn cache_report(+ config: &Config,+ days: u32,+ filter: &super::report::ReportFilter,+ limit: usize,+) -> Result<Outcome<Value>> {+ log::debug!(target: "cost_rpc", "[cost_rpc] cache_report.entry days={days} limit={limit}");+ let tracker = resolve_tracker(config)?;+ let (from, to) = report_window(days);+ let records = tracker+ .records_between(from, to)+ .context("cost cache report query failed")?;+ let mut report = super::report::build_cache_report(&records, from, to, filter);+ let keep = limit.clamp(1, 1000);+ if report.calls.len() > keep {+ report.calls.drain(..report.calls.len() - keep);+ }+ log::debug!(+ target: "cost_rpc",+ "[cost_rpc] cache_report.exit calls={} hit_ratio={:.3} cold={}",+ report.calls.len(),+ report.cache_hit_ratio,+ report.cold_calls+ );+ let value = serde_json::to_value(report).context("cost cache report serialize failed")?;+ Ok(Outcome::new(value, Vec::new()))+}+#[cfg(test)]#[path = "rpc_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/platform/cost/schemas.rs b/crates/openhuman-core/src/platform/cost/schemas.rsindex f5eb667eda..fd867e3286 100644--- a/crates/openhuman-core/src/platform/cost/schemas.rs+++ b/crates/openhuman-core/src/platform/cost/schemas.rs@@ -30,6 +30,19 @@ fn default_usage_days() -> u32 {30}+#[derive(Debug, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+struct ReportParams {+ #[serde(default)]+ days: Option<u32>,+ #[serde(default, alias = "group_by")]+ group_by: Vec<super::report::GroupKey>,+ #[serde(default)]+ filter: super::report::ReportFilter,+ #[serde(default)]+ limit: Option<usize>,+}+fn default_usage_limit() -> usize {250}@@ -40,6 +53,8 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {schema_for("cost_get_daily_history"),schema_for("cost_get_summary"),schema_for("cost_get_usage_log"),+ schema_for("cost_report"),+ schema_for("cost_cache_report"),]}@@ -61,6 +76,14 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {schema: schema_for("cost_get_usage_log"),handler: handle_cost_get_usage_log,},+ RegisteredController {+ schema: schema_for("cost_report"),+ handler: handle_cost_report,+ },+ RegisteredController {+ schema: schema_for("cost_cache_report"),+ handler: handle_cost_cache_report,+ },]}@@ -130,6 +153,41 @@ fn schema_for(function: &str) -> ControllerSchema {"Usage records plus category totals, newest records first.",)],},+ "cost_report" => ControllerSchema {+ namespace: "cost",+ function: "report",+ 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.",+ inputs: vec![days_input(), group_by_input(), filter_input()],+ outputs: vec![json_output(+ "report",+ "`totals` and `rows` (one per group, most expensive first), each with a `key` map.",+ )],+ },+ "cost_cache_report" => ControllerSchema {+ namespace: "cost",+ function: "cache_report",+ description: "Prompt-cache behaviour over the last `days`, call by call: hit ratio, \+ cold calls (a repeat call in a thread that read nothing from the cache) \+ and what uncached input cost above the cached rate.",+ inputs: vec![+ days_input(),+ filter_input(),+ FieldSchema {+ name: "limit",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Newest calls to list (default 200, clamped to [1, 1000]); totals \+ cover every call.",+ required: false,+ },+ ],+ outputs: vec![json_output(+ "cache_report",+ "`calls`, `cache_hit_ratio`, `cold_calls` and `uncached_premium_usd`.",+ )],+ },_ => ControllerSchema {namespace: "cost",function: "unknown",@@ -257,6 +315,81 @@ fn handle_cost_get_usage_log(params: Map<String, Value>) -> ControllerFuture {})}+fn parse_report_params(params: Map<String, Value>) -> Result<ReportParams, String> {+ if params.is_empty() {+ return Ok(ReportParams::default());+ }+ serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))+}++fn handle_cost_report(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let cid = new_correlation_id();+ log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_report.entry");+ let config = config_rpc::load_config_with_timeout().await?;+ let p = parse_report_params(params)?;+ let days = p.days.unwrap_or_else(default_usage_days);+ let outcome = cost_rpc::usage_report(&config, days, &p.group_by, &p.filter)+ .map_err(|e| e.to_string())?;+ to_json(outcome)+ })+}++fn handle_cost_cache_report(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let cid = new_correlation_id();+ log::debug!(target: "cost_rpc", "[cost_rpc][{cid}] cost_cache_report.entry");+ let config = config_rpc::load_config_with_timeout().await?;+ let p = parse_report_params(params)?;+ let days = p.days.unwrap_or_else(default_usage_days);+ let limit = p.limit.unwrap_or(200);+ let outcome =+ cost_rpc::cache_report(&config, days, &p.filter, limit).map_err(|e| e.to_string())?;+ to_json(outcome)+ })+}++fn days_input() -> FieldSchema {+ FieldSchema {+ name: "days",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Trailing days to cover (default 30, clamped to [1, 366]).",+ required: false,+ }+}++fn group_by_input() -> FieldSchema {+ FieldSchema {+ name: "groupBy",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::Enum {+ variants: vec![+ "day",+ "week",+ "month",+ "model",+ "provider",+ "route",+ "agent",+ "thread",+ "origin",+ "session_agent",+ ],+ })))),+ comment: "Dimensions to group by, in order; omit for totals only.",+ required: false,+ }+}++fn filter_input() -> FieldSchema {+ FieldSchema {+ name: "filter",+ ty: TypeSchema::Option(Box::new(TypeSchema::Json)),+ comment: "Optional `{thread_id, agent_id, model, provider, route, origin, \+ session_agent}`; every set field must match.",+ required: false,+ }+}+fn to_json(outcome: Outcome<Value>) -> Result<Value, String> {outcome.into_cli_compatible_json()}