opencode-plugin-litellm 0.11.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -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,14 +70,15 @@ 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
- | ⏱️ **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. |
80
+ | ⏱️ **Non-blocking startup** | Health checks fail fast (3 s); discovery fetches are capped at **15 s** (configurable via `LITELLM_REQUEST_TIMEOUT_MS`) for slow remote proxies. Repeat config-hook invocations are a no-op. |
81
+ | 📝 **TUI-safe logging** | All plugin logs go through OpenCode's log API (into OpenCode's own log files), never to stdout — the TUI stays intact. |
85
82
  | 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
86
83
  | 🪶 **Zero runtime deps** | Only depends on `@opencode-ai/plugin`. No build step, no bundler. |
87
84
  | 🔒 **TypeScript strict** | Strict-mode compiled, fully typed public API. |
@@ -183,18 +180,10 @@ If you want to rename a model in the picker, pin its `organizationOwner`, or oth
183
180
 
184
181
  Here, `openai/gpt-4o` keeps your custom name; every other model from the proxy is still discovered and added automatically.
185
182
 
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.
183
+ ### Reasoning models and effort variants
193
184
 
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.
185
+ All discovered models — reasoning-tier included — register under your single
186
+ LiteLLM provider and are invoked through `/v1/chat/completions`.
198
187
 
199
188
  If LiteLLM reports per-model reasoning-effort support (e.g.
200
189
  `supports_low_reasoning_effort`, `supports_medium_reasoning_effort`,
@@ -203,39 +192,13 @@ surfaces those as OpenCode variants under the discovered model. Each variant
203
192
  sets `reasoningEffort` to the reported level, so you can switch between
204
193
  effort levels from the model picker without hand-curating every entry.
205
194
 
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).
195
+ > **Note**: OpenAI's reasoning-tier models (gpt-5, o1, o3, o4) reject
196
+ > requests that combine `reasoning_effort` with function tools on
197
+ > `/v1/chat/completions`. If you hit that error, fix it on the LiteLLM
198
+ > side — e.g. enable the Responses API for that model
199
+ > (`use_responses_api: true` in its `litellm_params`) — or leave
200
+ > `reasoningEffort` unset for that model in OpenCode. See the FAQ entry
201
+ > below.
239
202
 
240
203
  ### Authentication
241
204
 
@@ -250,6 +213,16 @@ If your LiteLLM proxy requires a master key, expose it via either approach:
250
213
 
251
214
  The env var path lets you commit `opencode.json` without leaking secrets. The `/connect` path is useful when you'd rather manage the credential through OpenCode's own auth store (`~/.local/share/opencode/auth.json`) instead of an env var or config file — the plugin reads that file as a fallback and applies the stored key to its own health-check, model-discovery, and completion-time provider requests, so a key-only proxy works end to end.
252
215
 
216
+ ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
217
+
218
+ Each discovery request (`/v1/models`, `/v1/model/info`) is capped at 15 s by default. Proxies with many database-defined models — or a gateway in front of LiteLLM — can legitimately take longer. Raise the budget with:
219
+
220
+ ```bash
221
+ export LITELLM_REQUEST_TIMEOUT_MS=60000
222
+ ```
223
+
224
+ The overall discovery cap scales with it (max of 20 s and the request timeout + 5 s), so a slow proxy never blocks startup indefinitely but isn't cut off mid-flight either. Invalid values fall back to the default.
225
+
253
226
  ### Custom headers (Cloudflare Access, API gateways)
254
227
 
255
228
  If your LiteLLM proxy is behind Cloudflare Access or another gateway that requires extra HTTP headers, use the `customHeaders` option:
@@ -279,34 +252,41 @@ These headers are included in every request the plugin makes during model discov
279
252
  sequenceDiagram
280
253
  participant OC as OpenCode
281
254
  participant Plugin as opencode-litellm
255
+ participant Cache as disk cache
282
256
  participant LL as LiteLLM proxy
283
257
 
284
258
  OC->>Plugin: config(initial)
285
259
  alt provider.litellm configured
286
- Plugin->>LL: GET /v1/models @ baseURL
260
+ Plugin->>Plugin: use configured baseURL
287
261
  else not configured
288
- Plugin->>LL: probe :4000, :8000, :8080
262
+ Plugin->>LL: probe :4000, :8000, :8080 (GET /v1/models, 3 s fail-fast)
289
263
  LL-->>Plugin: 200 OK on one
