<!-- source: https://deepwiki.com/qhkm/zeptoclaw/10.7-cost-tracking-and-quotas -->

# Cost Tracking and Quotas

- src/agent/scratchpad.rs
- src/providers/quota.rs
- src/providers/rotation.rs
- src/r8r_bridge/mod.rs
- src/utils/metrics.rs
- src/utils/mod.rs
- src/utils/slo.rs

ZeptoClaw provides comprehensive cost tracking and quota enforcement for LLM API usage. The system monitors token consumption, calculates estimated costs per provider/model, and enforces configurable quota limits to prevent unexpected billing. Quotas can be set per-provider with flexible actions (reject, fallback, or warn) when limits are exceeded.

## Overview

ZeptoClaw implements a multi-layered cost control architecture:

1. Token Counting : Real-time tracking of input and output tokens per session src/utils/metrics.rs 54-55
2. Quota Enforcement : Per-provider cost (USD) and token quotas with configurable reset periods (Daily/Monthly) src/providers/quota.rs 40-48
3. Cost Estimation : Per-provider/per-model pricing calculation for major models src/utils/cost.rs 1-10
4. Service Level Objectives (SLO) : Tracking of tool success rates and p95 latencies src/utils/slo.rs 14-16
5. Result Sanitization : Dynamic byte-budgeting for tool outputs to prevent context-filling token waste src/utils/sanitize.rs 91-103
6. Cost-Aware Selection : Automatic provider selection based on real-time pricing data via RotationStrategy::CostAware src/providers/rotation.rs 50-58

The quota system operates as a provider decorator (`QuotaProvider`), while session metrics are handled by a thread-safe `MetricsCollector` [src/utils/metrics.rs51-56](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L51-L56)

**Sources:** [src/providers/quota.rs1-5](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L1-L5) [src/utils/metrics.rs1-5](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L1-L5) [src/utils/slo.rs1-6](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/slo.rs#L1-L6) [src/utils/sanitize.rs1-5](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/sanitize.rs#L1-L5) [src/providers/rotation.rs50-58](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/rotation.rs#L50-L58)

## Quota Management System

### Quota Logic and Persistence

The `QuotaStore` manages the persistent state of API usage, typically stored in `~/.zeptoclaw/quota/usage.json` [src/providers/quota.rs115-125](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L115-L125) It tracks `QuotaUsage` which includes the `period_key` (e.g., `"2026-03"` for monthly or `"2026-03-01"` for daily), accumulated `cost_usd`, and total `tokens` [src/providers/quota.rs91-101](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L91-L101)

#### Quota Component Diagram

```

```

**Sources:** [src/providers/quota.rs40-77](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L40-L77) [src/providers/quota.rs91-113](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L91-L113) [src/providers/quota.rs120-125](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L120-L125)

### Quota Enforcement Flow

When a request is made through a provider wrapped in a quota check, the system evaluates the current usage against the `QuotaConfig`.

1. Check : QuotaStore::check compares usage.cost_usd and usage.tokens against limits src/providers/quota.rs 170-207
2. Thresholds : If usage is ≥ 80% (defined by WARNING_THRESHOLD ), it returns QuotaCheckResult::Warning src/providers/quota.rs 128-169 If ≥ 100%, it returns Exceeded src/providers/quota.rs 209-211
3. Record : After a successful LLM call, QuotaStore::record updates the persistent state src/providers/quota.rs 222-240

**Sources:** [src/providers/quota.rs128-213](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L128-L213) [src/providers/quota.rs222-240](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L222-L240)

## Session Metrics and SLOs

### Metrics Collection

The `MetricsCollector` uses a `Mutex<HashMap<String, ToolMetrics>>` to track per-tool execution statistics including `call_count`, `error_count`, and durations [src/utils/metrics.rs11-24](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L11-L24) It also maintains global session token totals [src/utils/metrics.rs54-55](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L54-L55)

#### Metrics Entity Mapping

```

```

**Sources:** [src/utils/metrics.rs11-24](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L11-L24) [src/utils/metrics.rs51-56](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L51-L56) [src/utils/slo.rs18-35](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/slo.rs#L18-L35) [src/utils/slo.rs39-40](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/slo.rs#L39-L40)

### SLO Tracking

The `SessionSLO` system evaluates session performance against predefined targets:

- Tool Success Rate : Target ≥ 95% ( SLO_TOOL_SUCCESS_RATE ) src/utils/slo.rs 15
- Latency : Approximate p95 tool latency < 10s ( SLO_P95_LATENCY_SECS ) src/utils/slo.rs 16
- Completion : Verification that the agent produced a final response via agent_completed src/utils/slo.rs 25-26

The `worst_case_tool_latency` is computed using a rough upper-bound estimate: `avg + 2 * (max - avg)` clamped to max [src/utils/metrics.rs134-156](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L134-L156)

**Sources:** [src/utils/slo.rs14-35](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/slo.rs#L14-L35) [src/utils/slo.rs39-56](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/slo.rs#L39-L56) [src/utils/metrics.rs134-156](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/metrics.rs#L134-L156)

## Cost-Aware Provider Rotation

The `RotationProvider` supports a `CostAware` strategy that selects the cheapest healthy provider based on input cost per million tokens [src/providers/rotation.rs50-51](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/rotation.rs#L50-L51)

- Selection Logic : It uses pricing data from src/utils/cost::default_pricing src/providers/rotation.rs 51
- Tie Breaking : Ties are broken by the order of providers in the configuration src/providers/rotation.rs 53-54
- Fallback : Providers without pricing data are treated as having infinite cost and are only used if no cheaper alternatives are healthy src/providers/rotation.rs 54-55

**Sources:** [src/providers/rotation.rs41-58](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/rotation.rs#L41-L58)

## Result Sanitization and Budgeting

To prevent "token bloat" from large tool outputs (like `cat` on a large file or `curl` of a binary), ZeptoClaw performs dynamic sanitization in `src/utils/sanitize.rs`.

### Dynamic Byte Budgeting

The function `compute_tool_result_budget` calculates a fair share of the remaining context window for tool results [src/utils/sanitize.rs91-103](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/sanitize.rs#L91-L103):

- Input : context_limit , current_usage_tokens , and pending_result_count .
- Calculation : (remaining_tokens * 4) / pending_result_count .
- Clamping : Clamped between MIN_RESULT_BUDGET (1KB) and max_result_bytes (default 20KB) src/utils/sanitize.rs 10-14

### Sanitization Rules

The `sanitize_tool_result` function applies several transformations [src/utils/sanitize.rs35-49](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/sanitize.rs#L35-L49):

1. Base64 Removal : Replaces data:...;base64,... URIs with placeholders via RE_BASE64 src/utils/sanitize.rs 24-25
2. Hex Stripping : Removes contiguous hex strings longer than 200 characters via RE_LONG_HEX src/utils/sanitize.rs 27-29
3. Smart Truncation : If the result still exceeds the budget, it preserves the head and tail while truncating the middle src/utils/sanitize.rs 50-71

**Sources:** [src/utils/sanitize.rs10-29](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/sanitize.rs#L10-L29) [src/utils/sanitize.rs35-74](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/sanitize.rs#L35-L74) [src/utils/sanitize.rs91-103](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/utils/sanitize.rs#L91-L103)

## Summary Table: Quota Actions

**Sources:** [src/providers/quota.rs50-61](https://github.com/qhkm/zeptoclaw/blob/2c743d31/src/providers/quota.rs#L50-L61)
