Skip to content

fix(anthropic): report the installed claude-cli version on the OAuth path - #150790

Closed
KrasimirKralev wants to merge 11 commits into
openclaw:mainfrom
KrasimirKralev:fix/anthropic-installed-claude-code-version
Closed

KrasimirKralev wants to merge 11 commits into
openclaw:mainfrom
KrasimirKralev:fix/anthropic-installed-claude-code-version

Conversation

@KrasimirKralev

@KrasimirKralev KrasimirKralev commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

On the subscription (OAuth) path the Anthropic transport presents itself as claude-cli/<version> with the version pinned in the bundle (ANTHROPIC_CLAUDE_CODE_VERSION = "2.1.75"). Anthropic gates its newest models on that number, so every Fable 5.1 turn on a subscription login fails:

HTTP 400 {"type":"error","error":{"type":"invalid_request_error","message":"Claude Code 2.1.75 does not support this model; version 2.1.251 or newer is required. …","details":{"error_code":"claude_code_version_too_old"}}}

The same login works from a Hermes agent on the same machine, because that adapter reports the version of the CLI actually installed there. main and the 2026.9.4 release still pin 2.1.75 (canonical issue #94716).

Change

  • @openclaw/ai keeps the pinned value as the fallback and gains setAnthropicClaudeCodeVersion / getAnthropicClaudeCodeVersion; the billing system block is computed from the current value. The package still spawns nothing.
  • The host (src/llm/ai-transport-host.ts, beside the redactor wiring) asks the installed CLI once per process — claude --version, then claude-code --version — through the repository's command runner (runCommandWithTimeout, the same one src/agents/workspace.ts uses for git --version), so npm's claude.cmd shim on Windows launches through its trusted cmd.exe wrapping. 3 s timeout, 16 KiB output bound, hidden window. The probe settles on the first line the CLI prints and lets the runner stop the command in the background: some installs keep running after printing their version, and waiting for the exit held the identity gate past its bound. It adopts the printed version only when it is newer than the fallback. No CLI, a slow one, an unexpected line, or an older install leaves the fallback exactly as it is today.
  • Initialization ordering: the probe registers itself as identity startup work in @openclaw/ai (deferAnthropicClaudeCodeIdentityUntil, bounded at 7 s). In both client builders (providers/anthropic.ts createClient, transports/anthropic-transport-client.ts createAnthropicTransportClient) the auth route is decided from the key first; only an OAuth request then does await resolveAnthropicClaudeCodeIdentity() as its very first await — before the guarded fetch, the headers or the SDK client are built — and that single snapshot feeds both the user-agent header and the billing system block (buildAnthropicSystemBlocks takes the block as a parameter). API-key, Copilot, Foundry, Cloudflare-gateway and injected-SDK-client routes never touch the gate. A probe that fails or never settles leaves the fallback and never fails a request.
  • Layout: the transport's client construction (auth routing, headers, guarded fetch) moved from anthropic-transport-stream.ts into the sibling anthropic-transport-client.ts (behavior-preserving; the stream module was over the repository's line cap and may not grow). The new request-boundary tests live in sibling *.claude-code-identity.test.ts files for the same reason; the two existing test files are byte-identical to main.
  • What did NOT change: nothing is ever reported that the machine does not print itself; API-key requests carry no identity headers and no longer wait for anything; no new config, env var, or dependency; the @openclaw/ai package still performs no process spawning; the pinned constant is unchanged.

Evidence

Real environment: Ubuntu 24.04 x64, Node 24.21, this branch at b26ed3f03f (the current head), a real Anthropic subscription OAuth profile (sk-ant-oat…, redacted), the real host wiring (src/llm/ai-transport-host.ts — its probe and identity registration, the real buildModelFetch), the production Anthropic Messages transport from @openclaw/ai/transports, live https://api.anthropic.com/v1/messages. The only variable between the two arms is whether the installed CLI is reachable on PATH. Requests target anthropic/claude-fable-5-1, the gated model.

Exact command run at this head (each arm), from the repo root:

node --import ./scripts/tsx.mjs .artifacts/proof/run-oauth-proof.mts

Before (installed CLI hidden from PATH → the pinned fallback, i.e. what main sends):

