Skip to content

fix(anthropic): resolve claude-code version at runtime for OAuth user-agent (fixes #94716) - #95205

Closed
Darren2030 wants to merge 3 commits into
openclaw:mainfrom
Darren2030:fix-claude-cli-user-agent-94716
Closed

Darren2030 wants to merge 3 commits into
openclaw:mainfrom
Darren2030:fix-claude-cli-user-agent-94716

Conversation

@Darren2030

@Darren2030 Darren2030 commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #94716. The Anthropic OAuth bearer path in both the legacy SDK provider and the native messages transport hardcoded the Claude Code user-agent version to 2.1.75. Anthropic now rejects that stale version, causing authentication_error: Invalid bearer token for users on newer Claude Code CLI installs.

This change reads the installed @anthropic-ai/claude-code package version at runtime and uses it in the user-agent: claude-cli/<version> header. If the package cannot be resolved or its version is invalid, the helper throws a clear configuration error instead of silently sending a stale fallback.

Changes

  • src/llm/utils/claude-code-version.ts: new helper that resolves the installed Claude Code version and builds the OAuth user-agent header.
  • src/llm/providers/anthropic.ts: replace hardcoded claudeCodeVersion = "2.1.75" with the runtime helper.
  • src/agents/anthropic-transport-stream.ts: replace hardcoded CLAUDE_CODE_VERSION constant with the runtime helper.
  • src/llm/utils/claude-code-version.test.ts: unit tests for version resolution, user-agent formatting, and invalid-value handling.
  • src/agents/anthropic-transport-stream.test.ts: set a test resolver and assert the exact OAuth user-agent value.
  • scripts/repro/issue-94716-claude-code-user-agent.mts: standalone reproduction script that simulates an installed Claude Code version and verifies the resolved user-agent.

Real behavior proof

  • Behavior addressed: OAuth user-agent header now uses the installed Claude Code version instead of a stale hardcoded value.
  • Real environment tested: Linux x64, Node.js v22.x, OpenClaw main branch in a local clone.
  • Exact steps or command run after this patch:
    • node --import tsx scripts/repro/issue-94716-claude-code-user-agent.mts
    • pnpm test src/llm/utils/claude-code-version.test.ts --run
    • pnpm test src/agents/anthropic-transport-stream.test.ts --run
    • pnpm test src/llm/providers/anthropic.test.ts --run
    • pnpm build
  • Evidence after fix:
=== Reproduction for issue #94716 ===
Installed Claude Code version (simulated): 2.1.177
Resolved user-agent: claude-cli/2.1.177
PASS: OAuth user-agent uses the installed claude-code version, not a stale hardcoded value.

Unit tests:

Test Files  2 passed (2)
     Tests  40 passed (40)
  • Observed result after fix: The reproduction resolves claude-cli/2.1.177 from a simulated installed package, confirming the header follows the installed CLI version. Existing Anthropic transport tests pass with the new runtime resolver.
  • What was not tested: A live OAuth request against Anthropic's API; the reproduction uses a local fake package.json and the unit/transport tests use mocked fetch.

Verification

  • node --import tsx scripts/repro/issue-94716-claude-code-user-agent.mts → PASS
  • pnpm test src/llm/utils/claude-code-version.test.ts --run → 5 passed
  • pnpm test src/agents/anthropic-transport-stream.test.ts --run → 76 passed
  • pnpm test src/llm/providers/anthropic.test.ts --run → 35 passed
  • npx oxlint --import-plugin --config .oxlintrc.json <changed files> → clean
  • pnpm format:check <changed files> → clean
  • pnpm build → success

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: S triage: blank-template Candidate: PR template appears mostly untouched. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jun 20, 2026
@clawsweeper

clawsweeper Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed July 3, 2026, 10:52 AM ET / 14:52 UTC.

Summary
The PR replaces both hardcoded Anthropic Claude Code OAuth user-agent constants with a shared runtime resolver, adds resolver and transport coverage, and adds a repro script.

PR surface: Source +98, Tests +76, Other +73. Total +247 across 6 files.

Reproducibility: yes. from source: current main and v2026.6.11 still send claude-cli/2.1.75 from both Anthropic OAuth builders, and the linked issue provides a concrete Windows/OpenClaw 2026.6.8 reproduction. I did not run a live Anthropic OAuth request in this read-only review.

Review metrics: 3 noteworthy metrics.

  • Synchronous command lookup: 1 added. The helper adds a blocking local command lookup to a provider path that constructs Anthropic OAuth headers.
  • Auth resolver fail-closed path: 1 added. The PR replaces a stale constant with discovery that can now stop OAuth request construction when no supported version source is found.
  • Current lint failures: 1 current diff-caused failure. The repro script currently fails the PR lint shard, so the head is not validation-clean even aside from the auth-provider design issue.

Stored data model
Persistent data-model change detected: serialized state: scripts/repro/issue-94716-claude-code-user-agent.mts, serialized state: src/llm/utils/claude-code-version.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #94716
Summary: This PR is a candidate fix for the canonical stale Anthropic OAuth user-agent bug; several sibling PRs attempt the same repair with different resolver designs.

Members:

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

Merge readiness
Overall: 🧂 unranked krab
Proof: 🦞 diamond lobster
Patch quality: 🧂 unranked krab
Result: blocked by patch quality or review findings.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Move version discovery to a prepared or cached provider/setup boundary and remove per-request execFileSync.
  • [P2] Add focused Windows/npm global CLI resolution proof or use a non-subprocess package/bin metadata source.
  • [P2] Fix the repro script lint failure on the catch callback variable.

Risk before merge

  • [P1] Merging as-is runs whichever claude executable is first on PATH while building Anthropic OAuth headers, broadening an auth-provider path into local command execution.
  • [P1] A missing, slow, incompatible, or unparseable CLI can add synchronous request latency or fail closed before the OAuth request is sent, changing upgrade behavior for existing users.
  • [P1] The linked report is a Windows npm-global install; the resolver calls execFileSync("claude") while its repro creates claude.cmd, leaving that reported path unproven.
  • [P1] The current head also has a diff-caused lint failure in the repro script.

Maintainer options:

  1. Prepare A Cross-Platform Version Before Requests (recommended)
    Resolve and cache the Claude Code version at an owned setup or provider boundary, handle Windows npm shims or package metadata explicitly, and have both OAuth builders consume that prepared value.
  2. Accept Request-Path Discovery Explicitly
    Maintainers may intentionally accept per-request PATH command execution and fail-closed behavior for the urgent auth fix, but that should be an explicit auth-provider compatibility decision.
  3. Pause For A Cleaner Sibling PR
    If maintainers prefer a non-subprocess or fixed-version implementation, pause this branch and continue with the same-root-cause PR that best matches the desired auth-provider policy.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Move Claude Code version resolution out of Anthropic OAuth request/header construction: keep the shared helper and both call sites, cache or prepare the version at an owned setup/provider initialization boundary, avoid per-request `execFileSync("claude", ["--version"])`, handle Windows npm CLI shims or package metadata explicitly, preserve clear diagnostics when no supported source can be resolved, fix the repro script lint failure, and update the helper/provider/transport tests plus the repro script.

Next step before merge

  • [P2] Queue a focused repair because the stale-header fix is valid and the remaining blockers are concrete code changes in the resolver and repro script.

Security
Needs attention: The diff introduces ambient PATH command execution into an Anthropic OAuth header path.

Review findings

  • [P1] Resolve Claude version outside the auth request path — src/llm/utils/claude-code-version.ts:35-38
  • [P1] Handle Windows npm shims before relying on execFile — src/llm/utils/claude-code-version.ts:35
  • [P3] Annotate the repro catch variable as unknown — scripts/repro/issue-94716-claude-code-user-agent.mts:70
Review details

Best possible solution:

Keep the two-call-site stale-header fix, but prepare and cache a cross-platform Claude Code version at an owned setup or provider boundary before OAuth request construction.

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

Yes from source: current main and v2026.6.11 still send claude-cli/2.1.75 from both Anthropic OAuth builders, and the linked issue provides a concrete Windows/OpenClaw 2026.6.8 reproduction. I did not run a live Anthropic OAuth request in this read-only review.

Is this the best way to solve the issue?

No: fixing both OAuth builders is the right scope, but synchronous first-on-PATH CLI discovery during header construction is not the safest owner boundary. A prepared and cached cross-platform version source before request construction is the better fix.

Full review comments:

  • [P1] Resolve Claude version outside the auth request path — src/llm/utils/claude-code-version.ts:35-38
    Both patched OAuth builders call claudeCodeUserAgent() while constructing headers, and the default resolver synchronously executes the first claude on PATH with a 2s timeout before package fallback. That makes Anthropic OAuth request/client construction depend on ambient command execution and can stall or fail closed for existing users; resolve and cache this at an owned setup or provider boundary instead.
    Confidence: 0.9
  • [P1] Handle Windows npm shims before relying on execFile — src/llm/utils/claude-code-version.ts:35
    The linked bug is reported on Windows with a global npm Claude Code install, and this PR's repro creates claude.cmd on Windows, but the resolver calls execFileSync("claude"). Node's child_process docs say .cmd files cannot be launched by execFile() without a terminal, so the reported install path remains unproven; resolve the package/bin source or explicit shim path instead.
    Confidence: 0.86
  • [P3] Annotate the repro catch variable as unknown — scripts/repro/issue-94716-claude-code-user-agent.mts:70
    The current check-lint job fails on this catch callback because repository lint requires catch variables to be typed as unknown. Updating the callback type keeps the repro script validation-clean.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e272da5c5579.

Label changes

Label justifications:

  • P1: The PR targets a current Anthropic OAuth failure that can block Claude subscription-backed gateway and agent runs.
  • merge-risk: 🚨 compatibility: The patch changes shipped OAuth behavior from a hardcoded header to runtime discovery that can fail for existing installs or upgrades.
  • merge-risk: 🚨 auth-provider: The changed header is part of Anthropic OAuth bearer authentication and directly affects Claude subscription-backed provider requests.
  • merge-risk: 🚨 availability: A synchronous CLI lookup with a timeout can stall or fail Anthropic request/client construction before a request is sent.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): Contributor terminal proof exercises the production resolver through a fake PATH claude binary and reports a real installed Linux CLI check; this is sufficient for the changed resolver/header behavior, though not a live Anthropic OAuth round trip.
  • proof: sufficient: Contributor real behavior proof is sufficient. Contributor terminal proof exercises the production resolver through a fake PATH claude binary and reports a real installed Linux CLI check; this is sufficient for the changed resolver/header behavior, though not a live Anthropic OAuth round trip.
