Skip to content

fix(anthropic): keep setup tokens off the OAuth usage endpoint - #198161

Merged
obviyus merged 5 commits into
openclaw:mainfrom
555aaditya:fix/156296-anthropic-owns-claude-usage
Nov 13, 2026
Merged

obviyus merged 5 commits into
openclaw:mainfrom
555aaditya:fix/156296-anthropic-owns-claude-usage

Conversation

@555aaditya

@555aaditya 555aaditya commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #156296
Fixes #143419

Builds on #146726 by @RamiNoodle733, #155805 by @saariuslystoned and #156223. This version keeps the public plugin SDK unchanged.

What Problem This Solves

Fixes: an Anthropic setup-token profile polls /api/oauth/usage, which setup tokens may not be scoped for. Usage status then shows an HTTP error for Claude instead of quota, or nothing useful.

User Impact

User impact: with a stored setup-token profile, OpenClaw no longer calls the OAuth usage endpoint. If a claude.ai web session is configured (CLAUDE_AI_SESSION_KEY, CLAUDE_WEB_SESSION_KEY or CLAUDE_WEB_COOKIE), Claude quota comes from it. If not, Anthropic usage is skipped. OAuth logins, configured bearers and Admin API keys keep their current paths.

Why This Change Was Made

resolveOAuthToken resolves both oauth and token profiles and does not report which kind it used, so the Anthropic plugin sent setup tokens to the OAuth usage endpoint.

The plugin classifies the credential by the profile resolveOAuthToken actually selected: it reads that profile's stored type with findPersistedAuthProfileCredentialAsync (already public in plugin-sdk/agent-runtime) and treats only type: "token" as a setup token. An earlier revision matched the resolved token against key candidates; that misclassified an OAuth profile whose access token is also configured in ANTHROPIC_OAUTH_TOKEN or the provider key, because candidates include configured values. No SDK type or signature changes.

Changes:

  • src/infra/provider-usage.fetch.claude.ts and its test move to extensions/anthropic/claude-usage.ts. The Anthropic plugin was the only consumer.
  • fetchClaudeUsage leaves the private-local plugin-sdk/provider-usage subpath. fetchUsageJson and readUsageJson are exported there for the plugin instead.
  • Stored setup-token profiles use the web session through a prefixed usage token, like the existing Admin API key handling. Without a session, usage auth returns { handled: true }. If the web session request fails, the error names the next step: Claude web usage unavailable. Renew the claude.ai session in CLAUDE_AI_SESSION_KEY, CLAUDE_WEB_SESSION_KEY or CLAUDE_WEB_COOKIE, then retry.
  • The web session key is read from the usage context's env.
  • docs/concepts/usage-tracking.md documents the setup-token behavior.

Unchanged:

  • OAuth profiles, including the 403 user:profile scope fallback to the web session.
  • Configured bearers (ANTHROPIC_OAUTH_TOKEN or the provider key) with the sk-ant-oat01- shape still try OAuth usage. They carry no credential type, and the shape check also matches scoped OAuth access tokens, as kept in fix(anthropic): avoid usage polling with setup tokens #156223.
  • Admin API keys, and the excluded anthropic:claude-cli profile.

Not in this change: the 429 handling and last-good snapshot retention suggested in the issue comments.

Evidence

Same isolated state on the latest stable release, current main and this branch. OPENCLAW_HOME and OPENCLAW_CONFIG_PATH point at a temp directory. A fixture setup token (sk-ant-oat01- plus 80 characters) is stored with openclaw models auth paste-token --provider anthropic --profile-id anthropic:setup → Auth profile: anthropic:setup (anthropic/token). Then openclaw status --usage --json, Anthropic entry:

Build No web session CLAUDE_AI_SESSION_KEY set (fixture)
[email protected] from npm "error": "HTTP 401: OAuth access token is invalid." "error": "HTTP 401: OAuth access token is invalid."
main (d1c800bf951) "error": "HTTP 401: OAuth access token is invalid.", "authProfileId": "anthropic:setup" not run
this branch no Anthropic entry (usage skipped) "error": "Claude web usage unavailable. Renew the claude.ai session in CLAUDE_AI_SESSION_KEY, CLAUDE_WEB_SESSION_KEY or CLAUDE_WEB_COOKIE, then retry.", "authProfileId": "anthropic:setup"

Stable and main send the setup token to /api/oauth/usage. With a real setup token that request returns the 403 scope error from #143419; the fixture token gets 401. The branch makes no OAuth usage request and goes to claude.ai when a session is set. The fixture session is rejected there, which gives the recovery message. The OpenAI entry in the same output is identical on main and the branch.

