events

package module
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 22 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 events turns each request and each keep-alive ping into one structural event: an OTel log record with no text, no tool names and no free strings, only enums, keyed hashes, versions and model ids that pass a format check (docs/events/events.md).

This module is separate from the root module because it needs the OTel logs API, and the root module imports only the standard library (R3), the same reason metrics and host are their own modules. A host brings the OTel SDK and the exporter; this module only builds records and calls log.Logger.Emit.

This is the scaffold of accountant#85: the envelope, identity hashing and the Emitter's lifecycle (sequence numbers, option validation, fail-open). The field groups of docs/events/events.md §6.3–§6.13 are filled in by later changes.

Index

Constants

This section is empty.

Variables

View Source
var (
	Int      = ExtraType{/* contains filtered or unexported fields */}
	Float    = ExtraType{/* contains filtered or unexported fields */}
	Bool     = ExtraType{/* contains filtered or unexported fields */}
	Duration = ExtraType{/* contains filtered or unexported fields */}
	Hashed   = ExtraType{/* contains filtered or unexported fields */}
)

Int, Float, Bool, Duration and Hashed are the non-enum extra types (docs/events/events.md §6.12.3).

Functions

func ResourceAttributes

func ResourceAttributes(p Producer) []attribute.KeyValue

ResourceAttributes gives the §6.1 OTel resource attributes of p: the fields that do not change inside one run, and so are sent once for each export batch rather than on every record. The host adds them to the resource of the LoggerProvider it builds, before it calls New.

ResourceAttributes checks the same formats New does (docs/events/events.md §8: "New and ResourceAttributes check the formats again, so a Producer built by hand cannot skip them"), so a Producer built by hand with a bad field never puts that field on the resource in clear. A field that fails its check is left out, not sent as given (E4: absent is unknown).

Types

type CGEngineFacts

type CGEngineFacts struct {
	Mode               string // observe | enforce
	Applied            bool   // the forwarded body is the compacted one
	FallbackReason     string // why the original body was forwarded in enforce mode; see cgFallbackReasonValues
	CacheAware         bool   // the cache-aware pipeline ran
	Preset             string // engine preset; Names.Presets plus "custom"/"other", else "other"
	TokensBefore       int    // engine counts, whole request
	TokensAfter        int
	FrozenTokens       int   // prefix left alone for cache safety
	PrefixRewritten    *bool // a change landed inside the previous turn's cached prefix; absent when unknown
	SavedGross         int   // engine tokens
	SavedUnique        int
	AttemptedTokens    *int   // tokens the engine tried to remove
	RestoredTokens     *int   // tokens it put back
	CompactionPoint    *int   // the token count at which the client compacts
	CompactionPointSrc string // measured | assumed | window_fallback | other

	Components []ComponentFact // §6.9.2
	Sweep      *SweepFacts     // §6.9.1 cg.sweep.*
	Expand     *ExpandFacts    // §6.9.1 cg.expand.*
	Defer      *DeferFacts     // §6.9.1 cg.defer.*
	Split      *SplitFacts     // §6.9.1 cg.split.*
	Summary    *SummaryFacts   // §6.9.1 cg.summary.*
	KA         *KeeperFacts    // §6.9.3 cg.ka.*
}

CGEngineFacts holds the §6.9.1 engine summary, with its sub-groups. A nil *CGEngineFacts means the host has no engine: the whole cg.* group does not apply (docs/events/events.md §6.9.1). A nil sub-group pointer means that sub-group does not apply (for example the sweep did not run).

type CacheHostFacts

type CacheHostFacts struct {
	// HostPhase is cache.host_phase: the host's own cold decision, "hot" | "cold" | "unknown", else
	// "other". Empty when not given.
	HostPhase string
	// HostMissReason is cache.host_miss_reason: the host's label for a cache miss, from
	// Names.Enums["cache.host_miss_reason"], else "other". Empty when not given.
	HostMissReason string
	// EstimateHeld is acct.estimate_held: the host held a price estimate instead of the measured figure.
	// nil when not given.
	EstimateHeld *bool
}

CacheHostFacts holds the host-computed (H) fields of §6.8 (docs/events/events.md): the host's own cold decision, its cache-miss label, and whether it held a price estimate. A host fills only what it has; an empty string or a nil pointer means "not given" (E4).

type CallFacts

type CallFacts struct {
	Component       string   // the component that made the call; allowlisted vs Names.Components, else "other"
	Purpose         string   // summary | sweep_question | extract | other (fixed list)
	Cold            *bool    // the cache was cold when the call was made
	Escalated       *bool    // the call went to a larger model after a first attempt
	CandidateTokens *int     // tokens the call could remove
	Accepted        *bool    // the answer was used
	Rejection       string   // why the answer was not used; Names.Enums["acct.ops.call.rejection"], else "other"
	LatencyMs       *int     // call latency
	Cost            *float64 // what the call cost, in cost.currency
}