Evidence reviewed

PR surface:

Source +98, Tests +76, Other +73. Total +247 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 104 6 +98
Tests 2 78 2 +76
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 73 0 +73
Total 6 255 8 +247

Security concerns:

  • [medium] PATH command execution in OAuth header construction — src/llm/utils/claude-code-version.ts:35
    execFileSync("claude", ["--version"]) runs whichever executable appears first on PATH while constructing Anthropic OAuth headers. Even without a shell and with a timeout, this broadens an auth-provider request path into local command execution and should move to a prepared/cached boundary.
    Confidence: 0.86

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/llm/utils/claude-code-version.test.ts.
  • [P1] node scripts/run-vitest.mjs src/agents/anthropic-transport-stream.test.ts.
  • [P1] node scripts/run-vitest.mjs src/llm/providers/anthropic.test.ts.
  • [P1] node --import tsx scripts/repro/issue-94716-claude-code-user-agent.mts.
  • [P1] pnpm build.

What I checked:

  • Current main legacy provider still uses stale OAuth header: Current main defines claudeCodeVersion = "2.1.75" and uses it for the Anthropic OAuth bearer user-agent. (src/llm/providers/anthropic.ts:98, e272da5c5579)
  • Current main native transport still uses stale OAuth header: Current main separately defines CLAUDE_CODE_VERSION = "2.1.75" and uses it for the native Anthropic Messages OAuth user-agent. (src/agents/anthropic-transport-stream.ts:74, e272da5c5579)
  • Latest release still contains the stale constants: Tag v2026.6.11 still contains the same stale 2.1.75 constants in the Anthropic provider and native transport paths. (src/llm/providers/anthropic.ts:93, e085fa1a3ffd)
  • PR resolver runs a synchronous PATH command: The proposed helper calls execFileSync("claude", ["--version"], { timeout: 2000 }) before package fallback. (src/llm/utils/claude-code-version.ts:35, 1ae8d6024d55)
  • PR wires both OAuth builders to the resolver: Both the legacy SDK provider and native transport call claudeCodeUserAgent() while building OAuth headers. (src/llm/providers/anthropic.ts:1010, 1ae8d6024d55)
  • Node child_process contract checked: Official Node child_process docs say execFileSync() blocks the event loop and .bat/.cmd files cannot be launched through execFile() on Windows without a terminal.

