opencode-plugin-litellm 1.6.1 → 1.7.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
@@ -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 `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. |
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,27 @@ 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. 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.
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, 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.
336
346
 
337
347
  ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
338
348
 
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.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",
@@ -14,8 +14,7 @@
14
14
  "scripts": {
15
15
  "typecheck": "tsc --noEmit",
16
16
  "test": "vitest run",
17
- "build": "npm run typecheck",
18
- "prepublishOnly": "npm run build"
17
+ "prepublishOnly": "npm run typecheck"
19
18
  },
20
19
  "keywords": [
21
20
  "opencode",
@@ -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,
@@ -313,41 +319,53 @@ async function makeProviderSource(
313
319
  provider: ProviderInfo | undefined,
314
320
  pluginOptions: Record<string, unknown>,
315
321
  ): Promise<ProviderSource | null> {
316
- const id = provider?.id ?? readString(pluginOptions.providerID) ?? CHAT_PROVIDER_ID
317
322
  const providerSettings = asRecord(provider?.settings)
318
323
  const settings = { ...pluginOptions, ...providerSettings }
319
- const configuredBaseURL = readString(settings.baseURL)
320
324
  const customHeaders = {
321
325
  ...readHeaders(pluginOptions.customHeaders),
322
326
  ...readCustomHeaders(settings),
323
327
  ...readHeaders(provider?.headers),
324
328
  }
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
- }
329
+ // Credential plus dialog form answers. A provider wired to its own
330
+ // integration keeps using exactly that one; otherwise the plugin's
331
+ // registered integration is consulted, so a gateway can be connected
332
+ // entirely from the web UI with no hand-written config.
333
+ const connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
334
+ context,
335
+ provider?.integrationID ?? LITELLM_INTEGRATION_ID,
336
+ )
337
+ const id =
338
+ provider?.id ??
339
+ readString(pluginOptions.providerID) ??
340
+ connected?.providerID ??
341
+ CHAT_PROVIDER_ID
342
+ const configuredBaseURL = readString(settings.baseURL)
343
+ const connectedApiKey = connected?.apiKey
337
344
  const configuredApiKey =
338
345
  readString(providerSettings.apiKey) ??
339
346
  readString(pluginOptions.apiKey) ??
340
347
  process.env.LITELLM_API_KEY ??
341
348
  process.env.LITELLM_MASTER_KEY
342
- const usesConnectionCredential = !configuredApiKey && Boolean(provider?.integrationID)
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)
354
+ const integrationID =
355
+ provider?.integrationID ??
356
+ (usesConnectionCredential && connectedApiKey ? LITELLM_INTEGRATION_ID : undefined)
343
357
  const apiKey = configuredApiKey ?? connectedApiKey
344
358
  const filters = readModelFilters(settings)
345
359
  const capabilities = parseModelCapabilities(settings.modelCapabilities)
346
360
  const compatibility = parseModelCompatibility(settings.modelCompatibility)
347
361
  const formatModelNames = readFormatModelNames(settings)
362
+ // Explicit config beats the URL typed into the dialog, which beats the
363
+ // environment and local port probing.
348
364
  const detectedBaseURL = configuredBaseURL
349
365
  ? normalizeBaseURL(configuredBaseURL)
350
- : await autoDetectLiteLLM(apiKey, customHeaders)
366
+ : connected?.baseURL
367
+ ? normalizeBaseURL(connected.baseURL)
368
+ : await autoDetectLiteLLM(apiKey, customHeaders)
351
369
 
352
370
  if (!detectedBaseURL) {
353
371
  return null
@@ -399,7 +417,7 @@ async function makeProviderSource(
399
417
  package: providerPackage,
400
418
  settings,
401
419
  headers: customHeaders,
402
- integrationID: provider?.integrationID,
420
+ integrationID,
403
421
  usesConnectionCredential,
404
422
  credentialReloadRequired: false,
405
423
  refreshRequired: false,
@@ -602,6 +620,62 @@ async function reconcileProviderSources(
602
620
  return changed
603
621
  }
604
622
 
623
+ /**
624
+ * Build and publish a source from the dialog's active credential.
625
+ *
626
+ * Called for the first connect with nothing bound yet, and to rebuild
627
+ * dialog-built sources after a credential switch — a reconnect may move the
628
+ * gateway to a new base URL or provider id, so those sources are re-derived
629
+ * wholesale instead of key-refreshed.
630
+ *
631
+ * An existing source for the same id is left untouched unless it is a pure
632
+ * auto-detection/dialog-built fallback (no explicit baseURL in
633
+ * options/config): a fallback only stands in until a real endpoint is
634
+ * known, so the dialog's answers take over from it. Explicit option/env
635
+ * baseURLs — and host-registered providers — keep winning and are never
636
+ * replaced. Replaced sources' owned model ids carry over so models the
637
+ * gateway no longer serves are dropped on the next merge, and sources
638
+ * replaced under a different id are dropped from `sources` and marked in
639
+ * `staleProviderIds` for removal from the provider registry.
640
+ */
641
+ async function publishConnectedSource(
642
+ context: Context,
643
+ pluginOptions: Record<string, unknown>,
644
+ sources: Map<string, ProviderSource>,
645
+ staleProviderIds: Set<string>,
646
+ replacing: ProviderSource[] = [],
647
+ ): Promise<void> {
648
+ try {
649
+ const source = await makeProviderSource(context, undefined, pluginOptions)
650
+ if (!source) return
651
+ const existing = sources.get(source.id)
652
+ if (existing && !(existing.fromFallback && !readString(existing.settings.baseURL))) return
653
+ const previous = existing ?? replacing.find((candidate) => candidate.id === source.id)
654
+ if (previous) source.ownedModelIds = new Set(previous.ownedModelIds)
655
+ for (const previousSource of replacing) {
656
+ if (previousSource.id === source.id) continue
657
+ const mapped = sources.get(previousSource.id)
658
+ if (mapped === previousSource) sources.delete(previousSource.id)
659
+ // Absent from the map means an earlier attempt already removed it but
660
+ // failed before reloading — still owed a registry removal. A different
661
+ // live source under the id (e.g. a host-registered provider took over)
662
+ // is left entirely alone.
663
+ if (mapped === previousSource || mapped === undefined) {
664
+ staleProviderIds.add(previousSource.id)
665
+ }
666
+ }
667
+ sources.set(source.id, source)
668
+ await context.provider.reload()
669
+ source.pendingPublication = false
670
+ logInfo(
671
+ `[opencode-litellm] Registered provider "${source.id}" from the connected LiteLLM credential.`,
672
+ )
673
+ } catch (error) {
674
+ const message = error instanceof Error ? error.message : String(error)
675
+ logInfo(`[opencode-litellm] Could not register the connected provider: ${message}`)
676
+ }
677
+ }
678
+
605
679
  const definition = Plugin.define({
606
680
  id: 'opencode-litellm',
607
681
  async setup(context) {
@@ -615,6 +689,14 @@ const definition = Plugin.define({
615
689
 
616
690
  const pluginOptions = asRecord(context.options)
617
691
  const sources = new Map<string, ProviderSource>()
692
+ // Providers the dialog replaced under a new id; the transform below
693
+ // removes them from the registry on the next reload.
694
+ const staleProviderIds = new Set<string>()
695
+
696
+ // Surface LiteLLM in the connect-provider dialog so gateways can be
697
+ // connected from the web UI. Purely additive: a host without the
698
+ // integration API, or a failed registration, keeps every other auth path.
699
+ const integrationRegistration = await registerLiteLLMIntegration(context)
618
700
 
619
701
  // First pass. On OpenCode 2 the host has not registered user-configured
620
702
  // providers yet, so this typically finds only built-ins; the event loop
@@ -633,12 +715,21 @@ const definition = Plugin.define({
633
715
  }
634
716
 
635
717
  const providerRegistration = await context.provider.transform((editor) => {
718
+ // Sources replaced under a different id leave their registry entries
719
+ // behind; drop them before publishing the current sources.
720
+ for (const id of staleProviderIds) editor.remove(id)
721
+ staleProviderIds.clear()
636
722
  for (const source of sources.values()) {
637
723
  const current = editor.get(source.id)
638
724
  if (current) {
639
725
  editor.update(source.id, (provider) => {
640
726
  provider.package = source.package
641
727
  provider.name = source.name
728
+ // Bind the provider to the integration its credential comes from,
729
+ // so OpenCode keeps injecting the key after a credential switch.
730
+ if (source.usesConnectionCredential && source.integrationID) {
731
+ provider.integrationID = Integration.ID.make(source.integrationID)
732
+ }
642
733
  const settings = {
643
734
  ...(provider.settings ?? {}),
644
735
  ...runtimeSettings(source),
@@ -668,6 +759,12 @@ const definition = Plugin.define({
668
759
  package: source.package,
669
760
  settings: runtimeSettings(source),
670
761
  headers: source.headers,
762
+ // With `integrationID` set, OpenCode resolves the API key from
763
+ // the connected credential at request time — the key itself
764
+ // never enters provider settings.
765
+ ...(source.usesConnectionCredential && source.integrationID
766
+ ? { integrationID: Integration.ID.make(source.integrationID) }
767
+ : {}),
671
768
  },
672
769
  models: source.models,
673
770
  })
@@ -744,6 +841,18 @@ const definition = Plugin.define({
744
841
  continue
745
842
  }
746
843
  if (event.type === 'credential.switched') {
844
+ // Sources the plugin built from the dialog re-derive everything
845
+ // (key, baseURL, provider id) from the active connection, so a
846
+ // reconnect can legitimately move them to a different gateway.
847
+ // Configured sources only refresh their key: config outranks the
848
+ // dialog for everything but the key.
849
+ const dialogBuilt = [...sources.values()].filter(
850
+ (source) =>
851
+ source.integrationID === event.data.integrationID &&
852
+ source.fromFallback &&
853
+ source.usesConnectionCredential &&
854
+ !readString(source.settings.baseURL),
855
+ )
747
856
  const changedSources = (await Promise.all(
748
857
  [...sources.values()]
749
858
  .filter((source) => source.integrationID === event.data.integrationID)
@@ -755,8 +864,24 @@ const definition = Plugin.define({
755
864
  source.credentialReloadRequired = true
756
865
  source.refreshRequired = true
757
866
  }
758
- if (changedSources.length > 0) {
759
- await refreshProviderSources(context, changedSources, inFlight)
867
+ const keyOnlySources = changedSources.filter((source) => !dialogBuilt.includes(source))
868
+ if (keyOnlySources.length > 0) {
869
+ await refreshProviderSources(context, keyOnlySources, inFlight)
870
+ }
871
+ if (
872
+ event.data.integrationID === LITELLM_INTEGRATION_ID &&
873
+ (dialogBuilt.length > 0 || changedSources.length === 0)
874
+ ) {
875
+ // Rebuild dialog-built sources from the fresh credential — or,
876
+ // when no source is bound yet, publish the first one, taking
877
+ // over from a keyless auto-detection fallback if one exists.
878
+ await publishConnectedSource(
879
+ context,
880
+ pluginOptions,
881
+ sources,
882
+ staleProviderIds,
883
+ dialogBuilt,
884
+ )
760
885
  }
761
886
  continue
762
887
  }
@@ -782,6 +907,7 @@ const definition = Plugin.define({
782
907
  return async () => {
783
908
  controller.abort()
784
909
  await providerRegistration.dispose()
910
+ await integrationRegistration?.dispose()
785
911
  }
786
912
  },
787
913
  })