290
264
  Plugin->>Plugin: auto-create provider entry
291
265
  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
266
+ Plugin->>Cache: read SWR cache (no network yet)
267
+ alt cache hit
268
+ Cache-->>Plugin: cached models
269
+ Plugin->>OC: merge into provider.litellm (instant startup)
270
+ else cache miss
271
+ Plugin->>LL: GET /v1/models (with auth if set)
272
+ Plugin->>LL: GET /v1/model/info (best-effort)
273
+ LL-->>Plugin: { data: [...models] } + per-model info
274
+ Plugin->>Plugin: enrich models, hide non-chat (embedding/image/audio)
275
+ Plugin->>Plugin: format names, infer modalities + limits + pricing
276
+ Plugin->>OC: merge into provider.litellm
277
+ Plugin->>Cache: persist for next startup
278
+ end
279
+ Note over Plugin,Cache: on session.created, revalidate cache in<br/>the background (throttled to 5 min)
280
+ OC->>OC: render model picker with all discovered models
301
281
  ```
302
282
 
303
283
  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.
284
+ 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).
285
+ 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.
286
+ 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.
287
+ 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.
288
+ 6. Discovered models are merged on top of any user-defined ones — never overwriting them — and persisted to the cache.
289
+ 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
290
 
311
291
  ## 📋 Requirements
312
292
 
@@ -331,7 +311,13 @@ sequenceDiagram
331
311
  <details>
332
312
  <summary><b>Why doesn't a model appear in OpenCode after I add it to LiteLLM?</b></summary>
333
313
 
334
- OpenCode reads the plugin output once at startup. After updating `litellm config.yaml`, restart **both** LiteLLM and OpenCode to refresh the model list.
314
+ Once LiteLLM exposes the model (restart or hot-reload LiteLLM if you edited
315
+ its `config.yaml`), the plugin picks it up automatically: whenever you open a
316
+ new session (and at most every 5 minutes), it re-queries the proxy and
317
+ updates the on-disk cache. The new model appears on your **next OpenCode
318
+ start** — no OpenCode config change needed. To force an immediate refetch,
319
+ delete the cache directory (`~/.cache/opencode-litellm/`, or
320
+ `$XDG_CACHE_HOME/opencode-litellm/`).
335
321
  </details>
336
322
 
337
323
  <details>
@@ -343,7 +329,12 @@ Yes. Set `provider.litellm.options.baseURL` to your remote URL and (optionally)
343
329
  <details>
344
330
  <summary><b>What happens if LiteLLM is offline at startup?</b></summary>
345
331
 
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.
332
+ OpenCode starts normally either way. With a warm on-disk cache, the
333
+ previously discovered models are served from the cache — no network call —
334
+ so the picker works as usual; only the background refresh is skipped until
335
+ the proxy is back. With a cold cache (first run, or after the 7-day expiry),
336
+ the plugin logs a warning and you won't see LiteLLM-discovered models until
337
+ the proxy is reachable again.
347
338
  </details>
348
339
 
349
340
  <details>
@@ -391,29 +382,12 @@ The `customHeaders` map works for any gateway that requires extra HTTP headers
391
382
  <details>
392
383
  <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
384
 
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.
395
-
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:
397
-
398
- ```jsonc
399
- "provider": {
400
- "litellm": {
401
- "options": {
402
- "responsesApiModels": ["my-renamed-gpt-5-high"]
403
- }
404
- }
405
- }
406
- ```
385
+ 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:
407
386
 
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>
387
+ - Enable the Responses API for that model in your LiteLLM config (e.g. `use_responses_api: true` in its `litellm_params`), or
388
+ - Leave the model's `reasoningEffort` unset in OpenCode (don't pick a reasoning-effort variant for it).
413
389
 
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).
390
+ 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
391
  </details>
418
392
 
419
393
  ## 🛠️ Development
@@ -423,6 +397,7 @@ git clone https://github.com/yuseferi/opencode-litellm.git
423
397
  cd opencode-litellm
424
398
  npm install
425
399
  npm run typecheck
400
+ npm test
426
401
  ```
427
402
 
428
403
  The project is intentionally tiny:
@@ -433,11 +408,13 @@ src/
433
408
  ├── types/index.ts # LiteLLM API types