Likely related people:

  • vincentkoc: Recent GitHub path history shows repeated work in both affected Anthropic provider and native transport files, including bearer-auth and stream-path changes. (role: recent area contributor; confidence: medium; commits: 9e6332338855, 066700bdd0e4, e3b619505c07; files: src/llm/providers/anthropic.ts, src/agents/anthropic-transport-stream.ts)
  • steipete: Recent history shows Anthropic provider and Claude CLI adjacent work across the same owner boundary, including provider fixes and CLI backend documentation. (role: adjacent contributor and merger; confidence: medium; commits: a02813164dd5, d89ad161241b, bb46b79d3c14; files: src/llm/providers/anthropic.ts, src/agents/anthropic-transport-stream.ts, extensions/anthropic/cli-backend.ts)
  • anagnorisis2peripeteia: Recent Claude CLI backend changes touched the installed CLI execution policy that this resolver tries to interrogate. (role: adjacent Claude CLI backend contributor; confidence: low; commits: 298a0cd55f5e, 3d7523b61807; files: extensions/anthropic/cli-backend.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jun 20, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Jun 20, 2026
@Darren2030

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated real behavior proof from a fresh run on this branch:

Environment: Linux x64, Node.js v22.x, openclaw/openclaw@main + this PR

Reproduction script (scripts/repro/issue-94716-claude-code-user-agent.mts):

=== Reproduction for issue #94716 ===
Installed Claude Code version (simulated): 2.1.177
Resolved user-agent: claude-cli/2.1.177
PASS: OAuth user-agent uses the installed claude-code version, not a stale hardcoded value.

Unit / integration tests:

pnpm test src/llm/utils/claude-code-version.test.ts --run
Test Files  1 passed (1)
Tests       5 passed (5)

pnpm test src/agents/anthropic-transport-stream.test.ts --run
Test Files  1 passed (1)
Tests       76 passed (76)

pnpm test src/llm/providers/anthropic.test.ts --run
Test Files  1 passed (1)
Tests       35 passed (35)

Lint / format / build:

npx oxlint --import-plugin --config .oxlintrc.json \
  src/llm/utils/claude-code-version.ts \
  src/llm/providers/anthropic.ts \
  src/agents/anthropic-transport-stream.ts \
  src/llm/utils/claude-code-version.test.ts \
  src/agents/anthropic-transport-stream.test.ts
→ clean

pnpm format:check <changed files>
→ All matched files use the correct format.

pnpm build
→ success (tsdown + ui:build + postbuild checks all green)

The reproduction uses a real temporary node_modules/@anthropic-ai/claude-code/package.json and exercises the actual production resolver path, confirming the OAuth user-agent tracks the installed CLI version instead of the stale hardcoded 2.1.75.

@clawsweeper

clawsweeper Bot commented Jun 20, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@Darren2030

Copy link
Copy Markdown
Contributor Author

Updated the implementation and proof for #94716.

Key change since the last review: the resolver now prefers claude --version (the supported install source) and falls back to @anthropic-ai/claude-code/package.json only when the CLI is not on PATH. This matches the issue reporter's environment where claude is installed globally via npm install -g @anthropic-ai/claude-code.

The resolver still never silently falls back to the stale hardcoded 2.1.75; any resolution failure surfaces as a clear configuration error.

Fresh verification:

  • node --import tsx scripts/repro/issue-94716-claude-code-user-agent.mts → PASS
  • pnpm test src/llm/utils/claude-code-version.test.ts --run → 10 passed
  • pnpm test src/agents/anthropic-transport-stream.test.ts --run → 76 passed
  • pnpm test src/llm/providers/anthropic.test.ts --run → 35 passed
  • npx oxlint --import-plugin --config .oxlintrc.json <changed files> → clean
  • pnpm format:check <changed files> → clean
  • pnpm build → success

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 20, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@Darren2030

Darren2030 commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addressed the P1 finding about resolver ownership:

  • The default resolver now first runs claude --version (the supported external CLI install source) and parses the leading semver. This matches the layout described in extensions/anthropic/cli-backend.ts:30 where the supported package is @anthropic-ai/claude-code with binary claude.
  • If the claude binary is not on PATH or its output is unparseable, it falls back to resolving @anthropic-ai/claude-code/package.json from the Node module graph, so dependency installs still work.
  • In all failure cases it throws a configuration error; there is no silent fallback to the stale 2.1.75 value.

Updated real behavior proof:

  • node --import tsx scripts/repro/issue-94716-claude-code-user-agent.mts now simulates an installed claude binary via PATH injection and verifies claude-cli/2.1.177 is resolved.
  • Direct local CLI verification: claudeCodeUserAgent() returns claude-cli/2.1.154 against the real installed claude on this Linux host.
  • Tests: pnpm test src/llm/utils/claude-code-version.test.ts --run → 10 passed; transport and provider tests also pass.
  • Build: pnpm build succeeds.
  • Lint/format: oxlint and oxfmt clean on changed files.

Also added unit coverage for the CLI output parser and the non-digit-leading string validation.

@clawsweeper clawsweeper Bot added 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. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jun 20, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jun 20, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jun 21, 2026
@Darren2030 Darren2030 closed this Jul 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. triage: blank-template Candidate: PR template appears mostly untouched.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Anthropic claude-cli provider sends stale user-agent (claude-cli/2.1.75) — bearer auth fails with authentication_error

1 participant