Skip to content

Commit 4c2cf2a

Browse files
committed
Add Copilot model multipliers via IDE-auth models API
1 parent 80a5c3d commit 4c2cf2a

3 files changed

Lines changed: 303 additions & 3 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/component/dialog-model.tsx‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { useDialog } from "@tui/ui/dialog"
77
import { createDialogProviderOptions, DialogProvider } from "./dialog-provider"
88
import { useKeybind } from "../context/keybind"
99
import * as fuzzysort from "fuzzysort"
10+
import type { Provider } from "@opencode-ai/sdk/v2"
1011

1112
export function useConnected() {
1213
const sync = useSync()
@@ -15,6 +16,21 @@ export function useConnected() {
1516
)
1617
}
1718

19+
function getMultiplier(providerID: string, model: Provider["models"][string]) {
20+
if (!providerID.startsWith("github-copilot")) return
21+
const billing = (model as { billing?: { multiplier?: number } }).billing
22+
const multiplier = billing?.multiplier
23+
if (typeof multiplier !== "number") return
24+
if (!Number.isFinite(multiplier)) return
25+
return `${multiplier}x`
26+
}
27+
28+
function getFooter(providerID: string, model: Provider["models"][string]) {
29+
const multiplier = getMultiplier(providerID, model)
30+
if (multiplier) return multiplier
31+
if (providerID === "opencode" && model.cost?.input === 0) return "Free"
32+
}
33+
1834
export function DialogModel(props: { providerID?: string }) {
1935
const local = useLocal()
2036
const sync = useSync()
@@ -62,7 +78,7 @@ export function DialogModel(props: { providerID?: string }) {
6278
description: provider.name,
6379
category: "Favorites",
6480
disabled: provider.id === "opencode" && model.id.includes("-nano"),
65-
footer: model.cost?.input === 0 && provider.id === "opencode" ? "Free" : undefined,
81+
footer: getFooter(provider.id, model),
6682
onSelect: () => {
6783
dialog.clear()
6884
local.model.set(
@@ -95,7 +111,7 @@ export function DialogModel(props: { providerID?: string }) {
95111
description: provider.name,
96112
category: "Recent",
97113
disabled: provider.id === "opencode" && model.id.includes("-nano"),
98-
footer: model.cost?.input === 0 && provider.id === "opencode" ? "Free" : undefined,
114+
footer: getFooter(provider.id, model),
99115
onSelect: () => {
100116
dialog.clear()
101117
local.model.set(
@@ -138,7 +154,7 @@ export function DialogModel(props: { providerID?: string }) {
138154
: undefined,
139155
category: connected() ? provider.name : undefined,
140156
disabled: provider.id === "opencode" && model.includes("-nano"),
141-
footer: info.cost?.input === 0 && provider.id === "opencode" ? "Free" : undefined,
157+
footer: getFooter(provider.id, info),
142158
onSelect() {
143159
dialog.clear()
144160
local.model.set(

‎packages/opencode/src/plugin/copilot.ts‎

Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import path from "path"
12
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
23
import { Installation } from "@/installation"
34
import { iife } from "@/util/iife"
5+
import type { Provider } from "@/provider/provider"
6+
import { Global } from "@/global"
47

58
const CLIENT_ID = "Ov23li8tweQw6odWQebz"
69
// Add a small safety buffer when polling to avoid hitting the server
@@ -17,6 +20,272 @@ function getUrls(domain: string) {
1720
}
1821
}
1922

23+
type CopilotModel = {
24+
id?: string
25+
model?: string
26+
name?: string
27+
display_name?: string
28+
multiplier?: number
29+
rate_multiplier?: number
30+
relative_cost?: number
31+
relative_cost_multiplier?: number
32+
cost_multiplier?: number
33+
billing?: {
34+
multiplier?: number
35+
rate_multiplier?: number
36+
}
37+
}
38+
39+
type CopilotModelsResponse = {
40+
data?: CopilotModel[]
41+
models?: CopilotModel[]
42+
}
43+
44+
function getModelsUrl(base: string) {
45+
if (base.endsWith("/")) return `${base}models`
46+
return `${base}/models`
47+
}
48+
49+
function getGitHubApiBase(enterpriseUrl?: string) {
50+
if (!enterpriseUrl) return "https://api.github.com"
51+
const domain = normalizeDomain(enterpriseUrl)
52+
if (domain.startsWith("api.")) return `https://${domain}`
53+
return `https://${domain}/api/v3`
54+
}
55+
56+
type CopilotTokenResponse = {
57+
token?: string
58+
endpoints?: {
59+
api?: string
60+
}
61+
}
62+
63+
let cache: Record<string, string> | undefined
64+
let idsCache: Record<string, string> | undefined
65+
66+
function format(value: string | undefined, prefix: string) {
67+
if (!value) return
68+
const trimmed = value.trim()
69+
if (!trimmed) return
70+
if (trimmed.includes("/")) return trimmed
71+
return `${prefix}/${trimmed}`
72+
}
73+
74+
function clean(value: string | undefined) {
75+
if (!value) return
76+
const trimmed = value.trim()
77+
if (!trimmed) return
78+
return trimmed
79+
}
80+
81+
function codeVersion() {
82+
const bin = Bun.which("code")
83+
if (!bin) return
84+
const result = Bun.spawnSync([bin, "--version"])
85+
if (result.exitCode !== 0) return
86+
const text = result.stdout.toString().trim()
87+
const line = text.split("\n")[0]?.trim()
88+
if (!line) return
89+
return line
90+
}
91+
92+
async function chatVersion() {
93+
const extensions = path.join(Global.Path.home, ".vscode", "extensions")
94+
const glob = new Bun.Glob("github.copilot-chat-*")
95+
for await (const entry of glob.scan({ cwd: extensions, onlyFiles: false })) {
96+
const match = /github\.copilot-chat-([0-9.]+)/.exec(entry)
97+
if (match) return match[1]
98+
const info = await Bun.file(path.join(extensions, entry, "package.json")).json().catch(() => undefined)
99+
const version = info?.version
100+
if (typeof version === "string") return version
101+
}
102+
}
103+
104+
async function editor() {
105+
if (cache) return cache
106+
const ed = format(Bun.env.OPENCODE_COPILOT_EDITOR_VERSION, "vscode")
107+
const plugin = format(Bun.env.OPENCODE_COPILOT_EDITOR_PLUGIN_VERSION, "copilot-chat")
108+
if (ed || plugin) {
109+
cache = {
110+
"Editor-Version": ed ?? `opencode/${Installation.VERSION}`,
111+
"Editor-Plugin-Version": plugin ?? `opencode/${Installation.VERSION}`,
112+
}
113+
return cache
114+
}
115+
116+
const code = codeVersion()
117+
const chat = await chatVersion()
118+
cache = {
119+
"Editor-Version": format(code, "vscode") ?? `opencode/${Installation.VERSION}`,
120+
"Editor-Plugin-Version": format(chat, "copilot-chat") ?? `opencode/${Installation.VERSION}`,
121+
}
122+
return cache
123+
}
124+
125+
async function ids() {
126+
if (idsCache) return idsCache
127+
const file = path.join(Global.Path.state, "copilot-ids.json")
128+
const env = {
129+
session: clean(Bun.env.OPENCODE_COPILOT_SESSION_ID),
130+
machine: clean(Bun.env.OPENCODE_COPILOT_MACHINE_ID),
131+
integration: clean(Bun.env.OPENCODE_COPILOT_INTEGRATION_ID),
132+
}
133+
const payload = (await Bun.file(file).json().catch(() => undefined)) as
134+
| {
135+
session?: unknown
136+
machine?: unknown
137+
}
138+
| undefined
139+
const stored = {
140+
session: typeof payload?.session === "string" ? payload.session : undefined,
141+
machine: typeof payload?.machine === "string" ? payload.machine : undefined,
142+
}
143+
const session = env.session ?? stored.session ?? crypto.randomUUID()
144+
const machine = env.machine ?? stored.machine ?? crypto.randomUUID()
145+
if (!env.session && !env.machine) {
146+
if (session !== stored.session || machine !== stored.machine) {
147+
await Bun.file(file).write(JSON.stringify({ session, machine }, null, 2))
148+
}
149+
}
150+
idsCache = {
151+
"Copilot-Integration-Id": env.integration ?? "vscode-chat",
152+
"VScode-SessionId": session,
153+
"VScode-MachineId": machine,
154+
}
155+
return idsCache
156+
}
157+
158+
function getCopilotToken(value: unknown) {
159+
if (!value || typeof value !== "object") return
160+
const token = (value as { oauth_token?: unknown }).oauth_token
161+
if (typeof token === "string") return token
162+
}
163+
164+
async function loadCopilotGitHubToken() {
165+
const payload = await Bun.file(path.join(Global.Path.home, ".config", "github-copilot", "apps.json"))
166+
.json()
167+
.catch(() => undefined)
168+
if (!payload) return
169+
if (Array.isArray(payload)) return payload.map(getCopilotToken).find(Boolean)
170+
const direct = getCopilotToken(payload)
171+
if (direct) return direct
172+
const record = payload as Record<string, unknown>
173+
if (Array.isArray(record.apps)) return record.apps.map(getCopilotToken).find(Boolean)
174+
return Object.values(record).map(getCopilotToken).find(Boolean)
175+
}
176+
177+
async function fetchCopilotToken(githubToken?: string, enterpriseUrl?: string) {
178+
if (!githubToken) return
179+
const base = getGitHubApiBase(enterpriseUrl)
180+
const response = await fetch(`${base}/copilot_internal/v2/token`, {
181+
headers: {
182+
Authorization: `token ${githubToken}`,
183+
"X-GitHub-Api-Version": "2025-04-01",
184+
"User-Agent": `opencode/${Installation.VERSION}`,
185+
Accept: "application/json",
186+
},
187+
}).catch(() => undefined)
188+
189+
if (!response?.ok) return
190+
const payload = (await response.json().catch(() => undefined)) as CopilotTokenResponse | undefined
191+
if (!payload?.token) return
192+
return {
193+
token: payload.token,
194+
api: payload.endpoints?.api,
195+
}
196+
}
197+
198+
function normalizeKey(value: string) {
199+
return value.trim().toLowerCase()
200+
}
201+
202+
function expandKey(value: string) {
203+
const key = normalizeKey(value)
204+
const parts = key.split("/")
205+
const tail = parts[parts.length - 1]
206+
if (tail && tail !== key) return [key, tail]
207+
return [key]
208+
}
209+
210+
function getMultiplierFromModel(model: CopilotModel) {
211+
const candidates = [
212+
model.billing?.multiplier,
213+
model.billing?.rate_multiplier,
214+
model.multiplier,
215+
model.rate_multiplier,
216+
model.relative_cost_multiplier,
217+
model.relative_cost,
218+
model.cost_multiplier,
219+
]
220+
const value = candidates.find((item) => typeof item === "number" && Number.isFinite(item))
221+
if (value === undefined) return
222+
return value as number
223+
}
224+
225+
async function applyCopilotMultipliers(provider: Provider.Info | undefined, token: string, baseURL?: string) {
226+
if (!provider?.models) return
227+
if (!token) return
228+
229+
const first = Object.values(provider.models)[0]
230+
const base = baseURL ?? first?.api?.url
231+
if (!base) return
232+
233+
async function fetchModels(url: string) {
234+
const headers = await editor()
235+
const meta = await ids()
236+
const response = await fetch(url, {
237+
headers: {
238+
Authorization: `Bearer ${token}`,
239+
"Editor-Version": headers["Editor-Version"],
240+
"Editor-Plugin-Version": headers["Editor-Plugin-Version"],
241+
"Copilot-Integration-Id": meta["Copilot-Integration-Id"],
242+
"VScode-SessionId": meta["VScode-SessionId"],
243+
"VScode-MachineId": meta["VScode-MachineId"],
244+
"X-GitHub-Api-Version": "2025-10-01",
245+
"x-initiator": "user",
246+
"Openai-Intent": "model-access",
247+
"User-Agent": `opencode/${Installation.VERSION}`,
248+
Accept: "application/json",
249+
},
250+
}).catch(() => undefined)
251+
252+
if (!response?.ok) return []
253+
const payload = (await response.json().catch(() => undefined)) as CopilotModelsResponse | undefined
254+
return Array.isArray(payload?.data)
255+
? payload?.data
256+
: Array.isArray(payload?.models)
257+
? payload?.models
258+
: []
259+
}
260+
261+
const models = await fetchModels(getModelsUrl(base))
262+
263+
const multipliers = new Map<string, number>(
264+
models.flatMap((model) => {
265+
const multiplier = getMultiplierFromModel(model)
266+
if (multiplier === undefined) return []
267+
const keys = [
268+
model.id,
269+
model.model,
270+
model.name,
271+
model.display_name,
272+
].flatMap((value) => (typeof value === "string" ? expandKey(value) : []))
273+
if (!keys.length) return []
274+
return keys.map((key) => [key, multiplier] as const)
275+
}),
276+
)
277+
278+
Object.values(provider.models).forEach((model) => {
279+
if (model.billing?.multiplier !== undefined) return
280+
const multiplier =
281+
multipliers.get(normalizeKey(model.id)) ??
282+
multipliers.get(normalizeKey(model.name)) ??
283+
(model.id.includes("/") ? multipliers.get(expandKey(model.id)[1]) : undefined)
284+
if (multiplier === undefined) return
285+
model.billing = { multiplier }
286+
})
287+
}
288+
20289
export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
21290
const sdk = input.client
22291
return {
@@ -57,6 +326,15 @@ export async function CopilotAuthPlugin(input: PluginInput): Promise<Hooks> {
57326
}
58327
}
59328

329+
const copilot = await fetchCopilotToken(info.refresh, enterpriseUrl)
330+
const fallback =
331+
copilot || enterpriseUrl ? undefined : await fetchCopilotToken(await loadCopilotGitHubToken(), enterpriseUrl)
332+
await applyCopilotMultipliers(
333+
provider,
334+
fallback?.token ?? copilot?.token ?? info.refresh,
335+
fallback?.api ?? copilot?.api ?? baseURL,
336+
)
337+
60338
return {
61339
baseURL,
62340
apiKey: "",

‎packages/opencode/src/provider/provider.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,11 @@ export namespace Provider {
585585
})
586586
.optional(),
587587
}),
588+
billing: z
589+
.object({
590+
multiplier: z.number().optional(),
591+
})
592+
.optional(),
588593
limit: z.object({
589594
context: z.number(),
590595
input: z.number().optional(),
@@ -810,6 +815,7 @@ export namespace Provider {
810815
write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
811816
},
812817
},
818+
billing: existingModel?.billing,
813819
options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
814820
limit: {
815821
context: model.limit?.context ?? existingModel?.limit?.context ?? 0,

0 commit comments

Comments
 (0)