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): track spend per scope and surface it in reports
Steven Enamakel802cd09faa8b
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rsindex 0e80ae5630..3f03b3f1a5 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs@@ -370,6 +370,7 @@ impl OpenhumanEventBridge {let estimate = Self::estimate_call_cost(&self.model, usage);let provider_cost = carried.as_ref()+ .filter(|u| !u.cost_is_estimate).map(|u| u.charged_amount_usd).filter(|c| c.is_finite() && *c > 0.0);let cost_is_estimate = provider_cost.is_none();diff --git a/crates/openhuman-core/src/platform/cost/global.rs b/crates/openhuman-core/src/platform/cost/global.rsindex 10d554f53a..41429e1be4 100644--- a/crates/openhuman-core/src/platform/cost/global.rs+++ b/crates/openhuman-core/src/platform/cost/global.rs@@ -274,7 +274,10 @@ pub fn record_embedding_usage(cost_source: CostSource::Estimated,run_id: None,root_run_id: None,- scope: UsageScope::default(),+ scope: UsageScope {+ origin: Some(super::report::EMBEDDING_ORIGIN.to_string()),+ ..UsageScope::ambient(Some(provider), None)+ },timestamp: chrono::Utc::now(),};log::debug!(diff --git a/crates/openhuman-core/src/platform/cost/report.rs b/crates/openhuman-core/src/platform/cost/report.rsindex a70e0acf3e..412e620cf6 100644--- a/crates/openhuman-core/src/platform/cost/report.rs+++ b/crates/openhuman-core/src/platform/cost/report.rs@@ -86,6 +86,9 @@ impl GroupKey {}}+/// The `origin` of an embedding batch's record.+pub const EMBEDDING_ORIGIN: &str = "embedding";+/// The group value of a record that does not carry that attribute (recorded/// before attribution existed, or outside any thread).pub const UNKNOWN: &str = "unknown";@@ -97,8 +100,10 @@ fn route_label(model: &str) -> &'static str {}}-/// Which records a report covers. Every set field must match.+/// Which records a report covers. Every set field must match. Unknown keys+/// are refused, so a misspelt filter cannot widen a report to everything.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]pub struct ReportFilter {#[serde(default)]pub thread_id: Option<String>,@@ -285,11 +290,25 @@ pub fn build_cache_report(to: DateTime<Utc>,filter: &ReportFilter,) -> CacheReport {- let mut ordered: Vec<&CostRecord> = records.iter().filter(|r| filter.admits(r)).collect();- ordered.sort_by_key(|r| r.usage.timestamp);+ // Embedding batches never read a prompt cache; they would only dilute the+ // ratio and show up as zero-hit calls.+ let mut ordered: Vec<&CostRecord> = records+ .iter()+ .filter(|r| r.usage.scope.origin.as_deref() != Some(EMBEDDING_ORIGIN))+ .filter(|r| filter.admits(r))+ .collect();+ // The id breaks timestamp ties, so the same records always classify the+ // same way.+ ordered.sort_by(|a, b| {+ a.usage+ .timestamp+ .cmp(&b.usage.timestamp)+ .then_with(|| a.id.cmp(&b.id))+ });// A call is a repeat only against an earlier call with the same cache- // identity: a model switch or another agent prompt starts a fresh cache.- let mut caches_seen: HashSet<(String, String, Option<String>)> = HashSet::new();+ // identity: a model, provider or agent prompt switch starts a fresh cache.+ type CacheIdentity = (String, String, Option<String>, Option<String>);+ let mut caches_seen: HashSet<CacheIdentity> = HashSet::new();let mut report = CacheReport {from,to,@@ -305,17 +324,27 @@ pub fn build_cache_report(let cached = usage.cached_input_tokens.min(usage.input_tokens);let thread = usage.scope.thread_id.clone();let repeat = thread.as_ref().is_some_and(|t| {- !caches_seen.insert((t.clone(), usage.model.clone(), usage.scope.agent_id.clone()))+ !caches_seen.insert((+ t.clone(),+ usage.model.clone(),+ usage.scope.agent_id.clone(),+ usage.scope.provider.clone(),+ ))});let cold = repeat && cached == 0 && usage.input_tokens > 0;if cold {report.cold_calls += 1;}- if let Some(price) = super::catalog::lookup(&usage.model) {- let premium = (price.input_per_mtok_usd - price.cached_input_per_mtok_usd).max(0.0);- let uncached = usage.input_tokens - cached;- report.uncached_premium_usd += uncached as f64 / 1_000_000.0 * premium;- }+ // Through the tier-aware estimator: what this call's input cost against+ // what it would have cost had every input token been cached.+ let actual = super::catalog::estimate_cost_usd(&usage.model, usage.input_tokens, 0, cached);+ let all_cached = super::catalog::estimate_cost_usd(+ &usage.model,+ usage.input_tokens,+ 0,+ usage.input_tokens,+ );+ report.uncached_premium_usd += (actual - all_cached).max(0.0);report.input_tokens += usage.input_tokens;report.cached_input_tokens += cached;report.calls.push(CacheCall {diff --git a/crates/openhuman-core/src/platform/cost/schemas.rs b/crates/openhuman-core/src/platform/cost/schemas.rsindex 5ac167ef24..def57d64c6 100644--- a/crates/openhuman-core/src/platform/cost/schemas.rs+++ b/crates/openhuman-core/src/platform/cost/schemas.rs@@ -30,6 +30,7 @@ fn default_usage_days() -> u32 {30}+/// `cost_report` params. Each report takes only what its schema declares.#[derive(Debug, Deserialize, Default)]#[serde(rename_all = "camelCase", deny_unknown_fields)]struct ReportParams {@@ -39,6 +40,16 @@ struct ReportParams {group_by: Vec<super::report::GroupKey>,#[serde(default)]filter: super::report::ReportFilter,+}++/// `cost_cache_report` params.+#[derive(Debug, Deserialize, Default)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+struct CacheReportParams {+ #[serde(default)]+ days: Option<u32>,+ #[serde(default)]+ filter: super::report::ReportFilter,#[serde(default)]limit: Option<usize>,}@@ -316,9 +327,11 @@ fn handle_cost_get_usage_log(params: Map<String, Value>) -> ControllerFuture {})}-fn parse_report_params(params: Map<String, Value>) -> Result<ReportParams, String> {+fn parse_report_params<T: serde::de::DeserializeOwned + Default>(+ params: Map<String, Value>,+) -> Result<T, String> {if params.is_empty() {- return Ok(ReportParams::default());+ return Ok(T::default());}serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))}@@ -328,7 +341,7 @@ fn handle_cost_report(params: Map<String, Value>) -> ControllerFuture {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 p: ReportParams = 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())?;@@ -341,7 +354,7 @@ fn handle_cost_cache_report(params: Map<String, Value>) -> ControllerFuture {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 p: CacheReportParams = parse_report_params(params)?;let days = p.days.unwrap_or_else(default_usage_days);let limit = p.limit.unwrap_or(200);let outcome =diff --git a/crates/openhuman-core/src/platform/cost/scope.rs b/crates/openhuman-core/src/platform/cost/scope.rsindex e046f3e660..c105ae2103 100644--- a/crates/openhuman-core/src/platform/cost/scope.rs+++ b/crates/openhuman-core/src/platform/cost/scope.rs@@ -46,9 +46,15 @@ pub(crate) fn describe_origin(Some(AgentTurnOrigin::WebChat { thread_id, .. }) => {(Some(thread_id.clone()), Some("web_chat".to_string()))}- Some(AgentTurnOrigin::ExternalChannel { channel, .. }) => {- (None, Some(format!("channel:{channel}")))- }+ // A channel conversation's history key is its stable identity.+ Some(AgentTurnOrigin::ExternalChannel {+ channel,+ history_key,+ ..+ }) => (+ history_key.clone().filter(|key| !key.trim().is_empty()),+ Some(format!("channel:{channel}")),+ ),Some(AgentTurnOrigin::TrustedAutomation { source, .. }) => {let label = match source {TrustedAutomationSource::Cron => "cron",