Skip to content

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

refactor(cost): thread dispatch context through usage recording

Steven Enamakel1d43147b6fa6
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
index 35c242157e..f75f50fcec 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
@@ -421,7 +421,8 @@ pub(in super::super) async fn run_subagent_via_graph(
crate::platform::cost::record_provider_usage_scoped(
model,
&billed,
- crate::platform::cost::UsageScope::ambient(
+ crate::platform::cost::UsageScope::in_ctx(
+ &dispatch,
Some(&usage_provider_id),
Some((agent_id, task_id)),
),
diff --git a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs b/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
index e4e743fa9f..da3f907ac2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
@@ -7,6 +7,7 @@
use std::sync::Arc;
use async_trait::async_trait;
+use crate::core::runtime::DispatchCtx;
use tinyinference_embeddings::{EmbeddingModel, Result as EmbedResult};
/// Wraps the host-bound [`EmbeddingModel`] (credentials, rate limit and
@@ -14,11 +15,12 @@ use tinyinference_embeddings::{EmbeddingModel, Result as EmbedResult};
/// call. Everything else delegates to the model.
pub(crate) struct ProviderEmbeddingModel {
model: Arc<dyn EmbeddingModel>,
+ dispatch: DispatchCtx,
}
impl ProviderEmbeddingModel {
/// Builds the cost-recording binding over `model`.
- pub(crate) fn new(model: Arc<dyn EmbeddingModel>) -> Self {
+ pub(crate) fn new(model: Arc<dyn EmbeddingModel>, dispatch: DispatchCtx) -> Self {
tracing::debug!(
provider = model.name(),
model_id = model.model_id(),
@@ -26,7 +28,7 @@ impl ProviderEmbeddingModel {
signature = %model.signature(),
"[embeddings] constructing cost-recording embedding binding"
);
- Self { model }
+ Self { model, dispatch }
}
}
@@ -60,6 +62,7 @@ impl EmbeddingModel for ProviderEmbeddingModel {
let approx_input_tokens =
tinyinference_embeddings::estimate_embedding_input_tokens(texts);
crate::platform::cost::record_embedding_usage(
+ &self.dispatch,
self.model.name(),
self.model.model_id(),
approx_input_tokens,
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
index b6753a6384..780c6f0f47 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
@@ -104,6 +104,9 @@ pub struct OpenHumanBudgetGate {
/// The ledger budgets are checked against; `None` reads the process-wide
/// cost tracker. Set by tests.
tracker: Option<Arc<cost::CostTracker>>,
+ /// The context the session runs under: budgets attributed to the user
+ /// agent (`session_agent`) read its tenant from here.
+ dispatch: crate::core::runtime::DispatchCtx,
}
impl OpenHumanBudgetGate {
@@ -128,6 +131,7 @@ impl OpenHumanBudgetGate {
last_model: RwLock::new(fallback),
background: false,
tracker: None,
+ dispatch: crate::core::runtime::DispatchCtx::unbound(),
}
}
@@ -146,6 +150,12 @@ impl OpenHumanBudgetGate {
self
}
+ /// Resolves the tenant of budget checks from `dispatch`.
+ pub fn with_dispatch(mut self, dispatch: crate::core::runtime::DispatchCtx) -> Self {
+ self.dispatch = dispatch;
+ self
+ }
+
pub fn as_background_work(mut self) -> Self {
self.background = true;
self
@@ -214,9 +224,9 @@ impl OpenHumanBudgetGate {
policies: &[crate::config::BudgetPolicy],
tracker: &cost::CostTracker,
) -> Option<String> {
- // The user agent (`session_agent` budgets) comes from the ambient
+ // The user agent (`session_agent` budgets) comes from the gate's
// context; the agent and thread from the estimate.
- let mut scope = cost::UsageScope::ambient(None, None);
+ let mut scope = cost::UsageScope::in_ctx(&self.dispatch, None, None);
if let Some(agent) = est.agent_id.as_ref().filter(|a| !a.is_empty()) {
scope.agent_id = Some(agent.clone());
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs
index e864faa4c3..898e48f95b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs
@@ -177,7 +177,9 @@ impl OpenHumanHostBundleFactory {
}
let security = Arc::new(security);
let models = Arc::new(OpenHumanModelResolver::new(Arc::clone(&inputs.config)));
- let budget = Arc::new(OpenHumanBudgetGate::new(Arc::clone(&inputs.config)));
+ let budget = Arc::new(
+ OpenHumanBudgetGate::new(Arc::clone(&inputs.config)).with_dispatch(turn.dispatch_ctx()),
+ );
// The turn's live `AgentProgress` channel is fed by exactly one
// producer: `OpenhumanEventBridge`, which `turn_exec` subscribes to
// the run's `EventSink` on every turn and which carries what the UI
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs
index 4f89760931..1aa2d5645a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs
@@ -116,6 +116,8 @@ pub(crate) struct OpenhumanEventBridge {
/// start/completed ordering (which would leave a tool row stuck `running`
/// when a `ToolCallCompleted` overtakes its `ToolCallStarted`) (#4466).
pub(super) sender: OrderedSender<AgentProgress>,
+ /// The context the run acts under; usage records take their tenant from it.
+ pub(super) dispatch: crate::core::runtime::DispatchCtx,
}
impl OpenhumanEventBridge {
@@ -136,6 +138,7 @@ impl OpenhumanEventBridge {
Arc::default(),
Arc::default(),
Vec::new(),
+ crate::core::runtime::DispatchCtx::unbound(),
)
}
@@ -157,6 +160,7 @@ impl OpenhumanEventBridge {
failure_map: ToolFailureMap,
usage_carry: ProviderUsageCarry,
tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,
+ dispatch: crate::core::runtime::DispatchCtx,
) -> Arc<Self> {
Arc::new(Self {
sender: OrderedSender::new(on_progress),
@@ -175,6 +179,7 @@ impl OpenhumanEventBridge {
unknown_calls: Mutex::new(std::collections::HashMap::new()),
tool_sets,
state: Mutex::new(BridgeState::default()),
+ dispatch,
})
}
@@ -416,7 +421,11 @@ impl OpenhumanEventBridge {
crate::platform::cost::record_provider_usage_scoped(
&self.model,
&usage_info,
- crate::platform::cost::UsageScope::ambient(Some(&self.provider_id), subagent)
+ crate::platform::cost::UsageScope::in_ctx(
+ &self.dispatch,
+ Some(&self.provider_id),
+ subagent,
+ )
.with_definition(self.definition.get().map(String::as_str)),
);
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index b04fe8ccf1..e73d220fc9 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@ -380,6 +380,7 @@ async fn drive_turn(
failure_map.clone(),
provider_usage_carry.clone(),
bridge_tool_sets.clone(),
+ run_context.dispatch_ctx(),
);
bridge.set_definition(
run_context
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs
index 36d0602f09..2af5deec41 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs
@@ -99,6 +99,7 @@ pub(crate) struct TinyagentsTurnOutcome {
/// count. Recording is best-effort — a missing/uninitialised tracker is a
/// silent no-op by contract.
pub(crate) fn record_unobserved_turn_usage(
+ ctx: &crate::core::runtime::DispatchCtx,
model: &str,
input_tokens: u64,
output_tokens: u64,
@@ -123,7 +124,7 @@ pub(crate) fn record_unobserved_turn_usage(
Some(usd) => usage.with_estimated_usd(usd),
None => usage,
};
- crate::platform::cost::record_provider_usage(model, &usage);
+ crate::platform::cost::record_provider_usage(ctx, model, &usage);
true
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
index bd7174bc2f..7ec4f3a3f4 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
@@ -117,6 +117,7 @@ pub(super) async fn finalize_turn_outcome(
.with_cached_input_tokens(cached),
);
crate::agent::tinyagents::turn_outcome::record_unobserved_turn_usage(
+ &run_context.dispatch_ctx(),
model, input, output, cached, estimate,
);
let mut cost = tinyagents_harness::cost::CostTally::default();
diff --git a/crates/openhuman-core/src/platform/cost/global.rs b/crates/openhuman-core/src/platform/cost/global.rs
index 5138a6b120..3981e0e82d 100644
--- a/crates/openhuman-core/src/platform/cost/global.rs
+++ b/crates/openhuman-core/src/platform/cost/global.rs
@@ -19,6 +19,7 @@ use std::sync::Arc;
use parking_lot::RwLock;
+use crate::core::runtime::DispatchCtx;
use crate::config::CostConfig;
use crate::inference::provider::types::BilledUsage;