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.
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
- ...readHeaders(pluginOptions.customHeaders),
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
- const connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
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(apiKey, customHeaders)
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
- const connectionKey = credential?.type === 'key' ? credential.key : undefined
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
@@ -11,6 +11,18 @@ function stripVersionSuffix(part: string): string {
11
11
  return part.replace(/@(default|\d{6,8})$/i, '')
12
12
  }
13
13
 
14
+ /**
15
+ * Like `looksLikeVersionComponent`, but tolerates a single leading
16
+ * version letter — only the letters seen in real version positions
17
+ * (`v3`, `k2`, `m2`), so quantization prefixes like `q4` never pair.
18
+ * Dotted ids like `deepseek-v3.2` or `kimi-k2.5` have their version
19
+ * split apart by the tokenizer, and the letter-prefixed half must
20
+ * still merge back with the digits after the dot.
21
+ */
22
+ function looksLikePrefixedVersionComponent(token: string): boolean {
23
+ return /^[vkm]?\d{1,2}$/i.test(token)
24
+ }
25
+
14
26
  /**
15
27
  * Heuristic: does this numeric token look like a real version component
16
28
  * (single or double digit) rather than a date stamp or build number?
@@ -31,6 +43,15 @@ function looksLikeVersionComponent(token: string): boolean {
31
43
  * version pair, but the formatter would otherwise render it as
32
44
  * "Claude Opus 4 5".
33
45
  *
46
+ * The left-hand token may also carry a single version letter (`v3`,
47
+ * `k2`, `m2`): ids like `deepseek-v3.2` or `kimi-k2.5` get their dot
48
+ * split apart by the tokenizer and must re-join as `v3.2` / `k2.5`,
49
+ * never render as "DeepSeek V3 2" / "Kimi K2 5".
50
+ * Quantization prefixes never pair (`q4_0` tokenises as `q4` + `0`,
51
+ * but `q` is not a version letter), so `mistral-7b-instruct-q4_0`
52
+ * renders "Mistral 7B Instruct Q4 0" while ids with a real version
53
+ * pair like `llama-3.1-8b-instruct-q4_0` keep merging `3.1`.
54
+ *
34
55
  * Conservative on purpose:
35
56
  * - Only the FIRST mergeable pair scanning from the right is collapsed:
36
57
  * `gpt-3-5-turbo-16k` merges `3-5` into `3.5` and stops there.
@@ -49,7 +70,7 @@ function joinTrailingVersionPair(tokens: string[]): string[] {
49
70
  for (let i = tokens.length - 1; i >= 1; i--) {
50
71
  const a = tokens[i - 1]
51
72
  const b = tokens[i]
52
- if (looksLikeVersionComponent(a) && looksLikeVersionComponent(b)) {
73
+ if (looksLikePrefixedVersionComponent(a) && looksLikeVersionComponent(b)) {
53
74
  const prev = tokens[i - 2]
54
75
  const next = tokens[i + 1]
55
76
  const prevIsShortNumeric = prev !== undefined && looksLikeVersionComponent(prev)
@@ -101,7 +122,11 @@ export function categorizeModel(model: LiteLLMModel): 'chat' | 'embedding' | 'im
101
122
  * - Collapse a trailing pair of bare numeric tokens into a single
102
123
  * dotted version. Anthropic uses dash-only ids — `claude-opus-4-7`
103
124
  * would otherwise render as "Claude Opus 4 7" instead of
104
- * "Claude Opus 4.7".
125
+ * "Claude Opus 4.7". The left-hand token may carry a version
126
+ * letter, so `deepseek-v3.2` renders "DeepSeek V3.2", not
127
+ * "Deepseek V3 2".
128
+ * - Keep the official casing of known brand names (GLM, DeepSeek,
129
+ * MiniMax) instead of generic title-case.
105
130
  *
106
131
  * Examples:
107
132
  * "openai/gpt-4o-mini" -> "GPT 4o Mini"
@@ -110,6 +135,10 @@ export function categorizeModel(model: LiteLLMModel): 'chat' | 'embedding' | 'im
110
135
  * "claude-sonnet-4-6@default" -> "Claude Sonnet 4.6"
111
136
  * "bedrock/amazon.nova-pro-v1" -> "Amazon Nova Pro V1"
112
137
  * "qwen/qwen3-30b-a3b" -> "Qwen3 30B A3B"
138
+ * "litellm/deepseek-v3.2" -> "DeepSeek V3.2"
139
+ * "litellm/glm-5.3" -> "GLM 5.3"
140
+ * "litellm/kimi-k2.5" -> "Kimi K2.5"
141
+ * "litellm/minimax-m2.5" -> "MiniMax M2.5"
113
142
  */
114
143
  export function formatModelName(model: LiteLLMModel): string {
115
144
  const { id } = model
@@ -124,10 +153,17 @@ export function formatModelName(model: LiteLLMModel): string {
124
153
  const modelPart = stripVersionSuffix(afterProvider)
125
154
 
126
155
  const acronyms = new Set([
127
- 'gpt', 'oss', 'api', 'gguf', 'ggml', 'nomic', 'vl', 'it', 'mlx',
156
+ 'gpt', 'glm', 'oss', 'api', 'gguf', 'ggml', 'nomic', 'vl', 'it', 'mlx',
128
157
  'llm', 'ai', 'sdk', 'aws', 'gcp', 'tts', 'stt', 'mm',
129
158
  ])
130
159
 
160
+ // Mixed-case brand names that generic title-case would mangle
161
+ // ("Deepseek", "Minimax").
162
+ const brandNames: Record<string, string> = {
163
+ deepseek: 'DeepSeek',
164
+ minimax: 'MiniMax',
165
+ }
166
+
131
167
  const rawTokens = modelPart
132
168
  .split(/[-_.]/) // split on -, _ and .
133
169
  .filter(Boolean)
@@ -138,6 +174,7 @@ export function formatModelName(model: LiteLLMModel): string {
138
174
  // when both sides are pure digits).
139
175
  const tokens = joinTrailingVersionPair(rawTokens).map((token) => {
140
176
  const lower = token.toLowerCase()
177
+ if (brandNames[lower]) return brandNames[lower]
141
178
  if (acronyms.has(lower)) return token.toUpperCase()
142
179
  // sizes (30b, 7b, 4k...)
143
180
  if (/^\d+[bkmg]$/i.test(token)) return token.toUpperCase()
@@ -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 the most common
161
- * ports. The default `litellm --port` is 4000, with 8000 and 8080 also common.
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(apiKey?: string, customHeaders?: Record<string, string>): Promise<string | null> {
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 commonPorts = [4000, 8000, 8080]
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` and `wellknown` entries there, but LiteLLM proxies
8
- * only ever use a plain API key, so that's the only variant we care about.
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 loadOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
37
- if (!cachedAuthFile) {
38
- cachedAuthFile = (async () => {
39
- try {
40
- const raw = await readFile(resolveAuthPath(), 'utf-8')
41
- const parsed: unknown = JSON.parse(raw)
42
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
43
- return parsed as OpenCodeAuthFile
44
- }
45
- } catch {
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
- /** Test-only: force the next read to hit disk again. */
81
- export function __resetOpenCodeAuthCacheForTests(): void {
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
+ }