opencode-plugin-litellm 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,15 @@ import {
13
13
  } from '../utils/format-model-name'
14
14
  import { requiresResponsesAPI } from '../utils/transport'
15
15
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
16
- import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
16
+ import { getOpenCodeStoredApiKey, resetOpenCodeAuthCache } from '../utils/opencode-auth'
17
+ import { sameProxy, ssoIdentity } from '../utils/sso'
18
+ import {
19
+ createSsoSession,
20
+ liteLLMAuthHook,
21
+ ssoFetch,
22
+ type SignInTarget,
23
+ type SsoSession,
24
+ } from './auth'
17
25
  import type { ModelHints } from '../utils/model-cache'
18
26
  import {
19
27
  buildCacheKey,
@@ -34,6 +42,8 @@ const CHAT_PROVIDER_ID = 'litellm'
34
42
  // with it so it never treats its own sibling as a chat provider.
35
43
  const RESPONSES_PROVIDER_SUFFIX = '-responses'
36
44
  const RESPONSES_NPM = '@ai-sdk/openai'
45
+ // `@ai-sdk/openai` throws without an API key, even when the sign-in's `fetch` sends the real token.
46
+ const SIGN_IN_PLACEHOLDER = 'litellm-sign-in'
37
47
  // Covers the 3 s health check plus the parallel models/model-info fetch
38
48
  // phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
39
49
  // proxies aren't cut off by the overall cap either (issue #20).
@@ -98,6 +108,8 @@ const injectedModelIds = new Map<string, Set<string>>()
98
108
  interface RefreshContext {
99
109
  baseURL: string
100
110
  apiKey?: string
111
+ /** A LiteLLM sign-in, whose rotating access token replaces `apiKey`. */
112
+ session?: SsoSession
101
113
  customHeaders?: Record<string, string>
102
114
  filters: ModelFilters
103
115
  capabilities: ModelCapabilities
@@ -106,6 +118,23 @@ interface RefreshContext {
106
118
  }
107
119
  const refreshContexts = new Map<string, RefreshContext>()
108
120
 
121
+ /**
122
+ * OpenCode 1 caches the global config for the whole process, so after a
123
+ * login rebuilds the instance a provider's options come back still holding
124
+ * what this plugin wrote. Only the values the user configured count as
125
+ * configuration: this snapshot is taken before the plugin first writes.
126
+ */
127
+ const configuredOptions = new WeakMap<object, Record<string, unknown>>()
128
+
129
+ function userOptions(options: Record<string, unknown>): Record<string, unknown> {
130
+ let configured = configuredOptions.get(options)
131
+ if (!configured) {
132
+ configured = { ...options }
133
+ configuredOptions.set(options, configured)
134
+ }
135
+ return configured
136
+ }
137
+
109
138
  /** Cache keys with an in-flight background refresh, to avoid pile-ups. */
110
139
  const refreshInFlight = new Set<string>()
111
140
 
@@ -535,6 +564,7 @@ function ensureResponsesProvider(
535
564
  baseURL: string,
536
565
  apiKey: string | undefined,
537
566
  customHeaders: Record<string, string> | undefined,
567
+ runtimeFetch: typeof fetch | undefined,
538
568
  ): Record<string, unknown> {
539
569
  const id = `${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`
540
570
  if (!config.provider[id] || typeof config.provider[id] !== 'object') {
@@ -553,8 +583,15 @@ function ensureResponsesProvider(
553
583
  provider.options = {}
554
584
  }
555
585
  const options = provider.options as Record<string, unknown>
556
- if (!options.baseURL) options.baseURL = `${baseURL}/v1`
557
- if (!options.apiKey && apiKey) options.apiKey = apiKey
586
+ const configured = userOptions(options)
587
+ if (!configured.baseURL) options.baseURL = `${baseURL}/v1`
588
+ if (!configured.apiKey) {
589
+ const key = apiKey ?? (runtimeFetch ? SIGN_IN_PLACEHOLDER : undefined)
590
+ if (key) options.apiKey = key
591
+ else delete options.apiKey
592
+ }
593
+ if (runtimeFetch) options.fetch = runtimeFetch
594
+ else if (configured.fetch === undefined) delete options.fetch
558
595
  // OpenCode 1 reads provider headers from `options.headers` and hands them to
559
596
  // the runtime package (`@ai-sdk/openai` here); it has no `customHeaders` key.
560
597
  // Mirror the chat provider's native headers and promote the plugin's
@@ -605,6 +642,7 @@ function injectDiscoveredModels(
605
642
  baseURL: string,
606
643
  apiKey: string | undefined,
607
644
  customHeaders: Record<string, string> | undefined,
645
+ runtimeFetch?: typeof fetch,
608
646
  ): string[] {
609
647
  const responsesSet = new Set(responsesIds)
610
648
  const existingSibling = config.provider[`${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`]
@@ -640,6 +678,7 @@ function injectDiscoveredModels(
640
678
  baseURL,
641
679
  apiKey,
642
680
  customHeaders,
681
+ runtimeFetch,
643
682
  )
644
683
  added.push(...mergeModels(siblingModels, responsesEntries))
645
684
  }
@@ -664,10 +703,11 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
664
703
  }
665
704
  refreshInFlight.add(cacheKey)
666
705
  try {
706
+ const apiKey = ctx.session ? await ctx.session.access(ctx.customHeaders) : ctx.apiKey
667
707
  const discovered = await withTimeout(
668
708
  discoverModels(
669
709
  ctx.baseURL,
670
- ctx.apiKey,
710
+ apiKey,
671
711
  ctx.customHeaders,
672
712
  ctx.providerId,
673
713
  ctx.filters,
@@ -716,7 +756,13 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
716
756
  */
717
757
  export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
718
758
  initLogging(input.client)
759
+ // OpenCode rebuilds the plugin after a login; this instance must read the new credential.
760
+ resetOpenCodeAuthCache()
761
+ const warn = (message: string) => log('warn', message)
762
+ const session = createSsoSession(input.client, CHAT_PROVIDER_ID, warn)
763
+ let signInTarget: SignInTarget = { baseURL: undefined, previousURL: undefined, headers: {} }
719
764
  return {
765
+ auth: liteLLMAuthHook(CHAT_PROVIDER_ID, () => signInTarget),
720
766
  config: async (config: any) => {
721
767
  // Ensure the provider entry exists
722
768
  if (!config.provider) config.provider = {}
@@ -756,7 +802,9 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
756
802
 
757
803
  // Process each matched provider
758
804
  for (const { id: providerId, provider } of liteLLMProviders) {
759
- const options = (provider.options ?? {}) as Record<string, unknown>
805
+ // Snapshot the object this plugin writes into, so a later run recognizes those writes.
806
+ if (!provider.options || typeof provider.options !== 'object') provider.options = {}
807
+ const options = userOptions(provider.options as Record<string, unknown>)
760
808
  const configuredBase =
761
809
  typeof options.baseURL === 'string' ? options.baseURL : undefined
762
810
  const configuredKey =
@@ -779,11 +827,46 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
779
827
  override of a user's saved key.
780
828
  */
781
829
  const storedKey = await getOpenCodeStoredApiKey(providerId)
782
- const apiKey = configuredKey ?? storedKey ?? envKey
783
830
  // Native `options.headers` and the legacy `customHeaders` both reach
784
831
  // discovery and the runtime, so a gateway that only sets one still
785
832
  // authenticates the plugin's own fetches.
786
833
  const customHeaders = readProviderHeaders(options)
834
+ // A LiteLLM sign-in for the provider the auth hook serves is a stored
835
+ // credential too: it beats the environment, and a configured key beats it.
836
+ let sso =
837
+ providerId === CHAT_PROVIDER_ID && !configuredKey ? await session.stored() : undefined
838
+ const signedInTo = sso?.metadata.baseURL
839
+ if (configuredBase && typeof signedInTo === 'string' && !sameProxy(configuredBase, signedInTo)) {
840
+ // The provider points elsewhere, and that host must not receive this sign-in's token.
841
+ log(
842
+ 'warn',
843
+ `[opencode-litellm] Not using the LiteLLM sign-in for ${signedInTo}: provider "${providerId}" is configured for ${configuredBase}.`,
844
+ )
845
+ sso = undefined
846
+ }
847
+ if (providerId === CHAT_PROVIDER_ID) {
848
+ const previousURL = sso?.metadata.baseURL
849
+ signInTarget = {
850
+ baseURL: configuredBase,
851
+ previousURL: typeof previousURL === 'string' ? previousURL : undefined,
852
+ headers: customHeaders ?? {},
853
+ }
854
+ }
855
+ const ssoKey = sso
856
+ ? await session.access(customHeaders).catch((error: unknown) => {
857
+ const message = error instanceof Error ? error.message : String(error)
858
+ log('warn', `[opencode-litellm] LiteLLM sign-in unusable: ${message}`)
859
+ return undefined
860
+ })
861
+ : undefined
862
+ // An unusable sign-in still outranks the environment: discovery goes without
863
+ // a key (an empty one also stops the discovery helpers' own environment
864
+ // fallback), and requests ask to connect again.
865
+ const apiKey = configuredKey ?? storedKey ?? (sso ? (ssoKey ?? '') : envKey)
866
+ // A sign-in's token rotates, so it goes out per request instead of
867
+ // sitting in `apiKey`.
868
+ const runtimeKey = sso ? undefined : apiKey
869
+ const runtimeFetch = sso ? ssoFetch(session, customHeaders) : undefined
787
870
  const filters = readModelFilters(options)
788
871
  const capabilities = parseModelCapabilities(options.modelCapabilities)
789
872
  const formatModelNames = readFormatModelNames(options)
@@ -792,8 +875,13 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
792
875
  let baseURL: string | null = null
793
876
  if (configuredBase) {
794
877
  baseURL = normalizeBaseURL(configuredBase)
878
+ } else if (typeof sso?.metadata.baseURL === 'string') {
879
+ // The proxy the sign-in was issued by.
880
+ baseURL = normalizeBaseURL(sso.metadata.baseURL)
795
881
  } else {
796
- baseURL = await autoDetectLiteLLM(apiKey, customHeaders)
882
+ // A sign-in only goes to a proxy named for it: probing local ports
883
+ // would hand its token to whatever answers there.
884
+ baseURL = await autoDetectLiteLLM(apiKey, customHeaders, sso ? [] : undefined)
797
885
  }
798
886
 
799
887
  if (!baseURL) {
@@ -818,7 +906,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
818
906
  actualProvider.options = {}
819
907
  }
820
908
  const actualOptions = actualProvider.options as Record<string, unknown>
821
- if (!actualOptions.baseURL) {
909
+ if (!configuredBase) {
822
910
  actualOptions.baseURL = `${baseURL}/v1`
823
911
  }
824
912
  /*
@@ -832,9 +920,13 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
832
920
  go out with no Authorization header even though discovery
833
921
  succeeded using the same resolved key.
834
922
  */
835
- if (!actualOptions.apiKey && apiKey) {
836
- actualOptions.apiKey = apiKey
923
+ // Recomputed every run, so an earlier credential never lingers (see userOptions).
924
+ if (!configuredKey) {
925
+ if (runtimeKey) actualOptions.apiKey = runtimeKey
926
+ else delete actualOptions.apiKey
837
927
  }
928
+ if (runtimeFetch) actualOptions.fetch = runtimeFetch
929
+ else if (options.fetch === undefined) delete actualOptions.fetch
838
930
 
839
931
  if (!actualProvider.models) {
840
932
  actualProvider.models = {}
@@ -847,16 +939,23 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
847
939
  // fresh discovery instead of serving the old adjusted view.
848
940
  // The cache key is isolated by the effective credential (a fingerprint,
849
941
  // never the raw key): a credential change starts a fresh discovery
850
- // instead of serving another credential's cached model list.
942
+ // instead of serving another credential's cached model list. A sign-in
943
+ // keeps one key while its token rotates, and even once it expired, so
944
+ // the provider keeps its models and can be reconnected from `/connect`.
851
945
  const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities, {
852
946
  formatModelNames,
853
- }, apiKey)
947
+ }, sso ? ssoIdentity(sso) : apiKey)
854
948
 
855
949
  // Remember how to reach this proxy so the `event` hook can
856
950
  // revalidate its cache in the background on new sessions.
951
+ // Only this run's context refreshes in the background: an earlier one may hold another proxy.
952
+ for (const [key, context] of refreshContexts) {
953
+ if (context.providerId === providerId && key !== cacheKey) refreshContexts.delete(key)
954
+ }
857
955
  refreshContexts.set(cacheKey, {
858
956
  baseURL,
859
957
  apiKey,
958
+ session: sso ? session : undefined,
860
959
  customHeaders,
861
960
  filters,
862
961
  capabilities,
@@ -904,8 +1003,9 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
904
1003
  cached.models,
905
1004
  cached.responsesIds,
906
1005
  baseURL,
907
- apiKey,
1006
+ runtimeKey,
908
1007
  customHeaders,
1008
+ runtimeFetch,
909
1009
  )
910
1010
  injectedModelIds.set(cacheKey, new Set(added))
911
1011
  log(
@@ -939,8 +1039,9 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
939
1039
  discovered.models,
940
1040
  discovered.responsesIds,
941
1041
  baseURL,
942
- apiKey,
1042
+ runtimeKey,
943
1043
  customHeaders,
1044
+ runtimeFetch,
944
1045
  )
945
1046
  injectedModelIds.set(cacheKey, new Set(added))
946
1047
  writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
@@ -1,4 +1,15 @@
1
+ import { Integration, type Credential } from '@opencode/plugin'
2
+ import type { IntegrationOAuthAuthorization } from '@opencode/plugin/promise/integration'
1
3
  import type { Context } from '@opencode/plugin/promise/plugin'
4
+ import {
5
+ authorizeLiteLLM,
6
+ authorizeOidc,
7
+ parseOidcConfig,
8
+ refreshSsoToken,
9
+ signInRoot,
10
+ type SsoAuthorization,
11
+ type SsoToken,
12
+ } from '../utils/sso'
2
13
 
3
14
  // OpenCode 2 exposes no log API through the plugin context (see
4
15
  // initV2Logging); the host captures console output into its log files, so a
@@ -19,6 +30,11 @@ function logInfo(message: string): void {
19
30
  */
20
31
  export const LITELLM_INTEGRATION_ID = 'litellm'
21
32
 
33
+ const SSO_METHOD_ID = 'sso'
34
+ const OIDC_METHOD_ID = 'oidc'
35
+ // Only OAuth credentials from these methods carry a LiteLLM bearer token.
36
+ const OAUTH_METHOD_IDS: ReadonlySet<string> = new Set([SSO_METHOD_ID, OIDC_METHOD_ID])
37
+
22
38
  /** A credential saved through the connect dialog, with its form answers. */
23
39
  export interface ConnectedLiteLLM {
24
40
  /** Key resolved from the active connection's credential. */
@@ -27,8 +43,18 @@ export interface ConnectedLiteLLM {
27
43
  baseURL: string | undefined
28
44
  /** Provider id typed into the dialog's form, when present. */
29
45
  providerID: string | undefined
46
+ /** Id of an OAuth credential, which stays put while its access token rotates. */
47
+ credentialID?: string
48
+ }
49
+
50
+ /** The configured proxy URL and gateway headers a sign-in for a provider id uses. */
51
+ export interface SignInTarget {
52
+ baseURL: string | undefined
53
+ headers: Record<string, string>
30
54
  }
31
55
 
56
+ type SignInTargetResolver = (providerID: string) => Promise<SignInTarget>
57
+
32
58
  function readAnswer(
33
59
  configuration: Record<string, unknown> | undefined,
34
60
  key: string,
@@ -37,11 +63,89 @@ function readAnswer(
37
63
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
38
64
  }
39
65
 
66
+ /** The bearer token a connection provides, or undefined when it is not a LiteLLM credential. */
67
+ export function connectionApiKey(credential: Credential.Value | undefined): string | undefined {
68
+ if (credential?.type === 'key') return credential.key
69
+ if (credential?.type === 'oauth' && OAUTH_METHOD_IDS.has(credential.methodID))
70
+ return credential.access
71
+ return undefined
72
+ }
73
+
74
+ // Fields are built per form: the host may decorate the fields of each method it registers.
75
+ const providerIDField = () =>
76
+ ({
77
+ key: 'providerID',
78
+ type: 'string',
79
+ title: 'Provider ID',
80
+ description:
81
+ 'Provider the discovered models appear under. Pick a different id when your config already defines a "litellm" provider, so the connected gateway gets its own entry. Reconnecting with a different id moves the gateway there.',
82
+ default: LITELLM_INTEGRATION_ID,
83
+ }) as const
84
+
85
+ const signInBaseURLField = () =>
86
+ ({
87
+ key: 'baseURL',
88
+ type: 'string',
89
+ format: 'uri',
90
+ title: 'Base URL',
91
+ description:
92
+ "The LiteLLM proxy to sign in to. Leave empty to use the configured provider's URL, the current sign-in's proxy, or LITELLM_BASE_URL.",
93
+ placeholder: 'https://llm.example.com',
94
+ }) as const
95
+
96
+ /** Proxy URL, provider id, and gateway headers for a sign-in. */
97
+ async function signInTarget(
98
+ context: Context,
99
+ answer: Record<string, unknown>,
100
+ resolveTarget: SignInTargetResolver,
101
+ ): Promise<{ providerID: string; baseURL: string | undefined; headers: Record<string, string> }> {
102
+ const providerID = readAnswer(answer, 'providerID') ?? LITELLM_INTEGRATION_ID
103
+ const target = await resolveTarget(providerID)
104
+ const typed = readAnswer(answer, 'baseURL')
105
+ // Nothing typed or configured: the current sign-in's proxy, as on OpenCode 1, even before a
106
+ // provider is published for it. Unlike configuration, it is only a default.
107
+ const current =
108
+ typed || target.baseURL ? undefined : await readConnectedConfig(context, LITELLM_INTEGRATION_ID)
109
+ const previous = current?.credentialID ? current.baseURL : undefined
110
+ const baseURL = signInRoot(typed ?? previous, target.baseURL, providerID)
111
+ return { providerID, baseURL, headers: target.headers }
112
+ }
113
+
114
+ /** Wraps a sign-in for the host, storing the session as an OAuth credential of `methodID`. */
115
+ function toAuthorization(
116
+ authorization: SsoAuthorization,
117
+ methodID: string,
118
+ metadata: Record<string, unknown>,
119
+ ): IntegrationOAuthAuthorization {
120
+ const toCredential = (token: SsoToken): Credential.OAuth => ({
121
+ type: 'oauth',
122
+ methodID: Integration.MethodID.make(methodID),
123
+ access: token.access,
124
+ refresh: token.refresh,
125
+ expires: token.expires,
126
+ metadata: { ...token.metadata, ...metadata },
127
+ })
128
+ const { url, instructions, expiresAt } = authorization
129
+ if (authorization.mode === 'code') {
130
+ return {
131
+ url,
132
+ instructions,
133
+ expiresAt,
134
+ mode: 'code',
135
+ callback: (code) => authorization.callback(code).then(toCredential),
136
+ }
137
+ }
138
+ const callback = authorization.callback.then(toCredential)
139
+ // The host awaits it once the attempt is recorded; an earlier rejection must not go unhandled.
140
+ callback.catch(() => {})
141
+ return { url, instructions, expiresAt, mode: 'auto', callback }
142
+ }
143
+
40
144
  /**
41
145
  * Registers the LiteLLM integration so gateways can be connected from the
42
- * web UI instead of hand-edited config: the dialog collects the API key as a
43
- * credential plus a small form for the proxy base URL and an optional
44
- * provider id.
146
+ * web UI instead of hand-edited config: an API key with a small form for the
147
+ * proxy base URL and an optional provider id, or a browser sign-in through
148
+ * LiteLLM SSO or directly with an OpenID Connect identity provider.
45
149
  *
46
150
  * Returns the transform registration, or undefined when the host has no
47
151
  * integration API (OpenCode 1.18.x's embedded v2 host) or registration
@@ -49,8 +153,18 @@ function readAnswer(
49
153
  */
50
154
  export async function registerLiteLLMIntegration(
51
155
  context: Context,
156
+ resolveTarget: SignInTargetResolver,
52
157
  ): Promise<{ dispose(): Promise<void> } | undefined> {
53
158
  if (!context.integration?.transform) return undefined
159
+ // Shared by both sign-in methods: the stored flow decides how a session renews.
160
+ const refresh = async (credential: Credential.OAuth): Promise<Credential.OAuth> => {
161
+ const metadata = credential.metadata ?? {}
162
+ const { headers } = await resolveTarget(
163
+ readAnswer(metadata, 'providerID') ?? LITELLM_INTEGRATION_ID,
164
+ )
165
+ const token = await refreshSsoToken({ ...credential, metadata }, headers)
166
+ return { ...credential, access: token.access, refresh: token.refresh, expires: token.expires }
167
+ }
54
168
  try {
55
169
  return await context.integration.transform((editor) => {
56
170
  editor.update(LITELLM_INTEGRATION_ID, (integration) => {
@@ -71,16 +185,102 @@ export async function registerLiteLLMIntegration(
71
185
  'Where the LiteLLM proxy runs, including the /v1 suffix. Leave empty to use LITELLM_BASE_URL or auto-detect a local proxy.',
72
186
  placeholder: 'https://llm.example.com/v1',
73
187
  },
188
+ providerIDField(),
189
+ ],
190
+ },
191
+ })
192
+ editor.method.update({
193
+ integrationID: LITELLM_INTEGRATION_ID,
194
+ method: {
195
+ id: SSO_METHOD_ID,
196
+ type: 'oauth',
197
+ label: 'LiteLLM SSO',
198
+ form: [
199
+ signInBaseURLField(),
200
+ providerIDField(),
201
+ {
202
+ key: 'team',
203
+ type: 'string',
204
+ title: 'Team',
205
+ description:
206
+ 'LiteLLM team ID or alias, for accounts in several teams. Leave empty unless sign-in asks for one.',
207
+ },
208
+ ],
209
+ },
210
+ authorize: async (answer) => {
211
+ const { providerID, baseURL, headers } = await signInTarget(
212
+ context,
213
+ answer,
214
+ resolveTarget,
215
+ )
216
+ if (!baseURL)
217
+ throw new Error('Enter the LiteLLM proxy URL as Base URL, or set LITELLM_BASE_URL')
218
+ const authorization = await authorizeLiteLLM(baseURL, headers, readAnswer(answer, 'team'))
219
+ return toAuthorization(authorization, SSO_METHOD_ID, { providerID })
220
+ },
221
+ refresh,
222
+ })
223
+ editor.method.update({
224
+ integrationID: LITELLM_INTEGRATION_ID,
225
+ method: {
226
+ id: OIDC_METHOD_ID,
227
+ type: 'oauth',
228
+ label: 'Identity provider (OIDC)',
229
+ form: [
230
+ signInBaseURLField(),
231
+ providerIDField(),
232
+ {
233
+ key: 'issuer',
234
+ type: 'string',
235
+ format: 'uri',
236
+ title: 'Issuer',
237
+ description:
238
+ "Your identity provider's issuer URL; the proxy's JWT auth must trust it.",
239
+ placeholder: 'https://idp.example.com',
240
+ required: true,
241
+ },
242
+ {
243
+ key: 'clientId',
244
+ type: 'string',
245
+ title: 'Client ID',
246
+ description:
247
+ 'A public client (no secret) for authorization code + PKCE with the redirect http://127.0.0.1:<port>/callback. The proxy must accept it as an audience.',
248
+ required: true,
249
+ },
74
250
  {
75
- key: 'providerID',
251
+ key: 'scope',
76
252
  type: 'string',
77
- title: 'Provider ID',
253
+ title: 'Scopes',
78
254
  description:
79
- 'Provider the discovered models appear under. Pick a different id when your config already defines a "litellm" provider, so the connected gateway gets its own entry. Reconnecting with a different id moves the gateway there.',
80
- default: LITELLM_INTEGRATION_ID,
255
+ 'Space-separated, including openid. Some identity providers only issue refresh tokens with offline_access.',
256
+ default: 'openid',
257
+ },
258
+ {
259
+ key: 'redirectPorts',
260
+ type: 'string',
261
+ title: 'Redirect ports',
262
+ description:
263
+ 'Loopback ports to try in order, for identity providers that only accept exact registered redirect URIs. Leave empty for any free port.',
264
+ placeholder: '8400, 8401',
81
265
  },
82
266
  ],
83
267
  },
268
+ authorize: async (answer) => {
269
+ // Nothing is sent to the proxy, so its URL is only recorded for discovery.
270
+ const { providerID, baseURL } = await signInTarget(context, answer, resolveTarget)
271
+ const config = parseOidcConfig({
272
+ issuer: readAnswer(answer, 'issuer'),
273
+ clientId: readAnswer(answer, 'clientId'),
274
+ scope: readAnswer(answer, 'scope'),
275
+ redirectPorts: readAnswer(answer, 'redirectPorts'),
276
+ })
277
+ const authorization = await authorizeOidc(config)
278
+ return toAuthorization(authorization, OIDC_METHOD_ID, {
279
+ providerID,
280
+ ...(baseURL ? { baseURL } : {}),
281
+ })
282
+ },
283
+ refresh,
84
284
  })
85
285
  })
86
286
  } catch (error) {
@@ -92,12 +292,13 @@ export async function registerLiteLLMIntegration(
92
292
 
93
293
  /**
94
294
  * Resolves the active credential for an integration into the values the
95
- * plugin needs: the API key plus the dialog's form answers.
295
+ * plugin needs: the API key (or a sign-in's access token) plus the dialog's
296
+ * form answers.
96
297
  *
97
298
  * Returns undefined when the integration has no connection, the credential
98
- * is not a key, or the host lacks the connection API. Errors are swallowed
99
- * on purpose — a missing or unrelated integration must never prevent other
100
- * auth sources from working.
299
+ * is not a LiteLLM one, or the host lacks the connection API. Errors are
300
+ * swallowed on purpose — a missing or unrelated integration must never
301
+ * prevent other auth sources from working.
101
302
  */
102
303
  export async function readConnectedConfig(
103
304
  context: Context,
@@ -108,13 +309,22 @@ export async function readConnectedConfig(
108
309
  try {
109
310
  const active = await connection.active(integrationID)
110
311
  if (!active) return undefined
312
+ // Resolving refreshes a sign-in whose access token is about to expire.
111
313
  const credential = await connection.resolve(active)
112
- if (!credential || credential.type !== 'key') return undefined
113
- const configuration = credential.configuration as Record<string, unknown> | undefined
314
+ const apiKey = connectionApiKey(credential)
315
+ if (!credential || apiKey === undefined) return undefined
316
+ // OpenCode 2.1 moved the form answers from `configuration` to `metadata`,
317
+ // where sign-ins store theirs too; metadata wins where both hold one.
318
+ const answers: Record<string, unknown> = {
319
+ ...(credential.type === 'key' ? credential.configuration : undefined),
320
+ ...credential.metadata,
321
+ }
114
322
  return {
115
- apiKey: credential.key,
116
- baseURL: readAnswer(configuration, 'baseURL'),
117
- providerID: readAnswer(configuration, 'providerID'),
323
+ apiKey,
324
+ baseURL: readAnswer(answers, 'baseURL'),
325
+ providerID: readAnswer(answers, 'providerID'),
326
+ credentialID:
327
+ credential.type === 'oauth' && active.type === 'credential' ? active.id : undefined,
118
328
  }
119
329
  } catch {
120
330
  return undefined