Tests

  • extensions/anthropic/usage.test.ts: new cases for a stored setup-token profile without a session, a stored setup-token profile routed to the web session (asserting only claude.ai URLs are requested), the web session recovery message, an OAuth profile whose access token is also the configured bearer (stays on OAuth usage), and a configured setup-token-shaped bearer that keeps the OAuth path. With the resolver and fetch changes reverted, 3 of 11 fail. With the fix, 11/11 pass.
  • extensions/anthropic/claude-usage.test.ts: the moved fetcher tests, 14/14 unchanged.
  • pnpm test:extension anthropic: 45 files, 520 passed, 1 skipped.
  • src/plugin-sdk/lazy-runtime-facades.test.ts, extensions/codex/registration-imports.test.ts, src/infra/provider-usage*: passed.
  • pnpm check:changed: everything passes except Plugin SDK surface budget, which fails identically on unchanged main (public entrypoints 163 > 162, public exports 3888 > 3867, public callable exports 2243 > 2236, public wildcard reexports 1 > 0). This change only touches the local-only subpath (3726 → 3727 exports).
  • git diff --check: clean.

Environment: macOS 27.2, Node 26.12.1, pnpm 12.15.0.

Maintainer follow-up

A maintainer pushed 22ad1bde5b8 to this branch: setup-token classification now uses the selected profile's stored type instead of value membership in the key candidates (the remaining review finding), with a regression test for an OAuth profile whose token equals the configured bearer.

Re-run on that head with a real stored Claude setup token (isolated HOME/state, token piped from a secret store, never printed), openclaw status --usage --json, Anthropic entry:

Build No web session CLAUDE_AI_SESSION_KEY set (fixture)
main (a7d05c7af04) "error": "HTTP 429: Rate limited. Please try again later.", "authProfileId": "anthropic:setup" not run
this branch (22ad1bde5b8) no Anthropic entry (usage skipped, no request to /api/oauth/usage) "error": "Claude web usage unavailable. Renew the claude.ai session …", "authProfileId": "anthropic:setup" (request went to claude.ai)

extensions/anthropic/usage.test.ts + claude-usage.test.ts: 25/25 pass.

Accepted edge case: a setup token supplied only through config or ANTHROPIC_OAUTH_TOKEN (no stored profile) carries no type and keeps the OAuth usage path, as before.

Anthropic setup-token profiles resolved through the usage OAuth helper
and polled /api/oauth/usage, which those tokens may not be scoped for,
so usage status showed a misleading quota error.

Move Claude usage fetching into the Anthropic plugin. The plugin tells
a stored setup-token profile apart from an OAuth login without new SDK
fields: resolveApiKeyCandidatesFromConfigAndStore returns api_key and
token profile values but never OAuth access tokens, so a resolved token
found among the candidates is a setup token. Setup tokens, stored or
configured, now use the claude.ai web session when one is set and are
skipped otherwise. OAuth profiles keep the existing path, including the
user:profile scope fallback.

fetchClaudeUsage leaves the private-local plugin-sdk/provider-usage
subpath; fetchUsageJson and readUsageJson are exported there for the
plugin instead.

Fixes openclaw#156296
Fixes openclaw#143419
@clawsweeper

clawsweeper Bot commented Nov 13, 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 extensions: anthropic extensions: codex size: S labels Nov 13, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Moves Claude usage fetching into the Anthropic plugin and routes stored setup-token profiles through a configured web session instead of OAuth usage.

Example: Run openclaw status --usage --json with the stored anthropic:setup token profile and no web session.

  • Before: Claude usage reports an OAuth HTTP error, including the observed HTTP 429.
  • After: Anthropic usage is skipped without calling the OAuth usage endpoint.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with supplied shipped-CLI evidence, distinct regression coverage, and no open findings; current-head CI is still running.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Supplied macOS CLI output exercises stored setup-token usage before and after the repair, covering omission without a session and claude.ai routing with a rejected fixture session; subsequent commits leave that production code unchanged. Inspected images show historical billing UI and the original error, rather than additional after-fix proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Claude usage shows an OAuth quota error for a stored setup token that can still support inference.
Reason: The maintainer-authored linked issue explicitly requests this routing and ownership change; unrelated rate-limit caching suggestions remain outside its scope.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current usage-routing bug and completes the maintainer-requested plugin cutover. Earlier findings are resolved; no new actionable defect was found. Current-head CI remains pending.

Priority: P2
Reviewed head: ab4835a410dce000d701ea953af750a32e146a0c

Before merge

None.

Findings

None.

Agent review details

How this fits together

The shared usage collector selects credentials, then the Anthropic plugin chooses an Admin, OAuth, or claude.ai request and returns a provider usage snapshot for CLI and UI consumers.

flowchart TD
  A[CLI or UI usage request] --> B[Shared credential resolver]
  B --> C[Anthropic usage plugin]
  C --> D[OAuth usage]
  C --> E[Web session usage]
  C --> F[Admin usage]
  D --> G[Usage snapshot]
  E --> G
  F --> G
Loading

Technical review

Best possible solution:

