usage

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package usage records one JSONL line per observed Jev transport attempt and aggregates those lines into a report with an estimated cost. Appends hold an exclusive file lock so lines from concurrent goroutines and processes never interleave.

Index

Constants

View Source
const (
	FormatText = "text"
	FormatJSON = "json"
)

Format names an output format.

View Source
const (
	SourceMeasured    = "measured"
	SourceUnavailable = "unavailable"
	TransportHTTPS    = "https"
	TransportFixture  = "fixture"
)

Usage sources and transports.

View Source
const (
	DefaultInputUSDPerMTok  = 0.042
	DefaultOutputUSDPerMTok = 0.0
	EnvInputRate            = "JEVKIT_INPUT_USD_PER_MTOK"
	EnvOutputRate           = "JEVKIT_OUTPUT_USD_PER_MTOK"
)

Default rates: input tokens cost USD 0.042 per million, output is free.

View Source
const (
	PurposeSDLC       = "SDLC"
	PurposeCompaction = "compaction"
	PurposeSecurity   = "security checks"
	PurposeMCP        = "MCP"
	PurposeCLI        = "CLI"
	PurposeOther      = "other"
)

Purposes name what a Jev call was used for.

View Source
const (
	HookFileName = "hooks.jsonl"
)

HookOutcome values match agents.Outcome* constants.

Variables

This section is empty.

Functions

func Append

func Append(stateDir string, rec Record) error

Append writes rec as one line under an exclusive lock. Missing fields are defaulted: the timestamp to now (UTC), the transport to https, and the usage source from whether any token count is present. Negative counts clamp to zero.

func AppendHook

func AppendHook(stateDir string, rec HookInvocation) error

AppendHook writes rec as one line under an exclusive lock. Failures are returned to the caller; hook runners ignore them so telemetry never breaks a fail-open path. An empty timestamp is filled with Now (UTC).

func CountRuns

func CountRuns(stateDir string, runIDs map[string]bool) (int, error)

CountRuns reports how many records are attributable to runIDs, without modifying the log — used to preview how much a prune/delete would remove.

func HookPath

func HookPath(stateDir string) string

HookPath is <stateDir>/jevkit/hooks.jsonl.

func Path

func Path(stateDir string) string

Path is <stateDir>/jevkit/usage.jsonl.

func Purpose

func Purpose(r Record) string

Purpose classifies a call by its run, then its question set, then its origin: an SDLC run's routing calls count as SDLC whichever surface made them, and a compaction hook's calls as compaction.

func RemoveRuns

func RemoveRuns(stateDir string, runIDs map[string]bool) (removed int, err error)

RemoveRuns rewrites the usage log to drop every record whose RunID is in runIDs — the "attributable" usage a deleted run tree owns. Records with an empty RunID, or a RunID not in the set, are shared/unattributable and are always preserved untouched. A missing file removes nothing.

func Render

func Render(w io.Writer, s Summary, format string, omitEmpty bool) error

Render writes s as text or indented JSON. With omitEmpty, text output for a summary with no calls is empty.

Types

type Cost

type Cost struct {
	EstimatedUSD     float64 `json:"estimated_usd"`
	InputUSDPerMTok  float64 `json:"input_rate_usd_per_mtok"`
	OutputUSDPerMTok float64 `json:"output_rate_usd_per_mtok"`
	Note             string  `json:"note"`
}

Cost is an estimate from the configured rates.

type Filter

type Filter struct {
	PlanKey        string
	Session        string
	Agent          string
	RunID          string
	Model          string
	QuestionSetID  string
	Since, Until   time.Time
	IncludeFixture bool
}

Filter selects records. Empty fields match everything. Fixture-transport records (offline tests) are excluded unless IncludeFixture is set. Since and Until bound the record timestamp (inclusive); records with an unparseable timestamp are excluded when either bound is set.

type HookInvocation

type HookInvocation struct {
	Timestamp  string `json:"timestamp"`
	Agent      string `json:"agent,omitempty"`
	Event      string `json:"event"`
	Outcome    string `json:"outcome"`
	Tool       string `json:"tool,omitempty"`
	DurationMs int64  `json:"durationMs,omitempty"`
	LoadError  string `json:"loadError,omitempty"`
}

HookInvocation is one hooks.jsonl line recording a hook dispatch. It sits beside usage.jsonl under the same state directory so hook activity is part of local usage tracking, without polluting Jev call aggregates.

func ReadHooks

func ReadHooks(path string) ([]HookInvocation, error)

ReadHooks returns valid global hook-dispatch records. They are activity, not Jev API calls, and are never added to token totals.

type Record

type Record struct {
	Timestamp     string `json:"timestamp"`
	Model         string `json:"model"`
	QuestionSetID string `json:"questionSetId"`
	InputTokens   int    `json:"input_tokens"`
	OutputTokens  int    `json:"output_tokens"`
	UsageSource   string `json:"usageSource"`
	Transport     string `json:"transport"`
	Agent         string `json:"agent,omitempty"`
	PlanKey       string `json:"planKey,omitempty"`
	Session       string `json:"session,omitempty"`
	RunID         string `json:"runId,omitempty"`
	Origin        string `json:"origin,omitempty"`
	Status        string `json:"status,omitempty"`
}

Record is one usage.jsonl line.

func ReadRecords

func ReadRecords(path string) ([]Record, error)

ReadRecords returns every parseable record in path. A missing file yields none; blank and malformed lines are skipped.

type Summary

type Summary struct {
	Kind                string             `json:"kind"`
	SchemaVersion       int                `json:"schema_version"`
	Calls               int                `json:"calls"`
	Attempts            int                `json:"attempts,omitempty"`
	InputTokens         int                `json:"input_tokens"`
	OutputTokens        int                `json:"output_tokens"`
	CallsMeasured       int                `json:"calls_measured"`
	CallsUnavailable    int                `json:"calls_unavailable"`
	AttemptsMeasured    int                `json:"attempts_measured,omitempty"`
	AttemptsUnavailable int                `json:"attempts_unavailable,omitempty"`
	FailedAttempts      int                `json:"failed_attempts,omitempty"`
	ByQuestionSet       map[string]*Tokens `json:"by_question_set"`
	ByModel             map[string]*Tokens `json:"by_model"`
	ByAgent             map[string]*Tokens `json:"by_agent"`
	ByOrigin            map[string]*Tokens `json:"by_origin,omitempty"`
	ByPurpose           map[string]*Tokens `json:"by_purpose,omitempty"`
	ByRun               map[string]*Tokens `json:"by_run,omitempty"`
	Cost                *Cost              `json:"cost"`
}

Summary is the aggregate report.

func Aggregate

func Aggregate(recs []Record, f Filter, getenv func(string) string) Summary

Aggregate tallies the records that pass f. getenv supplies the rate overrides (nil means os.Getenv). Invalid or negative rates fall back to the defaults. Cost is nil when nothing matched.

type Tokens

type Tokens struct {
	Calls        int `json:"calls"`
	Attempts     int `json:"attempts,omitempty"`
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
	Measured     int `json:"measured"`
	Unavailable  int `json:"unavailable"`
}

Tokens is a call and token tally.

Jump to

Keyboard shortcuts

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