Skip to content

Commit 1c58023

Browse files
thdxropencode
andcommitted
improve anthropic oauth token caching and authentication handling
🤖 Generated with [opencode](https://opencode.ai) Co-Authored-By: opencode <[email protected]>
1 parent 4e0aa58 commit 1c58023

File tree

5 files changed

+21
-4
lines changed

5 files changed

+21
-4
lines changed

bun.lock

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

packages/opencode/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
"@types/turndown": "5.0.5",
2121
"@types/yargs": "17.0.33",
2222
"typescript": "catalog:",
23-
"zod-to-json-schema": "3.24.5"
23+
"zod-to-json-schema": "3.24.5",
24+
"@ai-sdk/anthropic": "1.2.12"
2425
},
2526
"dependencies": {
2627
"@clack/prompts": "0.11.0",

packages/opencode/src/auth/anthropic.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,15 @@ export namespace AuthAnthropic {
4848
await Auth.set("anthropic", {
4949
type: "oauth",
5050
refresh: json.refresh_token as string,
51+
access: json.access_token as string,
5152
expires: Date.now() + json.expires_in * 1000,
5253
})
5354
}
5455

5556
export async function access() {
5657
const info = await Auth.get("anthropic")
5758
if (!info || info.type !== "oauth") return
59+
if (info.access && info.expires > Date.now()) return info.access
5860
const response = await fetch(
5961
"https://console.anthropic.com/v1/oauth/token",
6062
{
@@ -74,6 +76,7 @@ export namespace AuthAnthropic {
7476
await Auth.set("anthropic", {
7577
type: "oauth",
7678
refresh: json.refresh_token as string,
79+
access: json.access_token as string,
7780
expires: Date.now() + json.expires_in * 1000,
7881
})
7982
return json.access_token as string

packages/opencode/src/auth/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export namespace Auth {
77
export const Oauth = z.object({
88
type: z.literal("oauth"),
99
refresh: z.string(),
10+
access: z.string(),
1011
expires: z.number(),
1112
})
1213

packages/opencode/src/provider/provider.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,18 @@ export namespace Provider {
5050
}
5151
return {
5252
apiKey: "",
53-
headers: {
54-
authorization: `Bearer ${access}`,
55-
"anthropic-beta": "oauth-2025-04-20",
53+
async fetch(input: any, init: any) {
54+
const access = await AuthAnthropic.access()
55+
const headers = {
56+
...init.headers,
57+
authorization: `Bearer ${access}`,
58+
"anthropic-beta": "oauth-2025-04-20",
59+
}
60+
delete headers["x-api-key"]
61+
return fetch(input, {
62+
...init,
63+
headers,
64+
})
5665
},
5766
}
5867
},

0 commit comments

Comments
 (0)