> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch38-monitoring-and-troubleshooting/38.3-usage-tracking.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 38.3 Usage Tracking

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~270k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

LLM API call costs are one of the main operational expenses for AI applications. OpenClaw provides a multi-layered usage tracking system, from token counting for individual requests to cost summaries across sessions, helping users understand and control expenses.

## 38.3.1 Token Usage Normalization

Different LLM providers (Anthropic, OpenAI, Google, etc.) return usage field names that vary. `normalizeUsage()` (`src/agents/usage.ts`, 106 lines) is responsible for unifying various formats into a standard form:

```typescript
export type UsageLike = {
  input?: number;               // Anthropic format
  inputTokens?: number;         // Camel case format
  input_tokens?: number;        // Snake case format
  promptTokens?: number;        // OpenAI format
  prompt_tokens?: number;       // OpenAI snake case format
  // ... output / cacheRead / cacheWrite have similarly multiple naming conventions
};

export type NormalizedUsage = {
  input?: number;
  output?: number;
  cacheRead?: number;
  cacheWrite?: number;
  total?: number;
};

export function normalizeUsage(raw?: UsageLike | null): NormalizedUsage | undefined {
  const input = raw.input ?? raw.inputTokens ?? raw.input_tokens
    ?? raw.promptTokens ?? raw.prompt_tokens;
  const output = raw.output ?? raw.outputTokens ?? raw.output_tokens
    ?? raw.completionTokens ?? raw.completion_tokens;
  const cacheRead = raw.cacheRead ?? raw.cache_read ?? raw.cache_read_input_tokens;
  const cacheWrite = raw.cacheWrite ?? raw.cache_write ?? raw.cache_creation_input_tokens;
  const total = raw.total ?? raw.totalTokens ?? raw.total_tokens;
  return { input, output, cacheRead, cacheWrite, total };
}
```

Each field has 3-5 possible naming variants (camel case, snake case, abbreviations, full names). `normalizeUsage()` uses the `??` chain to try each one in sequence, ensuring that responses from any provider's format can be correctly parsed.

> **Sidebar**: `cacheRead` and `cacheWrite` are token types corresponding to the "Prompt Caching" feature introduced by Anthropic. When the system prompt is cached, the cost of reading cached tokens in subsequent requests is much lower than regular input tokens. `cacheWrite` is the number of tokens written to the cache for the first time, and `cacheRead` is the number of tokens that hit the cache in subsequent requests.

## 38.3.2 Session-Level Cost Calculation

`loadSessionCostSummary()` (`src/infra/session-cost-usage.ts`) parses all LLM call records line by line from a session's transcript file and calculates the total cost of a single session:

```typescript
export type SessionCostSummary = CostUsageTotals & {
  messageCounts: SessionMessageCounts;     // Message statistics
  toolUsage: SessionToolUsage;             // Tool call statistics
  modelUsage: SessionModelUsage[];         // Grouped by model
  latency: SessionLatencyStats;            // Latency statistics
  dailyBreakdown: SessionDailyUsage[];     // Grouped by day
  dailyMessageCounts: SessionDailyMessageCounts[];
  dailyLatency: SessionDailyLatency[];
  dailyModelUsage: SessionDailyModelUsage[];
};
```

The parsing process uses `readline` to read the JSONL-formatted transcript file line by line, avoiding loading large files into memory at once:

```typescript
const rl = readline.createInterface({
  input: fs.createReadStream(sessionFile),
  crlfDelay: Infinity,
});
for await (const line of rl) {
  const entry = JSON.parse(line);
  // Extract usage, cost, model, provider, duration, etc.
}
```

### Cost Estimation

When the API response does not include cost data (some providers do not return fees), OpenClaw uses a built-in model pricing table for estimation:

```typescript
const cost = estimateUsageCost({
  usage: normalizedUsage,
  model: "claude-sonnet-4-20250514",
  provider: "anthropic",
});
```

The pricing table is maintained in `src/utils/usage-format.ts` and covers the input/output/cache token unit prices for mainstream models.

## 38.3.3 Cross-Session Aggregation

The Gateway's `sessions.usage` RPC method (`src/gateway/server-methods/usage.ts`, 767 lines) provides cross-session usage aggregation queries. It supports filtering by time range and multi-dimensional aggregation:

### Query Parameters

