Skip to content

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

docs(cost): document budget policies and their enforcement

Steven Enamakel35a05941a8f0
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 dffd370a8b..59cf07fb9a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/budget_gate.rs
@@ -185,7 +185,11 @@ impl OpenHumanBudgetGate {
return None;
}
};
- for hit in verdict.hits.iter().filter(|hit| hit.action == crate::config::BudgetAction::Warn || !hit.exceeded) {
+ for hit in verdict
+ .hits
+ .iter()
+ .filter(|hit| hit.action == crate::config::BudgetAction::Warn || !hit.exceeded)
+ {
log::warn!(
"[tinyagents][budget] budget `{}` for {} at ${:.4}/{:?} usd, {}/{:?} tokens (exceeded={})",
hit.policy,
diff --git a/crates/openhuman-core/src/platform/cost/README.md b/crates/openhuman-core/src/platform/cost/README.md
index 14e6fcbbb9..ea88de45f8 100644
--- a/crates/openhuman-core/src/platform/cost/README.md
+++ b/crates/openhuman-core/src/platform/cost/README.md
@@ -27,6 +27,7 @@ Local API-usage cost tracking for the agent. Records per-call token usage and co
| `crates/openhuman-core/src/platform/cost/route.rs` | `CostRoute` / `route_for_model`: derives from the model id whether a record counts against OpenHuman-managed credits or is BYOK/local (#5016). |
| `crates/openhuman-core/src/platform/cost/scope.rs` | `UsageScope::ambient`: a record's attribution (thread, origin, agent definition, sub-agent task, embedded/SaaS user agent, provider) read from the recording task's turn origin, memory identity and `CoreContext`. |
| `crates/openhuman-core/src/platform/cost/report.rs` | Pure usage reports over ledger records: `build_report` (group by day/week/month/model/provider/route/agent/thread/origin/session_agent; tokens, charged vs estimated cost, cache-hit ratio) and `build_cache_report` (per-call hits, cold calls, uncached premium). |
+| `crates/openhuman-core/src/platform/cost/budget.rs` | Budgets (`[[cost.budgets]]`): `evaluate` / `check_call` sum a policy's bucket (global, or this call's thread/agent/model/provider/user agent) over its day or month and report warnings and refusals. The agent budget gate (`agent/tinyagents/host/budget_gate.rs`) runs it before every model call. |
| `crates/openhuman-core/src/platform/cost/tools.rs` | Read-only, default-on LLM tools (`cost_get_dashboard`, `cost_get_daily_history`, …) re-exported through `crates/openhuman-core/src/tools/mod.rs`. |
## Public surface
@@ -97,3 +98,30 @@ None. The module has no `bus.rs` and no `DomainEvent` publishers/subscribers.
- Legacy `budget_utilization` is clamped to `1.0` in the RPC payload; `budget_status` is computed from the raw (unclamped) utilisation against `warn`/`alert` thresholds. A non-positive monthly limit forces `BudgetStatus::Normal` and `0.0` utilisation.
- All amounts are stored/computed in USD; `currency` is a presentation hint only.
- Time bucketing is UTC throughout (`naive_utc().date()`); model is the bucket key for per-model stats, and `provider` is derived from the `provider/model` slash prefix in DTO mapping.
+
+## Budgets
+
+Budgets are opt-in and empty by default:
+
+```toml
+[[cost.budgets]]
+name = "monthly cap"
+max_usd = 50.0 # and/or max_tokens
+period = "month" # or "day" (UTC)
+action = "refuse" # or "warn" (default)
+
+[[cost.budgets]]
+name = "planner per day"
+scope = "agent" # global (default) | thread | agent | model | provider | session_agent
+match = "planner" # omit to apply to each value separately
+period = "day"
+max_usd = 2.0
+warn_fraction = 0.8 # default
+```
+
+Before every model call, the agent's budget gate (`OpenHumanBudgetGate::acquire`) sums each policy's bucket from the ledger over its period:
+
+- **Refuse:** a `refuse` policy at or over its limit refuses the call with `TinyAgentsError::LimitExceeded("BUDGET_EXCEEDED: …")`, before any scheduler slot is taken.
+- **Warn:** a `warn` policy, or any policy past `warn_fraction`, logs a warning.
+- **Unattributed calls:** a call without the policy's attribute is outside it. For example, a call with no thread is outside a per-thread budget.
+- **No checking at all** when no budgets are configured, when there is no cost tracker, or when the ledger cannot be read. The budget check never fails a call for a reason of its own.
diff --git a/crates/openhuman-core/src/platform/cost/budget_tests.rs b/crates/openhuman-core/src/platform/cost/budget_tests.rs
index 30bba7a07c..973f8b4771 100644
--- a/crates/openhuman-core/src/platform/cost/budget_tests.rs
+++ b/crates/openhuman-core/src/platform/cost/budget_tests.rs
@@ -17,7 +17,12 @@ fn spend(day: u32, model: &str, agent: Option<&str>, thread: Option<&str>, usd:
CostRecord::new("s", usage)
}
-fn policy(scope: BudgetScope, period: BudgetPeriod, max_usd: f64, action: BudgetAction) -> BudgetPolicy {
+fn policy(
+ scope: BudgetScope,
+ period: BudgetPeriod,
+ max_usd: f64,
+ action: BudgetAction,
+) -> BudgetPolicy {
BudgetPolicy {
name: Some("test".into()),
scope,
@@ -48,20 +53,40 @@ fn period_starts_are_midnight_and_the_first_of_the_month() {
#[test]
fn a_global_monthly_budget_refuses_once_reached() {
- let records = vec![spend(2, "m", None, None, 6.0), spend(14, "m", None, None, 4.0)];
- let policies = vec![policy(BudgetScope::Global, BudgetPeriod::Month, 10.0, BudgetAction::Refuse)];
+ let records = vec![
+ spend(2, "m", None, None, 6.0),
+ spend(14, "m", None, None, 4.0),
+ ];
+ let policies = vec![policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 10.0,
+ BudgetAction::Refuse,
+ )];
let scope = UsageScope::default();
let verdict = evaluate(&policies, &records, call("m", &scope), now());
let hit = verdict.refusal().expect("refused");
assert!(hit.exceeded);
assert_eq!(hit.bucket, "*");
- assert!(hit.refusal().starts_with("BUDGET_EXCEEDED:"), "{}", hit.refusal());
+ assert!(
+ hit.refusal().starts_with("BUDGET_EXCEEDED:"),
+ "{}",
+ hit.refusal()
+ );
}
#[test]
fn a_daily_budget_counts_only_today() {
- let records = vec![spend(14, "m", None, None, 9.0), spend(15, "m", None, None, 1.0)];
- let policies = vec![policy(BudgetScope::Global, BudgetPeriod::Day, 5.0, BudgetAction::Refuse)];
+ let records = vec![
+ spend(14, "m", None, None, 9.0),
+ spend(15, "m", None, None, 1.0),
+ ];
+ let policies = vec![policy(
+ BudgetScope::Global,
+ BudgetPeriod::Day,
+ 5.0,
+ BudgetAction::Refuse,
+ )];
let scope = UsageScope::default();
let verdict = evaluate(&policies, &records, call("m", &scope), now());
assert!(verdict.hits.is_empty(), "{verdict:?}");
@@ -72,17 +97,30 @@ fn warn_policies_and_the_warn_fraction_never_refuse() {
let records = vec![spend(10, "m", None, None, 8.5)];
let scope = UsageScope::default();
let near = evaluate(
- &[policy(BudgetScope::Global, BudgetPeriod::Month, 10.0, BudgetAction::Refuse)],
+ &[policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 10.0,
+ BudgetAction::Refuse,
+ )],
&records,
call("m", &scope),
now(),
);
assert_eq!(near.hits.len(), 1);
assert!(!near.hits[0].exceeded);
- assert!(near.refusal().is_none(), "past the warn fraction is only a warning");
+ assert!(
+ near.refusal().is_none(),
+ "past the warn fraction is only a warning"
+ );
let over_warn_only = evaluate(
- &[policy(BudgetScope::Global, BudgetPeriod::Month, 5.0, BudgetAction::Warn)],
+ &[policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 5.0,
+ BudgetAction::Warn,
+ )],
&records,
call("m", &scope),
now(),
@@ -97,7 +135,12 @@ fn per_agent_budgets_count_each_agent_separately() {
spend(10, "m", Some("planner"), None, 9.0),
spend(10, "m", Some("orchestrator"), None, 1.0),
];
- let policies = vec![policy(BudgetScope::Agent, BudgetPeriod::Month, 5.0, BudgetAction::Refuse)];
+ let policies = vec![policy(
+ BudgetScope::Agent,
+ BudgetPeriod::Month,
+ 5.0,
+ BudgetAction::Refuse,
+ )];
let planner = UsageScope {
agent_id: Some("planner".into()),
..UsageScope::default()
@@ -106,54 +149,111 @@ fn per_agent_budgets_count_each_agent_separately() {
agent_id: Some("orchestrator".into()),
..UsageScope::default()
};
- assert!(evaluate(&policies, &records, call("m", &planner), now()).refusal().is_some());
- assert!(evaluate(&policies, &records, call("m", &orchestrator), now()).hits.is_empty());
+ assert!(evaluate(&policies, &records, call("m", &planner), now())
+ .refusal()
+ .is_some());
+ assert!(
+ evaluate(&policies, &records, call("m", &orchestrator), now())
+ .hits
+ .is_empty()
+ );
// A call with no agent is outside a per-agent budget.
let unattributed = UsageScope::default();
- assert!(evaluate(&policies, &records, call("m", &unattributed), now()).hits.is_empty());
+ assert!(
+ evaluate(&policies, &records, call("m", &unattributed), now())
+ .hits
+ .is_empty()
+ );
}
#[test]
fn a_match_limits_the_budget_to_one_bucket() {
- let records = vec![spend(10, "expensive", None, None, 9.0), spend(10, "cheap", None, None, 9.0)];
- let mut only_expensive = policy(BudgetScope::Model, BudgetPeriod::Month, 5.0, BudgetAction::Refuse);
+ let records = vec![
+ spend(10, "expensive", None, None, 9.0),
+ spend(10, "cheap", None, None, 9.0),
+ ];
+ let mut only_expensive = policy(
+ BudgetScope::Model,
+ BudgetPeriod::Month,
+ 5.0,
+ BudgetAction::Refuse,
+ );
only_expensive.matches = Some("expensive".into());
let scope = UsageScope::default();
- assert!(evaluate(&[only_expensive.clone()], &records, call("expensive", &scope), now())
- .refusal()
- .is_some());
- assert!(evaluate(&[only_expensive], &records, call("cheap", &scope), now())
- .hits
- .is_empty());
+ assert!(evaluate(
+ &[only_expensive.clone()],
+ &records,
+ call("expensive", &scope),
+ now()
+ )
+ .refusal()
+ .is_some());
+ assert!(
+ evaluate(&[only_expensive], &records, call("cheap", &scope), now())
+ .hits
+ .is_empty()
+ );
}
#[test]
fn token_limits_count_input_and_output() {
- let records = vec![spend(10, "m", None, None, 0.0), spend(11, "m", None, None, 0.0)];
- let mut tokens = policy(BudgetScope::Global, BudgetPeriod::Month, 0.0, BudgetAction::Refuse);
+ let records = vec![
+ spend(10, "m", None, None, 0.0),
+ spend(11, "m", None, None, 0.0),
+ ];
+ let mut tokens = policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 0.0,
+ BudgetAction::Refuse,
+ );
tokens.max_usd = None;
tokens.max_tokens = Some(3000);
let scope = UsageScope::default();
let verdict = evaluate(&[tokens], &records, call("m", &scope), now());
let hit = verdict.refusal().expect("3000 tokens used");
assert_eq!(hit.tokens, 3000);
- assert!(hit.refusal().contains("3000 of 3000 tokens"), "{}", hit.refusal());
+ assert!(
+ hit.refusal().contains("3000 of 3000 tokens"),
+ "{}",
+ hit.refusal()
+ );
}
#[test]
fn a_policy_without_limits_is_ignored() {
- let mut empty = policy(BudgetScope::Global, BudgetPeriod::Month, 0.0, BudgetAction::Refuse);
+ let mut empty = policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 0.0,
+ BudgetAction::Refuse,
+ );
empty.max_usd = None;
let scope = UsageScope::default();
- let verdict = evaluate(&[empty], &[spend(10, "m", None, None, 99.0)], call("m", &scope), now());
+ let verdict = evaluate(
+ &[empty],
+ &[spend(10, "m", None, None, 99.0)],
+ call("m", &scope),
+ now(),
+ );
assert!(verdict.hits.is_empty());
}
#[test]
fn earliest_start_covers_the_longest_period() {
let policies = vec![
- policy(BudgetScope::Global, BudgetPeriod::Day, 1.0, BudgetAction::Warn),
- policy(BudgetScope::Global, BudgetPeriod::Month, 1.0, BudgetAction::Warn),
+ policy(
+ BudgetScope::Global,
+ BudgetPeriod::Day,
+ 1.0,
+ BudgetAction::Warn,
+ ),
+ policy(
+ BudgetScope::Global,
+ BudgetPeriod::Month,
+ 1.0,
+ BudgetAction::Warn,
+ ),
];
assert_eq!(
earliest_start(&policies, now()),