# spendcap

**Budgets that act before the call.**

An AI agent in a loop can spend faster than any bill can tell you. One accounting agent made more than 15,000 paid
API calls in under an hour and ran up about $50,000 with no attacker involved. Providers are adding spend caps, and
most of them read the bill. `spendcap` sits in front of the agent instead: every model or tool call first reserves
the most it can cost, and a call that would cross the cap never starts.

One file, zero dependencies, Node 18+ and the browser. MIT licence.

```
npm test                            # 13 tests
node bin/spendcap.js compare runaway  # the runaway agent, six ways
node bin/spendcap.js demo
```

## What it does

- **Budgets on a path.** `acme`, `acme/finance`, `acme/finance/agent-7`: each can have a dollar and/or token limit
  per minute, hour, day, month or in total. A call counts against every budget above it.
- **Reserve, then settle.** `reserve()` holds the most a call can cost (input tokens plus the maximum output, or the
  tool's price). If any budget above it would go over, the call is refused. `settle()` charges what it really cost
  and releases the rest. Open holds count, so ten agents can't each spend the last dollar.
- **Breakers for runaway agents.** A *loop breaker* stops the same call with the same arguments repeated N times in
  a window. A *velocity breaker* stops a scope that spends more than $X in a window.
- **Pause and resume.** A cap reached or a breaker tripped pauses the scope. Only a named person can resume it, and
  the ledger keeps who and why.
- **Alerts** at the fractions you choose, once per period.
- **A simulator** that runs three workloads (a research agent, a runaway loop, a legitimate month-end burst) under six
  setups, including a cap enforced from the bill after a delay.

## The runaway agent, six ways

60 minutes, cap $1,000, seed 7. The agent works normally for five minutes, then retries the same $3.30 sync call
about 270 times a minute.

| Setup | Spent | Over the cap | Stopped |
|---|---|---|---|
| No cap | $49,536 | - | never |
| Cap from the bill, 10 min delay | $10,002 | $9,002 | 11.1 min into the loop |
| Cap from the bill, 1 min delay | $1,901 | $900.80 | 2.1 min into the loop |
| spendcap: reserve before each call | $999.90 | $0.00 | 64 s into the loop |
| spendcap + loop breaker | $95.70 | $0.00 | 4 s into the loop |
| spendcap + velocity breaker | $125.40 | $0.00 | 6 s into the loop |

A cap that reads the bill overshoots by roughly speed times delay. On the research agent and the month-end burst,
none of the setups refuses a single call, and every finished task stays finished.

## Use it

```js
const S = require("spendcap");

const cap = S.create({ onAlert: e => notify(e) });
cap.budget("acme", { usd: 500, per: "month" })
   .budget("acme/support", { usd: 20, per: "day", alertAt: [0.5, 0.9] })
   .guard("acme/support", { loop: { repeats: 10, window: 60 }, velocity: { usd: 5, window: 60 } });

const r = cap.reserve("acme/support/bot-1", { model: "standard", args: { ticket: 812 }, inTokens: 3000, maxOutTokens: 1000 });
if (!r.ok) return stop(r.why);              // "would exceed acme/support ($19.98 of $20.00 per day, this call up to $0.0175)"
const answer = await llm(...);
cap.settle(r.id, { outTokens: answer.usage.output_tokens });

// or in one go:
await cap.call("acme/support/bot-1", { tool: "search", args: { q } }, () => search(q));

cap.status("acme/support");   // { spent, held, limit, left, pct, paused, why }
cap.resume("acme/support", "dana@acme");
cap.ledger();                 // reserve, settle, deny, alert, pause, resume, cancel
```

Prices are in `S.PRICES` (generic `mini`, `standard`, `large` models per million tokens; tools per call). Pass your
own with `S.create({ prices })`.

## Command line

```
spendcap compare  <runaway|research|burst> [--cap 1000] [--minutes 60] [--seed 7]
spendcap simulate <workload> --setup <none|bill10|bill1|reserve|loop|velocity> [--cap 1000]
spendcap price    <model|tool> [inTokens] [outTokens]
spendcap replay   budgets.json calls.jsonl    (exit code 2 if any call was refused)
spendcap demo
```

## Limits

A reservation needs an upper bound for each call: the maximum output tokens for a model, a price for a tool. A tool
priced by usage needs an estimate, and the governor can only hold what it is told. The breakers' thresholds are a
trade-off: set the velocity limit below your real peak and legitimate bursts will pause. Everything runs in one
process; several processes sharing one budget need the ledger in a shared store.

## Examples

- `examples/guard-an-agent.js`: a budget tree, alerts and both breakers around a support bot.
- `examples/runaway.js`: the comparison above.
- `examples/resume-with-owner.js`: a loop is paused and a named owner resumes it.
