opencode-plugin-litellm 0.11.1 → 1.0.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
@@ -21,6 +21,8 @@
21
21
  Auto-detect a running LiteLLM proxy, pull every model from `/v1/models`, and register them in OpenCode.
22
22
  **No model lists to hand-maintain. No restart loops. No surprises.**
23
23
 
24
+ <img src="https://raw.githubusercontent.com/yuseferi/opencode-litellm/main/assets/architecture.svg" alt="How opencode-litellm works: OpenCode loads models through the config hook, the plugin discovers them from the LiteLLM proxy and caches them on disk for instant startup" width="100%" />
25
+
24
26
  [Quickstart](#-quickstart) · [Configuration](#%EF%B8%8F-configuration) · [How it works](#-how-it-works) · [FAQ](#-faq) · [Contributing](./CONTRIBUTING.md)
25
27
 
26
28
  </div>
@@ -38,14 +40,8 @@ Maintaining a `models` block in `opencode.json` for every model your LiteLLM pro
38
40
 
39
41
  ## 🚀 Quickstart
40
42
 
41
- ```bash
42
- # 1. Install
43
- npm install opencode-plugin-litellm
44
- # or: bun add opencode-plugin-litellm
45
- ```
46
-
47
43
  ```jsonc
48
- // 2. Add to opencode.json
44
+ // 1. Add to opencode.json — OpenCode installs the plugin from npm automatically
49
45
  {
50
46
  "$schema": "https://opencode.ai/config.json",
51
47
  "plugin": ["opencode-plugin-litellm@latest"],
@@ -61,10 +57,10 @@ npm install opencode-plugin-litellm
61
57
  ```
62
58
 
63
59
  ```bash
64
- # 3. Start LiteLLM (if it isn't already)
60
+ # 2. Start LiteLLM (if it isn't already)
65
61
  litellm --config config.yaml --port 4000
66
62
 
67
- # 4. Run OpenCode — every model in your LiteLLM model_list is now available.
63
+ # 3. Run OpenCode — every model in your LiteLLM model_list is now available.
68
64
  opencode
69
65
  ```
70
66
 
@@ -74,12 +70,12 @@ opencode
74
70
  |---|---|
75
71
  | 🔍 **Auto-detection** | Probes `localhost:4000`, `:8000`, `:8080` and adopts the first responsive proxy. |
76
72
  | 📡 **Dynamic discovery** | Queries `/v1/models` so your OpenCode model picker always reflects your live `model_list`. |
77
- | 🏷️ **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`. |
73
+ | ⚡ **Instant startup (SWR)** | Discovered models are cached on disk and loaded synchronously — startup never blocks on the network. A background refresh on new sessions keeps the cache fresh; entries expire after 7 days. |
74
+ | 🏷️ **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`. |
78
75
  | 🧠 **Modality-aware** | Enriches `/v1/models` entries with `/v1/model/info` (`mode`, token limits, capability flags) and hides embedding / image / audio models from the picker. |
79
- | 💵 **Real pricing** | Maps `input_cost_per_token` / `output_cost_per_token` 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. |
80
- | 🧪 **Reasoning-aware routing** | Auto-routes `gpt-5*` / `o1`/`o3`/`o4*` models through a sibling `litellm-responses` provider that uses `/v1/responses`, so tools + `reasoning_effort` actually work. Override per model via `responsesApiModels` / `chatApiModels`. |
81
- | 🏢 **Provider extraction** | Pulls `litellm_provider` (or the `provider/model` prefix) into `organizationOwner` so models group correctly in the UI. |
82
- | 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY` env vars or `provider.litellm.options.apiKey`. |
76
+ | 💵 **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
+ | 🧩 **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` env vars, `provider.litellm.options.apiKey`, or the key you stored via OpenCode's `/connect`. |
83
79
  | 🌐 **Gateway-friendly** | Supports `customHeaders` for proxies behind Cloudflare Access or other API gateways requiring extra HTTP headers. |
84
80
  | ⏱️ **Non-blocking startup** | Health checks fail fast (3 s); discovery fetches are capped at **15 s** for slow remote proxies. Repeat config-hook invocations are a no-op. |
85
81
  | 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
@@ -183,18 +179,10 @@ If you want to rename a model in the picker, pin its `organizationOwner`, or oth
183
179
 
184
180
  Here, `openai/gpt-4o` keeps your custom name; every other model from the proxy is still discovered and added automatically.
185
181
 
186
- ### Reasoning models (gpt-5, o1/o3/o4)
187
-
188
- OpenAI's reasoning-tier models reject requests that combine `reasoning_effort`
189
- with function tools when sent to `/v1/chat/completions`. The OpenAI Responses
190
- API (`/v1/responses`) has no such restriction, so the plugin routes those
191
- models through a **second provider entry** named `litellm-responses` that
192
- uses an SDK speaking the Responses API.
182
+ ### Reasoning models and effort variants
193
183
 
194
- You don't need to do anything for the default behaviour — the plugin
195
- detects reasoning-tier models from their id (`gpt-5*`, `o1*`, `o3*`,
196
- `o4*`) and from LiteLLM's `mode === 'responses'` field, and creates the
197
- sibling provider lazily.
184
+ All discovered models — reasoning-tier included — register under your single
185
+ LiteLLM provider and are invoked through `/v1/chat/completions`.
198
186
 
199
187
  If LiteLLM reports per-model reasoning-effort support (e.g.
200
188
  `supports_low_reasoning_effort`, `supports_medium_reasoning_effort`,
@@ -203,39 +191,13 @@ surfaces those as OpenCode variants under the discovered model. Each variant
203
191
  sets `reasoningEffort` to the reported level, so you can switch between
204
192
  effort levels from the model picker without hand-curating every entry.
205
193
 
206
- To override the routing per model:
207
-
208
- ```jsonc
209
- {
210
- "provider": {
211
- "litellm": {
212
- "options": {
213
- "baseURL": "http://localhost:4000/v1",
214
-
215
- // "auto" (default) | "chat" | "responses"
216
- "transport": "auto",
217
-
218
- // Force these into /v1/responses (highest precedence)
219
- "responsesApiModels": ["gpt-5-4-high", "my-custom-reasoning-model"],
220
-
221
- // Force these into /v1/chat/completions
222
- "chatApiModels": ["o1-mini-cheap"]
223
- }
224
- }
225
- }
226
- }
227
- ```
228
-
229
- The two providers share `baseURL` and `apiKey`. Models curated by hand
230
- under either provider's `models` block are preserved verbatim, and a
231
- discovered model is skipped if its key already exists under **either**
232
- provider.
233
-
234
- > **Note**: this requires LiteLLM ≥ 1.40 (which proxies `/v1/responses`)
235
- > and an `@ai-sdk/openai` version that supports the Responses API. Older
236
- > AI SDKs may silently fall back to chat-completions, in which case set
237
- > `responsesApiModels` to an empty list and fix the upstream LiteLLM
238
- > config instead (e.g. `use_responses_api: true` per model).
194
+ > **Note**: OpenAI's reasoning-tier models (gpt-5, o1, o3, o4) reject
195
+ > requests that combine `reasoning_effort` with function tools on
196
+ > `/v1/chat/completions`. If you hit that error, fix it on the LiteLLM
197
+ > side — e.g. enable the Responses API for that model
198
+ > (`use_responses_api: true` in its `litellm_params`) — or leave
199
+ > `reasoningEffort` unset for that model in OpenCode. See the FAQ entry
200
+ > below.
239
201
 
240
202
  ### Authentication
241
203
 
@@ -279,34 +241,41 @@ These headers are included in every request the plugin makes during model discov
279
241
  sequenceDiagram
280
242
  participant OC as OpenCode
281
243
  participant Plugin as opencode-litellm
244
+ participant Cache as disk cache
282
245
  participant LL as LiteLLM proxy
283
246
 
284
247
  OC->>Plugin: config(initial)
285
248
  alt provider.litellm configured
286
- Plugin->>LL: GET /v1/models @ baseURL
249
+ Plugin->>Plugin: use configured baseURL
287
250
  else not configured
288
- Plugin->>LL: probe :4000, :8000, :8080
251
+ Plugin->>LL: probe :4000, :8000, :8080 (GET /v1/models, 3 s fail-fast)
289
252
  LL-->>Plugin: 200 OK on one
290
253
  Plugin->>Plugin: auto-create provider entry
291
254
  end
292
- Plugin->>LL: GET /v1/models (with auth if set)
293
- Plugin->>LL: GET /v1/model/info (best-effort, for `mode` + limits)
294
- LL-->>Plugin: { data: [...models] } + per-model info
295
- Plugin->>Plugin: enrich models, hide non-chat (embedding/image/audio)
296
- Plugin->>Plugin: format names, infer modalities, extract owner
297
- Plugin->>Plugin: bucket each model by transport (chat vs responses)
298
- Plugin->>OC: merge chat-completions models into provider.litellm
299
- Plugin->>OC: merge responses models into provider.litellm-responses (lazy)
300
- OC->>OC: render model picker with all eligible discovered chat models
255
+ Plugin->>Cache: read SWR cache (no network yet)
256
+ alt cache hit
257
+ Cache-->>Plugin: cached models
258
+ Plugin->>OC: merge into provider.litellm (instant startup)
259
+ else cache miss
260
+ Plugin->>LL: GET /v1/models (with auth if set)
261
+ Plugin->>LL: GET /v1/model/info (best-effort)
262
+ LL-->>Plugin: { data: [...models] } + per-model info
263
+ Plugin->>Plugin: enrich models, hide non-chat (embedding/image/audio)
264
+ Plugin->>Plugin: format names, infer modalities + limits + pricing
265
+ Plugin->>OC: merge into provider.litellm
266
+ Plugin->>Cache: persist for next startup
267
+ end
268
+ Note over Plugin,Cache: on session.created, revalidate cache in<br/>the background (throttled to 5 min)
269
+ OC->>OC: render model picker with all discovered models
301
270
  ```
302
271
 
303
272
  1. On OpenCode startup the `config` lifecycle hook fires.
304
- 2. If `provider.litellm` exists, its `baseURL` is used. Otherwise common ports are probed.
305
- 3. A health check (`GET /v1/models`) verifies the proxy is reachable and authorized.
306
- 4. Models from the response are enriched with `/v1/model/info` metadata (`mode`, token limits, capability flags, and per-token pricing — `/v1/models` omits these for database-defined models) and converted into OpenCode model entries keyed by `id`, with formatted `name`, `organizationOwner`, inferred `modalities`, and `cost` (USD/1M tokens, converted from LiteLLM's USD/token). Non-chat models (embedding / image / audio) are excluded from the picker.
307
- 5. Each model is bucketed by transport — reasoning-tier models (`gpt-5*`, `o1`/`o3`/`o4*`, or anything with `mode === 'responses'`) go into the `litellm-responses` provider; everything else goes into `litellm`. Per-model overrides via `responsesApiModels` / `chatApiModels` win.
308
- 6. Discovered models are merged on top of any user-defined ones — never overwriting them. A model is skipped if its key already exists under **either** provider.
309
- 7. The whole flow is wrapped in a `Promise.race` against a 20 s timeout so a slow proxy never blocks boot.
273
+ 2. If `provider.litellm` exists, its `baseURL` is used. Otherwise common ports are probed — that probe is the only health check (3 s fail-fast per port).
274
+ 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.
275
+ 4. **Fast path:** if a fresh on-disk cache exists (≤ 7 days old), its models are merged in synchronously — startup never waits on the network.
276
+ 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.
277
+ 6. Discovered models are merged on top of any user-defined ones — never overwriting them — and persisted to the cache.
278
+ 7. On every `session.created` event the cache is revalidated in the background (throttled to once per 5 minutes); refreshed entries surface on the next OpenCode start. The whole cold path is capped by a 20 s timeout so a slow proxy never blocks boot.
310
279
 
311
280
  ## 📋 Requirements
312
281
 
@@ -331,7 +300,13 @@ sequenceDiagram
331
300
  <details>
332
301
  <summary><b>Why doesn't a model appear in OpenCode after I add it to LiteLLM?</b></summary>
333
302
 
334
- OpenCode reads the plugin output once at startup. After updating `litellm config.yaml`, restart **both** LiteLLM and OpenCode to refresh the model list.
303
+ Once LiteLLM exposes the model (restart or hot-reload LiteLLM if you edited
304
+ its `config.yaml`), the plugin picks it up automatically: whenever you open a
305
+ new session (and at most every 5 minutes), it re-queries the proxy and
306
+ updates the on-disk cache. The new model appears on your **next OpenCode
307
+ start** — no OpenCode config change needed. To force an immediate refetch,
308
+ delete the cache directory (`~/.cache/opencode-litellm/`, or
309
+ `$XDG_CACHE_HOME/opencode-litellm/`).
335
310
  </details>
336
311
 
337
312
  <details>
@@ -343,7 +318,12 @@ Yes. Set `provider.litellm.options.baseURL` to your remote URL and (optionally)
343
318
  <details>
344
319
  <summary><b>What happens if LiteLLM is offline at startup?</b></summary>
345
320
 
346
- The plugin logs a warning and is a no-op. OpenCode starts normally; you just won't see LiteLLM-discovered models until you restart with the proxy up.
321
+ OpenCode starts normally either way. With a warm on-disk cache, the
322
+ previously discovered models are served from the cache — no network call —
323
+ so the picker works as usual; only the background refresh is skipped until
324
+ the proxy is back. With a cold cache (first run, or after the 7-day expiry),
325
+ the plugin logs a warning and you won't see LiteLLM-discovered models until
326
+ the proxy is reachable again.
347
327
  </details>
348
328
 
349
329
  <details>
@@ -391,29 +371,12 @@ The `customHeaders` map works for any gateway that requires extra HTTP headers
391
371
  <details>
392
372
  <summary><b>I get <code>Function tools with reasoning_effort are not supported … in /v1/chat/completions</code> — what do I do?</b></summary>
393
373
 
394
- This error comes from OpenAI: their reasoning-tier models (gpt-5, o1, o3, o4) refuse function-tool calls on `/v1/chat/completions` when `reasoning_effort` is set. They require `/v1/responses` instead.
374
+ This error comes from OpenAI: their reasoning-tier models (gpt-5, o1, o3, o4) refuse function-tool calls on `/v1/chat/completions` when `reasoning_effort` is set. The plugin registers every discovered model through the chat-completions path, so fix this on the LiteLLM side:
395
375
 
396
- As of `0.2.0`, `opencode-litellm` automatically routes those models through a sibling `litellm-responses` provider that uses the Responses API. If your model id doesn't match the heuristic (e.g. you renamed it in LiteLLM), add it explicitly:
376
+ - Enable the Responses API for that model in your LiteLLM config (e.g. `use_responses_api: true` in its `litellm_params`), or
377
+ - Leave the model's `reasoningEffort` unset in OpenCode (don't pick a reasoning-effort variant for it).
397
378
 
398
- ```jsonc
399
- "provider": {
400
- "litellm": {
401
- "options": {
402
- "responsesApiModels": ["my-renamed-gpt-5-high"]
403
- }
404
- }
405
- }
406
- ```
407
-
408
- The model will appear under the **LiteLLM (responses)** provider in the picker; pick it from there and tool-calling will work.
409
- </details>
410
-
411
- <details>
412
- <summary><b>Why are there suddenly two providers (<code>litellm</code> and <code>litellm-responses</code>) in the picker?</b></summary>
413
-
414
- Same LiteLLM proxy, different transport. `litellm` talks to `/v1/chat/completions`; `litellm-responses` talks to `/v1/responses`. The split is required for OpenAI reasoning models — see the FAQ entry above.
415
-
416
- The responses provider is created lazily and only appears if at least one discovered model needs it. To collapse everything back into a single provider, set `"transport": "chat"` in `provider.litellm.options` (you'll lose tool-calling on reasoning models in exchange).
379
+ If your model id doesn't look like a reasoning model to LiteLLM (e.g. you renamed it), also check that its `model_info` in `litellm config.yaml` carries the right `supports_*` flags.
417
380
  </details>
418
381
 
419
382
  ## 🛠️ Development
@@ -423,6 +386,7 @@ git clone https://github.com/yuseferi/opencode-litellm.git
423
386
  cd opencode-litellm
424
387
  npm install
425
388
  npm run typecheck
389
+ npm test
426
390
  ```
427
391
 
428
392
  The project is intentionally tiny:
@@ -433,11 +397,13 @@ src/
433
397
  ├── types/index.ts # LiteLLM API types
434
398
  ├── utils/
435
399
  │ ├── litellm-api.ts # health check, discovery (/v1/models + /v1/model/info), auto-detect
436
- │ └── format-model-name.ts # owner extraction, name formatting, categorization
400
+ │ ├── format-model-name.ts # name formatting, categorization
401
+ │ ├── model-cache.ts # stale-while-revalidate on-disk model cache
402
+ │ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
437
403
  └── plugin/
438
- ├── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering)
439
- ├── discover.ts # V2 Model bucketing (unused by the config hook)
440
- └── build-model.ts # V2 Model entry builder
404
+ └── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering)
405
+
406
+ test/ # vitest suite for the pure logic
441
407
  ```
442
408
 
443
409
  See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full contributor workflow.
@@ -445,9 +411,6 @@ See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full contributor workflow.
445
411
  ## 🗺️ Roadmap
446
412
 
447
413
  - [ ] Optional cost/latency overlay using LiteLLM's `/spend` and `/health` endpoints
448
- - [ ] In-memory cache with TTL to avoid re-querying on rapid restarts
449
- - [ ] Model categorization based on `litellm.proxy.config.model_list[].model_info`
450
- - [ ] Tests with [vitest](https://vitest.dev/)
451
414
  - [ ] `chat.params` hook for injecting LiteLLM routing tags / fallbacks
452
415
 
453
416
  Have an idea? [Open an issue](https://github.com/yuseferi/opencode-litellm/issues/new).
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.11.1",
4
+ "version": "1.0.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",
@@ -13,6 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "typecheck": "tsc --noEmit",
16
+ "test": "vitest run",
16
17
  "build": "npm run typecheck",
17
18
  "prepublishOnly": "npm run build"
18
19
  },
@@ -39,14 +40,14 @@
39
40
  "provenance": true
40
41
  },
41
42
  "dependencies": {
42
- "@opencode-ai/plugin": "^1.14.0",
43
- "@opencode-ai/sdk": "^1.2.0"
43
+ "@opencode-ai/plugin": "^1.14.0"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@semantic-release/changelog": "^7.0.0",
47
47
  "@semantic-release/git": "^11.0.1",
48
48
  "@types/node": "^25.0.3",
49
49
  "semantic-release": "^25.0.8",
50
- "typescript": "^5.9.3"
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^4.1.11"
51
52
  }
52
53
  }
@@ -25,24 +25,27 @@ const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000 // 5 minutes
25
25
  /**
26
26
  * OpenCode invokes the `config` hook several times per run with a
27
27
  * cumulative config object. Track which model ids we already injected
28
- * per baseURL so repeat invocations can return early instead of
29
- * re-querying the proxy.
28
+ * per provider (keyed by `providerId@baseURL`) so repeat invocations
29
+ * can return early instead of re-querying the proxy.
30
30
  */
31
31
  const injectedModelIds = new Map<string, Set<string>>()
32
32
 
33
33
  /**
34
- * Per-baseURL fetch context captured during the `config` hook, so the
34
+ * Per-provider fetch context captured during the `config` hook, so the
35
35
  * `event` hook can revalidate the cache in the background (SWR) without
36
- * re-deriving auth/headers.
36
+ * re-deriving auth/headers. Keyed by `providerId@baseURL` — the same
37
+ * key as the on-disk cache — so providers sharing a proxy keep
38
+ * independent refresh contexts.
37
39
  */
38
40
  interface RefreshContext {
41
+ baseURL: string
39
42
  apiKey?: string
40
43
  customHeaders?: Record<string, string>
41
44
  providerId: string
42
45
  }
43
46
  const refreshContexts = new Map<string, RefreshContext>()
44
47
 
45
- /** baseURLs with an in-flight background refresh, to avoid pile-ups. */
48
+ /** Cache keys with an in-flight background refresh, to avoid pile-ups. */
46
49
  const refreshInFlight = new Set<string>()
47
50
 
48
51
  /**
@@ -115,6 +118,9 @@ function enrichModel(model: LiteLLMModel, info: LiteLLMModelInfo): LiteLLMModel
115
118
  supports_audio_input: model.supports_audio_input ?? info.supports_audio_input,
116
119
  input_cost_per_token: model.input_cost_per_token ?? info.input_cost_per_token,
117
120
  output_cost_per_token: model.output_cost_per_token ?? info.output_cost_per_token,
121
+ cache_read_input_token_cost: model.cache_read_input_token_cost ?? info.cache_read_input_token_cost,
122
+ cache_creation_input_token_cost:
123
+ model.cache_creation_input_token_cost ?? info.cache_creation_input_token_cost,
118
124
  }
119
125
  }
120
126
 
@@ -144,9 +150,12 @@ function toConfigModel(
144
150
  const entry: Record<string, unknown> = {
145
151
  name: formatModelName(model),
146
152
  }
147
- if (model.max_input_tokens || model.max_output_tokens) {
153
+ // Some deployments only report the OpenAI-style `max_tokens` total;
154
+ // use it as the context limit when `max_input_tokens` is absent.
155
+ const contextLimit = model.max_input_tokens ?? model.max_tokens
156
+ if (contextLimit || model.max_output_tokens) {
148
157
  entry.limit = {
149
- context: model.max_input_tokens ?? 0,
158
+ context: contextLimit ?? 0,
150
159
  output: model.max_output_tokens ?? 0,
151
160
  }
152
161
  }
@@ -164,10 +173,17 @@ function toConfigModel(
164
173
  // to their own default instead of us asserting "this model is free"
165
174
  // for something LiteLLM simply has no price anchor for (e.g. rerank).
166
175
  if (model.input_cost_per_token != null || model.output_cost_per_token != null) {
167
- entry.cost = {
176
+ const cost: Record<string, number> = {
168
177
  input: (model.input_cost_per_token ?? 0) * USD_PER_TOKEN_TO_PER_MILLION,
169
178
  output: (model.output_cost_per_token ?? 0) * USD_PER_TOKEN_TO_PER_MILLION,
170
179
  }
180
+ if (model.cache_read_input_token_cost != null) {
181
+ cost.cache_read = model.cache_read_input_token_cost * USD_PER_TOKEN_TO_PER_MILLION
182
+ }
183
+ if (model.cache_creation_input_token_cost != null) {
184
+ cost.cache_write = model.cache_creation_input_token_cost * USD_PER_TOKEN_TO_PER_MILLION
185
+ }
186
+ entry.cost = cost
171
187
  }
172
188
  const input: Array<'text' | 'image' | 'pdf' | 'audio'> = ['text']
173
189
  if (model.supports_vision) input.push('image')
@@ -309,37 +325,37 @@ function mergeModels(
309
325
  }
310
326
 
311
327
  /**
312
- * Revalidate a baseURL's model cache off the critical path (SWR). The
328
+ * Revalidate a provider's model cache off the critical path (SWR). The
313
329
  * refreshed entries land in the on-disk cache and surface on the next
314
330
  * OpenCode start — OpenCode only reads provider config at startup, so
315
331
  * we can't mutate the live picker here.
316
332
  */
317
- async function backgroundRefresh(baseURL: string): Promise<void> {
318
- if (refreshInFlight.has(baseURL)) return
319
- const ctx = refreshContexts.get(baseURL)
333
+ async function backgroundRefresh(cacheKey: string): Promise<void> {
334
+ if (refreshInFlight.has(cacheKey)) return
335
+ const ctx = refreshContexts.get(cacheKey)
320
336
  if (!ctx) return
321
337
  // Skip if the cache was refreshed recently — a burst of new sessions
322
338
  // shouldn't hammer the proxy with health checks and discovery calls.
323
- const savedAt = readModelCacheSavedAt(baseURL)
339
+ const savedAt = readModelCacheSavedAt(cacheKey)
324
340
  if (savedAt !== null && Date.now() - savedAt < REFRESH_MIN_INTERVAL_MS) {
325
341
  return
326
342
  }
327
- refreshInFlight.add(baseURL)
343
+ refreshInFlight.add(cacheKey)
328
344
  try {
329
345
  const built = await withTimeout(
330
- discoverModels(baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
346
+ discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
331
347
  DISCOVERY_TIMEOUT_MS,
332
348
  )
333
349
  if (built && Object.keys(built).length > 0) {
334
- writeModelCache(baseURL, built)
350
+ writeModelCache(cacheKey, built)
335
351
  console.log(
336
- `[opencode-litellm] Background-refreshed model cache for ${baseURL} (${Object.keys(built).length} models)`,
352
+ `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(built).length} models)`,
337
353
  )
338
354
  }
339
355
  } catch {
340
356
  // Best-effort — a failed refresh just leaves the stale cache in place.
341
357
  } finally {
342
- refreshInFlight.delete(baseURL)
358
+ refreshInFlight.delete(cacheKey)
343
359
  }
344
360
  }
345
361
 
@@ -479,13 +495,15 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
479
495
 
480
496
  const models = actualProvider.models as Record<string, unknown>
481
497
 
498
+ const cacheKey = `${providerId}@${baseURL}`
499
+
482
500
  // Remember how to reach this proxy so the `event` hook can
483
501
  // revalidate its cache in the background on new sessions.
484
- refreshContexts.set(baseURL, { apiKey, customHeaders, providerId })
502
+ refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, providerId })
485
503
 
486
504
  // Repeat config-hook invocations within a run are a no-op once
487
- // we've injected this baseURL's models.
488
- const alreadyInjected = injectedModelIds.get(baseURL)
505
+ // we've injected this provider's models.
506
+ const alreadyInjected = injectedModelIds.get(cacheKey)
489
507
  if (
490
508
  alreadyInjected &&
491
509
  [...alreadyInjected].every((id) => Object.hasOwn(models, id))
@@ -496,10 +514,12 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
496
514
  // SWR fast path: serve cached entries synchronously so startup
497
515
  // isn't blocked on the network. A background refresh (see the
498
516
  // `event` hook) keeps the cache fresh for the next launch.
499
- const cached = readModelCache(baseURL)
517
+ // The cache is scoped per provider so two providers pointing at
518
+ // the same proxy (with different keys) don't share model lists.
519
+ const cached = readModelCache(cacheKey)
500
520
  if (cached && Object.keys(cached).length > 0) {
501
521
  const added = mergeModels(models, cached)
502
- injectedModelIds.set(baseURL, new Set(added))
522
+ injectedModelIds.set(cacheKey, new Set(added))
503
523
  console.log(
504
524
  `[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
505
525
  )
