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
Merge one-hour cache-write capture (#739) into token-cost-estimates
Claude9a5be9b2ee33
diff --cc CLAUDE.mdindex 6b796bd9,d7c2ac32..96229e06--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -537,10 -536,10 +537,10 @@@ unpacked through Chrome's developer mod- For macOS-only behavior, gate tests with `runtime.GOOS == "darwin"` or assert the non-Darwin contract explicitly.- Keep endpoint event schema fields stable: `vendor`, `product`, `schema_version`, required event fields, and Wazuh-compatible JSONL output are release contracts.- Preserve optional event fields for agent-native metadata (`session`, `trace`, `tool`, `file`, `command`, `mcp`, `approval`, `content`, `model`, `repository`, and `branch`) without changing existing required field semantics.-- Reading a runtime's own on-disk session store is a `poll` collection path, not a new method: it is a pull that sees committed records after the fact, which is what `poll` means. fx is the case that exercises it (`cli/beacon/internal/fxsession`); a future runtime with the same shape uses `poll` too rather than adding a fifth value to a release-contract field.+- Reading a runtime's own on-disk session store is a `poll` collection path, not a new method: it is a pull that sees committed records after the fact, which is what `poll` means. fx is the case that exercises it (`cli/beacon/internal/fxsession`); a future runtime with the same shape uses `poll` too rather than adding a fifth value to a release-contract field. The token aggregator relies on that marker: when one session (endpoint, normalized harness, session id) has usage from both a live method and `poll`, `preferLiveOverPoll` in `cli/beacon/internal/tokens/tokens.go` keeps live usage authoritative from the first event of that live channel in the session and drops the backfill's copies from then on, so a poll mapper must keep the runtime's own session id and real record timestamps rather than deduplicating against the live log itself.- Set the provenance markers on every new collection path. `harness.collection_method` (`hook`, `otlp`, `plugin`, `poll`) records the mechanism; `event.fidelity` (`observed`, `inferred`) records whether the source named the action or Beacon derived it. Both are defined in `pkg/asymptoteobserve/provenance.go` and are the only sanctioned way to express that difference — do not add per-runtime confidence fields, and do not leave a derived action unmarked. A new plugin-shaped runtime must be added to `CollectionMethodForPlatform`, whose default is `hook`. An action synthesized from an adjacent observation, such as an approval built from a pre-tool notification on a runtime with no approval hook, is `inferred`.- Keep event identity derivable rather than asserted. `gen_ai.tool.call.id` carries the runtime's own name for one tool invocation, promoted on every capture path from the shared alias list in `pkg/asymptoteobserve.ToolCallIDKeys`; a new runtime adds its spelling there rather than in a mapper. `event.id` is a deterministic UUID derived by `EventIDForLine` from the event about to be written, so both capture paths name one action the same way. Its namespace constant and derivation are a contract: changing either renames every event ID Beacon has written, and a test pins the value.- - Keep `gen_ai.usage` as the single canonical token-usage representation: normalize all runtime token telemetry (span attributes, metric datapoints, legacy `llm.usage.*` aliases) into it, mirror OTel GenAI semconv JSON names exactly, and never add parallel or per-harness token fields. `gen_ai.usage.cost_usd` carries runtime-reported cost only and is never written from a price list; list-price estimates are computed only at report time from the embedded catalog (`cli/beacon/internal/pricing`), are always labeled as estimates, and are never stored in events.+ - Keep `gen_ai.usage` as the single canonical token-usage representation: normalize all runtime token telemetry (span attributes, metric datapoints, legacy `llm.usage.*` aliases) into it, mirror OTel GenAI semconv JSON names exactly, and never add parallel or per-harness token fields. `gen_ai.usage.cache_creation.ephemeral_1h_input_tokens` (optional, Anthropic's own name) is the subset of `cache_creation.input_tokens` written with a one-hour TTL: a breakdown like `reasoning` inside output, never added to a total, built with `asymptoteobserve.NewCacheCreationUsage` (clamps it to the write count) and differenced with `GenAIUsageCacheCreationInfo.Minus`. It is set by Claude Code session files, Pi-family `cacheWrite1h` and the browser extension's Claude adapter; Claude Code's OTLP export has no split, and reports price unsplit writes at the five-minute rate. `gen_ai.usage.cost_usd` carries runtime-reported cost only and is never written from a price list; list-price estimates are computed only at report time from the embedded catalog (`cli/beacon/internal/pricing`), are always labeled as estimates, and are never stored in events.- `cli/beacon/internal/pricing` estimates list-price cost for reports: integer-microdollar math over the gen_ai.usage counts (disjoint input/output/cache read/cache write, a one-hour write subset, reasoning inside output), long-context bands only for a single request, and a strict model-name ladder (exact, canonical via `NormalizeModelName`, dotted version, Bedrock route prefix, then stripping a `[1m]` marker, snapshot date or effort suffix) that leaves a model unpriced rather than guess, including when two entries tie with different prices. Its `catalog.json` is embedded, offline and report-time only (hooks never import it); it is generated from LiteLLM's MIT-licensed `model_prices_and_context_window.json` and records the upstream URL, commit and fetch/generation dates. Regenerate with `cd cli/beacon && go run ./internal/pricing/internal/gen` (resolves LiteLLM's main with `git ls-remote` and fetches that commit; `-src`/`-commit` for a local copy) and review the one-model-per-line diff; the generator never runs in builds or tests.- When adding a new signal, include stable identifiers/counts/hashes alongside any retained raw content, and route raw fields through redaction, sanitization, truncation, and event-size controls.- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.diff --cc browser-extension/src/shared/normalize.tsindex 4066a85f,ca30c99c..4ad8cc5b--- a/browser-extension/src/shared/normalize.ts+++ b/browser-extension/src/shared/normalize.ts@@@ -161,12 -149,22 +161,22 @@@ export function normalizeTurnif (turn.usage?.outputTokens != null)respAttrs.push(int('gen_ai.usage.output_tokens', turn.usage.outputTokens));// Cache counts use the dotted spelling the collector reads first- // (GenAIUsageFromAttrs), and are disjoint from input_tokens, so a total is- // input + output + cache_read + cache_creation with nothing double-counted.+ // (GenAIUsageFromAttrs). They are subsets of input_tokens above, and the+ // collector stores them disjoint from the uncached remainder.- if (turn.usage?.cacheCreationInputTokens != null)- respAttrs.push(- int('gen_ai.usage.cache_creation.input_tokens', turn.usage.cacheCreationInputTokens),- );+ if (turn.usage?.cacheCreationInputTokens != null) {+ const writes = turn.usage.cacheCreationInputTokens;+ respAttrs.push(int('gen_ai.usage.cache_creation.input_tokens', writes));+ // The one-hour subset is a breakdown of the writes, not a fourth count, and+ // can never exceed them.+ const oneHour = turn.usage.cacheCreation1hInputTokens;+ if (oneHour != null)+ respAttrs.push(+ int(+ 'gen_ai.usage.cache_creation.ephemeral_1h_input_tokens',+ Math.min(Math.max(oneHour, 0), Math.max(writes, 0)),+ ),+ );+ }if (turn.usage?.cacheReadInputTokens != null)respAttrs.push(int('gen_ai.usage.cache_read.input_tokens', turn.usage.cacheReadInputTokens));diff --cc browser-extension/test/unit/normalize.test.tsindex c34374c8,c571a36e..7641a7fd--- a/browser-extension/test/unit/normalize.test.ts+++ b/browser-extension/test/unit/normalize.test.ts@@@ -106,40 -106,27 +106,61 @@@ describe('normalizeTurn — full retentexpect(r['gen_ai.usage.cache_read.input_tokens']).toBe(18500);});+ it('emits the semconv input count, which includes cache reads and writes', () => {+ // Anthropic's usage.input_tokens excludes both cache counts, but the OTel+ // GenAI semconv input_tokens "SHOULD include all types of input tokens,+ // including cached tokens". The collector reduces every semconv input by+ // the cache counts beside it, so emitting Anthropic's disjoint count here+ // would have it subtract the cache a second time.+ const records = normalize(+ baseTurn({+ usage: { inputTokens: 37, outputTokens: 214, cacheCreationInputTokens: 1024, cacheReadInputTokens: 18500 },+ }),+ ).logRecords;+ const r = flat(byAction(records, 'agent.response.completed')!.attributes);+ expect(r['gen_ai.usage.input_tokens']).toBe(37 + 1024 + 18500);+ expect(r['gen_ai.usage.output_tokens']).toBe(214);+ });++ it('adds only the cache counts the stream reported to the input count', () => {+ const records = normalize(+ baseTurn({ usage: { inputTokens: 37, outputTokens: 5, cacheReadInputTokens: 900 } }),+ ).logRecords;+ const r = flat(byAction(records, 'agent.response.completed')!.attributes);+ expect(r['gen_ai.usage.input_tokens']).toBe(937);+ expect(r['gen_ai.usage.cache_creation.input_tokens']).toBeUndefined();+ });++ it('does not invent an input count from cache counts alone', () => {+ const records = normalize(+ baseTurn({ usage: { outputTokens: 5, cacheReadInputTokens: 900 } }),+ ).logRecords;+ const r = flat(byAction(records, 'agent.response.completed')!.attributes);+ expect(r['gen_ai.usage.input_tokens']).toBeUndefined();+ expect(r['gen_ai.usage.cache_read.input_tokens']).toBe(900);+ });++ it('emits the one-hour cache-write subset, clamped to the write count', () => {+ const emit = (cacheCreationInputTokens: number, cacheCreation1hInputTokens?: number) =>+ flat(+ byAction(+ normalize(+ baseTurn({+ usage: { inputTokens: 37, outputTokens: 214, cacheCreationInputTokens, cacheCreation1hInputTokens },+ }),+ ).logRecords,+ 'agent.response.completed',+ )!.attributes,+ );+ const r = emit(20000, 16000);+ expect(r['gen_ai.usage.cache_creation.input_tokens']).toBe(20000);+ expect(r['gen_ai.usage.cache_creation.ephemeral_1h_input_tokens']).toBe(16000);+ // A breakdown larger than its count is a malformed record, not extra writes.+ expect(emit(500, 900)['gen_ai.usage.cache_creation.ephemeral_1h_input_tokens']).toBe(500);+ // Unreported stays absent, never a guessed zero.+ expect(emit(500)['gen_ai.usage.cache_creation.ephemeral_1h_input_tokens']).toBeUndefined();+ });+it('omits cache attributes entirely when the stream reported none', () => {const r = flat(respRec.attributes);expect(r['gen_ai.usage.cache_creation.input_tokens']).toBeUndefined();diff --cc cli/beacon/internal/tokens/tokens.goindex 42200fc6,f510f812..da93d4b2--- a/cli/beacon/internal/tokens/tokens.go+++ b/cli/beacon/internal/tokens/tokens.go@@@ -885,48 -713,6 +892,50 @@@ func dedupeOverlappingChannels(events [return out}+// usageFieldSet records which usage fields a channel reported anywhere in a scope, so a second+// channel can give up exactly those fields and keep the ones only it reports.+type usageFieldSet struct {+ input, output, cacheRead, cacheCreation, reasoning, cost bool+}++func (fs *usageFieldSet) mark(u Usage) {+ fs.input = fs.input || u.InputTokens != 0+ fs.output = fs.output || u.OutputTokens != 0+ fs.cacheRead = fs.cacheRead || u.CacheReadInputTokens != 0+ fs.cacheCreation = fs.cacheCreation || u.CacheCreationInputTokens != 0+ fs.reasoning = fs.reasoning || u.ReasoningOutputTokens != 0+ fs.cost = fs.cost || u.CostUSD != 0+}++func (fs *usageFieldSet) any() bool {+ return fs.input || fs.output || fs.cacheRead || fs.cacheCreation || fs.reasoning || fs.cost+}++// clear zeroes the fields in the set on u and reports whether u still carries any usage.+func (fs *usageFieldSet) clear(u *Usage) bool {+ if fs.input {+ u.InputTokens = 0+ }+ if fs.output {+ u.OutputTokens = 0+ }+ if fs.cacheRead {+ u.CacheReadInputTokens = 0+ }+ if fs.cacheCreation {++ // The one-hour subset is part of the writes, not a field of its own.+ u.CacheCreationInputTokens = 0++ u.CacheCreation1hInputTokens = 0+ }+ if fs.reasoning {+ u.ReasoningOutputTokens = 0+ }+ if fs.cost {+ u.CostUSD = 0+ }+ return u.TotalTokens() != 0 || u.ReasoningOutputTokens != 0 || u.CostUSD != 0+}+// 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.diff --cc collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.goindex 8f50e338,70b8ebc6..0246fdb0--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go@@@ -1369,19 -1359,16 +1369,25 @@@ var inclusiveInputTokenKeys = []string{// names it accepts Claude Code's bare claude_code.llm_request span attribute// names (input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens)// so span-level usage and the per-step session drilldown carry real counts.+//+// Beacon keeps input, cache read and cache creation disjoint, so an inclusive+// input count (see inclusiveInputTokenKeys) is reduced by the cache counts+// reported beside it, the same reduction the Codex turn span gets. The raw+// attributes keep the value as reported.func GenAIUsageFromAttrs(attrs map[string]interface{}) *GenAIUsageInfo {usage := &GenAIUsageInfo{}- if value, ok := Int64Attr(attrs, "gen_ai.usage.cache_creation.input_tokens", "gen_ai.usage.cache_creation_input_tokens", "cache_creation_tokens"); ok {+ var cached int64+ if value, ok := Int64Attr(attrs, "gen_ai.usage.cache_creation.input_tokens", "gen_ai.usage.cache_write.input_tokens", "gen_ai.usage.cache_creation_input_tokens", "cache_creation_tokens"); ok {- usage.CacheCreation = &GenAIUsageCacheCreationInfo{InputTokens: &value}+ // The one-hour subset of the writes, from the browser extension's Claude adapter.+ // Claude Code's own api_request log reports only the cache_creation_tokens total.+ var oneHour *int64+ if h, ok := Int64Attr(attrs, "gen_ai.usage.cache_creation.ephemeral_1h_input_tokens"); ok {+ oneHour = &h+ }+ usage.CacheCreation = asymptoteobserve.NewCacheCreationUsage(value, oneHour)+ if value > 0 {+ cached += value+ }}if value, ok := Int64Attr(attrs, "gen_ai.usage.cache_read.input_tokens", "gen_ai.usage.cache_read_input_tokens", "cache_read_tokens"); ok {usage.CacheRead = &GenAIUsageCacheReadInfo{InputTokens: &value}diff --cc docs/cli/token-usage.mdxindex 25683439,065ec867..61926234--- a/docs/cli/token-usage.mdx+++ b/docs/cli/token-usage.mdx@@@ -23,10 -23,10 +23,10 @@@ Beacon normalizes token telemetry fromA few rules shape how the numbers read:- - **Counts are kept disjoint.** `input_tokens`, `output_tokens`, `cache_read`, and `cache_creation` do not overlap, so a total is `input + output + cache_read + cache_creation` without double-counting. Codex reports input inclusive of both cache reads and cache writes, so Beacon subtracts both before storing uncached input. The same applies to any source using the OpenTelemetry GenAI names (`gen_ai.usage.input_tokens`, or the older `prompt_tokens` spellings), whose input includes cached tokens by definition: Beacon subtracts the cache read and cache creation counts reported alongside it, unless the input is smaller than they are and so is already uncached. Claude Code's own counts are already disjoint and are stored as reported.-- **Counts are kept disjoint.** `input_tokens`, `output_tokens`, `cache_read`, and `cache_creation` do not overlap, so a total is `input + output + cache_read + cache_creation` without double-counting. Codex reports input inclusive of both cache reads and cache writes, so Beacon subtracts both before storing uncached input. `cache_creation.ephemeral_1h_input_tokens` is a breakdown of `cache_creation`, never a fifth count.++- **Counts are kept disjoint.** `input_tokens`, `output_tokens`, `cache_read`, and `cache_creation` do not overlap, so a total is `input + output + cache_read + cache_creation` without double-counting. Codex reports input inclusive of both cache reads and cache writes, so Beacon subtracts both before storing uncached input. The same applies to any source using the OpenTelemetry GenAI names (`gen_ai.usage.input_tokens`, or the older `prompt_tokens` spellings), whose input includes cached tokens by definition: Beacon subtracts the cache read and cache creation counts reported alongside it, unless the input is smaller than they are and so is already uncached. Claude Code's own counts are already disjoint and are stored as reported. `cache_creation.ephemeral_1h_input_tokens` is a breakdown of `cache_creation`, never a fifth count.- **Reported and estimated cost are kept apart.** `cost_usd` is what the runtime reported and nothing else. Beside it, every report carries a list-price estimate (`estimated_cost_usd`) for every runtime, including the ones that report no cost, and an effective cost that picks one of the two. See [Cost: reported, estimated, effective](#cost-reported-estimated-effective). Events never carry an estimate; it is computed when the report is built.- **Attribution depends on the metadata a runtime attaches.** Model, harness, repository, and run grouping work whenever those fields are present. Per-session grouping (`--session`, the session step tree) requires a session or conversation id on the usage signal. Per-user grouping uses the event user directly or a matching session context event from a local hook.-- **Duplicate channels are de-duplicated.** When a runtime emits the same usage on more than one signal (Claude Code reports it on both logs and metrics), Beacon counts it once.+- **Duplicate channels are de-duplicated.** When a runtime emits the same usage on more than one signal (Claude Code reports it on both logs and metrics), Beacon counts it once. The same holds when one session is read both live (OTLP, a hook, or a Beacon-managed plugin) and by a `beacon endpoint <runtime> sync` backfill of the runtime's own session store (`harness.collection_method=poll`), as Claude Code, Codex CLI, Cline, OpenCode, OpenClaw Gateway and Pi sessions can be. Within one session on one endpoint, live capture is authoritative from the moment its channel started capturing that session: backfilled usage from then on gives up the fields the live channel reports and is dropped once nothing is left, while backfilled usage from before it is kept, since it is the only record of turns from before Beacon's live capture started. Usage without a session id, or without a usable timestamp, is never matched this way, and a live channel that reports only context occupancy does not suppress anything. `--json` reports how many backfilled events were dropped as `suppressed_poll_events`.### Per-runtime coveragediff --cc docs/telemetry-schema/normalization.mdxindex 8c0136bb,f7f5a484..88441576--- a/docs/telemetry-schema/normalization.mdx+++ b/docs/telemetry-schema/normalization.mdx@@@ -178,9 -178,10 +178,10 @@@ Beacon preserves OpenTelemetry GenAI se| Source signal | Normalized field ||---------------|------------------|-| `gen_ai.usage.input_tokens`, `llm.usage.prompt_tokens`, `gen_ai.usage.prompt_tokens` | `gen_ai.usage.input_tokens` |+| `gen_ai.usage.input_tokens`, `llm.usage.prompt_tokens`, `gen_ai.usage.prompt_tokens` | `gen_ai.usage.input_tokens`, less the cache read and cache creation counts reported beside it (see below) || `gen_ai.usage.output_tokens`, `llm.usage.completion_tokens`, `gen_ai.usage.completion_tokens` | `gen_ai.usage.output_tokens` |-| `gen_ai.usage.cache_creation.input_tokens` | `gen_ai.usage.cache_creation.input_tokens` |+| `gen_ai.usage.cache_creation.input_tokens`, `gen_ai.usage.cache_write.input_tokens` | `gen_ai.usage.cache_creation.input_tokens` |+ | `gen_ai.usage.cache_creation.ephemeral_1h_input_tokens` (browser extension), Anthropic `usage.cache_creation.ephemeral_1h_input_tokens` (Claude Code session files), Pi `cacheWrite1h` | `gen_ai.usage.cache_creation.ephemeral_1h_input_tokens`: the subset of `cache_creation.input_tokens` written with a one-hour TTL, clamped to it and never added to a total || `gen_ai.usage.cache_read.input_tokens` | `gen_ai.usage.cache_read.input_tokens` || `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` |