Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(lenses): built-in Token Usage lens, and counted usage in lens data

Claude780c55ea0dc8
diff --git a/cli/beacon/internal/endpoint/dashboard/lens_data.go b/cli/beacon/internal/endpoint/dashboard/lens_data.go
index 4b8d3833..aab25771 100644
--- a/cli/beacon/internal/endpoint/dashboard/lens_data.go
+++ b/cli/beacon/internal/endpoint/dashboard/lens_data.go
@@ -111,9 +111,44 @@ func lensDataFromShow(show TraceShowResultV1, raw []schema.Event, opts LensDataO
data.Findings = findings
}
data.TokenCoverage = lensTokenCoverage(raw, show.Trace.Harness.Name)
+ data.TokenUsage = lensTokenUsage(raw)
return data
}
+// lensTokenUsage counts the trace's usage with the same aggregation `beacon token-usage` and the
+// dashboard's token view use, so a lens's total matches theirs. Summing each event's own usage
+// would not: a runtime that reports one turn on two channels, or as a cumulative counter, would
+// be counted twice. raw is in log append order, which the cumulative handling relies on.
+func lensTokenUsage(raw []schema.Event) *asymptoteobserve.LensTokenUsageV1 {
+ if len(raw) == 0 {
+ return nil
+ }
+ report := tokens.Aggregate(raw, tokens.Options{})
+ out := &asymptoteobserve.LensTokenUsageV1{
+ Totals: lensUsage(report.Totals),
+ EventsWithUsage: report.EventsWithUsage,
+ }
+ for _, group := range report.ByModel {
+ out.ByModel = append(out.ByModel, asymptoteobserve.LensTokenModelV1{
+ Model: group.Key,
+ Usage: lensUsage(group.Usage),
+ Events: group.Usage.Events,
+ })
+ }
+ return out
+}
+
+func lensUsage(u tokens.Usage) TraceUsageV1 {
+ return TraceUsageV1{
+ InputTokens: u.InputTokens,
+ OutputTokens: u.OutputTokens,
+ CacheReadInputTokens: u.CacheReadInputTokens,
+ CacheCreationInputTokens: u.CacheCreationInputTokens,
+ ReasoningOutputTokens: u.ReasoningOutputTokens,
+ CostUSD: u.CostUSD,
+ }
+}
+
// fitLensEvents keeps the longest prefix of the bundle's events that encodes within budget, and
// reports whether it dropped any. Spans that only cover dropped events are kept: they are small,
// and a lens resolves span event IDs leniently because truncation already allows a miss.
diff --git a/cli/beacon/internal/endpoint/dashboard/lens_data_test.go b/cli/beacon/internal/endpoint/dashboard/lens_data_test.go
index 27d7165f..afedceed 100644
--- a/cli/beacon/internal/endpoint/dashboard/lens_data_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/lens_data_test.go
@@ -12,6 +12,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -343,3 +344,34 @@ func TestLensDataEndpointBySession(t *testing.T) {
t.Fatalf("unknown session status = %d, want 404", rec.Code)
}
}
+
+// The lens total is the token report's count, computed by the same aggregation, so a lens and
+// `beacon token-usage` cannot disagree about one trace.
+func TestLensTokenUsageMatchesTheTokenReport(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ withoutHistory(t)
+ turn := func(id string, input, output int64, cost float64, model string) schema.Event {
+ e := testSchemaEvent("2026-06-11T10:00:00Z", "claude_code", "agent.message", "agent", "repo-a")
+ e.Event.ID = id
+ e.Session = &schema.SessionInfo{ID: "u1"}
+ e.Model = model
+ e.GenAI = &schema.GenAIInfo{Usage: &schema.GenAIUsageInfo{InputTokens: int64Ptr(input), OutputTokens: int64Ptr(output), CostUSD: &cost}}
+ return e
+ }
+ events := []schema.Event{turn("a", 100, 10, 0.01, "model-a"), turn("b", 300, 30, 0.03, "model-b")}
+ path := newTestLog(t, marshalEvents(t, events...))
+
+ data, ok, err := BuildSessionLensData(path, "u1", LensDataOptions{UserMode: true})
+ if err != nil || !ok {
+ t.Fatalf("BuildSessionLensData = ok %v, err %v", ok, err)
+ }
+ want := tokens.Aggregate(events, tokens.Options{})
+ got := data.TokenUsage
+ if got == nil || got.Totals.InputTokens != want.Totals.InputTokens || got.Totals.OutputTokens != want.Totals.OutputTokens ||
+ got.EventsWithUsage != want.EventsWithUsage || len(got.ByModel) != len(want.ByModel) {
+ t.Fatalf("token usage = %#v, want the token report's %#v", got, want.Totals)
+ }
+ if got.Totals.InputTokens != 400 || got.ByModel[0].Model != "model-b" || got.ByModel[0].Events != 1 {
+ t.Fatalf("token usage = %#v", got)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/token-usage.lens.html b/cli/beacon/internal/endpoint/dashboard/lenses/token-usage.lens.html
new file mode 100644
index 00000000..c882e6da
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/lenses/token-usage.lens.html
@@ -0,0 +1,212 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Token Usage</title>
+<script type="application/beacon-lens+json">
+{
+ "id": "token-usage",
+ "title": "Token Usage",
+ "description": "An itemized bill: counted usage by turn and by model, every event that reported usage, and whether this runtime reports usage at all.",
+ "icon": "coins",
+ "version": 1,
+ "api": "beacon.lens.v1",
+ "author": "Beacon"
+}
+</script>
+<style>
+ body {
+ margin: 0;
+ color: var(--beacon-text, #111827);
+ font: 400 13px/1.5 var(--beacon-font-sans, ui-sans-serif, system-ui, sans-serif);
+ }
+ .muted { color: var(--beacon-muted, #6b7280); }
+ .warn { color: var(--beacon-warn, #92400e); }
+ h2 { margin: 18px 0 6px; font-size: 13px; font-weight: 400; color: var(--beacon-muted, #6b7280); }
+ h2:first-of-type { margin-top: 0; }
+ p { margin: 0 0 8px; }
+ table { width: 100%; border-collapse: collapse; }
+ th, td { padding: 4px 8px; border-bottom: 1px solid var(--beacon-line, rgba(0,0,0,0.1)); font-weight: 400; text-align: left; vertical-align: top; }
+ th { color: var(--beacon-muted, #6b7280); white-space: nowrap; }
+ .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
+ tfoot td { border-bottom: 0; }
+ .mono { font: 13px var(--beacon-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace); }
+ .clip { max-width: 28rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+</style>
+</head>
+<body>
+<p id="status" class="muted">Loading trace…</p>
+<main id="root" hidden></main>
+<script>
+(function () {
+ "use strict";
+ var root = document.getElementById("root");
+ var number = new Intl.NumberFormat();
+ var money = new Intl.NumberFormat(undefined, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 4 });
+ var FIELDS = [
+ { key: "input_tokens", label: "Input" },
+ { key: "output_tokens", label: "Output" },
+ { key: "cache_read_input_tokens", label: "Cache read" },
+ { key: "cache_creation_input_tokens", label: "Cache write" },
+ { key: "reasoning_output_tokens", label: "Reasoning" }
+ ];
+
+ // Every node is built with textContent: prompts and titles are untrusted trace content.
+ function el(tag, text, className) {
+ var node = document.createElement(tag);
+ if (text !== undefined && text !== null) node.textContent = String(text);
+ if (className) node.className = className;
+ return node;
+ }
+ function n(u, key) { return (u && Number(u[key])) || 0; }
+ function add(into, u) {
+ FIELDS.forEach(function (f) { into[f.key] = n(into, f.key) + n(u, f.key); });
+ into.cost_usd = n(into, "cost_usd") + n(u, "cost_usd");
+ return into;
+ }
+ function tokensOf(u) { return n(u, "input_tokens") + n(u, "output_tokens") + n(u, "cache_read_input_tokens") + n(u, "cache_creation_input_tokens"); }
+
+ // Columns are the usage fields any row in this table reports, plus cost when any row has one.
+ function columnsFor(rows) {
+ var cols = FIELDS.filter(function (f) { return rows.some(function (r) { return n(r.usage, f.key); }); });
+ if (rows.some(function (r) { return n(r.usage, "cost_usd"); })) cols.push({ key: "cost_usd", label: "Cost", money: true });
+ return cols;
+ }
+ function cell(u, col) {
+ var v = n(u, col.key);
+ return el("td", v ? (col.money ? money.format(v) : number.format(v)) : "—", "num");
+ }
+
+ // rows: [{ cells: [Node...], usage: {...} }], lead: header labels for the leading cells.
+ function usageTable(lead, rows, footer) {
+ var cols = columnsFor(rows.concat(footer ? [footer] : []));
+ var t = el("table");
+ var head = t.appendChild(el("thead")).appendChild(el("tr"));
+ lead.forEach(function (h) { head.appendChild(el("th", h.label || h, h.num ? "num" : "")); });
+ cols.forEach(function (c) { head.appendChild(el("th", c.label, "num")); });
+ var body = t.appendChild(el("tbody"));
+ rows.forEach(function (r) {
+ var tr = body.appendChild(el("tr"));
+ r.cells.forEach(function (c) { tr.appendChild(c); });
+ cols.forEach(function (c) { tr.appendChild(cell(r.usage, c)); });
+ });
+ if (footer) {
+ var tr = t.appendChild(el("tfoot")).appendChild(el("tr"));
+ footer.cells.forEach(function (c) { tr.appendChild(c); });
+ cols.forEach(function (c) { tr.appendChild(cell(footer.usage, c)); });
+ }
+ return t;
+ }
+
+ function coverageNote(cov, harness) {
+ if (!cov) return null;
+ var name = cov.harness || harness || "This runtime";
+ if (cov.status === "silent") {
+ return el("p", name + " is a runtime Beacon reads usage from, but this trace reported none. Its hooks or telemetry export may not be delivering usage (" + (cov.reason || cov.expectation) + ").", "warn");
+ }
+ if (cov.status === "not_instrumented" || cov.expectation === "none") {
+ return el("p", name + " does not expose token usage to Beacon, so no usage here is expected rather than a gap.", "muted");
+ }
+ if (cov.expectation === "generic_otlp") {
+ return el("p", name + " reports usage only if it emits OpenTelemetry GenAI usage; totals may be partial.", "muted");
+ }
+ return null;
+ }
+
+ function render(data) {
+ var trace = data.trace || {};
+ var events = Array.isArray(trace.events) ? trace.events : [];
+ var summary = trace.summary || {};
+ var counted = data.token_usage;
+
+ var note = coverageNote(data.token_coverage, summary.harness && summary.harness.name);
+ if (note) root.appendChild(note);
+
+ // Line items: every event that reported usage, attributed to the prompt before it.
+ var items = [];
+ var turns = [];
+ var turn = null;
+ events.forEach(function (e) {
+ if (!e) return;
+ if (e.type === "user_message") {
+ var text = (e.content && e.content.included && e.content.text) || e.title || "Prompt";
+ turn = { prompt: String(text).split("\n")[0], number: e.number, usage: {}, events: 0 };
+ turns.push(turn);
+ return;
+ }
+ if (!e.usage) return;
+ items.push(e);
+ if (!turn) {
+ turn = { prompt: "Before the first prompt", number: null, usage: {}, events: 0 };
+ turns.push(turn);
+ }
+ add(turn.usage, e.usage);
+ turn.events += 1;
+ });
+ var reported = items.reduce(function (sum, e) { return add(sum, e.usage); }, {});
+
+ if (!counted || !counted.events_with_usage) {
+ if (!note) root.appendChild(el("p", "No token usage was reported in this trace.", "muted"));
+ finish();
+ return;
+ }
+
+ root.appendChild(el("h2", "Counted usage"));
+ root.appendChild(el("p", number.format(tokensOf(counted.totals)) + " tokens over " + number.format(counted.events_with_usage) +
+ (counted.events_with_usage === 1 ? " usage report" : " usage reports") +
+ (n(counted.totals, "cost_usd") ? " · " + money.format(n(counted.totals, "cost_usd")) + " reported by the runtime" : "") + "."));
+ root.appendChild(usageTable([""], [{ cells: [el("td", "Total")], usage: counted.totals }]));
+ if (tokensOf(reported) !== tokensOf(counted.totals)) {
+ root.appendChild(el("p", "The events below report " + number.format(tokensOf(reported)) + " tokens in total. Beacon counts " +
+ number.format(tokensOf(counted.totals)) + ", after removing usage a runtime reported on more than one channel and turning cumulative counters into deltas.", "muted"));
+ }
+
+ var models = Array.isArray(counted.by_model) ? counted.by_model : [];
+ if (models.length) {
+ root.appendChild(el("h2", "By model"));
+ root.appendChild(usageTable(["Model", { label: "Reports", num: true }], models.map(function (m) {
+ return { cells: [el("td", m.model || "unknown", "mono"), el("td", number.format(m.events || 0), "num")], usage: m.usage };
+ })));
+ }
+
+ var billed = turns.filter(function (t) { return t.events; });
+ if (billed.length) {
+ root.appendChild(el("h2", "By turn"));
+ root.appendChild(usageTable([{ label: "#", num: true }, "Prompt", { label: "Reports", num: true }], billed.map(function (t) {
+ return {
+ cells: [el("td", t.number ? "#" + t.number : "—", "num"), el("td", t.prompt, "clip"), el("td", number.format(t.events), "num")],
+ usage: t.usage
+ };
+ })));
+ }
+
+ root.appendChild(el("h2", "Line items"));
+ root.appendChild(usageTable([{ label: "#", num: true }, { label: "Time", num: true }, "Event", "Model"], items.map(function (e) {
+ var when = e.timestamp ? new Date(e.timestamp) : null;
+ return {
+ cells: [
+ el("td", "#" + e.number, "num"),
+ el("td", when && !isNaN(when) ? when.toLocaleTimeString() : "—", "num"),
+ el("td", e.title || e.action || e.type, "clip"),
+ el("td", e.model || "—", "mono")
+ ],
+ usage: e.usage
+ };
+ }), { cells: [el("td"), el("td"), el("td", "Reported by events"), el("td")], usage: reported }));
+ if (data.truncated) root.appendChild(el("p", "This trace was truncated; later line items are missing.", "muted"));
+ if (n(counted.totals, "cost_usd")) root.appendChild(el("p", "Costs are what the runtime reported. Beacon never estimates cost.", "muted"));
+ finish();
+ }
+
+ function finish() {
+ document.getElementById("status").hidden = true;
+ root.hidden = false;
+ }
+
+ window.beacon.getTrace().then(render, function (err) {
+ document.getElementById("status").textContent = "Could not load this trace: " + ((err && err.message) || err);
+ });
+})();
+</script>
+</body>
+</html>
diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonl b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonl
index fe71aade..b46fa9db 100644
--- a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonl
+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/fixtures/runtime.jsonl
@@ -11,3 +11,5 @@
{"vendor": "beacon", "product": "endpoint-agent", "schema_version": "1.0", "severity": "info", "endpoint": {"os": "linux"}, "harness": {"name": "claude_code"}, "session": {"id": "rich", "working_directory": "/work/service"}, "timestamp": "2026-06-12T09:01:00Z", "event": {"id": "rich-denied", "kind": "agent_runtime", "action": "approval.decided", "category": "approval"}, "message": "approval.decided", "approval": {"required": true, "decision": "deny", "reason": "user denied rm"}}
{"vendor": "beacon", "product": "endpoint-agent", "schema_version": "1.0", "severity": "info", "endpoint": {"os": "linux"}, "harness": {"name": "claude_code"}, "session": {"id": "rich", "working_directory": "/work/service"}, "timestamp": "2026-06-12T09:01:10Z", "event": {"id": "rich-answer", "kind": "agent_runtime", "action": "agent.message", "category": "agent"}, "message": "agent.message", "gen_ai": {"usage": {"input_tokens": 5200, "output_tokens": 800, "cost_usd": 0.031}}, "model": "claude-sonnet-5-5"}
{"timestamp": "2026-06-15T10:00:00Z", "vendor": "beacon", "product": "endpoint-agent", "schema_version": "1.0", "severity": "info", "endpoint": {"os": "linux"}, "harness": {"name": "claude_code"}, "session": {"id": "sqlish", "working_directory": "/w"}, "event": {"id": "sqlish-edit", "kind": "agent_runtime", "action": "file.modified", "category": "file"}, "message": "file.modified", "file": {"path": "/w/q.sql", "operation": "modify", "diff": "diff --git a/q.sql b/q.sql\n--- a/q.sql\n+++ b/q.sql\n@@ -1,3 +1,3 @@\n--- removed sql comment\n+++i;\n select 1;\n", "diff_hash": "sha256:sql", "diff_bytes": 108}, "content": {"retention": "full", "included": true}}
+{"vendor": "beacon", "product": "endpoint-agent", "schema_version": "1.0", "severity": "info", "endpoint": {"os": "linux"}, "harness": {"name": "claude_code"}, "session": {"id": "rich", "working_directory": "/work/service"}, "timestamp": "2026-06-12T09:01:20Z", "event": {"id": "rich-prompt-2", "kind": "agent_runtime", "action": "prompt.submitted", "category": "prompt"}, "message": "prompt.submitted", "prompt": {"text": "Now document the change"}, "content": {"retention": "full", "included": true}}
+{"vendor": "beacon", "product": "endpoint-agent", "schema_version": "1.0", "severity": "info", "endpoint": {"os": "linux"}, "harness": {"name": "claude_code"}, "session": {"id": "rich", "working_directory": "/work/service"}, "timestamp": "2026-06-12T09:01:30Z", "event": {"id": "rich-answer-2", "kind": "agent_runtime", "action": "agent.message", "category": "agent"}, "message": "agent.message", "model": "claude-haiku-4-5", "gen_ai": {"usage": {"input_tokens": 1200, "output_tokens": 300, "cache_read": {"input_tokens": 4000}, "cache_creation": {"input_tokens": 800}, "cost_usd": 0.004}}}
diff --git a/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/builtin-token-usage.spec.ts b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/builtin-token-usage.spec.ts
new file mode 100644
index 00000000..3d47f73d
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/testdata/lens-e2e/tests/builtin-token-usage.spec.ts
@@ -0,0 +1,36 @@
+import { expect, test } from '@playwright/test';
+
+test('token usage: counted totals, by model, by turn and line items', async ({ page }) => {
+ await page.goto('/session.html?id=rich&lens=token-usage');
+ const frame = page.frameLocator('iframe.lens-frame');
+ await expect(frame.locator('#root')).toBeVisible();
+
+ // 5,200 + 800 on the first turn; 1,200 + 300 + 4,000 cache read + 800 cache write on the second.
+ await expect(frame.locator('#root')).toContainText('12,300 tokens over 2 usage reports · $0.035 reported by the runtime.');
+ // The events agree with Beacon's count, so there is nothing to reconcile.
+ await expect(frame.locator('#root')).not.toContainText('Beacon counts');
+
+ const tables = frame.locator('table');
+ const byModel = tables.nth(1);
+ await expect(byModel.locator('tbody tr')).toHaveCount(2);
+ await expect(byModel).toContainText('claude-sonnet-5-5');
+ await expect(byModel).toContainText('claude-haiku-4-5');
+
+ const byTurn = tables.nth(2);
+ await expect(byTurn.locator('tbody tr')).toHaveCount(2);
+ await expect(byTurn.locator('tbody tr').nth(0)).toContainText('Make the retry backoff deterministic');
+ await expect(byTurn.locator('tbody tr').nth(1)).toContainText('Now document the change');
+ await expect(byTurn.locator('tbody tr').nth(1)).toContainText('4,000'); // cache read column shown
+
+ const items = tables.nth(3);
+ await expect(items.locator('tbody tr')).toHaveCount(2);
+ await expect(items.locator('tfoot')).toContainText('Reported by events');
+ await expect(frame.locator('#root')).toContainText('Beacon never estimates cost.');
+});
+
+test('token usage: a runtime that should report usage but did not is flagged', async ({ page }) => {
+ await page.goto('/session.html?id=s1&lens=token-usage');
+ const frame = page.frameLocator('iframe.lens-frame');
+ await expect(frame.locator('#root')).toContainText('is a runtime Beacon reads usage from, but this trace reported none');
+ await expect(frame.locator('table')).toHaveCount(0);
+});
diff --git a/pkg/asymptoteobserve/lens.go b/pkg/asymptoteobserve/lens.go
index a594950b..b5e66cc9 100644
--- a/pkg/asymptoteobserve/lens.go
+++ b/pkg/asymptoteobserve/lens.go
@@ -58,6 +58,11 @@ type LensDataV1 struct {
// TokenCoverage says whether this trace's runtime can report token usage at all, so a lens can
// distinguish "used no tokens" from "this runtime never reports them". Nil when unknown.
TokenCoverage *LensTokenCoverageV1 `json:"token_coverage,omitempty"`
+ // TokenUsage is the trace's usage as `beacon token-usage` counts it: duplicate channels
+ // removed and cumulative counters turned into deltas. Per-event usage in Trace is what each
+ // event reported, so the two can differ; a lens that shows both should say why. Nil when
+ // unknown.
+ TokenUsage *LensTokenUsageV1 `json:"token_usage,omitempty"`
// Truncated is true when Trace holds fewer events than the trace has, because the bundle hit
// the size cap. Trace.Range then carries the counts.
Truncated bool `json:"truncated"`
@@ -92,6 +97,22 @@ type LensTokenCoverageV1 struct {
Reason string `json:"reason,omitempty"`
}
+// LensTokenUsageV1 is a trace's counted token usage.
+type LensTokenUsageV1 struct {
+ Totals TraceUsageV1 `json:"totals"`
+ // EventsWithUsage counts the events that contributed to Totals.
+ EventsWithUsage int `json:"events_with_usage"`
+ // ByModel splits Totals by model, largest first.
+ ByModel []LensTokenModelV1 `json:"by_model,omitempty"`
+}
+
+// LensTokenModelV1 is one model's share of a trace's counted usage.
+type LensTokenModelV1 struct {
+ Model string `json:"model"`
+ Usage TraceUsageV1 `json:"usage"`
+ Events int `json:"events"`
+}
+
var (
lensIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
lensIconPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
diff --git a/spec/lenses/SPEC.md b/spec/lenses/SPEC.md
index 3e0bb3f9..42f7357d 100644
--- a/spec/lenses/SPEC.md
+++ b/spec/lenses/SPEC.md
@@ -89,6 +89,11 @@ const data = await window.beacon.getTrace();
"expectation": "reported", // reported | generic_otlp | none
"reason": "OTLP token and cost telemetry"
},
+ "token_usage": { // absent: unknown
+ "totals": { "input_tokens": 18234, "output_tokens": 1650, "cost_usd": 0.0912 },
+ "events_with_usage": 1,
+ "by_model": [{ "model": "claude-sonnet-5-5", "usage": { /* same shape */ }, "events": 1 }]
+ },
"truncated": false
}
```
@@ -118,10 +123,17 @@ trace view uses. Its main parts:
`findings.items[]` are the active threat rules' matches over this trace's
own events: `rule_id`, `title`, `severity` (`info` … `critical`), `posture`,
`reason`, `taxonomy`, and `event_ids`. The evidence is referenced by
-`trace.events[].id`, not copied. Findings and `token_coverage` are computed
-from the live runtime log. For a trace whose lines have been rotated out of
-that log (and are kept only in the opt-in trace history), they may be
-missing or partial while `trace` is still complete.
+`trace.events[].id`, not copied. Findings, `token_coverage` and
+`token_usage` are computed from the live runtime log. For a trace whose lines
+have been rotated out of that log (and are kept only in the opt-in trace
+history), they may be missing or partial while `trace` is still complete.
+
+`token_usage` is the trace's usage as `beacon token-usage` counts it, with
+duplicate channels removed and cumulative counters turned into deltas. Each
+event's own `usage` is what that event reported, so summing those can count
+the same tokens twice; use `token_usage.totals` for the total, and say so if
+you show both. `cost_usd` is only ever what the runtime reported; Beacon never
+estimates cost.
`truncated` is true when the bundle holds fewer events than the trace has,
because it hit the size cap. A finding's evidence ID may then point at an
@@ -234,3 +246,4 @@ The host enforces these rules; a lens does not opt into them.
### Changelog
- `lenses/v1`: initial specification.
+- `lenses/v1` (additive): `token_usage`, the counted usage of the trace.
diff --git a/spec/lenses/examples/lens-data.json b/spec/lenses/examples/lens-data.json
index c0774f69..6275c8df 100644
--- a/spec/lenses/examples/lens-data.json
+++ b/spec/lenses/examples/lens-data.json
@@ -216,5 +216,26 @@
"expectation": "reported",
"reason": "OTLP token and cost telemetry"
},
+ "token_usage": {
+ "totals": {
+ "input_tokens": 18234,
+ "output_tokens": 1650,
+ "cache_read_input_tokens": 120400,
+ "cost_usd": 0.0912
+ },
+ "events_with_usage": 1,
+ "by_model": [
+ {
+ "model": "claude-sonnet-5-5",
+ "usage": {
+ "input_tokens": 18234,
+ "output_tokens": 1650,
+ "cache_read_input_tokens": 120400,
+ "cost_usd": 0.0912
+ },
+ "events": 1
+ }
+ ]
+ },
"truncated": false
}