usagereport

package
v0.16.399 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package usagereport is a runtime's usage report: what its Claude Code and Codex transcripts say about prompts, sessions, tokens and their API-equivalent cost, per day, project and model. A transcript is reduced once to compact per-file facts, kept by size and modification time in memory and in a file shared with the previous runtime, and the report is a reduction of those facts.

Index

Constants

View Source
const (
	ToolSkill = "skill"
	ToolMCP   = "mcp"
	ToolBash  = "bash"
	ToolOther = "other"
)

The kinds of a ToolCall.

View Source
const AliveSuffix = ".alive"

AliveSuffix names the file a collector touches after each background pass (Collector.KeepFresh): the facts file itself is written only when a transcript changed, so its own time does not say whether anyone still keeps it.

View Source
const DefaultWait = 20 * time.Second

DefaultWait is how long a request waits for a report being built before it is answered with the progress.

View Source
const MRSuffix = ".mrs"

MRSuffix names the file next to a facts file that holds the keys.

View Source
const SQLiteEnv = "HARNESSLY_USAGE_SQLITE"

SQLiteEnv turns the database on.

View Source
const (
	// WindowDays is how far back the report looks.
	WindowDays = 400
)

Variables

This section is empty.

Functions

func CountListedSkills

func CountListedSkills(content string) int

CountListedSkills is the number of distinct skills a skill listing names: its lines `- name: description` (a line without a description is a skill too). Only the count leaves the machine, never a name or a description.

func DefaultOwner

func DefaultOwner(host string) string

DefaultOwner is the person a report is for when the session names none: the user at this host.

func MRsOfCall added in v0.16.86

func MRsOfCall(command, output string) []string

MRsOfCall is the merge requests a Bash call created or pushed to, read from its command and its output.

func MRsOfMCP added in v0.16.86

func MRsOfMCP(verb, output string) []string

MRsOfMCP is the merge requests the answer of a merge-request MCP call names (save_merge_request creates or changes one; the answer carries its address).

func PRKeys added in v0.16.86

func PRKeys(prs []string) (keys, other []string)

PRKeys are the merge request keys a facts' pr-link addresses name, and the addresses that are not GitLab merge requests (counted as they were, never sent to the hub).

Types

type Clock

type Clock struct{ Offset float64 }

Clock is the report's day boundary: an offset from UTC in seconds.

type Collector

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

Collector keeps the facts of the transcripts and the latest report. Concurrent callers share one build.

func NewCollector

func NewCollector(cfg Config) *Collector

NewCollector is a collector with nothing read yet.

func (*Collector) Entries added in v0.16.86

func (c *Collector) Entries() []Entry

Entries are the transcripts known with their facts, in the order they became known. The agent reads them to tell the hub of calls and sessions; a subagent's file is told apart by its path.

func (*Collector) Facts

func (c *Collector) Facts() []*Facts

Facts are the facts of every transcript known, in the order they became known.

func (*Collector) FileCount

func (c *Collector) FileCount() int

FileCount is how many transcripts have facts.

func (*Collector) KeepFresh added in v0.16.86

func (c *Collector) KeepFresh(every time.Duration, stop <-chan struct{})

KeepFresh passes over the transcripts every interval until stop closes, so the facts file stays current for its readers while nobody opens the report; after each pass it touches the alive file.

func (*Collector) Refresh

func (c *Collector) Refresh()

Refresh brings the facts up to date with the transcripts on disk: only files whose size or modification time changed are read again, in parallel.

func (*Collector) Report

func (c *Collector) Report(person string, wait time.Duration) (*Report, error)

Report is the current report for a person. A build that takes longer than wait is not waited for: the answer is then the previous report, or an empty one, marked with how far the pass has got.

type Config

type Config struct {
	// ClaudeRoot is Claude Code's projects folder, CodexRoot Codex's sessions folder.
	ClaudeRoot, CodexRoot string
	// MoreCodexRoots, when set, are the sessions folders of the other homes Codex is run in (other sign-ins).
	MoreCodexRoots func() []string
	// CacheFile keeps the facts of every transcript between runs (the previous runtime reads and writes the same file).
	CacheFile string
	// SQLiteFacts keeps the facts in a database beside CacheFile too (HARNESSLY_USAGE_SQLITE=1 does the same); sqlitefacts.go.
	SQLiteFacts bool
	Projects    *Projects
	Clock       Clock
	// Timezone is the zone the report says its days are in.
	Timezone string
	// Machine is the host name the report carries.
	Machine string
	// Workers read transcripts in parallel on a first pass (GOMAXPROCS when 0).
	Workers int
	// Now is the clock (tests move it); nil is the real one.
	Now func() time.Time
	// AccountOf names the account of a provider a session ran on, by the agent and its session; "" for a session
	// without one. nil knows no accounts: every row is without one.
	AccountOf func(provider, session string) string
}

