Skip to content

fix(anthropic): avoid usage polling with setup tokens - #155805

Closed
saariuslystoned wants to merge 15 commits into
openclaw:mainfrom
saariuslystoned:fix/anthropic-setup-token-usage
Closed

saariuslystoned wants to merge 15 commits into
openclaw:mainfrom
saariuslystoned:fix/anthropic-setup-token-usage

Conversation

@saariuslystoned

@saariuslystoned saariuslystoned commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #146726

Closes #143419 and carries the compatibility repair from #146726 onto a branch writable by this account.

What Problem This Solves

Fixes: Anthropic setup-token profiles poll /api/oauth/usage, which those tokens cannot authorize, and then surface a misleading quota error.

User Impact

User impact: a stored Anthropic setup-token profile no longer makes the unsupported OAuth usage request. If a claude.ai web session is configured, quota loads from that fallback; if that fallback fails, status shows Claude web usage unavailable. Existing OAuth and API-key profiles keep their previous usage paths.

Why This Change Was Made

Classification uses the stored auth-profile type. Anthropic setup-token onboarding persists type: "token"; OAuth login persists type: "oauth" even when the access token uses the sk-ant-oat01- shape; API keys persist type: "api_key". Token prefix alone must not suppress usage.

Compatibility decision

Maintainer decision — 2026-09-23: Ayaan accepted this compatibility tradeoff: “go for it, claude's setup-token is inference only”. Stored Anthropic type: "token" profiles skip OAuth usage polling, including manually pasted bearer credentials that might otherwise have usage scope.

Evidence that this is the stored-profile contract, not an over-broad skip:

  • Anthropic's only writers of type: "token" are setup-token auth and models auth paste-token, both validated by validateAnthropicSetupToken.
  • OAuth login writes type: "oauth". API-key auth writes type: "api_key".
  • Profile order already prefers OAuth (typeScore 0) over token (1) over API key (2).
  • A static/env sk-ant-oat01- credential with no stored token profile still uses the OAuth usage path.
  • Runtime proof did not find a working stored OAuth or API-key profile that loses quota access under this classification.

No code change in this follow-up. If later evidence shows a supported Anthropic writer storing a working OAuth usage token as type: "token", narrow then.

Evidence

Exact head: c119d0e89f4673d1750cdccd5000b5bd6b5bfba8

Isolated disposable store only. Temporary HOME / OPENCLAW_STATE_DIR / OPENCLAW_CONFIG_PATH, loopback HTTP fixtures, synthetic sentinels. No live user Gateway, no inference/chat, no real provider request.

After-fix request counters and usage snapshots from the PR-head Anthropic usage owner plus official auth-profile upsert:

Case OAuth /api/oauth/usage Other requests Resulting snapshot
Fresh setup-token profile (type: "token") 0 none auth { handled: true }, provider omitted
Existing stored type: "token" profile 0 none same skip
Configured claude.ai web-session success 0 claude.ai orgs=1, usage=1 5h window at 17%
Web-session fallback failure 0 claude.ai orgs=1 error: "Claude web usage unavailable"
Existing stored API-key profile 0 none { handled: true } (unchanged; not setup-token)
Static oat01 credential, no stored token profile 1 none 5h window at 23%
Preferred OAuth mixed with lower-priority setup token 1 none OAuth profile wins, 5h at 23%
Fresh profile written via official upsert 0 none persisted type: "token", then skipped

Commands:

node scripts/run-vitest.mjs \
  extensions/anthropic/usage.setup-token.test.ts \
  extensions/anthropic/usage.test.ts \
  src/infra/provider-usage.auth.plugin.test.ts \
  --maxWorkers=1
# 39 passed (17 + 22), 8.09s wall

pnpm tsgo:extensions
pnpm tsgo:core
pnpm exec oxlint extensions/anthropic/usage.ts \
  extensions/anthropic/usage.setup-token.test.ts \
  src/infra/provider-usage.auth.ts \
  src/infra/provider-usage.auth.plugin.test.ts \
  src/infra/provider-usage.fetch.claude.ts \
  src/plugins/provider-runtime.types.ts
pnpm exec oxfmt --check <same files plus docs/concepts/usage-tracking.md>
git diff --check

All passed.