CallFacts holds the host-sourced (H) fields of acct.ops[].call for one spend operation (docs/events/events.md §6.9). The accountant gives the A fields (model, route.host_hash, tokens, detached) from accountant.PricedOp.Call; the host gives these.

type CommonPrefix

type CommonPrefix struct {
	Section accountant.Section
	Index   int
	Bytes   int
}

CommonPrefix is <copy>.common_prefix (docs/events/events.md §6.5): the end of the longest prefix that this forwarded body shares with the thread's previous forwarded body. Section and Index are the position of the last shared entry; Bytes is the cumulative bytes of the shared prefix.

type ComponentFact

type ComponentFact struct {
	Name        string         // allowlisted vs Names.Components, else "other"
	Action      string         // acted | skipped | gated | reverted | error
	Reason      string         // skip, gate or error reason; Names.Reasons["component:"+Name], else "other". Never error text.
	Mutated     bool           // the component changed the body
	First       *bool          // a fresh act, not a replay of an earlier one
	SavedGross  *int           // engine tokens
	SavedUnique *int           // engine tokens
	DurationMs  *int           //
	Gates       map[string]int // how many times each gate fired, keyed by gate enum value
}

ComponentFact holds the host-sourced (H) fields of one cg.components entry (docs/events/events.md §6.9.2). The whole §6.9.1 cg.* group is H.

type CostFacts

type CostFacts struct {
	// Output is tokens.output: output tokens, including reasoning. nil when not given.
	Output *int
	// Reasoning is tokens.reasoning: the reasoning part of output, when the provider says. nil when not given.
	Reasoning *int

	// Amount is cost.amount, in the unit Currency. It is sent only when BillingModeAPI is true (the host
	// has a Pricer and route.billing_mode is api). nil when the host computed no figure.
	Amount *float64
	// Estimated is cost.estimated: the Pricer said the figure is estimated. nil when not given.
	Estimated *bool
	// Source is cost.source: "gateway" | "modelled", else "other". Empty when not given.
	Source string
	// Provenance is cost.provenance: "authoritative" | "configured" | "discovered" | "bundled", else
	// "other". Empty when not given.
	Provenance string
	// Currency is cost.currency: "usd" | "credits" | "other". Empty when the record has no money field.
	Currency string
	// Refused is cost.refused: "cost_implausible" | "usage_implausible" | "incomplete" | "other". Empty
	// when the host refused no cost figure.
	Refused string
}

CostFacts holds the host-computed (H) fields of §6.7 (docs/events/events.md): the money figures cost.* and the two token counts the provider does not split apart in Usage, tokens.output and tokens.reasoning. A host fills only what it has; a nil pointer or an empty string means "not given" (E4: absent is unknown), so the module sends no attribute for it.

type DeferFacts

type DeferFacts struct {
	ListTokens           int    // tokens of the list of deferred tools
	Loads                int    //
	WrongGuesses         int    //
	Searches             int    //
	DroppedSearches      int    //
	DirectCalls          int    //
	Retries400           int    //
	ClientSearchDisabled string // why the client's own tool search is off; Names.Enums["cg.defer.client_search_disabled"]
	Probe                string // outcome of the deferral probe; Names.Enums["cg.defer.probe"]
}

DeferFacts holds cg.defer.* (docs/events/events.md §6.9.1). nil when deferral is not in cg.components.

type Emitter

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

Emitter builds and emits the events of one producer. An Emitter is safe for concurrent use.

func New

func New(l log.Logger, h *Hasher, p Producer, opts ...Option) (*Emitter, error)

New builds an Emitter. l is the OTel Logger the host built for "accountant/events" on a LoggerProvider whose resource holds ResourceAttributes(p) (docs/events/events.md §9). h and p must not be nil / the zero value.

func (*Emitter) Close

func (e *Emitter) Close()

Close stops the periodic-stats goroutine (when one runs) and emits the last accountant.stats event with the run's counters (§6.11). It is idempotent.

func (*Emitter) ExportErrorHandler

func (e *Emitter) ExportErrorHandler() otel.ErrorHandler

ExportErrorHandler gives an otel.ErrorHandler the host registers for the export path of the LoggerProvider it built for this Emitter, so an export failure is observable the same way as any other OTel error. It counts into exportErrors, not refused: an export failure happens after a record was already emitted with a producer.seq, so it is an error, not a lost record (docs/events/events.md §6.11).

func (*Emitter) ForgetThread

func (e *Emitter) ForgetThread(session, thread string)

ForgetThread drops the Emitter's common_prefix state for one thread. The host calls it when it drops the thread from its own stores (docs/events/events.md §8). session and thread are the request's own RequestMeta.Session and Thread.ID, the same values the request integration keys the state on.

func (*Emitter) Ping

func (e *Emitter) Ping(p Ping)

Ping emits one accountant.ping event: the envelope plus §6.2 identity (without request_hash and thread.turn) and the §6.10 cg.ping.* fields.

func (*Emitter) Request

func (e *Emitter) Request(r Request)

Request emits one accountant.request event: the envelope (emit) plus every §6.2–§6.9.4 field this module knows how to encode.