@@ -515,8 +535,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
515
535
  )
516
536
  if (built && Object.keys(built).length > 0) {
517
537
  const added = mergeModels(models, built)
518
- injectedModelIds.set(baseURL, new Set(added))
519
- writeModelCache(baseURL, built)
538
+ injectedModelIds.set(cacheKey, new Set(added))
539
+ writeModelCache(cacheKey, built)
520
540
  }
521
541
  }
522
542
  },
@@ -525,8 +545,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
525
545
  // opens. Fresh data lands in the cache and surfaces on the next
526
546
  // OpenCode start (SWR).
527
547
  if (event.type !== 'session.created') return
528
- for (const baseURL of refreshContexts.keys()) {
529
- void backgroundRefresh(baseURL)
548
+ for (const cacheKey of refreshContexts.keys()) {
549
+ void backgroundRefresh(cacheKey)
530
550
  }
531
551
  },
532
552
  }
@@ -40,6 +40,8 @@ export interface LiteLLMModel {
40
40
  */
41
41
  input_cost_per_token?: number
42
42
  output_cost_per_token?: number
43
+ cache_read_input_token_cost?: number
44
+ cache_creation_input_token_cost?: number
43
45
  }
44
46
 
45
47
  export interface LiteLLMModelsResponse {
@@ -83,66 +85,3 @@ export interface LiteLLMModelInfoEntry {
83
85
  export interface LiteLLMModelInfoResponse {
84
86
  data?: LiteLLMModelInfoEntry[]
85
87
  }
86
-
87
- export type ModelType = 'chat' | 'embedding' | 'image' | 'audio' | 'unknown'
88
-
89
- /**
90
- * Which OpenAI-compatible HTTP surface a model should be invoked through.
91
- *
92
- * - `chat` → `/v1/chat/completions` (most models)
93
- * - `responses` → `/v1/responses` (gpt-5*, o-series with reasoning)
94
- */
95
- export type Transport = 'chat' | 'responses'
96
-
97
- /**
98
- * User-facing routing override. Defaults to `'auto'`.
99
- *
100
- * - `'auto'` → use the heuristic + LiteLLM `mode` field
101
- * - `'chat'` → force every discovered model into the chat-completions provider
102
- * - `'responses'` → force every discovered model into the responses provider
103
- */
104
- export type TransportPolicy = 'auto' | Transport
105
-
106
- export interface LiteLLMOptions {
107
- baseURL?: string
108
- apiKey?: string
109
- /**
110
- * Routing policy for discovered models. See {@link TransportPolicy}.
111
- * Defaults to `'auto'`.
112
- */
113
- transport?: TransportPolicy
114
- /**
115
- * Explicit allowlist of model ids that MUST be routed through the
116
- * OpenAI Responses API (`/v1/responses`). Takes priority over the
117
- * heuristic and over the `transport` policy.
118
- *
119
- * Match is exact against the LiteLLM model id (e.g. `"gpt-5-4-high"`).
120
- */
121
- responsesApiModels?: string[]
122
- /**
123
- * Explicit denylist of model ids that MUST be routed through chat
124
- * completions (`/v1/chat/completions`), even if the heuristic would
125
- * otherwise put them in the responses bucket. Takes priority over
126
- * the heuristic but is overridden by `responsesApiModels`.
127
- */
128
- chatApiModels?: string[]
129
- /**
130
- * Arbitrary HTTP headers to include in every request to the LiteLLM
131
- * proxy during model discovery (health check + `/v1/models`).
132
- *
133
- * Useful for proxies behind Cloudflare Access or other gateways that
134
- * require extra authentication headers beyond the standard
135
- * `Authorization: Bearer` token.
136
- *
137
- * Example (Cloudflare Access Service Token):
138
- * ```json
139
- * {
140
- * "customHeaders": {
141
- * "CF-Access-Client-Id": "{env:CF_ACCESS_CLIENT_ID}",
142
- * "CF-Access-Client-Secret": "{env:CF_ACCESS_CLIENT_SECRET}"
143
- * }
144
- * }
145
- * ```
146
- */
147
- customHeaders?: Record<string, string>
148
- }
@@ -1,19 +1,5 @@
1
1
  import type { LiteLLMModel } from '../types'
2
2
 
3
- /**
4
- * Extract owner / provider from a LiteLLM model ID.
5
- *
6
- * LiteLLM model IDs commonly take the shape `<provider>/<model>` (e.g.
7
- * `openai/gpt-4o`, `anthropic/claude-3-5-sonnet`, `bedrock/...`). When
8
- * available we prefer the `litellm_provider` field returned by the API.
9
- */
10
- export function extractModelOwner(model: LiteLLMModel): string | undefined {
11
- if (model.litellm_provider) return model.litellm_provider
12
- const parts = model.id.split('/')
13
- if (parts.length > 1) return parts[0]
14
- return undefined
15
- }
16
-
17
3
  /**
18
4
  * Strip Vertex-style version pinning suffixes that have no place in a
19
5
  * display name. LiteLLM exposes Anthropic-on-Vertex models with ids
@@ -46,22 +32,32 @@ function looksLikeVersionComponent(token: string): boolean {
46
32
  * "Claude Opus 4 5".
47
33
  *
48
34
  * Conservative on purpose:
49
- * - Only the LAST adjacent pair is collapsed, so `gpt-3-5-turbo-16k`
50
- * keeps `[3, 5, turbo, 16k]` (`turbo` between blocks the merge).
51
- * - Both tokens must look like real version components (1–2 digits) —
52
- * this avoids merging date stamps in ids like
53
- * `claude-opus-4-5-20251101`, where the trailing `20251101` is a
54
- * YYYYMMDD revision and must stay separate.
35
+ * - Only the FIRST mergeable pair scanning from the right is collapsed:
36
+ * `gpt-3-5-turbo-16k` merges `3-5` into `3.5` and stops there.
37
+ * - Both tokens must look like real version components (1–2 digits),
38
+ * so a `YYYYMMDD` revision stamp like `20251101` is never merged
39
+ * into a version number itself.
55
40
  * - We refuse to collapse if the token immediately AFTER the pair is
56
- * also numeric (would create ambiguity in `1-2-3` runs).
41
+ * also a short number, or if the token immediately BEFORE it is one
42
+ * too — both signal an ambiguous numeric run (`1-2-3`) rather than
43
+ * a version pair. A trailing 6–8 digit `YYYYMMDD` revision stamp
44
+ * does not block the merge — it stays its own token, so
45
+ * `claude-opus-4-5-20251101` renders "Claude Opus 4.5 20251101",
46
+ * not "Claude Opus 4 5 20251101".
57
47
  */
58
48
  function joinTrailingVersionPair(tokens: string[]): string[] {
59
49
  for (let i = tokens.length - 1; i >= 1; i--) {
60
50
  const a = tokens[i - 1]
61
51
  const b = tokens[i]
62
52
  if (looksLikeVersionComponent(a) && looksLikeVersionComponent(b)) {
53
+ const prev = tokens[i - 2]
63
54
  const next = tokens[i + 1]
64
- if (next === undefined || !/^\d+$/.test(next)) {
55
+ const prevIsShortNumeric = prev !== undefined && looksLikeVersionComponent(prev)
56
+ const nextIsDateStamp = next !== undefined && /^\d{6,8}$/.test(next)
57
+ if (
58
+ !prevIsShortNumeric &&
59
+ (next === undefined || nextIsDateStamp || !/^\d+$/.test(next))
60
+ ) {
65
61
  const merged = [...tokens.slice(0, i - 1), `${a}.${b}`, ...tokens.slice(i + 1)]
66
62
  return merged
67
63
  }
@@ -159,32 +155,3 @@ export function formatModelName(model: LiteLLMModel): string {
159
155
 
160
156
  return tokens.join(' ') || id
161
157
  }
162
-
163
- /**
164
- * Decide whether a model must be invoked through the OpenAI Responses
165
- * API (`/v1/responses`) instead of `/v1/chat/completions`.
166
- *
167
- * OpenAI's reasoning-tier models (gpt-5*, o1/o3/o4*) reject requests
168
- * that combine `reasoning_effort` with function tools when sent to
169
- * `/v1/chat/completions`. The Responses API has no such restriction,
170
- * so we route those models there.
171
- *
172
- * Detection rules (first match wins):
173
- * 1. `model.mode === 'responses'` (LiteLLM exposes this on newer versions)
174
- * 2. The model id (after any `provider/` prefix) matches the
175
- * `gpt-5*` / `o[134]*` family.
176
- */
177
- export function requiresResponsesAPI(model: LiteLLMModel): boolean {
178
- if (model.mode && model.mode.toLowerCase() === 'responses') return true
179
-
180
- const id = model.id.toLowerCase()
181
- const slashIdx = id.indexOf('/')
182
- const tail = slashIdx >= 0 ? id.slice(slashIdx + 1) : id
183
-
184
- // gpt-5, gpt-5.4, gpt-5-4-high, gpt-5o, ...
185
- if (/^gpt-?5(?:[-.].*)?$/.test(tail)) return true
186
- // o1, o1-mini, o3, o3-mini, o4-mini, o4, ... but NOT "openai", "ollama"
187
- if (/^o[134](?:[-.].*)?$/.test(tail)) return true
188
-
189
- return false
190
- }
@@ -37,23 +37,27 @@ function cacheDir(): string {
37
37
  return join(base, 'opencode-litellm')
38
38
  }
39
39
 
40
- /** Stable, filesystem-safe filename derived from the normalized baseURL. */
41
- function cacheFile(baseURL: string): string {
42
- const hash = createHash('sha256').update(baseURL).digest('hex').slice(0, 16)
40
+ /**
41
+ * Stable, filesystem-safe filename derived from the cache key. Callers
42
+ * pass `providerId@baseURL` so two providers pointing at the same proxy
43
+ * (possibly with different API keys) keep separate caches.
44
+ */
45
+ function cacheFile(cacheKey: string): string {
46
+ const hash = createHash('sha256').update(cacheKey).digest('hex').slice(0, 16)
43
47
  return join(cacheDir(), `models-${hash}.json`)
44
48
  }
45
49
 
46
50
  /**
47
- * Read cached model entries for a baseURL. Returns `null` on any
51
+ * Read cached model entries for a cache key. Returns `null` on any
48
52
  * problem (missing file, parse error, version mismatch, or an entry
49
53
  * older than `CACHE_MAX_AGE_MS`) — the caller treats that as a cache
50
54
  * miss and falls back to a live fetch.
51
55
  */
52
56
  export function readModelCache(
53
- baseURL: string,
57
+ cacheKey: string,
54
58
  ): Record<string, unknown> | null {
55
59
  try {
56
- const raw = readFileSync(cacheFile(baseURL), 'utf8')
60
+ const raw = readFileSync(cacheFile(cacheKey), 'utf8')
57
61
  const parsed = JSON.parse(raw) as ModelCacheFile
58
62
  if (parsed.version !== CACHE_VERSION) return null
59
63
  if (!parsed.models || typeof parsed.models !== 'object') return null
@@ -70,13 +74,13 @@ export function readModelCache(
70
74
  }
71
75
 
72
76
  /**
73
- * Return the `savedAt` timestamp (epoch ms) of a baseURL's cache entry,
74
- * or `null` if there's no readable/valid cache. Used to throttle
77
+ * Return the `savedAt` timestamp (epoch ms) of a cache entry, or
78
+ * `null` if there's no readable/valid cache. Used to throttle
75
79
  * background refreshes so still-fresh caches aren't re-fetched.
76
80
  */
77
- export function readModelCacheSavedAt(baseURL: string): number | null {
81
+ export function readModelCacheSavedAt(cacheKey: string): number | null {
78
82
  try {
79
- const raw = readFileSync(cacheFile(baseURL), 'utf8')
83
+ const raw = readFileSync(cacheFile(cacheKey), 'utf8')
80
84
  const parsed = JSON.parse(raw) as ModelCacheFile
81
85
  if (parsed.version !== CACHE_VERSION) return null
82
86
  if (typeof parsed.savedAt !== 'number') return null
@@ -87,11 +91,11 @@ export function readModelCacheSavedAt(baseURL: string): number | null {
87
91
  }
88
92
 
89
93
  /**
90
- * Persist model entries for a baseURL. Best-effort: never throws, so a
91
- * read-only or full filesystem can't break discovery.
94
+ * Persist model entries for a cache key. Best-effort: never throws, so
95
+ * a read-only or full filesystem can't break discovery.
92
96
  */
93
97
  export function writeModelCache(
94
- baseURL: string,
98
+ cacheKey: string,
95
99
  models: Record<string, unknown>,
96
100
  ): void {
97
101
  try {
@@ -104,7 +108,7 @@ export function writeModelCache(
104
108
  // Write to a temp file and rename so concurrent OpenCode processes
105
109
  // never observe a partially-written JSON file (rename is atomic on
106
110
  // the same filesystem).
107
- const target = cacheFile(baseURL)
111
+ const target = cacheFile(cacheKey)
108
112
  const tmp = `${target}.${process.pid}.tmp`
109
113
  try {
110
114
  writeFileSync(tmp, JSON.stringify(payload), 'utf8')
@@ -1,82 +0,0 @@
1
- import type { Model as ModelV2 } from '@opencode-ai/sdk/v2'
2
- import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
3
- import {
4
- categorizeModel,
5
- formatModelName,
6
- } from '../utils/format-model-name'
7
-
8
- /**
9
- * Build an OpenCode V2 `Model` entry from a discovered LiteLLM model.
10
- *
11
- * The V2 schema requires a lot of fields we have no real data for
12
- * (`cost`, `limit`, `release_date`, …). We fill these with sensible
13
- * defaults — zero cost / zero limits / today's date — so the entry
14
- * type-checks and the picker renders something useful. Real values
15
- * can be added in a future release if LiteLLM exposes them via
16
- * `/v1/model/info`, which carries `max_tokens`, `input_cost_per_token`,
17
- * etc.
18
- */
19
- export function buildModelV2(
20
- providerID: string,
21
- api: { id: string; url: string; npm: string },
22
- model: LiteLLMModel,
23
- info?: LiteLLMModelInfo,
24
- ): ModelV2 {
25
- const type = categorizeModel(model)
26
- const isVision = !!model.supports_vision
27
- const isAudio = type === 'audio'
28
- const isImageOut = type === 'image'
29
-
30
- return {
31
- id: model.id,
32
- providerID,
33
- api,
34
- name: formatModelName(model),
35
- capabilities: {
36
- temperature: true,
37
- reasoning: !!model.supports_reasoning,
38
- attachment: isVision || isAudio,
39
- toolcall: !!model.supports_function_calling,
40
- input: {
41
- text: true,
42
- audio: isAudio,
43
- image: isVision,
44
- video: false,
45
- pdf: !!model.supports_pdf_input,
46
- },
47
- output: {
48
- text: !isImageOut,
49
- audio: false,
50
- image: isImageOut,
51
- video: false,
52
- pdf: false,
53
- },
54
- interleaved: false,
55
- },
56
- cost: {
57
- input: info?.input_cost_per_token ?? 0,
58
- output: info?.output_cost_per_token ?? 0,
59
- cache: {
60
- read: info?.cache_read_input_token_cost ?? 0,
61
- write: info?.cache_creation_input_token_cost ?? 0,
62
- },
63
- },
64
- limit: {
65
- context: model.max_input_tokens ?? 0,
66
- input: model.max_input_tokens,
67
- output: model.max_output_tokens ?? 0,
68
- },
69
- status: 'active',
70
- options: {},
71
- headers: {},
72
- release_date: '',
73
- variants: info?.supports_reasoning_efforts?.length
74
- ? Object.fromEntries(
75
- info.supports_reasoning_efforts.map((effort) => [
76
- effort,
77
- { reasoningEffort: effort },
78
- ]),
79
- )
80
- : undefined,
81
- }
82
- }
@@ -1,204 +0,0 @@
1
- import type { Model as ModelV2, Provider as ProviderV2 } from '@opencode-ai/sdk/v2'
2
- import {
3
- autoDetectLiteLLM,
4
- checkLiteLLMHealth,
5
- discoverLiteLLMModelInfo,
6
- discoverLiteLLMModels,
7
- normalizeBaseURL,
8
- } from '../utils/litellm-api'
9
- import { requiresResponsesAPI } from '../utils/format-model-name'
10
- import type { LiteLLMModel, LiteLLMModelInfo, Transport, TransportPolicy } from '../types'
11
- import { buildModelV2 } from './build-model'
12
-
13
- const DISCOVERY_TIMEOUT_MS = 5000
14
-
15
- /**
16
- * Decide which transport bucket a model belongs to. Order of
17
- * precedence (highest first):
18
- *
19
- * 1. Explicit allowlist `responsesApiModels` → 'responses'
20
- * 2. Explicit denylist `chatApiModels` → 'chat'
21
- * 3. Global policy `transport: 'chat' | 'responses'`
22
- * 4. Heuristic via {@link requiresResponsesAPI} → 'responses' or 'chat'
23
- */
24
- function pickTransport(
25
- model: LiteLLMModel,
26
- policy: TransportPolicy,
27
- responsesApiModels: ReadonlySet<string>,
28
- chatApiModels: ReadonlySet<string>,
29
- ): Transport {
30
- if (responsesApiModels.has(model.id)) return 'responses'
31
- if (chatApiModels.has(model.id)) return 'chat'
32
- if (policy === 'chat') return 'chat'
33
- if (policy === 'responses') return 'responses'
34
- return requiresResponsesAPI(model) ? 'responses' : 'chat'
35
- }
36
-
37
- /**
38
- * Resolve the LiteLLM `baseURL` and `apiKey` to use for discovery.
39
- *
40
- * Looks at the configured provider options first (so the user's
41
- * `opencode.json` wins), then falls back to env vars, and finally to
42
- * auto-detecting a local proxy on the common ports.
43
- */
44
- /**
45
- * Extract the `customHeaders` map from the provider options block.
46
- * Returns `undefined` when no custom headers are configured.
47
- */
48
- function readCustomHeaders(
49
- provider: ProviderV2 | undefined,
50
- ): Record<string, string> | undefined {
51
- const options = (provider?.options ?? {}) as Record<string, unknown>
52
- const raw = options.customHeaders
53
- if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
54
- const out: Record<string, string> = {}
55
- for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
56
- if (typeof v === 'string') out[k] = v
57
- }
58
- return Object.keys(out).length > 0 ? out : undefined
59
- }
60
- return undefined
61
- }
62
-
63
- async function resolveEndpoint(
64
- provider: ProviderV2 | undefined,
65
- ): Promise<{ baseURL: string; apiKey?: string; customHeaders?: Record<string, string> } | null> {
66
- const options = (provider?.options ?? {}) as Record<string, unknown>
67
- const configuredBase = typeof options.baseURL === 'string' ? options.baseURL : undefined
68
- const configuredKey = typeof options.apiKey === 'string' && options.apiKey ? options.apiKey : undefined
69
- const envKey = process.env.LITELLM_API_KEY ?? process.env.LITELLM_MASTER_KEY
70
- const customHeaders = readCustomHeaders(provider)
71
-
72
- if (configuredBase) {
73
- return { baseURL: normalizeBaseURL(configuredBase), apiKey: configuredKey ?? envKey, customHeaders }
74
- }
75
-
76
- const detected = await autoDetectLiteLLM(configuredKey ?? envKey, customHeaders)
77
- if (!detected) return null
78
- return { baseURL: normalizeBaseURL(detected), apiKey: configuredKey ?? envKey, customHeaders }
79
- }
80
-
81
- /**
82
- * Read the routing policy and per-model overrides off the provider's
83
- * `options` block. Defaults to `'auto'` with empty allow/deny lists.
84
- */
85
- function readRoutingOptions(
86
- provider: ProviderV2 | undefined,
87
- ): {
88
- policy: TransportPolicy
89
- responsesApiModels: Set<string>
90
- chatApiModels: Set<string>
91
- } {
92
- const options = (provider?.options ?? {}) as Record<string, unknown>
93
- const policy =
94
- typeof options.transport === 'string' &&
95
- (options.transport === 'auto' || options.transport === 'chat' || options.transport === 'responses')
96
- ? (options.transport as TransportPolicy)
97
- : 'auto'
98
- const responses = Array.isArray(options.responsesApiModels)
99
- ? options.responsesApiModels.filter((v): v is string => typeof v === 'string')
100
- : []
101
- const chat = Array.isArray(options.chatApiModels)
102
- ? options.chatApiModels.filter((v): v is string => typeof v === 'string')
103
- : []
104
- return {
105
- policy,
106
- responsesApiModels: new Set(responses),
107
- chatApiModels: new Set(chat),
108
- }
109
- }
110
-
111
- /**
112
- * Discover all models from the LiteLLM proxy and bucket them by the
113
- * transport (`chat` vs `responses`) they should use. Returns a map of
114
- * model id → V2 `Model` for the requested bucket only.
115
- *
116
- * Pass `bucket: 'all'` to ignore the routing heuristic and return
117
- * every discovered model. Useful for the default chat-only setup
118
- * where the user hasn't declared a sibling `litellm-responses`
119
- * provider — without `'all'`, gpt-5* / o-series models would be
120
- * silently dropped.
121
- *
122
- * Capped at {@link DISCOVERY_TIMEOUT_MS} so a slow / unreachable
123
- * proxy never stalls OpenCode startup.
124
- */
125
- export async function discoverBucket(
126
- bucket: Transport | 'all',
127
- provider: ProviderV2 | undefined,
128
- api: { id: string; url: string; npm: string },
129
- ): Promise<Record<string, ModelV2>> {
130
- const out: Record<string, ModelV2> = {}
131
-
132
- const work = async () => {
133
- const endpoint = await resolveEndpoint(provider)
134
- if (!endpoint) return
135
-
136
- const { baseURL, apiKey, customHeaders } = endpoint
137
- if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
138
- console.warn(`[opencode-litellm] LiteLLM appears offline or unauthorized at ${baseURL}`)
139
- return
140
- }
141
-
142
- const [modelsResult, infoResult] = await Promise.allSettled([
143
- discoverLiteLLMModels(baseURL, apiKey, customHeaders),
144
- discoverLiteLLMModelInfo(baseURL, apiKey, customHeaders),
145
- ])
146
-
147
- if (modelsResult.status === 'rejected') {
148
- console.warn(
149
- '[opencode-litellm] Model discovery failed:',
150
- modelsResult.reason instanceof Error ? modelsResult.reason.message : String(modelsResult.reason),
151
- )
152
- return
153
- }
154
- const models = modelsResult.value
155
-
156
- let infoByName: Map<string, LiteLLMModelInfo> | null = null
157
- if (infoResult.status === 'fulfilled') {
158
- infoByName = infoResult.value
159
- } else {
160
- console.warn(
161
- '[opencode-litellm] /v1/model/info unavailable; model costs will be zero:',
162
- infoResult.reason instanceof Error ? infoResult.reason.message : String(infoResult.reason),
163
- )
164
- }
165
-
166
- if (models.length === 0) {
167
- console.warn(
168
- '[opencode-litellm] LiteLLM responded but exposed zero models. Check your `model_list` in litellm config.yaml',
169
- )
170
- return
171
- }
172
-
173
- const resolvedApi = { ...api, url: `${baseURL}/v1` }
174
-
175
- const routing = readRoutingOptions(provider)
176
- for (const model of models) {
177
- if (bucket !== 'all') {
178
- const transport = pickTransport(
179
- model,
180
- routing.policy,
181
- routing.responsesApiModels,
182
- routing.chatApiModels,
183
- )
184
- if (transport !== bucket) continue
185
- }
186
- // OpenCode's @ai-sdk/openai-compatible adapter uses `api.id` as
187
- // the wire model name sent to the upstream LiteLLM endpoint
188
- // (verified empirically — without this override the wire request
189
- // sends the provider id "litellm" instead, and LiteLLM rejects
190
- // it with "team not allowed"). Set `api.id` per-model so each
191
- // entry carries the correct upstream model name.
192
- const perModelApi = { ...resolvedApi, id: model.id }
193
- const info = infoByName?.get(model.id) ?? {}
194
- out[model.id] = buildModelV2(resolvedApi.id, perModelApi, model, info)
195
- }
196
- }
197
-
198
- await Promise.race([
199
- work(),
200
- new Promise<void>((resolve) => setTimeout(resolve, DISCOVERY_TIMEOUT_MS)),
201
- ])
202
-
203
- return out
204
- }