providers

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

claude.go implements the Provider interface for Claude Code CLI.

codex.go implements the Provider interface for OpenAI Codex CLI.

Package providers defines interfaces and implementations for AI coding agents. Supports multiple backends: Claude Code, Codex CLI, etc.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Claude

type Claude struct {
	// contains filtered or unexported fields
}

Claude wraps the Claude Code CLI as a provider.

func NewClaude

func NewClaude() *Claude

NewClaude creates a Claude Code provider.

func NewClaudeWithPath

func NewClaudeWithPath(dataPath string) *Claude

NewClaudeWithPath creates a Claude provider with a custom data path.

func (*Claude) Cost

func (c *Claude) Cost() (inputCents, outputCents int64)

Cost returns Claude's token pricing (cents per 1K tokens). Based on Claude Opus 4 pricing.

func (*Claude) DataPath

func (c *Claude) DataPath() string

DataPath returns the configured data path.

func (*Claude) Execute

func (c *Claude) Execute(ctx context.Context, task Task) (Result, error)

Execute runs a task via Claude Code CLI.

func (*Claude) GetDailyStats

func (c *Claude) GetDailyStats(date string) (*DailyStat, error)

GetDailyStats returns usage stats for a specific date.

func (*Claude) GetTodayUsage

func (c *Claude) GetTodayUsage() (int64, error)

GetTodayUsage returns today's total token usage. Primary source: stats-cache.json (dailyModelTokens) — this is the metric the calibrator was trained against, so budget ratios stay consistent. Fallback: direct JSONL scanning if stats-cache is missing or has no entry for today. Note: JSONL input_tokens+output_tokens ≠ dailyModelTokens (Claude Code uses its own aggregation), so JSONL fallback is approximate.

func (*Claude) GetUsedPercent

func (c *Claude) GetUsedPercent(mode string, weeklyBudget int64) (float64, error)

GetUsedPercent calculates the used percentage based on mode and budget. mode: "daily" or "weekly" weeklyBudget: total weekly token budget

func (*Claude) GetWeeklyUsage

func (c *Claude) GetWeeklyUsage() (int64, error)

GetWeeklyUsage returns the last 7 days total token usage. Primary: stats-cache.json. Fallback: direct JSONL scanning.

func (*Claude) LastUsedPercentSource

func (c *Claude) LastUsedPercentSource() string

LastUsedPercentSource reports where the last GetUsedPercent call sourced data.

func (*Claude) ListSessionFiles

func (c *Claude) ListSessionFiles() ([]string, error)

ListSessionFiles finds all session JSONL files under the projects directory.

func (*Claude) Name

func (c *Claude) Name() string

Name returns "claude".

func (*Claude) ParseStatsCache

func (c *Claude) ParseStatsCache() (*StatsCache, error)

ParseStatsCache reads and parses the stats-cache.json file.

func (*Claude) ScanTodayTokens

func (c *Claude) ScanTodayTokens() (int64, error)

ScanTodayTokens walks JSONL session files and sums input+output tokens for assistant messages timestamped today (local time). Files not modified today are skipped via mtime check for performance.

func (*Claude) ScanWeeklyTokens

func (c *Claude) ScanWeeklyTokens() (int64, error)

ScanWeeklyTokens walks JSONL session files and sums input+output tokens for assistant messages timestamped within the last 7 days (local time).

type Codex

type Codex struct {
	// contains filtered or unexported fields
}

Codex wraps the Codex CLI as a provider.

func NewCodex

func NewCodex() *Codex

NewCodex creates a Codex provider.

func NewCodexWithPath

func NewCodexWithPath(dataPath string) *Codex

NewCodexWithPath creates a Codex provider with a custom data path.

func (*Codex) Cost

func (c *Codex) Cost() (inputCents, outputCents int64)

Cost returns Codex's token pricing (cents per 1K tokens). Based on GPT-4 pricing estimates.

func (*Codex) DataPath

func (c *Codex) DataPath() string

DataPath returns the configured data path.

func (*Codex) Execute

func (c *Codex) Execute(ctx context.Context, task Task) (Result, error)

Execute runs a task via Codex CLI.

func (*Codex) FindMostRecentSession

func (c *Codex) FindMostRecentSession() (string, error)

FindMostRecentSession finds the most recent session file by modification time.

func (*Codex) FindMostRecentSessionWithData

func (c *Codex) FindMostRecentSessionWithData() (string, error)

FindMostRecentSessionWithData finds the most recent session file by modification time that actually contains token_count events with data. This avoids returning stub sessions (started then exited, no data).

func (*Codex) GetPrimaryUsedPercent

func (c *Codex) GetPrimaryUsedPercent() (float64, error)

GetPrimaryUsedPercent returns the primary (daily) used_percent.

func (*Codex) GetRateLimits

