chiefusage

package
v0.256.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 10 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 chiefusage is muster's record of what the owner's CHIEF costs and what it is spared (migration 0107; docs/usage.md):

  • one row per chief turn (chief_turn_usage): what started it (Trigger), what it did (Outcome, from the tools it called) and the tokens its runtime reported for it — input, output, cache read, cache creation;
  • one row per inbound plugin message (plugin_message_handling): who handled it — one of muster's own deterministic paths, an approved routing rule, or the chief.

The usage page (internal/api usage.go) reads both through Report.

🔴 THE TOKENS ARE THE RUNTIME'S OWN NUMBERS, NEVER AN ESTIMATE. Every chief runtime answers muster's agent wire (internal/agents responses.go), whose response.completed carries the turn's `usage`: ccd sums the Claude Code transcript's per-message usage for the turn (cmd/ccd transcript.go) — the same numbers whether the CLI reaches Anthropic directly or OpenRouter through muster's LLM proxy — and a gateway runtime sends the Responses API's own. A turn whose runtime sent none is recorded with usage_known false and zero tokens, and the page counts it apart, never as free.

🔴 OWNED AND UNDER ROW-LEVEL SECURITY: ctx acts as the owner whose chief it is, and every read is that owner's alone.

Index

Constants

View Source
const (
	TriggerPlugin    = "plugin"     // an inbound plugin message delivered to the chief
	TriggerTaskEvent = "task_event" // a task muster handed the chief (a plugin's task notice)
	TriggerOwnerChat = "owner_chat" // a line the owner typed in the chief's chat
	TriggerView      = "view"       // a line the owner typed on a session's view
	TriggerAnswer    = "answer"     // the owner's answer to the chief's question, delivered
	TriggerHandBack  = "hand_back"  // a route handed back to the chief
	// TriggerSessionQuestion: one of the owner's mirrored sessions asked the
	// chief a question (chief_ask), delivered as a turn.
	TriggerSessionQuestion = "session_question"
	// TriggerMachine: the machine message door (POST /api/agents/{name}/messages).
	TriggerMachine = "machine"
	// TriggerKickoff: the chief's first turn, handed over by the kickoff deliverer.
	TriggerKickoff = "kickoff"
	// TriggerNudgeCheck: one stall check of the chief-nudge sweep — the fresh,
	// tool-less, throwaway call asking the chief about one stalled session
	// (internal/api chief_nudge.go askChiefForNudge; migration 0146). It never
	// passes chatTurn, so it records itself.
	TriggerNudgeCheck = "nudge_check"
	TriggerOther      = "other" // anything else (a nudge, a relay, a door this package does not know)
)

Trigger kinds: what started a chief turn (chief_turn_usage.trigger).

View Source
const (
	OutcomeRouted       = "routed"
	OutcomeSettled      = "settled"
	OutcomeAsk          = "ask"
	OutcomeTask         = "task"
	OutcomeRuleProposed = "rule_proposed"
	OutcomeOther        = "other"
	OutcomeFailed       = "failed"
)

Outcomes: what a chief turn did (chief_turn_usage.outcome).

View Source
const (
	HandlerFleetReport      = "fleet_report"
	HandlerThread           = "thread"
	HandlerClosedPR         = "closed_pr"
	HandlerPRRoute          = "pr_route"
	HandlerMailResume       = "mail_resume"
	HandlerTaskEventMention = "task_event_mention"
	// The task triage (internal/api task_triage.go): an assignment muster
	// placed itself — forwarded to the agent on the task, routed to the one
	// session on it, or put on the owner's board.
	HandlerTaskForward = "task_forward"
	HandlerTaskRoute   = "task_route"
	HandlerTaskBoard   = "task_board"
	// HandlerTaskClaimed: the triage left an assignment of a CLAIMED task
	// alone (notes.Claims): no card, no turn.
	HandlerTaskClaimed = "task_claimed"
	HandlerRule        = "rule"
	HandlerChief       = "chief"
)

Handlers: who handled an inbound plugin message (plugin_message_handling.handler).

View Source
const RuleProposeTool = "routing_rule_propose"

RuleProposeTool is the chief's tool that proposes a routing rule (internal/api routing_rules.go): named here because the outcome reads it.

View Source
const TopSendersShown = 10

TopSendersShown bounds Report.TopSenders.

Variables

MusterHandlers are the handlers that are muster's own deterministic paths (neither a rule nor the chief).

Functions

func OutcomeOf

