claudecode

package
v0.74.1 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package claudecode provides an adapter for Claude Code (Anthropic's CLI) that parses JSONL session files to display conversations and token usage.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateModelCost

func CalculateModelCost(model string, usage ModelUsage) float64

CalculateModelCost calculates cost for a specific model's usage.

func NewWatcher

func NewWatcher(projectDir string) (<-chan adapter.Event, io.Closer, error)

NewWatcher creates a watcher for Claude Code session changes.

Types

type Adapter

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

Adapter implements the adapter.Adapter interface for Claude Code sessions.

func New

func New() *Adapter

New creates a new Claude Code adapter.

func (*Adapter) Capabilities

func (a *Adapter) Capabilities() adapter.CapabilitySet

Capabilities returns the supported features.

func (*Adapter) Detect

func (a *Adapter) Detect(projectRoot string) (bool, error)

Detect checks if Claude Code sessions exist for the given project.

func (*Adapter) DiscoverRelatedProjectDirs

func (a *Adapter) DiscoverRelatedProjectDirs(mainWorktreePath string) ([]string, error)

DiscoverRelatedProjectDirs scans ~/.claude/projects/ for directories that appear related to the given main worktree path. This finds conversations from deleted worktrees that git no longer knows about.

Returns decoded absolute paths (e.g., "/Users/foo/code/myrepo-feature") for directories whose encoded name shares the same repository base name.

func (*Adapter) ID

func (a *Adapter) ID() string

ID returns the adapter identifier.

func (*Adapter) Icon

func (a *Adapter) Icon() string

Icon returns the adapter icon for badge display.

func (*Adapter) Messages

func (a *Adapter) Messages(sessionID string) ([]adapter.Message, error)

Messages returns all messages for the given session. Uses caching with incremental parsing for append-only growth optimization.

func (*Adapter) Name

func (a *Adapter) Name() string

Name returns the human-readable adapter name.

func (*Adapter) SearchMessages

func (a *Adapter) SearchMessages(sessionID, query string, opts adapter.SearchOptions) ([]adapter.MessageMatch, error)

SearchMessages searches message content within a session. Implements adapter.MessageSearcher interface.

func (*Adapter) SessionByID

func (a *Adapter) SessionByID(sessionID string) (*adapter.Session, error)

SessionByID returns a single session by ID without scanning the directory (td-27f6a1). Implements adapter.TargetedRefresher for efficient targeted refresh.

func (*Adapter) Sessions

func (a *Adapter) Sessions(projectRoot string) ([]adapter.Session, error)

Sessions returns all sessions for the given project, sorted by update time.

func (*Adapter) Usage

func (a *Adapter) Usage(sessionID string) (*adapter.UsageStats, error)

Usage returns aggregate usage stats for the given session.

func (*Adapter) Watch

func (a *Adapter) Watch(projectRoot string) (<-chan adapter.Event, io.Closer, error)

Watch returns a channel that emits events when session data changes.

type CacheCreation

type CacheCreation struct {
	Ephemeral5mInputTokens int `json:"ephemeral_5m_input_tokens"`
	Ephemeral1hInputTokens int `json:"ephemeral_1h_input_tokens"`
}

CacheCreation holds cache-specific token data.

type ContentBlock

type ContentBlock struct {
	Type      string `json:"type"`
	Text      string `json:"text,omitempty"`
	Thinking  string `json:"thinking,omitempty"`
	ID        string `json:"id,omitempty"`          // tool_use ID
	Name      string `json:"name,omitempty"`        // tool name
	Input     any    `json:"input,omitempty"`       // tool input
	ToolUseID string `json:"tool_use_id,omitempty"` // for tool_result linking
	Content   any    `json:"content,omitempty"`     // tool_result content (string or array)
	IsError   bool   `json:"is_error,omitempty"`    // tool_result error flag
}

ContentBlock represents a single block in the content array.

type DailyActivity

type DailyActivity struct {
	Date          string `json:"date"`
	MessageCount  int    `json:"messageCount"`
	SessionCount  int    `json:"sessionCount"`
	ToolCallCount int    `json:"toolCallCount"`
}

DailyActivity tracks activity for a single day.

type DailyModelTokens

type DailyModelTokens struct {
	Date          string         `json:"date"`
	TokensByModel map[string]int `json:"tokensByModel"`
}

DailyModelTokens tracks token usage by model for a day.

type LongestSession

type LongestSession struct {
	SessionID    string    `json:"sessionId"`
	Duration     int64     `json:"duration"` // milliseconds
	MessageCount int       `json:"messageCount"`
	Timestamp    time.Time `json:"timestamp"`
}

LongestSession tracks info about the longest session.

type MessageContent

type MessageContent struct {
	Role    string          `json:"role"`
	Content json.RawMessage `json:"content"`
	Model   string          `json:"model,omitempty"`
	ID      string          `json:"id,omitempty"`
	Usage   *Usage          `json:"usage,omitempty"`
}

MessageContent holds the actual message data.

type ModelUsage

type ModelUsage struct {
	InputTokens              int `json:"inputTokens"`
	OutputTokens             int `json:"outputTokens"`
	CacheReadInputTokens     int `json:"cacheReadInputTokens"`
	CacheCreationInputTokens int `json:"cacheCreationInputTokens"`
}

ModelUsage tracks cumulative token usage for a model.

type RawMessage

type RawMessage struct {
	Type       string          `json:"type"`
	UUID       string          `json:"uuid"`
	ParentUUID *string         `json:"parentUuid"`
	SessionID  string          `json:"sessionId"`
	Timestamp  time.Time       `json:"timestamp"`
	Message    *MessageContent `json:"message,omitempty"`
	CWD        string          `json:"cwd,omitempty"`
	Version    string          `json:"version,omitempty"`
	GitBranch  string          `json:"gitBranch,omitempty"`
	Slug       string          `json:"slug,omitempty"`
}

RawMessage represents a raw JSONL line from Claude Code.

type SessionMetadata

type SessionMetadata struct {
	Path             string
	SessionID        string
	Slug             string // Short slug from summary line (e.g., "ses_abc123")
	CWD              string
	Version          string
	GitBranch        string
	FirstMsg         time.Time
	LastMsg          time.Time
	MsgCount         int
	TotalTokens      int     // Sum of input + output tokens
	EstCost          float64 // Estimated cost based on model usage
	PrimaryModel     string  // Most used model in session
	FirstUserMessage string  // Content of the first user message (for title)
}

SessionMetadata holds metadata about a session file.

type StatsCache

type StatsCache struct {
	Version          int                   `json:"version"`
	LastComputedDate string                `json:"lastComputedDate"`
	TotalSessions    int                   `json:"totalSessions"`
	TotalMessages    int                   `json:"totalMessages"`
	FirstSessionDate time.Time             `json:"firstSessionDate"`
	DailyActivity    []DailyActivity       `json:"dailyActivity"`
	DailyModelTokens []DailyModelTokens    `json:"dailyModelTokens"`
	ModelUsage       map[string]ModelUsage `json:"modelUsage"`
	HourCounts       map[string]int        `json:"hourCounts"`
	LongestSession   LongestSession        `json:"longestSession"`
}

StatsCache represents the aggregated usage stats from stats-cache.json.

func LoadStatsCache

func LoadStatsCache() (*StatsCache, error)

LoadStatsCache loads and parses ~/.claude/stats-cache.json.

func (*StatsCache) CacheEfficiency

func (s *StatsCache) CacheEfficiency() float64

CacheEfficiency calculates the percentage of tokens served from cache.

func (*StatsCache) GetPeakHours

func (s *StatsCache) GetPeakHours(top int) []struct {
	Hour  string
	Count int
}

GetPeakHours returns the top n peak hours.

func (*StatsCache) GetRecentActivity

func (s *StatsCache) GetRecentActivity(days int) []DailyActivity

GetRecentActivity returns daily activity for the last n days.

func (*StatsCache) TotalCost

func (s *StatsCache) TotalCost() float64

TotalCost estimates the total cost across all models.

type ToolResult

type ToolResult struct {
	Type      string `json:"type"`
	ToolUseID string `json:"tool_use_id"`
	Content   string `json:"content"`
}

ToolResult represents the result of a tool call.

type Usage

type Usage struct {
	InputTokens              int            `json:"input_tokens"`
	OutputTokens             int            `json:"output_tokens"`
	CacheCreationInputTokens int            `json:"cache_creation_input_tokens"`
	CacheReadInputTokens     int            `json:"cache_read_input_tokens"`
	CacheCreation            *CacheCreation `json:"cache_creation,omitempty"`
}

Usage tracks token usage for a message.

Jump to

Keyboard shortcuts

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