usage

package
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: Apache-2.0 Imports: 13 Imported by: ? 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 usage records what an AI instance spends and reports it to the admin server. Every host of package ai (the admin server, a product service, a host agent) gets it by default through package ai/instance.

An instance keeps its own records in its own store for a retention period, publishes each one over NATS on UsageSubject(instance), and publishes a Heartbeat with running totals every HeartbeatInterval on HeartbeatSubject(instance). Records that could not be published wait in an outbox in the store and are retried on the next heartbeat; the collector stores records by ID, so a retry never counts twice. Without a NATS connection everything still works and stays local.

The admin server's AI collector subscribes to SubjectWildcard in every account (the same per-account connections that collect logs and store metrics) and keeps an aggregate store the AI > Usage page reads.

Index

Constants

View Source
const (
	// RecordPrefix is the store key prefix of an instance's own records,
	// followed by the record ID. ULIDs sort by time, so key order is
	// time order.
	RecordPrefix = "ai_usage:"
	// OutboxPrefix is the store key prefix of records that still have to
	// be published.
	OutboxPrefix = "ai_usage_outbox:"
	// OutboxFlushLimit bounds the outbox records published per heartbeat.
	OutboxFlushLimit = 500
)
View Source
const (
	// SubjectPrefix is the base of every AI usage subject. Agents and
	// services may publish under it by default (user.BaselinePublishSubjects).
	SubjectPrefix = "sys.ai"
	// SubjectWildcard matches every usage and heartbeat subject.
	SubjectWildcard = "sys.ai.>"

	// DefaultRetention is how long an instance keeps its own records.
	DefaultRetention = 30 * 24 * time.Hour
	// DefaultHeartbeatInterval is how often an instance reports its totals.
	DefaultHeartbeatInterval = 60 * time.Second
	// OfflineAfter is how many missed heartbeats mark an instance offline.
	OfflineAfter = 3
)

Variables

This section is empty.

Functions

func HeartbeatSubject

func HeartbeatSubject(instance string) string

HeartbeatSubject is where an instance publishes its Heartbeat.

func UsageSubject

func UsageSubject(instance string) string

UsageSubject is where an instance publishes each Record.

Types

type Heartbeat

type Heartbeat struct {
	Instance string `json:"instance"`
	Service  string `json:"service,omitempty"`
	Host     string `json:"host"`
	// Version is the platform build or a host-supplied version string.
	Version string `json:"version,omitempty"`
	// Provider and Model are the instance's defaults, when it has one.
	Provider  string    `json:"provider,omitempty"`
	Model     string    `json:"model,omitempty"`
	StartedAt time.Time `json:"started_at"`
	At        time.Time `json:"at"`
	// IntervalSeconds is the heartbeat period, so a collector can tell when
	// the instance went quiet.
	IntervalSeconds int    `json:"interval_seconds"`
	Totals          Totals `json:"totals"`
	SourceAccount   string `json:"source_account,omitempty"`
}

Heartbeat reports that an instance is running and what it has spent. Totals cover the records the instance still holds (its retention window), so they are comparable across restarts.

type Local

type Local interface {
	PutRecord(r Record) error
	PutHeartbeat(h Heartbeat) error
}

Local receives records and heartbeats in-process, for a host that is itself the collector (the admin server's own assistant). The admin's AIUsageStore satisfies it.

type Publisher

type Publisher interface {
	PublishRaw(subject string, data []byte) error
}

Publisher sends bytes on a NATS subject. *messenger.Client satisfies it.

type Record

type Record struct {
	ID string `json:"id"`
	// Instance names the AI instance (for example "admin_service"); Host is
	// the machine it runs on. Instance plus Host identifies one running
	// instance.
	Instance string `json:"instance"`
	Service  string `json:"service,omitempty"`
	Host     string `json:"host"`
	ai.RunRecord
	At time.Time `json:"at"`
	// SourceAccount is the NATS account the record arrived from, set by the
	// collector, not by the instance.
	SourceAccount string `json:"source_account,omitempty"`
}

Record is one run as stored and reported: the ai.RunRecord plus where it ran. ID is unique (a ULID), so a collector can store records idempotently.

type Recorder

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

Recorder stores, totals, and reports the runs of one AI instance. It implements ai.UsageSink. A Recorder records and stores whether or not it was started; Start adds the heartbeat and the outbox retry, and Close stops them and releases the publishing goroutine.

func NewRecorder

func NewRecorder(o RecorderOptions) (*Recorder, error)

NewRecorder validates o, applies the defaults, and starts the goroutine that publishes records.

func (*Recorder) Close

func (r *Recorder) Close() error

Close stops the heartbeat, publishes what is queued, and sends a final heartbeat when the Recorder was started. It is idempotent. Records arriving after Close are still stored, and wait in the outbox.

func (*Recorder) Options

func (r *Recorder) Options() RecorderOptions

Options returns the options with their defaults applied.

func (*Recorder) RecordRun

func (r *Recorder) RecordRun(_ context.Context, run ai.RunRecord)

RecordRun stores a run, adds it to the totals, hands it to Local, and queues it for publishing. It never waits on the network: a record that cannot be queued goes to the outbox and is retried on the next heartbeat.

func (*Recorder) Records

func (r *Recorder) Records(ctx context.Context, since time.Time, limit int) ([]Record, error)

Records returns the stored records at or after since, newest first, at most limit of them (limit <= 0 returns all). A zero since returns every record still held.

func (*Recorder) Start

func (r *Recorder) Start()

Start loads the totals from the stored records, sends a heartbeat, and then every HeartbeatInterval retries the outbox and sends a heartbeat. It returns at once; a second call does nothing.

func (*Recorder) Totals

func (r *Recorder) Totals() Totals

Totals returns the counters of the records the instance holds.

type RecorderOptions

type RecorderOptions struct {
	// Instance names the AI instance; it is the last token of the NATS
	// subjects, so it must match [A-Za-z0-9_-]+. Required.
	Instance string
	// Service is the hosting service, when there is one.
	Service string
	// Host is the machine name; empty uses os.Hostname.
	Host string
	// Version is reported in every Heartbeat.
	Version string
	// Store keeps the records and the outbox. Required.
	Store *store.Store
	// Publisher sends records and heartbeats over NATS. With neither a
	// Publisher nor a Local, every record waits in the outbox until a
	// restart with a publisher sends it. A host that is its own collector
	// (Local set, no Publisher) keeps no outbox: Local already has the record.
	Publisher Publisher
	// Local, when set, receives every record and heartbeat in-process.
	Local Local
	// Retention is how long records (and outbox entries) are kept; zero
	// means DefaultRetention.
	Retention time.Duration
	// HeartbeatInterval is the heartbeat period; zero means
	// DefaultHeartbeatInterval.
	HeartbeatInterval time.Duration
	// Provider and Model are the instance's defaults, reported in the
	// Heartbeat.
	Provider string
	Model    string
	// Logger receives operational lines; nil is silent.
	Logger *logger.Logger
}

RecorderOptions configures a Recorder.

type Totals

type Totals struct {
	Runs      int64    `json:"runs"`
	Turns     int64    `json:"turns"`
	ToolCalls int64    `json:"tool_calls"`
	Errors    int64    `json:"errors"`
	Usage     ai.Usage `json:"usage"`
}

Totals are cumulative counters.

func (*Totals) Add

func (t *Totals) Add(r Record)

Add accumulates one record.

Jump to

Keyboard shortcuts

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