claude on PATH: no (PATH stripped of /home/…/.local/bin)
identity settled before request: version=2.1.75 user-agent=claude-cli/2.1.75
request headers: {"user-agent":"claude-cli/2.1.75","x-app":"cli","authorization":"Bearer sk-ant-oat…[redacted]"}
request billing block: x-anthropic-billing-header: cc_version=2.1.75; cc_entrypoint=sdk-cli;
HTTP status: 400
stopReason: error
error: 400: {"error":{"details":{"error_code":"claude_code_version_too_old"},"message":"Claude Code 2.1.75 does not support this model; version 2.1.251 or newer is required. …"},"type":"error"}

After (installed CLI on PATH → detected, awaited and reported; identity settled before the request was built):

claude on PATH: yes (2.1.274 (Claude Code))
identity settled before request: version=2.1.274 user-agent=claude-cli/2.1.274
request headers: {"user-agent":"claude-cli/2.1.274","x-app":"cli","authorization":"Bearer sk-ant-oat…[redacted]"}
request billing block: x-anthropic-billing-header: cc_version=2.1.274; cc_entrypoint=sdk-cli;
HTTP status: 200
stopReason: stop
assistant: "ok"

Observed result after fix: running node against the live API through the direct OAuth transport, the request carries the detected version in both the user-agent header and the billing block (same number, one snapshot), and the gated model answers with HTTP 200 where the pinned identity was refused with claude_code_version_too_old. The identity was resolved before client construction in a fresh process whose probe was started at import time.

Why the proof was re-run on this head: an earlier head's probe waited for the CLI to exit and silently kept the fallback on this machine (the CLI lingered after printing), and the identity await sat behind the host's first-use fetch-builder work, which outlasted the gate. Both were caught by re-running this proof, not by the unit tests, and are fixed here (first-line settle; identity awaited before any other request work).

What was not tested: an upgrade in place (installing a newer CLI while a Gateway is already running — by design the version is probed once per process, so that takes a Gateway restart); the Windows .cmd launch itself (Linux host; the runner's cmd.exe wrapping is covered by src/process/exec.windows.test.ts, and the probe's use of the runner by src/llm/anthropic-claude-code-version.test.ts); a probe that never prints anything for the full 7 s bound (covered by the timeout path in the identity gate rather than a live run).

Proof limitations: the proof script imports the same transport and host modules the Gateway loads, but drives them directly rather than through a full Gateway boot; the token is read from a 0600 file and never printed.

Tests

  • packages/ai/src/providers/anthropic-claude-code-identity.test.ts (new): the identity gate — resolves immediately with the fallback when nothing is registered; waits for registered work and reports the adopted version; proceeds with what is known when the bound elapses; a failed probe means nothing adopted, never a failed request; user-agent and billing block derive from one read.
  • packages/ai/src/providers/anthropic.claude-code-identity.test.ts and packages/ai/src/transports/anthropic-transport-stream.claude-code-identity.test.ts (new, request boundary): with a probe that has not answered, an OAuth request is not sent until it settles and then carries the adopted version in the user-agent header and the billing block; an API-key request is sent immediately and carries neither; the identity is resolved before the fetch builder runs.
  • src/llm/anthropic-claude-code-version.test.ts: adopt newer, refuse older/equal/malformed, keep the newest seen, parse the CLI's 2.1.273 (Claude Code) line, fall through to the second command name, survive a throwing probe, probe once per process, make resolveAnthropicClaudeCodeIdentity wait for the probe, route the default probe through the shared runner, settle on the first printed line without waiting for a lingering CLI, report nothing when the launch fails.
  • Existing anthropic.test.ts, anthropic-transport-stream.test.ts, anthropic-payload-policy.test.ts unchanged and green: 284 tests across the seven files above. tsgo:core, oxlint, oxfmt --check, git diff --check, the line-cap / max-lines / assertion-safety ratchets against main, and the production knip scan pass on the changed files.

…path

On the subscription (OAuth) path the Anthropic transport presents itself
as `claude-cli/<version>` with the version pinned in the bundle (2.1.75).
Anthropic gates its newest models on that number: a Fable 5.1 request is
refused with HTTP 400 "version 2.1.251 or newer is required" — while the
same login works through the Anthropic CLI that is installed beside
OpenClaw, because that one is newer.

The pinned value stays as the fallback. The host now asks the installed
CLI what it is (`claude --version`, once per process, best effort) and
reports that version in the user-agent and the billing header when it is
newer than the fallback. Nothing is reported that the machine does not
print itself: no CLI, a slow one, or an unexpected output leaves the
fallback; an older install is never adopted.

