1+ import path from "path"
12import type { Hooks , PluginInput } from "@opencode-ai/plugin"
23import { Installation } from "@/installation"
34import { iife } from "@/util/iife"
5+ import type { Provider } from "@/provider/provider"
6+ import { Global } from "@/global"
47
58const 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 = / g i t h u b \. c o p i l o t - c h a t - ( [ 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+
20289export 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 : "" ,
0 commit comments