opencode-plugin-litellm 1.11.1 → 1.12.1

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
@@ -409,6 +409,36 @@ If your LiteLLM proxy is behind Cloudflare Access or another gateway that requir
409
409
 
410
410
  These headers are included in every request the plugin makes during model discovery (health check and `/v1/models`). To obtain a Cloudflare Access Service Token, follow the [Cloudflare docs](https://developers.cloudflare.com/cloudflare-one/identity/service-tokens/).
411
411
 
412
+ ### Separate management host and custom endpoints
413
+
414
+ Some deployments serve the OpenAI-compatible API and the management API (`/v1/model/info`) from different hosts. Without the info response the plugin only sees bare model ids, so reasoning effort variants and capability flags are missing. Point discovery at the right places:
415
+
416
+ ```jsonc
417
+ {
418
+ "provider": {
419
+ "litellm": {
420
+ "options": {
421
+ "baseURL": "https://llm.example.com/v1",
422
+ "managementBaseURL": "https://management.llm.example.com",
423
+ "modelsEndpoint": "/v1/models", // optional
424
+ "modelInfoEndpoint": "/v1/model/info" // optional
425
+ }
426
+ }
427
+ }
428
+ }
429
+ ```
430
+
431
+ | Setting | Env fallback | Default |
432
+ |---|---|---|
433
+ | `managementBaseURL` | `LITELLM_MANAGEMENT_BASE_URL` | `baseURL` |
434
+ | `modelsEndpoint` | `LITELLM_MODELS_ENDPOINT` | `/v1/models` |
435
+ | `modelInfoEndpoint` | `LITELLM_MODEL_INFO_ENDPOINT` | `/v1/model/info` |
436
+
437
+ - If the models endpoint fails but the info endpoint answers, the model list is built from the info response.
438
+ - The health check falls back to the info endpoint on the management host.
439
+ - A LiteLLM **sign-in** (SSO/OIDC) token is only sent to the origin that issued it. When `managementBaseURL` is on a different origin than `baseURL`, the info request goes out without the token: the model list still arrives, but capability metadata from that host does not. An API key (`apiKey` / `LITELLM_API_KEY`) is the operator's own and is still sent to the management host.
440
+ - Changing any of these starts a fresh discovery on the next start.
441
+
412
442
  ### Splitting one proxy into multiple providers (`includeModels` / `excludeModels`)
413
443
 
414
444
  If your LiteLLM catalog mixes naming conventions from different teams or environments (e.g. `prod/*` and `staging/*`), you can point two OpenCode providers at the *same* proxy and have each one surface only its slice:
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.11.1",
4
+ "version": "1.12.1",
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",
@@ -1,11 +1,16 @@
1
1
  import type { Plugin, PluginInput } from '@opencode-ai/plugin'
2
2
  import {
3
3
  autoDetectLiteLLM,
4
+ buildModelInfoMap,
4
5
  checkLiteLLMHealth,
5
- discoverLiteLLMModelInfo,
6
6
  discoverLiteLLMModels,
7
+ fetchLiteLLMModelInfoEntries,
7
8
  getRequestTimeoutMs,
9
+ modelsFromInfoEntries,
8
10
  normalizeBaseURL,
11
+ readDiscoveryEndpoints,
12
+ sameOriginURL,
13
+ type DiscoveryEndpoints,
9
14
  } from '../utils/litellm-api'
10
15
  import {
11
16
  applyModelNameTemplate,
@@ -121,6 +126,7 @@ interface RefreshContext {
121
126
  modelNameTemplate?: string
122
127
  providerName: string
123
128
  providerId: string
129
+ endpoints: DiscoveryEndpoints
124
130
  }
125
131
  const refreshContexts = new Map<string, RefreshContext>()
126
132
 
@@ -455,8 +461,10 @@ export async function discoverModels(
455
461
  filters: ModelFilters = {},
456
462
  capabilities: ModelCapabilities = {},
457
463
  naming: ModelNaming = {},
464
+ endpoints: DiscoveryEndpoints = {},
465
+ signInCredential = false,
458
466
  ): Promise<DiscoveredModels | null> {
459
- if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
467
+ if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders, endpoints, signInCredential))) {
460
468
  log(
461
469
  'warn',
462
470
  `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
@@ -468,12 +476,38 @@ export async function discoverModels(
468
476
  // database-defined models, so fetch `/v1/model/info` alongside
469
477
  // it. The info call is best-effort: without it, classification
470
478
  // falls back to id heuristics.
479
+ // A sign-in's token only goes to the proxy that issued it, so a management
480
+ // host on another origin gets the request without it and answers 401/404:
481
+ // the model list still arrives, without the info enrichment.
482
+ if (
483
+ signInCredential &&
484
+ endpoints.managementBaseURL &&
485
+ !sameOriginURL(endpoints.managementBaseURL, baseURL)
486
+ ) {
487
+ log(
488
+ 'warn',
489
+ `[opencode-litellm] Not sending the LiteLLM sign-in to the management host ${endpoints.managementBaseURL} for provider "${providerId}": a sign-in token only goes to the proxy that issued it. Model metadata from that host is unavailable.`,
490
+ )
491
+ }
471
492
  const [modelsResult, infoResult] = await Promise.allSettled([
472
- discoverLiteLLMModels(baseURL, apiKey, customHeaders),
473
- discoverLiteLLMModelInfo(baseURL, apiKey, customHeaders),
493
+ discoverLiteLLMModels(baseURL, apiKey, customHeaders, endpoints),
494
+ fetchLiteLLMModelInfoEntries(baseURL, apiKey, customHeaders, endpoints, signInCredential),
474
495
  ])
475
496
 
476
- if (modelsResult.status === 'rejected') {
497
+ let discovered: LiteLLMModel[]
498
+ if (modelsResult.status === 'fulfilled') {
499
+ discovered = modelsResult.value
500
+ } else if (infoResult.status === 'fulfilled' && infoResult.value.length > 0) {
501
+ // No usable models endpoint: the info response still names every model.
502
+ const error = modelsResult.reason
503
+ log(
504
+ 'warn',
505
+ `[opencode-litellm] Models endpoint failed for provider "${providerId}" (` +
506
+ (error instanceof Error ? error.message : String(error)) +
507
+ '); building the model list from the model info endpoint.',
508
+ )
509
+ discovered = modelsFromInfoEntries(infoResult.value)
510
+ } else {
477
511
  const error = modelsResult.reason
478
512
  log(
479
513
  'warn',
@@ -483,15 +517,14 @@ export async function discoverModels(
483
517
  return null
484
518
  }
485
519
 
486
- const discovered = modelsResult.value
487
520
  let infoByName: Map<string, LiteLLMModelInfo> | null = null
488
521
  if (infoResult.status === 'fulfilled') {
489
- infoByName = infoResult.value
522
+ infoByName = buildModelInfoMap(infoResult.value)
490
523
  } else {
491
524
  const reason = infoResult.reason
492
525
  log(
493
526
  'warn',
494
- `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only: ` +
527
+ `[opencode-litellm] Model info endpoint unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only: ` +
495
528
  (reason instanceof Error ? reason.message : String(reason)),
496
529
  )
497
530
  }
@@ -850,6 +883,8 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
850
883
  providerId: ctx.providerId,
851
884
  providerName: ctx.providerName,
852
885
  },
886
+ ctx.endpoints,
887
+ ctx.session !== undefined,
853
888
  ),
854
889
  DISCOVERY_TIMEOUT_MS,
855
890
  )
@@ -1019,6 +1054,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1019
1054
  const providerName =
1020
1055
  typeof provider.name === 'string' && provider.name ? provider.name : providerId
1021
1056
  const naming = { formatModelNames, modelNameTemplate, providerId, providerName }
1057
+ const endpoints = readDiscoveryEndpoints(options)
1022
1058
 
1023
1059
  // Resolve base URL
1024
1060
  let baseURL: string | null = null
@@ -1095,7 +1131,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1095
1131
  formatModelNames,
1096
1132
  modelNameTemplate,
1097
1133
  providerName,
1098
- }, sso ? ssoIdentity(sso) : apiKey)
1134
+ }, sso ? ssoIdentity(sso) : apiKey, endpoints)
1099
1135
 
1100
1136
  // Remember how to reach this proxy so the `event` hook can
1101
1137
  // revalidate its cache in the background on new sessions.
@@ -1114,6 +1150,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1114
1150
  modelNameTemplate,
1115
1151
  providerName,
1116
1152
  providerId,
1153
+ endpoints,
1117
1154
  })
1118
1155
 
1119
1156
  // The Responses sibling (if any) holds a disjoint set of ids, so the
@@ -1182,6 +1219,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1182
1219
  filters,
1183
1220
  capabilities,
1184
1221
  { formatModelNames, modelNameTemplate, providerId, providerName },
1222
+ endpoints,
1223
+ Boolean(sso),
1185
1224
  ),
1186
1225
  DISCOVERY_TIMEOUT_MS,
1187
1226
  )
@@ -45,6 +45,12 @@ export interface ConnectedLiteLLM {
45
45
  providerID: string | undefined
46
46
  /** Id of an OAuth credential, which stays put while its access token rotates. */
47
47
  credentialID?: string
48
+ /**
49
+ * `apiKey` is an SSO/OIDC access token. Such a token is bound to the proxy
50
+ * that issued it, so callers must not send it to another origin. A key saved
51
+ * in the dialog is the operator's own and carries no such restriction.
52
+ */
53
+ signIn: boolean
48
54
  }
49
55
 
50
56
  /** The configured proxy URL and gateway headers a sign-in for a provider id uses. */
@@ -325,6 +331,7 @@ export async function readConnectedConfig(
325
331
  providerID: readAnswer(answers, 'providerID'),
326
332
  credentialID:
327
333
  credential.type === 'oauth' && active.type === 'credential' ? active.id : undefined,
334
+ signIn: credential.type === 'oauth',
328
335
  }
329
336
  } catch {
330
337
  return undefined
package/src/plugin/v2.ts CHANGED
@@ -27,7 +27,12 @@ import {
27
27
  readModelCacheSavedAt,
28
28
  writeModelCache,
29
29
  } from '../utils/model-cache'
30
- import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
30
+ import {
31
+ normalizeBaseURL,
32
+ autoDetectLiteLLM,
33
+ readDiscoveryEndpoints,
34
+ type DiscoveryEndpoints,
35
+ } from '../utils/litellm-api'
31
36
  import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
32
37
  import { sameProxy } from '../utils/sso'
33
38
  import { parseModelCapabilities } from '../utils/model-capabilities'
@@ -84,6 +89,8 @@ interface ProviderSource {
84
89
  headers: Record<string, string>
85
90
  integrationID?: string
86
91
  usesConnectionCredential: boolean
92
+ /** `apiKey` is a LiteLLM sign-in token, which only goes to the proxy that issued it. */
93
+ signInCredential: boolean
87
94
  baseURL: string
88
95
  apiKey?: string
89
96
  customHeaders?: Record<string, string>
@@ -112,6 +119,7 @@ interface ProviderSource {
112
119
  formatModelNames: boolean
113
120
  modelNameTemplate?: string
114
121
  providerName: string
122
+ endpoints: DiscoveryEndpoints
115
123
  cacheKey: string
116
124
  models: Model.Info[]
117
125
  /**
@@ -472,6 +480,9 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
472
480
  'modelCompatibility',
473
481
  'formatModelNames',
474
482
  'modelNameTemplate',
483
+ 'managementBaseURL',
484
+ 'modelsEndpoint',
485
+ 'modelInfoEndpoint',
475
486
  'providerID',
476
487
  ]) {
477
488
  delete settings[key]
@@ -587,6 +598,9 @@ async function makeProviderSource(
587
598
  // fallback.
588
599
  const storedKey = await getOpenCodeStoredApiKey(id)
589
600
  const usesConnectionCredential = settingsApiKey === undefined && connectedApiKey !== undefined
601
+ // Only an OAuth connection is a sign-in; a key saved through `/connect` is the
602
+ // operator's own and may go wherever they pointed the management host.
603
+ const signInCredential = usesConnectionCredential && connected?.signIn === true
590
604
  const integrationID =
591
605
  provider?.integrationID ??
592
606
  (usesConnectionCredential ? connectedIntegrationID : undefined)
@@ -601,6 +615,7 @@ async function makeProviderSource(
601
615
  // distinguishable.
602
616
  const providerName = provider?.name || id
603
617
  const naming = { formatModelNames, modelNameTemplate, providerId: id, providerName }
618
+ const endpoints = readDiscoveryEndpoints(settings)
604
619
  // Explicit config beats the URL typed into the dialog, which beats the
605
620
  // environment and local port probing.
606
621
  const detectedBaseURL = configuredBaseURL
@@ -624,7 +639,7 @@ async function makeProviderSource(
624
639
  // the raw key): a credential change starts a fresh discovery instead of
625
640
  // serving another credential's cached model list. A sign-in is keyed by its
626
641
  // credential id, because its access token rotates on every refresh.
627
- const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, naming, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey)
642
+ const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, naming, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey, endpoints)
628
643
  const cacheEntry = readModelCacheEntry(cacheKey)
629
644
  let entries = cacheEntry?.models ?? null
630
645
  let responsesIds = cacheEntry?.responsesIds ?? []
@@ -640,6 +655,8 @@ async function makeProviderSource(
640
655
  filters,
641
656
  capabilities,
642
657
  naming,
658
+ endpoints,
659
+ signInCredential,
643
660
  ),
644
661
  DISCOVERY_TIMEOUT_MS,
645
662
  )
@@ -669,6 +686,7 @@ async function makeProviderSource(
669
686
  headers: customHeaders,
670
687
  integrationID,
671
688
  usesConnectionCredential,
689
+ signInCredential,
672
690
  credentialReloadRequired: false,
673
691
  refreshRequired: false,
674
692
  fromFallback: provider === undefined,
@@ -682,6 +700,7 @@ async function makeProviderSource(
682
700
  formatModelNames,
683
701
  modelNameTemplate,
684
702
  providerName,
703
+ endpoints,
685
704
  cacheKey,
686
705
  models: toProviderModels(id, entries ?? {}, {
687
706
  providerPackage,
@@ -749,6 +768,8 @@ async function refreshProviderSource(
749
768
  providerId: source.id,
750
769
  providerName: source.providerName,
751
770
  },
771
+ source.endpoints,
772
+ source.signInCredential,
752
773
  ),
753
774
  DISCOVERY_TIMEOUT_MS,
754
775
  )
@@ -835,11 +856,14 @@ async function refreshConnectionCredential(
835
856
  const settingsApiKey = readString(source.settings.apiKey)
836
857
  let nextKey: string | undefined
837
858
  let nextUsesConnection: boolean
859
+ let nextSignIn: boolean
838
860
  if (connectionKey !== undefined) {
839
861
  // An explicit settings apiKey stays first; a connection credential takes
840
862
  // over the environment/auto-detected key.
841
863
  nextKey = settingsApiKey ?? connectionKey
842
864
  nextUsesConnection = settingsApiKey === undefined
865
+ // A sign-in token is bound to the proxy that issued it; a key is not.
866
+ nextSignIn = nextUsesConnection && credential?.type === 'oauth'
843
867
  } else {
844
868
  // The connection credential is gone (the connection was removed or its
845
869
  // credential cleared): fall back through the stored credential / env key
@@ -850,10 +874,18 @@ async function refreshConnectionCredential(
850
874
  const envKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
851
875
  nextKey = settingsApiKey ?? storedKey ?? envKey
852
876
  nextUsesConnection = false
877
+ nextSignIn = false
878
+ }
879
+ if (
880
+ nextKey === source.apiKey &&
881
+ nextUsesConnection === source.usesConnectionCredential &&
882
+ nextSignIn === source.signInCredential
883
+ ) {
884
+ return false
853
885
  }
854
- if (nextKey === source.apiKey && nextUsesConnection === source.usesConnectionCredential) return false
855
886
  source.apiKey = nextKey
856
887
  source.usesConnectionCredential = nextUsesConnection
888
+ source.signInCredential = nextSignIn
857
889
  source.credentialReloadRequired = true
858
890
  return true
859
891
  } catch (error) {
@@ -1,4 +1,10 @@
1
- import type { LiteLLMModel, LiteLLMModelInfo, LiteLLMModelInfoResponse, LiteLLMModelsResponse } from '../types'
1
+ import type {
2
+ LiteLLMModel,
3
+ LiteLLMModelInfo,
4
+ LiteLLMModelInfoEntry,
5
+ LiteLLMModelInfoResponse,
6
+ LiteLLMModelsResponse,
7
+ } from '../types'
2
8
  import { CAPABILITY_FLAGS } from './model-capabilities'
3
9
  import { resolveReasoningEfforts } from './reasoning-efforts'
4
10
 
@@ -40,6 +46,51 @@ export function normalizeBaseURL(baseURL: string = DEFAULT_LITELLM_URL): string
40
46
  return normalized
41
47
  }
42
48
 
49
+ /**
50
+ * Optional overrides for where discovery looks. Each field is left unset when
51
+ * it matches the default, so default configs keep their cache identity.
52
+ */
53
+ export interface DiscoveryEndpoints {
54
+ /** Host serving the model-info endpoint when it differs from the model host. */
55
+ managementBaseURL?: string
56
+ modelsEndpoint?: string
57
+ modelInfoEndpoint?: string
58
+ }
59
+
60
+ function readEndpointPath(raw: unknown, fallback: string): string | undefined {
61
+ if (typeof raw !== 'string' || raw.trim() === '') return undefined
62
+ const trimmed = raw.trim()
63
+ const path = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
64
+ return path === fallback ? undefined : path
65
+ }
66
+
67
+ function readNonEmpty(raw: unknown): string | undefined {
68
+ return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : undefined
69
+ }
70
+
71
+ /**
72
+ * Read `managementBaseURL`, `modelsEndpoint` and `modelInfoEndpoint` from a
73
+ * provider's options/settings, falling back to `LITELLM_MANAGEMENT_BASE_URL`,
74
+ * `LITELLM_MODELS_ENDPOINT` and `LITELLM_MODEL_INFO_ENDPOINT`.
75
+ */
76
+ export function readDiscoveryEndpoints(options: Record<string, unknown>): DiscoveryEndpoints {
77
+ const management =
78
+ readNonEmpty(options.managementBaseURL) ?? readNonEmpty(process.env.LITELLM_MANAGEMENT_BASE_URL)
79
+ const models = readEndpointPath(
80
+ options.modelsEndpoint ?? process.env.LITELLM_MODELS_ENDPOINT,
81
+ MODELS_ENDPOINT,
82
+ )
83
+ const info = readEndpointPath(
84
+ options.modelInfoEndpoint ?? process.env.LITELLM_MODEL_INFO_ENDPOINT,
85
+ MODEL_INFO_ENDPOINT,
86
+ )
87
+ const endpoints: DiscoveryEndpoints = {}
88
+ if (management) endpoints.managementBaseURL = normalizeBaseURL(management)
89
+ if (models) endpoints.modelsEndpoint = models
90
+ if (info) endpoints.modelInfoEndpoint = info
91
+ return endpoints
92
+ }
93
+
43
94
  /** Build a full URL for a given API endpoint. */
44
95
  export function buildAPIURL(baseURL: string, endpoint: string = MODELS_ENDPOINT): string {
45
96
  return `${normalizeBaseURL(baseURL)}${endpoint}`
@@ -64,20 +115,42 @@ export async function checkLiteLLMHealth(
64
115
  baseURL: string = DEFAULT_LITELLM_URL,
65
116
  apiKey?: string,
66
117
  customHeaders?: Record<string, string>,
118
+ endpoints: DiscoveryEndpoints = {},
119
+ signInCredential = false,
67
120
  ): Promise<boolean> {
68
- try {
69
- const response = await fetch(buildAPIURL(baseURL), {
70
- method: 'GET',
71
- headers: buildHeaders(apiKey, customHeaders),
72
- signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
73
- })
74
- // 401 still means a server is alive — we just don't have the right
75
- // credentials. Surface that as "unhealthy" so the user is prompted
76
- // to set LITELLM_API_KEY.
77
- return response.ok
78
- } catch {
121
+ const ping = async (url: string): Promise<{ ok: boolean; status?: number }> => {
122
+ try {
123
+ const response = await fetch(url, {
124
+ method: 'GET',
125
+ headers: buildHeaders(
126
+ credentialForTarget(url, baseURL, apiKey, signInCredential),
127
+ customHeaders,
128
+ ),
129
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
130
+ })
131
+ // 401 still means a server is alive — we just don't have the right
132
+ // credentials. Surface that as "unhealthy" so the user is prompted
133
+ // to set LITELLM_API_KEY.
134
+ return { ok: response.ok, status: response.status }
135
+ } catch {
136
+ return { ok: false }
137
+ }
138
+ }
139
+ const modelsURL = buildAPIURL(baseURL, endpoints.modelsEndpoint)
140
+ const models = await ping(modelsURL)
141
+ if (models.ok) return true
142
+ const fallbackURL = infoURL(baseURL, endpoints)
143
+ // The info endpoint only deserves a second request when the server answered
144
+ // the models probe but does not serve that path, or when a management host is
145
+ // configured. A network error or a rejected credential fails there too, and
146
+ // retrying would double the health budget (3 s per probe) on the offline path
147
+ // that startup and auto-detection walk.
148
+ const pathMissing =
149
+ models.status === 404 || models.status === 405 || models.status === 501
150
+ if (fallbackURL === modelsURL || (!pathMissing && !endpoints.managementBaseURL)) {
79
151
  return false
80
152
  }
153
+ return (await ping(fallbackURL)).ok
81
154
  }
82
155
 
83
156
  /** Discover all models exposed by a LiteLLM proxy. */
@@ -85,8 +158,9 @@ export async function discoverLiteLLMModels(
85
158
  baseURL: string = DEFAULT_LITELLM_URL,
86
159
  apiKey?: string,
87
160
  customHeaders?: Record<string, string>,
161
+ endpoints: DiscoveryEndpoints = {},
88
162
  ): Promise<LiteLLMModel[]> {
89
- const url = buildAPIURL(baseURL)
163
+ const url = buildAPIURL(baseURL, endpoints.modelsEndpoint)
90
164
  const response = await fetch(url, {
91
165
  method: 'GET',
92
166
  headers: buildHeaders(apiKey, customHeaders),
@@ -101,22 +175,53 @@ export async function discoverLiteLLMModels(
101
175
  return data.data ?? []
102
176
  }
103
177
 
178
+ function infoURL(baseURL: string, endpoints: DiscoveryEndpoints): string {
179
+ return buildAPIURL(
180
+ endpoints.managementBaseURL ?? baseURL,
181
+ endpoints.modelInfoEndpoint ?? MODEL_INFO_ENDPOINT,
182
+ )
183
+ }
184
+
185
+ /** Whether two URLs name the same scheme, host and port. */
186
+ export function sameOriginURL(a: string, b: string): boolean {
187
+ try {
188
+ return new URL(a).origin === new URL(b).origin
189
+ } catch {
190
+ return false
191
+ }
192
+ }
193
+
104
194
  /**
105
- * Fetch per-model metadata (`mode`, token limits, capability flags and the
106
- * optional `display_name`) from `/v1/model/info`, keyed by model name.
107
- * `/v1/models` omits these fields for database-defined models, so
108
- * classification (e.g. filtering out embedding models) relies on this
109
- * endpoint.
195
+ * The credential to attach to `url`. A LiteLLM sign-in's access token is
196
+ * bound to the proxy that issued it, so it is withheld from a management host
197
+ * on another origin rather than handed to a server that never issued it. An
198
+ * API key is the operator's own and keeps going wherever they pointed it.
110
199
  */
111
- export async function discoverLiteLLMModelInfo(
200
+ function credentialForTarget(
201
+ url: string,
202
+ baseURL: string,
203
+ apiKey: string | undefined,
204
+ signInCredential: boolean,
205
+ ): string | undefined {
206
+ if (!signInCredential) return apiKey
207
+ return sameOriginURL(url, normalizeBaseURL(baseURL)) ? apiKey : undefined
208
+ }
209
+
210
+ /** Fetch the raw `/v1/model/info` entries from the management host (or `baseURL`). */
211
+ export async function fetchLiteLLMModelInfoEntries(
112
212
  baseURL: string = DEFAULT_LITELLM_URL,
113
213
  apiKey?: string,
114
214
  customHeaders?: Record<string, string>,
115
- ): Promise<Map<string, LiteLLMModelInfo>> {
116
- const url = buildAPIURL(baseURL, MODEL_INFO_ENDPOINT)
215
+ endpoints: DiscoveryEndpoints = {},
216
+ signInCredential = false,
217
+ ): Promise<LiteLLMModelInfoEntry[]> {
218
+ const url = infoURL(baseURL, endpoints)
117
219
  const response = await fetch(url, {
118
220
  method: 'GET',
119
- headers: buildHeaders(apiKey, customHeaders),
221
+ headers: buildHeaders(
222
+ credentialForTarget(url, baseURL, apiKey, signInCredential),
223
+ customHeaders,
224
+ ),
120
225
  signal: AbortSignal.timeout(getRequestTimeoutMs()),
121
226
  })
122
227
 
@@ -125,8 +230,34 @@ export async function discoverLiteLLMModelInfo(
125
230
  }
126
231
 
127
232
  const data = (await response.json()) as LiteLLMModelInfoResponse
233
+ return data.data ?? []
234
+ }
235
+
236
+ /**
237
+ * Build a model list from `/v1/model/info` entries, for proxies whose models
238
+ * endpoint is unusable. Duplicate `model_name`s (several deployments behind
239
+ * one name) collapse to the first entry.
240
+ */
241
+ export function modelsFromInfoEntries(entries: LiteLLMModelInfoEntry[]): LiteLLMModel[] {
242
+ const models = new Map<string, LiteLLMModel>()
243
+ for (const entry of entries) {
244
+ if (!entry.model_name || models.has(entry.model_name)) continue
245
+ const info = entry.model_info
246
+ models.set(entry.model_name, {
247
+ id: entry.model_name,
248
+ object: 'model',
249
+ ...(info?.mode !== undefined ? { mode: info.mode } : {}),
250
+ ...(info?.max_input_tokens !== undefined ? { max_input_tokens: info.max_input_tokens } : {}),
251
+ ...(info?.max_output_tokens !== undefined ? { max_output_tokens: info.max_output_tokens } : {}),
252
+ })
253
+ }
254
+ return [...models.values()]
255
+ }
256
+
257
+ /** Index `/v1/model/info` entries by every alias LiteLLM may use for a model. */
258
+ export function buildModelInfoMap(entries: LiteLLMModelInfoEntry[]): Map<string, LiteLLMModelInfo> {
128
259
  const infoByName = new Map<string, LiteLLMModelInfo>()
129
- for (const entry of data.data ?? []) {
260
+ for (const entry of entries) {
130
261
  if (!entry.model_info) continue
131
262
  // Some deployments set capability flags on the params block rather
132
263
  // than inside model_info. Fill those gaps so enrichment sees them.
@@ -157,6 +288,25 @@ export async function discoverLiteLLMModelInfo(
157
288
  return infoByName
158
289
  }
159
290
 
291
+ /**
292
+ * Fetch per-model metadata (`mode`, token limits, capability flags and the
293
+ * optional `display_name`) from `/v1/model/info`, keyed by model name.
294
+ * `/v1/models` omits these fields for database-defined models, so
295
+ * classification (e.g. filtering out embedding models) relies on this
296
+ * endpoint.
297
+ */
298
+ export async function discoverLiteLLMModelInfo(
299
+ baseURL: string = DEFAULT_LITELLM_URL,
300
+ apiKey?: string,
301
+ customHeaders?: Record<string, string>,
302
+ endpoints: DiscoveryEndpoints = {},
303
+ signInCredential = false,
304
+ ): Promise<Map<string, LiteLLMModelInfo>> {
305
+ return buildModelInfoMap(
306
+ await fetchLiteLLMModelInfoEntries(baseURL, apiKey, customHeaders, endpoints, signInCredential),
307
+ )
308
+ }
309
+
160
310
  /**
161
311
  * Use an explicit LITELLM_BASE_URL when set; otherwise try `ports` on localhost,
162
312
  * by default the most common ones. The default `litellm --port` is 4000, with
@@ -3,6 +3,7 @@ import { readFileSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node
3
3
  import { homedir, tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
5
  import { normalizeModelDisplayName, type ModelNaming } from './format-model-name'
6
+ import type { DiscoveryEndpoints } from './litellm-api'
6
7
 
7
8
  /**
8
9
  * Facts about a discovered model's upstream that OpenCode 2 turns into
@@ -116,6 +117,9 @@ function canonicalize(value: unknown): string {
116
117
  * `providerName` only matters when a template is set: `{provider_name}`
117
118
  * resolves to it, so renaming a provider must start a fresh discovery too.
118
119
  * The provider id is already part of the base key.
120
+ *
121
+ * A custom management host or endpoint path changes where model info comes
122
+ * from, so it joins the fingerprint too; defaults add nothing.
119
123
  */
120
124
  export function buildCacheKey(
121
125
  providerId: string,
@@ -124,6 +128,7 @@ export function buildCacheKey(
124
128
  capabilities: Record<string, Record<string, boolean>>,
125
129
  naming: ModelNaming = {},
126
130
  credential?: string,
131
+ endpoints: DiscoveryEndpoints = {},
127
132
  ): string {
128
133
  let base = `${providerId}@${baseURL}`
129
134
  // The credential fingerprint: a short hash (never the raw key) so a
@@ -135,7 +140,9 @@ export function buildCacheKey(
135
140
  }
136
141
  const rawNames = naming.formatModelNames === false
137
142
  const template = naming.modelNameTemplate
143
+ const hasEndpoints = Object.keys(endpoints).length > 0
138
144
  const hasAdjustments =
145
+ hasEndpoints ||
139
146
  (filters.includeModels?.length ?? 0) > 0 ||
140
147
  (filters.excludeModels?.length ?? 0) > 0 ||
141
148
  Object.keys(capabilities).length > 0 ||
@@ -159,6 +166,7 @@ export function buildCacheKey(
159
166
  excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
160
167
  capabilities,
161
168
  ...namingFingerprint,
169
+ ...(hasEndpoints ? { endpoints } : {}),
162
170
  }),
163
171
  )
164
172
  .digest('hex')