`@openclaw/ai` stays free of process spawning — it gains
`setAnthropicClaudeCodeVersion` / `getAnthropicClaudeCodeVersion` and
computes the billing block from the current value; the probe lives with
the other host wiring in `src/llm/ai-transport-host.ts`.
@clawsweeper

clawsweeper Bot commented Sep 17, 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 size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 17, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. 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 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 17, 2026, 8:53 AM ET / 12:53 UTC (Revision 8).

ClawSweeper review

What this changes

Detects the installed Claude CLI version at startup and uses one consistent version in Anthropic OAuth headers and billing metadata, retaining the existing fallback.

Merge readiness

⛔ Blocked before merge - 5 items remain

This remains a useful fix for an unfixed OAuth failure, but the probe bypasses its advertised output bound. The updated Linux live evidence is valid; the previously requested Windows evidence remains outstanding.

Priority: P1
Reviewed head: b26ed3f03f3284fb9cf0f5509d03ef9dce02cac0

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful implementation with convincing Linux recovery evidence, one concrete resource-bound defect, and outstanding Windows proof.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The current-head Ubuntu trace sufficiently proves production host discovery, matching OAuth identity fields, and live HTTP 400-to-200 recovery. Preserve that evidence: the remaining gap is the explicitly untested Windows npm-shim launch and cleanup claim requested previously, not a missing full-Gateway run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The current-head Ubuntu trace sufficiently proves production host discovery, matching OAuth identity fields, and live HTTP 400-to-200 recovery. Preserve that evidence: the remaining gap is the explicitly untested Windows npm-shim launch and cleanup claim requested previously, not a missing full-Gateway run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 10 items Current main still carries the stale identity: Fetched main retains the fixed 2.1.75 value and derives the billing block from it; installed-version adoption is not present in this owner.
Latest release retains the same fallback: The v2026.9.4 source also pins 2.1.75. The release blob was recovered through the read-only GitHub contents API after local historical-blob inspection failed.
Earlier functional findings are addressed: Both request builders await the identity only on their OAuth route and pass the resulting snapshot into payload construction. The host probe now uses runCommandWithTimeout, addressing the earlier bare-launcher finding.
Findings 1 actionable finding [P2] [P2] Bound raw stdout before accumulating probe output
Security None None.

How this fits together

OpenClaw’s Anthropic adapters turn model requests and credentials into API calls. The host discovers the installed CLI version, and OAuth requests use that value when presenting their client identity to Anthropic.

flowchart LR
  A[Installed Claude CLI] --> B[Host version probe]
  B --> C[Shared version or fallback]
  D[Model request and credential] --> E{OAuth route?}
  C --> F[Consistent request identity]
  E -->|Yes| F
  E -->|No| G[Existing request construction]
  F --> H[Anthropic API]
  G --> H
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The current-head Ubuntu trace sufficiently proves production host discovery, matching OAuth identity fields, and live HTTP 400-to-200 recovery. Preserve that evidence: the remaining gap is the explicitly untested Windows npm-shim launch and cleanup claim requested previously, not a missing full-Gateway run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • [P2] Bound raw stdout before accumulating probe output (P2) - If the installed CLI or a PATH wrapper emits a long stream without a newline, printed grows without the advertised 16 KiB limit and each chunk rescans the accumulated string. runCommandWithTimeout passes raw chunks to this observer before bounded capture, and terminateOnOutputLimit is unset, so maxOutputBytes does not protect this buffer. Cap accumulation by bytes and stop with the fallback when exceeded, with a regression covering oversized newline-free output. This concern was missed previously; the same accumulation exists at the earlier reviewed head 497abc1553e8f56eefd9dfd180b8f47e1942e1d7.
  • Resolve merge risk (P1) - Unexpected newline-free CLI output can consume substantially more startup memory and CPU than the stated 16 KiB limit permits.
  • Resolve merge risk (P1) - Windows npm-shim discovery and early-stop cleanup remain unverified on Windows.
  • Complete next step (P2) - Repair the uncapped stdout accumulator and complete the outstanding Windows discovery/cleanup proof. Redact credentials, private paths, and endpoints before posting; the current Linux live evidence is accepted.

Findings

  • [P2] [P2] Bound raw stdout before accumulating probe output — src/llm/anthropic-claude-code-version.ts:57-59
Agent review details

Security

None.

PR surface

