openclaw - ✅(Solved) Fix context1m beta header stripped for OAuth token auth — breaks Max plan users [1 pull requests, 1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
openclaw/openclaw#57292Fetched 2026-04-08 01:51:28
View on GitHub
Comments
0
Participants
1
Timeline
2
Reactions
0
Participants
Timeline (top)
cross-referenced ×1referenced ×1

Root Cause

  • Users on the Anthropic Max plan who authenticate via OAuth tokens cannot use extended context (>200K), even though their plan supports it.
  • Under Anthropic API stress/enforcement periods, these requests may be rate-limited or rejected more aggressively because they lack the proper beta header.
  • The warning fires continuously in logs (every few seconds during active sessions), creating log noise.
  • Sessions that build up context over time hit 429 rate limits and become unresponsive, requiring manual session store deletion to recover.

Fix Action

Workaround

Delete ~/.openclaw/agents/main/sessions/sessions.json and restart the gateway when sessions become unresponsive. This is not sustainable for production use.

PR fix notes

PR #59445: [AI-assisted] fix(anthropic): restore OAuth beta header injection after extension refactor

Description (problem / solution / changelog)

Summary

  • Problem: Anthropic OAuth users (Max plan, setup-token) get HTTP 401 because oauth-2025-04-20 beta header is not injected. The beta header wrapper's OAuth detection relies on options.apiKey, which is always undefined at the wrapper layer — the apiKey is resolved deeper in sdk.js's innermost streamFn.
  • Why it matters: All users authenticating via OAuth tokens (sk-ant-oat-*) cannot use Anthropic models. This also prevents context-1m stripping for OAuth, which may cause secondary rejections.
  • What changed: Always apply the Anthropic beta wrapper (not just when user-configured betas exist), detect OAuth at setup time from auth profile config instead of relying on runtime options.apiKey, and pass the flag to the wrapper.
  • What did NOT change (scope boundary): No Plugin SDK surface changes. All changes are within the Anthropic extension. The runtime options.apiKey fallback is preserved for backward compatibility.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #57292
  • Closes #41444
  • Related #19789 (the original OAuth beta preservation fix this restores)
  • This PR fixes a bug or regression

Root Cause / Regression History (if applicable)

  • Root cause: createAnthropicBetaHeadersWrapper checks options?.apiKey to detect OAuth tokens, but options.apiKey is always undefined at the wrapper layer in production — the apiKey is resolved by sdk.js inside the innermost streamFn, which is wrapped by (not wrapping) the beta header wrapper.
  • Missing detection / guardrail: No test covered the production scenario where options.apiKey is undefined. The existing test passes apiKey directly in options, masking the bug.
  • Prior context: PR #19789 (Feb 19, 2026) added OAuth beta preservation and relied on options.apiKey being available. The extension refactor 59c23dee (Apr 1) moved the wrapper into the Anthropic plugin, and the guard if (anthropicBetas?.length) was carried over unchanged. The combination of (a) the wrapper only applying when user betas exist and (b) options.apiKey always being undefined means the OAuth fix from #19789 became dead code.
  • Why this regressed now: The extension refactor changed the wrapper's position in the call chain. Previously the wrapper may have been closer to the apiKey resolution; after the refactor it's definitively outside it.
  • If unknown, what was ruled out: pi-ai's auth handling was verified clean (1068/1068 Anthropic tests pass). The bug is entirely in OpenClaw's wrapper chain.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: extensions/anthropic/stream-wrappers.test.ts
  • Scenario the test should lock in: OAuth beta injection when options.apiKey is undefined (the production path), using the isOAuthSetupTime flag
  • Why this is the smallest reliable guardrail: The wrapper is a pure function — unit tests with the correct inputs (undefined apiKey + setup-time flag) directly validate the fix
  • Existing test that already covers this (if any): The existing test at stream-wrappers.test.ts ("strips context-1m for subscription setup-token auth") passes apiKey in options, which only validates the runtime fallback path. Added 4 new tests covering the setup-time detection path.

User-visible / Behavior Changes

  • OAuth users (Max plan, setup-token auth) will no longer get HTTP 401 on Anthropic API calls
  • context-1m-2025-08-07 will be correctly stripped for OAuth users (previously included erroneously)
  • Non-OAuth users are unaffected — PI_AI_DEFAULT_ANTHROPIC_BETAS are now always injected (they were already injected when any beta was configured, this just ensures they're always present)

Diagram (if applicable)

Before (broken) — two paths, both fail for OAuth users:

sequenceDiagram
    participant Plugin as Anthropic Plugin<br/>wrapStreamFn
    participant Resolve as resolveAnthropicBetas()
    participant Wrapper as createAnthropicBeta<br/>HeadersWrapper
    participant SDK as sdk.js streamFn
    participant API as Anthropic API

    Note over Plugin,API: Path 1: No user-configured betas (e.g. no context1m)
    Plugin->>Resolve: extraParams, modelId
    Resolve-->>Plugin: undefined (no betas)
    Note over Plugin: if (anthropicBetas?.length) → false<br/>Wrapper NOT applied
    Plugin->>SDK: streamFn(model, ctx, options)
    SDK->>API: headers missing oauth-2025-04-20
    API-->>SDK: 401 "OAuth not supported"

    Note over Plugin,API: Path 2: context1m configured
    Plugin->>Resolve: extraParams, modelId
    Resolve-->>Plugin: ["context-1m-2025-08-07"]
    Plugin->>Wrapper: create(streamFn, betas)
    Note over Wrapper: options.apiKey = undefined<br/>isOauth = false ✗
    Wrapper->>Wrapper: Select PI_AI_DEFAULT_BETAS<br/>(missing oauth-2025-04-20)
    Wrapper->>SDK: streamFn(model, ctx, options)
    SDK->>API: headers missing oauth-2025-04-20
    API-->>SDK: 401 "OAuth not supported"

After (fixed) — wrapper always applied, OAuth detected from config:

sequenceDiagram
    participant Plugin as Anthropic Plugin<br/>wrapStreamFn
    participant Resolve as resolveAnthropicBetas()
    participant Config as hasOAuthAnthropicProfile()
    participant Wrapper as createAnthropicBeta<br/>HeadersWrapper
    participant SDK as sdk.js streamFn
    participant API as Anthropic API

    Plugin->>Resolve: extraParams, modelId
    Resolve-->>Plugin: betas ?? [] (always [])
    Plugin->>Config: config.auth.profiles
    Config-->>Plugin: isOAuth = true
    Plugin->>Wrapper: create(streamFn, betas, isOAuth=true)
    Note over Wrapper: isOAuth from setup-time flag ✓<br/>(no longer depends on options.apiKey)
    Wrapper->>Wrapper: Select PI_AI_OAUTH_BETAS<br/>includes oauth-2025-04-20 ✓
    Wrapper->>SDK: streamFn(model, ctx, options)
    SDK->>API: anthropic-beta: oauth-2025-04-20,...
    API-->>SDK: 200 OK

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No — only reads auth profile mode field (not credentials)
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: macOS (Darwin arm64)
  • Runtime/container: Node v25.8.2, pnpm 10.32.1
  • Model/provider: Anthropic (claude-sonnet-4-6, claude-opus-4-6)
  • Integration/channel: Telegram (via OpenClaw gateway)
  • Relevant config: auth.profiles.anthropic:manual.mode = "token" with sk-ant-oat01-* token

Steps

  1. Configure Anthropic auth with OAuth/setup-token (mode: "token" or mode: "oauth")
  2. Set context1m: true in model params (or leave unconfigured — both paths fail)
  3. Send a message to an Anthropic model

Expected

  • Request succeeds with anthropic-beta header containing oauth-2025-04-20

Actual

  • HTTP 401: "OAuth authentication is currently not supported." (because oauth-2025-04-20 is missing from the beta header)

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

curl proof (tokens redacted):

# Bearer + oauth-2025-04-20 → 429 (auth OK, rate limited)
# Bearer WITHOUT oauth-2025-04-20 → 401 "OAuth authentication is currently not supported."
# X-Api-Key WITHOUT oauth-2025-04-20 → 429 (auth OK — why the local workaround works)

Wrapper probe (before fix):

[PI-AI-DEBUG] wrapper: isOauth=false options.apiKey prefix=<undefined>
[PI-AI-DEBUG] wrapper: allBetas=["fine-grained-tool-streaming-...", "interleaved-thinking-...", "context-1m-..."]

Missing: oauth-2025-04-20, claude-code-20250219

Test results (after fix):

  • pnpm check — 0 warnings, 0 errors
  • pnpm build — clean, no INEFFECTIVE_DYNAMIC_IMPORT warnings
  • pnpm test — 0 failed units, 0 failed test files, 0 infrastructure failures
  • 6/6 stream-wrappers tests pass (4 new + 2 existing)

Human Verification (required)

  • Verified scenarios: Unit tests cover OAuth detection via setup-time flag with undefined apiKey; integration test covers the existing runtime apiKey fallback path; all three gates (check, build, test) pass clean
  • Edge cases checked: Empty betas array with OAuth (no user-configured betas); non-OAuth user with empty betas; mixed auth profiles
  • What you did NOT verify: Live OAuth token against Anthropic API (requires active gateway session with real credentials)

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Risks and Mitigations

  • Risk: hasOAuthAnthropicProfile reads config.auth.profiles which could be undefined or empty for users who haven't set up auth profiles yet.
    • Mitigation: Returns false when profiles are missing, falling back to PI_AI_DEFAULT_ANTHROPIC_BETAS (same as current behavior).
  • Risk: Always applying the beta wrapper adds PI_AI_DEFAULT_ANTHROPIC_BETAS even when no user betas are configured.
    • Mitigation: These betas (fine-grained-tool-streaming, interleaved-thinking) are required for OpenClaw's Anthropic integration to work. They were always injected when any beta was configured; this change only ensures they're present unconditionally.

Testing level: Fully tested (unit + integration + all gates) AI disclosure: This PR was developed with Claude Code (Opus 4.6). All code was reviewed line-by-line and the contributor understands the full change. Session logs available on request.

🤖 Generated with Claude Code

Changed files

  • extensions/anthropic/index.ts (modified, +33/-4)
  • extensions/anthropic/stream-wrappers.test.ts (modified, +47/-2)
  • extensions/anthropic/stream-wrappers.ts (modified, +7/-1)

Code Example

ignoring context1m for OAuth token auth on anthropic/claude-opus-4-6; Anthropic rejects context-1m beta with OAuth auth

---

{
  "auth": {
    "profiles": {
      "anthropic:manual": {
        "provider": "anthropic",
        "mode": "token"
      }
    }
  }
}
RAW_BUFFERClick to expand / collapse

Bug Description

OpenClaw strips the anthropic-beta: max-model-output-200k-2025-02-19 (context1m) header when the Anthropic auth profile uses OAuth token mode (mode: token). The log emits:

ignoring context1m for OAuth token auth on anthropic/claude-opus-4-6; Anthropic rejects context-1m beta with OAuth auth

This fires on every single request, regardless of model or context size.

Impact

  • Users on the Anthropic Max plan who authenticate via OAuth tokens cannot use extended context (>200K), even though their plan supports it.
  • Under Anthropic API stress/enforcement periods, these requests may be rate-limited or rejected more aggressively because they lack the proper beta header.
  • The warning fires continuously in logs (every few seconds during active sessions), creating log noise.
  • Sessions that build up context over time hit 429 rate limits and become unresponsive, requiring manual session store deletion to recover.

Environment

  • OpenClaw version: 2026.3.13 (61d171a) — also confirmed present in 2026.3.28
  • OS: macOS (Darwin arm64)
  • Node: v22.22.0
  • Auth config:
{
  "auth": {
    "profiles": {
      "anthropic:manual": {
        "provider": "anthropic",
        "mode": "token"
      }
    }
  }
}
  • Model: anthropic/claude-opus-4-6 (also fires for claude-sonnet-4-6)
  • Plan: Anthropic Max (supports extended context)

Expected Behavior

The context1m beta header should be sent for OAuth token auth users, or at minimum there should be a config override (e.g., forceContext1m: true or anthropicBeta: ["max-model-output-200k-2025-02-19"]) that allows Max plan users to opt in.

Actual Behavior

The header is unconditionally stripped for all OAuth token auth profiles. No config override exists.

Reproduction

  1. Configure Anthropic provider with mode: token (OAuth)
  2. Start a session and send any message
  3. Observe the warning in logs: ignoring context1m for OAuth token auth
  4. As the session grows in context, requests begin hitting 429 rate limits
  5. Eventually the session becomes unresponsive — only recoverable by deleting sessions.json and restarting

Suggested Fix

Either:

  1. Pass the context1m header through for OAuth token auth (Anthropic's API may now accept it for Max plan tokens)
  2. Add a provider-level config option to force the beta header regardless of auth mode
  3. Add an auth profile flag like context1m: true that overrides the stripping behavior

Workaround

Delete ~/.openclaw/agents/main/sessions/sessions.json and restart the gateway when sessions become unresponsive. This is not sustainable for production use.

extent analysis

Fix Plan

To resolve the issue, we will implement a provider-level config option to force the beta header regardless of auth mode. We will add a new property anthropicBeta to the auth profile config.

Step-by-Step Solution

  1. Update the auth config: Add the anthropicBeta property to the anthropic:manual profile.
{
  "auth": {
    "profiles": {
      "anthropic:manual": {
        "provider": "anthropic",
        "mode": "token",
        "anthropicBeta": ["max-model-output-200k-2025-02-19"]
      }
    }
  }
}
  1. Update the OpenClaw code: Modify the code to check for the anthropicBeta property in the auth profile and include the context1m header if it is present.
// In the auth profile processing code
if (profile.anthropicBeta) {
  // Include the context1m header
  headers['anthropic-beta'] = profile.anthropicBeta.join(',');
}
  1. Verify the fix: Restart the OpenClaw service and test with a new session to ensure the context1m header is included in the requests.

Verification

To verify the fix, check the logs for the absence of the ignoring context1m for OAuth token auth warning and confirm that the context1m header is included in the requests. You can use a tool like curl or a HTTP debugger to inspect the request headers.

Extra Tips

  • Make sure to update the OpenClaw version to the latest release after implementing the fix.
  • Consider adding a fallback mechanism to handle cases where the anthropicBeta property is not configured or the header is not accepted by the Anthropic API.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

openclaw - ✅(Solved) Fix context1m beta header stripped for OAuth token auth — breaks Max plan users [1 pull requests, 1 participants]