Skip to content

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

Merge token-cost-estimates into pricing-overrides

Claudef67621604cea
diff --cc CLAUDE.md
index d421caf9,d7c2ac32..b690ded6
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -539,8 -539,8 +539,8 @@@ unpacked through Chrome's developer mod
- 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.
- 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.
+- `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. Operators price what the catalog cannot (internal models, new releases, gateway aliases, negotiated rates) in a local overrides file, `<BaseDir>/pricing/overrides.json` (`pricing.DefaultOverridesPath`, user or system mode; `--pricing-file` on `beacon token-usage` and `beacon pricing` names another), schema `beacon.pricing.overrides/v1`, documented in `docs/cli/pricing.mdx`. It is offline and Beacon never writes it: the CLI reads it per run, and the dashboard re-reads it per `/api/tokens` request, read-only, falling back to the catalog with `pricing.overrides.error` when it is invalid (the CLI fails instead). Rates are USD per MTok converted exactly to microdollars; zero, negative, quoted, sub-microdollar, absurd, unknown and duplicate keys are refused with the key named. `Pricer.Lookup` runs the same ladder over the file's names first and a row replaces the catalog row whole (omitted cache rates are unpublished, priced by the usual fallbacks); aliases map a reported name to an exact row or catalog key. Reports record `source` (`override`/`catalog`), `alias`, and the file's path and SHA-256. `beacon pricing show|list|info|validate` (`cli/beacon/cmd/pricing.go`) inspects resolution, the catalog, its provenance and the file.
- 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.
- The local trace history (`~/.beacon/endpoint/history.db`, `cli/beacon/internal/endpoint/dashboard/history_*.go`) is opt-in: only `beacon endpoint traces reindex`, a yes to the first-run prompt, or (later) `beacon mcp setup` creates it, and nothing non-interactive is ever prompted. Once it exists, `list`, `search` and `show` must return exactly what the JSONL scan returns for the same log (`TestHistoryAnswersExactlyLikeTheJSONLScan`), so it stores every event and projects it with the same code. A change to the trace projection bumps `historyDerivationVersion`, which rebuilds derived data from the stored lines. The stored lines keep only the raw keys in `historyRawKeys`, and a test fails if the dashboard reads one that is missing. The line dictionary (`historyLineDictionary`) must never change without a new codec.
diff --cc cli/beacon/internal/tokens/report.go
index e594b840,6b489136..9e160601
--- a/cli/beacon/internal/tokens/report.go
+++ b/cli/beacon/internal/tokens/report.go
@@@ -158,41 -156,10 +158,41 @@@ func writePricingFooter(w io.Writer, re
provenance = "commit " + commit + ", " + provenance
}
fmt.Fprintln(w)
- fmt.Fprintln(w, "COST USD is what the runtimes reported. EST COST USD is an estimate at list price:")
+ overrides := report.Pricing.Overrides
+ if overrides != nil && overrides.Error == "" {
+ fmt.Fprintln(w, "COST USD is what the runtimes reported. EST COST USD is an estimate at list price,")
+ fmt.Fprintln(w, "or at your overrides file's rate for the models it names:")
+ } else {
+ fmt.Fprintln(w, "COST USD is what the runtimes reported. EST COST USD is an estimate at list price:")
+ }
fmt.Fprintf(w, " prices from %s (%s);\n", catalog.Name, provenance)
- fmt.Fprintf(w, " %s tier, no batch, priority or subscription discounts;\n", report.Pricing.Tier)
+ if overrides != nil {
+ if overrides.Error != "" {
+ fmt.Fprintf(w, " overrides file NOT used, list prices only: %s;\n", overrides.Error)
+ } else {
+ digest := overrides.SHA256
+ if len(digest) > 12 {
+ digest = digest[:12]
+ }
+ var byOverride []string
+ for _, m := range report.Pricing.Models {
+ if m.Source == pricing.SourceOverride || m.Alias != "" {
+ byOverride = append(byOverride, m.Model)
+ }
+ }
+ fmt.Fprintf(w, " overrides from %s (sha256 %s, %d model(s), %d alias(es));\n",
+ overrides.Path, digest, overrides.Models, overrides.Aliases)
+ if len(byOverride) > 0 {
+ fmt.Fprintf(w, " priced by the overrides file: %s;\n", strings.Join(byOverride, ", "))
+ }
+ }
+ }
+ if overrides != nil && overrides.Error == "" {
+ fmt.Fprintf(w, " catalog rates are %s tier, no batch, priority or subscription discounts;\n", report.Pricing.Tier)
+ } else {
+ fmt.Fprintf(w, " %s tier, no batch, priority or subscription discounts;\n", report.Pricing.Tier)
+ }
- fmt.Fprintln(w, " 1h cache writes are priced at the 5m rate until Beacon captures the split.")
+ fmt.Fprintln(w, " cache writes are priced at the 5m rate unless the source reported them as 1h writes.")
totals := report.Totals
fmt.Fprintf(w, "Effective cost (reported where the runtime reported one, the estimate elsewhere): %s USD",
effectiveString(totals))
diff --cc docs/cli/token-usage.mdx
index 806177dd,065ec867..7a4e7130
--- a/docs/cli/token-usage.mdx
+++ b/docs/cli/token-usage.mdx
@@@ -122,11 -122,10 +122,11 @@@ The text report prints `COST USD` (repo
### How the estimate is computed
- **Catalog.** Rates come from a catalog embedded in the binary, generated from LiteLLM's published model price list. The report's `pricing.catalog` block names the source, its upstream commit and the generation date. Nothing is fetched at report time.
-- **Standard tier only.** No batch, flex or priority tiers, regional surcharges, or subscription and enterprise discounts: nothing in a usage record says a call used them.
+- **Overrides.** A local overrides file (`~/.beacon/endpoint/pricing/overrides.json`, or `--pricing-file`) prices models the catalog does not know and replaces list prices with your negotiated rates. It wins over the catalog for every model one of its names matches. `pricing.overrides` records its path and SHA-256 digest, and each `pricing.models[]` entry says `source: override` or `source: catalog` (plus `alias` when a gateway name was mapped). An invalid file is an error, not a silent fallback to list prices; the dashboard, which must keep answering, falls back and reports it in `pricing.overrides.error`. See [beacon pricing](/cli/pricing).
+- **Standard tier only.** The catalog has no batch, flex or priority tiers, regional surcharges, or subscription and enterprise discounts: nothing in a usage record says a call used them. Put negotiated rates in the overrides file.
- **Model matching.** The model is matched to a catalog entry by exact name, then by canonical spelling (case, provider prefix), dotted versions (`claude-sonnet-4.6`), Bedrock route prefixes, and after stripping a context-window marker (`[1m]`), a snapshot date or an effort suffix. Never by similarity. `pricing.models` records, per model, the catalog key, how it matched, the base rates in USD per million tokens, and any rate fallback used.
- **Missing rates.** A model with no published cache-read or cache-write price has those tokens priced at its input rate, and the fallback is named in `pricing.models[].fallbacks`.
- - **1h cache writes** are priced at the 5-minute write rate, because `gen_ai.usage` does not yet carry the split.
+ - **1h cache writes.** Anthropic bills a cache write with a one-hour TTL at 2x the input rate, against 1.25x for the default five-minute TTL. Where the source reports the split, `gen_ai.usage.cache_creation.ephemeral_1h_input_tokens` carries the one-hour subset and those writes are priced at the model's one-hour rate (`cache_write_1h_at_write_rate` is named in `fallbacks` when the catalog has none). The split is reported by Claude Code session files (`beacon endpoint claude sync`), Pi-family runtimes whose usage carries `cacheWrite1h` (Pi fills it for Anthropic models), and the browser extension on claude.ai when the stream includes it. Claude Code's OTLP `api_request` log and token metric report only the total, so OTLP-only Claude Code usage prices every write at the five-minute rate and can understate sessions that use one-hour caching. Reports carry the subset as `cache_creation_1h_input_tokens` wherever it is non-zero.
- **Reasoning** is part of output and is not billed again. It is priced at the output rate only when a runtime reported reasoning and no output.
- **Long-context bands.** Several providers bill every token of a request above a prompt size at a higher rate (Anthropic and Gemini above 200k tokens, OpenAI's newer models above 272k). A band can only apply to a single request, so it is applied only to usage Beacon knows is one request: Claude Code `claude_code.api_request` records and session files, Codex session `token_count` records, Pi-family `message_end` and session files, OpenCode assistant messages, OpenClaw session files and DeepSeek Harness assistant messages. Metric datapoints, Codex turn spans, OpenClaw `llm_output` (one per turn), Cline task totals, Copilot shutdown totals and the Hermes, Factory and fx deltas sum several requests and are priced at base rates, which can understate a session that sent long prompts. `pricing.models[].bands_applied` counts the banded requests.
- **After deduplication.** The estimate prices the final per-event counts, after duplicate channels are removed and cumulative counters are differenced, so it covers exactly the tokens the totals count.