How Agents View Tracks Token Usage and Calculates Costs: Complete Technical Guide

Agents View extracts token consumption data from AI agent session files, persists it in a SessionUsage database record, and calculates monetary costs by multiplying total token counts against model-specific rates defined in the pricing module.

Agents View (kenn-io/agentsview) is an open-source session management system that monitors AI agent activity across SQLite and PostgreSQL backends. Understanding the process for tracking token usage and calculating costs reveals how the platform converts raw session JSON into actionable billing data with per-token precision.

How Token Usage Data Flows from Agent to Database

Session File Ingestion and Parsing

When an AI agent completes a session, it embeds a usage object within the session JSON payload. This object contains counters for input_tokens, output_tokens, and optional cache-related fields. The sync engine—whether running as a background service or triggered via CLI—parses this payload in the parser layer and writes a SessionUsage row into the database.

The SessionUsage Schema

The SessionUsage struct (defined in the DB package) stores the following fields:

  • InputTokens – Tokens the model received as prompt input
  • OutputTokens – Tokens the model emitted as response output
  • CacheReadTokens / CacheCreationTokens – Tokens retrieved from or saved to the model cache
  • TotalTokens – Sum of all token counters, used as the basis for cost calculation
  • HasTokenData – Boolean flag indicating whether any token counters are present
  • HasCost – Boolean flag indicating whether a monetary cost has been computed
  • CostUSD – Computed cost in US dollars (optional, depending on pricing configuration)

Calculating Costs from Token Counts

Model-to-Price Mapping

Cost calculation relies on internal/postgres/pricing.go, which maps model identifiers (e.g., Claude Opus 4) to per-token USD rates retrieved from provider pricing tables. This module supplies the rate multiplier used in the cost computation.

The Cost Computation Formula

The backend calculates session cost using the formula:


cost = (input_tokens + output_tokens + cache_read_tokens + cache_creation_tokens) × per_token_price

This logic is implemented in the PostgreSQL backend within internal/postgres/sessions.go and replicated for the SQLite backend in internal/db/analytics.go during the InsertSessionUsage step. The resulting value populates the cost_usd column of the session_usage table.

Querying Token Usage via CLI

The token-use Command

The CLI sub-command agentsview token-use <session-id> is implemented in cmd/agentsview/token_use.go. The runTokenUse function (lines 5-27) resolves the supplied session identifier, creates a minimal configuration, and calls backend.SessionUsage (lines 30-57). The function returns a sessionUsageOutput value (lines 91-99)—a thin wrapper around the database record that also reports whether the HTTP server is running.

$ agentsview token-use codex:123e4567-e89b-12d3-a456-426614174000
{
  "id": "codex:123e4567-e89b-12d3-a456-426614174000",
  "input_tokens": 3500,
  "output_tokens": 1200,
  "cache_read_tokens": 0,
  "cache_creation_tokens": 0,
  "total_tokens": 4700,
  "cost_usd": 0.047,
  "has_token_data": true,
  "has_cost": true,
  "server_running": false
}

Exit Codes and Error Handling

The usageExitCode helper in cmd/agentsview/token_use.go (lines 81-87) determines the CLI exit status:

  • 0 (tokenUseExitOK) – Token data or cost present
  • 2 (tokenUseExitNotFound) – Session not found in database
  • 3 (tokenUseExitNoTokenData) – Session exists but contains no token usage information

Programmatic Access Without CLI

For direct database access, import the DB package and call SessionUsage directly:

ctx := context.Background()
db, _ := db.Open(filepath.Join(cfg.DataDir, "agentsview.db"))
usage, err := db.SessionUsage(ctx, "codex:123e4567-e89b-12d3-a456-426614174000")
if err != nil {
    log.Fatalf("lookup failed: %v", err)
}
fmt.Printf("Tokens: %d (cost $%.2f)\n", usage.TotalTokens, usage.CostUSD)

Summary

  • Agents View extracts token usage from the usage object embedded in agent session JSON files during sync operations
  • The SessionUsage struct stores input, output, and cache token counts alongside computed USD costs in SQLite or PostgreSQL
  • Cost calculation multiplies total tokens by model-specific rates retrieved from internal/postgres/pricing.go
  • The agentsview token-use CLI command retrieves stored usage data with specific exit codes (0, 2, 3) for error states
  • Both SQLite (internal/db/analytics.go) and PostgreSQL backends support full token tracking and cost computation via the InsertSessionUsage operation

Frequently Asked Questions

Where does Agents View store token usage data?

Agents View stores token usage in the SessionUsage database table, implemented in both SQLite (internal/db/sessions.go) and PostgreSQL backends. The data persists in fields including InputTokens, OutputTokens, CacheReadTokens, CacheCreationTokens, and CostUSD, populated when the sync engine parses the usage object from agent session files.

How does the system calculate the cost of a session?

The system calculates cost by summing all token types (input, output, cache read, and cache creation) and multiplying by the per-token price for the specific model. The pricing data is retrieved from internal/postgres/pricing.go, which maps model names like "Claude Opus 4" to their respective USD rates, and the computation occurs during the InsertSessionUsage database operation.

What happens if I query a session that has no token data?

The CLI returns exit code 3 (tokenUseExitNoTokenData) when the session exists in the database but contains no token usage information. This occurs when the HasTokenData field is false, indicating the original agent session file lacked a usage object or the parser failed to extract it.

Can I access token usage data programmatically without using the CLI?

Yes, you can import the DB package and call SessionUsage(ctx, sessionID) directly. This method returns the SessionUsage struct with all token counts and cost fields, allowing integration into custom analytics pipelines or dashboards without invoking the agentsview token-use command.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →