# Budgets and limits

> Bound each run by turns, time and tokens.

A host bounds what a run may spend. Each limit ends the run with its own
outcome, so you can tell why it stopped:

```go
// core/guide_example_test.go
p, err := replay.New(provider.Caps{ContextWindow: 200_000, MaxOutputTokens: 8_192},
	replay.ToolCalls(history.ToolCall{ID: "c1", Name: "TaskList", Input: json.RawMessage(`{}`)}),
	replay.Reported("met", "Done."))
if err != nil {
	panic(err)
}
ctx := context.Background()
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeBypass),
	zelk.WithMaxTurns(1),
	zelk.WithMaxTime(10*time.Minute),
	zelk.WithBudget(event.Budget{Total: event.Limit{Max: 1_000_000}}))
if err != nil {
	panic(err)
}
defer a.Close(ctx)
s, err := a.Session(ctx, "bounded-1")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Tidy up.")))
if err != nil {
	panic(err)
}
res, err := x.Wait(ctx)
if err != nil {
	panic(err)
}
fmt.Println(res.Outcome, res.Turns)
// Output: max_turns 1
```

| Option | Bounds | Outcome when reached |
|---|---|---|
| `WithMaxTurns(n)` | model turns per run | `max_turns` |
| `WithMaxTime(d)` | wall time per run, crash downtime included | `max_budget` |
| `WithBudget(event.Budget{…})` | input, output and total tokens per run | `max_budget` |
| `WithQuotas(event.Quotas{…})` | spending across runs | `quota_exceeded` |
| `WithSubagentBudget(event.Tokens{…})` | each subagent's own allocation, reserved from its parent's budget | |

## Hard and soft limits

A **hard** token limit is enforced before each model call: zelk reserves
the most the call could use, from the model's context window and output
limit, and doesn't make a call the budget can't cover. So a hard budget
needs a model whose limits are known, and `New` or `Start` says so when
they aren't. A **soft** limit (`event.Limit{Max: n, Soft: true}`) lets the
run go past it once, with a warning and one turn to wrap up.

Every attempt is settled in the session's budget ledger exactly once, even
across crashes, so `Result.Ledger` and `Result.Usage` add up.

The [durability contract](/internals/durability/) specifies the ledger.

## Next

[Stores, leases and recovery](/go/stores/) keeps sessions past the process.
