opencode-plugin-litellm 1.7.0 → 1.7.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
@@ -78,7 +78,7 @@ also shows how to configure a provider directly in `opencode.json`.
78
78
  | 💵 **Real pricing** | Maps `input_cost_per_token` / `output_cost_per_token` (and cache read/write costs) from `/v1/model/info` into OpenCode's `cost` field, so the picker and `/cost` show what the proxy actually bills instead of `$0.00`. Models LiteLLM has no price for are left unpriced, not falsely marked free. |
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
- | 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, `providers.litellm.settings.apiKey`, OpenCode `/connect` credentials, and (OpenCode 2) a **LiteLLM** entry in the connect-provider dialog — key plus optional base URL, entered entirely from the web UI. |
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
82
  | 🌐 **Gateway-friendly** | Supports provider `headers` (and the legacy `customHeaders` option) for proxies behind Cloudflare Access or other API gateways. |
83
83
  | 🧩 **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
84
  | 🎚️ **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. |
@@ -332,7 +332,7 @@ If your LiteLLM proxy requires a master key, expose it via any of these approach
332
332
  | Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
333
333
  | Config | `"settings": { "apiKey": "{env:LITELLM_API_KEY}" }` |
334
334
 
335
- The env var path lets you commit `opencode.json` without leaking secrets. On OpenCode 1, `/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 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. OpenCode 2 users can still use `settings.apiKey` with an environment substitution or set `LITELLM_API_KEY` on the background service as shown in the Quickstart.
335
+ 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
336
 
337
337
  #### Web UI connect (OpenCode 2)
338
338
 
@@ -342,7 +342,9 @@ With no configuration at all, `/connect` → **LiteLLM** is enough:
342
342
  2. Optionally fill the form: **Base URL** (e.g. `https://llm.example.com/v1`) and **Provider ID** (defaults to `litellm`; pick a different id when your config already defines a `litellm` provider, so the connected gateway gets its own entry). Reconnecting with a different id moves the gateway to that provider.
343
343
  3. Models appear in the picker without editing `opencode.json` or restarting.
344
344
 
345
- Precedence when several sources are configured: explicit provider/plugin settings always win. For the key, the environment (`LITELLM_API_KEY`/`LITELLM_MASTER_KEY`) is consulted before the dialog credential; 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.
345
+ 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
+
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.
346
348
 
347
349
  ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
348
350
 
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.7.0",
4
+ "version": "1.7.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",
@@ -13,8 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "typecheck": "tsc --noEmit",
16
- "test": "vitest run",
17
- "prepublishOnly": "npm run typecheck"
16
+ "test": "vitest run"
18
17
  },
19
18
  "keywords": [
20
19
  "opencode",
@@ -761,9 +761,14 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
761
761
  the plugin reads the stored key here and applies it to both its own
762
762
  discovery fetches and the completion-time provider options. Without it,
763
763
  a key-only proxy would fail discovery even though chat works.
764
+
765
+ Precedence rule: the stored credential — the user's explicit
766
+ choice made in the box — wins over the pod environment. The env is a
767
+ box-level fallback for users who have not saved a credential — never an
768
+ override of a user's saved key.
764
769
  */
765
770
  const storedKey = await getOpenCodeStoredApiKey(providerId)
766
- const apiKey = configuredKey ?? envKey ?? storedKey
771
+ const apiKey = configuredKey ?? storedKey ?? envKey
767
772
  // Native `options.headers` and the legacy `customHeaders` both reach
768
773
  // discovery and the runtime, so a gateway that only sets one still
769
774
  // authenticates the plugin's own fetches.
@@ -829,9 +834,12 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
829
834
  // Identity includes the filter/capability/naming config: those
830
835
  // are baked into cached entries, so changing them must start a
831
836
  // fresh discovery instead of serving the old adjusted view.
837
+ // The cache key is isolated by the effective credential (a fingerprint,
838
+ // never the raw key): a credential change starts a fresh discovery
839
+ // instead of serving another credential's cached model list.
832
840
  const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities, {
833
841
  formatModelNames,
834
- })
842
+ }, apiKey)
835
843
 
836
844
  // Remember how to reach this proxy so the `event` hook can
837
845
  // revalidate its cache in the background on new sessions.
package/src/plugin/v2.ts CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  writeModelCache,
26
26
  } from '../utils/model-cache'
27
27
  import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
28
+ import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
28
29
  import { parseModelCapabilities } from '../utils/model-capabilities'
29
30
  import type { ModelCapabilities } from '../utils/model-capabilities'
