Documentation
¶
Overview ¶
Package metrics provides an asynchronous, SQLite-backed system for recording and querying operational measurements across LLM calls, tool executions, and file changes, and for aggregating them into per-session and cross-session usage summaries.
Core Types ¶
A Record is one observed occurrence with a Kind (llm_call, tool_call, or file_change), a Status, descriptive Attr dimensions, and numeric Measurement values. A Recorder persists records; the Store is the SQLite-backed implementation.
A Entry is a Record after attribution: it carries the identity, timestamp, and scope fields (scope.Scope) that the recorder fills in. Callers never construct an Entry directly; they call NewEntry or use the convenience helpers RecordLLMCall, RecordToolCall, and RecordFileChange.
Asynchronous Batched Writes ¶
Store (created via NewStore) queues records in a bounded in-memory channel and writes them in batched transactions on a background goroutine. Store.Record never blocks: when the queue is full the record is dropped with a warning. Store.Flush blocks until every queued record is written, and Store.Close flushes and stops the writer.
Querying & Aggregation ¶
[Query] describes a generic aggregation over records and measurements, supporting AggSum, AggMin, and AggMax over named Metric values, grouping by Dimension columns or attribute keys, and optional time [Bucket]ing. Store.Query (or the standalone RunQuery) executes a query and returns a [Result] of [Row]s.
Usage Accumulation ¶
Usage accumulates the records of one session into an github.com/masterkeysrd/tasksmith/api.SessionUsage, tracking LLM token counts, costs, latency, tool-call statistics, code-change totals, and prompt-cache behavior. Store.SessionUsage loads and accumulates all records for a session and its children.
Store.Summary aggregates LLM, tool, and code-change usage across sessions for a workspace or globally, with grouping by model, provider, agent, purpose, cost tier, or day, plus top-session rankings and period-over-period comparison.
Live Totals ¶
Live decorates a Store with running per-session totals. After each record it updates the affected sessions' Usage accumulators and calls a publish callback with the updated github.com/masterkeysrd/tasksmith/api.SessionUsage, enabling real-time usage display without polling the database.
Index ¶
- Constants
- Variables
- func BuildSQL(q api.MetricsQuery) (string, []any, error)
- func RecordFileChange(ctx context.Context, r Recorder, c api.FileChange) error
- func RecordLLMCall(ctx context.Context, r Recorder, c LLMCall) error
- func RecordPermissionReview(ctx context.Context, r Recorder, c PermissionReview) error
- func RecordToolCall(ctx context.Context, r Recorder, c ToolCall) error
- func RunQuery(ctx context.Context, db *sql.DB, q api.MetricsQuery) (api.MetricsResult, error)
- type AggFunc
- type Attr
- type Bucket
- type Cost
- type Dimension
- type Entry
- type Kind
- type LLMCall
- type Live
- type Measurement
- type Metric
- type PermissionReview
- type Purpose
- type Record
- type Recorder
- type Service
- type Status
- type Store
- func (s *Store) Close() error
- func (s *Store) DB() *sql.DB
- func (s *Store) Flush(ctx context.Context) error
- func (s *Store) LoadEntries(ctx context.Context, sessionID string) ([]Entry, error)
- func (s *Store) Query(ctx context.Context, q api.MetricsQuery) (api.MetricsResult, error)
- func (s *Store) Record(ctx context.Context, r Record) error
- func (s *Store) SessionUsage(ctx context.Context, sessionID string) (api.SessionUsage, error)
- func (s *Store) Summary(ctx context.Context, workspaceRoot string, req api.UsageRequest) (api.UsageSummary, error)
- func (s *Store) TurnUsage(ctx context.Context, turnIDs ...string) (api.UsageGroup, error)
- func (s *Store) Write(e Entry) error
- type ToolCall
- type Usage
Constants ¶
const ( AttrProvider = "provider" AttrModel = "model" AttrPurpose = "purpose" AttrCostTier = "cost_tier" AttrPriced = "priced" AttrBilling = "billing" AttrErrorKind = "error_kind" AttrTool = "tool" AttrToolCallID = "tool_call_id" AttrPath = "path" AttrSource = "source" AttrChange = "change" AttrRevert = "revert" AttrOutcome = "outcome" AttrRequestClass = "request_class" AttrDecision = "decision_scope" AttrRubricDigest = "rubric_digest" )
Attribute keys written by TaskSmith.
const ( BillingToken = "token" BillingQuota = "quota" )
Billing modes recorded on llm_call records. A quota-billed call has no price by design rather than a missing one, which is why it is recorded separately from an unpriced per-token call.
const ( ReviewOutcomeApproved = "approved" ReviewOutcomeDeferred = "deferred" ReviewOutcomeBelowThreshold = "below_threshold" ReviewOutcomeNoModel = "no_model" ReviewOutcomeOversize = "oversize" ReviewOutcomeInvalidManifest = "invalid_manifest" ReviewOutcomeTimeout = "timeout" ReviewOutcomeCanceled = "canceled" ReviewOutcomeError = "error" )
Review outcomes recorded on permission_review records. Everything other than ReviewOutcomeApproved fell back to the human permission flow.
const AttrPrefix = "attr."
AttrPrefix prefixes attr keys used as a Dimension.
const BaseTierKey = "base"
BaseTierKey is the group key used for calls billed at base pricing.
const MigrationScope = "metrics"
MigrationScope is the sqlite.Migrate scope of the metrics tables.
const TimeLayout = "2006-01-02T15:04:05.000000000Z"
TimeLayout is the fixed-width UTC layout used for created_at so that text ordering is chronological.
Variables ¶
var ErrClosed = errors.New("metrics: store is closed")
ErrClosed is returned by Store.Record after Store.Close.
var ErrInvalidQuery = errors.New("metrics: invalid query")
ErrInvalidQuery is returned for malformed queries.
Functions ¶
func BuildSQL ¶
func BuildSQL(q api.MetricsQuery) (string, []any, error)
BuildSQL returns the parameterized SQL for q and the group dimensions in select order. It is exported for testing.
func RecordFileChange ¶
RecordFileChange records a file_change. A nil recorder disables recording.
func RecordLLMCall ¶
RecordLLMCall records an llm_call. A nil recorder disables recording.
func RecordPermissionReview ¶
func RecordPermissionReview(ctx context.Context, r Recorder, c PermissionReview) error
RecordPermissionReview records a permission_review outcome. A nil recorder disables recording.
func RecordToolCall ¶
RecordToolCall records a tool_call. A nil recorder disables recording.
Types ¶
type Cost ¶
type Cost struct{ Input, Output, CacheRead, CacheWrite, Reasoning, Total int64 }
Cost is the nano-USD cost breakdown of an LLM call.
type Dimension ¶
type Dimension string
Dimension is a column name (workspace_root, session_id, parent_session_id, turn_id, message_id, agent, status, kind) or an attr key prefixed with "attr." (e.g. "attr.model").
type Entry ¶
type Entry struct {
ID string
CreatedAt time.Time
WorkspaceRoot string
SessionID string
ParentSessionID string
TurnID string
MessageID string
Agent string
Record
}
Entry is a Record after attribution: it carries the identity, timestamp and scope fields that the Recorder fills in. Callers never construct it.
type Kind ¶
type Kind string
Kind identifies what a record describes (free-form).
const ( KindLLMCall Kind = "llm_call" KindToolCall Kind = "tool_call" KindFileChange Kind = "file_change" // KindPermissionReview records one auto-mode permission-reviewer outcome // (including deferrals), separate from the llm_call inference record. KindPermissionReview Kind = "permission_review" )
Kinds written by TaskSmith.
type LLMCall ¶
type LLMCall struct {
Provider string
Model string
Purpose Purpose
Status Status
ErrorKind string
Tokens api.UsageTokens
Cost Cost // nano-USD
CostTier string // empty = base pricing
Priced bool
// Billing is [BillingQuota] for subscription-billed calls and
// [BillingToken] (or empty) otherwise.
Billing string
Duration time.Duration
TTFT time.Duration
Processing time.Duration
Generation time.Duration
}
LLMCall describes one LLM request for RecordLLMCall.
type Live ¶
type Live struct {
// contains filtered or unexported fields
}
Live decorates a Store with running per-session totals. After each record it calls publish with the updated usage of the affected sessions.
func NewLive ¶
func NewLive(store *Store, publish func(sessionID string, usage api.SessionUsage)) *Live
NewLive wraps store. publish is called outside of any lock.
func (*Live) SessionUsage ¶
SessionUsage returns the live usage of sessionID, loading it on first access.
type Measurement ¶
Measurement is a single integer value of a metric.
type Metric ¶
type Metric string
Metric is the name of a measurement (free-form).
const ( TokensInput Metric = "tokens.input" TokensOutput Metric = "tokens.output" TokensCacheRead Metric = "tokens.cache_read" TokensCacheWrite Metric = "tokens.cache_write" TokensReasoning Metric = "tokens.reasoning" CostInput Metric = "cost.input" CostOutput Metric = "cost.output" CostCacheRead Metric = "cost.cache_read" CostCacheWrite Metric = "cost.cache_write" CostReasoning Metric = "cost.reasoning" CostTotal Metric = "cost.total" LatencyDuration Metric = "latency.duration_ms" LatencyTTFT Metric = "latency.ttft_ms" LatencyProcessing Metric = "latency.processing_ms" LatencyGeneration Metric = "latency.generation_ms" LinesAdded Metric = "lines.added" LinesRemoved Metric = "lines.removed" FilesChanged Metric = "files.changed" )
Metric names written by TaskSmith.
type PermissionReview ¶
type PermissionReview struct {
Outcome string // one of the ReviewOutcome* constants
RequestClass string // bypass_sandbox | net | unsafe | outside | delete
Model string // "<provider>/<model>" when inference ran
Decision string // decision manifest scope (system/user/workspace/local)
RubricDigest string // short rubric fingerprint
Duration time.Duration
}
PermissionReview describes one auto-mode permission-reviewer outcome for RecordPermissionReview. Only bounded classification attributes are recorded; raw commands, paths, summaries, and diffs never are.
type Purpose ¶
type Purpose string
Purpose identifies why an LLM call was made.
const ( PurposeChat Purpose = "chat" PurposeCompaction Purpose = "compaction" PurposeTitle Purpose = "title" // PurposePermissionReview labels inference performed by the auto-mode // permission reviewer rather than the conversational agent. PurposePermissionReview Purpose = "permission_review" )
Purpose values.
type Record ¶
type Record struct {
Kind Kind
Status Status
Attrs []Attr
Measurements []Measurement
}
Record is one observed occurrence and its measurements.
type Service ¶
type Service interface {
Recorder
// TurnUsage returns the LLM usage recorded for the turns started by the
// given user message IDs, after all queued records are written.
TurnUsage(ctx context.Context, turnIDs ...string) (api.UsageGroup, error)
}
Service is a Recorder that can also report the usage of a single turn.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store is the asynchronous SQLite Recorder. Records are queued in memory and written in batched transactions by a background goroutine.
func NewStore ¶
NewStore migrates the metrics schema on db and starts the background writer. The caller keeps ownership of db and must call Store.Close before closing it.
func (*Store) LoadEntries ¶
LoadEntries reads every record of sessionID and of its child sessions.
func (*Store) Query ¶
func (s *Store) Query(ctx context.Context, q api.MetricsQuery) (api.MetricsResult, error)
Query runs q against the database.
func (*Store) Record ¶
Record attributes r from the scope in ctx and queues it for writing. It never blocks: when the queue is full the record is dropped with a warning.
func (*Store) SessionUsage ¶
SessionUsage computes the persisted usage of sessionID.
func (*Store) Summary ¶
func (s *Store) Summary(ctx context.Context, workspaceRoot string, req api.UsageRequest) (api.UsageSummary, error)
Summary aggregates LLM, tool and code-change usage across sessions.
type ToolCall ¶
type ToolCall struct {
Tool string
ToolCallID string
Status Status
ErrorKind string
Duration time.Duration
}
ToolCall describes one tool execution for RecordToolCall.
type Usage ¶
type Usage struct {
// contains filtered or unexported fields
}
Usage accumulates the metrics of one session into an api.SessionUsage.
func (*Usage) Snapshot ¶
func (u *Usage) Snapshot() api.SessionUsage
Snapshot returns a copy of the accumulated usage with groups sorted by key.