opencode-plugin-litellm 1.11.0 → 1.12.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
@@ -18,13 +18,16 @@
18
18
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](./LICENSE)
19
19
  [![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178c6?style=flat-square&logo=typescript&logoColor=white)](./tsconfig.json)
20
20
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen?style=flat-square)](./CONTRIBUTING.md)
21
+ [![Sponsor](https://img.shields.io/badge/sponsor-GitHub%20Sponsors-ea4aaa?style=flat-square&logo=githubsponsors&logoColor=white)](https://github.com/sponsors/yuseferi)
21
22
 
22
23
  Auto-detect a running LiteLLM proxy, pull every model from `/v1/models`, and register them in OpenCode.
23
24
  **No model lists to hand-maintain. No restart loops. No surprises.**
24
25
 
25
26
  <img src="https://raw.githubusercontent.com/yuseferi/opencode-litellm/main/assets/architecture.svg" alt="How opencode-litellm works: OpenCode registers discovered LiteLLM models through the provider API and refreshes its provider registry from a disk cache" width="100%" />
26
27
 
27
- [Quickstart](#-quickstart) · [Configuration](#%EF%B8%8F-configuration) · [How it works](#-how-it-works) · [FAQ](#-faq) · [Contributing](./CONTRIBUTING.md)
28
+ [Quickstart](#-quickstart) · [Configuration](#%EF%B8%8F-configuration) · [How it works](#-how-it-works) · [FAQ](#-faq) · [Contributing](./CONTRIBUTING.md) · [Sponsor](#-sponsor)
29
+
30
+ **Enjoying the plugin? [⭐ Star the repo](https://github.com/yuseferi/opencode-litellm)** — stars are how other OpenCode users find it.
28
31
 
29
32
  </div>
30
33
 
@@ -46,9 +49,9 @@ Maintaining a `models` block in `opencode.json` for every model your LiteLLM pro
46
49
 
47
50
  ## 🚀 Quickstart
48
51
 
49
- After a V2-compatible release is published, install the plugin from the CLI
50
- and configure the shared background service. If your OpenCode 2 executable is
51
- named `opencode2`, use it in place of `opencode` below.
52
+ Install the plugin from the CLI and configure the shared background service.
53
+ If your OpenCode 2 executable is named `opencode2`, use it in place of
54
+ `opencode` below.
52
55
 
53
56
  ```bash
54
57
  opencode plugin add opencode-plugin-litellm
@@ -58,10 +61,6 @@ opencode service set env LITELLM_API_KEY YOUR_API_KEY
58
61
 
59
62
  Then open OpenCode and select a discovered model under `litellm/...`.
60
63
 
61
- > **RFC status:** OpenCode 2 support is not yet included in the published npm
62
- > package. For now, `plugin add` installs the previous release, not this RFC
63
- > implementation.
64
-
65
64
  For a local LiteLLM proxy on port 4000, the base URL can be omitted and the
66
65
  plugin will detect it automatically. The [configuration section](#%EF%B8%8F-configuration)
67
66
  also shows how to configure a provider directly in `opencode.json`.
@@ -334,7 +333,7 @@ If your LiteLLM proxy requires a master key, expose it via any of these approach
334
333
  | Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
335
334
  | Config | `"settings": { "apiKey": "{env:LITELLM_API_KEY}" }` |
336
335
 
337
- The env var path lets you commit `opencode.json` without leaking secrets. `/connect` credentials are read from OpenCode's auth store (`~/.local/share/opencode/auth.json`) and applied to health checks, model discovery, and completion-time requests on BOTH OpenCode 1 and OpenCode 2. On OpenCode 2, a credential saved through `/connect` is a first-class integration connection: the plugin registers the **LiteLLM** integration with an API-key form, uses the stored key for discovery, and lets OpenCode inject it into completion requests — the key never appears in `opencode.json` or provider settings. A credential the user saves in the box (the active connection or the auth-store entry) wins over `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`; the environment is a box-level fallback, never an override of a saved key.
336
+ The env var path lets you commit `opencode.json` without leaking secrets. `/connect` credentials are read from wherever OpenCode keeps them — the provider's connection on OpenCode 2, and OpenCode's auth store (`~/.local/share/opencode/auth.json`) on OpenCode 1 and on 2.x boxes that still write it — and applied to health checks, model discovery, and completion-time requests on BOTH OpenCode 1 and OpenCode 2. On OpenCode 2, a credential saved through `/connect` is a first-class integration connection: the plugin registers the **LiteLLM** integration with an API-key form, uses the stored key for discovery, and lets OpenCode inject it into completion requests — the key never appears in `opencode.json` or provider settings. A config-defined provider keeps its key on an integration named after its own id, so a `litellm-team-a` provider uses the key connected for `litellm-team-a` and falls back to the plugin's `litellm` integration only when that one has no connection. A credential the user saves in the box (the active connection or the auth-store entry) wins over `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`; the environment is a box-level fallback, never an override of a saved key.
338
337
 
339
338
  #### Web UI connect (OpenCode 2)
340
339
 
@@ -410,6 +409,35 @@ If your LiteLLM proxy is behind Cloudflare Access or another gateway that requir
410
409
 
411
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/).
412
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
+ - Changing any of these starts a fresh discovery on the next start.
440
+
413
441
  ### Splitting one proxy into multiple providers (`includeModels` / `excludeModels`)
414
442
 
415
443
  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:
@@ -790,6 +818,16 @@ See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full contributor workflow.
790
818
 
791
819
  Have an idea? [Open an issue](https://github.com/yuseferi/opencode-litellm/issues/new).
792
820
 
821
+ ## 💖 Sponsor
822
+
823
+ This plugin is free, MIT-licensed, and stays that way. If it saves you time, you can
824
+ support its maintenance through **[GitHub Sponsors](https://github.com/sponsors/yuseferi)** —
825
+ one-off or recurring, cancel anytime.
826
+
827
+ [![Sponsor yuseferi on GitHub Sponsors](https://img.shields.io/badge/sponsor-GitHub%20Sponsors-ea4aaa?style=flat-square&logo=githubsponsors&logoColor=white)](https://github.com/sponsors/yuseferi)
828
+
829
+ Not in a position to sponsor? A bug report or a PR helps just as much.
830
+
793
831
  ## 🙏 Acknowledgements
794
832
 
795
833
  Inspired by [`opencode-lmstudio`](https://github.com/agustif/opencode-lmstudio) by [@agustif](https://github.com/agustif) — the architectural blueprint for OpenCode model-discovery plugins.
@@ -799,11 +837,3 @@ Built on top of [LiteLLM](https://github.com/BerriAI/litellm) by the [BerriAI](h
799
837
  ## 📄 License
800
838
 
801
839
  [MIT](./LICENSE) © [Yusef Mohamadi](https://github.com/yuseferi)
802
-
803
- ---
804
-
805
- <div align="center">
806
-
807
- If this project saved you time, consider giving it a ⭐ on [GitHub](https://github.com/yuseferi/opencode-litellm).
808
-
809
- </div>
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.0",
4
+ "version": "1.12.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",
@@ -33,6 +33,10 @@
33
33
  "url": "https://github.com/yuseferi/opencode-litellm/issues"
34
34
  },
35
35
  "homepage": "https://github.com/yuseferi/opencode-litellm#readme",
36
+ "funding": {
37
+ "type": "github",
38
+ "url": "https://github.com/sponsors/yuseferi"
39
+ },
36
40
  "publishConfig": {
37
41
  "access": "public",
38
42
  "provenance": true
@@ -1,11 +1,15 @@
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
+ type DiscoveryEndpoints,
9
13
  } from '../utils/litellm-api'
10
14
  import {
11
15
  applyModelNameTemplate,
@@ -121,6 +125,7 @@ interface RefreshContext {
121
125
  modelNameTemplate?: string
122
126
  providerName: string
123
127
  providerId: string
128
+ endpoints: DiscoveryEndpoints
124
129
  }
125
130
  const refreshContexts = new Map<string, RefreshContext>()
126
131
 
@@ -455,8 +460,9 @@ export async function discoverModels(
455
460
  filters: ModelFilters = {},
456
461
  capabilities: ModelCapabilities = {},
457
462
  naming: ModelNaming = {},
463
+ endpoints: DiscoveryEndpoints = {},
458
464
  ): Promise<DiscoveredModels | null> {
459
- if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
465
+ if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders, endpoints))) {
460
466
  log(
461
467
  'warn',
462
468
  `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
@@ -469,11 +475,24 @@ export async function discoverModels(
469
475
  // it. The info call is best-effort: without it, classification
470
476
  // falls back to id heuristics.
471
477
  const [modelsResult, infoResult] = await Promise.allSettled([
472
- discoverLiteLLMModels(baseURL, apiKey, customHeaders),
473
- discoverLiteLLMModelInfo(baseURL, apiKey, customHeaders),
478
+ discoverLiteLLMModels(baseURL, apiKey, customHeaders, endpoints),
479
+ fetchLiteLLMModelInfoEntries(baseURL, apiKey, customHeaders, endpoints),
474
480
  ])
475
481
 
476
- if (modelsResult.status === 'rejected') {
482
+ let discovered: LiteLLMModel[]
483
+ if (modelsResult.status === 'fulfilled') {
484
+ discovered = modelsResult.value
485
+ } else if (infoResult.status === 'fulfilled' && infoResult.value.length > 0) {
486
+ // No usable models endpoint: the info response still names every model.
487
+ const error = modelsResult.reason
488
+ log(
489
+ 'warn',
490
+ `[opencode-litellm] Models endpoint failed for provider "${providerId}" (` +
491
+ (error instanceof Error ? error.message : String(error)) +
492
+ '); building the model list from the model info endpoint.',
493
+ )
494
+ discovered = modelsFromInfoEntries(infoResult.value)
495
+ } else {
477
496
  const error = modelsResult.reason
478
497
  log(
479
498
  'warn',
@@ -483,15 +502,14 @@ export async function discoverModels(
483
502
  return null
484
503
  }
485
504
 
486
- const discovered = modelsResult.value
487
505
  let infoByName: Map<string, LiteLLMModelInfo> | null = null
488
506
  if (infoResult.status === 'fulfilled') {
489
- infoByName = infoResult.value
507
+ infoByName = buildModelInfoMap(infoResult.value)
490
508
  } else {
491
509
  const reason = infoResult.reason
492
510
  log(
493
511
  'warn',
494
- `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only: ` +
512
+ `[opencode-litellm] Model info endpoint unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only: ` +
495
513
  (reason instanceof Error ? reason.message : String(reason)),
496
514
  )
497
515
  }
@@ -850,6 +868,7 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
850
868
  providerId: ctx.providerId,
851
869
  providerName: ctx.providerName,
852
870
  },
871
+ ctx.endpoints,
853
872
  ),
854
873
  DISCOVERY_TIMEOUT_MS,
855
874
  )
@@ -1019,6 +1038,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1019
1038
  const providerName =
1020
1039
  typeof provider.name === 'string' && provider.name ? provider.name : providerId
1021
1040
  const naming = { formatModelNames, modelNameTemplate, providerId, providerName }
1041
+ const endpoints = readDiscoveryEndpoints(options)
1022
1042
 
1023
1043
  // Resolve base URL
1024
1044
  let baseURL: string | null = null
@@ -1095,7 +1115,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1095
1115
  formatModelNames,
1096
1116
  modelNameTemplate,
1097
1117
  providerName,
1098
- }, sso ? ssoIdentity(sso) : apiKey)
1118
+ }, sso ? ssoIdentity(sso) : apiKey, endpoints)
1099
1119
 
1100
1120
  // Remember how to reach this proxy so the `event` hook can
1101
1121
  // revalidate its cache in the background on new sessions.
@@ -1114,6 +1134,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1114
1134
  modelNameTemplate,
1115
1135
  providerName,
1116
1136
  providerId,
1137
+ endpoints,
1117
1138
  })