30
31
  import {
@@ -341,20 +342,25 @@ async function makeProviderSource(
341
342
  CHAT_PROVIDER_ID
342
343
  const configuredBaseURL = readString(settings.baseURL)
343
344
  const connectedApiKey = connected?.apiKey
344
- const configuredApiKey =
345
- readString(providerSettings.apiKey) ??
346
- readString(pluginOptions.apiKey) ??
347
- process.env.LITELLM_API_KEY ??
348
- process.env.LITELLM_MASTER_KEY
349
- // A provider bound to an integration relies on OpenCode for its credential
350
- // even before one is connected. The plugin's own integration only counts
351
- // once it actually resolved a key, so env/config setups are unaffected.
352
- const usesConnectionCredential =
353
- !configuredApiKey && Boolean(provider?.integrationID ?? connectedApiKey)
345
+ // Precedence rule: an explicit settings/plugin-options apiKey is the
346
+ // operator's deliberate config and stays first; then a credential the user
347
+ // saved in the box — the ACTIVE connection or the `/connect` entry in the
348
+ // box auth store — which wins over the pod environment. The env is a
349
+ // box-level fallback for users who have not saved a credential, never an
350
+ // override of the user's explicit choice.
351
+ const settingsApiKey = readString(providerSettings.apiKey) ?? readString(pluginOptions.apiKey)
352
+ const envApiKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
353
+ // The key OpenCode itself stored for this provider in the box auth store
354
+ // (/connect journey). A config-defined provider carries no integrationID, so
355
+ // the host-integration path above cannot see it — read the store directly,
356
+ // exactly like the v1 entrypoint does. Still ahead of the env: a saved
357
+ // credential is the user's explicit choice and beats the box-level fallback.
358
+ const storedKey = await getOpenCodeStoredApiKey(id)
359
+ const usesConnectionCredential = settingsApiKey === undefined && connectedApiKey !== undefined
354
360
  const integrationID =
355
361
  provider?.integrationID ??
356
- (usesConnectionCredential && connectedApiKey ? LITELLM_INTEGRATION_ID : undefined)
357
- const apiKey = configuredApiKey ?? connectedApiKey
362
+ (usesConnectionCredential ? LITELLM_INTEGRATION_ID : undefined)
363
+ const apiKey = settingsApiKey ?? connectedApiKey ?? storedKey ?? envApiKey
358
364
  const filters = readModelFilters(settings)
359
365
  const capabilities = parseModelCapabilities(settings.modelCapabilities)
360
366
  const compatibility = parseModelCompatibility(settings.modelCompatibility)
@@ -372,9 +378,12 @@ async function makeProviderSource(
372
378
  }
373
379
 
374
380
  const baseURL = normalizeBaseURL(detectedBaseURL)
381
+ // The cache key is isolated by the effective credential (a fingerprint, never
382
+ // the raw key): a credential change starts a fresh discovery instead of
383
+ // serving another credential's cached model list.
375
384
  const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
376
385
  formatModelNames,
377
- })
386
+ }, apiKey)
378
387
  const cacheEntry = readModelCacheEntry(cacheKey)
379
388
  let entries = cacheEntry?.models ?? null
380
389
  let responsesIds = cacheEntry?.responsesIds ?? []
@@ -531,16 +540,40 @@ async function refreshConnectionCredential(
531
540
  context: Context,
532
541
  source: ProviderSource,
533
542
  ): Promise<boolean> {
534
- if (!source.integrationID || !source.usesConnectionCredential) return false
543
+ // The gate is the integration's presence, not the current credential choice:
544
+ // setup may run before the user saves a credential, and the first save must
545
+ // refresh this source instead of leaving it on the environment key.
546
+ if (!source.integrationID) return false
535
547
 
536
548
  try {
537
549
  const connection = await context.integration.connection.active(source.integrationID)
538
550
  const credential = connection
539
551
  ? await context.integration.connection.resolve(connection)
540
552
  : undefined
541
- const apiKey = credential?.type === 'key' ? credential.key : undefined
542
- if (apiKey === source.apiKey) return false
543
- source.apiKey = apiKey
553
+ const connectionKey = credential?.type === 'key' ? credential.key : undefined
554
+ const settingsApiKey = readString(source.settings.apiKey)
555
+ let nextKey: string | undefined
556
+ let nextUsesConnection: boolean
557
+ if (connectionKey !== undefined) {
558
+ // An explicit settings apiKey stays first; a connection credential takes
559
+ // over the environment/auto-detected key.
560
+ nextKey = settingsApiKey ?? connectionKey
561
+ nextUsesConnection = settingsApiKey === undefined
562
+ } else {
563
+ // The connection credential is gone (the connection was removed or its
564
+ // credential cleared): fall back through the stored credential / env key
565
+ // — the same precedence `makeProviderSource` uses — instead of retaining
566
+ // the previous connection key, which `runtimeSettings` would otherwise
567
+ // materialize into provider settings.
568
+ const storedKey = await getOpenCodeStoredApiKey(source.id)
569
+ const envKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
570
+ nextKey = settingsApiKey ?? storedKey ?? envKey
571
+ nextUsesConnection = false
572
+ }
573
+ if (nextKey === source.apiKey && nextUsesConnection === source.usesConnectionCredential) return false
574
+ source.apiKey = nextKey
575
+ source.usesConnectionCredential = nextUsesConnection
576
+ source.credentialReloadRequired = true
544
577
  return true
545
578
  } catch (error) {
546
579
  const message = error instanceof Error ? error.message : String(error)
@@ -111,8 +111,16 @@ export function buildCacheKey(
111
111
  filters: { includeModels?: string[]; excludeModels?: string[] },
112
112
  capabilities: Record<string, Record<string, boolean>>,
113
113
  naming: { formatModelNames?: boolean } = {},
114
+ credential?: string,
114
115
  ): string {
115
- const base = `${providerId}@${baseURL}`
116
+ let base = `${providerId}@${baseURL}`
117
+ // The credential fingerprint: a short hash (never the raw key) so a
118
+ // credential change isolates the cached model list — a key that exposes a
119
+ // different set of models must start a fresh discovery instead of serving
120
+ // another credential's entries.
121
+ if (credential) {
122
+ base += `@${createHash('sha256').update(credential).digest('hex').slice(0, 12)}`
123
+ }
116
124
  const rawNames = naming.formatModelNames === false
117
125
  const hasAdjustments =
118
126
  (filters.includeModels?.length ?? 0) > 0 ||