| Parameter              | Type         | Default     | Description                                   |
| ---------------------- | ------------ | ----------- | --------------------------------------------- |
| `startDate`            | `YYYY-MM-DD` | 30 days ago | Start date                                    |
| `endDate`              | `YYYY-MM-DD` | Today       | End date                                      |
| `days`                 | `number`     | 30          | Lookback days (mutually exclusive with dates) |
| `limit`                | `number`     | 50          | Maximum number of sessions to return          |
| `key`                  | `string`     | —           | Query single session                          |
| `includeContextWeight` | `boolean`    | `false`     | Include system prompt weight                  |

### Aggregation Dimensions

The returned `SessionsUsageAggregates` contains the following dimensions:

```typescript
export type SessionsUsageAggregates = {
  messages: SessionMessageCounts;        // Message totals
  tools: SessionToolUsage;               // Tool call totals
  byModel: SessionModelUsage[];          // Grouped by model (sorted by cost descending)
  byProvider: SessionModelUsage[];       // Grouped by provider
  byAgent: Array<{ agentId; totals }>;   // Grouped by agent
  byChannel: Array<{ channel; totals }>; // Grouped by channel
  latency?: SessionLatencyStats;         // Latency statistics (avg/p95/min/max)
  dailyLatency?: SessionDailyLatency[];  // Latency by day
  modelDaily?: SessionDailyModelUsage[]; // By model by day
  daily: Array<{                         // Daily summary
    date; tokens; cost; messages; toolCalls; errors
  }>;
};
```

### Caching Strategy

Cross-session aggregation is a compute-intensive operation (requires reading multiple transcript files). The Gateway uses an in-memory cache with a 30-second TTL:

```typescript
const COST_USAGE_CACHE_TTL_MS = 30_000;
const costUsageCache = new Map<string, CostUsageCacheEntry>();

async function loadCostUsageSummaryCached(params) {
  const cacheKey = `${params.startMs}-${params.endMs}`;
  const cached = costUsageCache.get(cacheKey);
  if (cached?.summary && now - cached.updatedAt < COST_USAGE_CACHE_TTL_MS) {
    return cached.summary;  // Cache hit
  }
  if (cached?.inFlight) {
    return cached.summary ?? await cached.inFlight;  // Deduplicate concurrent requests
  }
  // Load and cache
}
```

Similar to the health check cache, this also uses `inFlight` Promise deduplication—when multiple clients request data for the same time range simultaneously, the actual computation is only performed once.

## 38.3.4 Provider-Level Usage Tracking

The `usage.status` RPC returns quota usage for each LLM provider:

```typescript
export type ProviderUsageSnapshot = {
  provider: UsageProviderId;   // "anthropic" | "openai-codex" | "google-gemini-cli" | ...
  displayName: string;         // Human-readable name
  windows: UsageWindow[];      // Usage within time windows
  plan?: string;               // Subscription plan (e.g., "pro")
  error?: string;              // Query error
};

export type UsageWindow = {
  label: string;               // e.g., "daily" / "monthly"
  usedPercent: number;          // Usage percentage 0-100
  resetAt?: number;             // Reset timestamp
};
```

OpenClaw supports usage queries for 8 providers: Anthropic, GitHub Copilot, Google Gemini CLI, Google Antigravity, MiniMax, OpenAI Codex, Xiaomi, and Zai. Each provider has its own API endpoint and authentication method, and `loadProviderUsageSummary()` provides a unified wrapper for the query logic.

## 38.3.5 Time Series Data and Logs

Two additional RPC methods provide finer-grained usage data:

* **`sessions.usage.timeseries`**: Returns the usage time series for a single session (up to 200 data points), suitable for plotting usage trend charts in the console UI
* **`sessions.usage.logs`**: Returns the raw LLM call logs for a single session (up to 1000 entries), including details of each call such as model, token count, latency, tool calls, etc.

***

## Section Summary

1. **Token normalization** (`normalizeUsage()`) solves the problem of inconsistent field naming across multiple providers, unifying 5 naming variants into a standard `input/output/cacheRead/cacheWrite/total` structure.
2. **Session-level costs** are calculated by parsing JSONL transcript files line by line, supporting multi-dimensional breakdown by day, model, and tool. When API cost data is missing, a built-in pricing table is used for estimation.
3. **Cross-session aggregation** supports time range filtering and 6 aggregation dimensions (messages/tools/models/providers/agents/channels), with 30-second caching + Promise deduplication optimizing performance.
4. **Provider quotas** tracking supports usage and reset time window queries for 8 LLM providers.
5. The entire usage system provides data support for the console UI's "Usage" panel, helping users visually understand the cost distribution of AI calls.