func (*Emitter) Signal

func (e *Emitter) Signal(s Signal)

Signal emits one accountant.signal event: the envelope plus §6.2 identity (without request_hash and thread.*) and the §6.13 signal.* fields. Timestamp is the accept time, which the host gives by calling Signal synchronously as it accepts the signal, so time.Now() here is that time.

type ExpandFacts

type ExpandFacts struct {
	Calls      int            // expand calls
	Tokens     int            // tokens they restored
	Reverts    int            //
	Mismatches *int           // expand calls whose returned bytes do not match the stored original; should be 0
	ByOrigin   []ExpandOrigin // cg.expand.by_origin
}

ExpandFacts holds cg.expand.* (docs/events/events.md §6.9.1). nil when no expand was possible.

type ExpandOrigin

type ExpandOrigin struct {
	Origin string // the operator that made the marker; allowlisted vs Names.Operators, else "other"
	Calls  int
	Tokens int
	First  bool // a first expand of that marker
}

ExpandOrigin is one cg.expand.by_origin entry (docs/events/events.md §6.9.1).

type ExtraType

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

ExtraType declares the type of one host extra (docs/events/events.md §6.12.3). There is no free string type: Enum is the closest, and it is checked against a fixed list.

func Enum

func Enum(values ...string) ExtraType

Enum declares an extra whose value is one of values, sent as a string; a value outside the list becomes "other" (docs/events/events.md §6.12.3).

type Hasher

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

Hasher computes the keyed hash of every identifier a host or a client chose (docs/events/events.md §5). A Hasher is safe for concurrent use; it holds no mutable state after construction.

func NewHasher

func NewHasher(key []byte, hashKeyID string) (*Hasher, error)

NewHasher builds a Hasher for one deployment's HMAC key. key must be at least 32 bytes, and hashKeyID must match ^[a-z0-9][a-z0-9_.-]{0,31}$ (docs/events/events.md §6.1). A key rotation uses a new hashKeyID; hashes made with different hashKeyID values never join.

func (*Hasher) HashKeyID

func (h *Hasher) HashKeyID() string

HashKeyID gives the id of the key h was built with (docs/events/events.md §6.1 hash_key_id).

type HostFacts

type HostFacts struct {
	Identity IdentityFacts // §6.2
	Route    RouteFacts    // §6.3

	Timing   TimingFacts   // §6.4
	Response ResponseFacts // §6.6
	Limits   LimitFacts    // §6.6.1

	// StructureIn and StructureOut are the H-sourced §6.5 pieces of the client and the forwarded body
	// (per-section tokens, tokens_basis, message shape). StructureOut does not apply when the request
	// was not forwarded.
	StructureIn, StructureOut StructureFacts
	Trigger                   TriggerFacts // §6.5.1
	// ToolDecls is tools.decl (§6.5.2); ToolDeclsKnown is tools.decl_known, true when the host parsed
	// the declarations (an empty ToolDecls with ToolDeclsKnown true means "no tools", not "unknown").
	ToolDecls      []ToolDecl
	ToolDeclsKnown bool

	Cost  CostFacts      // §6.7 H fields (tokens.output/.reasoning, cost.*)
	Cache CacheHostFacts // §6.8 H fields (cache.host_phase/.host_miss_reason, acct.estimate_held)
	Ops   OpsHostFacts   // §6.9 H fields (acct.ops[].marker_bytes and .call)

	// CG is the whole §6.9.1–§6.9.3 cg.* group. nil means the host has no engine: the group does not
	// apply (§6.9.1).
	CG *CGEngineFacts

	Plugins []PluginFact // §6.9.4

	// ConfigJSON is the canonical JSON of the engine config, for cg.engine.config_hash (§6.1): absent
	// ("") on a host with no engine. The module hashes it; the host never sends it in clear.
	ConfigJSON string
}

HostFacts has one sub-struct for each prefix of docs/events/events.md §6, so a host fills only the groups it has.

type IdentityFacts

type IdentityFacts struct {
	// UserHash is user_hash: §5. A host's own identity subject (docs/events/events.md §6.2). Hashed
	// id_hash("user", …).
	UserHash string
	// ProviderRequestHash is provider_request_hash: the provider's request-id header. Hashed
	// id_hash("provider_request", …). Absent when the request did not reach the provider.
	ProviderRequestHash string
	// TenantHash is tenant_hash: the account the host keys its state on. Hashed id_hash("tenant", …).
	TenantHash string
	// ProjectHash is project_hash: the project id. Hashed id_hash("project", …).
	ProjectHash string
	// WorkloadHash is workload_hash: a host's own agent id, else the peer SPIFFE id
	// (docs/events/events.md §6.2). Hashed id_hash("workload", …).
	WorkloadHash string
	// ThreadTurn is thread.turn (H): the index of this request in its thread, from 1. nil is absent. A
	// request sets it; a ping and a signal leave it nil, because they carry no thread.turn (§6.2).
	ThreadTurn *int
}

