buzz icon indicating copy to clipboard operation
buzz copied to clipboard

Agent API budgets and owner-wide spend visibility

Open mhyatt18 opened this issue 3 months ago • 3 comments

Motivation

Buzz can run multiple agents across channels, sessions, schedules, and background activity. That makes it easy for API usage to grow without the owner noticing until the provider bill arrives.

Owners need two connected controls:

  1. An enforceable API budget for each agent.
  2. A clear view of total agent spend across daily, weekly, and monthly windows.

Visibility alone is not enough. A dashboard can explain a large bill after the fact, but it cannot prevent one. Conversely, a per-agent limit is difficult to manage without seeing the overall portfolio.

Proposed solution

Add an owner-only Usage & Budgets surface that builds on the existing NIP-AM agent-turn metrics.

1. Per-agent budgets

Let the owner configure one or more USD limits for each agent:

  • daily;
  • weekly;
  • monthly.

Each configured limit should support:

  • a warning threshold before the limit is reached;
  • a hard-stop mode that allows the current turn to finish but prevents the next billable turn from starting;
  • a visible paused state explaining which budget was reached, the spend counted, and when the budget resets;
  • an explicit owner override by raising the limit, disabling it, or resuming after review;
  • enforcement across every channel, session, scheduled task, heartbeat, retry, and worker for that agent.

A restart, additional worker, or parallel session must not create a fresh budget. The limit belongs to the agent identity and owner, not to one process or channel.

2. Owner-wide spend dashboard

Show the owner:

  • total agent spend today, this week, and this month;
  • spend by agent;
  • spend by provider, model, and harness where that evidence is available;
  • current budget consumption and remaining amount for each agent;
  • a clear warning when usage or cost data is partial, delayed, estimated, or unavailable.

Daily, weekly, and monthly boundaries should use the owner’s configured timezone. Weekly boundaries should be explicit rather than silently assuming a locale.

3. Safe accounting and enforcement

NIP-AM already distinguishes known and unknown usage fields. Budget handling should preserve that discipline:

  • never treat unknown cost as $0;
  • distinguish provider-reported cost from a Buzz estimate;
  • identify the provider/model/pricing source used for any estimate;
  • avoid double-counting cumulative metrics, retries, session rotation, or cross-device archive sync;
  • state clearly that the provider’s own billing dashboard and invoice remain authoritative.

For a hard budget, incomplete accounting should fail safely. If Buzz cannot determine whether the next turn would violate the budget, it should pause before that turn and tell the owner why, rather than silently spending past the limit.

4. Notifications and recovery

  • Notify the owner when a warning threshold or hard limit is reached.
  • Do not let an agent caught by a limit enter a retry or respawn loop.
  • Resume automatically only when the applicable calendar window resets; otherwise require an explicit owner action.
  • Preserve a lightweight audit trail of budget changes, limit hits, overrides, and resumes.

Alternatives considered

  • Rely only on provider dashboards: providers show account-level billing, but not consistently by Buzz agent, channel, scheduled task, or workflow.
  • Ship usage charts without enforcement: useful for analysis, but it does not prevent surprise bills.
  • Use token limits only: token prices vary by provider, model, cache class, and time. Tokens remain useful diagnostic evidence, but they are not a reliable cross-provider budget unit.
  • Stop the current turn immediately: risks corrupting work or leaving tools and external actions half-complete. Preventing the next billable turn is safer and more predictable.

Additional context

  • No direct duplicate found in open issues or pull requests.
  • #3632 asks whether Buzz has monthly per-agent cost gating, but it is an architecture question rather than a product specification.
  • #4000 landed the NIP-AM usage aggregation backend, including fail-closed handling for unknown cost and pricing identity.
  • #4001 is the open owner-only usage UI for 1-day, 7-day, 30-day, and custom ranges. This request extends that visibility into budgets and enforcement rather than replacing it.
  • #5327 documents a real retry/respawn storm that exhausted a provider spend limit, illustrating why enforcement must cover retries and fail safely.

Acceptance criteria

  • An owner can set daily, weekly, and monthly USD limits independently for an agent.
  • The owner can see aggregate spend for today, this week, and this month, with a per-agent breakdown.
  • A hard-limited agent cannot start another billable turn after reaching its limit.
  • The budget applies across all of that agent’s channels, sessions, workers, retries, and scheduled activity.
  • Unknown or incomplete cost is never displayed or enforced as zero.
  • The UI distinguishes reported, estimated, partial, and unavailable spend.
  • The owner can identify why an agent is paused and either wait for reset or explicitly override the budget.