The earlier contributor proof above used the registered plugin owner. The additional CLI verification below exercises the shipped status entry point.

The original PR head branch is owned by another fork and cannot be updated by this account; this follow-up preserves the repair without force-pushing or changing the original PR.

Maintainer CLI verification (2026-09-23)

Ran the supported pnpm openclaw status --usage --json --timeout 2000 entry point at the exact head with isolated synthetic auth stores, official auth-profile upsert, and a fetch-boundary response fixture (no real provider calls). All three commands exited 0:

Stored credential / fixture OAuth requests CLI usage result
Setup token; fixture prepared to return 403 0 providers: [], no misleading quota error
Full OAuth; HTTP 200 1 Claude 5h usage at 23%
OAuth authorization-error control; HTTP 403 1 HTTP 403: scope requirement user:profile

The authorization-error control verifies that the status path exposes a genuine denial rather than suppressing all usage errors; it is not a pre-fix binary run. The 39 focused tests across the three files listed above also passed again.

@clawsweeper

clawsweeper Bot commented Sep 22, 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 triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. size: M labels Sep 22, 2026
@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 23, 2026, 1:20 AM ET / 05:20 UTC (Revision 3).

ClawSweeper review

What this changes

The PR skips unsupported quota requests for stored Anthropic setup tokens, preserves configured Claude web-session fallback, and adds credential-type metadata, tests, and documentation.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary, with no blocking correctness finding. The maintainer-edited compatibility decision resolves the previous blocker, and the supplied production-path evidence supports the changed behavior.

Priority: P2
Reviewed head: c119d0e89f4673d1750cdccd5000b5bd6b5bfba8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with useful production-path evidence, no blocking findings, and a resolved compatibility decision.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Exact-head production-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, web recovery/failure, and preserved OAuth selection. Supported status CLI output supplies additional end-to-end controls; no live Anthropic call is claimed. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Exact-head production-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, web recovery/failure, and preserved OAuth selection. Supported status CLI output supplies additional end-to-end controls; no live Anthropic call is claimed. No stored-data contract changes.
Evidence reviewed 9 items Introduced change verified: Reviewed the pinned merge-base-to-head delta across all seven paths. Classification follows credential selection, uses stored profile type rather than token shape, and retains existing Admin API priority. The stale test merge was not used to infer removal of current-main behavior.
Current main still needs the fix: Current main returns the selected OAuth/token credential without checking its stored type, then passes it to the OAuth usage fetcher. The new setup-token suppression is absent.
Latest-release comparison: The supplied latest release, v2026.9.5, also returns stored token credentials to ordinary OAuth usage polling. No merged replacement is established; the related predecessor remains open.
Findings None None.
Security None None.

How this fits together

OpenClaw’s provider usage subsystem turns configured credentials into quota information for status and billing displays. The Anthropic plugin selects organization billing, OAuth usage, or configured Claude web-session usage.

flowchart TD
  A[Configured credentials] --> B[Anthropic usage selection]
  B --> C[Admin billing]
  B --> D[OAuth quota]
  B --> E[Stored setup token]
  E --> F[Web session or skip]
  C --> G[Usage displays]
  D --> G
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +62, Tests +247, Docs 0. Total +309 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 4 66 4 +62
Tests 2 250 3 +247
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 317 8 +309

Review metrics

Metric Value Why it matters
Credential metadata 1 optional runtime field; 0 new configuration options The fix carries existing credential provenance without introducing a persisted format or configuration migration.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #143419
Summary: This PR is a candidate fix for the open setup-token usage report and carries forward the earlier draft’s work.

Members:

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

Technical review

Best possible solution:

Keep credential selection authoritative and apply the accepted setup-token policy within the existing Anthropic usage owner, preserving OAuth and configured web fallback.

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

Yes, source establishes the path: a stored Anthropic token profile reaches OAuth usage polling on current main. The original report shows a quota error; no live current-main provider reproduction was run here.

Is this the best way to solve the issue?

