Skip to content

fix(models): Claude CLI usage priced at $0 from stale models.json copies - #174641

Merged
obviyus merged 3 commits into
mainfrom
fix/models-json-stale-plugin-rows
Oct 16, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/models-json-stale-plugin-rows

Conversation

@obviyus

@obviyus obviyus commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

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. fix(anthropic): Claude CLI usage shows as unpriced in usage reports #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.

Discovery copies a plugin's provider under its hook aliases. When the owner
lookup failed (a scoped plugin snapshot, or an alias no manifest claims),
the writer sent that copy to the author-owned root models.json, where the
merge kept it forever. Frozen prices there, including zero placeholders for
unpriced models, outranked the live catalog.

The writer now stores discovery output with the plugin that produced it
unless config declares the id. Doctor removes root blocks that are exact
copies of a generated catalog block, keeping a byte-exact backup and
reporting each removal.
@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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: M labels Oct 16, 2026
@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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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 keeps discovered providers in their producing plugin’s catalog and lets Doctor back up and remove exact generated copies from root models.json.

Example: An affected install has frozen claude-cli pricing in root models.json.

  • Before: Usage reporting prices 2,105 claude-opus-4-8 turns at $0.00.
  • After: The supplied isolated Gateway comparison reports $220.04 after Doctor removes the duplicate, with identical token totals.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with supplied shipped-entry-point and stable-upgrade evidence, meaningful preservation tests, and no actionable finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied results exercise candidate Doctor through the CLI and sessions.usage through an isolated Gateway, showing duplicate removal, unchanged token totals, corrected estimates, byte-identical backups, and idempotence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Usage reports can show paid-equivalent Claude CLI usage as free because frozen generated root rows override current catalog prices.
Reason: The source-supported defect has observed user impact, and the collaborator-authored direction repairs both new writes and conservatively identifiable legacy copies.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a source-supported pricing defect that remains on main. No actionable patch defect was found, and the earlier draft blocker is resolved; exact-head CI is still pending.

Priority: P2
Reviewed head: a53d0f5622fcd73d31e6d3f4389e183a6e1769e9

Before merge

None.

Findings

None.

Agent review details

How this fits together

Model discovery feeds the catalog planner, which separates authored root providers from generated plugin catalogs; Doctor repairs legacy persisted copies, and usage reporting consumes the resulting pricing.

flowchart TD
  A[Plugin discovery] --> B[Catalog planner]
  B --> C[Generated plugin catalogs]
  B --> D[Authored root providers]
  E[Doctor repair] --> C
  E --> D
  D --> F[Usage pricing]
  C --> F
Loading

Technical review

Best possible solution:

Land the producer-routing fix and backed-up Doctor repair once the existing exact-head CI gates pass.

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

Source connects alias discovery, failed owner lookup, root persistence, and root-first zero pricing; the author supplies an affected-install comparison, but this read-only review ran no target code.

Is this the best way to solve the issue?

The patch fixes the writer and places legacy cleanup with Doctor while preserving runtime read-only behavior and authored overrides.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change verified: The pinned introduction diff adds producer tracking, routes otherwise unowned discovered providers to that producer, and adds Doctor-owned duplicate removal. (src/agents/models-config.plan.ts:87, a53d0f5622fc)
  • Current-main failure path: Main still routes providers without a manifest owner into the root file; pricing reads root models.json rates before catalog prices, including explicit zero rates. (src/agents/models-config.plan.ts:87, e455389ee32b)
  • Conservative repair boundary: Removal requires exact equality with a generated catalog block, excludes config-declared IDs and extra provider fields, and writes the original file to a private backup before replacement. (src/agents/plugin-model-catalog-root-copies.ts:77, a53d0f5622fc)
  • Supplied runtime and upgrade evidence: The complete PR body records shipped Doctor and isolated Gateway results, byte-identical backup verification, repeat-run idempotence, and a 2026.10.4 upgrade preserving authored providers, credentials, auth profiles, and session identity. (a53d0f5622fc)
  • Accepted compatibility tradeoff: The collaborator-authored PR explicitly accepts removing duplicate alias models and rewriting exact generated copies, with a full backup; edited, configured, and credential-bearing blocks remain protected. (src/commands/doctor-plugin-model-catalog.ts:71, a53d0f5622fc)
  • Distinct complementary pricing work: fix(anthropic): Claude CLI usage shows as unpriced in usage reports #173792 supplies Claude CLI catalog-price inheritance and cache-write accounting; its body explicitly leaves frozen root overrides to this PR. (3ac9834b761f)

