opencode-plugin-litellm 1.0.0 → 1.1.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
@@ -77,7 +77,9 @@ opencode
77
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
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`. |
79
79
  | 🌐 **Gateway-friendly** | Supports `customHeaders` for proxies behind Cloudflare Access or other API gateways requiring extra HTTP headers. |
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. |
80
+ | ðŸ§Đ **Splittable catalog** | `includeModels` / `excludeModels` (glob patterns) let one LiteLLM proxy be divided into several OpenCode providers — e.g. by naming prefix — without hand-maintaining a model list. |
81
+ | ⏱ïļ **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. |
82
+ | 📝 **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. |
81
83
  | ðŸĪ **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
82
84
  | ðŸŠķ **Zero runtime deps** | Only depends on `@opencode-ai/plugin`. No build step, no bundler. |
83
85
  | 🔒 **TypeScript strict** | Strict-mode compiled, fully typed public API. |
@@ -212,6 +214,16 @@ If your LiteLLM proxy requires a master key, expose it via either approach:
212
214
 
213
215
  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.
214
216
 
217
+ ### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
218
+
219
+ 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:
220
+
221
+ ```bash
222
+ export LITELLM_REQUEST_TIMEOUT_MS=60000
223
+ ```
224
+
225
+ 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.
226
+
215
227
  ### Custom headers (Cloudflare Access, API gateways)
216
228
 
217
229
  If your LiteLLM proxy is behind Cloudflare Access or another gateway that requires extra HTTP headers, use the `customHeaders` option:
@@ -235,6 +247,39 @@ If your LiteLLM proxy is behind Cloudflare Access or another gateway that requir
235
247
 
236
248
  These headers are included in every request the plugin makes during model discovery (health check and `/v1/models`). To obtain a Cloudflare Access Service Token, follow the [Cloudflare docs](https://developers.cloudflare.com/cloudflare-one/identity/service-tokens/).
237
249
 
250
+ ### Splitting one proxy into multiple providers (`includeModels` / `excludeModels`)
251
+
252
+ If your LiteLLM catalog mixes naming conventions from different teams or environments (e.g. `prod/*` and `staging/*`), you can point two OpenCode providers at the *same* proxy and have each one surface only its slice:
253
+
254
+ ```jsonc
255
+ {
256
+ "provider": {
257
+ "litellm": {
258
+ "npm": "@ai-sdk/openai-compatible",
259
+ "name": "Prod",
260
+ "options": {
261
+ "baseURL": "http://localhost:4000/v1",
262
+ "includeModels": ["prod/*"]
263
+ }
264
+ },
265
+ "litellm-staging": {
266
+ "npm": "@ai-sdk/openai-compatible",
267
+ "name": "Staging",
268
+ "options": {
269
+ "baseURL": "http://localhost:4000/v1",
270
+ "includeModels": ["staging/*"],
271
+ "excludeModels": ["staging/*-canary"]
272
+ }
273
+ }
274
+ }
275
+ }
276
+ ```
277
+
278
+ - `includeModels` is evaluated first — only ids matching at least one pattern are kept. Omit it to keep everything.
279
+ - `excludeModels` is evaluated after and always wins, even over `includeModels`.
280
+ - Patterns support only `*` (any run of characters); everything else is matched literally, so dots in ids like `gpt-4.1` need no escaping.
281
+ - Filtering happens before the on-disk cache is written, so each provider's cached view respects its own filters.
282
+
238
283
  ## 🔧 How it works
239
284
 
240
285
  ```mermaid
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-plugin-litellm",
4
- "version": "1.0.0",
4
+ "version": "1.1.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",
@@ -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 {
@@ -13,15 +14,45 @@ import {
13
14
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
14
15
  import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
15
16
  import { readModelCache, writeModelCache, readModelCacheSavedAt } from '../utils/model-cache'
17
+ import { passesModelFilter } from '../utils/model-filter'
18
+ import type { ModelFilters } from '../utils/model-filter'
16
19
 
17
20
  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
21
+ // Covers the 3 s health check plus the parallel models/model-info fetch
22
+ // phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
23
+ // proxies aren't cut off by the overall cap either (issue #20).
24
+ const DISCOVERY_TIMEOUT_MS = Math.max(20000, getRequestTimeoutMs() + 5000)
21
25
  // Don't revalidate a baseURL's cache more often than this, so a burst
22
26
  // of `session.created` events can't generate repeated discovery traffic.
23
27
  const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000 // 5 minutes
24
28
 
29
+ type LogLevel = 'info' | 'warn' | 'error' | 'debug'
30
+
31
+ let logClient: PluginInput['client'] | null = null
32
+
33
+ function initLogging(client: PluginInput['client']): void {
34
+ logClient = client
35
+ }
36
+
37
+ /**
38
+ * Route plugin logs through OpenCode's log API instead of stdout.
39
+ * console.* writes straight into the same terminal the OpenCode TUI
40
+ * renders in, corrupting the interface on every background refresh
41
+ * (issue #15); client.app.log lands in OpenCode's log files instead.
42
+ */
43
+ function log(level: LogLevel, message: string): void {
44
+ if (logClient) {
45
+ void logClient.app
46
+ .log({ body: { service: 'opencode-litellm', level, message } })
47
+ .catch(() => {})
48
+ return
49
+ }
50
+ // No client wired up (unit tests, unusual embedders) — fall back to
51
+ // the console rather than silently dropping diagnostics.
52
+ if (level === 'info' || level === 'debug') console.log(message)
53
+ else console.warn(message)
54
+ }
55
+
25
56
  /**
26
57
  * OpenCode invokes the `config` hook several times per run with a
27
58
  * cumulative config object. Track which model ids we already injected
@@ -41,6 +72,7 @@ interface RefreshContext {
41
72
  baseURL: string
42
73
  apiKey?: string
43
74
  customHeaders?: Record<string, string>
75
+ filters: ModelFilters
44
76
  providerId: string
45
77
  }
46
78
  const refreshContexts = new Map<string, RefreshContext>()
@@ -98,6 +130,24 @@ function readCustomHeaders(
98
130
  return undefined
99
131
  }
100
132
 
133
+ /**
134
+ * Read the `includeModels`/`excludeModels` glob filters from a provider
135
+ * options block (issue #21's feature: split one proxy's catalog across
136
+ * several OpenCode providers). Non-string entries are dropped; an empty
137
+ * result means "don't filter".
138
+ */
139
+ function readModelFilters(options: Record<string, unknown>): ModelFilters {
140
+ const readPatterns = (raw: unknown): string[] | undefined => {
141
+ if (!Array.isArray(raw)) return undefined
142
+ const out = raw.filter((v): v is string => typeof v === 'string')
143
+ return out.length > 0 ? out : undefined
144
+ }
145
+ return {
146
+ includeModels: readPatterns(options.includeModels),
147
+ excludeModels: readPatterns(options.excludeModels),
148
+ }
149
+ }
150
+
101
151
  /**
102
152
  * Overlay metadata from `/v1/model/info` onto a `/v1/models` entry.
103
153
  * Fields already present on the lean entry win; the info block only
@@ -208,6 +258,11 @@ function toConfigModel(
208
258
  *
209
259
  * Pure with respect to plugin config: it performs the network calls,
210
260
  * classifies + formats each model, and returns a `{ id -> entry }` map.
261
+ * The provider's `includeModels`/`excludeModels` filters are applied
262
+ * here (not at merge time) so every path that persists or serves a
263
+ * cache — cold discovery and background refresh — writes the same
264
+ * filtered view.
265
+ *
211
266
  * Returns `null` when the proxy is unreachable/unauthorized or exposes
212
267
  * no models, so callers can distinguish "no data" from "empty result".
213
268
  */
@@ -216,9 +271,11 @@ async function discoverModels(
216
271
  apiKey: string | undefined,
217
272
  customHeaders: Record<string, string> | undefined,
218
273
  providerId: string,
274
+ filters: ModelFilters = {},
219
275
  ): Promise<Record<string, unknown> | null> {
220
276
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
221
- console.warn(
277
+ log(
278
+ 'warn',
222
279
  `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
223
280
  )
224
281
  return null
@@ -235,9 +292,10 @@ async function discoverModels(
235
292
 
236
293
  if (modelsResult.status === 'rejected') {
237
294
  const error = modelsResult.reason
238
- console.warn(
239
- `[opencode-litellm] Model discovery failed for provider "${providerId}":`,
240
- error instanceof Error ? error.message : String(error),
295
+ log(
296
+ 'warn',
297
+ `[opencode-litellm] Model discovery failed for provider "${providerId}": ` +
298
+ (error instanceof Error ? error.message : String(error)),
241
299
  )
242
300
  return null
243
301
  }
@@ -248,14 +306,16 @@ async function discoverModels(
248
306
  infoByName = infoResult.value
249
307
  } else {
250
308
  const reason = infoResult.reason
251
- console.warn(
252
- `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only:`,
253
- reason instanceof Error ? reason.message : String(reason),
309
+ log(
310
+ 'warn',
311
+ `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only: ` +
312
+ (reason instanceof Error ? reason.message : String(reason)),
254
313
  )
255
314
  }
256
315
 
257
316
  if (discovered.length === 0) {
258
- console.warn(
317
+ log(
318
+ 'warn',
259
319
  `[opencode-litellm] LiteLLM responded for provider "${providerId}" but exposed zero models.`,
260
320
  )
261
321
  return null
@@ -264,6 +324,7 @@ async function discoverModels(
264
324
  const built: Record<string, unknown> = {}
265
325
  let skipped = 0
266
326
  let wildcards = 0
327
+ let filtered = 0
267
328
  const unmatched: string[] = []
268
329
  for (const model of discovered) {
269
330
  // `deepseek/*` is an access rule, not a callable model. But a
@@ -273,6 +334,13 @@ async function discoverModels(
273
334
  wildcards++
274
335
  continue
275
336
  }
337
+ // `includeModels`/`excludeModels` let one LiteLLM proxy be split
338
+ // across several OpenCode providers (e.g. by upstream naming
339
+ // prefix) without hand-maintaining a model list.
340
+ if (!passesModelFilter(model.id, filters.includeModels, filters.excludeModels)) {
341
+ filtered++
342
+ continue
343
+ }
276
344
  const info = infoByName?.get(model.id)
277
345
  if (infoByName && !info) unmatched.push(model.id)
278
346
  const entry = toConfigModel(info ? enrichModel(model, info) : model, info)
@@ -284,18 +352,31 @@ async function discoverModels(
284
352
  }
285
353
 
286
354
  if (unmatched.length > 0) {
287
- console.warn(
355
+ log(
356
+ 'warn',
288
357
  `[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s) on provider "${providerId}"; ` +
289
358
  `classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
290
359
  (unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
291
360
  )
292
361
  }
293
362
 
294
- console.log(
363
+ // Only blame the filters when every non-wildcard model was rejected by
364
+ // them — if some hit `skipped` (non-chat) instead, `built` being empty
365
+ // has an unrelated cause and this warning would misdirect the user.
366
+ if (filtered > 0 && filtered + wildcards === discovered.length) {
367
+ log(
368
+ 'warn',
369
+ `[opencode-litellm] includeModels/excludeModels filtered out all ${filtered} model(s) discovered for provider "${providerId}" — check the glob patterns in options.includeModels/options.excludeModels.`,
370
+ )
371
+ }
372
+
373
+ log(
374
+ 'info',
295
375
  `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
296
376
  `(${Object.keys(built).length} built` +
297
377
  (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
298
378
  (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
379
+ (filtered > 0 ? `, ${filtered} filtered by includeModels/excludeModels` : '') +
299
380
  ')',
300
381
  )
301
382
 
@@ -343,12 +424,13 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
343
424
  refreshInFlight.add(cacheKey)
344
425
  try {
345
426
  const built = await withTimeout(
346
- discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
427
+ discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId, ctx.filters),
347
428
  DISCOVERY_TIMEOUT_MS,
348
429
  )
349
430
  if (built && Object.keys(built).length > 0) {
350
431
  writeModelCache(cacheKey, built)
351
- console.log(
432
+ log(
433
+ 'info',
352
434
  `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(built).length} models)`,
353
435
  )
354
436
  }
@@ -383,7 +465,8 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
383
465
  * }
384
466
  * }
385
467
  */
386
- export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
468
+ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
469
+ initLogging(input.client)
387
470
  return {
388
471
  config: async (config: any) => {
389
472
  // Ensure the provider entry exists
@@ -441,6 +524,7 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
441
524
  const storedKey = await getOpenCodeStoredApiKey(providerId)
442
525
  const apiKey = configuredKey ?? envKey ?? storedKey
443
526
  const customHeaders = readCustomHeaders(options)
527
+ const filters = readModelFilters(options)
444
528
 
445
529
  // Resolve base URL
446
530
  let baseURL: string | null = null
@@ -451,7 +535,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
451
535
  }
452
536
 
453
537
  if (!baseURL) {
454
- console.warn(
538
+ log(
539
+ 'warn',
455
540
  `[opencode-litellm] No LiteLLM proxy found for provider "${providerId}". Configure options.baseURL or start LiteLLM on port 4000/8000/8080.`,
456
541
  )
457
542
  continue
@@ -499,7 +584,7 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
499
584
 
500
585
  // Remember how to reach this proxy so the `event` hook can
501
586
  // revalidate its cache in the background on new sessions.
502
- refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, providerId })
587
+ refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, filters, providerId })
503
588
 
504
589
  // Repeat config-hook invocations within a run are a no-op once
505
590
  // we've injected this provider's models.
@@ -520,7 +605,8 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
520
605
  if (cached && Object.keys(cached).length > 0) {
521
606
  const added = mergeModels(models, cached)
522
607
  injectedModelIds.set(cacheKey, new Set(added))
523
- console.log(
608
+ log(
609
+ 'info',
524
610
  `[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
525
611
  )
526
612
  continue
@@ -530,7 +616,7 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
530
616
  // persist for subsequent startups. Capped by a timeout so a slow
531
617
  // proxy never blocks boot.
532
618
  const built = await withTimeout(
533
- discoverModels(baseURL, apiKey, customHeaders, providerId),
619
+ discoverModels(baseURL, apiKey, customHeaders, providerId, filters),
534
620
  DISCOVERY_TIMEOUT_MS,
535
621
  )
536
622
  if (built && Object.keys(built).length > 0) {
@@ -1,2 +1,3 @@
1
1
  export * from './litellm-api'
2
2
  export * from './format-model-name'
3
+ export * from './model-filter'
@@ -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) {
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Minimal glob matching for model-id filters (`includeModels`/
3
+ * `excludeModels`). Supports only `*` (any run of characters, including
4
+ * none) — enough for the common case (`"anthropic/*"`) without pulling
5
+ * in a glob dependency. Everything else in the pattern is matched
6
+ * literally.
7
+ */
8
+ function globToRegExp(pattern: string): RegExp {
9
+ const escaped = pattern
10
+ .split('*')
11
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
12
+ .join('.*')
13
+ return new RegExp(`^${escaped}$`)
14
+ }
15
+
16
+ function matchesAny(id: string, patterns: readonly string[]): boolean {
17
+ return patterns.some((pattern) => globToRegExp(pattern).test(id))
18
+ }
19
+
20
+ /**
21
+ * Decide whether a discovered model id should be injected into a
22
+ * provider, given that provider's `includeModels`/`excludeModels`
23
+ * options.
24
+ *
25
+ * - No `includeModels` → every id passes the include step (default:
26
+ * don't filter).
27
+ * - `includeModels` present → only ids matching at least one pattern
28
+ * pass.
29
+ * - `excludeModels` is applied after, and always wins over `include`.
30
+ */
31
+ export function passesModelFilter(
32
+ id: string,
33
+ includeModels?: readonly string[],
34
+ excludeModels?: readonly string[],
35
+ ): boolean {
36
+ if (includeModels && includeModels.length > 0 && !matchesAny(id, includeModels)) {
37
+ return false
38
+ }
39
+ if (excludeModels && excludeModels.length > 0 && matchesAny(id, excludeModels)) {
40
+ return false
41
+ }
42
+ return true
43
+ }
44
+
45
+ /**
46
+ * The parsed `includeModels`/`excludeModels` options for one provider.
47
+ * `undefined` (or empty) arrays mean "don't filter" — a misconfigured
48
+ * option degrades toward no filtering rather than an empty provider.
49
+ */
50
+ export interface ModelFilters {
51
+ includeModels?: string[]
52
+ excludeModels?: string[]
53
+ }