Yes. Stored credential metadata avoids unreliable prefix classification, preserves selection order, and reuses the existing web fetcher; the compatibility tradeoff now has recorded maintainer acceptance.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This fixes misleading quota errors with limited impact; inference and core operation are not shown to be blocked.
  • merge-risk: 🚨 compatibility: Stored token profiles stop OAuth quota polling after upgrade, including potentially scoped pasted bearers; the maintainer-edited body explicitly accepts this tradeoff.
  • 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. Sufficient (live_output): Exact-head production-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, web recovery/failure, and preserved OAuth selection. Supported status CLI output supplies additional end-to-end controls; no live Anthropic call is claimed. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Exact-head production-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, web recovery/failure, and preserved OAuth selection. Supported status CLI output supplies additional end-to-end controls; no live Anthropic call is claimed. No stored-data contract changes.

Evidence

What I checked:

  • Introduced change verified: Reviewed the pinned merge-base-to-head delta across all seven paths. Classification follows credential selection, uses stored profile type rather than token shape, and retains existing Admin API priority. The stale test merge was not used to infer removal of current-main behavior. (extensions/anthropic/usage.ts:273, c119d0e89f46)
  • Current main still needs the fix: Current main returns the selected OAuth/token credential without checking its stored type, then passes it to the OAuth usage fetcher. The new setup-token suppression is absent. (extensions/anthropic/usage.ts:252, b373c9a9bcd4)
  • Latest-release comparison: The supplied latest release, v2026.9.5, also returns stored token credentials to ordinary OAuth usage polling. No merged replacement is established; the related predecessor remains open. (extensions/anthropic/usage.ts:252, ec9c1a13db89)
  • Previous compatibility decision resolved: The captured body records Ayaan’s explicit acceptance of suppressing OAuth usage for every selected stored Anthropic token profile, including pasted bearers that might have usage scope. GitHub’s PR page identifies obviyus as the body editor; the collaborator permission endpoint reports role_name maintain, and commit metadata identifies obviyus with Ayaan’s prior Anthropic work. This covers the unchanged head and the previous review’s sole rank-up item. (c119d0e89f46)
  • Credential contract and compatibility: Setup-token onboarding persists type token; the paste-token command validates Anthropic setup-token input before writing the same type. The patch carries that existing type through an optional runtime field without changing storage. Existing OAuth selection, static credentials, and Admin API handling remain intact; the provider-usage helper is documented as private-local. (src/infra/provider-usage.auth.ts:355, c119d0e89f46)
  • After-fix behavior evidence: The complete captured body, sourceRevision e8621ea31b8c24fdc0851a14b97183f99962ac59f600185d7296a5e039eeb0a0, records exact-head production-owner runs with disposable auth stores and loopback HTTP fixtures: fresh/existing setup tokens make zero OAuth requests, web fallback returns 17% usage or an explicit error, and static/preferred OAuth credentials retain their requests. Additional supported status CLI runs report zero requests for setup tokens, 23% usage for OAuth, and a visible genuine 403 control. These are bounded local runtime observations, not live Anthropic validation; reported tests and typechecks are supplemental. (extensions/anthropic/usage.ts:276, c119d0e89f46)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jesse Merhi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-22T15:55:24.592Z sha c119d0e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-22T16:39:12.195Z sha c119d0e :: blocked before merge. :: none

@saariuslystoned

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Proof is now in the PR body for head c119d0e89f4673d1750cdccd5000b5bd6b5bfba8. Isolated disposable store + loopback fixtures only; no live Gateway and no real provider request.

Compatibility decision: preserve stored Anthropic type: "token" suppression. Setup-token onboarding is the only Anthropic writer of that type. OAuth (type: "oauth") and API-key (type: "api_key") profiles, plus static oat01 credentials without a stored token profile, keep the previous usage path.

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Sep 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@obviyus
obviyus marked this pull request as ready for review September 23, 2026 05:10
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix(anthropic): avoid usage polling with setup tokens This is item 2/3 in the current shard. Shard 87/89.

This temporary status tracks the active review worker. The completed review will appear in the durable ClawSweeper review comment.

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

@saariuslystoned

Copy link
Copy Markdown
Contributor Author

Closing in favor of the ownership refactor tracked in #156296 (move Claude usage fetching into the Anthropic plugin). This patch conflicts with current main after the recent infra/provider refactors and the maintainer decision is to fix #143419 through that refactor rather than a core-side skip. Happy to help with the #156296 work if contributor PRs are welcome there.

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 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.

[Bug]: Claude setup-token profile is not able to get usage info

3 participants