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 CHANGED
@@ -79,6 +79,7 @@ also shows how to configure a provider directly in `opencode.json`.
79
79
  | 🧩 **Reasoning-effort variants** | When LiteLLM reports per-model effort support (`supports_low_reasoning_effort`, …), the plugin surfaces each level as a picker variant automatically. |
80
80
  | 🧭 **Responses-API routing** | Models LiteLLM reports with `mode: "responses"` are invoked through `/v1/responses` instead of `/v1/chat/completions`, with no extra configuration. OpenCode 2 overrides the runtime package per model; OpenCode 1 gets a `<provider>-responses` sibling. |
81
81
  | 🔐 **Auth-aware** | Honours `providers.litellm.settings.apiKey`, OpenCode `/connect` credentials, the box auth store, and `LITELLM_API_KEY` / `LITELLM_MASTER_KEY` on both the V1 server path and the OpenCode 2 plugin host; on OpenCode 2 a **LiteLLM** entry in the connect-provider dialog (key plus optional base URL) connects a gateway entirely from the web UI. A saved credential beats the environment key. |
82
+ | 🪪 **Single sign-on** | Signs in through LiteLLM SSO (CLI-auth PKCE, CLI SSO, or a token pasted from the LiteLLM UI) or directly with an OpenID Connect identity provider, from the connect dialog of OpenCode 1 and 2, their Desktop apps, or `opencode auth login`. The token is refreshed and sent with every request. |
82
83
  | 🌐 **Gateway-friendly** | Supports provider `headers` (and the legacy `customHeaders` option) for proxies behind Cloudflare Access or other API gateways. |
83
84
  | 🧩 **Splittable catalog** | `includeModels` / `excludeModels` (glob patterns) let one LiteLLM proxy be divided into several OpenCode providers — e.g. by naming prefix — without hand-maintaining a model list. |
84
85
  | 🎚️ **Capability overrides** | `modelCapabilities` forces or retracts per-model capability flags (`supports_vision`, `supports_function_calling`, …) when `/v1/model/info` is unavailable or disagrees with your deployment. |
@@ -327,6 +328,7 @@ If your LiteLLM proxy requires a master key, expose it via any of these approach
327
328
  | Method | Example |
328
329
  |---|---|
329
330
  | Web UI / `/connect` | Run `/connect` (or use the Desktop providers view), pick **LiteLLM**, paste the key, and optionally fill in the base URL and provider id |