mhyatt18 avatar Aug 12 '26 11:08 mhyatt18

Saw your issue on budget/spend handling — ran into similar pain building LLMCap, pre-request hard spend caps for LLM API calls (blocks before the call, not after). Curious if that's close to what you needed here, or if I'm off base. Free demo if useful: https://app.llmcap.io/demo — no pressure either way, just gathering feedback from people hitting this problem.

celikkanat avatar Aug 28 '26 15:08 celikkanat

The accounting rules in section 3 are the important part and they're a record problem, not a dashboard problem. "Never treat unknown cost as $0", "reported vs estimate", "name the pricing source", "don't double count retries" are all things that have to be true of each turn's record or the totals can't be trusted no matter how the UI draws them.

Concretely, building on 44200's per-turn event and turnSeq: one signed record per billable turn, with reported_cost and estimated_cost as separate fields (either may be absent, neither defaults to zero), the pricing source for the estimate, the model and provider that actually answered, and a sequence or chain so a reader can see when a turn is missing. Then the daily/weekly/monthly figures are sums anyone can re-add - which is also what #8556 needs for an external reader, and what #9207 needs so the 402 case shows up as "turn refused: balance exhausted" instead of silence.

I've opened #9299 to ask where that record should live relative to 44200, so I won't repeat the design here. #4000's aggregation already has the fail-closed handling for unknown cost; the question is whether the per-turn evidence behind it is something a non-owner can ever check. In buzz-app the Usage plugin is the live surface now, and it labels its figures a best-effort estimate from local session files; a signed per-turn receipt is what turns that estimate into something checkable.

StevenMih avatar Nov 09 '26 19:11 StevenMih

TurnUsage::turn_cost_usd in crates/buzz-acp/src/usage.rs already gives a per-turn cost (or None), but nothing checks it before the next turn starts. I wrote llm-budget (crates.io), a small Rust crate that covers only the enforcement piece: a hard USD cap per agent, booking each finished turn so the counter matches the bill, refusing the next turn once the cap is hit, a kill switch for "cost unknown, pause for the owner", and an audit record per charge. Here's roughly how it could sit around TurnCompletionGuard. I compiled and ran this against 0.3.1:

use llm_budget::{AgentBudget, BudgetError, ChargeContext};

/// One cap per agent per window. `spent_so_far` comes from the 44200
/// aggregation, so a restart or a second worker starts from the real number.
fn window_cap(agent: &str, limit_usd: f64, spent_so_far: f64) -> Result<AgentBudget, BudgetError> {
    let cap = AgentBudget::builder(agent, limit_usd).build()?;
    cap.charge_usd_force(spent_so_far, ChargeContext::new().task("rehydrate"));
    Ok(cap)
}

/// Before any billable turn: channel, schedule, heartbeat or retry.
fn may_start_turn(cap: &AgentBudget) -> Result<(), String> {
    if cap.is_killed() || cap.is_exhausted() {
        return Err(format!("paused: spent ${:.2} of ${:.2}", cap.spent_usd(), cap.limit_usd()));
    }
    Ok(())
}

/// After the turn completes. Unknown cost pauses instead of counting as $0.
fn book_turn(cap: &AgentBudget, session: &str, model: &str, turn_cost_usd: Option<f64>) {
    match turn_cost_usd {
        Some(usd) => {
            let out = cap.charge_usd_force(usd, ChargeContext::new().session(session).model(model));
            if out.over_cap {
                println!("limit reached, next turn will be refused");
            }
        }
        None => cap.kill("turn cost unknown; owner review needed"),
    }
}

fn main() -> Result<(), BudgetError> {
    let daily = window_cap("agent-npub1abc", 5.00, 4.20)?;
    may_start_turn(&daily).unwrap();
    book_turn(&daily, "sess-1", "claude-opus-4-5", Some(0.95));
    println!("{:?}", may_start_turn(&daily)); // Err("paused: spent $5.15 of $5.00")
    Ok(())
}

To be clear about the limits: it has no calendar windows or owner timezone (you'd build one cap per window and rebuild at the boundary, and show the reset time yourselves), and the counter is in-process, so the shared state across restarts, workers and parallel sessions still has to come from Buzz's own aggregation, as in the rehydrate step above. If you already have that aggregation, the gate itself is small, so this may only be worth it if you want the kill switch and audit trail ready-made.

Mattbusel avatar Nov 15 '26 02:11 Mattbusel