IdentityFacts are the §6.2 identity fields a host gives (Source H or H→M). The §6.2 fields with Source A or A→M are not here: session_hash, request_hash, thread.id and thread.parent come from accountant.RequestMeta and accountant.Thread, which encodeIdentity takes as separate parameters and hashes itself.

Every string field is a raw identifier that the module hashes (H→M); it is never sent in clear. An empty string is absent (E4), so the module emits no attribute for it.

type KeeperFacts

type KeeperFacts struct {
	WaitCause          string // own_tool | background | human | teammate | done | none (fixed list)
	WaitTimeoutMs      *int   // the timeout of the awaited tool, when known
	WakeDueMs          *int   // when a scheduled wake-up is due, from t0
	OpenBackground     *int   // open background tasks
	OpenTeammate       *int   // open teammates
	Strategy           string // the strategy in force; Names.Enums["cg.ka.strategy"], else "other"
	GrantedTTLS        *int   // the TTL the keeper granted the entry, in seconds
	PlannedPings       *int   //
	PlannedOffsetsMs   []int  // planned ping times from t0; empty when no ping is planned
	Held               *bool  // the keeper holds the entry
	SkipReason         string // why the keeper holds no entry; Names.Enums["cg.ka.skip_reason"], else "other"
	CfgMinPrefixTokens *int   // the prefix floor applied to this wait, after every config layer
	CfgMaxPings        *int   // effective setting
	CfgMaxBodyBytes    *int   // effective setting
	// PlannedOffsetsSet distinguishes an empty plan (no ping is planned, a real fact) from an absent one.
	// cg.ka.planned_offsets_ms is "empty when no ping is planned", so an empty slice is meaningful; set this
	// true to emit it, false to leave it absent (E4).
	PlannedOffsetsSet bool
}

KeeperFacts holds the cg.ka.* fields (docs/events/events.md §6.9.3). An absent optional field (nil pointer, or "" for an enum) is not written (E4).

type LimitFacts

type LimitFacts struct {
	// APITokensLeftPct is limit.api.tokens_left_pct: remaining input-token limit, percent.
	APITokensLeftPct *int
	// APIRequestsLeftPct is limit.api.requests_left_pct: remaining request limit, percent.
	APIRequestsLeftPct *int
	// Sub5hUtilPct is limit.sub.5h.util_pct: 5-hour window used share, percent.
	Sub5hUtilPct *int
	// Sub5hResetAt is limit.sub.5h.reset_at: when the 5-hour window resets. Encoded as Unix seconds.
	Sub5hResetAt *time.Time
	// Sub5hStatus is limit.sub.5h.status. Optional enum; a value outside limitSubStatuses becomes
	// "other".
	Sub5hStatus *string
	// Sub7dUtilPct is limit.sub.7d.util_pct: 7-day window used share, percent.
	Sub7dUtilPct *int
	// Sub7dResetAt is limit.sub.7d.reset_at: when the 7-day window resets. Encoded as Unix seconds.
	Sub7dResetAt *time.Time
	// Sub7dStatus is limit.sub.7d.status. Optional enum; a value outside limitSubStatuses becomes
	// "other".
	Sub7dStatus *string
	// BudgetUsedPct is limit.budget.used_pct: share of the host's daily budget used, percent.
	BudgetUsedPct *int
}

LimitFacts holds the §6.6.1 Limits fields a host reports for one accountant.request event (docs/events/events.md §6.6.1): headroom at the response, read from the provider's response headers or the host's own budget. Every field is Source H and every field is optional: a nil pointer means the host did not report the value, so the module writes no attribute for it (E4).

The _pct fields are percents (int). The spec gives limit.sub.*.util_pct from a 0..1 header fraction and limit.budget.used_pct from a ratio; the host converts to a percent before it fills this struct. The module writes the int it is given.

type MessageShape

type MessageShape struct {
	// Parsed is true when the host counted the message shape. It gates every field below.
	Parsed bool

	UserMessages      int // <copy>.msg.user
	AssistantMessages int // <copy>.msg.assistant

	TextBlocks       int // <copy>.blk.text
	ToolUseBlocks    int // <copy>.blk.tool_use
	ToolResultBlocks int // <copy>.blk.tool_result
	ThinkingBlocks   int // <copy>.blk.thinking

	ImageBase64 int // <copy>.blk.image.base64
	ImageURL    int // <copy>.blk.image.url
	ImageFile   int // <copy>.blk.image.file

	DocumentBase64 int // <copy>.blk.document.base64
	DocumentURL    int // <copy>.blk.document.url
	DocumentFile   int // <copy>.blk.document.file
	DocumentText   int // <copy>.blk.document.text

	ToolResultBytes    int // <copy>.tool_result.bytes
	ToolResultMaxBytes int // <copy>.tool_result.max_bytes

	OpaqueBytes int // <copy>.opaque_bytes
}