Retain the plugin-owned credential routing and preserved OAuth, Admin, and native Claude isolation contracts, then land after required checks pass.

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

Current-main source establishes token-profile selection followed by unconditional OAuth polling; supplied CLI output corroborates the failure, but this read-only review ran no target code.

Is this the best way to solve the issue?

The patch follows the explicit ownership request, reuses existing credential lookup and transport helpers, and removes the replaced core path without expanding the public SDK.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Claude usage parsing and transport ownership changes intended behavior with a stated reason (3e0e608: The historical split placed provider fetchers in infra; later normalization repairs preserved malformed-sibling isolation, billing, and reset parsing, which the move retains.)
  • Native Claude authentication isolation keeps the original intent (750a64e: Claude CLI must own its refresh-token family to prevent copied-token refreshes from invalidating native login.)
  • Lazy provider fetching keeps the original intent (071f606: Keep provider execution code out of broad registration imports; the patch removes the obsolete Claude facade and retains sibling lazy facades.)
  • Admin usage precedence keeps the original intent (8274022: Explicit or stored Admin credentials collect organization cost history while other credentials retain subscription usage paths.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +40, Tests +65, Docs +1. Total +106 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 60 20 +40
Tests 4 73 8 +65
Docs 2 3 2 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 136 30 +106

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #156296
Summary: This PR implements the canonical credential-aware plugin cutover and the associated stored setup-token polling repair.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Stored setup-token profiles produce misleading quota errors, while inference remains available.
  • 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 (4 earlier review cycles)
  • reviewed 2026-11-13T07:36:06.668Z sha fafa9f3 :: needs changes before merge. :: [P1] Preserve OAuth polling for untyped configured bearer tokens | [P2] Give users a recovery action when web usage fails
  • reviewed 2026-11-13T08:47:35.568Z sha b004f03 :: needs changes before merge. :: [P2] Classify the selected profile independently of configured bearer values
  • reviewed 2026-11-13T12:57:17.739Z sha 22ad1bd :: needs changes before merge. :: [P2] Preserve SDK exports or explain the mock's required isolation
  • reviewed 2026-11-13T13:09:08.556Z sha f88d9a8 :: needs maintainer review before merge. :: none

Reviewed November 13, 2026, 8:52 AM ET / 13:52 UTC (Revision 5).

…eb session recovery step

Configured bearers carry no credential type, and the setup-token shape
check also matches scoped OAuth access tokens, so only stored setup-token
profiles skip OAuth usage. A failed web session now tells the user to
renew the claude.ai session and retry.
@clawsweeper

clawsweeper Bot commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: applying reviewed decision.

I am applying the reviewed decision for this pull request: fix(anthropic): keep setup tokens off the OAuth usage endpoint This is item 1/1 in the current shard. Shard 1/1.

This transient lease prevents a newer review from overlapping label, comment, or close mutations.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@555aaditya

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 13, 2026
…stored type

A configured bearer equal to an OAuth profile's access token no longer
makes that profile look like a setup token.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 13, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Nov 13, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 13, 2026
@obviyus
obviyus merged commit 5dfccbb into openclaw:main Nov 13, 2026
114 checks passed
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
…law#198161)

* fix(anthropic): keep setup tokens off the OAuth usage endpoint

Anthropic setup-token profiles resolved through the usage OAuth helper
and polled /api/oauth/usage, which those tokens may not be scoped for,
so usage status showed a misleading quota error.

Move Claude usage fetching into the Anthropic plugin. The plugin tells
a stored setup-token profile apart from an OAuth login without new SDK
fields: resolveApiKeyCandidatesFromConfigAndStore returns api_key and
token profile values but never OAuth access tokens, so a resolved token
found among the candidates is a setup token. Setup tokens, stored or
configured, now use the claude.ai web session when one is set and are
skipped otherwise. OAuth profiles keep the existing path, including the
user:profile scope fallback.

fetchClaudeUsage leaves the private-local plugin-sdk/provider-usage
subpath; fetchUsageJson and readUsageJson are exported there for the
plugin instead.

Fixes openclaw#156296
Fixes openclaw#143419

* fix(anthropic): keep configured bearers on OAuth usage and name the web session recovery step

Configured bearers carry no credential type, and the setup-token shape
check also matches scoped OAuth access tokens, so only stored setup-token
profiles skip OAuth usage. A failed web session now tells the user to
renew the claude.ai session and retry.

* fix(anthropic): classify setup-token usage by the selected profile's stored type

A configured bearer equal to an OAuth profile's access token no longer
makes that profile look like a setup token.

Co-authored-by: obviyus <[email protected]>

* test(anthropic): mark the profile-type mock as isolated

Co-authored-by: obviyus <[email protected]>

---------

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

Labels

docs Improvements or additions to documentation extensions: anthropic extensions: codex 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: S 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.

Move Claude usage fetching into the Anthropic plugin [Bug]: Claude setup-token profile is not able to get usage info

2 participants