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
fix(embed): preserve authoritative billing sources and diagnostics
Steven Enamakelc07797f4dea4
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs b/crates/openhuman-core/src/agent/tinyagents/budget_charge.rsindex aee7e8c566..68be5d5d8c 100644--- a/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs+++ b/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs@@ -19,37 +19,70 @@ impl GatewayChargeModel {}}+fn rounded_micros(micros: Option<f64>) -> Option<ChargedAmount> {+ micros+ .filter(|amount| amount.is_finite() && *amount >= 0.0 && *amount < i64::MAX as f64)+ .map(|amount| ChargedAmount::usd_micros(amount.ceil() as i64))+}+fn normalize_charge(response: &mut ModelResponse) {let Some(usage) = response.usage.as_mut() else {// Missing usage must retain conservative token and charge reservations.+ tracing::trace!(+ source = "missing_usage",+ charge_known = false,+ "budget_charge_normalized"+ );return;};let Some(raw) = response.raw.as_ref() else {+ tracing::trace!(+ source = "typed_usage",+ charge_known = usage+ .charged_amount+ .is_some_and(|charge| charge.micros >= 0),+ "budget_charge_normalized"+ );return;};- if let Some(micros) = raw- .pointer("/usage/buyer_cost_micro")- .and_then(serde_json::Value::as_i64)- {- usage.charged_amount = (micros >= 0).then(|| ChargedAmount::usd_micros(micros));- return;- }- let micros = raw- .pointer("/usage/buyer_cost_micro")- .and_then(serde_json::Value::as_f64)- .or_else(|| {- raw.pointer("/usage/cost")- .and_then(serde_json::Value::as_f64)- .map(|cost| cost * 1_000_000.0)- });- let Some(micros) = micros else {- return;- };- // Buyer charge is authoritative, including zero. Invalid reported amounts- // remain unknown, and fractional micro-units round up rather than refunding- // money the gateway billed. No local price estimate enters the ledger.- usage.charged_amount = (micros.is_finite() && micros >= 0.0 && micros < i64::MAX as f64)- .then(|| ChargedAmount::usd_micros(micros.ceil() as i64));+ let (source, charge) =+ if let Some(managed) = raw.pointer("/openhuman_usage_meta/charged_amount_usd") {+ (+ "managed_backend",+ rounded_micros(managed.as_f64().map(|amount| amount * 1_000_000.0)),+ )+ } else if let Some(buyer) = raw.pointer("/usage/buyer_cost_micro") {+ let charge = if let Some(micros) = buyer.as_i64() {+ (micros >= 0).then_some(ChargedAmount::usd_micros(micros))+ } else {+ rounded_micros(buyer.as_f64())+ };+ ("gateway_buyer", charge)+ } else if let Some(cost) = raw.pointer("/usage/cost") {+ (+ "provider_cost",+ rounded_micros(cost.as_f64().map(|amount| amount * 1_000_000.0)),+ )+ } else {+ tracing::trace!(+ source = "typed_usage",+ charge_known = usage+ .charged_amount+ .is_some_and(|charge| charge.micros >= 0),+ "budget_charge_normalized"+ );+ return;+ };+ // Presence selects the authoritative billing source, including known zero+ // and malformed values. Invalid billing remains unknown; fractional units+ // round up. The ledger never substitutes a provider estimate for host or+ // buyer billing, and no locally calculated price enters settlement.+ usage.charged_amount = charge;+ tracing::trace!(+ source,+ charge_known = charge.is_some(),+ "budget_charge_normalized"+ );}#[async_trait]diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs b/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rsindex d7c0c046ca..b8b32e3a6a 100644--- a/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs@@ -36,7 +36,7 @@ async fn streaming_gateway_charge_settles_and_releases_the_reservation() {Arc::new(GatewayChargeModel::new(Arc::new(StreamingFixture))),budget.clone(),CallBudget {- input_tokens: 10,+ input_tokens: 1_000,output_tokens: 5,cost_micros: 100,},@@ -112,3 +112,46 @@ fn invalid_gateway_amount_discards_a_typed_charge_but_absent_metadata_preserves_normalize_charge(&mut response);assert!(response.usage.unwrap().charged_amount.is_none());}++#[test]+fn authoritative_billing_source_presence_prevents_unknown_charge_refunds() {+ for raw in [+ serde_json::json!({"usage": {"buyer_cost_micro": null, "cost": 0}}),+ serde_json::json!({"usage": {"buyer_cost_micro": "invalid", "cost": 0}}),+ serde_json::json!({"usage": {"cost": "invalid"}}),+ ] {+ let mut response = ModelResponse {+ usage: Some(Usage {+ charged_amount: Some(ChargedAmount::usd_micros(12)),+ ..Usage::new(10, 5)+ }),+ raw: Some(raw.clone()),+ ..ModelResponse::assistant("done")+ };+ normalize_charge(&mut response);+ assert!(response.usage.unwrap().charged_amount.is_none(), "{raw}");+ }+}++#[test]+fn managed_backend_charge_precedes_generic_provider_billing() {+ for (reported, expected) in [(0.0000064, Some(7)), (0.0, Some(0)), (-1.0, None)] {+ let mut response = ModelResponse {+ usage: Some(Usage::new(10, 5)),+ raw: Some(serde_json::json!({+ "openhuman_usage_meta": {"charged_amount_usd": reported},+ "usage": {"buyer_cost_micro": 42, "cost": 1}+ })),+ ..ModelResponse::assistant("done")+ };+ normalize_charge(&mut response);+ assert_eq!(+ response+ .usage+ .unwrap()+ .charged_amount+ .map(|charge| charge.micros),+ expected+ );+ }+}diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rsindex b0291ddea2..8d7ecdb667 100644--- a/crates/openhuman-embed/src/complete.rs+++ b/crates/openhuman-embed/src/complete.rs@@ -322,27 +322,25 @@ impl CompletionResponse {.and_then(|raw| raw.get("model")).and_then(Value::as_str).map(str::to_string);- // A relay may report its own upstream `cost: 0` while the buyer pays- // `buyer_cost_micro`. That actual bill precedes normalized estimates.- let cost_usd = raw- .as_ref()- .and_then(|raw| raw.pointer("/usage/buyer_cost_micro"))- .and_then(Value::as_f64)- .map(|micro| micro / 1_000_000.0)- .or_else(|| {- raw.as_ref()- .and_then(|raw| raw.pointer("/usage/cost"))- .and_then(Value::as_f64)- })- .or_else(|| {+ // Presence chooses the authoritative bill. Malformed billing must+ // remain unknown instead of falling through to a provider estimate.+ let raw_cost = raw.as_ref().and_then(|raw| {+ if let Some(managed) = raw.pointer("/openhuman_usage_meta/charged_amount_usd") {+ Some(managed.as_f64())+ } else if let Some(buyer) = raw.pointer("/usage/buyer_cost_micro") {+ Some(buyer.as_f64().map(|micro| micro / 1_000_000.0))+ } else {+ raw.pointer("/usage/cost").map(Value::as_f64)+ }+ });+ let cost_usd = raw_cost+ .unwrap_or_else(|| {response.usage.as_ref().and_then(|usage| usage.charged_amount).map(|amount| amount.micros as f64 / 1_000_000.0)})- // Invalid authoritative charges stay unknown, rather than being- // replaced by a lower-priority estimate or crediting the budget..filter(|cost| cost.is_finite() && *cost >= 0.0);let usage = match response.usage {Some(usage) => Some(CompletionUsage {diff --git a/crates/openhuman-embed/tests/budget_fanout.rs b/crates/openhuman-embed/tests/budget_fanout.rsindex 2de088ee35..a4b069d4f2 100644--- a/crates/openhuman-embed/tests/budget_fanout.rs+++ b/crates/openhuman-embed/tests/budget_fanout.rs@@ -253,6 +253,8 @@ async fn gateway_charge_precedence_and_unknown_cost_keep_budget_conservative() {(json!({"buyer_cost_micro": 0, "cost": 1}), 0),(json!({"cost": 0.0000064}), 7),(json!({"buyer_cost_micro": -1, "cost": 0}), 100),+ (json!({"buyer_cost_micro": null, "cost": 0}), 100),+ (json!({"buyer_cost_micro": "invalid", "cost": 0}), 100),(json!({"cost": -1}), 100),(json!({"cost": 1e20}), 100),(json!({}), 100),diff --git a/crates/openhuman-embed/tests/unit/completion_cost.rs b/crates/openhuman-embed/tests/unit/completion_cost.rsindex 3324bc341f..d2da4bdbf1 100644--- a/crates/openhuman-embed/tests/unit/completion_cost.rs+++ b/crates/openhuman-embed/tests/unit/completion_cost.rs@@ -67,3 +67,24 @@ fn buyer_charge_survives_without_normalized_token_usage() {assert_eq!(usage.cost_usd, Some(0.000007));assert_eq!(usage.input_tokens, 0);}++#[test]+fn authoritative_charge_presence_prevents_invalid_billing_fallbacks() {+ for raw in [+ json!({"usage": {"buyer_cost_micro": null, "cost": 0}}),+ json!({"usage": {"buyer_cost_micro": "invalid", "cost": 0}}),+ json!({"usage": {"cost": "invalid"}}),+ json!({"openhuman_usage_meta": {"charged_amount_usd": null}, "usage": {"cost": 0}}),+ ] {+ assert_eq!(cost(Some(raw), Some(12)), None);+ }+ assert_eq!(+ cost(+ Some(+ json!({"openhuman_usage_meta": {"charged_amount_usd": 0.0000064}, "usage": {"buyer_cost_micro": 42, "cost": 1}})+ ),+ Some(12)+ ),+ Some(0.0000064)+ );+}