1- import type { Hooks , PluginInput } from "@opencode-ai/plugin"
1+ import { readFile } from "node:fs/promises"
2+ import { homedir } from "node:os"
3+ import { join } from "node:path"
4+ import { InstallationVersion } from "@opencode-ai/core/installation/version"
5+ import type { Hooks } from "@opencode-ai/plugin"
6+ import type { Provider } from "@opencode-ai/sdk/v2"
7+ import { Effect , Schema } from "effect"
8+ import { OAUTH_DUMMY_KEY } from "../auth"
9+
10+ const AZURE_COGNITIVE_SERVICES_SCOPE = "https://cognitiveservices.azure.com/.default"
11+ const AZURE_FOUNDRY_SCOPE = "https://ai.azure.com/.default"
12+ const AZURE_TOKEN_REFRESH_BUFFER = 60_000
13+
14+ const AzureCliToken = Schema . Struct ( {
15+ accessToken : Schema . NonEmptyString ,
16+ expires_on : Schema . optional ( Schema . Number ) ,
17+ expiresOn : Schema . optional ( Schema . NonEmptyString ) ,
18+ } )
19+ const decodeAzureCliToken = Schema . decodeUnknownPromise ( AzureCliToken )
20+ const decodeAzureProfile = Schema . decodeUnknownPromise (
21+ Schema . fromJsonString ( Schema . Struct ( { subscriptions : Schema . Array ( Schema . Unknown ) } ) ) ,
22+ )
23+
24+ const decodeAzureAccounts = Schema . decodeUnknownPromise (
25+ Schema . Array (
26+ Schema . Struct ( {
27+ name : Schema . NonEmptyString ,
28+ resourceGroup : Schema . NonEmptyString ,
29+ } ) ,
30+ ) ,
31+ )
32+
33+ const decodeAzureDeployments = Schema . decodeUnknownPromise (
34+ Schema . Array (
35+ Schema . Struct ( {
36+ name : Schema . NonEmptyString ,
37+ properties : Schema . Struct ( {
38+ model : Schema . Struct ( {
39+ name : Schema . NonEmptyString ,
40+ } ) ,
41+ provisioningState : Schema . NonEmptyString ,
42+ } ) ,
43+ } ) ,
44+ ) ,
45+ )
46+
47+ type AzureCommand = {
48+ quiet ( ) : AzureCommand
49+ json ( ) : Promise < unknown >
50+ }
51+
52+ type AzureShell = ( strings : TemplateStringsArray , ...values : string [ ] ) => AzureCommand
53+ type AzureAccount = { readonly name : string ; readonly resourceGroup : string }
54+
55+ export async function AzureAuthPlugin ( input : { $ : AzureShell } ) : Promise < Hooks > {
56+ const available = Boolean ( Bun . which ( "az" , { PATH : process . env . PATH } ) )
57+ // Avoid launching Azure CLI on unrelated commands just because the executable is installed.
58+ const signedIn = available
59+ ? await readFile ( join ( process . env . AZURE_CONFIG_DIR ?? join ( homedir ( ) , ".azure" ) , "azureProfile.json" ) , "utf8" )
60+ . then ( ( text ) => decodeAzureProfile ( text . replace ( / ^ \uFEFF / , "" ) ) )
61+ . then ( ( profile ) => profile . subscriptions . length > 0 )
62+ . catch ( ( ) => false )
63+ : false
64+ const accounts =
65+ ! process . env . AZURE_RESOURCE_NAME && ! process . env . AZURE_RESOURCE_GROUP && signedIn
66+ ? await input . $ `az cognitiveservices account list --output json --only-show-errors`
67+ . quiet ( )
68+ . json ( )
69+ . then ( decodeAzureAccounts )
70+ . catch ( ( ) => [ ] )
71+ : [ ]
72+ return createAzureAuthHooks ( input . $ , fetch , accounts , available )
73+ }
74+
75+ export function createAzureAuthHooks (
76+ shell : AzureShell ,
77+ request : ( input : RequestInfo | URL , init ?: RequestInit ) => Promise < Response > = fetch ,
78+ accounts : readonly AzureAccount [ ] = [ ] ,
79+ available = true ,
80+ ) : Hooks {
81+ const tokens = new Map < string , { token : string ; expires : number } > ( )
82+ async function token ( scope : string ) {
83+ const cached = tokens . get ( scope )
84+ if ( cached && cached . expires - Date . now ( ) > AZURE_TOKEN_REFRESH_BUFFER ) return cached . token
85+
86+ const result = await decodeAzureCliToken (
87+ await shell `az account get-access-token --scope ${ scope } --output json` . quiet ( ) . json ( ) ,
88+ )
89+ const expires = result . expires_on !== undefined ? result . expires_on * 1000 : Date . parse ( result . expiresOn ?? "" )
90+ if ( ! Number . isFinite ( expires ) ) throw new Error ( "Azure CLI returned an invalid token expiration" )
91+ const refreshed = { token : result . accessToken , expires }
92+ tokens . set ( scope , refreshed )
93+ return refreshed . token
94+ }
295
3- export async function AzureAuthPlugin ( _input : PluginInput ) : Promise < Hooks > {
496 const prompts = [ ]
597 if ( ! process . env . AZURE_RESOURCE_NAME ) {
698 prompts . push ( {
@@ -10,17 +102,150 @@ export async function AzureAuthPlugin(_input: PluginInput): Promise<Hooks> {
10102 placeholder : "e.g. my-models" ,
11103 } )
12104 }
105+ const oauthPrompts =
106+ accounts . length > 0 && ! process . env . AZURE_RESOURCE_NAME
107+ ? [
108+ {
109+ type : "select" as const ,
110+ key : "resourceSelection" ,
111+ message : "Select Azure resource" ,
112+ options : [
113+ ...accounts . map ( ( account ) => ( {
114+ label : account . name ,
115+ value : account . name ,
116+ hint : account . resourceGroup ,
117+ } ) ) ,
118+ { label : "Enter another resource name" , value : "__manual__" } ,
119+ ] ,
120+ } ,
121+ {
122+ type : "text" as const ,
123+ key : "resourceName" ,
124+ message : "Enter Azure Resource Name" ,
125+ placeholder : "e.g. my-models" ,
126+ when : { key : "resourceSelection" , op : "eq" as const , value : "__manual__" } ,
127+ } ,
128+ ]
129+ : prompts
13130
14- return {
131+ const hooks : Hooks = {
132+ provider : {
133+ id : "azure" ,
134+ async models ( provider , context ) {
135+ if ( context . auth ?. type !== "oauth" ) return provider . models
136+ const resource = context . auth . accountId
137+ if ( ! resource ) return { }
138+ return discoverAzureModels ( provider . models , resource , shell ) . catch ( ( error : unknown ) => {
139+ Effect . runSync (
140+ Effect . logWarning ( "Azure model discovery failed" , {
141+ resource,
142+ error : error instanceof Error ? error . message : String ( error ) ,
143+ } ) ,
144+ )
145+ return provider . models
146+ } )
147+ } ,
148+ } ,
15149 auth : {
16150 provider : "azure" ,
151+ async loader ( getAuth ) {
152+ if ( ( await getAuth ( ) ) . type !== "oauth" ) return { }
153+
154+ return {
155+ apiKey : OAUTH_DUMMY_KEY ,
156+ async fetch ( input : RequestInfo | URL , init ?: RequestInit ) {
157+ const headers = new Headers ( input instanceof Request ? input . headers : undefined )
158+ new Headers ( init ?. headers ) . forEach ( ( value , key ) => headers . set ( key , value ) )
159+ headers . delete ( "api-key" )
160+ headers . delete ( "x-api-key" )
161+ headers . set ( "authorization" , `Bearer ${ await token ( scopeForRequest ( input ) ) } ` )
162+ headers . set ( "User-Agent" , `opencode/${ InstallationVersion } ` )
163+ return request ( input , { ...init , headers } )
164+ } ,
165+ }
166+ } ,
17167 methods : [
18168 {
19169 type : "api" ,
20170 label : "API key" ,
21171 prompts,
22172 } ,
173+ {
174+ type : "oauth" ,
175+ label : "Microsoft Entra ID (Azure CLI)" ,
176+ prompts : oauthPrompts ,
177+ async authorize ( inputs ) {
178+ return {
179+ url : "" ,
180+ instructions : "Sign in with `az login` before continuing." ,
181+ method : "auto" ,
182+ callback : async ( ) => {
183+ const resourceName =
184+ inputs ?. resourceName ??
185+ ( inputs ?. resourceSelection === "__manual__" ? undefined : inputs ?. resourceSelection ) ??
186+ process . env . AZURE_RESOURCE_NAME
187+ if ( ! resourceName ) throw new Error ( "Azure Resource Name is required" )
188+
189+ await token ( AZURE_COGNITIVE_SERVICES_SCOPE )
190+ return {
191+ type : "success" ,
192+ access : OAUTH_DUMMY_KEY ,
193+ refresh : OAUTH_DUMMY_KEY ,
194+ expires : Date . now ( ) + 365 * 24 * 60 * 60 * 1000 ,
195+ accountId : resourceName ,
196+ }
197+ } ,
198+ }
199+ } ,
200+ } ,
23201 ] ,
24202 } ,
25203 }
204+ if ( ! available && hooks . auth ) hooks . auth . methods = hooks . auth . methods . filter ( ( method ) => method . type !== "oauth" )
205+ return hooks
206+ }
207+
208+ async function discoverAzureModels ( models : Provider [ "models" ] , resourceName : string , shell : AzureShell ) {
209+ const resourceGroup = process . env . AZURE_RESOURCE_GROUP
210+ const account = resourceGroup
211+ ? { name : resourceName , resourceGroup }
212+ : (
213+ await decodeAzureAccounts (
214+ await shell `az cognitiveservices account list --output json --only-show-errors` . quiet ( ) . json ( ) ,
215+ )
216+ ) . find ( ( account ) => account . name . toLowerCase ( ) === resourceName . toLowerCase ( ) )
217+ if ( ! account ) throw new Error ( `Azure resource "${ resourceName } " was not found in the active subscription` )
218+
219+ const deployments = await decodeAzureDeployments (
220+ await shell `az cognitiveservices account deployment list --name ${ account . name } --resource-group ${ account . resourceGroup } --output json --only-show-errors`
221+ . quiet ( )
222+ . json ( ) ,
223+ )
224+ const found = new Map < string , Provider [ "models" ] [ string ] > ( )
225+ deployments . forEach ( ( deployment ) => {
226+ if ( deployment . properties . provisioningState !== "Succeeded" ) return
227+ const modelID = Object . keys ( models ) . find (
228+ ( modelID ) => modelID . toLowerCase ( ) === deployment . properties . model . name . toLowerCase ( ) ,
229+ )
230+ if ( ! modelID ) return
231+ const id = found . has ( modelID ) ? deployment . name : modelID
232+ found . set ( id , {
233+ ...models [ modelID ] ,
234+ id,
235+ name : id === modelID ? models [ modelID ] . name : `${ models [ modelID ] . name } (${ deployment . name } )` ,
236+ api : {
237+ ...models [ modelID ] . api ,
238+ id : deployment . name ,
239+ } ,
240+ } )
241+ } )
242+ return Object . fromEntries ( found )
243+ }
244+
245+ function scopeForRequest ( input : RequestInfo | URL ) {
246+ const url = new URL ( input instanceof Request ? input . url : input )
247+ if ( url . hostname . endsWith ( ".services.ai.azure.com" ) && ! url . pathname . startsWith ( "/models" ) ) {
248+ return AZURE_FOUNDRY_SCOPE
249+ }
250+ return AZURE_COGNITIVE_SERVICES_SCOPE
26251}
0 commit comments