opencode-anthropic-fix
v0.0.16
Published
Use your Claude Pro or Max subscription with [OpenCode](https://github.com/anomalyco/opencode). Supports multiple accounts with automatic rotation when you hit rate limits.
Readme
opencode-anthropic-fix
Use your Claude Pro or Max subscription with OpenCode. Supports multiple accounts with automatic rotation when you hit rate limits.
Background
AnomalyCo originally published this as a built-in plugin shipped with OpenCode itself. The repo was archived following a legal request from Anthropic. Before it was archived, rmk40 — a frequent contributor unrelated to AnomalyCo — had developed multi-account support that never made it upstream.
This fork continues that work and extends it with deeper research into how the official Claude Code CLI identifies itself to the API. The mimicry was derived by analyzing Claude Code's open source code on GitHub. This isn't just a system prompt injection — see the full mimicry analysis for details.
Educational purpose. This code exists to study how Anthropic's OAuth protocol and Claude Code's HTTP communication pattern work. It is not intended to be used in violation of Anthropic's Terms of Service.
Account risk. There is a real risk of account suspension if Anthropic detects requests are not coming from Claude Code. The mimicry tries hard to make every request look as close as possible to a genuine Claude Code request, but that reduces rather than eliminates the risk. Use at your own risk.
Quick Start
Prerequisites: OpenCode installed, a Claude Pro or Max subscription, Node.js 18+.
# 1. Clone and install
git clone https://github.com/marco-jardim/opencode-anthropic-fix.git
cd opencode-anthropic-fix
npm install
# 2. Install the plugin + CLI
npm run install:link
# 3. Start OpenCode and connect
opencode
# Press Ctrl+K → Connect Provider → Anthropic → "Claude Pro/Max (multi-account)"
# Follow the OAuth prompts to log inThat's it. OpenCode will now use your Claude subscription directly. All model costs show as $0.00.
What This Fork Adds
The original plugin provided basic OAuth support. This fork adds:
- Multi-account support — add up to 10 Claude accounts and rotate between them
- Automatic rate limit handling — when one account hits a limit, the plugin switches to another
- Health scoring — tracks account reliability and prefers healthy accounts
- Standalone CLI — manage accounts without opening OpenCode
- Configurable strategies — sticky, round-robin, or hybrid account selection
- Claude Code signature emulation — full HTTP header, system prompt, beta flag, and metadata mimicry derived from Claude Code's open source code
- Adaptive thinking for Opus 4.6 — automatically uses
adaptive-thinking-2026-01-28and mapsbudgetTokensto effort levels (low/medium/high/max) - 1M context limit override — patches
model.limit.contextso OpenCode compacts at the right threshold whilemodels.devcatches up
Installation
From npm (recommended)
Add to your opencode.json:
{
"plugins": ["opencode-anthropic-fix@latest"]
}OpenCode will install and load the plugin automatically on next start.
Development (symlink)
Best for active development. Edits to source files take effect immediately.
npm run install:linkThis creates:
- Plugin:
~/.config/opencode/plugin/opencode-anthropic-auth-plugin.js→./index.mjs - CLI:
~/.local/bin/opencode-anthropic-auth→./cli.mjs
Stable (copy)
Bundles the plugin and CLI into self-contained single files (via esbuild) and copies them. No symlinks, no node_modules needed at the destination.
npm run install:copyThis creates:
- Plugin:
~/.config/opencode/plugin/opencode-anthropic-auth-plugin.js(standalone, ~50KB) - CLI:
~/.local/bin/opencode-anthropic-auth(standalone, ~35KB)
Uninstall
npm run uninstallPATH Setup
If ~/.local/bin isn't on your PATH, add it:
export PATH="$HOME/.local/bin:$PATH"Adding Accounts
First Account
- Open OpenCode
- Press
Ctrl+K→ Connect Provider → Anthropic - Select "Claude Pro/Max (multi-account)"
- Open the URL in your browser, authorize, and paste the code back
You can also add accounts directly from the CLI without opening OpenCode:
opencode-anthropic-auth loginAdditional Accounts
Run the auth flow again (via CLI login or OpenCode's Connect Provider). The plugin detects existing accounts and shows a menu:
2 account(s) configured:
1. [email protected] (active)
2. [email protected]
(a)dd new, (f)resh start, (m)anage, (c)ancel? [a/f/m/c]:- Add — log in with another Claude account
- Fresh start — clear all accounts and start over
- Manage — enable/disable/remove accounts inline
- Cancel — keep current setup
This fork is OAuth-first. Use claude.ai login flows (login / reauth) for all accounts.
CLI
The CLI lets you manage accounts outside of OpenCode.
opencode-anthropic-auth [command] [args]| Command | Description |
| ---------------------- | ------------------------------------------------------------- |
| login | Add a new account via browser OAuth flow |
| logout <N> | Revoke tokens and remove account N |
| logout --all | Revoke all tokens and clear all accounts |
| reauth <N> | Re-authenticate account N with fresh OAuth tokens |
| refresh <N> | Attempt token refresh (no browser needed) |
| list | Show all accounts with status and live usage quotas (default) |
| status | Compact one-liner for scripts/prompts |
| switch <N> | Set account N as active |
| enable <N> | Enable a disabled account |
| disable <N> | Disable an account (skipped in rotation) |
| remove <N> | Remove an account permanently |
| reset <N\|all> | Clear rate-limit / failure tracking |
| stats | Show per-account token usage statistics |
| reset-stats [N\|all] | Reset usage statistics |
| strategy [name] | Show or change selection strategy |
| config | Show configuration and file paths |
| manage | Interactive account management menu |
| help | Show help |
Examples
# Add a new account via browser OAuth
opencode-anthropic-auth login
# See account status (includes live usage quotas)
opencode-anthropic-auth list
# Output:
# Anthropic Multi-Account Status
# # Account Status Failures Rate Limit
# ──────────────────────────────────────────────────────────────
# 1 [email protected] ● active 0 —
# 5h █████░░░░░ 45% resets in 2h 30m
# 7d █████░░░░░ 45% resets in 4d 16h
# Sonnet 7d ░░░░░░░░░░ 0%
#
# 2 [email protected] ● ready 0 —
# 5h ███░░░░░░░ 31% resets in 30m
# 7d ███████░░░ 70% resets in 19h 31m
# Sonnet 7d █░░░░░░░░░ 11% resets in 2d 10h
#
# Strategy: sticky | 2 of 2 enabled
# Storage: ~/.config/opencode/anthropic-accounts.json
# Switch active account
opencode-anthropic-auth switch 2
# Re-authenticate a broken account (opens browser)
opencode-anthropic-auth reauth 1
# Quick token refresh without browser
opencode-anthropic-auth refresh 1
# Revoke tokens and remove an account
opencode-anthropic-auth logout 2
# Revoke all tokens and clear all accounts
opencode-anthropic-auth logout --all
# View token usage per account
opencode-anthropic-auth stats
# Reset all usage counters
opencode-anthropic-auth reset-stats all
# One-liner for shell prompts
opencode-anthropic-auth status
# anthropic: 2 accounts (2 active), strategy: sticky, next: #1
# Interactive management
opencode-anthropic-auth manageFlags
| Flag | Description |
| ------------ | -------------------------------------------------- |
| --force | Skip confirmation prompts (for remove, logout) |
| --all | Target all accounts (for logout) |
| --no-color | Disable colored output |
| --help | Show help message |
Most commands have short aliases: ln, lo, ra, rf, ls, st, sw, en, dis, rm, strat, cfg, mg.
Slash Commands in OpenCode
The plugin also registers a built-in /anthropic slash command so you can manage accounts without leaving OpenCode.
Common examples
/anthropic # list (default)
/anthropic usage # full account list + quota windows
/anthropic switch 2
/anthropic refresh 1
/anthropic logout 2 # revoke tokens and remove account 2
/anthropic logout --all # revoke all tokens and clear all accounts
/anthropic strategy hybrid
/anthropic stats
/anthropic configOAuth flows from slash command
Login and reauth are two-step flows in slash mode:
/anthropic login
# opens URL instructions in chat
/anthropic login complete <code#state>
/anthropic reauth 1
# opens URL instructions in chat
/anthropic reauth complete <code#state>Pending slash OAuth flows expire after 10 minutes. If completion fails with an expiration message, run the start command again.
Notes
- Destructive commands (
remove,logout) run with non-interactive--forcebehavior in slash mode. - Interactive
manageis terminal-only; use granular slash commands instead.
Account Selection Strategies
Control how the plugin picks which account to use for each request.
| Strategy | Behavior | Best For |
| ---------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------- |
| sticky (default) | Stay on one account until it fails or is rate-limited | Single account, or when you want predictable behavior |
| round-robin | Rotate through accounts on every request | Spreading load evenly across accounts |
| hybrid | Score-based selection with stickiness bias. Considers health, token budget, and freshness | Multiple accounts with varying rate limits |
Change Strategy
# Via CLI
opencode-anthropic-auth strategy round-robin
# Via environment variable (overrides config file)
export OPENCODE_ANTHROPIC_STRATEGY=hybrid
# Via config file
# Edit ~/.config/opencode/anthropic-auth.jsonConfiguration
Configuration is stored at ~/.config/opencode/anthropic-auth.json. All settings are optional — defaults work well for most users.
{
// Account selection strategy: "sticky" | "round-robin" | "hybrid"
"account_selection_strategy": "sticky",
// Seconds before consecutive failure count resets (60-7200)
"failure_ttl_seconds": 3600,
// Enable debug logging
"debug": false,
// Claude Code signature emulation behavior
"signature_emulation": {
// Enable Claude-style attribution/stainless headers and betas
"enabled": true,
// Resolve latest @anthropic-ai/claude-code version once on plugin startup
"fetch_claude_code_version_on_startup": true,
// Compact long injected system instructions to reduce token usage.
// In "minimal" mode, repeated/contained blocks are deduplicated and title-generator
// requests are replaced with a compact dedicated prompt.
// "minimal" | "off"
"prompt_compaction": "minimal",
},
// Context limit override for 1M-window models.
// Prevents OpenCode from compacting too early when models.dev hasn't been
// updated yet (e.g. claude-opus-4-6 and any *-1m model variants).
// Only applied for OAuth (Max Plan) sessions — API key users use the
// context-1m-2025-08-07 beta header instead.
"override_model_limits": {
// Enable/disable the override
"enabled": true,
// Context window to inject (tokens). Default: 1_000_000.
"context": 1000000,
// Max output tokens to inject. 0 = leave the model's default unchanged.
"output": 0,
},
// Health score tuning (0-100 scale)
"health_score": {
"initial": 70,
"success_reward": 1,
"rate_limit_penalty": -10,
"failure_penalty": -20,
"recovery_rate_per_hour": 2,
"min_usable": 50,
"max_score": 100,
},
// Client-side rate limiting (token bucket)
"token_bucket": {
"max_tokens": 50,
"regeneration_rate_per_minute": 6,
"initial_tokens": 50,
},
// Toast notification settings
"toasts": {
// Suppress non-error toasts (account status, switching)
"quiet": false,
// Minimum seconds between account-switch toasts (0-300)
"debounce_seconds": 30,
},
}Environment Variables
| Variable | Description |
| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| OPENCODE_ANTHROPIC_STRATEGY | Override the account selection strategy at runtime. |
| OPENCODE_ANTHROPIC_DEBUG | Set to 1 to enable debug logging. |
| OPENCODE_ANTHROPIC_QUIET | Set to 1 to suppress non-error toasts (account status, switching). |
| OPENCODE_ANTHROPIC_EMULATE_CLAUDE_CODE_SIGNATURE | Set to 0 to disable Claude signature emulation (legacy mode). |
| OPENCODE_ANTHROPIC_FETCH_CLAUDE_CODE_VERSION | Set to 0 to skip npm version lookup at startup. |
| OPENCODE_ANTHROPIC_PROMPT_COMPACTION | Set to off to disable default minimal system prompt compaction. |
| OPENCODE_ANTHROPIC_DEBUG_SYSTEM_PROMPT | Set to 1 to log the final transformed system prompt to stderr (title-generator requests are skipped). |
| OPENCODE_ANTHROPIC_OVERRIDE_MODEL_LIMITS | Set to 0 to disable context limit overrides for 1M-window models (e.g. when models.dev has been updated). |
OAuth-only behavior
- The expected auth mode is OAuth (
claude login/ browser flow), not directANTHROPIC_API_KEYusage. - In OAuth mode, the plugin always includes
oauth-2025-04-20inanthropic-beta. - This applies to all models, including Haiku.
How It Works
When you make a request through OpenCode:
- The plugin selects an account based on your strategy
- It refreshes the OAuth token if expired
- It transforms the request (adds OAuth headers,
oauth-2025-04-20, signature headers, beta flags, tool prefixes) - If the response is account-specific (429/401, plus 400/403 billing/quota/permission errors), it marks that account and immediately tries the next account
- If the response is service-wide (500/503/529), it returns the error directly (switching accounts would not help)
- It tries each available account at most once per request
- Successful responses have tool name prefixes stripped from the stream
The plugin also:
- Zeros out model costs (your subscription covers usage)
- Emulates Claude-style request headers and beta flags by default
- Sanitizes "OpenCode" references to "Claude Code" in system prompts (required by Anthropic's API)
- In
prompt_compaction="minimal", deduplicates repeated/contained system blocks and uses a compact dedicated prompt for internal title-generation requests - Adds
?beta=trueto/v1/messagesrequests
When signature emulation is disabled (signature_emulation.enabled=false), the plugin falls back to legacy behavior including the Claude Code system prompt prefix.
Files
| Path | Description |
| ------------------------------------------------------------- | -------------------------------------- |
| ~/.config/opencode/anthropic-auth.json | Plugin configuration |
| ~/.config/opencode/anthropic-accounts.json | Account credentials (0600 permissions) |
| ~/.config/opencode/plugin/opencode-anthropic-auth-plugin.js | Installed plugin entry point |
| ~/.local/bin/opencode-anthropic-auth | CLI binary |
Account credentials are stored with restrictive file permissions (owner read/write only) and are excluded from git via an auto-generated .gitignore.
Troubleshooting
"Provider not showing up"
Make sure the plugin is installed in ~/.config/opencode/plugin/. Restart OpenCode after installing.
"Auth flow completes but requests fail"
Your OAuth token may have expired. Try a quick refresh first, or re-authenticate with fresh browser login:
# Quick token refresh (no browser needed)
opencode-anthropic-auth refresh 1
# Full re-authentication (opens browser)
opencode-anthropic-auth reauth 1Or re-run the auth flow from OpenCode: Ctrl+K → Connect Provider → Anthropic.
"Need to inspect the final system prompt sent to Anthropic"
Enable system prompt debug logging:
export OPENCODE_ANTHROPIC_DEBUG_SYSTEM_PROMPT=1
opencodeWhen enabled, the plugin prints the transformed system block (after sanitization/compaction) to stderr with prefix:
[opencode-anthropic-auth][system-debug] transformed system:Note: internal title-generator requests are intentionally skipped by this debug log to avoid noisy high-volume output.
"Rate limited on all accounts"
When all accounts are exhausted for an account-specific error, the plugin returns immediately instead of sleeping in-process. Try:
# Check status
opencode-anthropic-auth list
# Reset tracking if stuck
opencode-anthropic-auth reset all"Toast notifications when using other models"
You may see Claude: <email> toasts even when your selected model is not Anthropic (e.g., OpenAI Codex, Gemini). This is expected behavior — OpenCode uses Claude Haiku as a background "small model" for internal tasks like generating session titles, regardless of which model you selected. These background API calls go through the Anthropic provider, which triggers the plugin's fetch interceptor and its account-usage toast.
To suppress non-error toasts, set quiet mode in your config:
// ~/.config/opencode/anthropic-auth.json
{
"toasts": { "quiet": true },
}Or via environment variable:
export OPENCODE_ANTHROPIC_QUIET=1Error toasts (e.g., "Disabled Account 1 (token refresh failed)") are never suppressed.
"CLI command not found"
Make sure ~/.local/bin is on your PATH:
export PATH="$HOME/.local/bin:$PATH"License
Same as upstream. See anomalyco/opencode-anthropic-auth.
Maintained at marco-jardim/opencode-anthropic-fix.
