The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Add token usage aggregation library
Claude31eb47887137
diff --git a/cli/beacon/internal/endpoint/tokens/contextwindow.go b/cli/beacon/internal/endpoint/tokens/contextwindow.gonew file mode 100644index 00000000..8392db89--- /dev/null+++ b/cli/beacon/internal/endpoint/tokens/contextwindow.go@@ -0,0 +1,53 @@+package tokens++import "strings"++// contextWindows maps normalized model-name prefixes to context window sizes+// in tokens. Longest prefix wins. The table is a best-effort static snapshot;+// unknown models simply report raw input tokens without a utilization ratio.+var contextWindows = []struct {+ prefix string+ tokens int64+}{+ {"claude", 200000},+ {"gpt-5", 400000},+ {"gpt-4.1", 1047576},+ {"gpt-4o", 128000},+ {"gpt-4-turbo", 128000},+ {"gpt-4", 8192},+ {"gpt-3.5", 16385},+ {"o1", 200000},+ {"o3", 200000},+ {"o4", 200000},+ {"gemini-1.5-pro", 2097152},+ {"gemini-1.5-flash", 1048576},+ {"gemini-2", 1048576},+ {"gemini-3", 1048576},+}++// ContextWindow returns the context window size for a model name, matching+// provider-prefixed and date-suffixed variants such as+// "anthropic/claude-sonnet-4-5" or "gpt-4o-2024-08-06".+func ContextWindow(model string) (int64, bool) {+ normalized := normalizeModel(model)+ if normalized == "" {+ return 0, false+ }+ best := int64(0)+ bestLen := -1+ for _, entry := range contextWindows {+ if strings.HasPrefix(normalized, entry.prefix) && len(entry.prefix) > bestLen {+ best = entry.tokens+ bestLen = len(entry.prefix)+ }+ }+ return best, bestLen >= 0+}++func normalizeModel(model string) string {+ normalized := strings.ToLower(strings.TrimSpace(model))+ if idx := strings.LastIndex(normalized, "/"); idx >= 0 {+ normalized = normalized[idx+1:]+ }+ return normalized+}diff --git a/cli/beacon/internal/endpoint/tokens/contextwindow_test.go b/cli/beacon/internal/endpoint/tokens/contextwindow_test.gonew file mode 100644index 00000000..5a6dba9b--- /dev/null+++ b/cli/beacon/internal/endpoint/tokens/contextwindow_test.go@@ -0,0 +1,34 @@+package tokens++import "testing"++func TestContextWindowMatchesModelVariants(t *testing.T) {+ tests := []struct {+ model string+ want int64+ known bool+ }{+ {"claude-sonnet-4-5", 200000, true},+ {"anthropic/claude-3-5-sonnet-20241022", 200000, true},+ {"gpt-4o-2024-08-06", 128000, true},+ {"gpt-4o-mini", 128000, true},+ {"gpt-4.1-mini", 1047576, true},+ {"gpt-4-turbo", 128000, true},+ {"gpt-4", 8192, true},+ {"gpt-5-mini", 400000, true},+ {"o1-preview", 200000, true},+ {"gemini-1.5-pro-latest", 2097152, true},+ {"gemini-2.0-flash", 1048576, true},+ {"GPT-4O", 128000, true},+ {"experimental-model", 0, false},+ {"", 0, false},+ }+ for _, tt := range tests {+ t.Run(tt.model, func(t *testing.T) {+ got, known := ContextWindow(tt.model)+ if got != tt.want || known != tt.known {+ t.Fatalf("ContextWindow(%q) = %d/%v, want %d/%v", tt.model, got, known, tt.want, tt.known)+ }+ })+ }+}diff --git a/cli/beacon/internal/endpoint/tokens/report.go b/cli/beacon/internal/endpoint/tokens/report.gonew file mode 100644index 00000000..ae2fc349--- /dev/null+++ b/cli/beacon/internal/endpoint/tokens/report.go@@ -0,0 +1,120 @@+package tokens++import (+ "fmt"+ "io"+ "strings"+ "text/tabwriter"+)++// RenderText writes a human-readable token usage report.+func RenderText(w io.Writer, report Report) {+ fmt.Fprintf(w, "Token usage report (%d of %d events carry usage)\n\n", report.EventsWithUsage, report.TotalEvents)+ tw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "TOTALS\tINPUT\tOUTPUT\tCACHE READ\tCACHE CREATE\tREASONING\tCOST USD\tEVENTS")+ writeUsageRow(tw, "", report.Totals)+ tw.Flush()++ writeGroups(w, "BY MODEL", report.ByModel)+ writeGroups(w, "BY SESSION", report.BySession)+ writeGroups(w, "BY HARNESS", report.ByHarness)+ writeGroups(w, "BY REPOSITORY", report.ByRepository)+ writeGroups(w, "BY RUN", report.ByRun)++ if len(report.Utilization) > 0 {+ fmt.Fprintln(w)+ tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "CONTEXT UTILIZATION\tWINDOW\tCALLS\tMAX INPUT\tMAX\tP95\tNEAR LIMIT")+ for _, u := range report.Utilization {+ window := "unknown"+ maxRatio, p95Ratio := "-", "-"+ if u.ContextWindow > 0 {+ window = fmt.Sprintf("%d", u.ContextWindow)+ maxRatio = fmt.Sprintf("%.1f%%", u.MaxRatio*100)+ p95Ratio = fmt.Sprintf("%.1f%%", u.P95Ratio*100)+ }+ fmt.Fprintf(tw, "%s\t%s\t%d\t%d\t%s\t%s\t%d\n", u.Model, window, u.Calls, u.MaxInputTokens, maxRatio, p95Ratio, u.NearLimitCalls)+ }+ tw.Flush()+ }++ if len(report.Series) > 0 {+ fmt.Fprintln(w)+ tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "BUCKET\tINPUT\tOUTPUT\tCACHE READ\tCACHE CREATE\tREASONING\tCOST USD\tEVENTS")+ for _, bucket := range report.Series {+ writeUsageRow(tw, bucket.Start, bucket.Usage)+ }+ tw.Flush()+ }++ if report.SessionDetail != nil {+ fmt.Fprintf(w, "\nSESSION %s\n", report.SessionDetail.SessionID)+ tw = tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)+ fmt.Fprintln(tw, "STEP\tMODEL\tINPUT\tOUTPUT\tCACHE READ\tCACHE CREATE\tREASONING\tCOST USD")+ for _, step := range report.SessionDetail.Steps {+ writeStepRows(tw, step, 0)+ }+ tw.Flush()+ }+}++func writeGroups(w io.Writer, title string, groups []Group) {+ if len(groups) == 0 {+ return+ }+ fmt.Fprintln(w)+ tw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)+ fmt.Fprintf(tw, "%s\tINPUT\tOUTPUT\tCACHE READ\tCACHE CREATE\tREASONING\tCOST USD\tEVENTS\n", title)+ for _, group := range groups {+ writeUsageRow(tw, group.Key, group.Usage)+ }+ tw.Flush()+}++func writeUsageRow(w io.Writer, key string, usage Usage) {+ if key == "" {+ key = "total"+ }+ fmt.Fprintf(w, "%s\t%d\t%d\t%d\t%d\t%d\t%s\t%d\n",+ key,+ usage.InputTokens,+ usage.OutputTokens,+ usage.CacheReadInputTokens,+ usage.CacheCreationInputTokens,+ usage.ReasoningOutputTokens,+ formatCost(usage.CostUSD),+ usage.Events,+ )+}++func writeStepRows(w io.Writer, step *Step, depth int) {+ label := strings.TrimSpace(step.Name)+ if label == "" {+ label = step.Action+ }+ if label == "" {+ label = step.SpanID+ }+ fmt.Fprintf(w, "%s%s\t%s\t%d\t%d\t%d\t%d\t%d\t%s\n",+ strings.Repeat(" ", depth),+ label,+ step.Model,+ step.Usage.InputTokens,+ step.Usage.OutputTokens,+ step.Usage.CacheReadInputTokens,+ step.Usage.CacheCreationInputTokens,+ step.Usage.ReasoningOutputTokens,+ formatCost(step.Usage.CostUSD),+ )+ for _, child := range step.Children {+ writeStepRows(w, child, depth+1)+ }+}++func formatCost(cost float64) string {+ if cost == 0 {+ return "-"+ }+ return fmt.Sprintf("%.4f", cost)+}diff --git a/cli/beacon/internal/endpoint/tokens/tokens.go b/cli/beacon/internal/endpoint/tokens/tokens.gonew file mode 100644index 00000000..6cfa527a--- /dev/null+++ b/cli/beacon/internal/endpoint/tokens/tokens.go@@ -0,0 +1,483 @@+// Package tokens aggregates token usage and runtime-reported cost from+// Beacon endpoint JSONL events into attribution rollups: totals, per-model,+// per-session, per-harness, per-repository, per-CI-run, time series,+// context-window utilization, and per-step session detail.+package tokens++import (+ "sort"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++const defaultNearLimitRatio = 0.8++// Usage sums the canonical gen_ai.usage fields across events. Field names+// match the event schema so report consumers see one vocabulary.+type Usage struct {+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadInputTokens int64 `json:"cache_read_input_tokens"`+ CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`+ ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`+ CostUSD float64 `json:"cost_usd"`+ Events int `json:"events"`+}++func (u Usage) TotalTokens() int64 {+ return u.InputTokens + u.OutputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens+}++func (u *Usage) add(delta Usage) {+ u.InputTokens += delta.InputTokens+ u.OutputTokens += delta.OutputTokens+ u.CacheReadInputTokens += delta.CacheReadInputTokens+ u.CacheCreationInputTokens += delta.CacheCreationInputTokens+ u.ReasoningOutputTokens += delta.ReasoningOutputTokens+ u.CostUSD += delta.CostUSD+ u.Events += delta.Events+}++type Group struct {+ Key string `json:"key"`+ Usage Usage `json:"usage"`+}++// Step is one usage-bearing event inside a session. Steps with span identity+// nest under their parent span; steps without span identity stay flat in+// time order.+type Step struct {+ Timestamp string `json:"timestamp,omitempty"`+ Action string `json:"action,omitempty"`+ Name string `json:"name,omitempty"`+ Model string `json:"model,omitempty"`+ TraceID string `json:"trace_id,omitempty"`+ SpanID string `json:"span_id,omitempty"`+ ParentSpanID string `json:"parent_span_id,omitempty"`+ Usage Usage `json:"usage"`+ Children []*Step `json:"children,omitempty"`+}++type SessionDetail struct {+ SessionID string `json:"session_id"`+ Usage Usage `json:"usage"`+ Steps []*Step `json:"steps,omitempty"`+}++// ModelUtilization summarizes how close a model's calls run to its context+// window. Utilization samples sum input, cache read, and cache creation+// tokens per (harness, session, model, timestamp) group so Claude Code's+// per-type metric datapoints recombine into one per-interval context size.+type ModelUtilization struct {+ Model string `json:"model"`+ ContextWindow int64 `json:"context_window,omitempty"`+ Calls int `json:"calls"`+ MaxInputTokens int64 `json:"max_input_tokens"`+ MaxRatio float64 `json:"max_ratio,omitempty"`+ P95Ratio float64 `json:"p95_ratio,omitempty"`+ NearLimitCalls int `json:"near_limit_calls,omitempty"`+}++type TimeBucket struct {+ Start string `json:"start"`+ Usage Usage `json:"usage"`+}++type Options struct {+ // BucketSize controls the time-series granularity. Zero disables the series.+ BucketSize time.Duration+ // NearLimitRatio marks utilization samples at or above this fraction of the+ // model context window. Defaults to 0.8.+ NearLimitRatio float64+ // SessionID selects one session for per-step detail.+ SessionID string+ // TopLimit caps each group list (0 keeps all groups).+ TopLimit int+}++type Report struct {+ Totals Usage `json:"totals"`+ ByModel []Group `json:"by_model,omitempty"`+ BySession []Group `json:"by_session,omitempty"`+ ByHarness []Group `json:"by_harness,omitempty"`+ ByRepository []Group `json:"by_repository,omitempty"`+ ByRun []Group `json:"by_run,omitempty"`+ Utilization []ModelUtilization `json:"utilization,omitempty"`+ Series []TimeBucket `json:"series,omitempty"`+ SessionDetail *SessionDetail `json:"session_detail,omitempty"`+ EventsWithUsage int `json:"events_with_usage"`+ TotalEvents int `json:"total_events"`+}++// usageEvent is one usage-bearing event with its usage normalized to a delta+// contribution and its attribution keys extracted.+type usageEvent struct {+ ts time.Time+ order int+ action string+ name string+ harness string+ session string+ model string+ repository string+ run string+ traceID string+ spanID string+ parentSpanID string+ usage Usage+ cumulative bool+ metricName string+ seriesField string+ seriesValue float64+}++// Aggregate builds a token usage report from endpoint events. Events from+// cumulative metric series are converted to per-interval deltas (grouped by+// harness, session, model, metric name, and usage field; counter resets fall+// back to the raw value) so totals never double-count. Delta metrics and+// span-level usage sum directly.+func Aggregate(events []schema.Event, opts Options) Report {+ if opts.NearLimitRatio <= 0 {+ opts.NearLimitRatio = defaultNearLimitRatio+ }+ report := Report{TotalEvents: len(events)}+ usageEvents := collectUsageEvents(events)+ resolveCumulativeSeries(usageEvents)++ byModel := map[string]*Usage{}+ bySession := map[string]*Usage{}+ byHarness := map[string]*Usage{}+ byRepository := map[string]*Usage{}+ byRun := map[string]*Usage{}+ buckets := map[time.Time]*Usage{}+ for _, ue := range usageEvents {+ report.Totals.add(ue.usage)+ addGroup(byModel, ue.model, ue.usage)+ addGroup(bySession, ue.session, ue.usage)+ addGroup(byHarness, ue.harness, ue.usage)+ addGroup(byRepository, ue.repository, ue.usage)+ addGroup(byRun, ue.run, ue.usage)+ if opts.BucketSize > 0 && !ue.ts.IsZero() {+ start := ue.ts.Truncate(opts.BucketSize)+ if buckets[start] == nil {+ buckets[start] = &Usage{}+ }+ buckets[start].add(ue.usage)+ }+ }+ report.EventsWithUsage = len(usageEvents)+ report.ByModel = sortedGroups(byModel, opts.TopLimit)+ report.BySession = sortedGroups(bySession, opts.TopLimit)+ report.ByHarness = sortedGroups(byHarness, opts.TopLimit)+ report.ByRepository = sortedGroups(byRepository, opts.TopLimit)+ report.ByRun = sortedGroups(byRun, opts.TopLimit)+ report.Utilization = buildUtilization(usageEvents, opts.NearLimitRatio)+ report.Series = sortedBuckets(buckets)+ if session := strings.TrimSpace(opts.SessionID); session != "" {+ report.SessionDetail = buildSessionDetail(usageEvents, session)+ }+ return report+}++func collectUsageEvents(events []schema.Event) []*usageEvent {+ var out []*usageEvent+ for i, event := range events {+ if event.GenAI == nil || event.GenAI.Usage == nil {+ continue+ }+ usage := event.GenAI.Usage+ ue := &usageEvent{+ order: i,+ action: event.Event.Action,+ name: event.Message,+ harness: event.Harness.Name,+ model: event.Model,+ repository: event.Repository,+ usage: Usage{Events: 1},+ }+ if ts, err := time.Parse(time.RFC3339, event.Timestamp); err == nil {+ ue.ts = ts+ }+ if event.Session != nil {+ ue.session = event.Session.ID+ }+ if event.Run != nil && (event.Run.Provider != "" || event.Run.RunID != "") {+ ue.run = strings.TrimSuffix(event.Run.Provider+"/"+event.Run.RunID, "/")+ }+ if event.Trace != nil {+ ue.traceID = event.Trace.ID+ ue.spanID = event.Trace.SpanID+ ue.parentSpanID = event.Trace.ParentSpanID+ }+ if usage.InputTokens != nil {+ ue.usage.InputTokens = *usage.InputTokens+ }+ if usage.OutputTokens != nil {+ ue.usage.OutputTokens = *usage.OutputTokens+ }+ if usage.CacheRead != nil && usage.CacheRead.InputTokens != nil {+ ue.usage.CacheReadInputTokens = *usage.CacheRead.InputTokens+ }+ if usage.CacheCreation != nil && usage.CacheCreation.InputTokens != nil {+ ue.usage.CacheCreationInputTokens = *usage.CacheCreation.InputTokens+ }+ if usage.Reasoning != nil && usage.Reasoning.OutputTokens != nil {+ ue.usage.ReasoningOutputTokens = *usage.Reasoning.OutputTokens+ }+ if usage.CostUSD != nil {+ ue.usage.CostUSD = *usage.CostUSD+ }+ if ue.usage.TotalTokens() == 0 && ue.usage.ReasoningOutputTokens == 0 && ue.usage.CostUSD == 0 {+ continue+ }+ if event.Raw != nil {+ if temporality, _ := event.Raw["metric_temporality"].(string); strings.EqualFold(temporality, "cumulative") {+ ue.cumulative = true+ }+ ue.metricName, _ = event.Raw["metric_name"].(string)+ }+ out = append(out, ue)+ }+ return out+}++// resolveCumulativeSeries rewrites cumulative metric contributions into+// per-interval deltas. Each cumulative series is identified by harness,+// session, model, metric name, and the single usage field the datapoint set.+func resolveCumulativeSeries(events []*usageEvent) {+ series := map[string][]*usageEvent{}+ for _, ue := range events {+ if !ue.cumulative {+ continue+ }+ field, value := dominantUsageField(ue.usage)+ if field == "" {+ continue+ }+ ue.seriesField = field+ ue.seriesValue = value+ key := strings.Join([]string{ue.harness, ue.session, ue.model, ue.metricName, field}, "\x00")+ series[key] = append(series[key], ue)+ }+ for _, points := range series {+ sort.SliceStable(points, func(i, j int) bool {+ if points[i].ts.Equal(points[j].ts) {+ return points[i].order < points[j].order+ }+ return points[i].ts.Before(points[j].ts)+ })+ previous := 0.0+ for _, point := range points {+ delta := point.seriesValue - previous+ if delta < 0 {+ // Counter reset: the raw value is the new interval's total.+ delta = point.seriesValue+ }+ previous = point.seriesValue+ setUsageField(&point.usage, point.seriesField, delta)+ }+ }+}++func dominantUsageField(u Usage) (string, float64) {+ switch {+ case u.CostUSD != 0:+ return "cost_usd", u.CostUSD+ case u.InputTokens != 0:+ return "input_tokens", float64(u.InputTokens)+ case u.OutputTokens != 0:+ return "output_tokens", float64(u.OutputTokens)+ case u.CacheReadInputTokens != 0:+ return "cache_read_input_tokens", float64(u.CacheReadInputTokens)+ case u.CacheCreationInputTokens != 0:+ return "cache_creation_input_tokens", float64(u.CacheCreationInputTokens)+ case u.ReasoningOutputTokens != 0:+ return "reasoning_output_tokens", float64(u.ReasoningOutputTokens)+ default:+ return "", 0+ }+}++func setUsageField(u *Usage, field string, value float64) {+ switch field {+ case "cost_usd":+ u.CostUSD = value+ case "input_tokens":+ u.InputTokens = int64(value)+ case "output_tokens":+ u.OutputTokens = int64(value)+ case "cache_read_input_tokens":+ u.CacheReadInputTokens = int64(value)+ case "cache_creation_input_tokens":+ u.CacheCreationInputTokens = int64(value)+ case "reasoning_output_tokens":+ u.ReasoningOutputTokens = int64(value)+ }+}++func addGroup(groups map[string]*Usage, key string, delta Usage) {+ key = strings.TrimSpace(key)+ if key == "" {+ return+ }+ if groups[key] == nil {+ groups[key] = &Usage{}+ }+ groups[key].add(delta)+}++func sortedGroups(groups map[string]*Usage, limit int) []Group {+ out := make([]Group, 0, len(groups))+ for key, usage := range groups {+ out = append(out, Group{Key: key, Usage: *usage})+ }+ sort.SliceStable(out, func(i, j int) bool {+ left, right := out[i].Usage.TotalTokens(), out[j].Usage.TotalTokens()+ if left == right {+ return out[i].Key < out[j].Key+ }+ return left > right+ })+ if limit > 0 && len(out) > limit {+ out = out[:limit]+ }+ return out+}++func sortedBuckets(buckets map[time.Time]*Usage) []TimeBucket {+ starts := make([]time.Time, 0, len(buckets))+ for start := range buckets {+ starts = append(starts, start)+ }+ sort.Slice(starts, func(i, j int) bool { return starts[i].Before(starts[j]) })+ out := make([]TimeBucket, 0, len(starts))+ for _, start := range starts {+ out = append(out, TimeBucket{Start: start.UTC().Format(time.RFC3339), Usage: *buckets[start]})+ }+ return out+}++func buildUtilization(events []*usageEvent, nearLimitRatio float64) []ModelUtilization {+ type sample struct{ inputTotal int64 }+ samples := map[string]map[string]*sample{}+ for _, ue := range events {+ if ue.model == "" {+ continue+ }+ inputTotal := ue.usage.InputTokens + ue.usage.CacheReadInputTokens + ue.usage.CacheCreationInputTokens+ if inputTotal <= 0 {+ continue+ }+ callKey := strings.Join([]string{ue.harness, ue.session, ue.ts.UTC().Format(time.RFC3339)}, "\x00")+ if samples[ue.model] == nil {+ samples[ue.model] = map[string]*sample{}+ }+ if samples[ue.model][callKey] == nil {+ samples[ue.model][callKey] = &sample{}+ }+ samples[ue.model][callKey].inputTotal += inputTotal+ }+ out := make([]ModelUtilization, 0, len(samples))+ for model, calls := range samples {+ utilization := ModelUtilization{Model: model, Calls: len(calls)}+ window, known := ContextWindow(model)+ if known {+ utilization.ContextWindow = window+ }+ ratios := make([]float64, 0, len(calls))+ for _, call := range calls {+ if call.inputTotal > utilization.MaxInputTokens {+ utilization.MaxInputTokens = call.inputTotal+ }+ if !known {+ continue+ }+ ratio := float64(call.inputTotal) / float64(window)+ ratios = append(ratios, ratio)+ if ratio >= nearLimitRatio {+ utilization.NearLimitCalls+++ }+ }+ if len(ratios) > 0 {+ sort.Float64s(ratios)+ utilization.MaxRatio = ratios[len(ratios)-1]+ utilization.P95Ratio = percentile(ratios, 0.95)+ }+ out = append(out, utilization)+ }+ sort.SliceStable(out, func(i, j int) bool {+ if out[i].MaxRatio == out[j].MaxRatio {+ return out[i].Model < out[j].Model+ }+ return out[i].MaxRatio > out[j].MaxRatio+ })+ return out+}++// percentile reads the nearest-rank percentile from an ascending-sorted slice.+func percentile(sorted []float64, p float64) float64 {+ if len(sorted) == 0 {+ return 0+ }+ rank := int(float64(len(sorted))*p+0.999999) - 1+ if rank < 0 {+ rank = 0+ }+ if rank >= len(sorted) {+ rank = len(sorted) - 1+ }+ return sorted[rank]+}++func buildSessionDetail(events []*usageEvent, sessionID string) *SessionDetail {+ detail := &SessionDetail{SessionID: sessionID}+ var ordered []*usageEvent+ for _, ue := range events {+ if ue.session != sessionID {+ continue+ }+ detail.Usage.add(ue.usage)+ ordered = append(ordered, ue)+ }+ sort.SliceStable(ordered, func(i, j int) bool {+ if ordered[i].ts.Equal(ordered[j].ts) {+ return ordered[i].order < ordered[j].order+ }+ return ordered[i].ts.Before(ordered[j].ts)+ })+ steps := make([]*Step, 0, len(ordered))+ bySpan := map[string]*Step{}+ for _, ue := range ordered {+ step := &Step{+ Action: ue.action,+ Name: ue.name,+ Model: ue.model,+ TraceID: ue.traceID,+ SpanID: ue.spanID,+ ParentSpanID: ue.parentSpanID,+ Usage: ue.usage,+ }+ if !ue.ts.IsZero() {+ step.Timestamp = ue.ts.UTC().Format(time.RFC3339)+ }+ steps = append(steps, step)+ if step.SpanID != "" {+ bySpan[step.SpanID] = step+ }+ }+ for _, step := range steps {+ if step.ParentSpanID == "" {+ detail.Steps = append(detail.Steps, step)+ continue+ }+ parent, ok := bySpan[step.ParentSpanID]+ if !ok || parent == step {+ detail.Steps = append(detail.Steps, step)+ continue+ }+ parent.Children = append(parent.Children, step)+ }+ return detail+}diff --git a/cli/beacon/internal/endpoint/tokens/tokens_test.go b/cli/beacon/internal/endpoint/tokens/tokens_test.gonew file mode 100644index 00000000..20b3c760--- /dev/null+++ b/cli/beacon/internal/endpoint/tokens/tokens_test.go@@ -0,0 +1,215 @@+package tokens++import (+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++func usageEventFixture(ts, harness, session, model string, mutate func(*schema.Event)) schema.Event {+ event := schema.Event{+ Timestamp: ts,+ Event: schema.EventInfo{Kind: "agent_runtime", Action: "token.usage", Category: "metric"},+ Harness: schema.HarnessInfo{Name: harness},+ Model: model,+ GenAI: &schema.GenAIInfo{Usage: &schema.GenAIUsageInfo{}},+ }+ if session != "" {+ event.Session = &schema.SessionInfo{ID: session}+ }+ if mutate != nil {+ mutate(&event)+ }+ return event+}++func int64Ptr(v int64) *int64 { return &v }+func float64Ptr(v float64) *float64 { return &v }++func TestAggregateSumsDeltaUsageAcrossGroups(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(100)+ e.Repository = "github.com/acme/app"+ }),+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.OutputTokens = int64Ptr(40)+ }),+ usageEventFixture("2026-06-11T11:00:00Z", "asymptote_observe", "s2", "gpt-4o-mini", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(60)+ e.GenAI.Usage.OutputTokens = int64Ptr(20)+ e.GenAI.Usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: int64Ptr(5)}+ }),+ usageEventFixture("2026-06-11T11:30:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.Event.Action = "cost.usage"+ e.GenAI.Usage.CostUSD = float64Ptr(0.25)+ }),+ // Event without usage is counted in TotalEvents only.+ {Timestamp: "2026-06-11T11:45:00Z", Event: schema.EventInfo{Action: "tool.invoked"}, Harness: schema.HarnessInfo{Name: "claude_code"}},+ }++ report := Aggregate(events, Options{BucketSize: time.Hour})+ if report.TotalEvents != 5 || report.EventsWithUsage != 4 {+ t.Fatalf("event counts = %d/%d, want 4/5", report.EventsWithUsage, report.TotalEvents)+ }+ if report.Totals.InputTokens != 160 || report.Totals.OutputTokens != 60 || report.Totals.ReasoningOutputTokens != 5 || report.Totals.CostUSD != 0.25 {+ t.Fatalf("totals = %#v", report.Totals)+ }+ if len(report.ByModel) != 2 || report.ByModel[0].Key != "claude-sonnet-4-5" || report.ByModel[0].Usage.InputTokens != 100 || report.ByModel[0].Usage.CostUSD != 0.25 {+ t.Fatalf("by_model = %#v", report.ByModel)+ }+ if len(report.BySession) != 2 || report.BySession[0].Key != "s1" {+ t.Fatalf("by_session = %#v", report.BySession)+ }+ if len(report.ByHarness) != 2 || report.ByHarness[0].Key != "claude_code" {+ t.Fatalf("by_harness = %#v", report.ByHarness)+ }+ if len(report.ByRepository) != 1 || report.ByRepository[0].Key != "github.com/acme/app" || report.ByRepository[0].Usage.InputTokens != 100 {+ t.Fatalf("by_repository = %#v", report.ByRepository)+ }+ if len(report.Series) != 2 || report.Series[0].Start != "2026-06-11T10:00:00Z" || report.Series[0].Usage.InputTokens != 100 || report.Series[1].Usage.CostUSD != 0.25 {+ t.Fatalf("series = %#v", report.Series)+ }+}++func TestAggregateDedupesCumulativeSeries(t *testing.T) {+ cumulative := func(ts string, value int64) schema.Event {+ return usageEventFixture(ts, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(value)+ e.Raw = map[string]interface{}{+ "metric_name": "claude_code.token.usage",+ "metric_temporality": "Cumulative",+ }+ })+ }+ events := []schema.Event{+ cumulative("2026-06-11T10:00:00Z", 100),+ cumulative("2026-06-11T10:01:00Z", 250),+ cumulative("2026-06-11T10:02:00Z", 400),+ // Counter reset: raw value becomes the interval contribution.+ cumulative("2026-06-11T10:03:00Z", 50),+ }++ report := Aggregate(events, Options{})+ if report.Totals.InputTokens != 450 {+ t.Fatalf("cumulative input total = %d, want 450 (100+150+150+50)", report.Totals.InputTokens)+ }+}++func TestAggregateAttributesCIRuns(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "ci-1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(10)+ e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "12345"}+ }),+ usageEventFixture("2026-06-11T10:05:00Z", "claude_code", "ci-1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.OutputTokens = int64Ptr(4)+ e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "12345"}+ }),+ }+ report := Aggregate(events, Options{})+ if len(report.ByRun) != 1 || report.ByRun[0].Key != "github_actions/12345" {+ t.Fatalf("by_run = %#v", report.ByRun)+ }+ if report.ByRun[0].Usage.InputTokens != 10 || report.ByRun[0].Usage.OutputTokens != 4 {+ t.Fatalf("by_run usage = %#v", report.ByRun[0].Usage)+ }+}++func TestAggregateBuildsSessionStepTree(t *testing.T) {+ spanEvent := func(ts, span, parent string, input int64) schema.Event {+ return usageEventFixture(ts, "asymptote_observe", "s1", "gpt-4o-mini", func(e *schema.Event) {+ e.Event.Action = "tool.invoked"+ e.Message = "step-" + span+ e.GenAI.Usage.InputTokens = int64Ptr(input)+ e.Trace = &schema.TraceInfo{ID: "trace-1", SpanID: span, ParentSpanID: parent}+ })+ }+ events := []schema.Event{+ spanEvent("2026-06-11T10:00:00Z", "root", "", 100),+ spanEvent("2026-06-11T10:00:05Z", "child-a", "root", 30),+ spanEvent("2026-06-11T10:00:10Z", "child-b", "root", 20),+ spanEvent("2026-06-11T10:00:15Z", "grandchild", "child-a", 10),+ // Step without span identity stays flat at the top level.+ usageEventFixture("2026-06-11T10:00:20Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.OutputTokens = int64Ptr(7)+ }),+ }++ report := Aggregate(events, Options{SessionID: "s1"})+ detail := report.SessionDetail+ if detail == nil || detail.SessionID != "s1" {+ t.Fatalf("session detail = %#v", detail)+ }+ if detail.Usage.InputTokens != 160 || detail.Usage.OutputTokens != 7 {+ t.Fatalf("session usage = %#v", detail.Usage)+ }+ if len(detail.Steps) != 2 {+ t.Fatalf("top-level steps = %d, want 2 (root + flat step): %#v", len(detail.Steps), detail.Steps)+ }+ root := detail.Steps[0]+ if root.SpanID != "root" || len(root.Children) != 2 {+ t.Fatalf("root step = %#v", root)+ }+ if root.Children[0].SpanID != "child-a" || len(root.Children[0].Children) != 1 || root.Children[0].Children[0].SpanID != "grandchild" {+ t.Fatalf("child tree = %#v", root.Children)+ }+ if detail.Steps[1].SpanID != "" || detail.Steps[1].Usage.OutputTokens != 7 {+ t.Fatalf("flat step = %#v", detail.Steps[1])+ }+}++func TestAggregateUtilizationCombinesPerIntervalDataPoints(t *testing.T) {+ // Claude Code reports one datapoint per token type at the same timestamp;+ // utilization must recombine them into one context-size sample.+ at := "2026-06-11T10:00:00Z"+ events := []schema.Event{+ usageEventFixture(at, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(1000)+ }),+ usageEventFixture(at, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(179000)}+ }),+ usageEventFixture(at, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: int64Ptr(5000)}+ }),+ usageEventFixture("2026-06-11T11:00:00Z", "asymptote_observe", "s2", "experimental-model", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(123)+ }),+ }++ report := Aggregate(events, Options{})+ if len(report.Utilization) != 2 {+ t.Fatalf("utilization = %#v", report.Utilization)+ }+ claude := report.Utilization[0]+ if claude.Model != "claude-sonnet-4-5" || claude.ContextWindow != 200000 || claude.Calls != 1 {+ t.Fatalf("claude utilization = %#v", claude)+ }+ if claude.MaxInputTokens != 185000 || claude.MaxRatio != 0.925 || claude.NearLimitCalls != 1 {+ t.Fatalf("claude utilization sample = %#v", claude)+ }+ unknown := report.Utilization[1]+ if unknown.Model != "experimental-model" || unknown.ContextWindow != 0 || unknown.MaxRatio != 0 || unknown.MaxInputTokens != 123 {+ t.Fatalf("unknown model utilization = %#v", unknown)+ }+}++func TestAggregateTopLimitCapsGroups(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "model-a", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(300)+ }),+ usageEventFixture("2026-06-11T10:01:00Z", "claude_code", "s2", "model-b", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(200)+ }),+ usageEventFixture("2026-06-11T10:02:00Z", "claude_code", "s3", "model-c", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(100)+ }),+ }+ report := Aggregate(events, Options{TopLimit: 2})+ if len(report.ByModel) != 2 || report.ByModel[0].Key != "model-a" || report.ByModel[1].Key != "model-b" {+ t.Fatalf("by_model = %#v", report.ByModel)+ }+}