1118
1139
 
1119
1140
  // The Responses sibling (if any) holds a disjoint set of ids, so the
@@ -1182,6 +1203,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1182
1203
  filters,
1183
1204
  capabilities,
1184
1205
  { formatModelNames, modelNameTemplate, providerId, providerName },
1206
+ endpoints,
1185
1207
  ),
1186
1208
  DISCOVERY_TIMEOUT_MS,
1187
1209
  )
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'
@@ -112,6 +117,7 @@ interface ProviderSource {
112
117
  formatModelNames: boolean
113
118
  modelNameTemplate?: string
114
119
  providerName: string
120
+ endpoints: DiscoveryEndpoints
115
121
  cacheKey: string
116
122
  models: Model.Info[]
117
123
  /**
@@ -472,6 +478,9 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
472
478
  'modelCompatibility',
473
479
  'formatModelNames',
474
480
  'modelNameTemplate',
481
+ 'managementBaseURL',
482
+ 'modelsEndpoint',
483
+ 'modelInfoEndpoint',
475
484
  'providerID',
476
485
  ]) {
477
486
  delete settings[key]
@@ -533,23 +542,43 @@ async function makeProviderSource(
533
542
  const settings = { ...pluginOptions, ...providerSettings }
534
543
  const customHeaders = providerHeaders(pluginOptions, settings, provider)
535
544
  const configuredBaseURL = readString(settings.baseURL)
536
- // Credential plus dialog form answers. A provider wired to its own
537
- // integration keeps using exactly that one; otherwise the plugin's
538
- // registered integration is consulted, so a gateway can be connected
539
- // entirely from the web UI with no hand-written config.
540
- let connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
541
- context,
542
- provider?.integrationID ?? LITELLM_INTEGRATION_ID,
543
- )
544
- // A base URL configured for another proxy turns the sign-in off.
545
- if (connected?.credentialID && !signInReaches(connected.baseURL, configuredBaseURL)) {
546
- connected = undefined
545
+ // Credential plus dialog form answers. Which integration to read depends on
546
+ // how the provider got here:
547
+ // 1. a provider wired to its own integration keeps using exactly that one;
548
+ // 2. a config-defined provider owns no integrationID, but `/connect` files
549
+ // its key under an integration named after the provider id — so for
550
+ // `litellm-a` the key lives in `litellm-a`, not in `litellm`;
551
+ // 3. the plugin's registered integration is the fallback, so a gateway can
552
+ // be connected entirely from the web UI with no hand-written config.
553
+ const idHint = provider?.id ?? readString(pluginOptions.providerID)
554
+ const integrationCandidates: string[] = []
555
+ if (provider?.integrationID) {
556
+ // Explicitly linked: authoritative, never widened to another integration.
557
+ integrationCandidates.push(provider.integrationID)
558
+ } else {
559
+ if (idHint) integrationCandidates.push(idHint)
560
+ if (!integrationCandidates.includes(LITELLM_INTEGRATION_ID)) {
561
+ integrationCandidates.push(LITELLM_INTEGRATION_ID)
562
+ }
563
+ }
564
+ let connected: ConnectedLiteLLM | undefined
565
+ // The integration that actually supplied the credential. Recorded on the
566
+ // source so refresh and `credential.switched` re-read the same one.
567
+ let connectedIntegrationID: string | undefined
568
+ for (const candidateID of integrationCandidates) {
569
+ const candidate = await readConnectedConfig(context, candidateID)
570
+ // A base URL configured for another proxy turns the sign-in off.
571
+ if (
572
+ !candidate ||
573
+ (candidate.credentialID && !signInReaches(candidate.baseURL, configuredBaseURL))
574
+ ) {
575
+ continue
576
+ }
577
+ connected = candidate
578
+ connectedIntegrationID = candidateID
579
+ break
547
580
  }
548
- const id =
549
- provider?.id ??
550
- readString(pluginOptions.providerID) ??
551
- connected?.providerID ??
552
- CHAT_PROVIDER_ID
581
+ const id = idHint ?? connected?.providerID ?? CHAT_PROVIDER_ID
553
582
  const connectedApiKey = connected?.apiKey
554
583
  // Precedence rule: an explicit settings/plugin-options apiKey is the
555
584
  // operator's deliberate config and stays first; then a credential the user
@@ -559,16 +588,17 @@ async function makeProviderSource(
559
588
  // override of the user's explicit choice.
560
589
  const settingsApiKey = readString(providerSettings.apiKey) ?? readString(pluginOptions.apiKey)
561
590
  const envApiKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
562
- // The key OpenCode itself stored for this provider in the box auth store
563
- // (/connect journey). A config-defined provider carries no integrationID, so
564
- // the host-integration path above cannot see it — read the store directly,
565
- // exactly like the v1 entrypoint does. Still ahead of the env: a saved
566
- // credential is the user's explicit choice and beats the box-level fallback.
591
+ // The key OpenCode stored for this provider in the box auth store — the
592
+ // `/connect` journey on boxes that still keep `auth.json`. OpenCode 2.3 keeps
593
+ // credentials in its own database instead, so this is the legacy fallback;
594
+ // the connection read above is the current path. Still ahead of the env: a
595
+ // saved credential is the user's explicit choice and beats the box-level
596
+ // fallback.
567
597
  const storedKey = await getOpenCodeStoredApiKey(id)
568
598
  const usesConnectionCredential = settingsApiKey === undefined && connectedApiKey !== undefined
569
599
  const integrationID =
570
600
  provider?.integrationID ??
571
- (usesConnectionCredential ? LITELLM_INTEGRATION_ID : undefined)
601
+ (usesConnectionCredential ? connectedIntegrationID : undefined)
572
602
  const apiKey = settingsApiKey ?? connectedApiKey ?? storedKey ?? envApiKey
573
603
  const filters = readModelFilters(settings)
574
604
  const capabilities = parseModelCapabilities(settings.modelCapabilities)
@@ -580,6 +610,7 @@ async function makeProviderSource(
580
610
  // distinguishable.
581
611
  const providerName = provider?.name || id
582
612
  const naming = { formatModelNames, modelNameTemplate, providerId: id, providerName }
613
+ const endpoints = readDiscoveryEndpoints(settings)
583
614
  // Explicit config beats the URL typed into the dialog, which beats the
584
615
  // environment and local port probing.
585
616
  const detectedBaseURL = configuredBaseURL
@@ -603,7 +634,7 @@ async function makeProviderSource(
603
634
  // the raw key): a credential change starts a fresh discovery instead of
604
635
  // serving another credential's cached model list. A sign-in is keyed by its
605
636
  // credential id, because its access token rotates on every refresh.
606
- const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, naming, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey)
637
+ const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, naming, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey, endpoints)
607
638
  const cacheEntry = readModelCacheEntry(cacheKey)
608
639
  let entries = cacheEntry?.models ?? null
609
640
  let responsesIds = cacheEntry?.responsesIds ?? []
@@ -619,6 +650,7 @@ async function makeProviderSource(
619
650
  filters,
620
651
  capabilities,
621
652
  naming,
653
+ endpoints,
622
654
  ),
623
655
  DISCOVERY_TIMEOUT_MS,
624
656
  )
@@ -661,6 +693,7 @@ async function makeProviderSource(
661
693
  formatModelNames,
662
694
  modelNameTemplate,
663
695
  providerName,
696
+ endpoints,
664
697
  cacheKey,
665
698
  models: toProviderModels(id, entries ?? {}, {
666
699
  providerPackage,
@@ -728,6 +761,7 @@ async function refreshProviderSource(
728
761
  providerId: source.id,
729
762
  providerName: source.providerName,
730
763
  },
764
+ source.endpoints,
731
765
  ),
732
766
  DISCOVERY_TIMEOUT_MS,
733
767
  )
@@ -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,27 @@ export async function checkLiteLLMHealth(
64
115
  baseURL: string = DEFAULT_LITELLM_URL,
65
116
  apiKey?: string,
66
117
  customHeaders?: Record<string, string>,
118
+ endpoints: DiscoveryEndpoints = {},
67
119
  ): 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 {
79
- return false
120
+ const ping = async (url: string): Promise<boolean> => {
121
+ try {
122
+ const response = await fetch(url, {
123
+ method: 'GET',
124
+ headers: buildHeaders(apiKey, customHeaders),
125
+ signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
126
+ })
127
+ // 401 still means a server is alive — we just don't have the right
128
+ // credentials. Surface that as "unhealthy" so the user is prompted
129
+ // to set LITELLM_API_KEY.
130
+ return response.ok
131
+ } catch {
132
+ return false
133
+ }
80
134
  }
135
+ if (await ping(buildAPIURL(baseURL, endpoints.modelsEndpoint))) return true
136
+ // A proxy whose model host has no usable models endpoint can still be
137
+ // healthy on the management host.
138
+ return ping(infoURL(baseURL, endpoints))
81
139
  }
82
140
 
83
141
  /** Discover all models exposed by a LiteLLM proxy. */
@@ -85,8 +143,9 @@ export async function discoverLiteLLMModels(
85
143
  baseURL: string = DEFAULT_LITELLM_URL,
86
144
  apiKey?: string,
87
145
  customHeaders?: Record<string, string>,
146
+ endpoints: DiscoveryEndpoints = {},
88
147
  ): Promise<LiteLLMModel[]> {
89
- const url = buildAPIURL(baseURL)
148
+ const url = buildAPIURL(baseURL, endpoints.modelsEndpoint)
90
149
  const response = await fetch(url, {
91
150
  method: 'GET',
92
151
  headers: buildHeaders(apiKey, customHeaders),
@@ -101,20 +160,21 @@ export async function discoverLiteLLMModels(
101
160
  return data.data ?? []
102
161
  }
103
162
 
104
- /**
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.
110
- */
111
- export async function discoverLiteLLMModelInfo(
163
+ function infoURL(baseURL: string, endpoints: DiscoveryEndpoints): string {
164
+ return buildAPIURL(
165
+ endpoints.managementBaseURL ?? baseURL,
166
+ endpoints.modelInfoEndpoint ?? MODEL_INFO_ENDPOINT,
167
+ )
168
+ }
169
+
170
+ /** Fetch the raw `/v1/model/info` entries from the management host (or `baseURL`). */
171
+ export async function fetchLiteLLMModelInfoEntries(
112
172
  baseURL: string = DEFAULT_LITELLM_URL,
113
173
  apiKey?: string,
114
174
  customHeaders?: Record<string, string>,
115
- ): Promise<Map<string, LiteLLMModelInfo>> {
116
- const url = buildAPIURL(baseURL, MODEL_INFO_ENDPOINT)
117
- const response = await fetch(url, {
175
+ endpoints: DiscoveryEndpoints = {},
176
+ ): Promise<LiteLLMModelInfoEntry[]> {
177
+ const response = await fetch(infoURL(baseURL, endpoints), {
118
178
  method: 'GET',
119
179
  headers: buildHeaders(apiKey, customHeaders),
120
180
  signal: AbortSignal.timeout(getRequestTimeoutMs()),
@@ -125,8 +185,34 @@ export async function discoverLiteLLMModelInfo(
125
185
  }
126
186
 
127
187
  const data = (await response.json()) as LiteLLMModelInfoResponse
188
+ return data.data ?? []
189
+ }
190
+
191
+ /**
192
+ * Build a model list from `/v1/model/info` entries, for proxies whose models
193
+ * endpoint is unusable. Duplicate `model_name`s (several deployments behind
194
+ * one name) collapse to the first entry.
195
+ */
196
+ export function modelsFromInfoEntries(entries: LiteLLMModelInfoEntry[]): LiteLLMModel[] {
197
+ const models = new Map<string, LiteLLMModel>()
198
+ for (const entry of entries) {
199
+ if (!entry.model_name || models.has(entry.model_name)) continue
200
+ const info = entry.model_info
201
+ models.set(entry.model_name, {
202
+ id: entry.model_name,
203
+ object: 'model',
204
+ ...(info?.mode !== undefined ? { mode: info.mode } : {}),
205
+ ...(info?.max_input_tokens !== undefined ? { max_input_tokens: info.max_input_tokens } : {}),
206
+ ...(info?.max_output_tokens !== undefined ? { max_output_tokens: info.max_output_tokens } : {}),
207
+ })
208
+ }
209
+ return [...models.values()]
210
+ }
211
+
212
+ /** Index `/v1/model/info` entries by every alias LiteLLM may use for a model. */
213
+ export function buildModelInfoMap(entries: LiteLLMModelInfoEntry[]): Map<string, LiteLLMModelInfo> {
128
214
  const infoByName = new Map<string, LiteLLMModelInfo>()
129
- for (const entry of data.data ?? []) {
215
+ for (const entry of entries) {
130
216
  if (!entry.model_info) continue
131
217
  // Some deployments set capability flags on the params block rather
132
218
  // than inside model_info. Fill those gaps so enrichment sees them.
@@ -157,6 +243,22 @@ export async function discoverLiteLLMModelInfo(
157
243
  return infoByName
158
244
  }
159
245
 
246
+ /**
247
+ * Fetch per-model metadata (`mode`, token limits, capability flags and the
248
+ * optional `display_name`) from `/v1/model/info`, keyed by model name.
249
+ * `/v1/models` omits these fields for database-defined models, so
250
+ * classification (e.g. filtering out embedding models) relies on this
251
+ * endpoint.
252
+ */
253
+ export async function discoverLiteLLMModelInfo(
254
+ baseURL: string = DEFAULT_LITELLM_URL,
255
+ apiKey?: string,
256
+ customHeaders?: Record<string, string>,
257
+ endpoints: DiscoveryEndpoints = {},
258
+ ): Promise<Map<string, LiteLLMModelInfo>> {
259
+ return buildModelInfoMap(await fetchLiteLLMModelInfoEntries(baseURL, apiKey, customHeaders, endpoints))
260
+ }
261
+
160
262
  /**
161
263
  * Use an explicit LITELLM_BASE_URL when set; otherwise try `ports` on localhost,
162
264
  * 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')