Config is where the transcripts and the facts file are, and how the report names its days and projects.

type Day

type Day struct {
	Prompts, Sessions, TurnMs, Tools, ToolErrors, Interrupts, Denials, Compactions, PRs float64
	// Hours are the prompts per hour of the day.
	Hours [24]float64
}

Day is one day's activity, by the report's zone.

type Entry added in v0.16.86

type Entry struct {
	Path string
	// MtimeMs is the transcript's modification time when its facts were read, epoch ms.
	MtimeMs float64
	Facts   *Facts
}

Entry is the facts of one transcript with where they came from.

type EventRow

type EventRow struct {
	Key any
	Ts  float64
}

EventRow is an interrupt, a denied tool or a compaction: key and time.

type Facts

type Facts struct {
	Provider  string
	SessionID string
	// Sidechain: a subagent's transcript, counted toward its parent session and never as prompts.
	Sidechain          bool
	Title, FirstPrompt *string
	// Models are strings, except where a transcript named a model with another JSON value (the report then fails, as
	// the previous runtime's did).
	Models     []any
	Projects   []string
	Tasks, PRs []string
	// MRKeys are the merge requests Bash and MCP calls created or pushed to (hubproto.MRKey), beside the pr-link ones
	// in PRs. nil: not looked for (facts from a file that had none); they are kept in a file of their own (mrs.go).
	MRKeys   []string
	FirstTs  float64
	LastTs   float64
	Messages []MsgRow
	Prompts  []PromptRow
	Turns    []TurnRow
	Tools    []ToolRow
	// ToolCalls are the named calls of this parse, never cached; denied calls are left out, and so are calls whose
	// result is missing.
	ToolCalls []ToolCall
	// SkillsListed is how many skills the session's initial skill listing offered to the agent; 0 when the transcript
	// has no listing (or the facts come from a file that was not read for it). Kept in the side file, never cached.
	SkillsListed int
	Interrupts   []EventRow
	Denials      []EventRow
	Compactions  []EventRow
}

Facts is one transcript reduced.

type MsgRow

type MsgRow struct {
	Key                                any
	Ts                                 float64
	Model, Project                     int
	Input, Output, CacheRead, W5m, W1h float64
}

MsgRow is a model call: key, time (epoch seconds), model and project (indexes), input, output, cache read and cache writes of the 5-minute and 1-hour tiers.

type Progress

type Progress struct{ Done, Total int }

Progress is how far the first pass over the transcripts has got.

type Projects

type Projects struct {
	// Root is the name of the folder that holds the repositories ("" when there is none).
	Root string
	// TaskPrefixes are the tracker's task key prefixes (upper case): a task key in a prompt or branch is collected, and a
	// worktree folder named after a task loses the suffix.
	TaskPrefixes []string
	// contains filtered or unexported fields
}

Projects names projects from working folders the same way on every machine: the repository git names, or the folder under the workspace root, a worktree without its task suffix.

func (*Projects) Of

func (p *Projects) Of(cwd string, has bool) string

Of is the project of a working folder; "" (or none) has none.

func (*Projects) ParseClaude

func (p *Projects) ParseClaude(path string) (*Facts, error)

ParseClaude reduces a Claude Code transcript.

func (*Projects) ParseCodex

func (p *Projects) ParseCodex(path string) (*Facts, error)

ParseCodex reduces a Codex rollout.

type PromptRow

type PromptRow struct {
	Key     any
	Ts      float64
	Project int
}

PromptRow is a prompt of a person: key, time, project.

type Report

type Report struct {
	Person, Machine, GeneratedAt, Timezone string
	Days                                   []string
	DayStats                               map[string]*Day
	Usage                                  []*UsageRow
	Sessions                               []*Session
	Collecting                             *Progress
}

Report is a runtime's usage report.

func Build

func Build(files []*Facts, person, machine, timezone string, clock Clock, nowMs float64) (*Report, error)

