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
refactor token usage command
Justin D'Souza621c448f0b02
diff --git a/CLAUDE.md b/CLAUDE.mdindex d6c3c304..06a3529d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -35,7 +35,7 @@ Supported runtime surfaces today:- Asymptote Observe TypeScript SDK instrumentation for cloud applications, starting from OpenTelemetry/OpenLLMetry patterns and `observe()` wrappers.- Elasticsearch/Filebeat content pack generation for forwarding local Beacon JSONL into customer-managed Elastic deployments or the bundled loopback-only development stack.- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.-- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon endpoint tokens` report command for local and CI logs.+- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs.- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.Current non-goals unless explicitly requested:diff --git a/cli/beacon/cmd/endpoint_tokens.go b/cli/beacon/cmd/endpoint_tokens.godeleted file mode 100644index 3b68a34d..00000000--- a/cli/beacon/cmd/endpoint_tokens.go+++ /dev/null@@ -1,131 +0,0 @@-package cmd--import (- "encoding/json"- "strings"- "time"-- "github.com/spf13/cobra"-- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/tokens"-)--var endpointTokensOpts struct {- userMode bool- systemMode bool- logPath string- jsonOutput bool- since string- until string- session string- model string- harness string- repository string- runID string- bucket string- top int-}--var endpointTokensCmd = &cobra.Command{- Use: "tokens",- Short: "Report token usage and attribution from the endpoint runtime log",- SilenceUsage: true,- RunE: runEndpointTokens,-}--func runEndpointTokens(cmd *cobra.Command, args []string) error {- userMode := endpointTokensOpts.userMode- if endpointTokensOpts.systemMode {- userMode = false- }- runtimeLog := lifecycle.ResolveRuntimeLog(userMode, endpointTokensOpts.logPath)- query := dashboard.EventQuery{- NoLimit: true,- Session: endpointTokensOpts.session,- Model: endpointTokensOpts.model,- Harness: endpointTokensOpts.harness,- Repository: endpointTokensOpts.repository,- }- if since := strings.TrimSpace(endpointTokensOpts.since); since != "" {- parsed, err := time.Parse(time.RFC3339, since)- if err != nil {- return err- }- query.Since = parsed- }- if until := strings.TrimSpace(endpointTokensOpts.until); until != "" {- parsed, err := time.Parse(time.RFC3339, until)- if err != nil {- return err- }- query.Until = parsed- }- result, err := dashboard.ReadEvents(runtimeLog.EffectiveLogPath, query)- if err != nil {- return err- }- // Feed Aggregate in chronological (append) order so cumulative metric- // series resolve correctly when a batch of datapoints shares the same- // second-resolution timestamp.- dashboard.SortRecordsAppendOrder(result.Events)- session := strings.TrimSpace(endpointTokensOpts.session)- runID := strings.TrimSpace(endpointTokensOpts.runID)- events := make([]schema.Event, 0, len(result.Events))- for _, record := range result.Events {- // Match the session case-insensitively (consistent with the- // case-insensitive event query) so totals/grouping stay aligned with- // the per-step drilldown.- if session != "" && (record.Event.Session == nil || !strings.EqualFold(record.Event.Session.ID, session)) {- continue- }- if runID != "" {- // Accept either the bare run id or the composite provider/run_id- // key shown in the BY RUN rollup.- run := record.Event.Run- if run == nil || (run.RunID != runID && tokens.RunKey(run.Provider, run.RunID) != runID) {- continue- }- }- events = append(events, record.Event)- }- opts := tokens.Options{- SessionID: endpointTokensOpts.session,- TopLimit: endpointTokensOpts.top,- }- if bucket := strings.TrimSpace(endpointTokensOpts.bucket); bucket != "" {- parsed, err := time.ParseDuration(bucket)- if err != nil {- return err- }- opts.BucketSize = parsed- }- report := tokens.Aggregate(events, opts)- out := cmd.OutOrStdout()- if endpointTokensOpts.jsonOutput {- encoder := json.NewEncoder(out)- encoder.SetIndent("", " ")- return encoder.Encode(report)- }- tokens.RenderText(out, report)- return nil-}--func init() {- endpointCmd.AddCommand(endpointTokensCmd)- endpointTokensCmd.Flags().BoolVar(&endpointTokensOpts.userMode, "user", true, "Use per-user endpoint paths")- endpointTokensCmd.Flags().BoolVar(&endpointTokensOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.logPath, "log-path", "", "Runtime JSONL log path (defaults to the endpoint runtime log; in CI point at the session log)")- endpointTokensCmd.Flags().BoolVar(&endpointTokensOpts.jsonOutput, "json", false, "Print the token usage report as JSON")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.since, "since", "", "Only include events at or after this RFC3339 timestamp")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.until, "until", "", "Only include events at or before this RFC3339 timestamp")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.session, "session", "", "Filter to one session and include per-step detail")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.model, "model", "", "Filter by model name")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.harness, "harness", "", "Filter by harness name")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.repository, "repository", "", "Filter by repository")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.runID, "run-id", "", "Filter by CI run id")- endpointTokensCmd.Flags().StringVar(&endpointTokensOpts.bucket, "bucket", "", "Time-series bucket size (for example 1h or 15m)")- endpointTokensCmd.Flags().IntVar(&endpointTokensOpts.top, "top", 0, "Limit each grouping to the top N entries (0 keeps all)")-}diff --git a/cli/beacon/cmd/token_usage.go b/cli/beacon/cmd/token_usage.gonew file mode 100644index 00000000..117cab1d--- /dev/null+++ b/cli/beacon/cmd/token_usage.go@@ -0,0 +1,107 @@+package cmd++import (+ "encoding/json"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/tokens"+)++type tokenUsageOptions struct {+ userMode bool+ systemMode bool+ logPath string+ jsonOutput bool+ since string+ until string+ session string+ model string+ harness string+ repository string+ runID string+ bucket string+ top int+}++var tokenUsageOpts tokenUsageOptions++var tokenUsageCmd = &cobra.Command{+ Use: "token-usage",+ Short: "Report token usage and attribution from the endpoint runtime log",+ SilenceUsage: true,+ RunE: runTokenUsage,+}++func runTokenUsage(cmd *cobra.Command, args []string) error {+ userMode := tokenUsageOpts.userMode+ if tokenUsageOpts.systemMode {+ userMode = false+ }+ runtimeLog := lifecycle.ResolveRuntimeLog(userMode, tokenUsageOpts.logPath)+ query := dashboard.EventQuery{+ Session: tokenUsageOpts.session,+ Model: tokenUsageOpts.model,+ Harness: tokenUsageOpts.harness,+ Repository: tokenUsageOpts.repository,+ }+ if since := strings.TrimSpace(tokenUsageOpts.since); since != "" {+ parsed, err := time.Parse(time.RFC3339, since)+ if err != nil {+ return err+ }+ query.Since = parsed+ }+ if until := strings.TrimSpace(tokenUsageOpts.until); until != "" {+ parsed, err := time.Parse(time.RFC3339, until)+ if err != nil {+ return err+ }+ query.Until = parsed+ }+ events, err := dashboard.ReadEventsAppendOrder(runtimeLog.EffectiveLogPath, query)+ if err != nil {+ return err+ }+ opts := tokens.Options{+ SessionID: tokenUsageOpts.session,+ TopLimit: tokenUsageOpts.top,+ }+ if bucket := strings.TrimSpace(tokenUsageOpts.bucket); bucket != "" {+ parsed, err := time.ParseDuration(bucket)+ if err != nil {+ return err+ }+ opts.BucketSize = parsed+ }+ report := tokens.AggregateScoped(events, tokenUsageOpts.runID, opts)+ out := cmd.OutOrStdout()+ if tokenUsageOpts.jsonOutput {+ encoder := json.NewEncoder(out)+ encoder.SetIndent("", " ")+ return encoder.Encode(report)+ }+ tokens.RenderText(out, report)+ return nil+}++func init() {+ rootCmd.AddCommand(tokenUsageCmd)+ tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.userMode, "user", true, "Use per-user endpoint paths")+ tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.systemMode, "system", false, "Use system endpoint paths and launch daemon")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.logPath, "log-path", "", "Runtime JSONL log path (defaults to the endpoint runtime log; in CI point at the session log)")+ tokenUsageCmd.Flags().BoolVar(&tokenUsageOpts.jsonOutput, "json", false, "Print the token usage report as JSON")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.since, "since", "", "Only include events at or after this RFC3339 timestamp")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.until, "until", "", "Only include events at or before this RFC3339 timestamp")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.session, "session", "", "Filter to one session and include per-step detail")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.model, "model", "", "Filter by model name")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.harness, "harness", "", "Filter by harness name")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.repository, "repository", "", "Filter by repository")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.runID, "run-id", "", "Filter by CI run id")+ tokenUsageCmd.Flags().StringVar(&tokenUsageOpts.bucket, "bucket", "", "Time-series bucket size (for example 1h or 15m)")+ tokenUsageCmd.Flags().IntVar(&tokenUsageOpts.top, "top", 0, "Limit each grouping to the top N entries (0 keeps all)")+}diff --git a/cli/beacon/cmd/endpoint_tokens_test.go b/cli/beacon/cmd/token_usage_test.gosimilarity index 73%rename from cli/beacon/cmd/endpoint_tokens_test.gorename to cli/beacon/cmd/token_usage_test.goindex e61eb7ff..b90017f1 100644--- a/cli/beacon/cmd/endpoint_tokens_test.go+++ b/cli/beacon/cmd/token_usage_test.go@@ -11,17 +11,17 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/tokens")-func TestEndpointTokensCommandRegistered(t *testing.T) {- cmd, _, err := endpointCmd.Find([]string{"tokens"})+func TestTokenUsageCommandRegistered(t *testing.T) {+ cmd, _, err := rootCmd.Find([]string{"token-usage"})if err != nil {- t.Fatalf("Find tokens returned error: %v", err)+ t.Fatalf("Find token-usage returned error: %v", err)}- if cmd == nil || cmd.Use != "tokens" {- t.Fatalf("tokens command not registered: %#v", cmd)+ if cmd == nil || cmd.Use != "token-usage" {+ t.Fatalf("token-usage command not registered: %#v", cmd)}for _, flag := range []string{"log-path", "json", "since", "until", "session", "model", "harness", "repository", "run-id", "bucket", "top"} {if cmd.Flags().Lookup(flag) == nil {- t.Fatalf("tokens command missing --%s flag", flag)+ t.Fatalf("token-usage command missing --%s flag", flag)}}}@@ -40,38 +40,24 @@ func writeTokensFixtureLog(t *testing.T) string {return logPath}-func runTokensCommand(t *testing.T, args ...string) string {+func runTokenUsageCommand(t *testing.T, args ...string) string {t.Helper()- endpointTokensOpts = struct {- userMode bool- systemMode bool- logPath string- jsonOutput bool- since string- until string- session string- model string- harness string- repository string- runID string- bucket string- top int- }{userMode: true}- if err := endpointTokensCmd.Flags().Parse(args); err != nil {+ tokenUsageOpts = tokenUsageOptions{userMode: true}+ if err := tokenUsageCmd.Flags().Parse(args); err != nil {t.Fatalf("parse flags: %v", err)}var out bytes.Buffer- endpointTokensCmd.SetOut(&out)- defer endpointTokensCmd.SetOut(nil)- if err := runEndpointTokens(endpointTokensCmd, nil); err != nil {- t.Fatalf("runEndpointTokens returned error: %v", err)+ tokenUsageCmd.SetOut(&out)+ defer tokenUsageCmd.SetOut(nil)+ if err := runTokenUsage(tokenUsageCmd, nil); err != nil {+ t.Fatalf("runTokenUsage returned error: %v", err)}return out.String()}-func TestEndpointTokensTextReport(t *testing.T) {+func TestTokenUsageTextReport(t *testing.T) {logPath := writeTokensFixtureLog(t)- output := runTokensCommand(t, "--log-path", logPath)+ output := runTokenUsageCommand(t, "--log-path", logPath)for _, want := range []string{"3 of 3 events carry usage","claude-sonnet-4-5",@@ -86,9 +72,9 @@ func TestEndpointTokensTextReport(t *testing.T) {}}-func TestEndpointTokensJSONReport(t *testing.T) {+func TestTokenUsageJSONReport(t *testing.T) {logPath := writeTokensFixtureLog(t)- output := runTokensCommand(t, "--log-path", logPath, "--json", "--session", "session-1")+ output := runTokenUsageCommand(t, "--log-path", logPath, "--json", "--session", "session-1")var report tokens.Reportif err := json.Unmarshal([]byte(output), &report); err != nil {t.Fatalf("unmarshal JSON report: %v\n%s", err, output)@@ -104,12 +90,12 @@ func TestEndpointTokensJSONReport(t *testing.T) {}}-func TestEndpointTokensRunIDFilterAcceptsBareAndCompositeKeys(t *testing.T) {+func TestTokenUsageRunIDFilterAcceptsBareAndCompositeKeys(t *testing.T) {logPath := writeTokensFixtureLog(t)// The BY RUN rollup labels this run "github_actions/777"; both that// composite key and the bare run id must select the run's usage.for _, runID := range []string{"777", "github_actions/777"} {- output := runTokensCommand(t, "--log-path", logPath, "--json", "--run-id", runID)+ output := runTokenUsageCommand(t, "--log-path", logPath, "--json", "--run-id", runID)var report tokens.Reportif err := json.Unmarshal([]byte(output), &report); err != nil {t.Fatalf("unmarshal JSON report for %q: %v\n%s", runID, err, output)@@ -123,9 +109,9 @@ func TestEndpointTokensRunIDFilterAcceptsBareAndCompositeKeys(t *testing.T) {}}-func TestEndpointTokensEmptyLogSucceeds(t *testing.T) {+func TestTokenUsageEmptyLogSucceeds(t *testing.T) {logPath := filepath.Join(t.TempDir(), "runtime.jsonl")- output := runTokensCommand(t, "--log-path", logPath)+ output := runTokenUsageCommand(t, "--log-path", logPath)if !strings.Contains(output, "0 of 0 events carry usage") {t.Fatalf("empty report = %q", output)}diff --git a/cli/beacon/internal/endpoint/dashboard/events.go b/cli/beacon/internal/endpoint/dashboard/events.goindex 9f7c67ef..89b666ac 100644--- a/cli/beacon/internal/endpoint/dashboard/events.go+++ b/cli/beacon/internal/endpoint/dashboard/events.go@@ -83,6 +83,27 @@ func ReadEvents(path string, query EventQuery) (EventResult, error) {return result, nil}+// ReadEventsAppendOrder reads the full matching log (NoLimit) and returns the+// events in chronological (log append) order. Token aggregation needs append+// order because runtime timestamps are second-resolution, so a batch of+// cumulative datapoints from one export commonly shares a timestamp; the+// cumulative dedup then relies on append order to recover the emission sequence.+// The newest-first ReadEvents sort breaks such ties on lexicographic line IDs,+// which mis-orders line-9 vs line-10 within a second.+func ReadEventsAppendOrder(path string, query EventQuery) ([]schema.Event, error) {+ query.NoLimit = true+ result, err := ReadEvents(path, query)+ if err != nil {+ return nil, err+ }+ SortRecordsAppendOrder(result.Events)+ events := make([]schema.Event, 0, len(result.Events))+ for _, record := range result.Events {+ events = append(events, record.Event)+ }+ return events, nil+}+// StreamEvents reads every event from the runtime log and its rotated archives in// chronological (append) order and invokes fn for each, with no limit and no result// buffering. Rule evaluation (beacon scan) needs the full, ordered stream — ReadEventsdiff --git a/cli/beacon/internal/endpoint/dashboard/server.go b/cli/beacon/internal/endpoint/dashboard/server.goindex 822d9891..96132a3a 100644--- a/cli/beacon/internal/endpoint/dashboard/server.go+++ b/cli/beacon/internal/endpoint/dashboard/server.go@@ -15,7 +15,6 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/inventory""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/tokens")@@ -134,30 +133,15 @@ func Handler(opts Options) (http.Handler, error) {methodNotAllowed(w)return}- // Token rollups need the full matching log, not the latest page.- query := parseQuery(r, maxEventLimit)- query.NoLimit = true- result, err := ReadEvents(opts.LogPath, query)+ // Token rollups need the full matching log in append order, not the+ // latest page. tokenOptions carries the session, so AggregateScoped+ // applies the exact session filter; the dashboard never scopes by run.+ events, err := ReadEventsAppendOrder(opts.LogPath, parseQuery(r, maxEventLimit))if err != nil {writeError(w, http.StatusInternalServerError, err)return}- // Feed Aggregate in chronological (append) order so cumulative metric- // series resolve correctly when a batch of datapoints shares the same- // second-resolution timestamp.- SortRecordsAppendOrder(result.Events)- session := strings.TrimSpace(query.Session)- events := make([]schema.Event, 0, len(result.Events))- for _, record := range result.Events {- // Match the session case-insensitively (consistent with the- // case-insensitive event query) so totals/grouping stay aligned- // with the per-step drilldown.- if session != "" && (record.Event.Session == nil || !strings.EqualFold(record.Event.Session.ID, session)) {- continue- }- events = append(events, record.Event)- }- writeJSON(w, tokens.Aggregate(events, tokenOptions(r)))+ writeJSON(w, tokens.AggregateScoped(events, "", tokenOptions(r)))})mux.HandleFunc("/api/detections", func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {diff --git a/cli/beacon/internal/endpoint/tokens/tokens.go b/cli/beacon/internal/endpoint/tokens/tokens.goindex f519fce9..73ed81f8 100644--- a/cli/beacon/internal/endpoint/tokens/tokens.go+++ b/cli/beacon/internal/endpoint/tokens/tokens.go@@ -188,6 +188,37 @@ func Aggregate(events []schema.Event, opts Options) Report {return report}+// AggregateScoped narrows events to a single session and optional CI run before+// aggregating. The session filter uses opts.SessionID and matches exactly+// (case-insensitive) so totals and grouping stay aligned with the per-step+// drilldown, which keys on the exact session id; the broader substring match used+// by the event query is intentionally not reused here. When runID != "" only the+// matching run is kept, accepting either the bare run id or the composite+// provider/run_id key shown in the BY RUN rollup. Pass runID == "" to skip run+// filtering. Events should already be in chronological (append) order; see+// Aggregate.+func AggregateScoped(events []schema.Event, runID string, opts Options) Report {+ session := strings.TrimSpace(opts.SessionID)+ runID = strings.TrimSpace(runID)+ if session == "" && runID == "" {+ return Aggregate(events, opts)+ }+ filtered := make([]schema.Event, 0, len(events))+ for _, event := range events {+ if session != "" && (event.Session == nil || !strings.EqualFold(event.Session.ID, session)) {+ continue+ }+ if runID != "" {+ run := event.Run+ if run == nil || (run.RunID != runID && RunKey(run.Provider, run.RunID) != runID) {+ continue+ }+ }+ filtered = append(filtered, event)+ }+ return Aggregate(filtered, opts)+}+func collectUsageEvents(events []schema.Event) []*usageEvent {var out []*usageEventfor i, event := range events {diff --git a/cli/beacon/internal/endpoint/tokens/tokens_test.go b/cli/beacon/internal/endpoint/tokens/tokens_test.goindex ade970f0..61ed63af 100644--- a/cli/beacon/internal/endpoint/tokens/tokens_test.go+++ b/cli/beacon/internal/endpoint/tokens/tokens_test.go@@ -189,6 +189,44 @@ func TestAggregateRunKeyWithoutProvider(t *testing.T) {}}+func TestAggregateScopedFiltersSessionAndRun(t *testing.T) {+ events := []schema.Event{+ usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "Session-1", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(100)+ e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "777"}+ }),+ usageEventFixture("2026-06-11T10:01:00Z", "claude_code", "session-2", "claude-sonnet-4-5", func(e *schema.Event) {+ e.GenAI.Usage.InputTokens = int64Ptr(50)+ e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "888"}+ }),+ }++ // Session match is exact but case-insensitive.+ report := AggregateScoped(events, "", Options{SessionID: "session-1"})+ if report.Totals.InputTokens != 100 || report.TotalEvents != 1 {+ t.Fatalf("session scope totals = %#v (events=%d), want only session-1", report.Totals, report.TotalEvents)+ }+ if report.SessionDetail == nil || report.SessionDetail.SessionID != "session-1" {+ t.Fatalf("session detail = %#v", report.SessionDetail)+ }++ // Run id accepts both the bare id and the composite provider/run_id key.+ for _, runID := range []string{"888", "github_actions/888"} {+ got := AggregateScoped(events, runID, Options{})+ if got.Totals.InputTokens != 50 || got.TotalEvents != 1 {+ t.Fatalf("run scope %q totals = %#v (events=%d), want only run 888", runID, got.Totals, got.TotalEvents)+ }+ if len(got.ByRun) != 1 || got.ByRun[0].Key != "github_actions/888" {+ t.Fatalf("run scope %q by_run = %#v", runID, got.ByRun)+ }+ }++ // No scope keeps every event.+ if all := AggregateScoped(events, "", Options{}); all.Totals.InputTokens != 150 || all.TotalEvents != 2 {+ t.Fatalf("unscoped totals = %#v (events=%d), want all events", all.Totals, all.TotalEvents)+ }+}+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) {diff --git a/docs/cli/index.mdx b/docs/cli/index.mdxindex 33974547..6c5f8c50 100644--- a/docs/cli/index.mdx+++ b/docs/cli/index.mdx@@ -33,18 +33,19 @@ Top-level Agent Beacon CLI commands.| Command | Description ||---------|-------------|-| [`beacon version`](/cli/version) | Display the installed Agent Beacon CLI version. |-| [`beacon login`](/cli/login) | Log in to the Asymptote dashboard from the Beacon CLI. |-| [`beacon scan`](/cli/scan) | Run threat-detection rules over local endpoint telemetry. |-| [`beacon rules`](/cli/rules) | Manage and author Beacon threat-detection rules. || [`beacon ci`](/cli/ci) | Run ephemeral AI runtime telemetry collection in CI. || [`beacon cloud`](/cli/cloud) | Configure provider-managed cloud agent telemetry setup helpers. |-| [`beacon mcp`](/cli/mcp) | Expose local Beacon activity to MCP clients. |-| [`beacon ingest`](/cli/ingest) | Upload Beacon telemetry to configured ingest destinations. |-| [`beacon endpoint`](/cli/endpoint) | Manage local endpoint telemetry, runtime logs, and integrations. |-| [`beacon status`](/cli/endpoint-status) | Alias for `beacon endpoint status`. || [`beacon doctor`](/cli/endpoint-doctor) | Alias for `beacon endpoint doctor`. |+| [`beacon endpoint`](/cli/endpoint) | Manage local endpoint telemetry, runtime logs, and integrations. |+| [`beacon ingest`](/cli/ingest) | Upload Beacon telemetry to configured ingest destinations. || [`beacon inventory`](/cli/endpoint-inventory) | Alias for `beacon endpoint inventory`. |+| [`beacon login`](/cli/login) | Log in to the Asymptote dashboard from the Beacon CLI. |+| [`beacon mcp`](/cli/mcp) | Expose local Beacon activity to MCP clients. |+| [`beacon rules`](/cli/rules) | Manage and author Beacon threat-detection rules. |+| [`beacon scan`](/cli/scan) | Run threat-detection rules over local endpoint telemetry. |+| [`beacon status`](/cli/endpoint-status) | Alias for `beacon endpoint status`. |+| [`beacon token-usage`](/cli/token-usage) | Report token usage and attribution from the endpoint runtime log. |+| [`beacon version`](/cli/version) | Display the installed Agent Beacon CLI version. |## beacon version@@ -167,7 +168,6 @@ Manage the local endpoint agent and inspect supported agent harness telemetry.| [`beacon endpoint repair`](/cli/endpoint-repair) | Repair Beacon endpoint service files, telemetry configuration, and optional collector forwarding destinations. || [`beacon endpoint uninstall`](/cli/endpoint-uninstall) | Remove Beacon endpoint service files, with an option to keep local logs. || [`beacon endpoint config`](/cli/endpoint-config) | Inspect, validate, and update endpoint configuration. |-| [`beacon endpoint tokens`](/cli/endpoint-tokens) | Report token usage and attribution from the endpoint runtime log. || [`beacon endpoint dashboard`](/cli/dashboard#beacon-endpoint-dashboard) | Run the local dashboard over Beacon runtime logs for endpoint inspection. || [`beacon endpoint wazuh`](/cli/wazuh) | Configure Wazuh ingestion for Beacon endpoint events. || [`beacon endpoint elastic`](/cli/elastic) | Generate Elastic content and run a local Elasticsearch, Kibana, and Filebeat validation stack. |diff --git a/docs/cli/endpoint-tokens.mdx b/docs/cli/token-usage.mdxsimilarity index 90%rename from docs/cli/endpoint-tokens.mdxrename to docs/cli/token-usage.mdxindex 9a9a8642..380e702a 100644--- a/docs/cli/endpoint-tokens.mdx+++ b/docs/cli/token-usage.mdx@@ -1,14 +1,14 @@----title: "beacon endpoint tokens"+title: "beacon token-usage"description: "Report token usage and attribution from the Beacon endpoint runtime log"---## Command Overview-`beacon endpoint tokens` reads Beacon endpoint events from the runtime JSONL log and summarizes token usage, cost, models, sessions, runs, harnesses, and repositories.+`beacon token-usage` reads Beacon endpoint events from the runtime JSONL log and summarizes token usage, cost, models, sessions, runs, harnesses, and repositories.```bash title="Command syntax"-beacon endpoint tokens [flags]+beacon token-usage [flags]```Use this command when you need a local report before opening the dashboard, sending diagnostics, or validating token attribution for a specific agent session.@@ -38,31 +38,31 @@ A few rules shape how the numbers read:Show token usage from the default per-user endpoint log:```bash title="Show local token usage"-beacon endpoint tokens+beacon token-usage```Print a machine-readable report:```bash title="Print JSON"-beacon endpoint tokens --json+beacon token-usage --json```Filter to one session and include per-step detail:```bash title="Filter by session"-beacon endpoint tokens --session claude-session-123+beacon token-usage --session claude-session-123```Group usage into hourly time buckets:```bash title="Bucket usage over time"-beacon endpoint tokens --bucket 1h+beacon token-usage --bucket 1h```Inspect a CI runtime log and filter to a run:```bash title="Inspect a CI run"-beacon endpoint tokens --log-path ./beacon-runtime.jsonl --run-id github/123456 --json+beacon token-usage --log-path ./beacon-runtime.jsonl --run-id github/123456 --json```## Filtersdiff --git a/docs/docs.json b/docs/docs.jsonindex eb8b071f..8c336fe6 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -270,6 +270,7 @@"cli/version","cli/login","cli/scan",+ "cli/token-usage",{"group": "beacon rules","root": "cli/rules",@@ -333,7 +334,6 @@"cli/endpoint-repair","cli/endpoint-uninstall","cli/endpoint-config",- "cli/endpoint-tokens","cli/dashboard","cli/wazuh","cli/elastic",diff --git a/docs/runtimes/codex-cli.mdx b/docs/runtimes/codex-cli.mdxindex 50b81e7d..083a1110 100644--- a/docs/runtimes/codex-cli.mdx+++ b/docs/runtimes/codex-cli.mdx@@ -31,7 +31,7 @@ Two attribution limits are specific to Codex and follow from what Codex emits, n- **No cost.** Codex does not emit a cost signal, so `gen_ai.usage.cost_usd` is empty for Codex turns. Beacon never derives cost from local pricing tables.- **No per-session attribution.** Codex's usage metric carries no conversation id, so Codex turns do not roll up by session. Model, harness, repository, and run attribution work normally.-See [How token attribution works](/cli/endpoint-tokens#how-token-attribution-works) for the cross-runtime model.+See [How token attribution works](/cli/token-usage#how-token-attribution-works) for the cross-runtime model.## CI supportdiff --git a/docs/telemetry-schema/normalization.mdx b/docs/telemetry-schema/normalization.mdxindex 479cf7e5..ea2fb82b 100644--- a/docs/telemetry-schema/normalization.mdx+++ b/docs/telemetry-schema/normalization.mdx@@ -82,7 +82,7 @@ Beacon preserves OpenTelemetry GenAI semantic convention fields under the nested| `gen_ai.usage.reasoning.output_tokens` | `gen_ai.usage.reasoning.output_tokens` || `gen_ai.usage.cost`, runtime `*.cost.usage` metric datapoints | `gen_ai.usage.cost_usd` |-Usage also arrives as metric datapoints, not just span and log attributes. Claude Code's `claude_code.token.usage` and `claude_code.cost.usage` and Codex's `codex.turn.token_usage` are expanded per datapoint and mapped into the same `gen_ai.usage` fields by their `token_type` (for example Codex `cached_input` maps to `cache_read.input_tokens` and `reasoning_output` to `reasoning.output_tokens`; rollup types such as `total` are ignored). `gen_ai.usage.cost_usd` carries runtime-reported cost only and is never derived from a local pricing table. See [How token attribution works](/cli/endpoint-tokens#how-token-attribution-works) for how these normalized fields aggregate into local reports.+Usage also arrives as metric datapoints, not just span and log attributes. Claude Code's `claude_code.token.usage` and `claude_code.cost.usage` and Codex's `codex.turn.token_usage` are expanded per datapoint and mapped into the same `gen_ai.usage` fields by their `token_type` (for example Codex `cached_input` maps to `cache_read.input_tokens` and `reasoning_output` to `reasoning.output_tokens`; rollup types such as `total` are ignored). `gen_ai.usage.cost_usd` carries runtime-reported cost only and is never derived from a local pricing table. See [How token attribution works](/cli/token-usage#how-token-attribution-works) for how these normalized fields aggregate into local reports.## Prompt and content handlingdiff --git a/packages/asymptote-sdk-js/README.md b/packages/asymptote-sdk-js/README.mdindex ed91b2eb..85e288c3 100644--- a/packages/asymptote-sdk-js/README.md+++ b/packages/asymptote-sdk-js/README.md@@ -136,7 +136,7 @@ Call `Observe.flush()` before short-lived scripts exit, orThe OpenLLMetry instrumentations record `gen_ai.usage.*` token counts on everysupported model call, and the Beacon collector normalizes them into endpoint-JSONL for the token usage dashboard and `beacon endpoint tokens` reports. Two+JSONL for the token usage dashboard and `beacon token-usage` reports. Twonotes:- Streaming responses report usage only after the stream is fully consumed;