opencode-plugin-litellm 1.6.1 → 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`, and OpenCode `/connect` credentials on the V1 server path. |
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. |
@@ -322,17 +322,29 @@ Selecting a Responses model on OpenCode 1 therefore means picking
322
322
 
323
323
  ### Authentication
324
324
 
325
- If your LiteLLM proxy requires a master key, expose it via either approach:
325
+ If your LiteLLM proxy requires a master key, expose it via any of these approaches:
326
326
 
327
327
  | Method | Example |
328
328
  |---|---|
329
+ | Web UI / `/connect` | Run `/connect` (or use the Desktop providers view), pick **LiteLLM**, paste the key, and optionally fill in the base URL and provider id |
329
330
  | Env var (base URL) | `LITELLM_BASE_URL=https://litellm.internal.example.com/v1` |
330
331
  | Env var | `export LITELLM_API_KEY=sk-...` |
331
332
  | Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
332
333
  | Config | `"settings": { "apiKey": "{env:LITELLM_API_KEY}" }` |
333
- | OpenCode `/connect` | Run `/connect`, search for your `litellm` provider entry, and paste the 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. OpenCode 2 users can 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
+
337
+ #### Web UI connect (OpenCode 2)
338
+
339
+ With no configuration at all, `/connect` → **LiteLLM** is enough:
340
+
341
+ 1. Enter the API key when prompted.
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
+ 3. Models appear in the picker without editing `opencode.json` or restarting.
344
+
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.
336
348
 
337
349
  ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
338
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.6.1",
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,9 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "typecheck": "tsc --noEmit",
16
- "test": "vitest run",
17
- "build": "npm run typecheck",
18
- "prepublishOnly": "npm run build"
16
+ "test": "vitest run"
19
17
  },