Build reduces the facts of every transcript into the report, as of nowMs.

func BuildWith

func BuildWith(files []*Facts, person, machine, timezone string, clock Clock, nowMs float64, accountOf func(provider, session string) string) (*Report, error)

BuildWith is Build with the account each session ran on: accountOf names it by the agent and its session, "" for a session without one; nil knows no accounts.

func Empty

func Empty(person, machine, timezone string, nowMs float64, p Progress) *Report

Empty is the report while nothing is built yet.

func (*Report) JSON

func (r *Report) JSON() []byte

JSON is the report as the previous runtime wrote it.

func (*Report) With

func (r *Report) With(person string, collecting *Progress) *Report

With is the report for another person, and with the progress of a pass still running (nil when none).

type Route

type Route struct {
	Collector *Collector
	// Authorized is the old API's own check (a page session or the cli-token), SessionOK the page session the handler
	// asks for besides; Claims are the session's claims.
	Authorized, SessionOK func(*http.Request) bool
	Claims                func(*http.Request) map[string]any
	// Owner is the person when the session names none (DefaultOwner when empty).
	Owner string
	// Machine is this host's name.
	Machine string
	// Wait replaces DefaultWait (tests).
	Wait time.Duration
}

Route answers GET <platform API>/stats: this runtime's usage report, alone (?shape=report) or as a team of one runtime. ?wait=0 does not wait for a report being built.

func (*Route) Answer

func (rt *Route) Answer(r *http.Request) (int, any, http.Header)

Answer is the whole answer, refusals included. The previous handler checked no method.

type Session

type Session struct {
	ID, Provider                                             string
	Title, Project                                           *string
	Start, End, Prompts, TurnMs                              float64
	Input, Output, CacheRead, CacheWrite, Cost, SubagentCost float64
	Model                                                    *string
	Tasks, PRs                                               []string
}

Session is one conversation, its subagents included.

type Stored added in v0.16.86

type Stored struct {
	Path string
	// contains filtered or unexported fields
}

Stored is the facts file another process keeps (the runtime's collector), read as it is: no transcript is read here. The machine's agent uses it so that the transcripts are parsed once per machine, not once per reader.

func (*Stored) Alive added in v0.16.86

func (s *Stored) Alive(maxAge time.Duration, now time.Time) bool

Alive says the keeper of the file has passed over the transcripts within maxAge.

func (*Stored) Entries added in v0.16.86

func (s *Stored) Entries() []Entry

Entries are the transcripts of the last read, in the file's order.

func (*Stored) Forget added in v0.16.86

func (s *Stored) Forget()

Forget drops what was read, so its memory is free while another source is used.

func (*Stored) Refresh added in v0.16.86

func (s *Stored) Refresh()

Refresh reads the file again when its size or time changed.

type ToolCall added in v0.16.86

type ToolCall struct {
	Ts    float64
	Kind  string
	Name  string
	Error bool
	// N is how many calls this one stands for (a sum read back from the side file); zero is one call, Error its
	// outcome. Errs is how many of the N failed.
	N, Errs int
}

ToolCall is a finished call of a tool, named: Kind is skill, mcp, bash or other; Name is the skill's name, the MCP server's name or the tool's own name. The facts cache does not hold them (that file's format is fixed): they are kept beside it, summed by UTC day, kind and name (mrs.go), and read back as one ToolCall per sum with N and Errs set.

func (ToolCall) Count added in v0.16.86

func (c ToolCall) Count() (calls, errors int)

Count is how many calls this one stands for and how many of them failed.

type ToolRow

type ToolRow struct {
	Key   any
	Ts    float64
	Error float64
}

ToolRow is a tool result: key, time, 1 for an error.

type TurnRow

type TurnRow struct {
	Key any
	Ts  float64
	Ms  float64
}

TurnRow is a turn's working time: key, time, milliseconds.

type UsageRow

type UsageRow struct {
	Day, Provider, Model, Project string
	// Account is the name of the account of the provider the sessions of the row ran on; "" for sessions
	// nobody noted an account of: the CLI's own sign-in, and everything from before accounts were noted.
	Account                                              string
	Input, Output, CacheRead, CacheWrite, Cost, APICalls float64
}

UsageRow is the usage of a day, provider, model and project, and of the account of the provider it was paid by.

Jump to

Keyboard shortcuts

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