func OutcomeOf(tools []string, failed bool) (string, bool)

OutcomeOf is the outcome of a turn that called tools (by name, in either spelling: bare, or mcp__muster__-prefixed) and failed or not, and whether one of its calls proposed a rule.

func WithTrigger

func WithTrigger(ctx context.Context, t Trigger) context.Context

WithTrigger marks ctx as a turn started by t. The door that starts the turn sets it (the plugin deliverer, the owner's chat doors, the answer delivery); the turn's recorder reads it (TriggerFrom).

Types

type ContextReader added in v0.201.0

type ContextReader interface {
	// LatestContext is session sessionID's latest turn that reported usage;
	// ok false when it has none.
	LatestContext(ctx context.Context, sessionID int64) (SessionContext, bool, error)
}

ContextReader reads a session's context fill. PGStore implements it; a separate interface so a Store fake need not.

type Day

type Day struct {
	Day                                 time.Time
	Turns, UnknownTurns                 int64
	Tokens                              Tokens
	Messages, ByRule, ByMuster, ByChief int64
}

Day is one UTC day's chief turns and messages.

type Handling

type Handling struct {
	MessageID      int64
	Plugin, Sender string
	Handler        string
	RuleID         int64
	FallbackRuleID int64
}

Handling is who handled one inbound plugin message. RuleID is set exactly for HandlerRule; FallbackRuleID for HandlerChief when a rule matched and its session could not take the message.

type PGStore

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

PGStore is Store on chief_turn_usage and plugin_message_handling (migration 0107), under row-level security, reading routing_rules for the rules' impact. Numbers, tags and ids only: no column holds a prompt, a reply or a message body.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG is Store over pool.

func (*PGStore) BookSessionLLM added in v0.243.0

func (s *PGStore) BookSessionLLM(ctx context.Context, u SessionLLMUsage) error

BookSessionLLM adds u to its (owner, session, day) row: one statement, so two concurrent requests never lose a count. Settle is the proxy's path.

func (*PGStore) DaySpent added in v0.243.0

func (s *PGStore) DaySpent(ctx context.Context, day time.Time) (float64, error)

DaySpent implements SessionLLMStore.

func (*PGStore) LatestContext added in v0.201.0

func (s *PGStore) LatestContext(ctx context.Context, sessionID int64) (SessionContext, bool, error)

LatestContext implements ContextReader: the newest row of the session that the runtime reported usage for (usage_known), under row-level security — so another owner's session reads as none.

func (*PGStore) RecordHandling

func (s *PGStore) RecordHandling(ctx context.Context, h Handling) error

RecordHandling implements Store. One row per message: a later handler replaces an earlier one (a mail resume that fell back to the chief is the chief's), keeping the first fallback rule a chief hand-off names.

func (*PGStore) RecordTurn

func (s *PGStore) RecordTurn(ctx context.Context, t Turn) error

RecordTurn implements Store.

func (*PGStore) Release added in v0.243.0

func (s *PGStore) Release(ctx context.Context, id int64) error

Release implements SessionLLMStore.

func (*PGStore) Report

func (s *PGStore) Report(ctx context.Context, since time.Time) (Report, error)

Report implements Store.

func (*PGStore) Reserve added in v0.243.0

func (s *PGStore) Reserve(ctx context.Context, sessionID int64, day time.Time, ttl time.Duration,
	decide func(SessionSpend) float64) (int64, SessionSpend, error)

Reserve implements SessionLLMStore. The advisory lock is per owner and transaction-scoped: every Reserve of one owner, in every muster process, runs one at a time, and each sees the reservations of those before it.

func (*PGStore) SessionLLMReport added in v0.243.0

func (s *PGStore) SessionLLMReport(ctx context.Context, since time.Time) (SessionLLMReport, error)

SessionLLMReport implements SessionLLMStore.

func (*PGStore) SessionRef added in v0.243.0

func (s *PGStore) SessionRef(ctx context.Context, sessionKey string) (SessionRef, bool, error)

SessionRef implements SessionLLMStore.

func (*PGStore) SessionSpent added in v0.243.0

func (s *PGStore) SessionSpent(ctx context.Context, sessionID int64) (float64, error)

SessionSpent implements SessionLLMStore.

func (*PGStore) Settle added in v0.243.0

func (s *PGStore) Settle(ctx context.Context, id int64, u SessionLLMUsage) error

Settle implements SessionLLMStore.

func (*PGStore) Spend added in v0.243.0

func (s *PGStore) Spend(ctx context.Context, sessionID int64, day time.Time) (SessionSpend, error)

Spend implements SessionLLMStore.

func (*PGStore) Window added in v0.255.0

func (s *PGStore) Window(ctx context.Context, since, until time.Time) (Window, error)

Window is the principal's chief turns created in [since, until) (the morning report's usage line). Unlike Report it has an upper bound and no day buckets.

type Report

type Report struct {
	Since time.Time
	// Days is one entry per UTC day from Since's day to today, oldest first,
	// days with nothing included (zeros).
	Days   []Day
	Totals Totals
	// Sources is the messages by plugin, most first.
	Sources []Source
	// BySource is the chief's tokens by what started its turns (the trigger,
	// and the plugin for a plugin message or task event), costliest first.
	BySource []TokenRow
	// TopSenders is the costliest plugin senders (at most TopSendersShown).
	TopSenders []TokenRow
	// Rules is every rule the owner approved, with its impact.
	Rules []RuleImpact
}

Report is the usage page's numbers over [Since, now).

type RuleImpact

type RuleImpact struct {
	RuleID             int64
	Plugin, Sender     string
	State              string
	Hits               int64 // in the window
	HitsAll            int64 // since approval
	BeforeTurns        int64
	AvgBefore, Avoided int64
}

RuleImpact is one approved rule's hits and the tokens it is estimated to have saved: Avoided = AvgBefore × Hits, where AvgBefore is the average total tokens of the chief's plugin-message turns for the rule's plugin (and its sender, when it matches on one) that ran BEFORE the rule was approved, over the BeforeTurns such turns whose usage is known. With none, AvgBefore and Avoided are 0 and the page says there is nothing to estimate from.

type SessionContext added in v0.201.0

type SessionContext struct {
	Tokens int64
	Model  string
	At     time.Time
}

SessionContext is a chat session's context fill as its LATEST recorded turn left it (LatestContext): the tokens that turn's last model request was sent — input + cache read + cache creation, the chip's derivation (ui.ContextView) — and the model it ran on.

type SessionLLMDay added in v0.243.0

type SessionLLMDay struct {
	Day      time.Time
	Requests int64
	CostUSD  float64
}

SessionLLMDay is one UTC day's chief-session spend.

type SessionLLMReport added in v0.243.0

type SessionLLMReport struct {
	// Today is the owner's booked USD on the current UTC day.
	Today float64
	// Days is one entry per UTC day from since's day to today, oldest first,
	// days with nothing included (zeros).
	Days []SessionLLMDay
	// Sessions is every session with spend in the window, costliest first.
	Sessions []SessionLLMRow
}

SessionLLMReport is the usage page's "Chief sessions on OpenRouter" numbers.

type SessionLLMRow added in v0.243.0

type SessionLLMRow struct {
	SessionID int64
	Model     string
	Turns     int64
	Requests  int64
	Tokens    Tokens
	CostUSD   float64
}

SessionLLMRow is one session's spend in the window: its model, the turns recorded for it (chief_turn_usage), its tokens and USD.

type SessionLLMStore added in v0.243.0

type SessionLLMStore interface {
	// SessionRef reads the session with this session key, as ctx's owner sees
	// it (row-level security: another owner's session reads as none); ok
	// false when there is none.
	SessionRef(ctx context.Context, sessionKey string) (SessionRef, bool, error)
	// Spend is session sessionID's SessionSpend on day, as ctx's owner.
	Spend(ctx context.Context, sessionID int64, day time.Time) (SessionSpend, error)
	// Reserve reads the SessionSpend and asks decide how much to reserve for
	// one request, in ONE transaction under the owner's lock: decide's
	// answer above 0 is recorded as a reservation (id), lasting ttl; 0
	// reserves nothing (id 0). The spend decide saw is returned.
	Reserve(ctx context.Context, sessionID int64, day time.Time, ttl time.Duration,
		decide func(SessionSpend) float64) (int64, SessionSpend, error)
	// Settle books u and drops reservation id, in one transaction.
	Settle(ctx context.Context, id int64, u SessionLLMUsage) error
	// Release drops reservation id (its request was not sent, or failed).
	Release(ctx context.Context, id int64) error
	// SessionLLMReport is the usage page's section over [since, now).
	SessionLLMReport(ctx context.Context, since time.Time) (SessionLLMReport, error)
}

SessionLLMStore is the chief sessions' spend book. PGStore implements it.

type SessionLLMUsage added in v0.243.0

type SessionLLMUsage struct {
	SessionID int64
	// Model is the session's stored model (the pin), kept with the row so the
	// usage page names it after the session is gone.
	Model                                string
	Day                                  time.Time // a UTC midnight
	Input, Output, CacheRead, CacheWrite int64
	CostUSD                              float64
	Estimated                            bool
}

SessionLLMUsage is one proxied request of a chief session, booked to its (owner, session, day) row.

type SessionRef added in v0.243.0

type SessionRef struct {
	ID        int64
	OwnerID   int64
	AgentID   int64
	Model     string
	IsDefault bool
}

SessionRef is a chat session as the LLM proxy's chief-session door reads it by its session key: whose it is, the agent it belongs to, its stored model and whether it is the chief's primary (default) chat.

type SessionSpend added in v0.243.0

type SessionSpend struct {
	DaySpent, DayReserved         float64
	SessionSpent, SessionReserved float64
}

SessionSpend is what a chief session's caps are checked against: the owner's booked USD on the day and in flight (live reservations, any session), and the session's booked USD over its life and in flight.

type Source

type Source struct {
	Plugin                              string
	Messages, ByRule, ByMuster, ByChief int64
}

Source is one plugin's messages, by who handled them.

type Store

type Store interface {
	RecordTurn(ctx context.Context, t Turn) error
	RecordHandling(ctx context.Context, h Handling) error
	Report(ctx context.Context, since time.Time) (Report, error)
}

Store records turns and handlings and reads them back as a Report.

type TokenRow

type TokenRow struct {
	Trigger, Plugin, Sender string
	Turns                   int64
	Tokens                  Tokens
}

TokenRow is a group of chief turns and their tokens: by trigger and plugin (BySource) or by plugin and sender (TopSenders).

type Tokens

type Tokens struct {
	Input, Output, CacheRead, CacheCreation int64
}

Tokens is a turn's token counts, as its runtime reported them.

func (Tokens) Add

func (t Tokens) Add(u Tokens) Tokens

Add is t plus u.

func (Tokens) Total

func (t Tokens) Total() int64

Total is every token the turn moved: input, output, cache read and cache creation. ⚠ A COUNT, NOT A COST: a cache read is billed far below an input token, so two turns with equal totals can cost very different amounts. The page shows the four apart for that reason.

type Totals

type Totals struct {
	Turns, UnknownTurns                            int64
	Tokens                                         Tokens
	Messages, ByRule, ByMuster, ByChief, Fallbacks int64
}

Totals is the window's sums.

func (Totals) WithoutChiefPercent

func (t Totals) WithoutChiefPercent() int64

WithoutChiefPercent is the share of the window's messages handled without a chief turn (by a rule or muster's own paths), in whole percent; 0 with none.

