opencode-plugin-litellm 1.8.1 → 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.
- package/README.md +32 -1
- package/package.json +1 -1
- package/src/plugin/auth.ts +312 -0
- package/src/plugin/index.ts +115 -14
- package/src/plugin/integration.ts +226 -16
- package/src/plugin/v2.ts +83 -13
- package/src/utils/litellm-api.ts +9 -5
- package/src/utils/opencode-auth.ts +70 -19
- package/src/utils/sso.ts +998 -0
|
@@ -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:
|
|
43
|
-
*
|
|
44
|
-
* provider
|
|
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: '
|
|
251
|
+
key: 'scope',
|
|
76
252
|
type: 'string',
|
|
77
|
-
title: '
|
|
253
|
+
title: 'Scopes',
|
|
78
254
|
description:
|
|
79
|
-
'
|
|
80
|
-
default:
|
|
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
|
|
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
|
|
99
|
-
* on purpose — a missing or unrelated integration must never
|
|
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
|
-
|
|
113
|
-
|
|
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
|
|
116
|
-
baseURL: readAnswer(
|
|
117
|
-
providerID: readAnswer(
|
|
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
|
package/src/plugin/v2.ts
CHANGED
|
@@ -14,9 +14,11 @@ import {
|
|
|
14
14
|
} from './index'
|
|
15
15
|
import {
|
|
16
16
|
LITELLM_INTEGRATION_ID,
|
|
17
|
+
connectionApiKey,
|
|
17
18
|
readConnectedConfig,
|
|
18
19
|
registerLiteLLMIntegration,
|
|
19
20
|
type ConnectedLiteLLM,
|
|
21
|
+
type SignInTarget,
|
|
20
22
|
} from './integration'
|
|
21
23
|
import {
|
|
22
24
|
buildCacheKey,
|
|
@@ -26,6 +28,7 @@ import {
|
|
|
26
28
|
} from '../utils/model-cache'
|
|
27
29
|
import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
|
|
28
30
|
import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
|
|
31
|
+
import { sameProxy } from '../utils/sso'
|
|
29
32
|
import { parseModelCapabilities } from '../utils/model-capabilities'
|
|
30
33
|
import type { ModelCapabilities } from '../utils/model-capabilities'
|
|
31
34
|
import {
|
|
@@ -317,6 +320,45 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
|
|
|
317
320
|
return settings
|
|
318
321
|
}
|
|
319
322
|
|
|
323
|
+
function providerHeaders(
|
|
324
|
+
pluginOptions: Record<string, unknown>,
|
|
325
|
+
settings: Record<string, unknown>,
|
|
326
|
+
provider: ProviderInfo | undefined,
|
|
327
|
+
): Record<string, string> {
|
|
328
|
+
return {
|
|
329
|
+
...readHeaders(pluginOptions.customHeaders),
|
|
330
|
+
...readCustomHeaders(settings),
|
|
331
|
+
...readHeaders(provider?.headers),
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The proxy URL and headers a sign-in uses: the configured provider's, else the plugin options'. */
|
|
336
|
+
async function signInTarget(
|
|
337
|
+
context: Context,
|
|
338
|
+
pluginOptions: Record<string, unknown>,
|
|
339
|
+
providerID: string,
|
|
340
|
+
): Promise<SignInTarget> {
|
|
341
|
+
const providers = await listMatchingProviders(context)
|
|
342
|
+
const provider = providers.find((candidate) => candidate.id === providerID)
|
|
343
|
+
const settings = { ...pluginOptions, ...asRecord(provider?.settings) }
|
|
344
|
+
return {
|
|
345
|
+
baseURL: readString(settings.baseURL),
|
|
346
|
+
headers: providerHeaders(pluginOptions, settings, provider),
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Whether a sign-in may go to `baseURL`. Its token only goes to the proxy that issued it, as on
|
|
352
|
+
* OpenCode 1; a sign-in that names no proxy (OIDC) goes where the provider points.
|
|
353
|
+
*/
|
|
354
|
+
function signInReaches(signedInTo: string | undefined, baseURL: string | undefined): boolean {
|
|
355
|
+
if (!signedInTo || !baseURL || sameProxy(signedInTo, baseURL)) return true
|
|
356
|
+
logInfo(
|
|
357
|
+
`[opencode-litellm] Not using the LiteLLM sign-in for ${signedInTo}: ${baseURL} must not receive its token.`,
|
|
358
|
+
)
|
|
359
|
+
return false
|
|
360
|
+
}
|
|
361
|
+
|
|
320
362
|
async function makeProviderSource(
|
|
321
363
|
context: Context,
|
|
322
364
|
provider: ProviderInfo | undefined,
|
|
@@ -324,25 +366,25 @@ async function makeProviderSource(
|
|
|
324
366
|
): Promise<ProviderSource | null> {
|
|
325
367
|
const providerSettings = asRecord(provider?.settings)
|
|
326
368
|
const settings = { ...pluginOptions, ...providerSettings }
|
|
327
|
-
const customHeaders =
|
|
328
|
-
|
|
329
|
-
...readCustomHeaders(settings),
|
|
330
|
-
...readHeaders(provider?.headers),
|
|
331
|
-
}
|
|
369
|
+
const customHeaders = providerHeaders(pluginOptions, settings, provider)
|
|
370
|
+
const configuredBaseURL = readString(settings.baseURL)
|
|
332
371
|
// Credential plus dialog form answers. A provider wired to its own
|
|
333
372
|
// integration keeps using exactly that one; otherwise the plugin's
|
|
334
373
|
// registered integration is consulted, so a gateway can be connected
|
|
335
374
|
// entirely from the web UI with no hand-written config.
|
|
336
|
-
|
|
375
|
+
let connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
|
|
337
376
|
context,
|
|
338
377
|
provider?.integrationID ?? LITELLM_INTEGRATION_ID,
|
|
339
378
|
)
|
|
379
|
+
// A base URL configured for another proxy turns the sign-in off.
|
|
380
|
+
if (connected?.credentialID && !signInReaches(connected.baseURL, configuredBaseURL)) {
|
|
381
|
+
connected = undefined
|
|
382
|
+
}
|
|
340
383
|
const id =
|
|
341
384
|
provider?.id ??
|
|
342
385
|
readString(pluginOptions.providerID) ??
|
|
343
386
|
connected?.providerID ??
|
|
344
387
|
CHAT_PROVIDER_ID
|
|
345
|
-
const configuredBaseURL = readString(settings.baseURL)
|
|
346
388
|
const connectedApiKey = connected?.apiKey
|
|
347
389
|
// Precedence rule: an explicit settings/plugin-options apiKey is the
|
|
348
390
|
// operator's deliberate config and stays first; then a credential the user
|
|
@@ -373,7 +415,13 @@ async function makeProviderSource(
|
|
|
373
415
|
? normalizeBaseURL(configuredBaseURL)
|
|
374
416
|
: connected?.baseURL
|
|
375
417
|
? normalizeBaseURL(connected.baseURL)
|
|
376
|
-
: await autoDetectLiteLLM(
|
|
418
|
+
: await autoDetectLiteLLM(
|
|
419
|
+
apiKey,
|
|
420
|
+
customHeaders,
|
|
421
|
+
// A sign-in only goes to a proxy named for it: probing local ports
|
|
422
|
+
// would hand its token to whatever answers there.
|
|
423
|
+
usesConnectionCredential && connected?.credentialID ? [] : undefined,
|
|
424
|
+
)
|
|
377
425
|
|
|
378
426
|
if (!detectedBaseURL) {
|
|
379
427
|
return null
|
|
@@ -382,10 +430,11 @@ async function makeProviderSource(
|
|
|
382
430
|
const baseURL = normalizeBaseURL(detectedBaseURL)
|
|
383
431
|
// The cache key is isolated by the effective credential (a fingerprint, never
|
|
384
432
|
// the raw key): a credential change starts a fresh discovery instead of
|
|
385
|
-
// serving another credential's cached model list.
|
|
433
|
+
// serving another credential's cached model list. A sign-in is keyed by its
|
|
434
|
+
// credential id, because its access token rotates on every refresh.
|
|
386
435
|
const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
|
|
387
436
|
formatModelNames,
|
|
388
|
-
}, apiKey)
|
|
437
|
+
}, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey)
|
|
389
438
|
const cacheEntry = readModelCacheEntry(cacheKey)
|
|
390
439
|
let entries = cacheEntry?.models ?? null
|
|
391
440
|
let responsesIds = cacheEntry?.responsesIds ?? []
|
|
@@ -477,10 +526,21 @@ async function refreshProviderSource(
|
|
|
477
526
|
return
|
|
478
527
|
}
|
|
479
528
|
|
|
480
|
-
const apiKey = source.apiKey
|
|
481
529
|
let refresh!: Promise<void>
|
|
482
530
|
refresh = (async () => {
|
|
483
531
|
try {
|
|
532
|
+
// A sign-in's access token rotates; resolving the connection refreshes an
|
|
533
|
+
// expiring one, so discovery does not run with a token that has expired.
|
|
534
|
+
if (source.usesConnectionCredential && source.integrationID) {
|
|
535
|
+
const connected = await readConnectedConfig(context, source.integrationID)
|
|
536
|
+
if (
|
|
537
|
+
connected?.apiKey &&
|
|
538
|
+
(!connected.credentialID || signInReaches(connected.baseURL, source.baseURL))
|
|
539
|
+
) {
|
|
540
|
+
source.apiKey = connected.apiKey
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
const apiKey = source.apiKey
|
|
484
544
|
const discovered = await withTimeout(
|
|
485
545
|
discoverModels(
|
|
486
546
|
source.baseURL,
|
|
@@ -552,7 +612,15 @@ async function refreshConnectionCredential(
|
|
|
552
612
|
const credential = connection
|
|
553
613
|
? await context.integration.connection.resolve(connection)
|
|
554
614
|
: undefined
|
|
555
|
-
|
|
615
|
+
let connectionKey = connectionApiKey(credential)
|
|
616
|
+
// A new sign-in may be for another proxy than the one this source points to.
|
|
617
|
+
if (
|
|
618
|
+
connectionKey !== undefined &&
|
|
619
|
+
credential?.type === 'oauth' &&
|
|
620
|
+
!signInReaches(readString(credential.metadata?.baseURL), source.baseURL)
|
|
621
|
+
) {
|
|
622
|
+
connectionKey = undefined
|
|
623
|
+
}
|
|
556
624
|
const settingsApiKey = readString(source.settings.apiKey)
|
|
557
625
|
let nextKey: string | undefined
|
|
558
626
|
let nextUsesConnection: boolean
|
|
@@ -731,7 +799,9 @@ const definition = Plugin.define({
|
|
|
731
799
|
// Surface LiteLLM in the connect-provider dialog so gateways can be
|
|
732
800
|
// connected from the web UI. Purely additive: a host without the
|
|
733
801
|
// integration API, or a failed registration, keeps every other auth path.
|
|
734
|
-
const integrationRegistration = await registerLiteLLMIntegration(context)
|
|
802
|
+
const integrationRegistration = await registerLiteLLMIntegration(context, (providerID) =>
|
|
803
|
+
signInTarget(context, pluginOptions, providerID),
|
|
804
|
+
)
|
|
735
805
|
|
|
736
806
|
// First pass. On OpenCode 2 the host has not registered user-configured
|
|
737
807
|
// providers yet, so this typically finds only built-ins; the event loop
|
package/src/utils/litellm-api.ts
CHANGED
|
@@ -157,15 +157,19 @@ export async function discoverLiteLLMModelInfo(
|
|
|
157
157
|
}
|
|
158
158
|
|
|
159
159
|
/**
|
|
160
|
-
* Use an explicit LITELLM_BASE_URL when set; otherwise try
|
|
161
|
-
*
|
|
160
|
+
* Use an explicit LITELLM_BASE_URL when set; otherwise try `ports` on localhost,
|
|
161
|
+
* by default the most common ones. The default `litellm --port` is 4000, with
|
|
162
|
+
* 8000 and 8080 also common.
|
|
162
163
|
*/
|
|
163
|
-
export async function autoDetectLiteLLM(
|
|
164
|
+
export async function autoDetectLiteLLM(
|
|
165
|
+
apiKey?: string,
|
|
166
|
+
customHeaders?: Record<string, string>,
|
|
167
|
+
ports: readonly number[] = [4000, 8000, 8080],
|
|
168
|
+
): Promise<string | null> {
|
|
164
169
|
const configuredBaseURL = process.env.LITELLM_BASE_URL?.trim()
|
|
165
170
|
if (configuredBaseURL) return normalizeBaseURL(configuredBaseURL)
|
|
166
171
|
|
|
167
|
-
const
|
|
168
|
-
for (const port of commonPorts) {
|
|
172
|
+
for (const port of ports) {
|
|
169
173
|
const baseURL = `http://localhost:${port}`
|
|
170
174
|
if (await checkLiteLLMHealth(baseURL, apiKey, customHeaders)) {
|
|
171
175
|
return baseURL
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises'
|
|
2
2
|
import { homedir } from 'node:os'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
|
+
import type { SsoToken } from './sso'
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Shape of an `api`-type entry in OpenCode's own credential store. OpenCode
|
|
7
|
-
* also stores `oauth`
|
|
8
|
-
*
|
|
8
|
+
* also stores `oauth` (a LiteLLM sign-in, see `getOpenCodeStoredSso`) and
|
|
9
|
+
* `wellknown` entries there.
|
|
9
10
|
*/
|
|
10
11
|
interface OpenCodeApiAuthEntry {
|
|
11
12
|
type: 'api'
|
|
@@ -33,22 +34,22 @@ function resolveAuthPath(): string {
|
|
|
33
34
|
// (model discovery itself is cached per baseURL for the same reason).
|
|
34
35
|
let cachedAuthFile: Promise<OpenCodeAuthFile | null> | null = null
|
|
35
36
|
|
|
36
|
-
async function
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
// File doesn't exist, isn't readable, or isn't valid JSON — treat
|
|
47
|
-
// as "no stored credentials" rather than failing plugin startup.
|
|
48
|
-
}
|
|
49
|
-
return null
|
|
50
|
-
})()
|
|
37
|
+
async function readOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
|
|
38
|
+
try {
|
|
39
|
+
const raw = await readFile(resolveAuthPath(), 'utf-8')
|
|
40
|
+
const parsed: unknown = JSON.parse(raw)
|
|
41
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
42
|
+
return parsed as OpenCodeAuthFile
|
|
43
|
+
}
|
|
44
|
+
} catch {
|
|
45
|
+
// File doesn't exist, isn't readable, or isn't valid JSON — treat
|
|
46
|
+
// as "no stored credentials" rather than failing plugin startup.
|
|
51
47
|
}
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function loadOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
|
|
52
|
+
cachedAuthFile ??= readOpenCodeAuthFile()
|
|
52
53
|
return cachedAuthFile
|
|
53
54
|
}
|
|
54
55
|
|
|
@@ -77,7 +78,57 @@ export async function getOpenCodeStoredApiKey(providerId: string): Promise<strin
|
|
|
77
78
|
return undefined
|
|
78
79
|
}
|
|
79
80
|
|
|
80
|
-
/**
|
|
81
|
-
|
|
81
|
+
/**
|
|
82
|
+
* Force the next read to hit disk again. OpenCode 1 rebuilds its plugin
|
|
83
|
+
* instance after a login, and the new instance must see the new credential.
|
|
84
|
+
*/
|
|
85
|
+
export function resetOpenCodeAuthCache(): void {
|
|
82
86
|
cachedAuthFile = null
|
|
83
87
|
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* An OpenCode 1 OAuth entry for a LiteLLM sign-in. OpenCode 1 keeps only these
|
|
91
|
+
* fields and drops the rest the next time it rewrites the file, so the
|
|
92
|
+
* sign-in's metadata travels as JSON in `accountId`.
|
|
93
|
+
*/
|
|
94
|
+
export function toOpenCodeOAuthEntry(token: SsoToken): {
|
|
95
|
+
type: 'oauth'
|
|
96
|
+
access: string
|
|
97
|
+
refresh: string
|
|
98
|
+
expires: number
|
|
99
|
+
accountId: string
|
|
100
|
+
} {
|
|
101
|
+
const { access, refresh, expires, metadata } = token
|
|
102
|
+
return { type: 'oauth', access, refresh, expires, accountId: JSON.stringify(metadata) }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The LiteLLM sign-in OpenCode 1 stored for `providerId`, read from disk on
|
|
107
|
+
* every call: the plugin refreshes it in place, and so may another OpenCode
|
|
108
|
+
* process sharing the file.
|
|
109
|
+
*/
|
|
110
|
+
export async function getOpenCodeStoredSso(providerId: string): Promise<SsoToken | undefined> {
|
|
111
|
+
const entry = (await readOpenCodeAuthFile())?.[providerId]
|
|
112
|
+
if (
|
|
113
|
+
entry?.type !== 'oauth' ||
|
|
114
|
+
typeof entry.access !== 'string' ||
|
|
115
|
+
typeof entry.refresh !== 'string' ||
|
|
116
|
+
typeof entry.expires !== 'number' ||
|
|
117
|
+
typeof entry.accountId !== 'string'
|
|
118
|
+
) {
|
|
119
|
+
return undefined
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const metadata: unknown = JSON.parse(entry.accountId)
|
|
123
|
+
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return undefined
|
|
124
|
+
return {
|
|
125
|
+
access: entry.access,
|
|
126
|
+
refresh: entry.refresh,
|
|
127
|
+
expires: entry.expires,
|
|
128
|
+
metadata: metadata as Record<string, unknown>,
|
|
129
|
+
}
|
|
130
|
+
} catch {
|
|
131
|
+
// Not one of this plugin's sign-ins.
|
|
132
|
+
return undefined
|
|
133
|
+
}
|
|
134
|
+
}
|