434
409
  ├── utils/
435
410
  │ ├── litellm-api.ts # health check, discovery (/v1/models + /v1/model/info), auto-detect
436
- │ └── format-model-name.ts # owner extraction, name formatting, categorization
411
+ │ ├── format-model-name.ts # name formatting, categorization
412
+ │ ├── model-cache.ts # stale-while-revalidate on-disk model cache
413
+ │ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
437
414
  └── 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
415
+ └── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering)
416
+
417
+ test/ # vitest suite for the pure logic
441
418
  ```
442
419
 
443
420
  See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full contributor workflow.
@@ -445,9 +422,6 @@ See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full contributor workflow.
445
422
  ## 🗺️ Roadmap
446
423
 
447
424
  - [ ] 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
425
  - [ ] `chat.params` hook for injecting LiteLLM routing tags / fallbacks
452
426
 
453
427
  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.1",
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
  }
@@ -4,6 +4,7 @@ import {
4
4
  checkLiteLLMHealth,
5
5
  discoverLiteLLMModelInfo,
6
6
  discoverLiteLLMModels,
7
+ getRequestTimeoutMs,
7
8
  normalizeBaseURL,
8
9
  } from '../utils/litellm-api'
9
10
  import {
@@ -15,34 +16,65 @@ import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
15
16
  import { readModelCache, writeModelCache, readModelCacheSavedAt } from '../utils/model-cache'
16
17
 
17
18
  const CHAT_PROVIDER_ID = 'litellm'
18
- // Covers the sequential 3 s health check plus the parallel 15 s
19
- // models/model-info fetch phase, with headroom.
20
- const DISCOVERY_TIMEOUT_MS = 20000
19
+ // Covers the 3 s health check plus the parallel models/model-info fetch
20
+ // phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
21
+ // proxies aren't cut off by the overall cap either (issue #20).
22
+ const DISCOVERY_TIMEOUT_MS = Math.max(20000, getRequestTimeoutMs() + 5000)
21
23
  // Don't revalidate a baseURL's cache more often than this, so a burst
22
24
  // of `session.created` events can't generate repeated discovery traffic.
23
25
  const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000 // 5 minutes
24
26
 
27
+ type LogLevel = 'info' | 'warn' | 'error' | 'debug'
28
+
29
+ let logClient: PluginInput['client'] | null = null
30
+
31
+ function initLogging(client: PluginInput['client']): void {
32
+ logClient = client
33
+ }
34
+
35
+ /**
36
+ * Route plugin logs through OpenCode's log API instead of stdout.
37
+ * console.* writes straight into the same terminal the OpenCode TUI
38
+ * renders in, corrupting the interface on every background refresh
39
+ * (issue #15); client.app.log lands in OpenCode's log files instead.
40
+ */
41
+ function log(level: LogLevel, message: string): void {
42
+ if (logClient) {
43
+ void logClient.app
44
+ .log({ body: { service: 'opencode-litellm', level, message } })
45
+ .catch(() => {})
46
+ return
47
+ }
48
+ // No client wired up (unit tests, unusual embedders) — fall back to
49
+ // the console rather than silently dropping diagnostics.
50
+ if (level === 'info' || level === 'debug') console.log(message)
51
+ else console.warn(message)
52
+ }
53
+
25
54
  /**
26
55
  * OpenCode invokes the `config` hook several times per run with a
27
56
  * 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.
57
+ * per provider (keyed by `providerId@baseURL`) so repeat invocations
58
+ * can return early instead of re-querying the proxy.
30
59
  */
31
60
  const injectedModelIds = new Map<string, Set<string>>()
32
61
 
33
62
  /**
34
- * Per-baseURL fetch context captured during the `config` hook, so the
63
+ * Per-provider fetch context captured during the `config` hook, so the
35
64
  * `event` hook can revalidate the cache in the background (SWR) without
36
- * re-deriving auth/headers.
65
+ * re-deriving auth/headers. Keyed by `providerId@baseURL` — the same
66
+ * key as the on-disk cache — so providers sharing a proxy keep
67
+ * independent refresh contexts.
37
68
  */
38
69
  interface RefreshContext {
70
+ baseURL: string
39
71
  apiKey?: string
40
72
  customHeaders?: Record<string, string>
41
73
  providerId: string
42
74
  }
43
75
  const refreshContexts = new Map<string, RefreshContext>()
44
76
 
45
- /** baseURLs with an in-flight background refresh, to avoid pile-ups. */
77
+ /** Cache keys with an in-flight background refresh, to avoid pile-ups. */
46
78
  const refreshInFlight = new Set<string>()
47
79
 
48
80
  /**
@@ -115,6 +147,9 @@ function enrichModel(model: LiteLLMModel, info: LiteLLMModelInfo): LiteLLMModel
115
147
  supports_audio_input: model.supports_audio_input ?? info.supports_audio_input,
116
148
  input_cost_per_token: model.input_cost_per_token ?? info.input_cost_per_token,
117
149
  output_cost_per_token: model.output_cost_per_token ?? info.output_cost_per_token,
150
+ cache_read_input_token_cost: model.cache_read_input_token_cost ?? info.cache_read_input_token_cost,
151
+ cache_creation_input_token_cost:
152
+ model.cache_creation_input_token_cost ?? info.cache_creation_input_token_cost,
118
153
  }
119
154
  }
120
155
 
@@ -144,9 +179,12 @@ function toConfigModel(
144
179
  const entry: Record<string, unknown> = {
145
180
  name: formatModelName(model),
146
181
  }
147
- if (model.max_input_tokens || model.max_output_tokens) {
182
+ // Some deployments only report the OpenAI-style `max_tokens` total;
183
+ // use it as the context limit when `max_input_tokens` is absent.
184
+ const contextLimit = model.max_input_tokens ?? model.max_tokens
185
+ if (contextLimit || model.max_output_tokens) {
148
186
  entry.limit = {
149
- context: model.max_input_tokens ?? 0,
187
+ context: contextLimit ?? 0,
150
188
  output: model.max_output_tokens ?? 0,
151
189
  }
152
190
  }
@@ -164,10 +202,17 @@ function toConfigModel(
164
202
  // to their own default instead of us asserting "this model is free"
165
203
  // for something LiteLLM simply has no price anchor for (e.g. rerank).
166
204
  if (model.input_cost_per_token != null || model.output_cost_per_token != null) {
167
- entry.cost = {
205
+ const cost: Record<string, number> = {
168
206
  input: (model.input_cost_per_token ?? 0) * USD_PER_TOKEN_TO_PER_MILLION,
169
207
  output: (model.output_cost_per_token ?? 0) * USD_PER_TOKEN_TO_PER_MILLION,
170
208
  }
209
+ if (model.cache_read_input_token_cost != null) {
210
+ cost.cache_read = model.cache_read_input_token_cost * USD_PER_TOKEN_TO_PER_MILLION
211
+ }
212
+ if (model.cache_creation_input_token_cost != null) {
213
+ cost.cache_write = model.cache_creation_input_token_cost * USD_PER_TOKEN_TO_PER_MILLION
214
+ }
215
+ entry.cost = cost
171
216
  }
172
217
  const input: Array<'text' | 'image' | 'pdf' | 'audio'> = ['text']
173
218
  if (model.supports_vision) input.push('image')
@@ -202,7 +247,8 @@ async function discoverModels(
202
247
  providerId: string,
203
248
  ): Promise<Record<string, unknown> | null> {
204
249
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
205
- console.warn(
250
+ log(
251
+ 'warn',
206
252
  `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