Source +380, Tests +590, Other +4. Total +974 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 8 800 420 +380
Tests 4 590 0 +590
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 5 1 +4
Total 14 1395 421 +974

Review metrics

Metric Value Why it matters
Production versus test growth Production +380 lines; tests +590; tooling +4 The stated production-growth rationale is shared identity readiness and host discovery; the client extraction primarily relocates existing behavior.
OAuth startup wait Up to 7 seconds, shared per process Only OAuth requests wait for discovery; other authentication routes bypass this gate.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #94716
Summary: This PR addresses the canonical issue’s stale direct-OAuth identity for hosts with a sufficiently recent installed CLI; it does not resolve every fallback case.

Members:

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

Merge-risk options

Maintainer options:

  1. Enforce the probe’s actual memory bound (recommended)
    Bound raw stdout accumulation before decoding or concatenation, stop discovery on oversized output, and retain the fallback.

Technical review

Best possible solution:

Keep one bounded host probe and one consistent per-request OAuth identity, preserving the existing fallback and unaffected authentication routes.

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

Yes: current main retains the stale identity, and supplied live A/B traces demonstrate rejection and recovery. The newly identified output-bound defect is source-proven; no target code was executed during this review.

Is this the best way to solve the issue?

No, not quite yet: the shared identity and host-owned discovery are appropriate, but the observer must enforce the advertised output bound.

Full review comments:

  • [P2] [P2] Bound raw stdout before accumulating probe output — src/llm/anthropic-claude-code-version.ts:57-59
    If the installed CLI or a PATH wrapper emits a long stream without a newline, printed grows without the advertised 16 KiB limit and each chunk rescans the accumulated string. runCommandWithTimeout passes raw chunks to this observer before bounded capture, and terminateOnOutputLimit is unset, so maxOutputBytes does not protect this buffer. Cap accumulation by bytes and stop with the fallback when exceeded, with a regression covering oversized newline-free output. This concern was missed previously; the same accumulation exists at the earlier reviewed head 497abc1553e8f56eefd9dfd180b8f47e1942e1d7.
    Confidence: 0.97
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: Recent release reports and current-head live evidence establish broken Anthropic subscription model requests.
  • merge-risk: 🚨 availability: The new startup probe retains uncapped raw stdout despite configuring a bounded runner capture.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The current-head Ubuntu trace sufficiently proves production host discovery, matching OAuth identity fields, and live HTTP 400-to-200 recovery. Preserve that evidence: the remaining gap is the explicitly untested Windows npm-shim launch and cleanup claim requested previously, not a missing full-Gateway run. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current main still carries the stale identity: Fetched main retains the fixed 2.1.75 value and derives the billing block from it; installed-version adoption is not present in this owner. (packages/ai/src/providers/anthropic-model-contract.ts:38, 3c0fb2025a1d)
  • Latest release retains the same fallback: The v2026.9.4 source also pins 2.1.75. The release blob was recovered through the read-only GitHub contents API after local historical-blob inspection failed. (packages/ai/src/providers/anthropic-model-contract.ts:38, 3a9d69db306c)
  • Earlier functional findings are addressed: Both request builders await the identity only on their OAuth route and pass the resulting snapshot into payload construction. The host probe now uses runCommandWithTimeout, addressing the earlier bare-launcher finding. (packages/ai/src/providers/anthropic.ts:477, b26ed3f03f32)
  • Current-head live API evidence: The supplied body, captured under sourceRevision 6f1980cef6d6c0fb49ab37b220d14762679575827b3c330d7c1716fa4d516fc7, records Ubuntu 24.04 and Node 24.21 using the production host wiring and Messages transport at this head. Hiding the CLI yields version 2.1.75 and HTTP 400; exposing installed version 2.1.274 yields matching header/billing values, HTTP 200, and assistant output. This directly demonstrates recovery without requiring a full Gateway boot. (src/llm/ai-transport-host.ts:30, b26ed3f03f32)
  • Probe accumulator bypasses the output bound: The observer appends every raw stdout chunk to printed until a newline arrives. The shared runner invokes this observer before bounded capture; maxOutputBytes limits its own capture, while termination on exceeding that limit is opt-in and unset here. (src/llm/anthropic-claude-code-version.ts:57, b26ed3f03f32)
  • Runner contract confirms the uncapped observer: Raw output reaches onOutputChunk independently of captured-output truncation. shouldTerminateOnOutputLimit returns false for an unspecified option, so the probe’s separate accumulator has no 16 KiB ceiling. (src/process/exec-runner.ts:446, b26ed3f03f32)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Enforce the stdout accumulator’s byte limit and cover oversized output without a newline.
  • Add redacted Windows npm-shim discovery and cleanup evidence; update the PR body to trigger re-review, or ask a maintainer to comment @clawsweeper re-review.

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 (7 earlier review cycles)
  • reviewed 2026-09-17T10:01:41.318Z sha a623d17 :: needs real behavior proof before merge. :: [P2] Await version adoption before building OAuth requests
  • reviewed 2026-09-17T10:31:24.664Z sha a623d17 :: needs real behavior proof before merge. :: [P2] Await version adoption before building OAuth requests
  • reviewed 2026-09-17T10:55:23.443Z sha 5d9faca :: needs changes before merge. :: [P2] Restrict the discovery wait to OAuth requests | [P2] Use the Windows-aware command runner for CLI discovery
  • reviewed 2026-09-17T11:52:20.573Z sha b703bdc :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-17T12:12:38.511Z sha f81de85 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-17T12:23:52.165Z sha 704d2df :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-17T12:41:40.595Z sha 497abc1 :: needs real behavior proof before merge. :: none

…requests

The host probe that adopts the installed CLI version ran unawaited, so the
first direct OAuth request of a fresh process could still go out as the pinned
2.1.75 while a newer install was being detected, and the managed transport
read the version twice per request (user-agent at client construction,
billing block after message conversion), so a probe finishing in between
produced two versions in one request.

The probe now registers itself as identity startup work in @openclaw/ai
(deferAnthropicClaudeCodeIdentityUntil, bounded at 7 s); both transports await
resolveAnthropicClaudeCodeIdentity() once, before constructing the client, and
thread that single snapshot into the user-agent header and the billing system
block. A probe that fails or never settles leaves the pinned fallback and
never fails a request.

Tests: the identity gate (waits, one snapshot, bounded, failure-safe); both
transports through the request boundary with a delayed probe (fetch not
called until it settles; user-agent and billing block carry the same adopted
version); the host probe making resolveAnthropicClaudeCodeIdentity wait.
@openclaw-barnacle openclaw-barnacle Bot added size: L and removed size: M triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Sep 17, 2026
@KrasimirKralev

Copy link
Copy Markdown
Contributor Author

Addressed the P2 finding in 5d9facaa (current head).

  • adoptInstalledClaudeCodeVersion() now registers its probe as identity startup work in @openclaw/ai (deferAnthropicClaudeCodeIdentityUntil, bounded at 7 s).
  • Both request builders (providers/anthropic.ts and transports/anthropic-transport-stream.ts) await resolveAnthropicClaudeCodeIdentity() once, before constructing the client, and thread that single snapshot into the user-agent header and the billing system block. The managed adapter no longer reads the version on both sides of convertAnthropicMessages, so the two fields cannot disagree.
  • A probe that fails or never settles leaves the pinned fallback and never fails a request.

PR body now carries the after-fix production-path evidence: one node run through this branch's host wiring and the direct OAuth transport against the live Anthropic API, once with the installed CLI hidden from PATH (2.1.75 reported, HTTP 400 claude_code_version_too_old) and once with it on PATH (2.1.274 in both the user-agent header and the billing block, HTTP 200, assistant answered "ok"). The identity was settled before the request was built in both arms; the only variable between them is the CLI on PATH.

Request-boundary tests in both adapters cover the wait: no request is sent until the probe settles, then one version appears in both fields.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 17, 2026
Both Anthropic adapters awaited the installed-CLI discovery gate as the first
step of a request, before auth routing, so while a fresh process was still
probing, an API-key request, a Copilot or Foundry request and an injected SDK
client all waited up to 7 s for an identity none of them ever sends.

The wait now happens inside the OAuth branch of each client builder, after the
auth route is decided. That branch returns the snapshot it resolved, the
callers thread it into the billing system block, and every other route builds
its client and its params without touching the gate.

Tests: with a probe still pending, an API-key request reaches the client and
the wire immediately and carries neither a claude-cli user-agent nor a billing
block, in the provider and in the native transport; the existing OAuth tests
still prove the wait and one version in both fields.
The version probe spawned `claude --version` with a bare execFile. On Windows
npm installs the CLI as a `claude.cmd` shim, which that spawn cannot launch —
windowsHide adds no batch-file handling — so both candidate commands failed and
the OAuth path silently kept reporting the pinned 2.1.75.

