usage

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package usage records and aggregates token-usage statistics across all jcode surfaces (TUI, web, ACP). It uses an append-only JSON-lines event log (~/.jcode/usage/events.jsonl), one line per agent turn. Append-only writes are atomic for small records under O_APPEND, so multiple jcode processes can record concurrently without a read-modify-write race; all derived metrics are computed at read time by Aggregate.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Estimate

func Estimate(s string) int

Estimate approximates the token count of a string.

func EstimateBytes

func EstimateBytes(n int) int

EstimateBytes approximates the token count of a byte length.

func RecordEvent

func RecordEvent(ev Event)

RecordEvent stamps ev with the current time and appends it to the default store. Callers fill in the session/project/model + token deltas; TS/Date are set here. Best-effort: errors are swallowed so stats never break a run.

func Today

func Today() string

Today returns the current local date as YYYY-MM-DD.

Types

type Aggregated

type Aggregated struct {
	Totals         Totals
	ActiveDays     int
	CurrentStreak  int
	LongestStreak  int
	MostUsedModel  string
	CacheHitRate   float64 // cached / prompt, clamped to [0,1]
	CacheSupported bool
	Days           map[string]*DayBucket
	ByModel        []Share
	ByProject      []Share
}

Aggregated is the full derived view over a set of events.

func Aggregate

func Aggregate(events []Event, today string) Aggregated

Aggregate reduces raw events into derived statistics. `today` (YYYY-MM-DD, local) anchors the current-streak computation so the function stays pure and testable.

func (Aggregated) Trend

func (a Aggregated) Trend() []DayBucket

Trend returns the day buckets in ascending date order.

type ContextBreakdown

type ContextBreakdown struct {
	SystemPromptTokens int `json:"system_prompt_tokens"`
	SystemToolsTokens  int `json:"system_tools_tokens"`
	MCPToolsTokens     int `json:"mcp_tools_tokens"`
	SkillsTokens       int `json:"skills_tokens"`
	MessagesTokens     int `json:"messages_tokens"`
	ContextLimit       int `json:"context_limit"`
}

ContextBreakdown partitions a context window into the categories that make it up. The four static buckets (system prompt / tools / MCP tools / skills) are computed from the live agent assembly; MessagesTokens and ContextLimit are filled in at query time.

func (ContextBreakdown) StaticTotal

func (b ContextBreakdown) StaticTotal() int

StaticTotal is the sum of the four assembly-time buckets (everything except the conversation messages).

type DayBucket

type DayBucket struct {
	Date   string `json:"date"`
	Tokens int64  `json:"tokens"`
	Turns  int64  `json:"turns"` // recorded turns ("轮") that day
	Calls  int64  `json:"calls"`
}

DayBucket is one day's rolled-up usage.

type Event

type Event struct {
	TS         int64  `json:"ts"`   // unix seconds
	Date       string `json:"date"` // YYYY-MM-DD, local time
	Project    string `json:"project,omitempty"`
	Session    string `json:"session,omitempty"` // session UUID
	Model      string `json:"model,omitempty"`
	Prompt     int    `json:"prompt"`
	Completion int    `json:"completion"`
	Cached     int    `json:"cached"`
	Reasoning  int    `json:"reasoning,omitempty"`
	CacheWrite int    `json:"cache_write,omitempty"`
	Total      int    `json:"total"`
	Calls      int    `json:"calls,omitempty"` // API calls in this turn
}

Event is a single recorded agent turn's token usage. Token fields are the per-turn delta (not cumulative).

type Share

type Share struct {
	Name   string  `json:"name"`
	Tokens int64   `json:"tokens"`
	Share  float64 `json:"share"` // fraction of the grand total, 0-1
}

Share is a labelled token total (per-model or per-project).

type Store

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

Store is an append-only event-log writer/reader.

func Default

func Default() *Store

Default returns the process-wide store bound to ~/.jcode/usage/events.jsonl. If the path cannot be resolved, the returned store is a no-op.

func NewStore

func NewStore(path string) *Store

NewStore returns a Store backed by the given file path.

func (*Store) Load

func (s *Store) Load(since string) ([]Event, error)

Load reads all events with Date >= since (YYYY-MM-DD). An empty since loads everything. A missing log file yields an empty slice, not an error. Malformed lines are skipped so a single bad write can't break stats.

func (*Store) Record

func (s *Store) Record(ev Event) error

Record appends one event. Turns with no token usage are dropped. A nil or pathless store is a no-op so callers never need to guard.

type Totals

type Totals struct {
	Total      int64 `json:"total"`
	Prompt     int64 `json:"prompt"`
	Completion int64 `json:"completion"`
	Cached     int64 `json:"cached"`
	Reasoning  int64 `json:"reasoning"`
	CacheWrite int64 `json:"cache_write"`
	Calls      int64 `json:"calls"`
	Turns      int64 `json:"turns"` // number of recorded events
}

Totals holds cumulative token counters over the aggregated window.

Jump to

Keyboard shortcuts

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