11import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
22import type { SessionRequestKind , SessionTitle } from "@opencode/plugin/effect/session"
33import { isRecord } from "@opencode/util/record"
4- import { Effect , Option , Schema } from "effect"
4+ import { Clock , Effect , Option , Schema } from "effect"
55import { FetchHttpClient , HttpClient , HttpClientRequest , HttpClientResponse } from "effect/http"
66import { IntegrationConnection } from "../../integration/connection.js"
77import { Credential } from "../../credential.js"
@@ -13,6 +13,7 @@ import { Agent } from "../../agent.js"
1313import { define } from "@opencode/plugin/effect/plugin"
1414import { Provider } from "../../provider.js"
1515import { SessionAffinity } from "../../session/affinity.js"
16+ import type { Session } from "@opencode/schema/session"
1617import { SharedCache } from "../../shared-cache.js"
1718import { activeCredential } from "./credential-settings.js"
1819import { ProviderRefresh } from "./refresh.js"
@@ -45,6 +46,11 @@ const User = Schema.Struct({
4546 ) ,
4647} )
4748const decodeUser = Schema . decodeUnknownOption ( User )
49+ const AutoRoute = Schema . Struct ( {
50+ session_token : Schema . String ,
51+ expires_at : Schema . Number ,
52+ selected_model : Schema . Struct ( { id : Schema . String } ) ,
53+ } )
4854const JsonBody = Schema . fromJsonString ( Schema . Unknown )
4955const decodeBody = Schema . decodeUnknownOption ( JsonBody )
5056
@@ -164,6 +170,9 @@ export const GithubCopilotPlugin = define({
164170 const cache = yield * SharedCache . Service
165171 const http = yield * HttpClient . HttpClient
166172 const outbound = yield * FetchHttpClient . Fetch
173+ // Each Session keeps the model Copilot's Auto router picked until its token nears expiry, the Session is compacted,
174+ // or the account changes. The token unlocks the pick and its Auto discount; Copilot rejects it for any other model.
175+ const routes = new Map < Session . ID , { model : string ; account : string ; token ?: string ; until : number } > ( )
167176 const discovered = yield * ProviderRefresh . start ( {
168177 integrationID : "github-copilot" ,
169178 initial : { } as {
@@ -246,11 +255,14 @@ export const GithubCopilotPlugin = define({
246255 if ( ! item ) return
247256 const loaded = discovered . current
248257 if ( loaded . models ) {
258+ const url = loaded . baseURL ?? baseURL ( )
259+ const router = CopilotModels . autoModel ( url , loaded . models )
249260 evt . add ( {
250261 info : item . provider ,
251- models : Array . from (
252- CopilotModels . derive ( loaded . baseURL ?? baseURL ( ) , loaded . models , Array . from ( item . models . values ( ) ) ) . values ( ) ,
253- ) ,
262+ models : [
263+ ...CopilotModels . derive ( url , loaded . models , Array . from ( item . models . values ( ) ) ) . values ( ) ,
264+ ...( router ? [ router ] : [ ] ) ,
265+ ] ,
254266 sourceConnection : loaded . connection ,
255267 } )
256268 return
@@ -294,6 +306,82 @@ export const GithubCopilotPlugin = define({
294306 evt . headers [ "X-Interaction-Type" ] = interaction
295307 evt . headers [ "X-Interaction-Id" ] = session ? SessionAffinity . get ( session ) : evt . sessionID
296308 if ( interaction !== "conversation-agent" ) evt . headers [ "x-initiator" ] = "agent"
309+ const route = routes . get ( evt . sessionID )
310+ if ( route ?. token && route . model === evt . model . id ) evt . headers [ "Copilot-Session-Token" ] = route . token
311+ } ) ,
312+ { providerID : Provider . ID . githubCopilot } ,
313+ )
314+ const route = Effect . fn ( "GithubCopilotPlugin.route" ) ( function * ( sessionID : Session . ID ) {
315+ const loaded = discovered . current
316+ if ( ! loaded . baseURL || ! loaded . token || ! loaded . models ) return
317+ const user = yield * ctx . session . context ( { sessionID } ) . pipe (
318+ Effect . map ( ( messages ) => messages . findLast ( ( message ) => message . type === "user" ) ) ,
319+ Effect . orElseSucceed ( ( ) => undefined ) ,
320+ )
321+ const headers = ( yield * providers . get ( Provider . ID . githubCopilot ) ) ?. headers ?? { }
322+ const picked = yield * HttpClient . filterStatusOk ( http )
323+ . execute (
324+ HttpClientRequest . post ( `${ loaded . baseURL } /auto` ) . pipe (
325+ HttpClientRequest . setHeaders ( {
326+ ...headers ,
327+ Authorization : `Bearer ${ loaded . token } ` ,
328+ "User-Agent" : App . useragent ( ctx . app ) ,
329+ "X-GitHub-Api-Version" : apiVersion ,
330+ } ) ,
331+ HttpClientRequest . bodyJsonUnsafe ( {
332+ prompt : user ?. text ?? "" ,
333+ ...( user ?. files ?. some ( ( file ) => file . mime . startsWith ( "image/" ) ) ? { has_image : true } : { } ) ,
334+ } ) ,
335+ ) ,
336+ )
337+ . pipe (
338+ Effect . flatMap ( HttpClientResponse . schemaBodyJson ( AutoRoute ) ) ,
339+ Effect . timeout ( "5 seconds" ) ,
340+ Effect . tapError ( ( cause ) => Effect . logWarning ( "Copilot Auto routing failed" , { cause } ) ) ,
341+ Effect . option ,
342+ )
343+ const now = yield * Clock . currentTimeMillis
344+ if ( Option . isSome ( picked ) && loaded . models . has ( picked . value . selected_model . id ) )
345+ return {
346+ model : picked . value . selected_model . id ,
347+ account : loaded . token ,
348+ token : picked . value . session_token ,
349+ // Route again before the token can expire mid-request.
350+ until : picked . value . expires_at * 1000 - 5 * 60_000 ,
351+ }
352+ const models = Array . from ( loaded . models . values ( ) )
353+ const fallback =
354+ models . find ( ( model ) => model . is_chat_fallback ) ?? models . find ( ( model ) => model . billing ?. auto_discount )
355+ // Retry routing soon when the router fails or picks a model this client cannot serve.
356+ return fallback && { model : fallback . id , account : loaded . token , until : now + 5 * 60_000 }
357+ } )
358+ yield * ctx . session . hook (
359+ "experimental.model.resolve" ,
360+ ( evt ) =>
361+ Effect . gen ( function * ( ) {
362+ // Titles use Copilot's utility model, so they never route.
363+ if ( evt . model . id !== CopilotModels . auto || evt . kind === "title" ) return
364+ const now = yield * Clock . currentTimeMillis
365+ const cached = routes . get ( evt . sessionID )
366+ const current =
367+ cached && cached . until > now && cached . account === discovered . current . token
368+ ? cached
369+ : yield * route ( evt . sessionID )
370+ if ( ! current ) return
371+ for ( const [ id , route ] of routes ) if ( route . until <= now ) routes . delete ( id )
372+ routes . set ( evt . sessionID , current )
373+ evt . target = Model . Ref . make ( { providerID : Provider . ID . githubCopilot , id : Model . ID . make ( current . model ) } )
374+ } ) ,
375+ { providerID : Provider . ID . githubCopilot } ,
376+ )
377+ // Compaction rewrites the prompt, so the request after it routes again, like Copilot's own clients. The compaction
378+ // request itself still carries the current pick's token.
379+ yield * ctx . session . hook (
380+ "compaction" ,
381+ ( evt ) =>
382+ Effect . sync ( ( ) => {
383+ const route = routes . get ( evt . sessionID )
384+ if ( route ) route . until = 0
297385 } ) ,
298386 { providerID : Provider . ID . githubCopilot } ,
299387 )
@@ -328,8 +416,7 @@ export const GithubCopilotPlugin = define({
328416 Effect . gen ( function * ( ) {
329417 // The Messages route sends the token as `x-api-key`, the OpenAI routes as a bearer token.
330418 const token =
331- evt . request . headers . get ( "x-api-key" ) ??
332- evt . request . headers . get ( "authorization" ) ?. replace ( / ^ B e a r e r \s + / i, "" )
419+ evt . request . headers . get ( "x-api-key" ) ?? evt . request . headers . get ( "authorization" ) ?. replace ( / ^ B e a r e r \s + / i, "" )
333420 if ( ! token ) return
334421 const text = yield * Effect . promise ( ( ) => evt . request . clone ( ) . text ( ) )
335422 const body = Option . getOrUndefined ( decodeBody ( text ) )
0 commit comments