It now goes through runCommandWithTimeout, the runner the rest of src/ uses for
short buffered commands and the one whose trusted cmd.exe wrapping is covered
by src/process/exec.windows.test.ts. The contract is unchanged: 3 s timeout,
16 KiB of captured output, hidden window, first line of stdout, null on any
failure, never throwing, and the probe injection point stays for tests.

Tests: the default probe calls the runner with the expected argv and bounds,
and reports nothing when the launch rejects or the command exits nonzero.
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 17, 2026
…line

The probe waited for the CLI to exit, but an install can keep running after
printing its version, so the runner hit the 3 s timeout and the probe reported
nothing although the version had already arrived: the OAuth request went out
with the pinned fallback again.

The probe now stops the command as soon as the first stdout line is complete
and reports that line; the exit code says nothing about a line that already
arrived, and a launch failure still rejects into the fallback. Test: a runner
that prints the version and lingers is stopped and its version adopted.
Waiting for the runner to stop a lingering CLI held the identity gate past
its bound: on this machine the installed CLI printed its version at once but
took eight seconds to stop, so the first OAuth request still went out with
the pinned fallback. The probe now resolves as soon as the first stdout line
is complete and leaves the runner to stop the command in the background,
bounded by its timeout.
…g files

Both big Anthropic test files are over the 1000-line cap and grandfathered by
the fast-baseline ratchet, so the identity request-boundary tests added here
made them grow and the ratchet rejected the branch.

The two pairs move into focused siblings with their own minimal harness (the
SDK constructor mock for the provider, a host fetch mock for the transport):
the OAuth request that waits for a pending installed-CLI probe and carries one
version in both the user-agent and the billing block, and the API-key request
that must not wait and carries neither. No assertion changed, and the two big
files are back at or under their ratchet counts.
The native Messages transport module is over its 700-line cap and grew again
here, so the fast-baseline ratchet rejected the branch.

Client construction moves to a sibling module: base-URL resolution, the
SSE-backed HTTP client, and the auth routing that decides which credential and
which identity headers one request carries — subscription OAuth, Copilot and
Foundry bearer, gateway and plain API key. The stream module keeps payload
building, the response contract and the stream function, and imports the client
back; the Messages endpoint URL stays on its public surface, where callers
outside the package already find it. Behavior is unchanged.

The moved JSON.parse assertion now carries the SAFETY invariant the assertion
ratchet asks of a new file, so the stream module's baseline shrinks by one.
…st work

Both client builders reached the OAuth branch only after running the work above
it — most of all the host's guarded model fetch, which loads plugin metadata
and takes seconds on a cold process. The identity gate is bounded from the
probe's start, so that work spent the budget and the first subscription request
of a fresh process still went out as the pinned 2.1.75, which is what the live
proof on this branch showed.

The auth route is now decided from the credential first, and the identity is
awaited as the very first await when that route is OAuth; the branch itself
consumes the snapshot, so one request still carries one version in the
user-agent and the billing block. Every other route — gateway, Copilot,
Foundry, plain API key, injected client — still never touches the gate.

Tests: the request-boundary tests now assert the order, so a slow fetch builder
cannot change which version an OAuth request carries.
The production scan flags the version parser and the once-per-process reset
seam as unused exports: only the focused probe tests consume them, while
production reaches the probe through adoptInstalledClaudeCodeVersion. Record
that in the ignore map next to the other test-only seams.
@KrasimirKralev

Copy link
Copy Markdown
Contributor Author

Both P2 findings from the third review are addressed; head is b26ed3f0.

  • Discovery wait restricted to OAuth requests — ec64def8, tightened in 59fb16dc: each client builder decides the auth route from the key first; only an OAuth request awaits resolveAnthropicClaudeCodeIdentity(), and it does so as its very first await, before the guarded fetch, headers or SDK client are built. API-key, Copilot, Foundry, Cloudflare-gateway and injected-SDK-client routes never touch the gate. Request-boundary tests (now in sibling *.claude-code-identity.test.ts files): with a probe still pending, an API-key request reaches the wire immediately and carries neither a claude-cli user-agent nor a cc_version block; the OAuth request waits and carries one version in both fields; the identity is resolved before the fetch builder runs.
  • CLI discovery through the Windows-aware runner — b703bdc4, then f81de859 / 065e5cf9 / b26ed3f0: the probe goes through runCommandWithTimeout (src/process/exec.ts), the runner src/agents/workspace.ts uses for git --version; its trusted cmd.exe wrapping of .cmd shims is covered by src/process/exec.windows.test.ts, and it sets the hidden window itself. Preserved: 3 s timeout, 16 KiB output bound, first stdout line only, null on launch failure. One correction found by re-running the live proof on the runner-based head: the CLI on this machine prints its version at once but keeps running afterwards, so a probe that waited for the exit reported nothing; the probe now settles on the first printed line and leaves the runner to stop the command in the background (test: a runner that prints and never returns is stopped and its version adopted).