MessageShape is the H-sourced message-shape breakdown of one body copy (docs/events/events.md §6.5, counts only). Parsed says the host counted the shape: when false the encoder emits nothing (E4: absent is unknown); when true every count is a real number, so a 0 is a real zero.

type Names

type Names struct {
	// Operators are acct.ops[].operator, failed_checks[].operator and cg.expand.by_origin[].origin
	// values (§6.9).
	Operators []string
	// Components are cg.components[].name values (§6.9.2).
	Components []string
	// Plugins are plugins[].name values (§6.9.4).
	Plugins []string
	// BuiltinTools are tools.decl[].name values (§6.5.2).
	BuiltinTools []string
	// Presets are cg.preset values (§6.9.1).
	Presets []string
	// Reasons is the reason enum of each component and plugin, keyed "component:<name>" or
	// "plugin:<name>", so the two never collide.
	Reasons map[string][]string
	// Enums is the values of every other host enum, keyed by field name: "cg.sweep.warm_gate",
	// "cg.defer.client_search_disabled", "cg.defer.probe", "cg.ka.strategy", "cg.ka.skip_reason",
	// "cache.host_miss_reason", "acct.ops.call.rejection".
	Enums map[string][]string
}

Names is every name the host may send in clear. A name outside its list becomes "other" (E1, docs/events/events.md §8).

type OpsHostFacts

type OpsHostFacts struct {
	// MarkerBytes maps an operation's ID (accountant.Operation.ID, the same id acct.ops matches on) to the
	// bytes of the marker the operation left in the body (acct.ops[].marker_bytes). Absent keys stay absent.
	MarkerBytes map[string]int
	// Calls holds the H fields of acct.ops[].call, keyed by the operation's ID (docs/events/events.md §6.9).
	Calls map[string]CallFacts
}

OpsHostFacts holds the host-sourced (H) fields of §6.9 acct.ops. A later integration pass adds it to the one HostFacts struct (docs/events/events.md §8); this group defines it on its own so the groups build in parallel.

type Option

type Option func(*Emitter) error

Option configures an Emitter at New.

func WithExtra

func WithExtra(key string, t ExtraType) Option

WithExtra declares one host extra (docs/events/events.md §6.12). key must match ^[a-z][a-z0-9_]{0,31}$; an Enum's values must match the same pattern. A host declares at most 64 extras.

func WithMaxThreads

func WithMaxThreads(n int) Option

WithMaxThreads bounds how many threads' common_prefix state the Emitter keeps (docs/events/events.md §6.5, §8). When a new thread would exceed n, the Emitter drops the least-recently-used thread; that thread's next request has no common_prefix. The default is 1024.

func WithNames

func WithNames(n Names) Option

WithNames declares every name the host may send in clear (docs/events/events.md §8). New returns an error for a value of n.Reasons or n.Enums that does not match the enum-value format of §6.12.

func WithStatsExtras

func WithStatsExtras(f func() map[string]any) Option

WithStatsExtras gives the function the Emitter calls at each stats snapshot to fill the stats event's extras (docs/events/events.md §6.12.2).

func WithStatsInterval

func WithStatsInterval(d time.Duration) Option

WithStatsInterval sets how often the Emitter emits an accountant.stats snapshot (§6.11). When d > 0, New starts a ticker goroutine that calls emitStats every d; Close stops it. Close always emits one final snapshot regardless of this option.

type Ping

type Ping struct {
	// Ping is as for PingOps. A refused ping fills Session, ThreadID, Model and Host too; only Usage
	// stays zero.
	Ping accountant.Ping

	// Window is the keep-alive window id: accountant.PingWindowID(thread, window start), the same id
	// PingOps puts in PingFacts.PingWindow. The module hashes it.
	Window string

	// ParentThreadID is thread.parent for this ping (§6.2): the thread this one was forked from, "" if
	// none. accountant.Ping carries no parent (it is the library's own, generic type, used by PingOps
	// too, which has no need for it), so the host gives it here when it has one. The module hashes it
	// the same way as a request's thread.parent.
	ParentThreadID string

	// Host holds the §6.10 fields marked H, the §6.2 identity (without request_hash and thread.turn,
	// which a ping does not carry), and the config JSON for cg.engine.config_hash.
	Host PingHostFacts

	// Extra holds declared host extras (§6.12); keys outside WithExtra's declarations are dropped.
	Extra map[string]any
}

Ping is one keep-alive decision (docs/events/events.md §8, §6.10).

type PingHostFacts

type PingHostFacts struct {
	// Identity is the §6.2 identity fields (without request_hash and thread.turn, which a ping does not
	// carry; Emitter.Ping passes "" / nil for those regardless of ThreadTurn's value here).
	Identity IdentityFacts
	Fields   PingHostFields // §6.10 cg.ping.* fields

	// ConfigJSON is the canonical JSON of the engine config, for cg.engine.config_hash (§6.1): absent
	// ("") on a host with no engine. The module hashes it; the host never sends it in clear.
	ConfigJSON string
}

PingHostFacts holds everything a host gives for one accountant.ping event beyond the envelope.

