Skip to content

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

feat(budget): add budget gate for tinyagents host

Steven Enamakel6227e9bd8972
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 59cf07fb9a..e488883054 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
@@ -10,10 +10,12 @@
//! * **admission / back-pressure** — [`scheduler_gate::wait_for_capacity`],
//! which owns the single-slot global LLM semaphore and the
//! AC-power / CPU / signed-out policy backoff;
-//! * **pricing hints** — [`cost::catalog::estimate_cost_usd`] on the way in.
-//! Nothing here refuses a call on cost, and nothing here writes the cost
-//! ledger: the event bridge records each model call under its real model, and
-//! a second write from this gate double-counted tokens and requests;
+//! * **pricing hints and budgets** — [`cost::catalog::estimate_cost_usd`] on
+//! the way in, and the opt-in `[[cost.budgets]]` policies, which can refuse a
+//! call (`BUDGET_EXCEEDED`). The legacy `monthly_limit_usd` still refuses
+//! nothing. Nothing here writes the cost ledger: the event bridge records
+//! each model call under its real model, and a second write from this gate
+//! double-counted tokens and requests;
//! * **compression advice** — the agent's
//! [`AgentTokenjuiceCompression`] profile, which decides how much lossy
//! compaction that agent tolerates.
@@ -77,9 +79,8 @@ use crate::platform::cost;
/// of state needed to bridge the two contract mismatches described in the
/// module docs.
pub struct OpenHumanBudgetGate {
- /// Session config. Read only for the fallback model id — everything
- /// budget-shaped is read live from the global cost tracker so a settings
- /// update takes effect without rebuilding the gate.
+ /// Session config: the fallback model id, and where `[[cost.budgets]]` is
+ /// re-read from on each check (see [`Self::live_budgets`]).
config: Arc<Config>,
/// The agent's TokenJuice profile, which bounds how aggressive a
/// compression hint this gate is willing to give.
@@ -149,31 +150,71 @@ impl OpenHumanBudgetGate {
/// for a reason of its own: without budgets, a cost tracker or a readable
/// ledger, the call goes ahead.
fn check_budgets(&self, est: &CallEstimate) -> Option<String> {
- if self.config.cost.budgets.is_empty() {
+ let policies = self.live_budgets();
+ if policies.is_empty() {
return None;
}
let Some(tracker) = cost::try_global() else {
log::debug!("[tinyagents][budget] budgets configured but no cost tracker; not checked");
return None;
};
- self.check_budgets_against(est, &tracker)
+ self.check_budgets_against(est, &policies, &tracker)
}
- /// [`Self::check_budgets`] against an explicit ledger.
+ /// The `[[cost.budgets]]` in effect now. A session's gate outlives
+ /// settings changes (cached web-chat sessions keep theirs), so the
+ /// session's `config.toml` is re-read on every check; an embedder config
+ /// with no file on disk, or one that does not parse, keeps the policies
+ /// the gate was built with.
+ fn live_budgets(&self) -> Vec<crate::config::BudgetPolicy> {
+ #[derive(serde::Deserialize, Default)]
+ struct File {
+ #[serde(default)]
+ cost: Cost,
+ }
+ #[derive(serde::Deserialize, Default)]
+ struct Cost {
+ #[serde(default)]
+ budgets: Vec<crate::config::BudgetPolicy>,
+ }
+ match std::fs::read_to_string(&self.config.config_path) {
+ Ok(raw) => match toml::from_str::<File>(&raw) {
+ Ok(file) => file.cost.budgets,
+ Err(error) => {
+ log::debug!(
+ "[tinyagents][budget] config budgets unreadable ({error}); using the session's"
+ );
+ self.config.cost.budgets.clone()
+ }
+ },
+ Err(_) => self.config.cost.budgets.clone(),
+ }
+ }
+
+ /// [`Self::check_budgets`] against explicit policies and ledger.
pub(crate) fn check_budgets_against(
&self,
est: &CallEstimate,
+ policies: &[crate::config::BudgetPolicy],
tracker: &cost::CostTracker,
) -> Option<String> {
- let policies = &self.config.cost.budgets;
- let mut scope = cost::UsageScope::ambient(None, None);
+ // The provider this session's calls go to, so `provider` budgets have
+ // a bucket; the user agent comes from the ambient context.
+ let provider = crate::platform::cost::provider_of_model(&self.attributed_model());
+ let mut scope = cost::UsageScope::ambient(provider.as_deref(), None);
if let Some(agent) = est.agent_id.as_ref().filter(|a| !a.is_empty()) {
scope.agent_id = Some(agent.clone());
}
if let Some(thread) = est.thread_id.as_ref() {
scope.thread_id = Some(thread.as_str().to_string());
}
- let model = self.attributed_model();
+ // This call's own model: `last_model` is shared by every call on the
+ // gate and may already belong to another one.
+ let model = if est.model.trim().is_empty() {
+ self.attributed_model()
+ } else {
+ est.model.clone()
+ };
let call = cost::budget::CallUnderCheck {
model: &model,
scope: &scope,
@@ -188,7 +229,8 @@ impl OpenHumanBudgetGate {
for hit in verdict
.hits
.iter()
- .filter(|hit| hit.action == crate::config::BudgetAction::Warn || !hit.exceeded)
+ // Every hit is worth a line: a warning, or the refusal about to be
+ // returned.
{
log::warn!(
"[tinyagents][budget] budget `{}` for {} at ${:.4}/{:?} usd, {}/{:?} tokens (exceeded={})",
diff --git a/crates/openhuman-core/src/platform/cost/budget.rs b/crates/openhuman-core/src/platform/cost/budget.rs
index 4d890e4b5b..713c127ae5 100644
--- a/crates/openhuman-core/src/platform/cost/budget.rs
+++ b/crates/openhuman-core/src/platform/cost/budget.rs
@@ -140,20 +140,22 @@ pub fn evaluate(
continue;
}
spent_usd += usage.cost_usd;
- tokens += usage.input_tokens + usage.output_tokens;
+ // Saturating: a corrupt record must not wrap a total back under
+ // its limit.
+ tokens = tokens.saturating_add(usage.input_tokens.saturating_add(usage.output_tokens));
}
let over = |spent: f64, max: Option<f64>, fraction: f64| {
max.is_some_and(|max| max >= 0.0 && spent >= max * fraction)
};
let warn_fraction = policy.warn_fraction.clamp(0.0, 1.0);
+ // Token limits compare as integers; only the warn threshold, a
+ // fraction of the limit, is computed in floating point.
let exceeded = over(spent_usd, policy.max_usd, 1.0)
- || over(tokens as f64, policy.max_tokens.map(|t| t as f64), 1.0);
+ || policy.max_tokens.is_some_and(|max| tokens >= max);
let warning = over(spent_usd, policy.max_usd, warn_fraction)
- || over(
- tokens as f64,
- policy.max_tokens.map(|t| t as f64),
- warn_fraction,
- );
+ || policy.max_tokens.is_some_and(|max| {
+ tokens >= max || (tokens as f64) >= (max as f64) * warn_fraction
+ });
if exceeded || warning {
verdict.hits.push(BudgetHit {
policy: policy