Skip to content

fix(anthropic): Claude CLI usage shows as unpriced in usage reports - #173792

Merged
obviyus merged 6 commits into
mainfrom
investigate/claude-cli-pricing
Oct 16, 2026
Merged

obviyus merged 6 commits into
mainfrom
investigate/claude-cli-pricing

Conversation

@obviyus

@obviyus obviyus commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: usage reports show Claude CLI traffic (for example claude-cli/claude-opus-5-5, the default CLI model) as "Unpriced", because the CLI reports no cost and the claude-cli catalog has no priced rows.

User Impact

Usage views now estimate Claude CLI usage at Anthropic's API rates, as subscription routes such as Kimi Code already do. The figures are estimates of what the API would cost, not plan charges. Prices apply right away, offline included, from the bundled Anthropic catalog rows, with no catalog publish needed. A Claude CLI turn that used 1h prompt caching is now priced like the CLI's own cost figure.

Why This Change Was Made

Since #168728, Claude CLI models come from the CLI's own menu with zero placeholder costs. Since #156535, estimates use the provider that handles the request, so claude-cli/* never picks up the anthropic/* rows.

  • priceAs: a new modelPricing provider field names the provider whose catalog rows price this provider's models when it has no price of its own. resolveModelPricing tries that provider's row for the same model, one hop only. A provider's own catalog or hosted price still wins.
    • Plugin manifests already let cliBackends own modelCatalog rows. modelPricing now accepts them too.
    • The anthropic manifest declares claude-cli: { priceAs: "anthropic" }.
    • Each model has one price fact, and nothing extra is published to the hosted catalog.
  • 1h cache writes: Claude Code splits cache writes by TTL (cache_creation.ephemeral_1h_input_tokens). normalizeUsage read only the camelCase cacheWrite1h, so CLI turns lost the 1h subset and would have been priced at the 5m rate. normalizeUsage now reads the split, and CLI usage records and persisted transcript usage carry it to the existing calculator.

Evidence

  • End to end through the shipped Gateway (openclaw gateway usage-cost).

    • Setup:
      • an isolated state and a build of this branch;
      • one real openclaw agent --local turn on anthropic/claude-opus-5-5 through the claude-cli runtime;
      • a synthetic claude executable that answered with the repo's spawn-proof protocol and reported 1,000,000 input and 100,000 output tokens with no cost. No provider request was made.
    Catalog state usage-cost
    Today's live hosted catalog (0 claude-cli/* keys), loaded with openclaw models refresh Total: $6.00 · 1.1m tokens
    Catalog refresh disabled (bundled manifest rows only) Total: $6.00 · 1.1m tokens
    Earlier revision's baseline, with no CLI pricing $0.0000, Missing cost: 1 (claude-cli/claude-opus-5-5 1)
  • 1h cache writes against the CLI's own cost:

    • Recorded Claude 2.1 turn (test/fixtures/cli/claude-2.1-thinking-progress.jsonl): it now prices at $0.40499, equal to the CLI's costUSD. Before the fix it priced at $0.26641.
    • 35 real Claude Code sessions on one install: catalog rates with the 1h split reproduce the CLI's total costUSD exactly ($2.5640). Pricing every write at the 5m rate gives $1.763.
  • Tests:

    • Resolver: claude-cli/claude-opus-5-5 resolves to the anthropic row, and a claude-cli hosted price wins over the mapping. The mapping test fails without the fallback.
    • Manifest: priceAs is normalized for a CLI backend and dropped for an unowned id.
    • CLI usage: parsing and transcript persistence keep cacheWrite1h. The transcript test fails without the carry-through.
    • Pricing, manifest, bundled-manifest contract, session-cost and CLI output suites pass (114 tests).
    • The catalog publisher is unchanged. Its two local second rename failure cases also fail on main on this machine.
  • Gap (by design): for tiered models such as claude-haiku-5-5, a multi-call turn whose summed prompt passes the 100k tier boundary stays unpriced. Whole-turn counters cannot show each call's tier.

  • Gap: a per-agent models.json written by older versions can still hold frozen claude-cli rows, including zero costs. Those rows outrank the catalog. fix(models): Claude CLI usage priced at $0 from stale models.json copies #174641 removes them.

Merge risk:

  • A two-way door: a revert removes the field and the mapping. No state is written.
  • It adds an optional priceAs field to the published modelPricing manifest contract and lets cliBackends declare pricing policies. Only the Anthropic plugin uses either.
  • Blast radius: cost estimates for Claude CLI sessions. Routing and billing do not change.

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR estimates Claude CLI usage using Anthropic catalog prices and preserves one-hour cache-write counters.

Example: A claude-cli/claude-opus-5-5 turn reports 1,000,000 input tokens and 100,000 output tokens without a monetary cost.

  • Before: The usage report marks the turn as missing a price.
  • After: The usage report estimates $6.00 at Anthropic API rates.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level repair with shipped-entry-point evidence, useful regressions, and no remaining findings; unrelated required CI remains a landing constraint.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied isolated built-Gateway run exercises agent execution, transcript persistence, and gateway usage-cost with a synthetic Claude executable, producing the expected $6.00 estimate online and offline; the recorded Claude fixture and Yigtwxx's follow-up verify the one-hour accounting result.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Claude CLI traffic appears unpriced, and one-hour cache writes would otherwise receive understated estimates.