type PingHostFields

type PingHostFields struct {
	Kind              string   // plain|sweep_question|summary|extra_slot|manual|other
	Index             *int     // 1 for the first ping of the window, then 2, ...
	Outcome           string   // sent|refused|failed
	RefuseReason      string   // pingRefuseReasons; absent when empty
	ScheduledOffsetMs *int     // does not apply to a manual ping
	PrefixTokens      *int     // billed prefix the ping would replay
	ProjectedCost     *float64 // in Currency
	Status            *int     // upstream status (sent and failed only)
	ErrorKind         string   // pingErrorKinds; absent when empty
	LatencyMs         *int     // send to last byte
	Cost              *float64 // in Currency
	Currency          string   // as cost.currency; present whenever ProjectedCost or Cost is present
}

PingHostFields holds the §6.10 cg.ping.* fields a host reports for one keep-alive decision (docs/events/events.md §6.10, the rows marked H). It is the §6.10 equivalent of the scaffold's empty PingHostFacts, which this worker must not edit; the final ping integration moves these fields onto PingHostFacts (ping.go) and passes them to encodePing. Pointer fields are optional values: absent when nil (E4).

type PluginFact

type PluginFact struct {
	// Name is Invocation.Plugin, kept only if it is in the host allowlist (Names.Plugins), else "other".
	Name string
	// Direction is "inbound" | "outbound".
	Direction string
	// Phase is "request" | "response".
	Phase string
	// Action is Invocation.Action, host-reported (including "deny"). See the note on encodePlugins for
	// why it is kept verbatim rather than mapped to "other".
	Action string
	// Reason is Invocation.Reason, kept only if it is in the plugin's declared enum
	// (Names.Reasons["plugin:"+Name]), else "other". Absent when empty.
	Reason string
	// Mutated is true when the plugin wrote the body.
	Mutated bool
	// Shadow is Invocation.Shadow.
	Shadow bool
	// Late is Invocation.Late.
	Late bool
	// DurationMs is the plugin's reported duration, when it reports one. Absent when nil (E4).
	DurationMs *int
}

PluginFact is one entry of the §6.9.4 plugins list: one plugin invocation, inbound or outbound (docs/events/events.md §6.9.4). The plugins list is request-only. The final request integration adds a Plugins []PluginFact field to HostFacts (request.go) and passes it to encodePlugins; this file defines the entry type and the encoder only.

type Producer

type Producer struct {
	// ID is service.instance.id: a random id of one install, kept on disk by the host. Not derived from
	// the host name.
	ID string
	// Kind is service.name: the host's name, one of the values the schema allows (docs/events/events.md
	// §6.1).
	Kind string
	// Version is service.version: the host version.
	Version string
	// EngineVersion is cg.engine.version: the engine version of the component named in
	// docs/events/events.md §6.9.1. Empty when the host has no such engine.
	EngineVersion string
	// RunID is producer.run_id: a random id of this process start, set by NewProducer. A restart gives a
	// new RunID, and producer.seq starts again at 1.
	RunID string
}

Producer identifies the process that emits events: one host process on one machine (docs/events/events.md §6.1).

func NewProducer

func NewProducer(id, kind, version string) (Producer, error)

NewProducer builds a Producer and checks the formats of docs/events/events.md §6.1: id must be 32 hex characters, kind must not be empty, and version and engineVersion (when given) must match the client.version format (§6.3). RunID is set to a new random id.

type Request

type Request struct {
	Meta                accountant.RequestMeta
	Thread              accountant.Thread
	Client              accountant.Body // body.in
	Forwarded           accountant.Body // body.out
	ClientBP, ForwardBP []accountant.Breakpoint
	Facts               accountant.EntryFacts

	// Ops are the inputs, for §6.9 sizes and positions, matched to PricedOp.OpID. An empty or repeated
	// ID matches nothing: those fields stay absent.
	Ops []accountant.Operation

	Usage accountant.Usage
	// UsagePresent is false when the response carried no usage at all (an upstream error, a denied
	// request): then the whole tokens.* group is absent, not a set of zeros (§6.7).
	UsagePresent bool

	// Result is nil when the host did not call Compute: acct.computed is false.
	Result *accountant.Result

	// Host holds the §6.2–§6.9.4 fields marked H, one sub-struct for each prefix.
	Host HostFacts

	// Extra holds declared host extras (§6.12); keys outside WithExtra's declarations are dropped.
	Extra map[string]any
}

Request is what the host gives for one request, after Compute, or after a failure with no Compute (docs/events/events.md §8).

type ResponseFacts