Likely related people:

  • Peter Steinberger: Raw commit 51b5f75 adds src/agents/models-config.plan.ts:66 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 51b5f75b92f7; files: src/agents/models-config.plan.ts)
  • Ayaan Zaidi: Raw commit f7d2fa7 adds src/agents/models-config.plan.ts:393 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f7d2fa7402bb; files: src/agents/models-config.plan.ts)

PR surface

Source +261, Tests +156, Docs +2. Total +419 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 271 10 +261
Tests 2 162 6 +156
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 435 16 +419

Review metrics

Metric Value Why it matters
Production versus test LOC Production +271/−10; tests +162/−6 Growth primarily implements exact-copy detection, backed-up persisted-file repair, and preservation regressions; these serve the same reported defect.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: Doctor rewrites persisted root catalogs and removes duplicate alias inventory; the maintainer-authored direction explicitly accepts this bounded change, with backups and supplied stable-upgrade preservation evidence.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, 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: Incorrect usage estimates affect installations with leaked root catalog copies; runtime operation and token accounting remain intact.
  • merge-risk: 🚨 compatibility: Doctor rewrites persisted root catalogs and removes duplicate alias inventory; the maintainer-authored direction explicitly accepts this bounded change, with backups and supplied stable-upgrade preservation evidence.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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 (1 earlier review cycle)
  • reviewed 2026-10-16T20:45:37.345Z sha a53d0f5 :: blocked before merge. :: none

Reviewed October 16, 2026, 5:12 PM ET / 21:12 UTC (Revision 2).

@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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 16, 2026
@clawsweeper clawsweeper Bot removed 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 merged commit 5e5ad80 into main Oct 16, 2026
257 checks passed
@obviyus
obviyus deleted the fix/models-json-stale-plugin-rows branch October 16, 2026 22:01
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 5e5ad80.

  • Bug: older versions copied plugin catalog blocks, such as anthropic under the claude-cli hook alias, into the author-owned root models.json. Those frozen rows outranked the live catalog, so unpriced models showed as $0.
  • Fix: discovery output now stays with the plugin that produced it. openclaw doctor --fix removes exact generated copies, with a byte-exact backup and a list of what it removed.
  • Proof: upgrades from 2026.9.2 and from 2026.10.4 keep authored providers, credentials, sessions and Claude CLI turns, and a second run changes nothing. On a copy of a real install, 2,105 claude-opus-4-8 turns went from $0.00 to $220.04 at identical token totals. Thanks @Yigtwxx for the cache-TTL review on the sibling pricing PR.

obviyus added a commit that referenced this pull request Oct 16, 2026
…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 #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. #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]>
steipete added a commit that referenced this pull request Oct 16, 2026
)

The native retention fixture replaced its manifest without declaring the
provider registered by its catalog hook. After 5e5ad80 (#174641) stopped
writing unowned discoveries to root models.json, all six native cases
returned empty catalogs before reaching their isolation/retention checks.
That change intentionally keeps unclaimed aliases out of model inventory.

Declare the fixture provider through the existing manifest contract. Keep
all catalog, lifetime, workspace-isolation and released-authority assertions.
No production behavior or update migration changes.

Proof: current main reproduced 6 failures / 1 pass. Rolling only the catalog
routing owner back to the culprit parent restored the unchanged 21-generation
case. With this fixture fix, all 7 cases pass using the Node infra project
and --maxWorkers=1 (20.42 s Vitest; 48.25 s wrapper). Targeted agents-root
typecheck, type-aware lint, formatting and git diff --check pass.

Independent P2 autoreview: scoped-clean, no actionable findings.
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…claw#174823)

The native retention fixture replaced its manifest without declaring the
provider registered by its catalog hook. After cb034c8 (openclaw#174641) stopped
writing unowned discoveries to root models.json, all six native cases
returned empty catalogs before reaching their isolation/retention checks.
That change intentionally keeps unclaimed aliases out of model inventory.

Declare the fixture provider through the existing manifest contract. Keep
all catalog, lifetime, workspace-isolation and released-authority assertions.
No production behavior or update migration changes.

Proof: current main reproduced 6 failures / 1 pass. Rolling only the catalog
routing owner back to the culprit parent restored the unchanged 21-generation
case. With this fixture fix, all 7 cases pass using the Node infra project
and --maxWorkers=1 (20.42 s Vitest; 48.25 s wrapper). Targeted agents-root
typecheck, type-aware lint, formatting and git diff --check pass.

Independent P2 autoreview: scoped-clean, no actionable findings.
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 commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime 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: 🐚 platinum hermit Good normal PR readiness with ordinary 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.

1 participant