Skip to content

Commit 5b2b256

Browse files
committed
Use existing file cache instead
1 parent 9268eb6 commit 5b2b256

File tree

1 file changed

+19
-8
lines changed
  • packages/opencode/src/plugin/github-copilot

1 file changed

+19
-8
lines changed

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

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +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 = 5 * 60 * 1000
1015

11-
const modelsCache = new Map<string, Record<string, Model>>()
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+
}
1223

1324
const CLIENT_ID = "Ov23li8tweQw6odWQebz"
1425
// Add a small safety buffer when polling to avoid hitting the server
@@ -50,19 +61,19 @@ export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
5061
}
5162

5263
const url = base(ctx.auth.enterpriseUrl)
53-
const key = `${url}:${ctx.auth.refresh}`
64+
const file = cachefile(url)
5465
const headers = {
5566
Authorization: `Bearer ${ctx.auth.refresh}`,
5667
"User-Agent": `opencode/${Installation.VERSION}`,
5768
}
5869

59-
// Fire-and-forget background refresh (same pattern as models.dev)
60-
CopilotModels.get(url, headers, provider.models)
61-
.then((result) => modelsCache.set(key, result))
62-
.catch((error) => log.error("failed to fetch copilot models", { error }))
70+
if (!fresh(file)) {
71+
CopilotModels.get(url, headers, provider.models)
72+
.then((result) => Filesystem.write(file, JSON.stringify(result)))
73+
.catch((error) => log.error("failed to fetch copilot models", { error }))
74+
}
6375

64-
// Return cached result immediately, falling back to static models
65-
const cached = modelsCache.get(key)
76+
const cached = await Filesystem.readJson<Record<string, Model>>(file).catch(() => undefined)
6677
if (cached) return cached
6778
return Object.fromEntries(Object.entries(provider.models).map(([id, model]) => [id, fix(model)]))
6879
},

0 commit comments

Comments
 (0)