type ResponseFacts struct {
	// Status is resp.status: the status sent to the client. Always reported.
	Status int
	// ErrorKind is resp.error_kind. Optional enum; a value outside respErrorKinds becomes "other".
	ErrorKind *string
	// StopReason is resp.stop_reason. Optional enum; a value outside respStopReasons becomes "other".
	StopReason *string
	// Bytes is resp.bytes: response body bytes received from upstream. Optional; does not apply when
	// the request was not forwarded.
	Bytes *int
	// BlkText is resp.blk.text: output text blocks. Optional.
	BlkText *int
	// BlkThinking is resp.blk.thinking: output thinking blocks. Optional.
	BlkThinking *int
	// ToolUseBy is resp.tool_use_by (H→M, §6.5.2): the tool calls of the response, by raw tool name.
	// The module resolves each key to its tool key before it emits (encodeResponse's decls parameter).
	// Empty when the response made no tool call.
	ToolUseBy map[string]int
	// SSEBuffered is resp.sse_buffered: the host buffered the stream before it sent it. Optional.
	SSEBuffered *bool
}

ResponseFacts holds the §6.6 Response fields a host reports for one accountant.request event (docs/events/events.md §6.6). Every field is Source H.

Status is plain int in the spec table: the host always reports it. The other fields are optional (int?, enum?, bool?): a nil pointer means the host did not report the value, so the module writes no attribute for it (E4: absent is unknown).

type RouteFacts

type RouteFacts struct {
	// ClientName is client.name: enum claude-code | codex | other. Parsed from User-Agent.
	ClientName string
	// ClientVersion is client.version (H→M): kept only for a known client (ClientName resolves to a
	// value other than "other") and only when it matches clientVersionPattern; otherwise absent.
	ClientVersion string

	// Provider is route.provider: enum anthropic | openai | bedrock | vertex | gateway | other.
	Provider string
	// Dialect is route.dialect: enum messages | chat | responses | completions | other.
	Dialect string
	// HostHash is route.host_hash (H→M): the upstream host. Hashed id_hash("host", …). A private
	// gateway name never leaves in clear.
	HostHash string
	// Redirected is route.redirected: a plugin sent the request to another host than the client asked
	// for. nil is absent. The requested host is not sent.
	Redirected *bool

	// ModelRequested is model.requested: the model the client asked for. A model id (modelIDPattern).
	ModelRequested string
	// ContextWindow is model.context_window in tokens. nil is absent.
	ContextWindow *int
	// ContextWindowExact is model.context_window_exact: the window comes from the catalogue, not a
	// guess. nil is absent.
	ContextWindowExact *bool

	// Stream is params.stream. nil is absent.
	Stream *bool
	// MaxTokens is params.max_tokens. nil is absent.
	MaxTokens *int
	// ThinkingMode is params.thinking_mode: enum enabled | adaptive | disabled | between_tools | other.
	ThinkingMode string
	// ThinkingBudget is params.thinking_budget. nil is absent.
	ThinkingBudget *int
	// ToolChoice is params.tool_choice: enum auto | any | tool | none | other. The tool name is not sent.
	ToolChoice string
	// Temperature is params.temperature. nil is absent.
	Temperature *float64
	// TopP is params.top_p. nil is absent.
	TopP *float64
	// Retry is params.retry: the client retry count. nil is absent.
	Retry *int
}

RouteFacts are the §6.3 client and route fields a host gives (Source H or H→M). The §6.3 fields with Source A are not here: route.billing_mode, model.sent, model.key and params.effort come from accountant.RequestMeta, which encodeClientRoute takes as a separate parameter.

An empty enum string, an empty model id and a nil pointer are all absent (E4). A non-empty enum value outside its set, and a model id that fails modelIDPattern, become "other" (E1).

type Signal

type Signal struct {
	// Session, User and Tenant are hashed by the module; never sent in clear.
	Session, User, Tenant string

	// Event, Kind and Effect are the enums of §6.13.
	Event, Kind, Effect string
}

Signal is one client lifecycle signal that the host accepted (docs/events/events.md §8, §6.13).

type SplitFacts

type SplitFacts struct {
	StableTokens int // tokens in the stable part of the split
	// TailHash is the cumulative hash at the end of the stable part. The module hashes it with
	// id_hash("prefix", TailHash) into cg.split.tail_hash (E1), so the host passes the raw value. "" is absent.
	TailHash string
}

SplitFacts holds cg.split.* (docs/events/events.md §6.9.1). nil when the split is not in cg.components.

type StructureFacts

type StructureFacts struct {
	// ToolsTokens, SystemTokens, MessagesTokens are <copy>.S.tokens (H, optional). Nil is absent.
	ToolsTokens, SystemTokens, MessagesTokens *int
	// TokensBasis is <copy>.tokens_basis (H, optional enum): provider | estimate | other. "" is absent.
	TokensBasis string
	// Shape is the message-shape breakdown (<copy>.msg.*, .blk.*, .tool_result.*, .opaque_bytes).
	Shape MessageShape
}

StructureFacts carries the H-sourced §6.5 pieces of one body copy: the per-section token counts, the tokens_basis, and the message-shape breakdown. accountant counts none of these, because it hashes bytes and never parses message JSON into block types. A host fills what it counted; an absent value is not emitted (E4).

type SummaryFacts