20
18
  "keywords": [
21
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.
@@ -0,0 +1,122 @@
1
+ import type { Context } from '@opencode/plugin/promise/plugin'
2
+
3
+ // OpenCode 2 exposes no log API through the plugin context (see
4
+ // initV2Logging); the host captures console output into its log files, so a
5
+ // plain console write with the `[opencode-litellm]` prefix is the house
6
+ // pattern for V2 modules (same as logInfo in plugin/v2.ts).
7
+ function logInfo(message: string): void {
8
+ console.log(message)
9
+ }
10
+
11
+ /**
12
+ * Integration id the plugin registers with OpenCode's connect-provider dialog.
13
+ *
14
+ * Deliberately identical to the default provider id (`CHAT_PROVIDER_ID` in
15
+ * `plugin/v2.ts`) so a credential saved through `/connect` lines up with the
16
+ * `litellm` provider without extra wiring; providers registered under other
17
+ * ids still resolve the same credential because the plugin stamps
18
+ * `info.integrationID` on them.
19
+ */
20
+ export const LITELLM_INTEGRATION_ID = 'litellm'
21
+
22
+ /** A credential saved through the connect dialog, with its form answers. */
23
+ export interface ConnectedLiteLLM {
24
+ /** Key resolved from the active connection's credential. */
25
+ apiKey: string | undefined
26
+ /** Base URL typed into the dialog's form, when present. */
27
+ baseURL: string | undefined
28
+ /** Provider id typed into the dialog's form, when present. */
29
+ providerID: string | undefined
30
+ }
31
+
32
+ function readAnswer(
33
+ configuration: Record<string, unknown> | undefined,
34
+ key: string,
35
+ ): string | undefined {
36
+ const value = configuration?.[key]
37
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
38
+ }
39
+
40
+ /**
41
+ * Registers the LiteLLM integration so gateways can be connected from the
42
+ * web UI instead of hand-edited config: the dialog collects the API key as a
43
+ * credential plus a small form for the proxy base URL and an optional
44
+ * provider id.
45
+ *
46
+ * Returns the transform registration, or undefined when the host has no
47
+ * integration API (OpenCode 1.18.x's embedded v2 host) or registration
48
+ * fails — model discovery must keep working without the dialog entry.
49
+ */
50
+ export async function registerLiteLLMIntegration(
51
+ context: Context,
52
+ ): Promise<{ dispose(): Promise<void> } | undefined> {
53
+ if (!context.integration?.transform) return undefined
54
+ try {
55
+ return await context.integration.transform((editor) => {
56
+ editor.update(LITELLM_INTEGRATION_ID, (integration) => {
57
+ integration.name = 'LiteLLM'
58
+ })
59
+ editor.method.update({
60
+ integrationID: LITELLM_INTEGRATION_ID,
61
+ method: {
62
+ type: 'key',
63
+ label: 'API Key',
64
+ form: [
65
+ {
66
+ key: 'baseURL',
67
+ type: 'string',
68
+ format: 'uri',
69
+ title: 'Base URL',
70
+ description:
71
+ 'Where the LiteLLM proxy runs, including the /v1 suffix. Leave empty to use LITELLM_BASE_URL or auto-detect a local proxy.',
72
+ placeholder: 'https://llm.example.com/v1',
73
+ },
74
+ {
75
+ key: 'providerID',
76
+ type: 'string',
77
+ title: 'Provider ID',
78
+ description:
79
+ 'Provider the discovered models appear under. 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 there.',
80
+ default: LITELLM_INTEGRATION_ID,
81
+ },
82
+ ],
83
+ },
84
+ })
85
+ })
86
+ } catch (error) {
87
+ const message = error instanceof Error ? error.message : String(error)
88
+ logInfo(`[opencode-litellm] Could not register the connect dialog integration: ${message}`)
89
+ return undefined
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Resolves the active credential for an integration into the values the
95
+ * plugin needs: the API key plus the dialog's form answers.
96
+ *
97
+ * Returns undefined when the integration has no connection, the credential
98
+ * is not a key, or the host lacks the connection API. Errors are swallowed
99
+ * on purpose — a missing or unrelated integration must never prevent other
100
+ * auth sources from working.
101
+ */
102
+ export async function readConnectedConfig(
103
+ context: Context,
104
+ integrationID: string,
105
+ ): Promise<ConnectedLiteLLM | undefined> {
106
+ const connection = context.integration?.connection
107
+ if (!connection) return undefined
108
+ try {
109
+ const active = await connection.active(integrationID)
110
+ if (!active) return undefined
111
+ const credential = await connection.resolve(active)
112
+ if (!credential || credential.type !== 'key') return undefined
113
+ const configuration = credential.configuration as Record<string, unknown> | undefined
114
+ return {
115
+ apiKey: credential.key,
116
+ baseURL: readAnswer(configuration, 'baseURL'),
117
+ providerID: readAnswer(configuration, 'providerID'),
118
+ }
119
+ } catch {
120
+ return undefined
121
+ }
122
+ }
package/src/plugin/v2.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Model, Plugin, Provider } from '@opencode/plugin'
1
+ import { Integration, Model, Plugin, Provider } from '@opencode/plugin'
2
2
  import type { Context } from '@opencode/plugin/promise/plugin'
3
3
  import type { PluginInput } from '@opencode-ai/plugin'
4
4
  import {
@@ -12,6 +12,12 @@ import {
12
12
  withTimeout,
13
13
  LiteLLMPlugin,
14
14
  } from './index'
15
+ import {
16
+ LITELLM_INTEGRATION_ID,
17
+ readConnectedConfig,
18
+ registerLiteLLMIntegration,
19
+ type ConnectedLiteLLM,
20
+ } from './integration'
15
21
  import {
16
22
  buildCacheKey,
17
23
  readModelCacheEntry,
@@ -19,6 +25,7 @@ import {
19
25
  writeModelCache,
20
26
  } from '../utils/model-cache'
21
27
  import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
28
+ import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
22
29
  import { parseModelCapabilities } from '../utils/model-capabilities'
23
30
  import type { ModelCapabilities } from '../utils/model-capabilities'
24
31
  import {
@@ -313,50 +320,70 @@ async function makeProviderSource(
313
320
  provider: ProviderInfo | undefined,
314
321
  pluginOptions: Record<string, unknown>,
315
322
  ): Promise<ProviderSource | null> {
316
- const id = provider?.id ?? readString(pluginOptions.providerID) ?? CHAT_PROVIDER_ID
317
323
  const providerSettings = asRecord(provider?.settings)
318
324
  const settings = { ...pluginOptions, ...providerSettings }
319
- const configuredBaseURL = readString(settings.baseURL)
320
325
  const customHeaders = {
321
326
  ...readHeaders(pluginOptions.customHeaders),
322
327
  ...readCustomHeaders(settings),
323
328
  ...readHeaders(provider?.headers),
324
329
  }
325
- let connectedApiKey: string | undefined
326
- if (provider?.integrationID) {
327
- try {
328
- const connection = await context.integration.connection.active(provider.integrationID)
329
- const credential = connection
330
- ? await context.integration.connection.resolve(connection)
331
- : undefined
332
- if (credential?.type === 'key') connectedApiKey = credential.key
333
- } catch {
334
- // A missing or unrelated integration does not prevent other auth sources.
335
- }
336
- }
337
- const configuredApiKey =
338
- readString(providerSettings.apiKey) ??
339
- readString(pluginOptions.apiKey) ??
340
- process.env.LITELLM_API_KEY ??
341
- process.env.LITELLM_MASTER_KEY
342
- const usesConnectionCredential = !configuredApiKey && Boolean(provider?.integrationID)
343
- const apiKey = configuredApiKey ?? connectedApiKey
330
+ // Credential plus dialog form answers. A provider wired to its own
331
+ // integration keeps using exactly that one; otherwise the plugin's
332
+ // registered integration is consulted, so a gateway can be connected
333
+ // entirely from the web UI with no hand-written config.
334
+ const connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
335
+ context,
336
+ provider?.integrationID ?? LITELLM_INTEGRATION_ID,
337
+ )
338
+ const id =
339
+ provider?.id ??
340
+ readString(pluginOptions.providerID) ??
341
+ connected?.providerID ??
342
+ CHAT_PROVIDER_ID
343
+ const configuredBaseURL = readString(settings.baseURL)
344
+ const connectedApiKey = connected?.apiKey
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
360
+ const integrationID =
361
+ provider?.integrationID ??
362
+ (usesConnectionCredential ? LITELLM_INTEGRATION_ID : undefined)
363
+ const apiKey = settingsApiKey ?? connectedApiKey ?? storedKey ?? envApiKey
344
364
  const filters = readModelFilters(settings)
345
365
  const capabilities = parseModelCapabilities(settings.modelCapabilities)
346
366
  const compatibility = parseModelCompatibility(settings.modelCompatibility)
347
367
  const formatModelNames = readFormatModelNames(settings)
368
+ // Explicit config beats the URL typed into the dialog, which beats the
369
+ // environment and local port probing.
348
370
  const detectedBaseURL = configuredBaseURL
349
371
  ? normalizeBaseURL(configuredBaseURL)
350
- : await autoDetectLiteLLM(apiKey, customHeaders)
372
+ : connected?.baseURL
373
+ ? normalizeBaseURL(connected.baseURL)
374
+ : await autoDetectLiteLLM(apiKey, customHeaders)
351
375
 
352
376
  if (!detectedBaseURL) {
353
377
  return null
354
378
  }
355
379
 
356
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.
357
384
  const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
358
385
  formatModelNames,
359
- })
386
+ }, apiKey)
360
387
  const cacheEntry = readModelCacheEntry(cacheKey)
361
388
  let entries = cacheEntry?.models ?? null
362
389
  let responsesIds = cacheEntry?.responsesIds ?? []
@@ -399,7 +426,7 @@ async function makeProviderSource(
399
426
  package: providerPackage,
400
427
  settings,
401
428
  headers: customHeaders,
402
- integrationID: provider?.integrationID,
429
+ integrationID,
403
430
  usesConnectionCredential,
404
431
  credentialReloadRequired: false,
405
432
  refreshRequired: false,
@@ -513,16 +540,40 @@ async function refreshConnectionCredential(
513
540
  context: Context,
514
541
  source: ProviderSource,
515
542
  ): Promise<boolean> {
516
- 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
517
547
 
518
548
  try {
519
549
  const connection = await context.integration.connection.active(source.integrationID)
520
550
  const credential = connection
521
551
  ? await context.integration.connection.resolve(connection)
522
552
  : undefined
523
- const apiKey = credential?.type === 'key' ? credential.key : undefined
524
- if (apiKey === source.apiKey) return false
525
- 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
526
577
  return true
527
578
  } catch (error) {
528
579
  const message = error instanceof Error ? error.message : String(error)
@@ -602,6 +653,62 @@ async function reconcileProviderSources(
602
653
  return changed
603
654
  }
604
655
 
656
+ /**
657
+ * Build and publish a source from the dialog's active credential.
658
+ *
659
+ * Called for the first connect with nothing bound yet, and to rebuild
660
+ * dialog-built sources after a credential switch — a reconnect may move the
661
+ * gateway to a new base URL or provider id, so those sources are re-derived
662
+ * wholesale instead of key-refreshed.
663
+ *
664
+ * An existing source for the same id is left untouched unless it is a pure
665
+ * auto-detection/dialog-built fallback (no explicit baseURL in
666
+ * options/config): a fallback only stands in until a real endpoint is
667
+ * known, so the dialog's answers take over from it. Explicit option/env
668
+ * baseURLs — and host-registered providers — keep winning and are never
669
+ * replaced. Replaced sources' owned model ids carry over so models the
670
+ * gateway no longer serves are dropped on the next merge, and sources
671
+ * replaced under a different id are dropped from `sources` and marked in
672
+ * `staleProviderIds` for removal from the provider registry.
673
+ */
674
+ async function publishConnectedSource(
675
+ context: Context,
676
+ pluginOptions: Record<string, unknown>,
677
+ sources: Map<string, ProviderSource>,
678
+ staleProviderIds: Set<string>,
679
+ replacing: ProviderSource[] = [],
680
+ ): Promise<void> {
681
+ try {
682
+ const source = await makeProviderSource(context, undefined, pluginOptions)
683
+ if (!source) return
684
+ const existing = sources.get(source.id)
685
+ if (existing && !(existing.fromFallback && !readString(existing.settings.baseURL))) return
686
+ const previous = existing ?? replacing.find((candidate) => candidate.id === source.id)
687
+ if (previous) source.ownedModelIds = new Set(previous.ownedModelIds)
688
+ for (const previousSource of replacing) {
689
+ if (previousSource.id === source.id) continue
690
+ const mapped = sources.get(previousSource.id)
691
+ if (mapped === previousSource) sources.delete(previousSource.id)
692
+ // Absent from the map means an earlier attempt already removed it but
693
+ // failed before reloading — still owed a registry removal. A different
694
+ // live source under the id (e.g. a host-registered provider took over)
695
+ // is left entirely alone.
696
+ if (mapped === previousSource || mapped === undefined) {
697
+ staleProviderIds.add(previousSource.id)
698
+ }
699
+ }
700
+ sources.set(source.id, source)
701
+ await context.provider.reload()
702
+ source.pendingPublication = false
703
+ logInfo(
704
+ `[opencode-litellm] Registered provider "${source.id}" from the connected LiteLLM credential.`,
705
+ )
706
+ } catch (error) {
707
+ const message = error instanceof Error ? error.message : String(error)
708
+ logInfo(`[opencode-litellm] Could not register the connected provider: ${message}`)
709
+ }
710
+ }
711
+
605
712
  const definition = Plugin.define({
606
713
  id: 'opencode-litellm',
607
714
  async setup(context) {
@@ -615,6 +722,14 @@ const definition = Plugin.define({
615
722
 
616
723
  const pluginOptions = asRecord(context.options)
617
724
  const sources = new Map<string, ProviderSource>()
725
+ // Providers the dialog replaced under a new id; the transform below
726
+ // removes them from the registry on the next reload.
727
+ const staleProviderIds = new Set<string>()
728
+
729
+ // Surface LiteLLM in the connect-provider dialog so gateways can be
730
+ // connected from the web UI. Purely additive: a host without the
731
+ // integration API, or a failed registration, keeps every other auth path.
732
+ const integrationRegistration = await registerLiteLLMIntegration(context)
618
733
 
619
734
  // First pass. On OpenCode 2 the host has not registered user-configured
620
735
  // providers yet, so this typically finds only built-ins; the event loop
@@ -633,12 +748,21 @@ const definition = Plugin.define({
633
748
  }
634
749
 
635
750
  const providerRegistration = await context.provider.transform((editor) => {
751
+ // Sources replaced under a different id leave their registry entries
752
+ // behind; drop them before publishing the current sources.
753
+ for (const id of staleProviderIds) editor.remove(id)
754
+ staleProviderIds.clear()
636
755
  for (const source of sources.values()) {
637
756
  const current = editor.get(source.id)
638
757
  if (current) {
639
758
  editor.update(source.id, (provider) => {
640
759
  provider.package = source.package
641
760
  provider.name = source.name
761
+ // Bind the provider to the integration its credential comes from,
762
+ // so OpenCode keeps injecting the key after a credential switch.
763
+ if (source.usesConnectionCredential && source.integrationID) {
764
+ provider.integrationID = Integration.ID.make(source.integrationID)
765
+ }
642
766
  const settings = {
643
767
  ...(provider.settings ?? {}),
644
768
  ...runtimeSettings(source),
@@ -668,6 +792,12 @@ const definition = Plugin.define({
668
792
  package: source.package,
669
793
  settings: runtimeSettings(source),
670
794
  headers: source.headers,
795
+ // With `integrationID` set, OpenCode resolves the API key from
796
+ // the connected credential at request time — the key itself
797
+ // never enters provider settings.
798
+ ...(source.usesConnectionCredential && source.integrationID
799
+ ? { integrationID: Integration.ID.make(source.integrationID) }
800
+ : {}),
671
801
  },
672
802
  models: source.models,
673
803
  })
@@ -744,6 +874,18 @@ const definition = Plugin.define({
744
874
  continue
745
875
  }
746
876
  if (event.type === 'credential.switched') {
877
+ // Sources the plugin built from the dialog re-derive everything
878
+ // (key, baseURL, provider id) from the active connection, so a
879
+ // reconnect can legitimately move them to a different gateway.
880
+ // Configured sources only refresh their key: config outranks the
881
+ // dialog for everything but the key.
882
+ const dialogBuilt = [...sources.values()].filter(
883
+ (source) =>
884
+ source.integrationID === event.data.integrationID &&
885
+ source.fromFallback &&
886
+ source.usesConnectionCredential &&
887
+ !readString(source.settings.baseURL),
888
+ )
747
889
  const changedSources = (await Promise.all(
748
890
  [...sources.values()]
749
891
  .filter((source) => source.integrationID === event.data.integrationID)
@@ -755,8 +897,24 @@ const definition = Plugin.define({
755
897
  source.credentialReloadRequired = true
756
898
  source.refreshRequired = true
757
899
  }
758
- if (changedSources.length > 0) {
759
- await refreshProviderSources(context, changedSources, inFlight)
900
+ const keyOnlySources = changedSources.filter((source) => !dialogBuilt.includes(source))
901
+ if (keyOnlySources.length > 0) {
902
+ await refreshProviderSources(context, keyOnlySources, inFlight)
903
+ }
904
+ if (
905
+ event.data.integrationID === LITELLM_INTEGRATION_ID &&
906
+ (dialogBuilt.length > 0 || changedSources.length === 0)
907
+ ) {
908
+ // Rebuild dialog-built sources from the fresh credential — or,
909
+ // when no source is bound yet, publish the first one, taking
910
+ // over from a keyless auto-detection fallback if one exists.
911
+ await publishConnectedSource(
912
+ context,
913
+ pluginOptions,
914
+ sources,
915
+ staleProviderIds,
916
+ dialogBuilt,
917
+ )
760
918
  }
761
919
  continue
762
920
  }
@@ -782,6 +940,7 @@ const definition = Plugin.define({
782
940
  return async () => {
783
941
  controller.abort()
784
942
  await providerRegistration.dispose()
943
+ await integrationRegistration?.dispose()
785
944
  }
786
945
  },
787
946
  })
@@ -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 ||