331
+ | Single sign-on | `/connect` (or the Desktop providers view) → **LiteLLM** → **LiteLLM SSO** or **Identity provider (OIDC)**; see [Single sign-on](#single-sign-on) |
330
332
  | Env var (base URL) | `LITELLM_BASE_URL=https://litellm.internal.example.com/v1` |
331
333
  | Env var | `export LITELLM_API_KEY=sk-...` |
332
334
  | Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
@@ -344,7 +346,36 @@ With no configuration at all, `/connect` → **LiteLLM** is enough:
344
346
 
345
347
  Precedence when several sources are configured: explicit provider/plugin settings always win. For the key, a credential saved in the box (the active connection or the `/connect` entry) beats the environment (`LITELLM_API_KEY`/`LITELLM_MASTER_KEY`), which is only a fallback; for the base URL, the dialog answer beats `LITELLM_BASE_URL` and local port auto-detection. A provider defined in `opencode.json` (without its own key) picks the saved credential up on the next start, while providers created from the dialog update immediately — reconnecting re-points them in place, including a changed base URL or provider id.
346
348
 
347
- The discovered model list is cached per credential: a short hash of the effective key (never the raw key) is part of every cache entry's key, so when the selected credential changes the next discovery starts fresh instead of serving another credential's model list. A `credential.switched` event also recomputes the effective key and reloads the provider registry when it changed — including the first credential saved after setup.
349
+ #### Single sign-on
350
+
351
+ The **LiteLLM** entry in `/connect` also offers two browser sign-ins. The sign-in returns to a temporary `http://127.0.0.1` callback, so the browser must run on the same machine as the OpenCode server (OpenCode Desktop's own server qualifies; a Desktop connected to a remote server does not), and the proxy needs an `https` base URL (plain `http` only on a loopback host). On OpenCode 2, OpenCode stores the session as a credential of the integration, refreshes it, and injects it into requests, as it does with a connected key; OpenCode 1 differences are [below](#opencode-1).
352
+
353
+ **LiteLLM SSO** signs in through the proxy. Leave **Base URL** empty to use the configured provider's URL, the current sign-in's proxy, or `LITELLM_BASE_URL`. A URL that differs from the configured one is refused, because explicit configuration wins in discovery and the token would go to a proxy that did not issue it. The plugin uses the newest flow the proxy offers:
354
+
355
+ 1. **CLI-auth contract** (`/.well-known/litellm-cli-auth`): authorization code + PKCE (`S256`) with a dynamically registered client. Advertised endpoints must stay on the proxy's origin, and these requests do not follow redirects. Access and refresh tokens rotate automatically; a temporary token-endpoint failure (network, 429, 5xx) keeps the current token until it actually expires.
356
+ 2. **CLI SSO** (`/sso/cli/start`, when the discovery path serves no contract the plugin speaks: a 404, an access gateway's 401 or 403, a page from a catch-all route, or another contract version): confirm the code OpenCode shows in the browser. When your account belongs to several teams, LiteLLM asks for one; the sign-in then fails with the list of teams, so connect again with the team's ID or alias as **Team**. The token lasts as long as the proxy reports (24 hours on proxies that report nothing), then you connect again.
357
+ 3. **UI token** (when `/sso/cli/start` answers with another error, such as 404 or 405 on older proxies, or 401 or 403 from an access gateway): sign in on the page OpenCode opens and paste the token from the LiteLLM UI as the code. The plugin exchanges it for a virtual key through `/key/generate`, and uses the token itself when the proxy cannot mint one: 403 (no key-generation rights), 404, or 500 (no database). Any other answer, such as 401 for an expired token, fails the sign-in.
358
+
359
+ A rate limit (429) or server error (5xx) at discovery or `/sso/cli/start` fails the sign-in instead of falling back to an older flow, so trying again can still reach the newer one.
360
+
361
+ **Identity provider (OIDC)** signs in with your identity provider directly, for proxies running LiteLLM JWT auth (`enable_jwt_auth`) that trust its issuer and accept the client ID as an audience. Enter the `https` issuer URL, a public client ID (no secret) registered for authorization code + PKCE with the redirect `http://127.0.0.1:<port>/callback`, the scopes (default `openid`; some identity providers only issue a refresh token with `offline_access`), and, for identity providers that only accept exact redirect URIs, the ports to try. The `id_token` is the bearer token: the plugin checks its issuer, audience, authorized party, subject, expiry, and nonce, and the proxy verifies its signature. Signing in sends nothing to the proxy, and identity provider requests never carry custom headers.
362
+
363
+ A sign-in's token only goes to the proxy it is for. Without a configured base URL, the plugin uses the proxy the sign-in came from; a base URL configured for another proxy turns the sign-in off, with a warning in the log. A sign-in that names no proxy, such as an OIDC sign-in with an empty **Base URL**, uses the configured base URL or `LITELLM_BASE_URL`; the plugin does not probe local ports for it, because whatever answered there would get the token. On OpenCode 2 this covers the plugin's own requests, but OpenCode itself pairs the provider whose id is `litellm` with the **LiteLLM** connection and sends that connection's token with the provider's requests. After pointing `litellm` at another proxy, connect again to that proxy, or disconnect.
364
+
365
+ Disconnecting removes the local credential only; it does not revoke the session on the proxy or the identity provider.
366
+
367
+ If a sign-in fails before the browser opens (no proxy URL, a plain `http` URL, an unreachable proxy or identity provider, an invalid OIDC field), OpenCode shows only a generic error, such as "Unknown error" in the Desktop app: OpenCode drops the message of an error a plugin raises at that step. The reason is in OpenCode's log. Errors after the browser step, such as the team list, are shown.
368
+
369
+ ##### OpenCode 1
370
+
371
+ OpenCode 1 lists the sign-ins under the `litellm` provider, in `/connect`, its Desktop app's providers view, and `opencode auth login`. The answers that can be left out sit behind a choice instead of an empty field, since the Desktop app cannot submit one: the proxy (**Configured or previous proxy** or **Another URL…**), the team, the scopes, and the redirect ports. Without a configured or previous proxy, pick **Another URL…**.
372
+
373
+ - **First sign-in:** run `opencode auth login -p litellm`. OpenCode 1 lists a provider in `/connect` and the Desktop app only once it has models, and the proxy hides them until you sign in. After that, reconnect from either; the model list stays cached for the sign-in, so LiteLLM keeps appearing even after the session ends.
374
+ - The session lives in OpenCode 1's `auth.json` like any login (the sign-in's details in `accountId`, the only field OpenCode 1 keeps). The plugin refreshes it shortly before it expires, sends the current token with every request (including the `-responses` sibling), and saves rotated tokens back; when another OpenCode process sharing the file refreshed first, it uses that one.
375
+ - A configured `apiKey` still wins over a sign-in, and a sign-in wins over `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, even once it expired: requests then ask you to connect again.
376
+ - Only the default `litellm` provider id can sign in: OpenCode 1 gives a plugin one auth entry. OpenCode 2 imports OpenCode 1 logins under a method this plugin does not claim, so connect again after upgrading.
377
+
378
+ The discovered model list is cached per credential: a short hash of the effective key (never the raw key) is part of every cache entry's key, so when the selected credential changes the next discovery starts fresh instead of serving another credential's model list. A sign-in is keyed by its credential id instead, because its access token rotates on every refresh. A `credential.switched` event also recomputes the effective key and reloads the provider registry when it changed — including the first credential saved after setup.
348
379
 
349
380
  ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
350
381
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-plugin-litellm",
4
- "version": "1.8.1",
4
+ "version": "1.9.0",
5
5
  "description": "OpenCode CLI (v1 and v2) and Desktop plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
@@ -0,0 +1,312 @@
1
+ import type { AuthHook, AuthOAuthResult, PluginInput } from '@opencode-ai/plugin'
2
+ import { getOpenCodeStoredSso, toOpenCodeOAuthEntry } from '../utils/opencode-auth'
3
+ import {
4
+ authorizeLiteLLM,
5
+ authorizeOidc,
6
+ parseOidcConfig,
7
+ refreshSsoToken,
8
+ signInRoot,
9
+ type SsoAuthorization,
10
+ type SsoToken,
11
+ } from '../utils/sso'
12
+
13
+ /** Where the config hook found the provider; a sign-in goes to its proxy, with its gateway headers. */
14
+ export interface SignInTarget {
15
+ /** The provider's configured base URL, which discovery always uses. */
16
+ baseURL: string | undefined
17
+ /** The proxy of the stored sign-in, the default for a provider configured nowhere. */
18
+ previousURL: string | undefined
19
+ headers: Record<string, string>
20
+ }
21
+
22
+ // OpenCode 2 refreshes credentials this long before they expire; OpenCode 1 leaves it to plugins.
23
+ const REFRESH_LEAD_MS = 5 * 60 * 1000
24
+ // After a refresh that did not happen (an unavailable token endpoint), requests use the current
25
+ // token for this long instead of each waiting on the token endpoint again.
26
+ const RETRY_MS = 30 * 1000
27
+
28
+ export interface SsoSession {
29
+ /** The stored sign-in, expired or not, or undefined without one. */
30
+ stored(): Promise<SsoToken | undefined>
31
+ /** A live access token; throws when the sign-in expired and cannot be refreshed. */
32
+ access(headers?: Record<string, string>): Promise<string | undefined>
33
+ }
34
+
35
+ interface SessionState {
36
+ token?: Promise<SsoToken | undefined>
37
+ refreshing?: Promise<SsoToken>
38
+ retryAt?: number
39
+ }
40
+
41
+ // One state per provider for the whole process: OpenCode 1 can keep calling a fetch an earlier
42
+ // plugin instance wrote into its cached config, and every caller must share one refresh.
43
+ const sessions = new Map<string, SessionState>()
44
+
45
+ /**
46
+ * The OpenCode 1 side of a LiteLLM sign-in: the session OpenCode stored in
47
+ * auth.json, refreshed when it nears expiry and saved back through the
48
+ * OpenCode client, because OpenCode 1 does not refresh plugin credentials.
49
+ */
50
+ export function createSsoSession(
51
+ client: PluginInput['client'],
52
+ providerID: string,
53
+ warn: (message: string) => void,
54
+ ): SsoSession {
55
+ const state = sessions.get(providerID) ?? {}
56
+ sessions.set(providerID, state)
57
+ // A new plugin instance follows a login, so it reads auth.json again.
58
+ state.token = undefined
59
+ state.retryAt = undefined
60
+ const stored = () => (state.token ??= getOpenCodeStoredSso(providerID))
61
+
62
+ async function refresh(current: SsoToken, headers?: Record<string, string>): Promise<SsoToken> {
63
+ const latest = await getOpenCodeStoredSso(providerID)
64
+ // Never overwrite a credential saved since: a logout, an API key, or another sign-in.
65
+ if (!latest) throw new Error('The LiteLLM sign-in was removed; connect LiteLLM again')
66
+ if (latest.access !== current.access) {
67
+ // Another OpenCode process refreshed it; a sign-in to another proxy must not inherit this one's requests.
68
+ if (latest.metadata.baseURL !== current.metadata.baseURL) {
69
+ throw new Error('The LiteLLM sign-in changed; connect LiteLLM again')
70
+ }
71
+ return latest
72
+ }
73
+ const next = await refreshSsoToken(current, headers)
74
+ if (next === current) {
75
+ state.retryAt = Date.now() + RETRY_MS
76
+ return current
77
+ }
78
+ // A credential saved during the refresh wins on disk; this process keeps its own tokens.
79
+ if ((await getOpenCodeStoredSso(providerID))?.access === current.access) {
80
+ const saved = await client.auth
81
+ .set({ path: { id: providerID }, body: toOpenCodeOAuthEntry(next) })
82
+ .catch((error: unknown) => ({ error }))
83
+ if (saved.error) {
84
+ warn(
85
+ '[opencode-litellm] Could not save the refreshed LiteLLM sign-in; the next start may ask for a new one.',
86
+ )
87
+ }
88
+ }
89
+ return next
90
+ }
91
+
92
+ return {
93
+ stored,
94
+ async access(headers) {
95
+ const current = await stored()
96
+ if (!current) return undefined
97
+ const now = Date.now()
98
+ if (current.expires > now + REFRESH_LEAD_MS) return current.access
99
+ if (current.expires > now && state.retryAt !== undefined && now < state.retryAt)
100
+ return current.access
101
+ // One refresh at a time: a rotated refresh token cannot be spent twice.
102
+ state.refreshing ??= refresh(current, headers)
103
+ .then((next) => {
104
+ state.token = Promise.resolve(next)
105
+ return next
106
+ })
107
+ .finally(() => {
108
+ state.refreshing = undefined
109
+ })
110
+ return (await state.refreshing).access
111
+ },
112
+ }
113
+ }
114
+
115
+ /** Sends the sign-in's live token on every request; OpenCode 1 builds requests from static options. */
116
+ export function ssoFetch(session: SsoSession, headers?: Record<string, string>): typeof fetch {
117
+ return async (input, init) => {
118
+ const access = await session.access(headers)
119
+ const requestHeaders = new Headers(
120
+ init?.headers ?? (input instanceof Request ? input.headers : undefined),
121
+ )
122
+ if (access) requestHeaders.set('Authorization', `Bearer ${access}`)
123
+ return fetch(input, { ...init, headers: requestHeaders })
124
+ }
125
+ }
126
+
127
+ function text(value: string | undefined): string | undefined {
128
+ return value?.trim() || undefined
129
+ }
130
+
131
+ /** Wraps a sign-in for OpenCode 1, which stores a successful result in auth.json. */
132
+ function toAuthResult(authorization: SsoAuthorization, baseURL?: string): AuthOAuthResult {
133
+ const success = (token: SsoToken) => {
134
+ const { type: _, ...entry } = toOpenCodeOAuthEntry({
135
+ ...token,
136
+ metadata: { ...token.metadata, ...(baseURL ? { baseURL } : {}) },
137
+ })
138
+ return { type: 'success' as const, ...entry }
139
+ }
140
+ const { url, instructions } = authorization
141
+ if (authorization.mode === 'code') {
142
+ return {
143
+ url,
144
+ instructions,
145
+ method: 'code',
146
+ callback: async (code) => success(await authorization.callback(code)),
147
+ }
148
+ }
149
+ return {
150
+ url,
151
+ instructions,
152
+ method: 'auto',
153
+ callback: async () => success(await authorization.callback),
154
+ }
155
+ }
156
+
157
+ type Prompt = NonNullable<
158
+ Extract<AuthHook['methods'][number], { type: 'oauth' }>['prompts']
159
+ >[number]
160
+
161
+ // OpenCode Desktop cannot submit an empty text prompt, so each optional answer sits behind a select.
162
+ const proxyPrompts: Prompt[] = [
163
+ {
164
+ type: 'select',
165
+ key: 'proxy',
166
+ message: 'LiteLLM proxy',
167
+ options: [
168
+ {
169
+ label: 'Configured or previous proxy',
170
+ value: 'known',
171
+ hint: 'the provider baseURL, the last sign-in, or LITELLM_BASE_URL',
172
+ },
173
+ { label: 'Another URL…', value: 'other' },
174
+ ],
175
+ },
176
+ {
177
+ type: 'text',
178
+ key: 'baseURL',
179
+ message: 'LiteLLM proxy URL',
180
+ placeholder: 'https://llm.example.com',
181
+ when: { key: 'proxy', op: 'eq', value: 'other' },
182
+ },
183
+ ]
184
+
185
+ /** The proxy a sign-in goes to: a typed URL, else the configured one, the previous sign-in's, or the environment's. */
186
+ function proxyFor(
187
+ inputs: Record<string, string>,
188
+ target: SignInTarget,
189
+ providerID: string,
190
+ ): string | undefined {
191
+ const typed = inputs.proxy === 'other' ? text(inputs.baseURL) : undefined
192
+ if (inputs.proxy === 'other' && !typed) throw new Error('Enter the LiteLLM proxy URL')
193
+ // The previous sign-in's proxy is only a default: unlike configuration, signing in elsewhere replaces it.
194
+ const previous = target.baseURL ? undefined : target.previousURL
195
+ return signInRoot(typed ?? previous, target.baseURL, providerID)
196
+ }
197
+
198
+ /**
199
+ * The `/connect` and `opencode auth login` entries for the LiteLLM provider:
200
+ * LiteLLM SSO, a direct sign-in with an OpenID Connect identity provider, or
201
+ * an API key. `target` reports where the config hook found the provider.
202
+ */
203
+ export function liteLLMAuthHook(providerID: string, target: () => SignInTarget): AuthHook {
204
+ return {
205
+ provider: providerID,
206
+ methods: [
207
+ {
208
+ type: 'oauth',
209
+ label: 'LiteLLM SSO',
210
+ prompts: [
211
+ ...proxyPrompts,
212
+ {
213
+ type: 'select',
214
+ key: 'teamChoice',
215
+ message: 'LiteLLM team',
216
+ options: [
217
+ {
218
+ label: 'Default',
219
+ value: 'default',
220
+ hint: 'LiteLLM asks only when your account has several',
221
+ },
222
+ { label: 'A specific team…', value: 'other' },
223
+ ],
224
+ },
225
+ {
226
+ type: 'text',
227
+ key: 'team',
228
+ message: 'LiteLLM team ID or alias',
229
+ when: { key: 'teamChoice', op: 'eq', value: 'other' },
230
+ },
231
+ ],
232
+ authorize: async (inputs = {}) => {
233
+ const baseURL = proxyFor(inputs, target(), providerID)
234
+ if (!baseURL) throw new Error('Enter the LiteLLM proxy URL, or set LITELLM_BASE_URL')
235
+ const team = inputs.teamChoice === 'other' ? text(inputs.team) : undefined
236
+ return toAuthResult(await authorizeLiteLLM(baseURL, target().headers, team))
237
+ },
238
+ },
239
+ {
240
+ type: 'oauth',
241
+ label: 'Identity provider (OIDC)',
242
+ prompts: [
243
+ ...proxyPrompts,
244
+ {
245
+ type: 'text',
246
+ key: 'issuer',
247
+ message: "Your identity provider's issuer URL",
248
+ placeholder: 'https://idp.example.com',
249
+ },
250
+ {
251
+ type: 'text',
252
+ key: 'clientId',
253
+ message:
254
+ 'Public client ID (no secret) for the redirect http://127.0.0.1:<port>/callback',
255
+ },
256
+ {
257
+ type: 'select',
258
+ key: 'scope',
259
+ message: 'Scopes',
260
+ options: [
261
+ { label: 'openid', value: 'openid' },
262
+ {
263
+ label: 'openid offline_access',
264
+ value: 'openid offline_access',
265
+ hint: 'some identity providers only issue refresh tokens with it',
266
+ },
267
+ { label: 'Other scopes…', value: 'other' },
268
+ ],
269
+ },
270
+ {
271
+ type: 'text',
272
+ key: 'customScope',
273
+ message: 'Scopes, space-separated, including openid',
274
+ when: { key: 'scope', op: 'eq', value: 'other' },
275
+ },
276
+ {
277
+ type: 'select',
278
+ key: 'ports',
279
+ message: 'Redirect port',
280
+ options: [
281
+ { label: 'Any free port', value: 'any' },
282
+ {
283
+ label: 'Specific ports…',
284
+ value: 'specific',
285
+ hint: 'for identity providers that only accept exact registered redirect URIs',
286
+ },
287
+ ],
288
+ },
289
+ {
290
+ type: 'text',
291
+ key: 'redirectPorts',
292
+ message: 'Ports to try, in order',
293
+ placeholder: '8400, 8401',
294
+ when: { key: 'ports', op: 'eq', value: 'specific' },
295
+ },
296
+ ],
297
+ authorize: async (inputs = {}) => {
298
+ // Nothing is sent to the proxy, so its URL is only recorded for discovery.
299
+ const baseURL = proxyFor(inputs, target(), providerID)
300
+ const config = parseOidcConfig({
301
+ issuer: text(inputs.issuer),
302
+ clientId: text(inputs.clientId),
303
+ scope: inputs.scope === 'other' ? text(inputs.customScope) : text(inputs.scope),
304
+ redirectPorts: inputs.ports === 'specific' ? text(inputs.redirectPorts) : undefined,
305
+ })
306
+ return toAuthResult(await authorizeOidc(config), baseURL)
307
+ },
308
+ },
309
+ { type: 'api', label: 'API key' },
310
+ ],
311
+ }
312
+ }
@@ -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)