opencode-plugin-litellm 1.8.1 → 1.10.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.
@@ -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