Housekeeping the CI lanes asked for: the transport's client construction moved to the sibling anthropic-transport-client.ts and the new tests to sibling files, so no over-cap file grows (704d2dfb, 738d25c4); the probe's two test-only exports are registered in config/knip.config.ts (497abc15).

Gates on this head: node scripts/run-vitest.mjs over the listed files → 284 passed across 7 files; git diff --check, oxlint, oxfmt --check, pnpm tsgo:core, line-cap / max-lines / assertion-safety ratchets and the production knip scan clean. Windows .cmd launch itself is not validated on this Linux host beyond the runner's own tests. The earlier pr-operation-lock failure is a tooling test unrelated to these files; it passes locally.

The live OAuth proof in the body was re-run at this head, both arms: the installed CLI's version is detected and awaited before the request is built (user-agent and billing block both 2.1.274, HTTP 200), while the pinned fallback is still refused with claude_code_version_too_old.

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Sep 17, 2026
steipete added a commit that referenced this pull request Sep 21, 2026
Direct Anthropic OAuth requests could fail with claude_code_version_too_old because they advertised Claude Code 2.1.75. Maintain a 2.1.278 client-version floor and prefer a newer installed stable CLI through the Anthropic plugin's shared, bounded probe. Both transports use one selected version for request headers and billing metadata; failed or slow probes fall back to the floor.

Preserve API-key and other provider routes without configuration, credential, dependency, or state migrations. Cover request identity and probe lifecycle, and repair the cold metadata fixture and OS-watch race encountered during validation. Focused tests and exact-head CI passed; candidate live OAuth acceptance remains unverified.

Thanks to @Cyb3rb1ade, @raghidtawil-lab, and @davidcittadini for the reports and controlled comparisons. The single-snapshot and header/billing boundary-test approach builds on @KrasimirKralev's prior work.

Fixes #94716. Related: #154016. Supersedes the approach in #150790 with credit; that PR remains open for maintainer follow-up. The separate model-allowlist issue #144903 is outside this repair.

Co-authored-by: Krasimir Kralev <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

Thank you for this, @KrasimirKralev — your diagnosis was right and your header/billing-consistency tests shaped the fix. The same defect is now fixed on main by #154098 (b58603ee2b3), which credits you as co-author: it keeps a maintained floor (2.1.278) as the fallback and prefers a newer installed CLI, but discovers the CLI through the Anthropic plugin's existing bounded probe instead of a host-level claude --version spawn, so @openclaw/ai still spawns nothing and there is no Windows-specific launcher to prove. Closing this PR as superseded; the credit stays in the landed commit and on #94716.

@steipete steipete closed this Sep 21, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 21, 2026
…law#154098)

Direct Anthropic OAuth requests could fail with claude_code_version_too_old because they advertised Claude Code 2.1.75. Maintain a 2.1.278 client-version floor and prefer a newer installed stable CLI through the Anthropic plugin's shared, bounded probe. Both transports use one selected version for request headers and billing metadata; failed or slow probes fall back to the floor.

Preserve API-key and other provider routes without configuration, credential, dependency, or state migrations. Cover request identity and probe lifecycle, and repair the cold metadata fixture and OS-watch race encountered during validation. Focused tests and exact-head CI passed; candidate live OAuth acceptance remains unverified.

Thanks to @Cyb3rb1ade, @raghidtawil-lab, and @davidcittadini for the reports and controlled comparisons. The single-snapshot and header/billing boundary-test approach builds on @KrasimirKralev's prior work.

Fixes openclaw#94716. Related: openclaw#154016. Supersedes the approach in openclaw#150790 with credit; that PR remains open for maintainer follow-up. The separate model-allowlist issue openclaw#144903 is outside this repair.

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

Labels

merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants