opencode-plugin-litellm 0.4.2 → 0.5.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
@@ -52,20 +52,12 @@ npm install opencode-plugin-litellm
52
52
  "npm": "@ai-sdk/openai-compatible",
53
53
  "options": {
54
54
  "baseURL": "http://localhost:4000/v1"
55
- },
56
- "models": {
57
- "_": { "name": "seed" }
58
55
  }
59
56
  }
60
57
  }
61
58
  }
62
59
  ```
63
60
 
64
- > **Why the `"_"` seed model?** OpenCode only activates the plugin's
65
- > model-discovery hook when the provider already has at least one model
66
- > entry. The seed is replaced at startup by the full list from your
67
- > LiteLLM proxy.
68
-
69
61
  ```bash
70
62
  # 3. Start LiteLLM (if it isn't already)
71
63
  litellm --config config.yaml --port 4000
@@ -95,7 +87,7 @@ opencode
95
87
 
96
88
  ### Minimal config (recommended)
97
89
 
98
- Point at your LiteLLM proxy and include a seed model so OpenCode registers the provider:
90
+ Point at your LiteLLM proxy — the plugin discovers all models automatically:
99
91
 
100
92
  ```jsonc
101
93
  {
@@ -106,9 +98,6 @@ Point at your LiteLLM proxy and include a seed model so OpenCode registers the p
106
98
  "npm": "@ai-sdk/openai-compatible",
107
99
  "options": {
108
100
  "baseURL": "http://localhost:4000/v1"
109
- },
110
- "models": {
111
- "_": { "name": "seed" }
112
101
  }
113
102
  }
114
103
  }
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": "0.4.2",
4
+ "version": "0.5.0",
5
5
  "description": "OpenCode plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
@@ -1,30 +1,74 @@
1
1
  import type { Plugin, PluginInput } from '@opencode-ai/plugin'
2
- import { discoverBucket } from './discover'
2
+ import {
3
+ autoDetectLiteLLM,
4
+ checkLiteLLMHealth,
5
+ discoverLiteLLMModels,
6
+ normalizeBaseURL,
7
+ } from '../utils/litellm-api'
8
+ import {
9
+ formatModelName,
10
+ extractModelOwner,
11
+ categorizeModel,
12
+ } from '../utils/format-model-name'
13
+ import type { LiteLLMModel } from '../types'
3
14
 
4
15
  const CHAT_PROVIDER_ID = 'litellm'
5
- const RESPONSES_PROVIDER_ID = 'litellm-responses'
16
+ const DISCOVERY_TIMEOUT_MS = 5000
17
+
18
+ /**
19
+ * Read `customHeaders` from a provider options block.
20
+ */
21
+ function readCustomHeaders(
22
+ options: Record<string, unknown>,
23
+ ): Record<string, string> | undefined {
24
+ const raw = options.customHeaders
25
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
26
+ const out: Record<string, string> = {}
27
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
28
+ if (typeof v === 'string') out[k] = v
29
+ }
30
+ return Object.keys(out).length > 0 ? out : undefined
31
+ }
32
+ return undefined
33
+ }
34
+
35
+ /**
36
+ * Convert a discovered LiteLLM model into an OpenCode config-level
37
+ * model entry (the shape used in `provider.*.models` inside
38
+ * `opencode.json`).
39
+ */
40
+ function toConfigModel(model: LiteLLMModel): Record<string, unknown> {
41
+ const type = categorizeModel(model)
42
+ const entry: Record<string, unknown> = {
43
+ name: formatModelName(model),
44
+ }
45
+ if (model.max_input_tokens || model.max_output_tokens) {
46
+ entry.limit = {
47
+ context: model.max_input_tokens ?? 0,
48
+ output: model.max_output_tokens ?? 0,
49
+ }
50
+ }
51
+ if (model.supports_function_calling) {
52
+ entry.tool_call = true
53
+ }
54
+ if (model.supports_vision) {
55
+ entry.attachment = true
56
+ }
57
+ if (type === 'embedding' || type === 'image' || type === 'audio') {
58
+ // skip non-chat models from the config — they can't be used as
59
+ // primary chat models and would clutter the picker.
60
+ return entry
61
+ }
62
+ return entry
63
+ }
6
64
 
7
65
  /**
8
66
  * LiteLLM Plugin for OpenCode.
9
67
  *
10
- * Implements the `provider.models` hook so OpenCode populates the
11
- * `litellm` provider's model list from a live LiteLLM proxy at
12
- * startup.
13
- *
14
- * **Important:** OpenCode only calls `provider.models` when the
15
- * provider has at least one model defined in `opencode.json`. You
16
- * must include a seed model entry — it can be any model id your
17
- * proxy exposes. The plugin will discover and add all remaining
18
- * models automatically.
19
- *
20
- * By default, every discovered model is registered under the
21
- * `litellm` provider — including OpenAI reasoning-tier models like
22
- * `gpt-5*`. Most of those models work fine through
23
- * `/v1/chat/completions` for normal use. If you actually hit the
24
- * "Function tools with reasoning_effort are not supported" error
25
- * from OpenAI, declare a sibling `litellm-responses` provider in
26
- * `opencode.json` (see {@link LiteLLMResponsesPlugin}) and the
27
- * plugin will route those models through `/v1/responses` instead.
68
+ * Uses the `config` hook to discover models from a LiteLLM proxy and
69
+ * inject them into the provider's `models` map at startup. This is the
70
+ * only reliable way to dynamically populate a provider — the
71
+ * `provider.models` hook is not called by OpenCode for custom providers.
28
72
  *
29
73
  * Configure the provider in your `opencode.json`:
30
74
  *
@@ -37,9 +81,6 @@ const RESPONSES_PROVIDER_ID = 'litellm-responses'
37
81
  * "options": {
38
82
  * "baseURL": "http://localhost:4000/v1",
39
83
  * "apiKey": "{env:LITELLM_API_KEY}"
40
- * },
41
- * "models": {
42
- * "_": { "name": "seed" }
43
84
  * }
44
85
  * }
45
86
  * }
@@ -47,65 +88,133 @@ const RESPONSES_PROVIDER_ID = 'litellm-responses'
47
88
  */
48
89
  export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
49
90
  return {
50
- provider: {
51
- id: CHAT_PROVIDER_ID,
52
- models: async (provider) => {
53
- // 'all' (not 'chat') by default so reasoning-tier models like
54
- // gpt-5* don't silently disappear when the user hasn't opted
55
- // into the responses-API split. The split only kicks in when
56
- // the user explicitly declares a `litellm-responses` provider.
57
- return discoverBucket('all', provider, {
58
- id: CHAT_PROVIDER_ID,
59
- url: '',
91
+ config: async (config: any) => {
92
+ // Ensure the provider entry exists
93
+ if (!config.provider) config.provider = {}
94
+
95
+ const existing = config.provider[CHAT_PROVIDER_ID] as
96
+ | Record<string, unknown>
97
+ | undefined
98
+ const options = (existing?.options ?? {}) as Record<string, unknown>
99
+ const configuredBase =
100
+ typeof options.baseURL === 'string' ? options.baseURL : undefined
101
+ const configuredKey =
102
+ typeof options.apiKey === 'string' && options.apiKey
103
+ ? options.apiKey
104
+ : undefined
105
+ const envKey =
106
+ process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
107
+ const apiKey = configuredKey ?? envKey
108
+ const customHeaders = readCustomHeaders(options)
109
+
110
+ // Resolve base URL
111
+ let baseURL: string | null = null
112
+ if (configuredBase) {
113
+ baseURL = normalizeBaseURL(configuredBase)
114
+ } else {
115
+ baseURL = await autoDetectLiteLLM(apiKey, customHeaders)
116
+ }
117
+
118
+ if (!baseURL) {
119
+ console.warn(
120
+ '[opencode-litellm] No LiteLLM proxy found. Configure provider.litellm.options.baseURL or start LiteLLM on port 4000/8000/8080.',
121
+ )
122
+ return
123
+ }
124
+
125
+ // Create provider entry if it doesn't exist
126
+ if (!existing) {
127
+ config.provider[CHAT_PROVIDER_ID] = {
60
128
  npm: '@ai-sdk/openai-compatible',
61
- })
62
- },
129
+ name: 'LiteLLM (proxy)',
130
+ options: {
131
+ baseURL: `${baseURL}/v1`,
132
+ },
133
+ models: {},
134
+ }
135
+ }
136
+
137
+ const provider = config.provider[CHAT_PROVIDER_ID] as Record<
138
+ string,
139
+ unknown
140
+ >
141
+
142
+ // Ensure npm is set
143
+ if (!provider.npm) {
144
+ provider.npm = '@ai-sdk/openai-compatible'
145
+ }
146
+
147
+ // Ensure options.baseURL is set
148
+ if (!provider.options) {
149
+ provider.options = { baseURL: `${baseURL}/v1` }
150
+ }
151
+
152
+ // Ensure models map exists
153
+ if (!provider.models) {
154
+ provider.models = {}
155
+ }
156
+
157
+ const models = provider.models as Record<string, unknown>
158
+
159
+ // Discover models with timeout
160
+ const work = async () => {
161
+ if (!(await checkLiteLLMHealth(baseURL!, apiKey, customHeaders))) {
162
+ console.warn(
163
+ `[opencode-litellm] LiteLLM appears offline or unauthorized at ${baseURL}`,
164
+ )
165
+ return
166
+ }
167
+
168
+ let discovered: LiteLLMModel[]
169
+ try {
170
+ discovered = await discoverLiteLLMModels(
171
+ baseURL!,
172
+ apiKey,
173
+ customHeaders,
174
+ )
175
+ } catch (error) {
176
+ console.warn(
177
+ '[opencode-litellm] Model discovery failed:',
178
+ error instanceof Error ? error.message : String(error),
179
+ )
180
+ return
181
+ }
182
+
183
+ if (discovered.length === 0) {
184
+ console.warn(
185
+ '[opencode-litellm] LiteLLM responded but exposed zero models.',
186
+ )
187
+ return
188
+ }
189
+
190
+ for (const model of discovered) {
191
+ // Don't overwrite user-curated entries
192
+ if (models[model.id]) continue
193
+ models[model.id] = toConfigModel(model)
194
+ }
195
+
196
+ // Remove the seed placeholder if real models were discovered
197
+ if (models['_'] && Object.keys(models).length > 1) {
198
+ delete models['_']
199
+ }
200
+
201
+ console.log(
202
+ `[opencode-litellm] Discovered ${discovered.length} models from ${baseURL}`,
203
+ )
204
+ }
205
+
206
+ await Promise.race([
207
+ work(),
208
+ new Promise<void>((resolve) =>
209
+ setTimeout(resolve, DISCOVERY_TIMEOUT_MS),
210
+ ),
211
+ ])
63
212
  },
64
213
  }
65
214
  }
66
215
 
67
- /**
68
- * Optional sibling plugin that registers the `litellm-responses`
69
- * provider for OpenAI reasoning-tier models.
70
- *
71
- * OpenAI's reasoning-tier models (`gpt-5*`, `o1`/`o3`/`o4*`) reject
72
- * requests that combine `reasoning_effort` with function tools when
73
- * sent to `/v1/chat/completions`. Routing those models through
74
- * `/v1/responses` (the OpenAI Responses API) avoids the rejection.
75
- *
76
- * This plugin is only active when the `litellm-responses` provider
77
- * is declared in `opencode.json`. When it is, the chat-only `litellm`
78
- * provider continues to register every discovered model — set
79
- * `chatApiModels` / `responsesApiModels` on either provider's options
80
- * if you want to control which side a particular model lives on.
81
- *
82
- * Example `opencode.json` snippet:
83
- *
84
- * {
85
- * "provider": {
86
- * "litellm-responses": {
87
- * "npm": "@ai-sdk/openai",
88
- * "name": "LiteLLM (responses)",
89
- * "options": {
90
- * "baseURL": "http://localhost:4000/v1",
91
- * "apiKey": "{env:LITELLM_API_KEY}",
92
- * "compatibility": "strict"
93
- * }
94
- * }
95
- * }
96
- * }
97
- */
216
+ // Re-export the responses plugin for backwards compat, but it's now a no-op.
217
+ // The config hook approach handles all models in a single provider.
98
218
  export const LiteLLMResponsesPlugin: Plugin = async (_input: PluginInput) => {
99
- return {
100
- provider: {
101
- id: RESPONSES_PROVIDER_ID,
102
- models: async (provider) => {
103
- return discoverBucket('responses', provider, {
104
- id: RESPONSES_PROVIDER_ID,
105
- url: '',
106
- npm: '@ai-sdk/openai',
107
- })
108
- },
109
- },
110
- }
219
+ return {}
111
220
  }