Reason: The maintainer-authored change restores useful estimates through existing owners and explicitly retains the previously accepted tier-ambiguity limitation.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR fixes a current pricing gap, resolves the earlier findings, and has no remaining code findings; the required CI failure matches an unrelated branch.

Priority: P2
Reviewed head: 4c0bacf9766e52ba3a17e93ff84a116e74d3c555

Before merge

None.

Findings

None.

Agent review details

How this fits together

CLI output supplies token counters to session transcripts, and usage reporting combines those counters with manifest-owned catalog pricing to produce estimated costs.

flowchart LR
  A[Claude CLI output] --> B[Usage normalization]
  B --> C[Session transcript]
  C --> D[Usage reporting]
  E[Anthropic manifest] --> F[Catalog pricing resolver]
  F --> D
Loading

Technical review

Best possible solution:

Land the shared one-hop pricing fallback and cache-write propagation while preserving explicit prices, endpoint exclusions, and conservative handling of ambiguous tiers.

Do we have a high-confidence way to reproduce the issue?

Current main lacks the Claude CLI pricing mapping and drops the nested one-hour subset; the supplied Gateway comparison and recorded Claude fixture independently demonstrate the resulting missing and understated estimates.

Is this the best way to solve the issue?

The patch extends the existing static pricing owner, avoids duplicated published rates, retains authored-price precedence, and carries cache TTL metadata to the existing calculator.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 5e5ad805485b.

Provenance checked

  • Static catalog pricing and endpoint exclusions keeps the original intent (205197c: Keep pricing on prepared static metadata while preserving authored prices, provider distinctions, and private-endpoint exclusions.)
  • Billing-provider price identity keeps the original intent (f1f18d7: Use the rates of the provider billing the route and retain API-rate estimates for subscription routes.)
  • CLI transcript accounting keeps the original intent (2f22858: Persist whole-turn counters while retaining latest-call context and avoiding invented tier boundaries.)
  • Manifest pricing normalization keeps the original intent (84da6de: Keep provider pricing policy normalized centrally and preserve authored costs while native catalog prices refresh.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change: The pinned introduction diff adds a one-hop priceAs fallback, declares claude-cli pricing in the Anthropic manifest, and carries cacheWrite1h through normalization and transcript persistence. (src/model-catalog/pricing.ts:330, 4c0bacf9766e)
  • Current main still needs this change: Fetched main has no claude-cli priceAs declaration and still reads only camelCase cacheWrite1h; the central fixes remain absent. (extensions/anthropic/openclaw.plugin.json:285, 5e5ad805485b)
  • Earlier findings resolved: The head documents CLI pricing ownership, preserves the one-hour subset, and checks source-provider private endpoints and external:false before following priceAs; focused regressions cover these contracts. (src/model-catalog/pricing.test.ts:307, 4c0bacf9766e)
  • Shipped-entry-point evidence: The full PR body records an isolated built Gateway and real agent CLI invocation with a synthetic Claude executable: usage-cost reports $6.00 with hosted metadata and with refresh disabled, versus missing pricing on the baseline. (4c0bacf9766e)
  • Credited cache-accounting review: Yigtwxx identified the lost one-hour cache-write subset and subsequently confirmed the repaired fixture pipeline estimates $0.40499, matching Claude's costUSD; the accepted tier-ambiguity limitation remains documented. (src/agents/cli-output-jsonl.test.ts:670, 4c0bacf9766e)
  • Independent CI failure attribution: Check annotations for this head's job 117208615043 and unrelated branch job 117193997986 contain the same initial-roster timeout at link-hover-preview.e2e.test.ts:227. The Mermaid and guest-session shards now pass; the required aggregate gate remains failed. (4c0bacf9766e)

Likely related people:

  • Peter Steinberger: Raw commit 205197c adds src/model-catalog/pricing.ts:126 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 205197c7a498; files: src/model-catalog/pricing.ts)
  • Vincent Koc: Raw commit f1f18d7 adds src/model-catalog/pricing.ts:334 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f1f18d72dec0; files: src/model-catalog/pricing.ts)
  • Mathias Caldas: Raw commit 2f22858 adds src/agents/cli-transcript-usage.ts:22 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2f228582f354; files: src/agents/cli-transcript-usage.ts)
  • Ayaan Zaidi: Raw commit 504d290 adds src/model-catalog/pricing.ts:205 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 504d2905d69c; files: src/model-catalog/pricing.ts)

PR surface

Source +56, Tests +142, Docs +17. Total +215 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 70 14 +56
Tests 4 142 0 +142
Docs 1 17 0 +17
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 229 14 +215

Review metrics