type SummaryFacts struct {
	GateBasis      string // thread | session: what the summary gate read
	GateTokens     int    // the billed input the gate compared
	ReserveWritten *int   // tokens of the summary reserve
	ReserveUsed    *int   //
	ReserveAgeS    *int   //
	Refresh        string // paid | not_worth_it | other
}

SummaryFacts holds cg.summary.* (docs/events/events.md §6.9.1). nil when the summarizer is not in cg.components.

type SweepFacts

type SweepFacts struct {
	AppliedCold       int    // sweep rewrites on a cold cache
	AppliedWarm       int    // sweep rewrites on a warm cache
	ReferencedLater   int    // swept items the agent referenced later
	FalseRef          int    // swept items whose later reference was false
	FalseRefWarm      int    //
	Reapplied         int    // rewrites applied again in the same session
	WarmGate          string // the gate that decided a warm rewrite; Names.Enums["cg.sweep.warm_gate"], else "other"
	WarmRewriteTokens *int   //
}

SweepFacts holds cg.sweep.* (docs/events/events.md §6.9.1). nil when the sweep is not in cg.components.

type TimingFacts

type TimingFacts struct {
	// TZOffsetMin is time.tz_offset_min: the user's offset from UTC, in minutes. Optional.
	TZOffsetMin *int
	// BodyReadMS is time.body_read_ms: t0 to the last request byte. Always reported.
	BodyReadMS int
	// PipelineMS is time.pipeline_ms: last request byte to the forward, including compaction.
	// Optional; does not apply when the request was not forwarded (resp.error_kind denied).
	PipelineMS *int
	// CGEngineMS is time.cg_engine_ms: the engine time of the component named in
	// docs/events/events.md §6.9.1, inside PipelineMS. Optional.
	CGEngineMS *int
	// ConnectMS is time.connect_ms: dial and TLS to upstream. Optional; absent when a pooled
	// connection was used.
	ConnectMS *int
	// TTFBMS is time.ttfb_ms: forward to the first response byte. Optional.
	TTFBMS *int
	// FirstTokenMS is time.first_token_ms: forward to the first content delta (stream only).
	// Optional.
	FirstTokenMS *int
	// ResponseEndMS is time.response_end_ms: forward to the last response byte. Optional; does not
	// apply when the request was not forwarded.
	ResponseEndMS *int
	// TotalMS is time.total_ms: t0 to the last byte sent to the client. Always reported.
	TotalMS int
}

TimingFacts holds the §6.4 Timing fields a host reports for one accountant.request event (docs/events/events.md §6.4). Every field is Source H. All _ms values are durations in milliseconds on the proxy's monotonic clock, from t0 = the proxy read the first request byte.

BodyReadMS and TotalMS are plain int in the spec table: the host always reports them. The other fields are int? (optional): a nil pointer means the host did not report the value, so the module writes no attribute for it (E4: absent is unknown). The module never writes a zero for a value the host did not give.

type ToolDecl

type ToolDecl struct {
	// Name is the real tool name. It is used to compute id, and, only when it is in Names.BuiltinTools,
	// emitted as tools.decl[].name. For every other tool the name field is absent (not "other"): an MCP
	// or custom name is chosen by a user or a server and never leaves in clear (anti-goal 1).
	Name string
	// SchemaJSON is the canonical JSON of the declaration's input schema, supplied by the host (the module
	// does not parse JSON). It is used only to compute id and is never emitted.
	SchemaJSON string
	// Kind is tools.decl[].kind (enum, declKinds).
	Kind string
	// Bytes is tools.decl[].bytes: the size of the declaration.
	Bytes int
	// Tokens is tools.decl[].tokens (optional): measured tokens of the declaration. Nil is absent.
	Tokens *int
	// State is tools.decl[].state (enum, declStates): sent | deferred | removed | added.
	State string
	// Search is tools.decl[].search: the declaration is a tool-search tool.
	Search bool
}

ToolDecl is one entry of tools.decl (docs/events/events.md §6.5.2). The host fills it; the module hashes the id and checks the name against the built-in allowlist.

type TriggerFacts

type TriggerFacts struct {
	// Kind is trigger.kind (enum, triggerKinds). "" encodes as "other".
	Kind string
	// Basis is trigger.basis (enum, triggerBases). "" encodes as "other".
	Basis string
	// ToolResultsBy is trigger.tool_results_by: tool_result blocks in the last user message, by tool key
	// (§6.5.2). Empty when the last user message has no tool_result. The total is the sum of the map.
	ToolResultsBy map[string]int
	// ToolErrors is trigger.tool_errors (optional): of those, how many have is_error set. Nil is absent.
	ToolErrors *int
	// ToolResultBytes is trigger.tool_result_bytes (optional): bytes of those blocks. Nil is absent.
	ToolResultBytes *int
	// Parallel is trigger.parallel (optional): the previous response asked for more than one tool call,
	// and this request returns them together. Nil is absent.
	Parallel *bool
}

TriggerFacts is the H-sourced §6.5.1 trigger of one request. The host fills it; the module encodes it.

Jump to

Keyboard shortcuts

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