@ex-machina/opencode-anthropic-auth 2.0.0-next.0 → 2.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,80 +1,137 @@
1
1
  # OpenCode Anthropic Auth Plugin
2
2
 
3
+ [![OpenCode v1 — npm latest tag](https://img.shields.io/npm/v/%40ex-machina%2Fopencode-anthropic-auth/latest?label=OpenCode%20v1%20(latest))](https://www.npmjs.com/package/@ex-machina/opencode-anthropic-auth?activeTab=versions)
4
+ [![OpenCode v2 — npm next tag](https://img.shields.io/npm/v/%40ex-machina%2Fopencode-anthropic-auth/next?label=OpenCode%20v2%20(next))](https://www.npmjs.com/package/@ex-machina/opencode-anthropic-auth?activeTab=versions)
5
+
3
6
  > [!WARNING]
4
7
  > This plugin comes with no guarantees. You might be banned for breaking the TOS, you might not be. I don't work at Anthropic, nor am I an attorney.
5
8
  >
6
9
  > Use your best judgment and don't try to abuse the subscriptions. Plugins like oh-my-openagent are _known_ to trigger bans. Please be careful when using Ralph loops or insanely heavy usage patterns.
7
10
 
8
11
  > [!IMPORTANT]
9
- > If you are seeing issues, please try to `rm -rf ~/.cache/opencode/packages/@ex-machina` and check your `opencode.json` config to make sure you're on the latest version.
12
+ > If you are seeing issues, try `rm -rf ~/.cache/opencode/packages/@ex-machina` and confirm that your `opencode.json` uses the plugin release line for your OpenCode version.
10
13
  >
11
14
  > Try this FIRST before making an Issue. Thanks!
12
15
 
13
16
  An [OpenCode](https://github.com/anomalyco/opencode) plugin that provides Anthropic OAuth authentication, enabling Claude Pro/Max users to use their subscription directly with OpenCode.
14
17
 
15
- ## Version compatibility
18
+ > [!NOTE]
19
+ > This repository uses [Agent Facets](https://agentfacets.io) to manage agent capabilities. See the [quickstart](https://docs.agentfacets.io/quickstart) to install the CLI and get started.
20
+
21
+ ## Version support
16
22
 
17
- | Plugin version | OpenCode version | Package |
18
- |-----------------|-------------------|---------------------------------------------|
19
- | 2.x (this readme) | OpenCode v2 (beta plugin API) | `@ex-machina/opencode-anthropic-auth` |
20
- | 1.x | OpenCode v1 | `@ex-machina/opencode-anthropic-auth@1` |
23
+ | OpenCode version | Plugin release | Support branch | npm dist-tag | Configuration key |
24
+ |------------------|----------------|----------------|--------------|-------------------|
25
+ | OpenCode v1 | 1.x | [`main`](https://github.com/ex-machina-co/opencode-anthropic-auth/tree/main) | `latest` | `plugin` |
26
+ | OpenCode v2 | 2.x prereleases | [`v2/main`](https://github.com/ex-machina-co/opencode-anthropic-auth/tree/v2/main) | `next` | `plugins` |
21
27
 
22
- OpenCode v2's plugin API is still beta, and this plugin currently targets the `@opencode-ai/plugin@0.0.0-next-17444` prerelease of it — pin the plugin version and keep an eye on the changelog when bumping either side. If you're still on OpenCode v1, keep using a `1.x` release; v1 plugins are **not** loadable by OpenCode v2, and this v2 port is not loadable by OpenCode v1.
28
+ Both release lines use the same npm package. They are not cross-compatible: the v1 plugin does not load in OpenCode v2, and the v2 plugin does not load in OpenCode v1. OpenCode v2's plugin API is still beta, so review the changelog before upgrading either side.
23
29
 
24
30
  ## Usage
25
31
 
26
- Add the plugin to your OpenCode configuration:
32
+ > [!TIP]
33
+ > Pin an exact plugin version for a stable setup that changes only when you choose to upgrade. If you intentionally want automatic updates, use the moving npm tag for your OpenCode release line.
34
+ >
35
+ > This applies to every OpenCode plugin: an unpinned or moving-tag dependency can install new code on startup, so only track automatic updates from publishers you trust.
36
+
37
+ ### OpenCode v1 (`latest`)
38
+
39
+ OpenCode v1 uses the singular `plugin` configuration key. A bare package spec tracks npm's `latest` tag:
27
40
 
28
41
  ```json
29
42
  {
30
- "plugins": ["@ex-machina/opencode-anthropic-auth"]
43
+ "plugin": ["@ex-machina/opencode-anthropic-auth"]
31
44
  }
32
45
  ```
33
46
 
34
- > [!TIP]
35
- > It is STRONGLY advised that you pin the plugin to a version. This will keep you from getting automatic updates; however, this will protect you from nefarious updates.
36
- >
37
- > This holds true for ANY OpenCode plugin. If you do not pin them, OpenCode will automatically update them on startup. It's a massive vulnerability waiting to happen.
47
+ You can also write the moving tag explicitly as `@ex-machina/opencode-anthropic-auth@latest`.
38
48
 
39
- #### Example of pinned version
49
+ For a stable setup, look up the exact version currently published on `latest`:
50
+
51
+ ```bash
52
+ npm view @ex-machina/opencode-anthropic-auth dist-tags.latest
53
+ ```
54
+
55
+ Substitute the command output for `<version>`:
56
+
57
+ ```json
58
+ {
59
+ "plugin": ["@ex-machina/opencode-anthropic-auth@<version>"]
60
+ }
61
+ ```
62
+
63
+ ### OpenCode v2 (`next`)
64
+
65
+ OpenCode v2 uses the plural `plugins` configuration key. Because npm's default tag points to the v1 line, specify `@next` if you want to track the newest v2 prerelease:
40
66
 
41
67
  ```json
42
68
  {
43
- "plugins": ["@ex-machina/opencode-anthropic-auth@<2.x.y-next.N>"]
69
+ "plugins": ["@ex-machina/opencode-anthropic-auth@next"]
44
70
  }
45
71
  ```
46
72
 
47
- The v2 line ships as prereleases on npm's `next` tag, so substitute a version that actually exists — `npm view @ex-machina/opencode-anthropic-auth dist-tags` shows the current one. Pin that exact version rather than tracking `@next`, which moves on every prerelease publish.
73
+ For a stable setup, look up the exact version currently published on `next`:
74
+
75
+ ```bash
76
+ npm view @ex-machina/opencode-anthropic-auth dist-tags.next
77
+ ```
78
+
79
+ Substitute the command output for `<version>`:
80
+
81
+ ```json
82
+ {
83
+ "plugins": ["@ex-machina/opencode-anthropic-auth@<version>"]
84
+ }
85
+ ```
48
86
 
49
87
  ## Authentication Methods
50
88
 
51
- - **Claude Pro/Max** - OAuth flow via `claude.ai` for Pro/Max subscribers. Uses your existing subscription at no additional API cost.
52
- - run the `/connect` command, select `Anthropic` -> `Claude Pro/Max` and do OAuth
53
- - **Manually enter API Key / `ANTHROPIC_API_KEY`** - Handled by OpenCode's built-in Anthropic integration, not by this plugin.
89
+ ### OpenCode v1
90
+
91
+ OpenCode v1 provides three authentication options:
92
+
93
+ - **Claude Pro/Max** — OAuth flow via `claude.ai` for Pro/Max subscribers. Uses your existing subscription at no additional API cost.
94
+ - Run `/connect`, select `Anthropic (API key)` -> `Claude Pro/Max`, and complete OAuth.
95
+ - **Create an API Key** — OAuth flow via `console.anthropic.com` that creates an API key on your behalf.
96
+ - **Manually enter API Key** — Standard API-key entry for users who already have one.
97
+
98
+ ### OpenCode v2
99
+
100
+ OpenCode v2 provides:
101
+
102
+ - **Claude Pro/Max** — OAuth flow via `claude.ai` for Pro/Max subscribers. Uses your existing subscription at no additional API cost.
103
+ - Run `/connect`, select `Anthropic` -> `Claude Pro/Max`, and complete OAuth.
104
+ - **Manually enter API Key / `ANTHROPIC_API_KEY`** — Handled by OpenCode's built-in Anthropic integration, not by this plugin.
54
105
 
55
106
  > [!NOTE]
56
- > The v1 release of this plugin also offered a "Create an API Key" OAuth flow (via `console.anthropic.com`) that minted and stored an API key for you. OpenCode v2's plugin API does not yet support an OAuth authorization flow that ends in a stored API key, so that flow isn't available in this v2 release. Use manual API key entry (or `ANTHROPIC_API_KEY`) in the meantime — see [issue #203](https://github.com/ex-machina-co/opencode-anthropic-auth/issues/203) for status.
57
- >
58
- > OpenCode v2 continues to display Anthropic's API prices for these models even though requests authenticated through Claude Pro/Max use the subscription. Dynamic cost display is deferred until the beta plugin API can safely cancel the required connection event subscription.
107
+ > OpenCode v1 also offers a "Create an API Key" OAuth flow that mints and stores an API key. OpenCode v2's plugin API cannot yet complete an OAuth flow by storing a generated API key, so that option is unavailable in v2. Use manual API-key entry or `ANTHROPIC_API_KEY` in the meantime; see [issue #203](https://github.com/ex-machina-co/opencode-anthropic-auth/issues/203) for status.
59
108
 
60
109
  ## Configuration
61
110
 
62
- The plugin supports the following environment variables:
111
+ The plugin reads the following environment variables:
112
+
113
+ - **`ANTHROPIC_BASE_URL`** — Overrides the Anthropic API endpoint for both release lines, such as when using a proxy. Must be a valid HTTP(S) URL.
114
+ - **`ANTHROPIC_INSECURE`** — Skips TLS certificate verification. Behavior differs by OpenCode version:
115
+ - **OpenCode v1** — Set to `1` or `true` to skip verification. Only effective when `ANTHROPIC_BASE_URL` is also set.
116
+ - **OpenCode v2** — Not supported. OpenCode v2 plugin request hooks cannot disable TLS verification. If set, the plugin logs a warning and leaves verification enabled; requests to an untrusted or self-signed `ANTHROPIC_BASE_URL` will fail.
117
+ - **`ANTHROPIC_CLAUDE_CODE_VERSION`** — Overrides the Claude Code version reported to Anthropic for both release lines. Must be `major.minor.patch` (for example, `2.1.258`). Defaults to the bundled version; a malformed value is logged and the bundled version is used instead. A value older than the bundled version is honored but logs a warning, since reporting an older version can make newer models reject the request. Read once when the plugin loads, so restart OpenCode after changing it.
63
118
 
64
- | Variable | Description |
65
- |-----------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
66
- | `ANTHROPIC_BASE_URL` | Override the API endpoint URL (e.g. for proxying). Must be a valid HTTP(S) URL. |
67
- | `ANTHROPIC_INSECURE` | **Not supported under OpenCode v2.** OpenCode v2 plugin request hooks can rewrite a request but cannot disable TLS verification for it. If this is set, the plugin logs a warning and leaves TLS verification enabled — requests to a self-signed/untrusted `ANTHROPIC_BASE_URL` will fail. |
119
+ Anthropic gates model access on the reported Claude Code version server-side, returning a 400 `claude_code_version_too_old` error for models that require a newer client. `ANTHROPIC_CLAUDE_CODE_VERSION` lets you raise the reported version without waiting for a plugin release.
68
120
 
69
121
  ## How It Works
70
122
 
71
- For Claude Pro/Max authentication, the plugin:
123
+ For Claude Pro/Max authentication, both release lines:
72
124
 
73
- 1. Initiates a PKCE OAuth flow against Anthropic's authorization endpoint
74
- 2. Exchanges the authorization code for access and refresh tokens
75
- 3. Automatically refreshes expired tokens
76
- 4. Injects the required OAuth headers and beta flags into API requests
77
- 5. Sanitizes the system prompt for compatibility (see below)
125
+ 1. Initiate a PKCE OAuth flow against Anthropic's authorization endpoint
126
+ 2. Exchange the authorization code for access and refresh tokens
127
+ 3. Automatically refresh expired tokens
128
+ 4. Inject the required OAuth headers and beta flags into API requests
129
+ 5. Sanitize the system prompt for compatibility (see below)
130
+
131
+ Model-cost display differs by OpenCode version:
132
+
133
+ - **OpenCode v1** — The plugin zeros out displayed model costs because usage is covered by the subscription.
134
+ - **OpenCode v2** — OpenCode continues to display Anthropic's API prices even though requests authenticated through Claude Pro/Max use the subscription. Dynamic cost display is deferred until the beta plugin API can safely cancel the required connection event subscription.
78
135
 
79
136
  ### System Prompt Sanitization
80
137
 
@@ -102,9 +159,14 @@ This does three things:
102
159
  2. Symlinks the build output into `.opencode/plugins/` so OpenCode loads it as a local plugin
103
160
  3. Starts `tsc --watch` for automatic rebuilds on source changes
104
161
 
105
- After starting the dev script, restart OpenCode v2 (`opencode2`) in this project directory to pick up the local build. Any edits to `src/` will trigger a rebuild — restart OpenCode again to load the new version.
162
+ After starting the dev script:
163
+
164
+ - On the `main` branch, restart OpenCode in this project directory.
165
+ - On the `v2/main` branch, restart OpenCode v2 (`opencode2`) in this project directory.
106
166
 
107
- You can confirm the plugin loaded correctly via the OpenCode v2 API:
167
+ Edits to `src/` trigger a rebuild; restart the corresponding OpenCode version again to load the new build.
168
+
169
+ You can confirm that the v2 plugin loaded through the OpenCode v2 API:
108
170
 
109
171
  ```bash
110
172
  opencode2 api get /api/plugin # should list "ex-machina.anthropic-auth"
@@ -128,9 +190,12 @@ This project uses [changesets](https://github.com/changesets/changesets) for ver
128
190
  bun change # create a changeset describing your changes
129
191
  ```
130
192
 
131
- Changesets merged to a release branch cause CI to open a release PR; merging that PR publishes to npm. This repository runs two release trains — `main` publishes the v1 line to npm's `latest`, and `v2/main` publishes the v2 line to `next` as `2.x.y-next.N` prereleases.
193
+ Changesets merged to a release branch cause CI to open a release PR; merging that PR publishes to npm. The repository has two release trains:
194
+
195
+ - `main` publishes plugin v1 for OpenCode v1 to npm's `latest` tag.
196
+ - `v2/main` publishes plugin v2 prereleases for OpenCode v2 to npm's `next` tag.
132
197
 
133
- Maintainers: see [RELEASING.md](RELEASING.md) for the full runbook, including how `main` is synced into `v2/main`.
198
+ Maintainers can find the complete two-train release and branch-sync process in the [release runbook](https://github.com/ex-machina-co/opencode-anthropic-auth/blob/v2/main/RELEASING.md).
134
199
 
135
200
  ## License
136
201
 
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Environment variable that overrides the reported Claude Code version.
3
+ *
4
+ * Anthropic gates model access on the reported version server-side, and that
5
+ * gate moves on Anthropic's schedule rather than this plugin's release
6
+ * schedule. The override lets users unblock a newly-gated model without
7
+ * waiting for a published bump.
8
+ */
9
+ export declare const ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR = "ANTHROPIC_CLAUDE_CODE_VERSION";
10
+ /**
11
+ * Outcome of reading the version override.
12
+ *
13
+ * The invalid arm carries no version: a malformed override must never reach
14
+ * the request path, so callers cannot accidentally report one. The outdated
15
+ * arm does carry one — an explicit older version is still honoured — but pairs
16
+ * it with the warning explaining why reporting it is risky.
17
+ */
18
+ export type ClaudeCodeVersionResolution = {
19
+ readonly type: 'success';
20
+ readonly version: string;
21
+ } | {
22
+ readonly type: 'outdated';
23
+ readonly version: string;
24
+ readonly warning: string;
25
+ } | {
26
+ readonly type: 'invalid';
27
+ readonly error: string;
28
+ };
29
+ /**
30
+ * Resolve the Claude Code version to report to Anthropic.
31
+ *
32
+ * Returns the bundled version when the override is unset. A set override is
33
+ * trimmed and must look like a Claude Code release; anything else resolves to
34
+ * `invalid` with a message describing how to correct it. An override older
35
+ * than the bundled version resolves to `outdated`: it is still reported, since
36
+ * it was set deliberately, but it can lock the user out of newer models.
37
+ * Never throws.
38
+ */
39
+ export declare function resolveClaudeCodeVersion(raw?: string | undefined): ClaudeCodeVersionResolution;
package/dist/config.js ADDED
@@ -0,0 +1,77 @@
1
+ import { CLAUDE_CODE_VERSION } from "./constants.js";
2
+ /**
3
+ * Environment variable that overrides the reported Claude Code version.
4
+ *
5
+ * Anthropic gates model access on the reported version server-side, and that
6
+ * gate moves on Anthropic's schedule rather than this plugin's release
7
+ * schedule. The override lets users unblock a newly-gated model without
8
+ * waiting for a published bump.
9
+ */
10
+ export const ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR = 'ANTHROPIC_CLAUDE_CODE_VERSION';
11
+ /**
12
+ * Claude Code releases are `major.minor.patch` with numeric components.
13
+ *
14
+ * Leading zeros are rejected: `02.1.258` is not a release Anthropic publishes,
15
+ * so accepting it would report a version string no server-side gate expects.
16
+ */
17
+ const VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
18
+ /**
19
+ * Is `candidate` an older Claude Code release than `baseline`?
20
+ *
21
+ * Both arguments must already match `VERSION_PATTERN`. Components are compared
22
+ * numerically rather than lexically — `2.1.99` sorts after `2.1.258` as a
23
+ * string but is the older release — and as `BigInt`, so an unbounded component
24
+ * cannot silently lose precision the way `Number` would.
25
+ */
26
+ function isOlderVersion(candidate, baseline) {
27
+ // The `0n` defaults are unreachable — `VERSION_PATTERN` guarantees exactly
28
+ // three components — but they keep the destructuring free of assertions.
29
+ const [major = 0n, minor = 0n, patch = 0n] = candidate
30
+ .split('.')
31
+ .map((part) => BigInt(part));
32
+ const [baseMajor = 0n, baseMinor = 0n, basePatch = 0n] = baseline
33
+ .split('.')
34
+ .map((part) => BigInt(part));
35
+ if (major !== baseMajor)
36
+ return major < baseMajor;
37
+ if (minor !== baseMinor)
38
+ return minor < baseMinor;
39
+ return patch < basePatch;
40
+ }
41
+ /**
42
+ * Resolve the Claude Code version to report to Anthropic.
43
+ *
44
+ * Returns the bundled version when the override is unset. A set override is
45
+ * trimmed and must look like a Claude Code release; anything else resolves to
46
+ * `invalid` with a message describing how to correct it. An override older
47
+ * than the bundled version resolves to `outdated`: it is still reported, since
48
+ * it was set deliberately, but it can lock the user out of newer models.
49
+ * Never throws.
50
+ */
51
+ export function resolveClaudeCodeVersion(raw = process.env[ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR]) {
52
+ if (raw === undefined) {
53
+ return { type: 'success', version: CLAUDE_CODE_VERSION };
54
+ }
55
+ const trimmed = raw.trim();
56
+ if (!VERSION_PATTERN.test(trimmed)) {
57
+ return {
58
+ type: 'invalid',
59
+ error: `${ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR} is set to ${JSON.stringify(raw)}, which is not a ` +
60
+ `Claude Code version. Expected major.minor.patch (for example, ${CLAUDE_CODE_VERSION}). ` +
61
+ `Reporting the bundled version ${CLAUDE_CODE_VERSION} instead; correct or unset ` +
62
+ `${ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR} and restart OpenCode to use the override.`,
63
+ };
64
+ }
65
+ if (isOlderVersion(trimmed, CLAUDE_CODE_VERSION)) {
66
+ return {
67
+ type: 'outdated',
68
+ version: trimmed,
69
+ warning: `${ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR} is set to ${JSON.stringify(trimmed)}, which is older ` +
70
+ `than the bundled Claude Code version ${CLAUDE_CODE_VERSION}. Anthropic gates model access on ` +
71
+ `the reported version, so reporting an older one can make newer models reject the request. ` +
72
+ `Set ${ANTHROPIC_CLAUDE_CODE_VERSION_ENV_VAR} to ${CLAUDE_CODE_VERSION} or newer — or unset it ` +
73
+ `to use the bundled version — and restart OpenCode.`,
74
+ };
75
+ }
76
+ return { type: 'success', version: trimmed };
77
+ }
@@ -24,7 +24,15 @@ export declare const CCH_POSITIONS: number[];
24
24
  */
25
25
  export declare const CLAUDE_CODE_VERSION = "2.1.258";
26
26
  export declare const CLAUDE_CODE_ENTRYPOINT = "sdk-cli";
27
- export declare const USER_AGENT = "claude-cli/2.1.258 (external, cli)";
27
+ /**
28
+ * Build the `user-agent` value for a reported Claude Code version.
29
+ *
30
+ * Both places we report the version (this header and the billing header's
31
+ * `cc_version`) must agree, so callers pass the same resolved version to each
32
+ * rather than reading a second, independently-derived constant.
33
+ */
34
+ export declare function formatUserAgent(version: string): string;
35
+ export declare const USER_AGENT: string;
28
36
  /**
29
37
  * Anchors that identify paragraphs to remove from the system prompt.
30
38
  * Any paragraph (text between blank lines) containing one of these
package/dist/constants.js CHANGED
@@ -34,7 +34,17 @@ export const CCH_POSITIONS = [4, 7, 20];
34
34
  */
35
35
  export const CLAUDE_CODE_VERSION = '2.1.258';
36
36
  export const CLAUDE_CODE_ENTRYPOINT = 'sdk-cli';
37
- export const USER_AGENT = `claude-cli/${CLAUDE_CODE_VERSION} (external, cli)`;
37
+ /**
38
+ * Build the `user-agent` value for a reported Claude Code version.
39
+ *
40
+ * Both places we report the version (this header and the billing header's
41
+ * `cc_version`) must agree, so callers pass the same resolved version to each
42
+ * rather than reading a second, independently-derived constant.
43
+ */
44
+ export function formatUserAgent(version) {
45
+ return `claude-cli/${version} (external, cli)`;
46
+ }
47
+ export const USER_AGENT = formatUserAgent(CLAUDE_CODE_VERSION);
38
48
  /**
39
49
  * Anchors that identify paragraphs to remove from the system prompt.
40
50
  * Any paragraph (text between blank lines) containing one of these
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Plugin } from '@opencode-ai/plugin';
2
2
  import { authorize, exchange, refreshToken } from "./auth.js";
3
- import { REQUIRED_BETAS } from "./constants.js";
3
+ import { resolveClaudeCodeVersion } from "./config.js";
4
+ import { CLAUDE_CODE_VERSION, REQUIRED_BETAS } from "./constants.js";
4
5
  import { createStrippedStream, isInsecure, mergeHeaders, rewriteRequestBody, rewriteUrl, setOAuthHeaders, } from "./transform.js";
5
6
  const PLUGIN_ID = 'ex-machina.anthropic-auth';
6
7
  const INTEGRATION_ID = 'anthropic';
@@ -48,6 +49,20 @@ export default Plugin.define({
48
49
  id: PLUGIN_ID,
49
50
  setup: async (ctx) => {
50
51
  warnIfInsecureUnsupported();
52
+ // Resolved once per plugin instance so every request reports the same
53
+ // version in both the user-agent and the billing header.
54
+ const versionResolution = resolveClaudeCodeVersion();
55
+ if (versionResolution.type === 'invalid') {
56
+ console.error(`[ex-machina.anthropic-auth] ${versionResolution.error}`);
57
+ }
58
+ else if (versionResolution.type === 'outdated') {
59
+ console.warn(`[ex-machina.anthropic-auth] ${versionResolution.warning}`);
60
+ }
61
+ // Only a malformed override lacks a usable version; an outdated one was
62
+ // set deliberately, so it is reported as configured.
63
+ const claudeCodeVersion = versionResolution.type === 'invalid'
64
+ ? CLAUDE_CODE_VERSION
65
+ : versionResolution.version;
51
66
  // Retain successful refreshes for this plugin generation so a host call
52
67
  // holding the rotated token cannot submit it again before persistence.
53
68
  const refreshInFlight = new Map();
@@ -116,9 +131,11 @@ export default Plugin.define({
116
131
  const request = event.request;
117
132
  const hasBody = request.method !== 'GET' && request.method !== 'HEAD';
118
133
  const bodyText = hasBody ? await request.clone().text() : undefined;
119
- const rewrittenBody = bodyText !== undefined ? rewriteRequestBody(bodyText) : undefined;
134
+ const rewrittenBody = bodyText !== undefined
135
+ ? rewriteRequestBody(bodyText, claudeCodeVersion)
136
+ : undefined;
120
137
  const headers = mergeHeaders(request);
121
- setOAuthHeaders(headers, credential.access);
138
+ setOAuthHeaders(headers, credential.access, claudeCodeVersion);
122
139
  if (rewrittenBody !== undefined)
123
140
  headers.delete('content-length');
124
141
  const { input: rewrittenInput } = rewriteUrl(request.url);
@@ -13,8 +13,11 @@ export declare function mergeBetaHeaders(headers: Headers): string;
13
13
  /**
14
14
  * Set OAuth-required headers on the request: authorization, beta, user-agent.
15
15
  * Removes x-api-key since we're using OAuth.
16
+ *
17
+ * `version` must be the same value passed to rewriteRequestBody for the same
18
+ * request, otherwise the two reported versions disagree.
16
19
  */
17
- export declare function setOAuthHeaders(headers: Headers, accessToken: string): Headers;
20
+ export declare function setOAuthHeaders(headers: Headers, accessToken: string, version?: string): Headers;
18
21
  /**
19
22
  * Add TOOL_PREFIX to tool names in the request body.
20
23
  * Prefixes both tool definitions and tool_use blocks in messages.
@@ -66,8 +69,11 @@ type SystemBlock = {
66
69
  export declare function prependClaudeCodeIdentity(system: unknown): SystemBlock[];
67
70
  /**
68
71
  * Rewrite the full request body: sanitize system prompt and prefix tool names.
72
+ *
73
+ * `version` must be the same value passed to setOAuthHeaders for the same
74
+ * request, otherwise the two reported versions disagree.
69
75
  */
70
- export declare function rewriteRequestBody(body: string): string;
76
+ export declare function rewriteRequestBody(body: string, version?: string): string;
71
77
  /**
72
78
  * Create a streaming response that strips the tool prefix from tool names.
73
79
  */
package/dist/transform.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { buildBillingHeaderValue } from "./cch.js";
2
- import { CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, OPENCODE_IDENTITY_PREFIX, PARAGRAPH_REMOVAL_ANCHORS, REQUIRED_BETAS, TEXT_REPLACEMENTS, TOOL_PREFIX, USER_AGENT, } from "./constants.js";
2
+ import { CLAUDE_CODE_ENTRYPOINT, CLAUDE_CODE_IDENTITY, CLAUDE_CODE_VERSION, formatUserAgent, OPENCODE_IDENTITY_PREFIX, PARAGRAPH_REMOVAL_ANCHORS, REQUIRED_BETAS, TEXT_REPLACEMENTS, TOOL_PREFIX, } from "./constants.js";
3
3
  // Bound an incomplete SSE line so malformed streams cannot grow memory forever.
4
4
  export const MAX_SSE_LINE_BYTES = 5 * 1024 * 1024;
5
5
  function headersAfterBodyTransform(source) {
@@ -271,11 +271,14 @@ export function mergeBetaHeaders(headers) {
271
271
  /**
272
272
  * Set OAuth-required headers on the request: authorization, beta, user-agent.
273
273
  * Removes x-api-key since we're using OAuth.
274
+ *
275
+ * `version` must be the same value passed to rewriteRequestBody for the same
276
+ * request, otherwise the two reported versions disagree.
274
277
  */
275
- export function setOAuthHeaders(headers, accessToken) {
278
+ export function setOAuthHeaders(headers, accessToken, version = CLAUDE_CODE_VERSION) {
276
279
  headers.set('authorization', `Bearer ${accessToken}`);
277
280
  headers.set('anthropic-beta', mergeBetaHeaders(headers));
278
- headers.set('user-agent', USER_AGENT);
281
+ headers.set('user-agent', formatUserAgent(version));
279
282
  headers.delete('x-api-key');
280
283
  return headers;
281
284
  }
@@ -467,13 +470,16 @@ export function prependClaudeCodeIdentity(system) {
467
470
  }
468
471
  /**
469
472
  * Rewrite the full request body: sanitize system prompt and prefix tool names.
473
+ *
474
+ * `version` must be the same value passed to setOAuthHeaders for the same
475
+ * request, otherwise the two reported versions disagree.
470
476
  */
471
- export function rewriteRequestBody(body) {
477
+ export function rewriteRequestBody(body, version = CLAUDE_CODE_VERSION) {
472
478
  try {
473
479
  const parsed = JSON.parse(body);
474
480
  const billingHeader = Array.isArray(parsed.messages) &&
475
481
  parsed.messages.some((message) => message.role === 'user')
476
- ? buildBillingHeaderValue(parsed.messages, undefined, CLAUDE_CODE_ENTRYPOINT)
482
+ ? buildBillingHeaderValue(parsed.messages, version, CLAUDE_CODE_ENTRYPOINT)
477
483
  : null;
478
484
  // Sanitize system prompt and prepend Claude Code identity
479
485
  parsed.system = prependClaudeCodeIdentity(parsed.system);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ex-machina/opencode-anthropic-auth",
3
- "version": "2.0.0-next.0",
3
+ "version": "2.0.0-next.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -24,6 +24,7 @@
24
24
  "check": "bun turbo check:all",
25
25
  "test": "bun test",
26
26
  "types": "tsc",
27
+ "check:package": "bun run build && bun scripts/check-package.ts",
27
28
  "format": "biome check --write --unsafe",
28
29
  "format:check": "biome format .",
29
30
  "lint": "biome lint --error-on-warnings .",