207
253
  )
208
254
  return null
@@ -219,9 +265,10 @@ async function discoverModels(
219
265
 
220
266
  if (modelsResult.status === 'rejected') {
221
267
  const error = modelsResult.reason
222
- console.warn(
223
- `[opencode-litellm] Model discovery failed for provider "${providerId}":`,
224
- error instanceof Error ? error.message : String(error),
268
+ log(
269
+ 'warn',
270
+ `[opencode-litellm] Model discovery failed for provider "${providerId}": ` +
271
+ (error instanceof Error ? error.message : String(error)),
225
272
  )
226
273
  return null
227
274
  }
@@ -232,14 +279,16 @@ async function discoverModels(
232
279
  infoByName = infoResult.value
233
280
  } else {
234
281
  const reason = infoResult.reason
235
- console.warn(
236
- `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only:`,
237
- reason instanceof Error ? reason.message : String(reason),
282
+ log(
283
+ 'warn',
284
+ `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only: ` +
285
+ (reason instanceof Error ? reason.message : String(reason)),
238
286
  )
239
287
  }
240
288
 
241
289
  if (discovered.length === 0) {
242
- console.warn(
290
+ log(
291
+ 'warn',
243
292
  `[opencode-litellm] LiteLLM responded for provider "${providerId}" but exposed zero models.`,
244
293
  )
245
294
  return null
@@ -268,14 +317,16 @@ async function discoverModels(
268
317
  }
269
318
 
270
319
  if (unmatched.length > 0) {
271
- console.warn(
320
+ log(
321
+ 'warn',
272
322
  `[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s) on provider "${providerId}"; ` +
273
323
  `classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
274
324
  (unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
275
325
  )
276
326
  }
277
327
 
278
- console.log(
328
+ log(
329
+ 'info',
279
330
  `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
280
331
  `(${Object.keys(built).length} built` +
281
332
  (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
@@ -309,37 +360,38 @@ function mergeModels(
309
360
  }
310
361
 
311
362
  /**
312
- * Revalidate a baseURL's model cache off the critical path (SWR). The
363
+ * Revalidate a provider's model cache off the critical path (SWR). The
313
364
  * refreshed entries land in the on-disk cache and surface on the next
314
365
  * OpenCode start — OpenCode only reads provider config at startup, so
315
366
  * we can't mutate the live picker here.
316
367
  */
317
- async function backgroundRefresh(baseURL: string): Promise<void> {
318
- if (refreshInFlight.has(baseURL)) return
319
- const ctx = refreshContexts.get(baseURL)
368
+ async function backgroundRefresh(cacheKey: string): Promise<void> {
369
+ if (refreshInFlight.has(cacheKey)) return
370
+ const ctx = refreshContexts.get(cacheKey)
320
371
  if (!ctx) return
321
372
  // Skip if the cache was refreshed recently — a burst of new sessions
322
373
  // shouldn't hammer the proxy with health checks and discovery calls.
323
- const savedAt = readModelCacheSavedAt(baseURL)
374
+ const savedAt = readModelCacheSavedAt(cacheKey)
324
375
  if (savedAt !== null && Date.now() - savedAt < REFRESH_MIN_INTERVAL_MS) {
325
376
  return
326
377
  }
327
- refreshInFlight.add(baseURL)
378
+ refreshInFlight.add(cacheKey)
328
379
  try {
329
380
  const built = await withTimeout(
330
- discoverModels(baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
381
+ discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
331
382
  DISCOVERY_TIMEOUT_MS,
332
383
  )
333
384
  if (built && Object.keys(built).length > 0) {
334
- writeModelCache(baseURL, built)
335
- console.log(
336
- `[opencode-litellm] Background-refreshed model cache for ${baseURL} (${Object.keys(built).length} models)`,
385
+ writeModelCache(cacheKey, built)
386
+ log(
387
+ 'info',
388
+ `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(built).length} models)`,
337
389
  )
338
390
  }
339
391
  } catch {
340
392
  // Best-effort — a failed refresh just leaves the stale cache in place.
341
393
  } finally {
342
- refreshInFlight.delete(baseURL)
394
+ refreshInFlight.delete(cacheKey)
343
395
  }
344
396
  }
345
397
 
@@ -367,7 +419,8 @@ async function backgroundRefresh(baseURL: string): Promise<void> {
367
419
  * }
368
420
  * }
369
421
  */
370
- export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
422
+ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
423
+ initLogging(input.client)
371
424
  return {
372
425
  config: async (config: any) => {
373
426
  // Ensure the provider entry exists
@@ -435,7 +488,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
435
488
  }
436
489
 
437
490
  if (!baseURL) {
438
- console.warn(
491
+ log(
492
+ 'warn',
439
493
  `[opencode-litellm] No LiteLLM proxy found for provider "${providerId}". Configure options.baseURL or start LiteLLM on port 4000/8000/8080.`,
440
494
  )
441
495
  continue
@@ -479,13 +533,15 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
479
533
 
480
534
  const models = actualProvider.models as Record<string, unknown>
481
535
 
536
+ const cacheKey = `${providerId}@${baseURL}`
537
+
482
538
  // Remember how to reach this proxy so the `event` hook can
483
539
  // revalidate its cache in the background on new sessions.
484
- refreshContexts.set(baseURL, { apiKey, customHeaders, providerId })
540
+ refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, providerId })
485
541
 
486
542
  // 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)
543
+ // we've injected this provider's models.
544
+ const alreadyInjected = injectedModelIds.get(cacheKey)
489
545
  if (
490
546
  alreadyInjected &&
491
547
  [...alreadyInjected].every((id) => Object.hasOwn(models, id))
@@ -496,11 +552,14 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
496
552
  // SWR fast path: serve cached entries synchronously so startup
497
553
  // isn't blocked on the network. A background refresh (see the
498
554
  // `event` hook) keeps the cache fresh for the next launch.
499
- const cached = readModelCache(baseURL)
555
+ // The cache is scoped per provider so two providers pointing at
556
+ // the same proxy (with different keys) don't share model lists.
557
+ const cached = readModelCache(cacheKey)
500
558
  if (cached && Object.keys(cached).length > 0) {
501
559
  const added = mergeModels(models, cached)
502
- injectedModelIds.set(baseURL, new Set(added))
503
- console.log(
560
+ injectedModelIds.set(cacheKey, new Set(added))
561
+ log(
562
+ 'info',
504
563
  `[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
505
564
  )
506
565
  continue
@@ -515,8 +574,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
515
574
  )
516
575
  if (built && Object.keys(built).length > 0) {
517
576
  const added = mergeModels(models, built)
518
- injectedModelIds.set(baseURL, new Set(added))
519
- writeModelCache(baseURL, built)
577
+ injectedModelIds.set(cacheKey, new Set(added))
578
+ writeModelCache(cacheKey, built)
520
579
  }
521
580
  }
522
581
  },
@@ -525,8 +584,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
525
584
  // opens. Fresh data lands in the cache and surfaces on the next
526
585
  // OpenCode start (SWR).
527
586
  if (event.type !== 'session.created') return
528
- for (const baseURL of refreshContexts.keys()) {
529
- void backgroundRefresh(baseURL)
587
+ for (const cacheKey of refreshContexts.keys()) {
588
+ void backgroundRefresh(cacheKey)
530
589
  }
531
590
  },
532
591
  }
@@ -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
- }
@@ -8,7 +8,23 @@ const MODEL_INFO_ENDPOINT = '/v1/model/info'
8
8
  // payloads from remote proxies with many database-defined models can
9
9
  // be large and slow to generate.
10
10
  const HEALTH_TIMEOUT_MS = 3000
11
- const FETCH_TIMEOUT_MS = 15000
11
+ const DEFAULT_FETCH_TIMEOUT_MS = 15000
12
+
13
+ /**
14
+ * Per-request timeout for discovery fetches (`/v1/models`,
15
+ * `/v1/model/info`), overridable via `LITELLM_REQUEST_TIMEOUT_MS` for
16
+ * proxies that legitimately need longer than the 15 s default (issue
17
+ * #20). Invalid values fall back to the default.
18
+ */
19
+ export function getRequestTimeoutMs(): number {
20
+ const raw = process.env.LITELLM_REQUEST_TIMEOUT_MS
21
+ if (!raw) return DEFAULT_FETCH_TIMEOUT_MS
22
+ // Number() (not parseInt) so '12.5' or '60abc' fall back to the
23
+ // default instead of silently truncating to a bogus 12 ms timeout.
24
+ const parsed = Number(raw)
25
+ if (!Number.isInteger(parsed) || parsed <= 0) return DEFAULT_FETCH_TIMEOUT_MS
26
+ return parsed
27
+ }
12
28
 
13
29
  /**
14
30
  * Normalise a base URL so the rest of the plugin can rely on a
@@ -72,7 +88,7 @@ export async function discoverLiteLLMModels(
72
88
  const response = await fetch(url, {
73
89
  method: 'GET',
74
90
  headers: buildHeaders(apiKey, customHeaders),
75
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
91
+ signal: AbortSignal.timeout(getRequestTimeoutMs()),
76
92
  })
77
93
 
78
94
  if (!response.ok) {
@@ -98,7 +114,7 @@ export async function discoverLiteLLMModelInfo(
98
114
  const response = await fetch(url, {
99
115
  method: 'GET',
100
116
  headers: buildHeaders(apiKey, customHeaders),
101
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
117
+ signal: AbortSignal.timeout(getRequestTimeoutMs()),
102
118
  })
103
119
 
104
120
  if (!response.ok) {
@@ -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
- }