Metric Value Why it matters
Optional manifest contract 1 new field: modelPricing.providers.<id>.priceAs Adds a documented plugin-facing pricing mapping without a required setting or new package export.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repairs missing or understated Claude CLI cost estimates without changing model execution or billing.
  • merge-risk: 🚨 compatibility: Expands the published manifest contract with optional priceAs and CLI-owned pricing policies; the maintainer-authored PR explicitly records this additive direction.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-16T04:34:54.713Z sha f45aff4 :: needs changes before merge. :: [P3] Document CLI backend ownership of pricing policies
  • reviewed 2026-10-16T17:34:45.738Z sha d5aff85 :: needs changes before merge. :: [P2] Preserve one-hour cache writes before publishing CLI estimates
  • reviewed 2026-10-16T21:04:03.969Z sha 3ac9834 :: needs changes before merge. :: [P2] Preserve source-provider exclusions before following priceAs
  • reviewed 2026-10-16T21:31:44.767Z sha 4c0bacf :: needs changes before merge. :: none

Reviewed October 16, 2026, 6:06 PM ET / 22:06 UTC (Revision 5).

@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus marked this pull request as ready for review October 16, 2026 04:40
@openclaw-barnacle openclaw-barnacle Bot added the docs Improvements or additions to documentation label Oct 16, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at d5aff85e8b6. The manifest/publisher change looks right to me: pricing ownership stays with the existing manifest and hosted-catalog owners, and the cliBackends docs are already in 362f4732d79. One thing outside the diff decides whether the new Claude CLI numbers are accurate, so I'm raising it before the catalog publish that turns these rows on.