func (c *Codex) GetRateLimits() (*CodexRateLimits, error)

GetRateLimits retrieves the latest rate limits from the most recent session.

func (*Codex) GetResetTime

func (c *Codex) GetResetTime(mode string) (time.Time, error)

GetResetTime returns the reset timestamp for the specified mode. mode: "daily" returns primary.resets_at, "weekly" returns secondary.resets_at.

func (*Codex) GetSecondaryUsedPercent

func (c *Codex) GetSecondaryUsedPercent() (float64, error)

GetSecondaryUsedPercent returns the secondary (weekly) used_percent.

func (*Codex) GetTodayTokenUsage

func (c *Codex) GetTodayTokenUsage() (*CodexTokenUsage, error)

GetTodayTokenUsage sums token usage across ALL sessions for today's date. Each session's cumulative total_token_usage is taken from the last token_count event in that file (since total_token_usage is cumulative within a session, the last event gives the session total).

func (*Codex) GetTodayTokens

func (c *Codex) GetTodayTokens() (int64, error)

GetTodayTokens returns total tokens used across all sessions today. Satisfies the snapshots.CodexUsage interface.

func (*Codex) GetUsageBreakdown

func (c *Codex) GetUsageBreakdown() UsageBreakdown

GetUsageBreakdown returns both rate limit percentages and local token counts so the budget display can show both authoritative and measured data.

func (*Codex) GetUsedPercent

func (c *Codex) GetUsedPercent(mode string, weeklyBudget int64) (float64, error)

GetUsedPercent returns the used percentage based on mode. Uses Codex's own rate limit percentages as the authoritative source since our local billable token calculation may not match Codex's internal accounting (prompt caching, model launch bonuses, etc.). For daily mode: primary rate limit used_percent (5h window). For weekly mode: secondary rate limit used_percent. Falls back to token-based calculation only if rate limits are unavailable.

func (*Codex) GetWeeklyTokenUsage

func (c *Codex) GetWeeklyTokenUsage() (*CodexTokenUsage, error)

GetWeeklyTokenUsage sums token usage across all sessions from the last 7 days.

func (*Codex) GetWeeklyTokens

func (c *Codex) GetWeeklyTokens() (int64, error)

GetWeeklyTokens returns total tokens used across all sessions in the last 7 days. Satisfies the snapshots.CodexUsage interface.

func (*Codex) GetWindowMinutes

func (c *Codex) GetWindowMinutes(mode string) (int64, error)

GetWindowMinutes returns the window duration for the specified mode.

func (*Codex) ListSessionFiles

func (c *Codex) ListSessionFiles() ([]string, error)

ListSessionFiles finds all session JSONL files under sessions/<year>/<month>/<day>/.

func (*Codex) ListSessionFilesForDate

func (c *Codex) ListSessionFilesForDate(t time.Time) ([]string, error)

ListSessionFilesForDate returns session files for a specific date.

func (*Codex) ListTodaySessionFiles

func (c *Codex) ListTodaySessionFiles() ([]string, error)

ListTodaySessionFiles returns session files for today's date. Codex stores sessions at sessions/YYYY/MM/DD/*.jsonl.

func (*Codex) Name

func (c *Codex) Name() string

Name returns "codex".

func (*Codex) ParseSessionJSONL

func (c *Codex) ParseSessionJSONL(path string) (*CodexRateLimits, error)

ParseSessionJSONL reads a Codex session JSONL file and extracts rate limits. Returns the most recent rate_limits entry found in the file.

func (*Codex) ParseSessionTokenUsage

func (c *Codex) ParseSessionTokenUsage(path string) (*CodexTokenUsage, error)

ParseSessionTokenUsage reads a Codex session JSONL file and computes the session's billable token usage. Codex total_token_usage is cumulative within a session, so we take the delta between the first and last events. The result excludes cached input tokens since those don't count against rate limits. Returns nil if no token usage data is found (e.g. stub sessions).

func (*Codex) RefreshRateLimits

func (c *Codex) RefreshRateLimits() (*CodexRateLimits, error)

RefreshRateLimits clears cached rate limits and re-reads from disk.

type CodexRateLimit

type CodexRateLimit struct {
	UsedPercent   float64 `json:"used_percent"`
	WindowMinutes int64   `json:"window_minutes"`
	ResetsAt      int64   `json:"resets_at"` // Unix timestamp
}

CodexRateLimit represents a single rate limit entry.

type CodexRateLimits

type CodexRateLimits struct {
	Primary   *CodexRateLimit `json:"primary"`
	Secondary *CodexRateLimit `json:"secondary"`
}

CodexRateLimits represents the rate_limits object in Codex session JSONL.

type CodexSessionEntry

type CodexSessionEntry struct {
	Type    string               `json:"type"`
	Payload *CodexSessionPayload `json:"payload,omitempty"`
}

CodexSessionEntry represents a line in Codex session JSONL. Codex wraps data in {"type":"event_msg","payload":{"type":"token_count","rate_limits":{...}}}.

type CodexSessionPayload

type CodexSessionPayload struct {
	Type       string               `json:"type"`
	Info       *CodexTokenCountInfo `json:"info,omitempty"`
	RateLimits *CodexRateLimits     `json:"rate_limits,omitempty"`
}

CodexSessionPayload represents the payload object in a Codex JSONL entry.

type CodexTokenCountInfo

type CodexTokenCountInfo struct {
	TotalTokenUsage *CodexTokenUsage `json:"total_token_usage"`
	LastTokenUsage  *CodexTokenUsage `json:"last_token_usage"`
}

CodexTokenCountInfo holds per-event and cumulative token usage.

type CodexTokenUsage

type CodexTokenUsage struct {
	InputTokens           int64 `json:"input_tokens"`
	CachedInputTokens     int64 `json:"cached_input_tokens"`
	OutputTokens          int64 `json:"output_tokens"`
	ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
	TotalTokens           int64 `json:"total_tokens"`
}

CodexTokenUsage represents token usage counters from a Codex session.

type DailyActivity

type DailyActivity struct {
	Date          string `json:"date"` // "YYYY-MM-DD"
	MessageCount  int64  `json:"messageCount"`
	SessionCount  int64  `json:"sessionCount"`
	ToolCallCount int64  `json:"toolCallCount"`
}

DailyActivity holds per-day message/session/tool counts.

type DailyModelTokens

type DailyModelTokens struct {
	Date          string           `json:"date"`          // "YYYY-MM-DD"
	TokensByModel map[string]int64 `json:"tokensByModel"` // model name -> token count
}

DailyModelTokens holds per-day token counts by model.

type DailyStat

type DailyStat struct {
	Date          string
	MessageCount  int64
	SessionCount  int64
	ToolCallCount int64
	TokensByModel map[string]int64
}

DailyStat is a convenience view combining activity and tokens for a date.

type MessageContent

type MessageContent struct {
	Model string      `json:"model,omitempty"`
	Usage *TokenUsage `json:"usage,omitempty"`
}

MessageContent holds the nested message object from Claude JSONL.

type Provider

type Provider interface {
	// Name returns the provider identifier.
	Name() string

	// Execute runs a task and returns the result.
	Execute(ctx context.Context, task Task) (Result, error)

	// Cost returns estimated cost per 1K tokens (input, output).
	Cost() (inputCents, outputCents int64)
}

Provider is the interface all AI coding agents must implement.

type Result

type Result struct {
}

Result holds the outcome of a provider execution.

type SessionMessage

type SessionMessage struct {
	Type      string          `json:"type"`
	Message   *MessageContent `json:"message,omitempty"`
	Timestamp time.Time       `json:"timestamp"`
}

SessionMessage represents a single message in a session JSONL file.

type StatsCache

type StatsCache struct {
	Version          int                `json:"version"`
	DailyActivity    []DailyActivity    `json:"dailyActivity"`
	DailyModelTokens []DailyModelTokens `json:"dailyModelTokens"`
}

StatsCache represents the stats-cache.json structure from Claude Code. The file uses two arrays: dailyActivity (message/session/tool counts) and dailyModelTokens (per-model token counts keyed by date).

func ParseStatsCache

func ParseStatsCache(path string) (*StatsCache, error)

ParseStatsCache reads stats-cache.json from a specific path.

func (*StatsCache) GetDailyStat

func (s *StatsCache) GetDailyStat(date string) *DailyStat

GetDailyStat builds a combined DailyStat for a given date.

func (*StatsCache) TokensByDate

func (s *StatsCache) TokensByDate() map[string]int64

TokensByDate returns a map of date -> total tokens across all models.

type Task

type Task struct {
}

Task represents work to be done by a provider.

type TokenUsage

type TokenUsage struct {
	InputTokens              int64 `json:"input_tokens"`
	OutputTokens             int64 `json:"output_tokens"`
	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
}

TokenUsage holds per-message token counts.

func ParseSessionJSONL

func ParseSessionJSONL(path string) (*TokenUsage, error)

ParseSessionJSONL reads a session JSONL file and returns token usage.

func (*TokenUsage) TotalTokens

func (u *TokenUsage) TotalTokens() int64

TotalTokens returns the sum of all token fields.

type UsageBreakdown

type UsageBreakdown struct {
	PrimaryPct   float64          // 5h window used_percent from rate limit
	WeeklyPct    float64          // weekly used_percent from rate limit
	TodayTokens  *CodexTokenUsage // local billable tokens today
	WeeklyTokens *CodexTokenUsage // local billable tokens this week
}

UsageBreakdown contains both rate-limit and local token data for display.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL