Skip to content

Commit 0488f5c

Browse files
committed
fix(copilot): Adds cache to model lookup call
1 parent 847fc9d commit 0488f5c

File tree

1 file changed

+36
-11
lines changed
  • packages/opencode/src/plugin/github-copilot

1 file changed

+36
-11
lines changed

packages/opencode/src/plugin/github-copilot/copilot.ts

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
22
import type { Model } from "@opencode-ai/sdk/v2"
3+
import { Global } from "@/global"
34
import { Installation } from "@/installation"
45
import { iife } from "@/util/iife"
6+
import { Filesystem } from "@/util/filesystem"
7+
import { Hash } from "@/util/hash"
58
import { Log } from "../../util/log"
69
import { setTimeout as sleep } from "node:timers/promises"
10+
import path from "path"
711
import { CopilotModels } from "./models"
812

913
const log = Log.create({ service: "plugin.copilot" })
14+
const ttl = 60 * 60 * 1000
15+
16+
function cachefile(url: string) {
17+
return path.join(Global.Path.cache, `copilot-models-${Hash.fast(url)}.json`)
18+
}
19+
20+
function fresh(file: string) {
21+
return Date.now() - Number(Filesystem.stat(file)?.mtimeMs ?? 0) < ttl
22+
}
1023

1124
const CLIENT_ID = "Ov23li8tweQw6odWQebz"
1225
// Add a small safety buffer when polling to avoid hitting the server
@@ -47,17 +60,29 @@ export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
4760
return Object.fromEntries(Object.entries(provider.models).map(([id, model]) => [id, fix(model)]))
4861
}
4962

50-
return CopilotModels.get(
51-
base(ctx.auth.enterpriseUrl),
52-
{
53-
Authorization: `Bearer ${ctx.auth.refresh}`,
54-
"User-Agent": `opencode/${Installation.VERSION}`,
55-
},
56-
provider.models,
57-
).catch((error) => {
58-
log.error("failed to fetch copilot models", { error })
59-
return Object.fromEntries(Object.entries(provider.models).map(([id, model]) => [id, fix(model)]))
60-
})
63+
const url = base(ctx.auth.enterpriseUrl)
64+
const file = cachefile(url)
65+
const headers = {
66+
Authorization: `Bearer ${ctx.auth.refresh}`,
67+
"User-Agent": `opencode/${Installation.VERSION}`,
68+
}
69+
70+
if (fresh(file)) {
71+
const cached = await Bun.file(file)
72+
.json()
73+
.catch(() => undefined)
74+
if (cached) return cached as Record<string, Model>
75+
}
76+
77+
return CopilotModels.get(url, headers, provider.models)
78+
.then(async (result) => {
79+
await Bun.write(file, JSON.stringify(result))
80+
return result
81+
})
82+
.catch((error) => {
83+
log.error("failed to fetch copilot models", { error })
84+
return Object.fromEntries(Object.entries(provider.models).map(([id, model]) => [id, fix(model)]))
85+
})
6186
},
6287
},
6388
auth: {

0 commit comments

Comments
 (0)