← Back to Roadmap

Task 8: Usage Tracker

3-4 hours Core

Current Issue / Scenario

Cost data exists in the codebase but isn't surfaced anywhere. AO already has a CostEstimate interface and getSessionInfo() extracts cost from agents — but there's no persistent storage, no CLI reports, no dashboard widget, and no team aggregation.

Current State

AspectStatus
Cost interface✓ Exists — CostEstimate { inputTokens, outputTokens, estimatedCostUsd } in types.ts
Agent extraction✓ Exists — Agent.getSessionInfo() returns AgentSessionInfo with optional cost field
Session timestamps✓ Exists — Session.createdAt, Session.lastActivityAt, Session.restoredAt
Persistent storage✗ Missing — cost data lives only in memory during session, not persisted
CLI reports✗ Missing — no ao usage command
Dashboard widget✗ Missing — dashboard shows session status but not cost/token consumption
Team aggregation✗ Missing — no per-model, per-day, or per-team reports
Why this matters: The building blocks exist (CostEstimate, getSessionInfo(), timestamps) but the data evaporates when a session ends. Teams running 5-10 agents need historical reports: "How much did this sprint cost?" and "Is Claude Code more cost-effective than Codex for our codebase?" The data is there — it just needs to be persisted and surfaced.

What To Do

How We Will Do It

Reference Implementation

oh-my-claudecode/src/team/usage-tracker.ts

github.com/Yeachan-Heo/oh-my-claudecode/src/team/usage-tracker.ts

Adaptation Strategy

The oh-my-claudecode tracker is designed for their team/worker model. AO's equivalent concepts:

oh-my-claudecodeAO equivalent
WorkerSession (one agent working on one task)
TeamOrchestrator instance (all sessions for a project)
TaskIssue/ticket being worked on
Prompt charsPrompt chars (keep as-is, or upgrade to token counts if available)

Data Format

// ~/.agent-orchestrator/usage.jsonl
// One entry per completed interaction

{"sessionId":"abc-123","taskId":"#42","model":"claude-code","startTime":"2026-03-19T06:00:00Z","endTime":"2026-03-19T06:12:34Z","wallClockMs":754000,"promptChars":24500,"responseChars":18200,"promptTokens":null,"responseTokens":null,"status":"completed"}
{"sessionId":"abc-123","taskId":"#42","model":"claude-code","startTime":"2026-03-19T06:12:35Z","endTime":"2026-03-19T06:15:02Z","wallClockMs":147000,"promptChars":8200,"responseChars":5100,"promptTokens":null,"responseTokens":null,"status":"completed"}

References

SourceWhat to take
oh-my-claudecode/usage-tracker.tsCore tracking logic, JSONL write pattern, report aggregation. ~150 lines, port directly.
oh-my-claudecode/worker-health.tsComplementary — tracks uptime, error rates. Could merge into same tracker for richer data.
AO types.ts (39K)Already defines CostEstimate { inputTokens, outputTokens, estimatedCostUsd } and AgentSessionInfo.cost. Build on this, don't reinvent.
AO session-manager.ts (82K)Session lifecycle events already exist (created, started, completed, failed). Hook into these for usage data capture.
AO dashboardpackages/web/src/components/ — add usage widget to SessionDetail and Dashboard views.

Implementation Plan

Read and understand source

Read oh-my-claudecode/src/team/usage-tracker.ts end-to-end. Note the interface, storage pattern, and report generation methods. ~30 minutes.

Create UsageTracker in AO core

Create packages/core/src/usage-tracker.ts. Reuse existing interfaces from types.ts:

// Already in types.ts:
// interface CostEstimate { inputTokens: number; outputTokens: number; estimatedCostUsd: number }
// interface AgentSessionInfo { agentSessionId; summary; cost?: CostEstimate }
// interface Session { id; createdAt; lastActivityAt; agentInfo: AgentSessionInfo | null }

// NEW: Persistent usage entry (combines existing data)
interface UsageEntry {
  sessionId: string;
  projectId: string;
  issueId: string | null;
  agentName: string;       // from Session.agentInfo or agent plugin name
  startTime: string;       // from Session.createdAt
  endTime: string;         // from Session.lastActivityAt at completion
  wallClockMs: number;     // endTime - startTime
  inputTokens: number;     // from CostEstimate
  outputTokens: number;    // from CostEstimate
  estimatedCostUsd: number; // from CostEstimate
  status: 'completed' | 'failed' | 'timeout';
}

JSONL Writer

Implement append-only JSONL writer. File: ~/.agent-orchestrator/usage.jsonl

  • appendEntry(entry: UsageEntry) — append one JSON line
  • readEntries(filter?: { since?: Date, sessionId?: string }) — read and parse
  • File rotation: when file exceeds 10MB, rotate to usage.jsonl.1

No external deps — just fs.appendFileSync.

Hook into session lifecycle

In AO's core session manager, add hooks:

  • Session start — record start time, session ID, task ID, model
  • Agent prompt — increment prompt char counter
  • Agent response — increment response char counter
  • Session end — calculate wall clock, write UsageEntry to JSONL

Look at packages/core/src/ for existing lifecycle events to hook into.

Report Generator

Create report functions (port from oh-my-claudecode):

  • generateReport(entries: UsageEntry[]): UsageReport
  • perSessionReport(sessionId: string) — time, chars, model for one session
  • perModelReport() — aggregate by model (Claude vs Codex vs Aider)
  • dailyReport(date: Date) — all usage for one day
  • costEstimate(report: UsageReport) — rough $ estimate based on model pricing

ao usage CLI Command

Add to packages/cli/src/commands/usage.ts:

$ ao usage
# Shows today's usage summary

$ ao usage --session abc-123
# Shows usage for specific session

$ ao usage --since 2026-03-15
# Shows usage since date

$ ao usage --by-model
# Breakdown by model (Claude vs Codex vs Aider)

$ ao usage --cost
# Rough cost estimate based on model pricing

Dashboard Widget

Add usage visualization to packages/web/:

  • SessionDetail — show time spent, chars consumed for that session
  • Dashboard overview — usage chart (daily bar chart or line chart)
  • Model breakdown — pie/donut chart of usage by agent runtime

Use simple SVG charts — no charting library needed for v1.

Test and Validate

  • Run 3-5 agent sessions with different runtimes
  • Verify JSONL entries are written correctly
  • ao usage shows accurate data
  • Dashboard widget renders usage correctly
  • File rotation works at 10MB
  • Cost estimates are reasonable (within 20% of actual provider charges)

Acceptance Criteria

Impact: Teams finally know what AO costs them. Per-model comparisons help choose the most cost-effective agent. Usage data feeds into billing, budgeting, and optimization decisions. All for ~150 lines of code.