1h cache writes on the CLI path are priced at the 5m rate (about 34% low on the repo's recorded Claude 2.1 turn)

The body says the CLI reports no cost. The recorded Claude CLI 2.1 result at test/fixtures/cli/claude-2.1-thinking-progress.jsonl:20 does report one: total_cost_usd: 0.40563, modelUsage["claude-opus-4-8"].costUSD: 0.40499. Every cache write in that turn is a 1h write: cache_creation.ephemeral_1h_input_tokens: 36955, ephemeral_5m_input_tokens: 0.

The CLI usage path drops that split:

  • src/agents/cli-output-records.ts:123 (normalizeCliUsageRecord) goes through normalizeUsage, which only reads a camelCase raw.cacheWrite1h (src/agents/usage.ts:200). CliUsage and CliBackendJsonlUsage (src/plugins/cli-backend.types.ts:287) also have no 1h field.
  • src/agents/cli-runner/cli-run-transcript.ts:137-151 persists buildUsageWithNoCost({...}) without it.
  • calculateUsageCost (packages/llm-core/src/usage-cost.ts:93-114) then prices all 36,955 tokens at cacheWrite (1.25x input) instead of the 1h rate (2x input).

The API path already reads this field: readAnthropicCacheWriteUsage (packages/ai/src/providers/anthropic-usage.ts:89-100).

I measured it with the real functions on main, which match this branch for these files. Fixture line 20 goes through readCliUsage → buildUsageWithNoCost → normalizeUsage → applyUsageCostEstimate, using the anthropic/claude-opus-4-8 rates from the live hosted catalog (input 5 / output 25 / cache read 0.5 / cache write 6.25). Those are the same models.dev/LiteLLM entries this PR maps claude-cli to.

Usage fed to applyUsageCostEstimate cacheWrite1h Estimate CLI's own costUSD
CLI transcript usage as persisted today not carried $0.26641 $0.40499
Same counters + readAnthropicCacheWriteUsage(line.usage).cacheWrite1h 36,955 $0.40499 $0.40499

Once these rows are live, a Claude CLI session that uses 1h caching goes from "Unpriced" to a figure about a third too low. That is arguably harder to notice than "Unpriced". Carrying the 1h subset reproduces the CLI's per-model figure exactly.

Suggested fix (same owner, small): read the 1h subset in normalizeCliUsageRecord, either with the anthropic reader or from cache_creation.ephemeral_1h_input_tokens directly. Then add cacheWrite1h to CliUsage and pass it through buildCliAssistantTranscriptUsage. It could be a follow-up, but it seems worth landing before the first publish that enables these keys, or at least listing next to the models.json gap in the body.

Smaller: tiered claude-haiku-5-5 stays unpriced for most multi-call CLI turns

Claude stream-json turns persist whole-turn counters, with the last call's prompt as contextUsage (src/agents/cli-output-stream.ts:350 → src/agents/cli-transcript-usage.ts:22). Once the summed prompt passes the 100k tier boundary, hasAmbiguousRequestTier (src/infra/session-cost-usage-pricing.ts:138) returns unpriced.

I ran the same pipeline with the live haiku-5-5 tiers and about 38.5k prompt tokens per call (a cached Claude Code prefix plus 500 new tokens):

Calls in the turn Estimate
1 $0.00063
2 $0.00126
3 undefined
4 undefined

This is the intended conservative behavior, not a bug in this PR. The body lists haiku-5-5 "with its context tiers" as covered, though, and most tool-using Claude Code turns cross that line. The CLI's per-model modelUsage[model].costUSD would be exact here. I did not check whether that figure is per turn or cumulative per process under the claude-stdio live session, so I'm not suggesting recording it as-is. That is just the direction I would look if exact tiered pricing matters.

@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 16, 2026
Claude CLI transcripts record no cost, and the claude-cli catalog lists no
priced rows, so usage reports showed claude-opus-5-5 as unpriced. Let CLI
backends own a modelPricing policy like providers do, and map claude-cli to
the Anthropic models.dev and LiteLLM entries. The hosted catalog then
publishes claude-cli/* provider prices that the usage resolver already reads.
Claude Code reports cache writes split by TTL under cache_creation, but
normalizeUsage read only the camelCase cacheWrite1h field, so CLI turns
lost the 1h subset and estimates priced those writes at the 5m rate.
Read the Anthropic split in normalizeUsage and carry it through CLI usage
records into the persisted transcript usage.
@obviyus
obviyus force-pushed the investigate/claude-cli-pricing branch from d5aff85 to c4a6811 Compare October 16, 2026 17:50
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@Yigtwxx thanks, both points checked out.

  • 1h cache writes: fixed in c4a6811. normalizeUsage now reads cache_creation.ephemeral_1h_input_tokens, and CLI usage records and persisted transcript usage carry cacheWrite1h. The recorded Claude 2.1 turn now prices at $0.40499, matching the CLI's costUSD. A transcript test fails without the carry-through.
  • Tiered haiku-5-5: left as is, since this is the intended conservative behavior. The body now lists it as a gap instead of claiming tier coverage.

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 16, 2026

@Yigtwxx Yigtwxx left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed at c4a68110f2c, merged locally onto current main.

The same fixture probe as before (test/fixtures/cli/claude-2.1-thinking-progress.jsonl line 20 through readCliUsage, then the transcript counters, then applyUsageCostEstimate at the opus-4-8 catalog rates):

Tree readCliUsage Estimate CLI costUSD
main no cacheWrite1h $0.26641 $0.40499
this PR cacheWrite1h: 36955 $0.40499 $0.40499

On the Claude stream-json path the persisted turn total comes from the terminal result record (output.diagnosticUsage → turnUsage). That record carries cache_creation, so the split survives multi-call turns too. Touched tests pass locally: cli-run-transcript 7/7, cli-output-jsonl/-records/-stream 113/113, usage.normalization 8/8, manifest-model-catalog 4/4. The two publish-model-catalog-v2 linked=true failures I saw on Windows also fail on main (symlink cycle), so they are not from this PR. Agreed on leaving the haiku tiers as a documented gap.

@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

CI on 4c0bacf9766, run 38968372943:

  • checks-ui-e2e (2/9) (chat-mermaid-load-errors) and checks-ui-e2e (7/9) (guest-session-controls) passed when the failed jobs were rerun once.
  • checks-ui-e2e (5/9) still fails in ui/src/e2e/link-hover-preview.e2e.test.ts > "keeps title hints when the optional hover runtime cannot load". The same failure occurs on unrelated branches:
    • run 38966282800 (deslop/z01-ui-20261015)
    • run 38966185327 (deslop/z16-5-core-fs-20261015)
    • run 38966126433 (solid2/w-idiom-components-catalog-menu)
    • run 38965984917 (deslop/bundle-w6d-ui-20261016)
    • run 38965948795 (fix/mobile-enter-newline)
    • run 38965704864 (solid2/w-idiom-components-memory-import)
    • run 38965338918 (solid2/w-idiom-components-sidebar-snapshot)

This PR changes no UI code: model pricing, the anthropic manifest, CLI usage records, and docs. All other required jobs pass.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

obviyus added a commit that referenced this pull request Oct 16, 2026
…ies (#174641)

## What Problem This Solves

Fixes: usage reports show Claude CLI models at $0.00 when an older OpenClaw version copied plugin catalog rows into an agent's root `models.json`. Those rows also outrank the live catalog forever. On one affected install this hid $220 of `claude-opus-4-8` usage behind a frozen zero price.

## User Impact

- New writes never put discovered plugin rows in the root `models.json`.
- `openclaw doctor --fix`, which update also runs, removes old copies. It removes a provider block only when it is an exact copy of a block in that plugin's generated catalog.
- Doctor saves the previous file as `models.json.bak-<timestamp>` and lists every removed provider.
- Edited blocks, blocks with credentials or overrides, and ids that config declares are never touched.
- Afterwards, prices come from the current catalog, and `models status` shows Claude CLI native auth instead of `missing`.

## Why This Change Was Made

Discovery copies a plugin's provider under its hook aliases, so `claude-cli` received the `anthropic` catalog. When owner lookup failed, the writer sent that copy to the author-owned root file instead of the plugin catalog. Owner lookup fails for a scoped plugin snapshot, or for an alias no manifest claims (on main today: `google-antigravity`, `google-interactions`, `azure-openai`, `modelstudio-native`). Since #142302 the root file merge keeps every existing provider, so the copy never left. The cost resolver reads the root file first, so its zero placeholders for unpriced models won over catalog prices.

- **Writer:** records which plugin produced each discovered provider id. When owner lookup fails, it stores the row with that producer unless config declares the id.
- **Doctor:** the catalog owner (`doctor-plugin-model-catalog.ts`) gets the legacy repair. A detector compares root blocks with the generated catalogs and requires exact equality, so no pricing or shape heuristics are involved. The file is rewritten, never deleted, because registry reads require it.

## Evidence

- **Census:** in 8 releases (2026.5.28 → 2026.10.4) run in isolated state, plain Claude CLI use never wrote the root file. The leak needs a scoped or partial owner snapshot. A real affected file, from 2026-09-06, is a byte-for-byte deep copy of the `anthropic` block in that install's generated catalog.
- **Upgrade harness:** I seeded 2026.9.2 state with that real file plus a hand-authored `my-proxy` provider, then ran the candidate's `openclaw doctor --fix --non-interactive`.
  - `claude-cli` was removed and `my-proxy` kept. The backup is byte-identical to the seeded file.
  - A second Doctor run found nothing.
  - Two later `models.json` writes left the file hash unchanged (`3bcc218b…`).
  - Control (same migrated state with the original file restored):
    - unchanged: default model, resolved model, allowlist, fallbacks, and the agent turn (`provider=claude-cli model=claude-opus-5`);
    - the model list drops only the 7 duplicate `claude-cli/*` rows;
    - Claude CLI runtime auth goes from `missing` to `claude-cli:runtime-synthetic`, the same in repeated runs.
- **Upgrade from the latest stable (2026.10.4):**
  - Seeding: 2026.10.4 created the state, with a config provider carrying a fake key, an `openai` API-key auth profile and one real Claude CLI session. I then added the real leaked `claude-cli` root block, its generated `anthropic` catalog row and an authored root provider with a fake key. The candidate's `doctor --fix --non-interactive` then ran.
  - Removed: `claude-cli` only. The backup is byte-identical to the seeded file, and a second Doctor run changed nothing.
  - Kept: the authored root provider with its key, the config provider with its key, the auth profile, and the session (same key and id).
  - The Claude CLI turn works before and after.
  - Every other config or auth change also happens with 2026.10.4's own Doctor on the same seed: the legacy `claude-cli/*` default canonicalized to `anthropic/*`, and plaintext keys copied into auth profiles. The one exception is main's existing `"anthropic/*"` runtime entry. That Doctor leaves the `claude-cli` copy in place.
- **Copy of a real install** (credentials, leases and other plugins' catalogs stripped; isolated Gateway): Doctor found and removed the copy. `sessions.usage` for June–October, with a fresh cache and only the root file differing:

  | claude-cli model | turns | stale root | repaired |
  |---|---|---|---|
  | claude-opus-4-8 | 2105 | $0.00 | $220.04 |
  | claude-haiku-4-5 | 12 | $0.00 | $0.20 |
  | other Claude models | 609 | $95.35 | $95.35 |

  Token totals are identical (4,307,266,930). The $220.04 equals the transcript token sums at the catalog's Opus 4.8 rates.
- **Comparison with the CLI's own cost:** Claude Code recorded `costUSD` for 35 sessions on that install. Catalog rates reproduce all of them exactly ($2.5640 vs $2.5640) once cache writes are priced at the 1h rate. Historical OpenClaw transcripts did not store that split, so they estimate those turns about 31% low. #173792 records the split for new turns.
- **Tests:**
  - Doctor: exact copy removed once with a byte-exact backup; edited copy kept; config-declared id kept.
  - Writer: an unowned hook alias goes to the producing plugin's catalog, not the root file. It fails without the fix.
  - The `models-config`, plugin catalog and Doctor catalog suites pass (208 tests).

**Merge risk:**
- **Writer change:** a two-way door; revert restores the old routing.
- **Doctor repair:** rewrites user files, but only exact generated copies, always with a full backup, so a removal is recoverable by restoring the backup.
- **Blast radius:** agents whose root `models.json` holds generated plugin copies, mainly Claude CLI installs from 2026-05 to 2026-10. Unowned alias copies no longer appear as separate models; they carried the producer's baseUrl under another id.

Co-authored-by: Ayaan Zaidi <[email protected]>
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: checks-ui-e2e (5/9) and the openclaw/ci-gate that aggregates it are red on head 4c0bacf9766 (run 38968372943, after one rerun of the failed jobs).

The only failing test is ui/src/e2e/link-hover-preview.e2e.test.ts > "keeps title hints when the optional hover runtime cannot load". The same failure occurs on unrelated branches: runs 38966282800, 38966185327, 38966126433, 38965984917, 38965948795, 38965704864 and 38965338918. This PR changes no UI code. Every other job passed, and the ClawSweeper review on this head is ready. Landing past it was approved by @obviyus.

@obviyus
obviyus merged commit be6eedf into main Oct 16, 2026
235 of 242 checks passed
@obviyus
obviyus deleted the investigate/claude-cli-pricing branch October 16, 2026 23:17
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in be6eedf.

  • Bug: Claude CLI usage showed as Unpriced, because the CLI reports no cost and claude-cli has no priced catalog rows.
  • Fix: a new modelPricing field, priceAs, prices claude-cli with the anthropic catalog rows. It never overrides a price of its own, a private endpoint, or external: false. CLI usage now also keeps Claude's 1h cache-write split.
  • Proof: a real Gateway usage-cost turn gives $6.00 with today's live catalog and offline. The recorded Claude 2.1 turn and 35 real sessions match the CLI's own costUSD exactly. Thanks @Yigtwxx for catching the cache-TTL undercount.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…ies (openclaw#174641)

## What Problem This Solves

Fixes: usage reports show Claude CLI models at $0.00 when an older OpenClaw version copied plugin catalog rows into an agent's root `models.json`. Those rows also outrank the live catalog forever. On one affected install this hid $220 of `claude-opus-4-8` usage behind a frozen zero price.

## User Impact

- New writes never put discovered plugin rows in the root `models.json`.
- `openclaw doctor --fix`, which update also runs, removes old copies. It removes a provider block only when it is an exact copy of a block in that plugin's generated catalog.
- Doctor saves the previous file as `models.json.bak-<timestamp>` and lists every removed provider.
- Edited blocks, blocks with credentials or overrides, and ids that config declares are never touched.
- Afterwards, prices come from the current catalog, and `models status` shows Claude CLI native auth instead of `missing`.

## Why This Change Was Made

Discovery copies a plugin's provider under its hook aliases, so `claude-cli` received the `anthropic` catalog. When owner lookup failed, the writer sent that copy to the author-owned root file instead of the plugin catalog. Owner lookup fails for a scoped plugin snapshot, or for an alias no manifest claims (on main today: `google-antigravity`, `google-interactions`, `azure-openai`, `modelstudio-native`). Since openclaw#142302 the root file merge keeps every existing provider, so the copy never left. The cost resolver reads the root file first, so its zero placeholders for unpriced models won over catalog prices.

- **Writer:** records which plugin produced each discovered provider id. When owner lookup fails, it stores the row with that producer unless config declares the id.
- **Doctor:** the catalog owner (`doctor-plugin-model-catalog.ts`) gets the legacy repair. A detector compares root blocks with the generated catalogs and requires exact equality, so no pricing or shape heuristics are involved. The file is rewritten, never deleted, because registry reads require it.

## Evidence

- **Census:** in 8 releases (2026.5.28 → 2026.10.4) run in isolated state, plain Claude CLI use never wrote the root file. The leak needs a scoped or partial owner snapshot. A real affected file, from 2026-09-06, is a byte-for-byte deep copy of the `anthropic` block in that install's generated catalog.
- **Upgrade harness:** I seeded 2026.9.2 state with that real file plus a hand-authored `my-proxy` provider, then ran the candidate's `openclaw doctor --fix --non-interactive`.
  - `claude-cli` was removed and `my-proxy` kept. The backup is byte-identical to the seeded file.
  - A second Doctor run found nothing.
  - Two later `models.json` writes left the file hash unchanged (`3bcc218b…`).
  - Control (same migrated state with the original file restored):
    - unchanged: default model, resolved model, allowlist, fallbacks, and the agent turn (`provider=claude-cli model=claude-opus-5`);
    - the model list drops only the 7 duplicate `claude-cli/*` rows;
    - Claude CLI runtime auth goes from `missing` to `claude-cli:runtime-synthetic`, the same in repeated runs.
- **Upgrade from the latest stable (2026.10.4):**
  - Seeding: 2026.10.4 created the state, with a config provider carrying a fake key, an `openai` API-key auth profile and one real Claude CLI session. I then added the real leaked `claude-cli` root block, its generated `anthropic` catalog row and an authored root provider with a fake key. The candidate's `doctor --fix --non-interactive` then ran.
  - Removed: `claude-cli` only. The backup is byte-identical to the seeded file, and a second Doctor run changed nothing.
  - Kept: the authored root provider with its key, the config provider with its key, the auth profile, and the session (same key and id).
  - The Claude CLI turn works before and after.
  - Every other config or auth change also happens with 2026.10.4's own Doctor on the same seed: the legacy `claude-cli/*` default canonicalized to `anthropic/*`, and plaintext keys copied into auth profiles. The one exception is main's existing `"anthropic/*"` runtime entry. That Doctor leaves the `claude-cli` copy in place.
- **Copy of a real install** (credentials, leases and other plugins' catalogs stripped; isolated Gateway): Doctor found and removed the copy. `sessions.usage` for June–October, with a fresh cache and only the root file differing:

  | claude-cli model | turns | stale root | repaired |
  |---|---|---|---|
  | claude-opus-4-8 | 2105 | $0.00 | $220.04 |
  | claude-haiku-4-5 | 12 | $0.00 | $0.20 |
  | other Claude models | 609 | $95.35 | $95.35 |

  Token totals are identical (4,307,266,930). The $220.04 equals the transcript token sums at the catalog's Opus 4.8 rates.
- **Comparison with the CLI's own cost:** Claude Code recorded `costUSD` for 35 sessions on that install. Catalog rates reproduce all of them exactly ($2.5640 vs $2.5640) once cache writes are priced at the 1h rate. Historical OpenClaw transcripts did not store that split, so they estimate those turns about 31% low. openclaw#173792 records the split for new turns.
- **Tests:**
  - Doctor: exact copy removed once with a byte-exact backup; edited copy kept; config-declared id kept.
  - Writer: an unowned hook alias goes to the producing plugin's catalog, not the root file. It fails without the fix.
  - The `models-config`, plugin catalog and Doctor catalog suites pass (208 tests).

**Merge risk:**
- **Writer change:** a two-way door; revert restores the old routing.
- **Doctor repair:** rewrites user files, but only exact generated copies, always with a full backup, so a removal is recoverable by restoring the backup.
- **Blast radius:** agents whose root `models.json` holds generated plugin copies, mainly Claude CLI installs from 2026-05 to 2026-10. Unowned alias copies no longer appear as separate models; they carried the producer's baseUrl under another id.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…penclaw#173792)

## What Problem This Solves

Fixes: usage reports show Claude CLI traffic (for example `claude-cli/claude-opus-5-5`, the default CLI model) as "Unpriced", because the CLI reports no cost and the `claude-cli` catalog has no priced rows.

## User Impact

Usage views now estimate Claude CLI usage at Anthropic's API rates, as subscription routes such as Kimi Code already do. The figures are estimates of what the API would cost, not plan charges. Prices apply right away, offline included, from the bundled Anthropic catalog rows, with no catalog publish needed. A Claude CLI turn that used 1h prompt caching is now priced like the CLI's own cost figure.

## Why This Change Was Made

Since openclaw#168728, Claude CLI models come from the CLI's own menu with zero placeholder costs. Since openclaw#156535, estimates use the provider that handles the request, so `claude-cli/*` never picks up the `anthropic/*` rows.

- **`priceAs`:** a new `modelPricing` provider field names the provider whose catalog rows price this provider's models when it has no price of its own. `resolveModelPricing` tries that provider's row for the same model, one hop only. A provider's own catalog or hosted price still wins.
  - Plugin manifests already let `cliBackends` own `modelCatalog` rows. `modelPricing` now accepts them too.
  - The anthropic manifest declares `claude-cli: { priceAs: "anthropic" }`.
  - Each model has one price fact, and nothing extra is published to the hosted catalog.
- **1h cache writes:** Claude Code splits cache writes by TTL (`cache_creation.ephemeral_1h_input_tokens`). `normalizeUsage` read only the camelCase `cacheWrite1h`, so CLI turns lost the 1h subset and would have been priced at the 5m rate. `normalizeUsage` now reads the split, and CLI usage records and persisted transcript usage carry it to the existing calculator.

## Evidence

- **End to end through the shipped Gateway (`openclaw gateway usage-cost`).**
  - Setup:
    - an isolated state and a build of this branch;
    - one real `openclaw agent --local` turn on `anthropic/claude-opus-5-5` through the `claude-cli` runtime;
    - a synthetic `claude` executable that answered with the repo's spawn-proof protocol and reported 1,000,000 input and 100,000 output tokens with no cost. No provider request was made.

  | Catalog state | `usage-cost` |
  |---|---|
  | Today's live hosted catalog (0 `claude-cli/*` keys), loaded with `openclaw models refresh` | `Total: $6.00 · 1.1m tokens` |
  | Catalog refresh disabled (bundled manifest rows only) | `Total: $6.00 · 1.1m tokens` |
  | Earlier revision's baseline, with no CLI pricing | `$0.0000`, `Missing cost: 1 (claude-cli/claude-opus-5-5 1)` |

- **1h cache writes against the CLI's own cost:**
  - **Recorded Claude 2.1 turn** (`test/fixtures/cli/claude-2.1-thinking-progress.jsonl`): it now prices at $0.40499, equal to the CLI's `costUSD`. Before the fix it priced at $0.26641.
  - **35 real Claude Code sessions on one install:** catalog rates with the 1h split reproduce the CLI's total `costUSD` exactly ($2.5640). Pricing every write at the 5m rate gives $1.763.
- **Tests:**
  - Resolver: `claude-cli/claude-opus-5-5` resolves to the `anthropic` row, and a `claude-cli` hosted price wins over the mapping. The mapping test fails without the fallback.
  - Manifest: `priceAs` is normalized for a CLI backend and dropped for an unowned id.
  - CLI usage: parsing and transcript persistence keep `cacheWrite1h`. The transcript test fails without the carry-through.
  - Pricing, manifest, bundled-manifest contract, session-cost and CLI output suites pass (114 tests).
  - The catalog publisher is unchanged. Its two local `second rename failure` cases also fail on main on this machine.
- **Gap (by design):** for tiered models such as `claude-haiku-5-5`, a multi-call turn whose summed prompt passes the 100k tier boundary stays unpriced. Whole-turn counters cannot show each call's tier.
- **Gap:** a per-agent `models.json` written by older versions can still hold frozen `claude-cli` rows, including zero costs. Those rows outrank the catalog. openclaw#174641 removes them.

**Merge risk:**
- A two-way door: a revert removes the field and the mapping. No state is written.
- It adds an optional `priceAs` field to the published `modelPricing` manifest contract and lets `cliBackends` declare pricing policies. Only the Anthropic plugin uses either.
- Blast radius: cost estimates for Claude CLI sessions. Routing and billing do not change.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 29, 2026
## What Problem This Solves

The repo has no written rules for agents that work on model listing, provider plugins or usage/cost. So the same classes of bugs keep coming back across providers and on the Models and Usage pages.

## User Impact

There is no user-visible change. Agents that work in these areas now get short rules from the scoped guide they already read.

## Why This Change Was Made

Each rule records a lesson that came back 2 or more times in merged work. Each rule is one line, in the guide that owns the area:

- **`src/plugins/AGENTS.md` "Model Listing":**
  - The hot path has no network request.
  - `models.list` has p99 under 300 ms. Rows and prices publish as one snapshot, and removals apply at once.
  - The authenticated listing decides which models show.
  - List with the credential and runtime that will execute the turn, with one row per model per provider.
  - Failed and empty listings each have defined semantics.
  - Capabilities come from the listing, not from model-ID rules.
  - One core admission rule.
- **`extensions/AGENTS.md`:**
  - Host policy that every provider shares stays core.
  - Sign-in goes through the Models page and `/login`. Setup saves the connection only.
  - Native CLIs own their login and model menu.
  - Refusals are classified by cause.
  - Attribution headers come from one helper.
- **`src/agents/AGENTS.md` "Run Authority":**
  - One model resolver for every entry path.
  - No silent fallback to another runtime or billing.
  - Native-runtime consent is asked once.
- **`src/gateway/AGENTS.md` "Usage And Cost" (new section):**
  - Measured, unpriced, partial and unknown usage stay distinct.
  - Each route is priced from the provider that bills it.
  - Reports are complete or flagged as partial.
- **`ui/AGENTS.md`:**
  - A route waits only for its first-paint data.
  - New "Layout Stability" section: zero layout shift, how to prove it, and a 200 ms load budget for Models and Usage.
- **Root `AGENTS.md`:** one line in "Read when relevant" that points to these sections.

Examples of the incidents behind the rules: #140139, #158000, #167444, #167658, #168033, #172608, #172773, #173792, #174641, #176404, #180838, #184066.

## Evidence

- `pnpm check:agents-md-size`: all 27 files are within 20000 chars.
- `oxfmt --check` passes on each of the 6 changed files.
- I checked the cited names on current `main`: `buildLiveModelProviderConfig`, `readModelId` and `modelPricing.providers.<id>.priceAs`.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 29, 2026
…87141)

## What Problem This Solves

The repo has no written rules for agents that work on model listing, provider plugins or usage/cost. So the same classes of bugs keep coming back across providers and on the Models and Usage pages.

## User Impact

There is no user-visible change. Agents that work in these areas now get short rules from the scoped guide they already read.

## Why This Change Was Made

Each rule records a lesson that came back 2 or more times in merged work. Each rule is one line, in the guide that owns the area:

- **`src/plugins/AGENTS.md` "Model Listing":**
  - The hot path has no network request.
  - `models.list` has p99 under 300 ms. Rows and prices publish as one snapshot, and removals apply at once.
  - The authenticated listing decides which models show.
  - List with the credential and runtime that will execute the turn, with one row per model per provider.
  - Failed and empty listings each have defined semantics.
  - Capabilities come from the listing, not from model-ID rules.
  - One core admission rule.
- **`extensions/AGENTS.md`:**
  - Host policy that every provider shares stays core.
  - Sign-in goes through the Models page and `/login`. Setup saves the connection only.
  - Native CLIs own their login and model menu.
  - Refusals are classified by cause.
  - Attribution headers come from one helper.
- **`src/agents/AGENTS.md` "Run Authority":**
  - One model resolver for every entry path.
  - No silent fallback to another runtime or billing.
  - Native-runtime consent is asked once.
- **`src/gateway/AGENTS.md` "Usage And Cost" (new section):**
  - Measured, unpriced, partial and unknown usage stay distinct.
  - Each route is priced from the provider that bills it.
  - Reports are complete or flagged as partial.
- **`ui/AGENTS.md`:**
  - A route waits only for its first-paint data.
  - New "Layout Stability" section: zero layout shift, how to prove it, and a 200 ms load budget for Models and Usage.
- **Root `AGENTS.md`:** one line in "Read when relevant" that points to these sections.

Examples of the incidents behind the rules: openclaw#140139, openclaw#158000, openclaw#167444, openclaw#167658, openclaw#168033, openclaw#172608, openclaw#172773, openclaw#173792, openclaw#174641, openclaw#176404, openclaw#180838, openclaw#184066.

## Evidence

- `pnpm check:agents-md-size`: all 27 files are within 20000 chars.
- `oxfmt --check` passes on each of the 6 changed files.
- I checked the cited names on current `main`: `buildLiveModelProviderConfig`, `readModelId` and `modelPricing.providers.<id>.priceAs`.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: anthropic merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants