Skip to content

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

Closed
obviyus wants to merge 16 commits into
mainfrom
fix/anthropic-setup-token-usage-maintainer
Closed

obviyus wants to merge 16 commits into
mainfrom
fix/anthropic-setup-token-usage-maintainer

Conversation

@obviyus

@obviyus obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator

Replaces #155805 (maintainer edits disabled); credit @saariuslystoned and @RamiNoodle733. Their original commits are preserved without rewriting.

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.

The replacement adds one test-only commit updating three credential-selection expectations for the new profileType metadata. Production code and CLI behavior are unchanged from the contributor head.

Replacement verification: node scripts/run-vitest.mjs src/infra/provider-usage.auth.normalizes-keys.test.ts --maxWorkers=1 — all 17 tests passed, including the three formerly failing expectations.

@clawsweeper

clawsweeper Bot commented Sep 23, 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.

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator Author

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: anthropic size: M labels Sep 23, 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. 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. labels Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 23, 2026, 1:49 AM ET / 05:49 UTC.

ClawSweeper review

What this changes

The PR skips unsupported Anthropic setup-token quota requests, preserves configured web-session fallback, and adds credential-type metadata, regression coverage, and documentation.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary on current main and v2026.9.5. No blocking correctness finding remains; the recorded compatibility acceptance and production-path evidence support this replacement PR.

Priority: P2
Reviewed head: 7d9318205a55a4a5fd13776304752266891b720b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with sufficient production-path evidence, an accepted compatibility tradeoff, and no blocking correctness findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Production Anthropic usage-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, preserved OAuth selection, and web fallback success/failure. Status CLI output adds entrypoint controls; the replacement changes tests only. No live Anthropic call or stored-data contract change is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Production Anthropic usage-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, preserved OAuth selection, and web fallback success/failure. Status CLI output adds entrypoint controls; the replacement changes tests only. No live Anthropic call or stored-data contract change is claimed.
Evidence reviewed 9 items Pinned introduced change: Reviewed the complete merge-base-to-head diff. Setup-token classification follows credential selection, preserves Admin API precedence, and uses stored profile type rather than token shape.
Still necessary on main: Current main returns selected OAuth/token credentials directly to the OAuth usage fetcher; the stored-token suppression is absent.
Latest-release comparison: Inspected the Anthropic usage resolver at the supplied latest release, v2026.9.5: it likewise returns stored token credentials without this classification. The related PRs are open, not merged fixes.
Findings None None.
Security None None.

How this fits together

OpenClaw’s provider usage subsystem turns configured credentials into quota and billing snapshots for status displays. The Anthropic plugin chooses the appropriate usage endpoint or skips credentials that cannot authorize quota requests.

flowchart TD
  A[Configured credentials] --> B[Anthropic usage selection]
  B --> C[Admin billing]
  B --> D[OAuth quota]
  B --> E[Stored setup token]
  E --> F[Configured 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 +249, Docs 0. Total +311 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 66 4 +62
Tests 3 255 6 +249
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 322 11 +311

Review metrics

Metric Value Why it matters
Runtime contract additions 1 optional credential field; 1 optional fetch argument; 0 new settings The repair carries existing credential provenance without changing stored profiles or requiring configuration migration.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #143419
Summary: This PR carries the candidate repair for the open setup-token quota report through the explicitly linked replacement chain.

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 in the existing Anthropic usage owner, preserving OAuth, Admin API, and configured web fallback.

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

Yes, source establishes the path: a selected stored Anthropic token profile reaches OAuth usage polling on current main. This review did not run a live current-main provider reproduction.

Is this the best way to solve the issue?

Yes. Stored profile metadata avoids unreliable token-prefix classification, preserves credential ordering, and reuses the existing web fetcher under an accepted compatibility policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: The repair addresses misleading quota errors without evidence that inference or core operation is blocked.
  • add merge-risk: 🚨 compatibility: Stored token profiles stop OAuth quota polling, including potentially scoped pasted bearers; the recorded maintainer decision explicitly accepts this tradeoff.
  • add proof: sufficient: Contributor real behavior proof is sufficient. Production Anthropic usage-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, preserved OAuth selection, and web fallback success/failure. Status CLI output adds entrypoint controls; the replacement changes tests only. No live Anthropic call or stored-data contract change is claimed.
  • 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. Sufficient (live_output): Production Anthropic usage-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, preserved OAuth selection, and web fallback success/failure. Status CLI output adds entrypoint controls; the replacement changes tests only. No live Anthropic call or stored-data contract change is claimed.

Label justifications:

  • P2: The repair addresses misleading quota errors without evidence that inference or core operation is blocked.
  • merge-risk: 🚨 compatibility: Stored token profiles stop OAuth quota polling, including potentially scoped pasted bearers; the recorded maintainer decision 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): Production Anthropic usage-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, preserved OAuth selection, and web fallback success/failure. Status CLI output adds entrypoint controls; the replacement changes tests only. No live Anthropic call or stored-data contract change is claimed.
  • proof: sufficient: Contributor real behavior proof is sufficient. Production Anthropic usage-owner runs with disposable stores and loopback HTTP fixtures demonstrate request suppression, preserved OAuth selection, and web fallback success/failure. Status CLI output adds entrypoint controls; the replacement changes tests only. No live Anthropic call or stored-data contract change is claimed.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the complete merge-base-to-head diff. Setup-token classification follows credential selection, preserves Admin API precedence, and uses stored profile type rather than token shape. (extensions/anthropic/usage.ts:273, 7d9318205a55)
  • Still necessary on main: Current main returns selected OAuth/token credentials directly to the OAuth usage fetcher; the stored-token suppression is absent. (extensions/anthropic/usage.ts:252, 80bab7e23ce0)
  • Latest-release comparison: Inspected the Anthropic usage resolver at the supplied latest release, v2026.9.5: it likewise returns stored token credentials without this classification. The related PRs are open, not merged fixes. (extensions/anthropic/usage.ts:252, ec9c1a13db89)
  • Accepted compatibility tradeoff: The captured PR body explicitly accepts suppressing OAuth usage for every selected stored Anthropic token profile, including pasted bearers that might possess usage scope. Its author, obviyus, has repository role maintain; GitHub commit metadata independently identifies that account as Ayaan Zaidi. The replacement preserves the accepted production implementation. (7d9318205a55)
  • Credential and compatibility boundary: Setup-token onboarding and Anthropic paste-token validate their input and write type token. The existing selector resolves credentials before forwarding the new optional profileType field. No stored format, credential writer, configuration option, or inference authorization changes; existing callback implementations remain source-compatible. (src/infra/provider-usage.auth.ts:355, 7d9318205a55)
  • After-fix production-path evidence: Captured sourceRevision 33d50bdc0b6ea8e882f8db25a23311381b45380d3eaf5fd05da4888aad23349d records production-owner runs with disposable auth stores and loopback HTTP fixtures: fresh/existing setup profiles make zero OAuth requests; web fallback returns 17% usage or an explicit failure; static and preferred OAuth credentials retain polling. Supported status CLI runs additionally show setup-token omission, OAuth usage at 23%, and a genuine 403 control. These are local runtime observations, not live Anthropic validation. The downloaded screenshot shows the original error only. (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.

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing this while preserving the web-session fallback, without widening the public plugin SDK, needs the ownership refactor described in #156296. Closing this proposal in favor of that work. Thank you @saariuslystoned and @RamiNoodle733 for investigating and contributing fixes.

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