type Trigger

type Trigger struct {
	Kind      string
	Plugin    string
	Sender    string
	MessageID int64
	// AskID is the attention ask whose answer a TriggerAnswer turn delivers
	// (0 for every other kind): read by the chief's approval card, not recorded.
	AskID int64
}

Trigger is what started a chief turn: its kind and, for a plugin message or a task event, the plugin, the sender and the message.

func TriggerFrom

func TriggerFrom(ctx context.Context) Trigger

TriggerFrom is ctx's trigger, TriggerOther when no door set one.

type Turn

type Turn struct {
	Chief        int64
	Trigger      Trigger
	Outcome      string
	RuleProposed bool
	Tokens       Tokens
	// Known: the runtime reported usage for the turn (else Tokens is zero and
	// means "unknown", not "free").
	Known    bool
	Duration time.Duration
	// SessionID is the chat session the turn ran in (chat_sessions.id,
	// migration 0115), 0 for none stored (a recap, a check); Model the model
	// that session ran on as muster knew it, "" unknown.
	SessionID int64
	Model     string
	// ContextTokens is the context the turn's LAST model request was sent
	// (agents.TurnUsage.Context) — what the chief chat's chip shows; valid when
	// Known.
	ContextTokens int64
}

Turn is one chief turn as recorded.

type Window added in v0.255.0

type Window struct {
	Turns  int64
	Busy   time.Duration
	Tokens Tokens
}

Window is the principal's chief turns in [Since, Until): how many, how long they ran together (each turn's own duration, summed — the chief's working time, not wall-clock time) and the tokens they moved.

Jump to

Keyboard shortcuts

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