opencode-plugin-litellm 1.3.0 → 1.4.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 +124 -95
- package/package.json +3 -2
- package/src/index.ts +1 -0
- package/src/plugin/index.ts +33 -18
- package/src/plugin/v2.ts +540 -0
- package/src/utils/litellm-api.ts +5 -3
- package/src/utils/model-cache.ts +1 -1
package/README.md
CHANGED
|
@@ -6,9 +6,10 @@
|
|
|
6
6
|
|
|
7
7
|
# opencode-litellm
|
|
8
8
|
|
|
9
|
-
**
|
|
9
|
+
**[OpenCode V1 + V2](https://opencode.ai) + [LiteLLM](https://github.com/BerriAI/litellm) provider with zero configuration.**
|
|
10
10
|
|
|
11
11
|
[](https://opencode.ai)
|
|
12
|
+
[](https://opencode.ai)
|
|
12
13
|
[](https://github.com/BerriAI/litellm)
|
|
13
14
|
|
|
14
15
|
[](https://www.npmjs.com/package/opencode-plugin-litellm)
|
|
@@ -21,7 +22,7 @@
|
|
|
21
22
|
Auto-detect a running LiteLLM proxy, pull every model from `/v1/models`, and register them in OpenCode.
|
|
22
23
|
**No model lists to hand-maintain. No restart loops. No surprises.**
|
|
23
24
|
|
|
24
|
-
<img src="https://raw.githubusercontent.com/yuseferi/opencode-litellm/main/assets/architecture.svg" alt="How opencode-litellm works: OpenCode
|
|
25
|
+
<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%" />
|
|
25
26
|
|
|
26
27
|
[Quickstart](#-quickstart) · [Configuration](#%EF%B8%8F-configuration) · [How it works](#-how-it-works) · [FAQ](#-faq) · [Contributing](./CONTRIBUTING.md)
|
|
27
28
|
|
|
@@ -30,59 +31,60 @@ Auto-detect a running LiteLLM proxy, pull every model from `/v1/models`, and reg
|
|
|
30
31
|
> **npm package:** `opencode-plugin-litellm` · **GitHub repo:** `yuseferi/opencode-litellm`
|
|
31
32
|
> The unscoped `opencode-litellm` npm name was already taken by another author.
|
|
32
33
|
|
|
34
|
+
> **✅ OpenCode V1 + V2 support:** OpenCode **2.0.19** uses native
|
|
35
|
+
> `Plugin.define`, provider-registry model discovery, and in-process refresh.
|
|
36
|
+
> OpenCode **1.18.29+** uses the legacy `server()` entrypoint. Both versions
|
|
37
|
+
> are supported by this package.
|
|
38
|
+
|
|
33
39
|
---
|
|
34
40
|
|
|
35
41
|
## ✨ Why this plugin?
|
|
36
42
|
|
|
37
43
|
Maintaining a `models` block in `opencode.json` for every model your LiteLLM proxy exposes is a chore — every new entry in your `model_list` means a config edit, a restart, and a context-switch.
|
|
38
44
|
|
|
39
|
-
`opencode-litellm` removes that loop entirely. It
|
|
45
|
+
`opencode-litellm` removes that loop entirely. It queries your LiteLLM proxy during plugin setup and registers discovered models with OpenCode's provider registry. New models are refreshed in-process through the V2 provider API, while V1 keeps its config-hook behavior.
|
|
40
46
|
|
|
41
47
|
## 🚀 Quickstart
|
|
42
48
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
"$schema": "https://opencode.ai/config.json",
|
|
47
|
-
"plugin": ["opencode-plugin-litellm@latest"],
|
|
48
|
-
"provider": {
|
|
49
|
-
"litellm": {
|
|
50
|
-
"npm": "@ai-sdk/openai-compatible",
|
|
51
|
-
"options": {
|
|
52
|
-
"baseURL": "http://localhost:4000/v1"
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
```
|
|
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.
|
|
58
52
|
|
|
59
53
|
```bash
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
# 3. Run OpenCode — every model in your LiteLLM model_list is now available.
|
|
64
|
-
opencode
|
|
54
|
+
opencode plugin add opencode-plugin-litellm
|
|
55
|
+
opencode service set env LITELLM_BASE_URL https://litellm.internal.example.com/v1
|
|
56
|
+
opencode service set env LITELLM_API_KEY YOUR_API_KEY
|
|
65
57
|
```
|
|
66
58
|
|
|
59
|
+
Then open OpenCode and select a discovered model under `litellm/...`.
|
|
60
|
+
|
|
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
|
+
For a local LiteLLM proxy on port 4000, the base URL can be omitted and the
|
|
66
|
+
plugin will detect it automatically. The [configuration section](#%EF%B8%8F-configuration)
|
|
67
|
+
also shows how to configure a provider directly in `opencode.json`.
|
|
68
|
+
|
|
67
69
|
## 🎯 Features
|
|
68
70
|
|
|
69
71
|
| | |
|
|
70
72
|
|---|---|
|
|
71
73
|
| 🔍 **Auto-detection** | Probes `localhost:4000`, `:8000`, `:8080` and adopts the first responsive proxy. |
|
|
72
74
|
| 📡 **Dynamic discovery** | Queries `/v1/models` so your OpenCode model picker always reflects your live `model_list`. |
|
|
73
|
-
| ⚡ **
|
|
75
|
+
| ⚡ **Stale-while-revalidate** | A warm disk cache supplies models without a network request. New sessions trigger a background refresh, and cache entries expire after 7 days. |
|
|
74
76
|
| 🏷️ **Smart formatting** | Turns `anthropic/claude-3-5-sonnet` into `Claude 3.5 Sonnet` in the picker — handles versions, sizes, quantizations, and brand-cased names like `gpt-4o`. Set `formatModelNames: false` to keep the raw LiteLLM ids instead. |
|
|
75
77
|
| 🧠 **Modality-aware** | Enriches `/v1/models` entries with `/v1/model/info` (`mode`, token limits, capability flags) and hides embedding / image / audio models from the picker. |
|
|
76
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. |
|
|
77
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. |
|
|
78
|
-
| 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY
|
|
79
|
-
| 🌐 **Gateway-friendly** | Supports `customHeaders` for proxies behind Cloudflare Access or other API gateways
|
|
80
|
+
| 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, `providers.litellm.settings.apiKey`, and OpenCode `/connect` credentials on the V1 server path. |
|
|
81
|
+
| 🌐 **Gateway-friendly** | Supports provider `headers` (and the legacy `customHeaders` option) for proxies behind Cloudflare Access or other API gateways. |
|
|
80
82
|
| 🧩 **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. |
|
|
81
83
|
| 🎚️ **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. |
|
|
82
|
-
| ⏱️ **
|
|
83
|
-
| 📝 **
|
|
84
|
+
| ⏱️ **Bounded startup** | Health checks fail fast (3 s); discovery fetches are capped at **15 s** (configurable via `LITELLM_REQUEST_TIMEOUT_MS`) for slow remote proxies. V2 model refresh runs in the background. |
|
|
85
|
+
| 📝 **OpenCode logging** | V1 logs go through OpenCode's log API; V2 logs use the V2 plugin host's console logging. |
|
|
84
86
|
| 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
|
|
85
|
-
|
|
|
87
|
+
| 🔌 **OpenCode V1 + V2** | Supports OpenCode 2's native `Plugin.define`, provider transforms, event subscription, and live model refresh, plus the OpenCode 1.18.29+ legacy `server()` entrypoint. |
|
|
86
88
|
| 🔒 **TypeScript strict** | Strict-mode compiled, fully typed public API. |
|
|
87
89
|
|
|
88
90
|
## ⚙️ Configuration
|
|
@@ -94,11 +96,12 @@ Point at your LiteLLM proxy — the plugin discovers all models automatically:
|
|
|
94
96
|
```jsonc
|
|
95
97
|
{
|
|
96
98
|
"$schema": "https://opencode.ai/config.json",
|
|
97
|
-
"
|
|
98
|
-
"
|
|
99
|
+
"plugins": ["opencode-plugin-litellm@latest"],
|
|
100
|
+
"providers": {
|
|
99
101
|
"litellm": {
|
|
100
|
-
"
|
|
101
|
-
"
|
|
102
|
+
"name": "LiteLLM (proxy)",
|
|
103
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
104
|
+
"settings": {
|
|
102
105
|
"baseURL": "http://localhost:4000/v1"
|
|
103
106
|
}
|
|
104
107
|
}
|
|
@@ -113,12 +116,12 @@ You **do not need to list any models** — the plugin still discovers them from
|
|
|
113
116
|
```jsonc
|
|
114
117
|
{
|
|
115
118
|
"$schema": "https://opencode.ai/config.json",
|
|
116
|
-
"
|
|
117
|
-
"
|
|
119
|
+
"plugins": ["opencode-plugin-litellm@latest"],
|
|
120
|
+
"providers": {
|
|
118
121
|
"litellm": {
|
|
119
|
-
"npm": "@ai-sdk/openai-compatible",
|
|
120
122
|
"name": "LiteLLM (proxy)",
|
|
121
|
-
"
|
|
123
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
124
|
+
"settings": {
|
|
122
125
|
"baseURL": "http://litellm.internal.example.com/v1",
|
|
123
126
|
"apiKey": "{env:LITELLM_API_KEY}"
|
|
124
127
|
}
|
|
@@ -129,6 +132,28 @@ You **do not need to list any models** — the plugin still discovers them from
|
|
|
129
132
|
|
|
130
133
|
That's the whole config — every model in your LiteLLM `model_list` will appear in the picker.
|
|
131
134
|
|
|
135
|
+
An explicit `settings.baseURL` in a LiteLLM provider takes precedence over
|
|
136
|
+
`LITELLM_BASE_URL`. If neither is set, the plugin checks the usual local ports.
|
|
137
|
+
|
|
138
|
+
### OpenCode 1.18.29+
|
|
139
|
+
|
|
140
|
+
The package also exposes the V1 server entrypoint for older OpenCode 1
|
|
141
|
+
installations. Keep the V1 `plugin` / `provider` configuration shape:
|
|
142
|
+
|
|
143
|
+
```jsonc
|
|
144
|
+
{
|
|
145
|
+
"plugin": ["opencode-plugin-litellm@latest"],
|
|
146
|
+
"provider": {
|
|
147
|
+
"litellm": {
|
|
148
|
+
"npm": "@ai-sdk/openai-compatible",
|
|
149
|
+
"options": {
|
|
150
|
+
"baseURL": "http://localhost:4000/v1"
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
132
157
|
### Example: governed upstream route with Tuning Engines
|
|
133
158
|
|
|
134
159
|
If your team routes model traffic through Tuning Engines for policy, traces,
|
|
@@ -159,20 +184,19 @@ Engines sits on the upstream model route as the governed control plane.
|
|
|
159
184
|
|
|
160
185
|
### Overriding or curating individual models (optional)
|
|
161
186
|
|
|
162
|
-
If you want to rename a model in the picker
|
|
187
|
+
If you want to rename a model in the picker or otherwise hand-curate metadata, add it under `models`. The plugin preserves your entries and only injects discovered models whose key isn't already defined:
|
|
163
188
|
|
|
164
189
|
```jsonc
|
|
165
190
|
{
|
|
166
|
-
"
|
|
191
|
+
"providers": {
|
|
167
192
|
"litellm": {
|
|
168
|
-
"
|
|
193
|
+
"settings": {
|
|
169
194
|
"baseURL": "http://litellm.internal.example.com/v1",
|
|
170
195
|
"apiKey": "{env:LITELLM_API_KEY}"
|
|
171
196
|
},
|
|
172
197
|
"models": {
|
|
173
198
|
"openai/gpt-4o": {
|
|
174
|
-
"name": "GPT-4o (curated)"
|
|
175
|
-
"organizationOwner": "openai"
|
|
199
|
+
"name": "GPT-4o (curated)"
|
|
176
200
|
}
|
|
177
201
|
}
|
|
178
202
|
}
|
|
@@ -208,12 +232,13 @@ If your LiteLLM proxy requires a master key, expose it via either approach:
|
|
|
208
232
|
|
|
209
233
|
| Method | Example |
|
|
210
234
|
|---|---|
|
|
235
|
+
| Env var (base URL) | `LITELLM_BASE_URL=https://litellm.internal.example.com/v1` |
|
|
211
236
|
| Env var | `export LITELLM_API_KEY=sk-...` |
|
|
212
237
|
| Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
|
|
213
|
-
| Config | `"
|
|
238
|
+
| Config | `"settings": { "apiKey": "{env:LITELLM_API_KEY}" }` |
|
|
214
239
|
| OpenCode `/connect` | Run `/connect`, search for your `litellm` provider entry, and paste the key |
|
|
215
240
|
|
|
216
|
-
The env var path lets you commit `opencode.json` without leaking secrets.
|
|
241
|
+
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.
|
|
217
242
|
|
|
218
243
|
### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
|
|
219
244
|
|
|
@@ -227,19 +252,19 @@ The overall discovery cap scales with it (max of 20 s and the request timeout +
|
|
|
227
252
|
|
|
228
253
|
### Custom headers (Cloudflare Access, API gateways)
|
|
229
254
|
|
|
230
|
-
If your LiteLLM proxy is behind Cloudflare Access or another gateway that requires extra HTTP headers, use the `
|
|
255
|
+
If your LiteLLM proxy is behind Cloudflare Access or another gateway that requires extra HTTP headers, use the provider's `headers` map:
|
|
231
256
|
|
|
232
257
|
```jsonc
|
|
233
258
|
{
|
|
234
|
-
"
|
|
259
|
+
"providers": {
|
|
235
260
|
"litellm": {
|
|
236
|
-
"
|
|
261
|
+
"settings": {
|
|
237
262
|
"baseURL": "https://litellm.internal.example.com/v1",
|
|
238
|
-
"apiKey": "{env:LITELLM_API_KEY}"
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}
|
|
263
|
+
"apiKey": "{env:LITELLM_API_KEY}"
|
|
264
|
+
},
|
|
265
|
+
"headers": {
|
|
266
|
+
"CF-Access-Client-Id": "{env:CF_ACCESS_CLIENT_ID}",
|
|
267
|
+
"CF-Access-Client-Secret": "{env:CF_ACCESS_CLIENT_SECRET}"
|
|
243
268
|
}
|
|
244
269
|
}
|
|
245
270
|
}
|
|
@@ -254,19 +279,19 @@ If your LiteLLM catalog mixes naming conventions from different teams or environ
|
|
|
254
279
|
|
|
255
280
|
```jsonc
|
|
256
281
|
{
|
|
257
|
-
"
|
|
282
|
+
"providers": {
|
|
258
283
|
"litellm": {
|
|
259
|
-
"npm": "@ai-sdk/openai-compatible",
|
|
260
284
|
"name": "Prod",
|
|
261
|
-
"
|
|
285
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
286
|
+
"settings": {
|
|
262
287
|
"baseURL": "http://localhost:4000/v1",
|
|
263
288
|
"includeModels": ["prod/*"]
|
|
264
289
|
}
|
|
265
290
|
},
|
|
266
291
|
"litellm-staging": {
|
|
267
|
-
"npm": "@ai-sdk/openai-compatible",
|
|
268
292
|
"name": "Staging",
|
|
269
|
-
"
|
|
293
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
294
|
+
"settings": {
|
|
270
295
|
"baseURL": "http://localhost:4000/v1",
|
|
271
296
|
"includeModels": ["staging/*"],
|
|
272
297
|
"excludeModels": ["staging/*-canary"]
|
|
@@ -280,6 +305,7 @@ If your LiteLLM catalog mixes naming conventions from different teams or environ
|
|
|
280
305
|
- `excludeModels` is evaluated after and always wins, even over `includeModels`.
|
|
281
306
|
- Patterns support only `*` (any run of characters); everything else is matched literally, so dots in ids like `gpt-4.1` need no escaping.
|
|
282
307
|
- Filtering happens before the on-disk cache is written, so each provider's cached view respects its own filters.
|
|
308
|
+
- Provider IDs beginning with `litellm-` are recognized automatically. Add `settings.litellm: true` to mark a provider with another ID.
|
|
283
309
|
|
|
284
310
|
### Correcting capability flags (`modelCapabilities`)
|
|
285
311
|
|
|
@@ -287,9 +313,9 @@ Model classification (tool-call badge, attachments, reasoning, input modalities)
|
|
|
287
313
|
|
|
288
314
|
```jsonc
|
|
289
315
|
{
|
|
290
|
-
"
|
|
316
|
+
"providers": {
|
|
291
317
|
"litellm": {
|
|
292
|
-
"
|
|
318
|
+
"settings": {
|
|
293
319
|
"baseURL": "http://localhost:4000/v1",
|
|
294
320
|
"modelCapabilities": {
|
|
295
321
|
"te-gpt-5.4-mini": { "supports_function_calling": true },
|
|
@@ -304,6 +330,7 @@ Model classification (tool-call badge, attachments, reasoning, input modalities)
|
|
|
304
330
|
- Overrides apply on top of whatever the proxy reports, with an explicit `false` winning — a flag the proxy never reported can be forced on just the same.
|
|
305
331
|
- Keys are exact model ids as they appear in `/v1/models` (not globs).
|
|
306
332
|
- Overridden flags flow into the picker exactly like natively reported ones, and the adjusted view is what gets persisted to the model cache.
|
|
333
|
+
- When `/v1/model/info` reports no modality flags, discovered chat models are registered as text-only. This avoids OpenCode's image-capable fallback for text-only deployments; set `supports_vision: true` explicitly for a route that has a working multimodal projector.
|
|
307
334
|
- Changing `modelCapabilities` (or `includeModels`/`excludeModels`) starts a fresh discovery on the next start — the cache is scoped by that config — so the picker reflects the new flags immediately.
|
|
308
335
|
|
|
309
336
|
### Keeping raw model ids in the picker (`formatModelNames`)
|
|
@@ -312,9 +339,9 @@ By default the plugin prettifies each discovered id into a display name — `ant
|
|
|
312
339
|
|
|
313
340
|
```jsonc
|
|
314
341
|
{
|
|
315
|
-
"
|
|
342
|
+
"providers": {
|
|
316
343
|
"litellm": {
|
|
317
|
-
"
|
|
344
|
+
"settings": {
|
|
318
345
|
"baseURL": "http://localhost:4000/v1",
|
|
319
346
|
"formatModelNames": false
|
|
320
347
|
}
|
|
@@ -337,44 +364,46 @@ sequenceDiagram
|
|
|
337
364
|
participant Cache as disk cache
|
|
338
365
|
participant LL as LiteLLM proxy
|
|
339
366
|
|
|
340
|
-
OC->>Plugin:
|
|
341
|
-
alt
|
|
367
|
+
OC->>Plugin: Plugin.define.setup(ctx)
|
|
368
|
+
alt providers.litellm configured
|
|
342
369
|
Plugin->>Plugin: use configured baseURL
|
|
343
370
|
else not configured
|
|
344
371
|
Plugin->>LL: probe :4000, :8000, :8080 (GET /v1/models, 3 s fail-fast)
|
|
345
372
|
LL-->>Plugin: 200 OK on one
|
|
346
|
-
Plugin->>Plugin:
|
|
373
|
+
Plugin->>Plugin: prepare litellm provider
|
|
347
374
|
end
|
|
348
375
|
Plugin->>Cache: read SWR cache (no network yet)
|
|
349
376
|
alt cache hit
|
|
350
377
|
Cache-->>Plugin: cached models
|
|
351
|
-
Plugin->>OC:
|
|
378
|
+
Plugin->>OC: provider.transform(cached models)
|
|
352
379
|
else cache miss
|
|
353
380
|
Plugin->>LL: GET /v1/models (with auth if set)
|
|
354
381
|
Plugin->>LL: GET /v1/model/info (best-effort)
|
|
355
382
|
LL-->>Plugin: { data: [...models] } + per-model info
|
|
356
383
|
Plugin->>Plugin: enrich models, hide non-chat (embedding/image/audio)
|
|
357
384
|
Plugin->>Plugin: format names, infer modalities + limits + pricing
|
|
358
|
-
Plugin->>OC:
|
|
385
|
+
Plugin->>OC: provider.transform(discovered models)
|
|
359
386
|
Plugin->>Cache: persist for next startup
|
|
360
387
|
end
|
|
361
388
|
Note over Plugin,Cache: on session.created, revalidate cache in<br/>the background (throttled to 5 min)
|
|
362
|
-
OC->>
|
|
389
|
+
OC->>Plugin: session.created event
|
|
390
|
+
Plugin->>LL: refresh model inventory
|
|
391
|
+
Plugin->>OC: provider.reload() when models changed
|
|
363
392
|
```
|
|
364
393
|
|
|
365
|
-
1. On OpenCode startup the `
|
|
366
|
-
2. If `
|
|
394
|
+
1. On OpenCode 2 startup the plugin's `setup` registers a provider transform. OpenCode 1 uses the legacy `config` hook.
|
|
395
|
+
2. If `providers.litellm` exists, its `settings.baseURL` is used. Otherwise common ports are probed — that probe is the only health check (3 s fail-fast per port).
|
|
367
396
|
3. With a configured `baseURL` the proxy is not contacted during startup unless the cache is cold; the discovery fetch itself fails fast if the proxy is unreachable.
|
|
368
|
-
4. **Fast path:** if a fresh on-disk cache exists (≤ 7 days old), its models are
|
|
397
|
+
4. **Fast path:** if a fresh on-disk cache exists (≤ 7 days old), its models are registered synchronously — startup does not wait on network discovery.
|
|
369
398
|
5. **Cold path:** `/v1/models` and `/v1/model/info` are fetched in parallel. Models are enriched with info metadata (`mode`, token limits, capability flags, per-token pricing — `/v1/models` omits these for database-defined models) and converted into OpenCode model entries with formatted `name`, inferred `modalities`, and `cost` (USD/1M tokens, converted from LiteLLM's USD/token). Non-chat models (embedding / image / audio) are excluded from the picker.
|
|
370
|
-
6. Discovered models are
|
|
371
|
-
7. On
|
|
399
|
+
6. Discovered models are added alongside user-defined models — never overwriting them — and persisted to the cache.
|
|
400
|
+
7. On `session.created`, the cache is revalidated in the background (throttled to once per 5 minutes). V2 calls `provider.reload()` when the inventory changes; V1 surfaces refreshed entries on the next OpenCode start. The cold path is capped by a 20 s timeout.
|
|
372
401
|
|
|
373
|
-
>
|
|
402
|
+
> The earlier Desktop limitation applied to OpenCode 1's config-hook path. OpenCode 2 registers models through its provider registry transform.
|
|
374
403
|
|
|
375
404
|
## 📋 Requirements
|
|
376
405
|
|
|
377
|
-
- [OpenCode](https://opencode.ai) ≥ 0.1.
|
|
406
|
+
- [OpenCode](https://opencode.ai) ≥ 2.0.14, or OpenCode 1.18.29+ for the legacy server entrypoint
|
|
378
407
|
- A running [LiteLLM](https://github.com/BerriAI/litellm) proxy:
|
|
379
408
|
```bash
|
|
380
409
|
pip install 'litellm[proxy]'
|
|
@@ -386,8 +415,8 @@ sequenceDiagram
|
|
|
386
415
|
|
|
387
416
|
| LiteLLM version | OpenCode version | Status |
|
|
388
417
|
|---|---|---|
|
|
389
|
-
| ≥ 1.40 | ≥ 0.1.
|
|
390
|
-
| 1.30 – 1.39 | ≥ 0.1.
|
|
418
|
+
| ≥ 1.40 | ≥ 2.0.14 or 1.18.29+ | ✅ Supported |
|
|
419
|
+
| 1.30 – 1.39 | ≥ 2.0.14 or 1.18.29+ | ⚠️ Should work (older `/v1/models` schema) |
|
|
391
420
|
| < 1.30 | any | ❌ Unsupported |
|
|
392
421
|
|
|
393
422
|
## ❓ FAQ
|
|
@@ -396,10 +425,9 @@ sequenceDiagram
|
|
|
396
425
|
<summary><b>Why doesn't a model appear in OpenCode after I add it to LiteLLM?</b></summary>
|
|
397
426
|
|
|
398
427
|
Once LiteLLM exposes the model (restart or hot-reload LiteLLM if you edited
|
|
399
|
-
its `config.yaml`), the plugin picks it up automatically
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
start** — no OpenCode config change needed. To force an immediate refetch,
|
|
428
|
+
its `config.yaml`), the plugin picks it up automatically. OpenCode 2 refreshes
|
|
429
|
+
the provider registry when a new session triggers a changed inventory; OpenCode
|
|
430
|
+
1 serves the refreshed cache on the next start. To force an immediate refetch,
|
|
403
431
|
delete the cache directory (`~/.cache/opencode-litellm/`, or
|
|
404
432
|
`$XDG_CACHE_HOME/opencode-litellm/`).
|
|
405
433
|
</details>
|
|
@@ -407,16 +435,15 @@ delete the cache directory (`~/.cache/opencode-litellm/`, or
|
|
|
407
435
|
<details>
|
|
408
436
|
<summary><b>Why do discovered models appear in the CLI but not OpenCode Desktop?</b></summary>
|
|
409
437
|
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
is being tracked in [issue #5](https://github.com/yuseferi/opencode-litellm/issues/5).
|
|
438
|
+
This was an OpenCode 1 config-hook limitation. OpenCode 2 registers discovered
|
|
439
|
+
models through the provider registry transform. If models are still missing in
|
|
440
|
+
OpenCode 2 Desktop, check the plugin log for provider discovery errors.
|
|
414
441
|
</details>
|
|
415
442
|
|
|
416
443
|
<details>
|
|
417
444
|
<summary><b>Can I use this with a remote LiteLLM proxy?</b></summary>
|
|
418
445
|
|
|
419
|
-
Yes. Set `
|
|
446
|
+
Yes. Set `providers.litellm.settings.baseURL` to your remote URL and optionally set `settings.apiKey`. Auto-detection only probes `localhost`, but explicit configuration works against any URL.
|
|
420
447
|
</details>
|
|
421
448
|
|
|
422
449
|
<details>
|
|
@@ -433,7 +460,7 @@ the proxy is reachable again.
|
|
|
433
460
|
<details>
|
|
434
461
|
<summary><b>Will my hand-curated model entries be overwritten?</b></summary>
|
|
435
462
|
|
|
436
|
-
No. The merge is additive: anything you've already defined under `
|
|
463
|
+
No. The merge is additive: anything you've already defined under `providers.litellm.models` is preserved. Discovered models are only added if their key isn't already present.
|
|
437
464
|
</details>
|
|
438
465
|
|
|
439
466
|
<details>
|
|
@@ -451,18 +478,19 @@ Yes — anything in your LiteLLM `model_list` shows up, including Ollama, Bedroc
|
|
|
451
478
|
<details>
|
|
452
479
|
<summary><b>My LiteLLM proxy is behind Cloudflare Access — how do I authenticate?</b></summary>
|
|
453
480
|
|
|
454
|
-
Cloudflare Access intercepts requests before they reach LiteLLM, so a plain `Authorization: Bearer` header isn't enough. Create a [Cloudflare Access Service Token](https://developers.cloudflare.com/cloudflare-one/identity/service-tokens/) and pass the credentials via `
|
|
481
|
+
Cloudflare Access intercepts requests before they reach LiteLLM, so a plain `Authorization: Bearer` header isn't enough. Create a [Cloudflare Access Service Token](https://developers.cloudflare.com/cloudflare-one/identity/service-tokens/) and pass the credentials via `providers.litellm.headers`:
|
|
455
482
|
|
|
456
483
|
```jsonc
|
|
457
484
|
{
|
|
458
|
-
"
|
|
485
|
+
"providers": {
|
|
459
486
|
"litellm": {
|
|
460
|
-
"
|
|
461
|
-
|
|
462
|
-
"
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
}
|
|
487
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
488
|
+
"settings": {
|
|
489
|
+
"baseURL": "https://litellm.your-company.com/v1"
|
|
490
|
+
},
|
|
491
|
+
"headers": {
|
|
492
|
+
"CF-Access-Client-Id": "{env:CF_ACCESS_CLIENT_ID}",
|
|
493
|
+
"CF-Access-Client-Secret": "{env:CF_ACCESS_CLIENT_SECRET}"
|
|
466
494
|
}
|
|
467
495
|
}
|
|
468
496
|
}
|
|
@@ -507,7 +535,8 @@ src/
|
|
|
507
535
|
│ ├── model-capabilities.ts # per-model capability flag overrides
|
|
508
536
|
│ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
|
|
509
537
|
└── plugin/
|
|
510
|
-
|
|
538
|
+
├── index.ts # OpenCode 1 server entry and shared discovery logic
|
|
539
|
+
└── v2.ts # OpenCode 2 definition, provider transform, event-driven reload
|
|
511
540
|
|
|
512
541
|
test/ # vitest suite for the pure logic
|
|
513
542
|
```
|
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.
|
|
4
|
+
"version": "1.4.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",
|
|
@@ -40,7 +40,8 @@
|
|
|
40
40
|
"provenance": true
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@opencode-ai/plugin": "^1.14.0"
|
|
43
|
+
"@opencode-ai/plugin": "^1.14.0",
|
|
44
|
+
"@opencode/plugin": "^2.0.14"
|
|
44
45
|
},
|
|
45
46
|
"devDependencies": {
|
|
46
47
|
"@semantic-release/changelog": "^7.0.0",
|
package/src/index.ts
CHANGED
package/src/plugin/index.ts
CHANGED
|
@@ -28,17 +28,30 @@ const CHAT_PROVIDER_ID = 'litellm'
|
|
|
28
28
|
// Covers the 3 s health check plus the parallel models/model-info fetch
|
|
29
29
|
// phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
|
|
30
30
|
// proxies aren't cut off by the overall cap either (issue #20).
|
|
31
|
-
const DISCOVERY_TIMEOUT_MS = Math.max(20000, getRequestTimeoutMs() + 5000)
|
|
31
|
+
export const DISCOVERY_TIMEOUT_MS = Math.max(20000, getRequestTimeoutMs() + 5000)
|
|
32
32
|
// Don't revalidate a baseURL's cache more often than this, so a burst
|
|
33
33
|
// of `session.created` events can't generate repeated discovery traffic.
|
|
34
34
|
const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000 // 5 minutes
|
|
35
35
|
|
|
36
36
|
type LogLevel = 'info' | 'warn' | 'error' | 'debug'
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
type LogDetails = {
|
|
39
|
+
service: string
|
|
40
|
+
level: LogLevel
|
|
41
|
+
message: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let logWriter: ((details: LogDetails) => void) | null = null
|
|
39
45
|
|
|
40
46
|
function initLogging(client: PluginInput['client']): void {
|
|
41
|
-
|
|
47
|
+
logWriter = (details) => {
|
|
48
|
+
void client.app.log({ body: details }).catch(() => {})
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** OpenCode 2 does not expose a server log method through its plugin context. */
|
|
53
|
+
export function initV2Logging(): void {
|
|
54
|
+
logWriter = null
|
|
42
55
|
}
|
|
43
56
|
|
|
44
57
|
/**
|
|
@@ -48,10 +61,8 @@ function initLogging(client: PluginInput['client']): void {
|
|
|
48
61
|
* (issue #15); client.app.log lands in OpenCode's log files instead.
|
|
49
62
|
*/
|
|
50
63
|
function log(level: LogLevel, message: string): void {
|
|
51
|
-
if (
|
|
52
|
-
|
|
53
|
-
.log({ body: { service: 'opencode-litellm', level, message } })
|
|
54
|
-
.catch(() => {})
|
|
64
|
+
if (logWriter) {
|
|
65
|
+
logWriter({ service: 'opencode-litellm', level, message })
|
|
55
66
|
return
|
|
56
67
|
}
|
|
57
68
|
// No client wired up (unit tests, unusual embedders) — fall back to
|
|
@@ -94,7 +105,7 @@ const refreshInFlight = new Set<string>()
|
|
|
94
105
|
* wins. Clears the timer either way so a resolved discovery can't keep
|
|
95
106
|
* a short-lived process alive waiting on a pending `setTimeout`.
|
|
96
107
|
*/
|
|
97
|
-
function withTimeout<T>(
|
|
108
|
+
export function withTimeout<T>(
|
|
98
109
|
promise: Promise<T>,
|
|
99
110
|
timeoutMs: number,
|
|
100
111
|
): Promise<T | null> {
|
|
@@ -109,7 +120,7 @@ function withTimeout<T>(
|
|
|
109
120
|
* Helper to determine if a provider ID or its configured options indicate
|
|
110
121
|
* compatibility with LiteLLM.
|
|
111
122
|
*/
|
|
112
|
-
function isLiteLLMProvider(
|
|
123
|
+
export function isLiteLLMProvider(
|
|
113
124
|
providerId: string,
|
|
114
125
|
options: Record<string, unknown>,
|
|
115
126
|
): boolean {
|
|
@@ -125,7 +136,7 @@ function isLiteLLMProvider(
|
|
|
125
136
|
/**
|
|
126
137
|
* Read `customHeaders` from a provider options block.
|
|
127
138
|
*/
|
|
128
|
-
function readCustomHeaders(
|
|
139
|
+
export function readCustomHeaders(
|
|
129
140
|
options: Record<string, unknown>,
|
|
130
141
|
): Record<string, string> | undefined {
|
|
131
142
|
const raw = options.customHeaders
|
|
@@ -145,7 +156,7 @@ function readCustomHeaders(
|
|
|
145
156
|
* several OpenCode providers). Non-string entries are dropped; an empty
|
|
146
157
|
* result means "don't filter".
|
|
147
158
|
*/
|
|
148
|
-
function readModelFilters(options: Record<string, unknown>): ModelFilters {
|
|
159
|
+
export function readModelFilters(options: Record<string, unknown>): ModelFilters {
|
|
149
160
|
const readPatterns = (raw: unknown): string[] | undefined => {
|
|
150
161
|
if (!Array.isArray(raw)) return undefined
|
|
151
162
|
const out = raw.filter((v): v is string => typeof v === 'string')
|
|
@@ -157,7 +168,7 @@ function readModelFilters(options: Record<string, unknown>): ModelFilters {
|
|
|
157
168
|
}
|
|
158
169
|
}
|
|
159
170
|
|
|
160
|
-
function readFormatModelNames(options: Record<string, unknown>): boolean {
|
|
171
|
+
export function readFormatModelNames(options: Record<string, unknown>): boolean {
|
|
161
172
|
return options.formatModelNames !== false
|
|
162
173
|
}
|
|
163
174
|
|
|
@@ -237,8 +248,8 @@ export function toConfigModel(
|
|
|
237
248
|
output: model.max_output_tokens ?? 0,
|
|
238
249
|
}
|
|
239
250
|
}
|
|
240
|
-
if (model.supports_function_calling) {
|
|
241
|
-
entry.tool_call =
|
|
251
|
+
if (model.supports_function_calling != null) {
|
|
252
|
+
entry.tool_call = model.supports_function_calling
|
|
242
253
|
}
|
|
243
254
|
if (model.supports_reasoning) {
|
|
244
255
|
entry.reasoning = true
|
|
@@ -267,9 +278,13 @@ export function toConfigModel(
|
|
|
267
278
|
if (model.supports_vision) input.push('image')
|
|
268
279
|
if (model.supports_pdf_input) input.push('pdf')
|
|
269
280
|
if (model.supports_audio_input) input.push('audio')
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
281
|
+
// LiteLLM often omits capability flags for database-defined models.
|
|
282
|
+
// Do not omit `modalities` in that case: OpenCode's fallback for an
|
|
283
|
+
// unknown custom model includes image input, which makes text-only
|
|
284
|
+
// llama.cpp routes receive image parts and fail with "image input is
|
|
285
|
+
// not supported". Text-only is the safe default until a proxy reports
|
|
286
|
+
// a positive capability.
|
|
287
|
+
entry.modalities = { input, output: ['text'] }
|
|
273
288
|
entry.variants = info?.supports_reasoning_efforts?.length
|
|
274
289
|
? Object.fromEntries(
|
|
275
290
|
info.supports_reasoning_efforts.map((effort) => [
|
|
@@ -295,7 +310,7 @@ export function toConfigModel(
|
|
|
295
310
|
* Returns `null` when the proxy is unreachable/unauthorized or exposes
|
|
296
311
|
* no models, so callers can distinguish "no data" from "empty result".
|
|
297
312
|
*/
|
|
298
|
-
async function discoverModels(
|
|
313
|
+
export async function discoverModels(
|
|
299
314
|
baseURL: string,
|
|
300
315
|
apiKey: string | undefined,
|
|
301
316
|
customHeaders: Record<string, string> | undefined,
|
package/src/plugin/v2.ts
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
import { Model, Plugin, Provider } from '@opencode/plugin'
|
|
2
|
+
import type { Context } from '@opencode/plugin/promise/plugin'
|
|
3
|
+
import type { PluginInput } from '@opencode-ai/plugin'
|
|
4
|
+
import {
|
|
5
|
+
DISCOVERY_TIMEOUT_MS,
|
|
6
|
+
discoverModels,
|
|
7
|
+
initV2Logging,
|
|
8
|
+
isLiteLLMProvider,
|
|
9
|
+
readCustomHeaders,
|
|
10
|
+
readFormatModelNames,
|
|
11
|
+
readModelFilters,
|
|
12
|
+
withTimeout,
|
|
13
|
+
LiteLLMPlugin,
|
|
14
|
+
} from './index'
|
|
15
|
+
import {
|
|
16
|
+
buildCacheKey,
|
|
17
|
+
readModelCache,
|
|
18
|
+
readModelCacheSavedAt,
|
|
19
|
+
writeModelCache,
|
|
20
|
+
} from '../utils/model-cache'
|
|
21
|
+
import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
|
|
22
|
+
import { parseModelCapabilities } from '../utils/model-capabilities'
|
|
23
|
+
import type { ModelCapabilities } from '../utils/model-capabilities'
|
|
24
|
+
import type { ModelFilters } from '../utils/model-filter'
|
|
25
|
+
|
|
26
|
+
const CHAT_PROVIDER_ID = 'litellm'
|
|
27
|
+
const OPENAI_COMPATIBLE_PACKAGE = '@opencode/ai/providers/openai-compatible'
|
|
28
|
+
const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000
|
|
29
|
+
|
|
30
|
+
type ProviderInfo = Awaited<ReturnType<Context['provider']['list']>>['data'][number]
|
|
31
|
+
|
|
32
|
+
interface ProviderSource {
|
|
33
|
+
id: string
|
|
34
|
+
name: string
|
|
35
|
+
activation: ProviderInfo['activation']
|
|
36
|
+
package: string
|
|
37
|
+
settings: Record<string, unknown>
|
|
38
|
+
headers: Record<string, string>
|
|
39
|
+
integrationID?: string
|
|
40
|
+
usesConnectionCredential: boolean
|
|
41
|
+
baseURL: string
|
|
42
|
+
apiKey?: string
|
|
43
|
+
customHeaders?: Record<string, string>
|
|
44
|
+
credentialReloadRequired: boolean
|
|
45
|
+
refreshRequired: boolean
|
|
46
|
+
filters: ModelFilters
|
|
47
|
+
capabilities: ModelCapabilities
|
|
48
|
+
formatModelNames: boolean
|
|
49
|
+
cacheKey: string
|
|
50
|
+
models: Model.Info[]
|
|
51
|
+
/**
|
|
52
|
+
* Model ids this plugin injected into the provider registry (as opposed
|
|
53
|
+
* to ids the user curated in config). Only these are eligible to be
|
|
54
|
+
* removed when a later refresh no longer discovers them.
|
|
55
|
+
*/
|
|
56
|
+
ownedModelIds: Set<string>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function asRecord(value: unknown): Record<string, unknown> {
|
|
60
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
61
|
+
? (value as Record<string, unknown>)
|
|
62
|
+
: {}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readHeaders(value: unknown): Record<string, string> {
|
|
66
|
+
const result: Record<string, string> = {}
|
|
67
|
+
for (const [key, header] of Object.entries(asRecord(value))) {
|
|
68
|
+
if (typeof header === 'string') result[key] = header
|
|
69
|
+
}
|
|
70
|
+
return result
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function readString(value: unknown): string | undefined {
|
|
74
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function numberOrZero(value: unknown): number {
|
|
78
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function toProviderModels(
|
|
82
|
+
providerID: string,
|
|
83
|
+
entries: Record<string, unknown>,
|
|
84
|
+
): Model.Info[] {
|
|
85
|
+
const provider = Provider.ID.make(providerID)
|
|
86
|
+
|
|
87
|
+
return Object.entries(entries).flatMap(([modelID, value]) => {
|
|
88
|
+
const entry = asRecord(value)
|
|
89
|
+
if (Object.keys(entry).length === 0) return []
|
|
90
|
+
|
|
91
|
+
const limit = asRecord(entry.limit)
|
|
92
|
+
const defaults = Model.Info.default(provider, Model.ID.make(modelID))
|
|
93
|
+
const modalities = asRecord(entry.modalities)
|
|
94
|
+
const input = Array.isArray(modalities.input)
|
|
95
|
+
? modalities.input.filter((item): item is string => typeof item === 'string')
|
|
96
|
+
: defaults.capabilities.input
|
|
97
|
+
const output = Array.isArray(modalities.output)
|
|
98
|
+
? modalities.output.filter((item): item is string => typeof item === 'string')
|
|
99
|
+
: defaults.capabilities.output
|
|
100
|
+
|
|
101
|
+
const rawCost = asRecord(entry.cost)
|
|
102
|
+
const cost: Model.Info['cost'] =
|
|
103
|
+
typeof rawCost.input === 'number' || typeof rawCost.output === 'number'
|
|
104
|
+
? [
|
|
105
|
+
{
|
|
106
|
+
input: numberOrZero(rawCost.input) as Model.Info['cost'][number]['input'],
|
|
107
|
+
output: numberOrZero(rawCost.output) as Model.Info['cost'][number]['output'],
|
|
108
|
+
cache: {
|
|
109
|
+
read: numberOrZero(rawCost.cache_read) as Model.Info['cost'][number]['cache']['read'],
|
|
110
|
+
write: numberOrZero(rawCost.cache_write) as Model.Info['cost'][number]['cache']['write'],
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
]
|
|
114
|
+
: []
|
|
115
|
+
|
|
116
|
+
const rawVariants = asRecord(entry.variants)
|
|
117
|
+
const variants = Object.entries(rawVariants).map(([id, settings]) => ({
|
|
118
|
+
id: id as Model.VariantID,
|
|
119
|
+
settings: asRecord(settings),
|
|
120
|
+
})) as Model.Info['variants']
|
|
121
|
+
return [
|
|
122
|
+
{
|
|
123
|
+
...defaults,
|
|
124
|
+
name: readString(entry.name) ?? modelID,
|
|
125
|
+
limit: {
|
|
126
|
+
context: numberOrDefault(limit.context, defaults.limit.context),
|
|
127
|
+
output: numberOrDefault(limit.output, defaults.limit.output),
|
|
128
|
+
},
|
|
129
|
+
capabilities: {
|
|
130
|
+
tools: entry.tool_call === undefined ? defaults.capabilities.tools : entry.tool_call === true,
|
|
131
|
+
input,
|
|
132
|
+
output,
|
|
133
|
+
},
|
|
134
|
+
cost,
|
|
135
|
+
variants,
|
|
136
|
+
},
|
|
137
|
+
]
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function numberOrDefault(value: unknown, fallback: number): number {
|
|
142
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
143
|
+
? value
|
|
144
|
+
: fallback
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Merge freshly discovered models into a provider's current model set.
|
|
149
|
+
*
|
|
150
|
+
* Previously-discovered ids owned by this plugin are replaced/removed so a
|
|
151
|
+
* refresh reflects LiteLLM's current inventory; ids the user curated
|
|
152
|
+
* themselves are never removed. Returns the merged list plus the set of
|
|
153
|
+
* ids the plugin now owns.
|
|
154
|
+
*/
|
|
155
|
+
function mergeProviderModels(
|
|
156
|
+
configured: Iterable<Model.Info>,
|
|
157
|
+
discovered: readonly Model.Info[],
|
|
158
|
+
owned: ReadonlySet<string>,
|
|
159
|
+
): { models: Model.Info[]; owned: Set<string> } {
|
|
160
|
+
const discoveredIds = new Set(discovered.map((model) => model.id))
|
|
161
|
+
const result = new Map<string, Model.Info>()
|
|
162
|
+
const nextOwned = new Set<string>()
|
|
163
|
+
|
|
164
|
+
for (const model of configured) {
|
|
165
|
+
// Drop plugin-injected models that LiteLLM no longer returns; curated
|
|
166
|
+
// models are not in `owned`, so they always survive.
|
|
167
|
+
if (owned.has(model.id) && !discoveredIds.has(model.id)) continue
|
|
168
|
+
result.set(model.id, model)
|
|
169
|
+
if (owned.has(model.id)) nextOwned.add(model.id)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
for (const model of discovered) {
|
|
173
|
+
if (!result.has(model.id)) {
|
|
174
|
+
result.set(model.id, model)
|
|
175
|
+
nextOwned.add(model.id)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { models: [...result.values()], owned: nextOwned }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function runtimeSettings(source: ProviderSource): Record<string, unknown> {
|
|
183
|
+
const settings = { ...source.settings }
|
|
184
|
+
for (const key of [
|
|
185
|
+
'litellm',
|
|
186
|
+
'litellmCompatible',
|
|
187
|
+
'litellm-compatible',
|
|
188
|
+
'litellm_compatible',
|
|
189
|
+
'customHeaders',
|
|
190
|
+
'includeModels',
|
|
191
|
+
'excludeModels',
|
|
192
|
+
'modelCapabilities',
|
|
193
|
+
'formatModelNames',
|
|
194
|
+
'providerID',
|
|
195
|
+
]) {
|
|
196
|
+
delete settings[key]
|
|
197
|
+
}
|
|
198
|
+
settings.baseURL = `${source.baseURL}/v1`
|
|
199
|
+
// Connection-managed credentials are resolved only for discovery. They
|
|
200
|
+
// must not be materialized into provider settings: OpenCode owns
|
|
201
|
+
// credential injection for integrated providers. Explicit credentials
|
|
202
|
+
// (provider settings, plugin options, env) still flow through.
|
|
203
|
+
if (source.apiKey && !source.usesConnectionCredential) settings.apiKey = source.apiKey
|
|
204
|
+
return settings
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function makeProviderSource(
|
|
208
|
+
context: Context,
|
|
209
|
+
provider: ProviderInfo | undefined,
|
|
210
|
+
pluginOptions: Record<string, unknown>,
|
|
211
|
+
): Promise<ProviderSource | null> {
|
|
212
|
+
const id = provider?.id ?? readString(pluginOptions.providerID) ?? CHAT_PROVIDER_ID
|
|
213
|
+
const providerSettings = asRecord(provider?.settings)
|
|
214
|
+
const settings = { ...pluginOptions, ...providerSettings }
|
|
215
|
+
const configuredBaseURL = readString(settings.baseURL)
|
|
216
|
+
const customHeaders = {
|
|
217
|
+
...readHeaders(pluginOptions.customHeaders),
|
|
218
|
+
...readCustomHeaders(settings),
|
|
219
|
+
...readHeaders(provider?.headers),
|
|
220
|
+
}
|
|
221
|
+
let connectedApiKey: string | undefined
|
|
222
|
+
if (provider?.integrationID) {
|
|
223
|
+
try {
|
|
224
|
+
const connection = await context.integration.connection.active(provider.integrationID)
|
|
225
|
+
const credential = connection
|
|
226
|
+
? await context.integration.connection.resolve(connection)
|
|
227
|
+
: undefined
|
|
228
|
+
if (credential?.type === 'key') connectedApiKey = credential.key
|
|
229
|
+
} catch {
|
|
230
|
+
// A missing or unrelated integration does not prevent other auth sources.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const configuredApiKey =
|
|
234
|
+
readString(providerSettings.apiKey) ??
|
|
235
|
+
readString(pluginOptions.apiKey) ??
|
|
236
|
+
process.env.LITELLM_API_KEY ??
|
|
237
|
+
process.env.LITELLM_MASTER_KEY
|
|
238
|
+
const usesConnectionCredential = !configuredApiKey && Boolean(provider?.integrationID)
|
|
239
|
+
const apiKey = configuredApiKey ?? connectedApiKey
|
|
240
|
+
const filters = readModelFilters(settings)
|
|
241
|
+
const capabilities = parseModelCapabilities(settings.modelCapabilities)
|
|
242
|
+
const formatModelNames = readFormatModelNames(settings)
|
|
243
|
+
const detectedBaseURL = configuredBaseURL
|
|
244
|
+
? normalizeBaseURL(configuredBaseURL)
|
|
245
|
+
: await autoDetectLiteLLM(apiKey, customHeaders)
|
|
246
|
+
|
|
247
|
+
if (!detectedBaseURL) {
|
|
248
|
+
return null
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const baseURL = normalizeBaseURL(detectedBaseURL)
|
|
252
|
+
const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
|
|
253
|
+
formatModelNames,
|
|
254
|
+
})
|
|
255
|
+
let entries = readModelCache(cacheKey)
|
|
256
|
+
|
|
257
|
+
if (!entries || Object.keys(entries).length === 0) {
|
|
258
|
+
entries = await withTimeout(
|
|
259
|
+
discoverModels(
|
|
260
|
+
baseURL,
|
|
261
|
+
apiKey,
|
|
262
|
+
customHeaders,
|
|
263
|
+
id,
|
|
264
|
+
filters,
|
|
265
|
+
capabilities,
|
|
266
|
+
formatModelNames,
|
|
267
|
+
),
|
|
268
|
+
DISCOVERY_TIMEOUT_MS,
|
|
269
|
+
)
|
|
270
|
+
if (entries && Object.keys(entries).length > 0) writeModelCache(cacheKey, entries)
|
|
271
|
+
} else {
|
|
272
|
+
logInfo(
|
|
273
|
+
`[opencode-litellm] Loaded ${Object.keys(entries).length} models from cache for provider "${id}" (${baseURL}); refresh happens in the background on new sessions.`,
|
|
274
|
+
)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return {
|
|
278
|
+
id,
|
|
279
|
+
name: provider?.name || 'LiteLLM (proxy)',
|
|
280
|
+
activation: provider?.activation ?? 'enabled',
|
|
281
|
+
package: provider?.package || OPENAI_COMPATIBLE_PACKAGE,
|
|
282
|
+
settings,
|
|
283
|
+
headers: customHeaders,
|
|
284
|
+
integrationID: provider?.integrationID,
|
|
285
|
+
usesConnectionCredential,
|
|
286
|
+
credentialReloadRequired: false,
|
|
287
|
+
refreshRequired: false,
|
|
288
|
+
baseURL,
|
|
289
|
+
apiKey,
|
|
290
|
+
customHeaders: Object.keys(customHeaders).length > 0 ? customHeaders : undefined,
|
|
291
|
+
filters,
|
|
292
|
+
capabilities,
|
|
293
|
+
formatModelNames,
|
|
294
|
+
cacheKey,
|
|
295
|
+
models: toProviderModels(id, entries ?? {}),
|
|
296
|
+
ownedModelIds: new Set<string>(),
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function logInfo(message: string): void {
|
|
301
|
+
console.log(message)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function refreshProviderSource(
|
|
305
|
+
context: Context,
|
|
306
|
+
source: ProviderSource,
|
|
307
|
+
inFlight: Map<string, Promise<void>>,
|
|
308
|
+
): Promise<void> {
|
|
309
|
+
const activeRefresh = inFlight.get(source.cacheKey)
|
|
310
|
+
if (activeRefresh) {
|
|
311
|
+
await activeRefresh
|
|
312
|
+
if (source.refreshRequired) await refreshProviderSource(context, source, inFlight)
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const savedAt = readModelCacheSavedAt(source.cacheKey)
|
|
317
|
+
if (
|
|
318
|
+
!source.refreshRequired &&
|
|
319
|
+
savedAt !== null &&
|
|
320
|
+
Date.now() - savedAt < REFRESH_MIN_INTERVAL_MS
|
|
321
|
+
) {
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const apiKey = source.apiKey
|
|
326
|
+
let refresh!: Promise<void>
|
|
327
|
+
refresh = (async () => {
|
|
328
|
+
try {
|
|
329
|
+
const entries = await withTimeout(
|
|
330
|
+
discoverModels(
|
|
331
|
+
source.baseURL,
|
|
332
|
+
apiKey,
|
|
333
|
+
source.customHeaders,
|
|
334
|
+
source.id,
|
|
335
|
+
source.filters,
|
|
336
|
+
source.capabilities,
|
|
337
|
+
source.formatModelNames,
|
|
338
|
+
),
|
|
339
|
+
DISCOVERY_TIMEOUT_MS,
|
|
340
|
+
)
|
|
341
|
+
if (!entries || Object.keys(entries).length === 0 || apiKey !== source.apiKey) return
|
|
342
|
+
|
|
343
|
+
const models = toProviderModels(source.id, entries)
|
|
344
|
+
if (JSON.stringify(models) === JSON.stringify(source.models)) {
|
|
345
|
+
writeModelCache(source.cacheKey, entries)
|
|
346
|
+
source.refreshRequired = false
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const previousModels = source.models
|
|
351
|
+
source.models = models
|
|
352
|
+
try {
|
|
353
|
+
await context.provider.reload()
|
|
354
|
+
} catch (error) {
|
|
355
|
+
source.models = previousModels
|
|
356
|
+
throw error
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
writeModelCache(source.cacheKey, entries)
|
|
360
|
+
source.refreshRequired = false
|
|
361
|
+
logInfo(
|
|
362
|
+
`[opencode-litellm] Refreshed ${models.length} models for provider "${source.id}"; the provider registry was reloaded.`,
|
|
363
|
+
)
|
|
364
|
+
} catch (error) {
|
|
365
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
366
|
+
logInfo(`[opencode-litellm] Background refresh failed for provider "${source.id}": ${message}`)
|
|
367
|
+
} finally {
|
|
368
|
+
if (inFlight.get(source.cacheKey) === refresh) inFlight.delete(source.cacheKey)
|
|
369
|
+
}
|
|
370
|
+
})()
|
|
371
|
+
inFlight.set(source.cacheKey, refresh)
|
|
372
|
+
await refresh
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function refreshConnectionCredential(
|
|
376
|
+
context: Context,
|
|
377
|
+
source: ProviderSource,
|
|
378
|
+
): Promise<boolean> {
|
|
379
|
+
if (!source.integrationID || !source.usesConnectionCredential) return false
|
|
380
|
+
|
|
381
|
+
try {
|
|
382
|
+
const connection = await context.integration.connection.active(source.integrationID)
|
|
383
|
+
const credential = connection
|
|
384
|
+
? await context.integration.connection.resolve(connection)
|
|
385
|
+
: undefined
|
|
386
|
+
const apiKey = credential?.type === 'key' ? credential.key : undefined
|
|
387
|
+
if (apiKey === source.apiKey) return false
|
|
388
|
+
source.apiKey = apiKey
|
|
389
|
+
return true
|
|
390
|
+
} catch (error) {
|
|
391
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
392
|
+
logInfo(`[opencode-litellm] Could not refresh credentials for provider "${source.id}": ${message}`)
|
|
393
|
+
return false
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function refreshProviderSources(
|
|
398
|
+
context: Context,
|
|
399
|
+
sources: ProviderSource[],
|
|
400
|
+
inFlight: Map<string, Promise<void>>,
|
|
401
|
+
): Promise<void> {
|
|
402
|
+
const pendingCredentialReload = sources.filter((source) => source.credentialReloadRequired)
|
|
403
|
+
if (pendingCredentialReload.length > 0) {
|
|
404
|
+
try {
|
|
405
|
+
await context.provider.reload()
|
|
406
|
+
for (const source of pendingCredentialReload) source.credentialReloadRequired = false
|
|
407
|
+
} catch (error) {
|
|
408
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
409
|
+
logInfo(`[opencode-litellm] Could not reload providers after a credential switch: ${message}`)
|
|
410
|
+
return
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
await Promise.all(sources.map((source) => refreshProviderSource(context, source, inFlight)))
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const definition = Plugin.define({
|
|
418
|
+
id: 'opencode-litellm',
|
|
419
|
+
async setup(context) {
|
|
420
|
+
initV2Logging()
|
|
421
|
+
|
|
422
|
+
const pluginOptions = asRecord(context.options)
|
|
423
|
+
let providers: ProviderInfo[] = []
|
|
424
|
+
try {
|
|
425
|
+
providers = (await context.provider.list()).data
|
|
426
|
+
} catch (error) {
|
|
427
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
428
|
+
logInfo(`[opencode-litellm] Could not read configured providers: ${message}`)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const matchingProviders = providers.filter((provider) =>
|
|
432
|
+
isLiteLLMProvider(provider.id, asRecord(provider.settings)),
|
|
433
|
+
)
|
|
434
|
+
const candidates: Array<ProviderInfo | undefined> = matchingProviders.length
|
|
435
|
+
? matchingProviders
|
|
436
|
+
: [undefined]
|
|
437
|
+
const sources: ProviderSource[] = []
|
|
438
|
+
|
|
439
|
+
for (const candidate of candidates) {
|
|
440
|
+
const source = await makeProviderSource(context, candidate, pluginOptions)
|
|
441
|
+
if (source) sources.push(source)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (sources.length === 0) {
|
|
445
|
+
logInfo(
|
|
446
|
+
'[opencode-litellm] No LiteLLM proxy found. Configure providers.litellm.settings.baseURL or start LiteLLM on port 4000/8000/8080.',
|
|
447
|
+
)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const providerRegistration = await context.provider.transform((editor) => {
|
|
451
|
+
for (const source of sources) {
|
|
452
|
+
const current = editor.get(source.id)
|
|
453
|
+
if (current) {
|
|
454
|
+
editor.update(source.id, (provider) => {
|
|
455
|
+
provider.package = source.package
|
|
456
|
+
provider.name = source.name
|
|
457
|
+
const settings = {
|
|
458
|
+
...(provider.settings ?? {}),
|
|
459
|
+
...runtimeSettings(source),
|
|
460
|
+
}
|
|
461
|
+
// Integration-managed credentials never belong in settings,
|
|
462
|
+
// even if a stale apiKey was materialized there previously.
|
|
463
|
+
if (source.usesConnectionCredential) delete settings.apiKey
|
|
464
|
+
provider.settings = settings
|
|
465
|
+
if (Object.keys(source.headers).length > 0) {
|
|
466
|
+
provider.headers = { ...provider.headers, ...source.headers }
|
|
467
|
+
}
|
|
468
|
+
})
|
|
469
|
+
const merged = mergeProviderModels(
|
|
470
|
+
current.models.values(),
|
|
471
|
+
source.models,
|
|
472
|
+
source.ownedModelIds,
|
|
473
|
+
)
|
|
474
|
+
source.ownedModelIds = merged.owned
|
|
475
|
+
editor.models.set(source.id, merged.models)
|
|
476
|
+
} else {
|
|
477
|
+
source.ownedModelIds = new Set(source.models.map((model) => model.id))
|
|
478
|
+
editor.add({
|
|
479
|
+
info: {
|
|
480
|
+
...Provider.Info.empty(Provider.ID.make(source.id)),
|
|
481
|
+
name: source.name,
|
|
482
|
+
activation: source.activation,
|
|
483
|
+
package: source.package,
|
|
484
|
+
settings: runtimeSettings(source),
|
|
485
|
+
headers: source.headers,
|
|
486
|
+
},
|
|
487
|
+
models: source.models,
|
|
488
|
+
})
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
const controller = new AbortController()
|
|
494
|
+
const inFlight = new Map<string, Promise<void>>()
|
|
495
|
+
void (async () => {
|
|
496
|
+
try {
|
|
497
|
+
for await (const event of context.event.subscribe({ signal: controller.signal })) {
|
|
498
|
+
if (event.type === 'credential.switched') {
|
|
499
|
+
const changedSources = (await Promise.all(
|
|
500
|
+
sources
|
|
501
|
+
.filter((source) => source.integrationID === event.data.integrationID)
|
|
502
|
+
.map(async (source) =>
|
|
503
|
+
(await refreshConnectionCredential(context, source)) ? source : undefined,
|
|
504
|
+
),
|
|
505
|
+
)).filter((source): source is ProviderSource => source !== undefined)
|
|
506
|
+
for (const source of changedSources) {
|
|
507
|
+
source.credentialReloadRequired = true
|
|
508
|
+
source.refreshRequired = true
|
|
509
|
+
}
|
|
510
|
+
if (changedSources.length > 0) {
|
|
511
|
+
await refreshProviderSources(context, changedSources, inFlight)
|
|
512
|
+
}
|
|
513
|
+
continue
|
|
514
|
+
}
|
|
515
|
+
if (event.type !== 'session.created') continue
|
|
516
|
+
void refreshProviderSources(context, sources, inFlight)
|
|
517
|
+
}
|
|
518
|
+
} catch (error) {
|
|
519
|
+
if (controller.signal.aborted) return
|
|
520
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
521
|
+
logInfo(`[opencode-litellm] Event subscription failed: ${message}`)
|
|
522
|
+
}
|
|
523
|
+
})()
|
|
524
|
+
|
|
525
|
+
return async () => {
|
|
526
|
+
controller.abort()
|
|
527
|
+
await providerRegistration.dispose()
|
|
528
|
+
}
|
|
529
|
+
},
|
|
530
|
+
})
|
|
531
|
+
|
|
532
|
+
export const LiteLLMPluginDefinition = {
|
|
533
|
+
...definition,
|
|
534
|
+
// OpenCode 1.18.29+ accepts object-form plugin exports with a server().
|
|
535
|
+
async server(input: PluginInput) {
|
|
536
|
+
return LiteLLMPlugin(input)
|
|
537
|
+
},
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export default LiteLLMPluginDefinition
|
package/src/utils/litellm-api.ts
CHANGED
|
@@ -172,11 +172,13 @@ export async function discoverLiteLLMModelInfo(
|
|
|
172
172
|
}
|
|
173
173
|
|
|
174
174
|
/**
|
|
175
|
-
*
|
|
176
|
-
* The default `litellm --port` is 4000,
|
|
177
|
-
* and 8080 is a common reverse-proxy default.
|
|
175
|
+
* Use an explicit LITELLM_BASE_URL when set; otherwise try the most common
|
|
176
|
+
* ports. The default `litellm --port` is 4000, with 8000 and 8080 also common.
|
|
178
177
|
*/
|
|
179
178
|
export async function autoDetectLiteLLM(apiKey?: string, customHeaders?: Record<string, string>): Promise<string | null> {
|
|
179
|
+
const configuredBaseURL = process.env.LITELLM_BASE_URL?.trim()
|
|
180
|
+
if (configuredBaseURL) return normalizeBaseURL(configuredBaseURL)
|
|
181
|
+
|
|
180
182
|
const commonPorts = [4000, 8000, 8080]
|
|
181
183
|
for (const port of commonPorts) {
|
|
182
184
|
const baseURL = `http://localhost:${port}`
|
package/src/utils/model-cache.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { join } from 'node:path'
|
|
|
8
8
|
* from older plugin versions are ignored rather than deserialized into
|
|
9
9
|
* an incompatible structure.
|
|
10
10
|
*/
|
|
11
|
-
const CACHE_VERSION =
|
|
11
|
+
const CACHE_VERSION = 2
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* Maximum age of a cache entry before it's treated as a miss. Without a
|