opencode-plugin-litellm 1.0.1 → 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,6 +77,7 @@ 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
+ | 🧩 **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. |
80
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. |
81
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. |
82
83
  | 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
@@ -246,6 +247,39 @@ If your LiteLLM proxy is behind Cloudflare Access or another gateway that requir
246
247
 
247
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/).
248
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
+
249
283
  ## 🔧 How it works
250
284
 
251
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.1",
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",
@@ -14,6 +14,8 @@ import {
14
14
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
15
15
  import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
16
16
  import { readModelCache, writeModelCache, readModelCacheSavedAt } from '../utils/model-cache'
17
+ import { passesModelFilter } from '../utils/model-filter'
18
+ import type { ModelFilters } from '../utils/model-filter'
17
19
 
18
20
  const CHAT_PROVIDER_ID = 'litellm'
19
21
  // Covers the 3 s health check plus the parallel models/model-info fetch
@@ -70,6 +72,7 @@ interface RefreshContext {
70
72
  baseURL: string
71
73
  apiKey?: string
72
74
  customHeaders?: Record<string, string>
75
+ filters: ModelFilters
73
76
  providerId: string
74
77
  }
75
78
  const refreshContexts = new Map<string, RefreshContext>()
@@ -127,6 +130,24 @@ function readCustomHeaders(
127
130
  return undefined
128
131
  }
129
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
+
130
151
  /**
131
152
  * Overlay metadata from `/v1/model/info` onto a `/v1/models` entry.
132
153
  * Fields already present on the lean entry win; the info block only
@@ -237,6 +258,11 @@ function toConfigModel(
237
258
  *
238
259
  * Pure with respect to plugin config: it performs the network calls,
239
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
+ *
240
266
  * Returns `null` when the proxy is unreachable/unauthorized or exposes
241
267
  * no models, so callers can distinguish "no data" from "empty result".
242
268
  */
@@ -245,6 +271,7 @@ async function discoverModels(
245
271
  apiKey: string | undefined,
246
272
  customHeaders: Record<string, string> | undefined,
247
273
  providerId: string,
274
+ filters: ModelFilters = {},
248
275
  ): Promise<Record<string, unknown> | null> {
249
276
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
250
277
  log(
@@ -297,6 +324,7 @@ async function discoverModels(
297
324
  const built: Record<string, unknown> = {}
298
325
  let skipped = 0
299
326
  let wildcards = 0
327
+ let filtered = 0
300
328
  const unmatched: string[] = []
301
329
  for (const model of discovered) {
302
330
  // `deepseek/*` is an access rule, not a callable model. But a
@@ -306,6 +334,13 @@ async function discoverModels(
306
334
  wildcards++
307
335
  continue
308
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
+ }
309
344
  const info = infoByName?.get(model.id)
310
345
  if (infoByName && !info) unmatched.push(model.id)
311
346
  const entry = toConfigModel(info ? enrichModel(model, info) : model, info)
@@ -325,12 +360,23 @@ async function discoverModels(
325
360
  )
326
361
  }
327
362
 
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
+
328
373
  log(
329
374
  'info',
330
375
  `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
331
376
  `(${Object.keys(built).length} built` +
332
377
  (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
333
378
  (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
379
+ (filtered > 0 ? `, ${filtered} filtered by includeModels/excludeModels` : '') +
334
380
  ')',
335
381
  )
336
382
 
@@ -378,7 +424,7 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
378
424
  refreshInFlight.add(cacheKey)
379
425
  try {
380
426
  const built = await withTimeout(
381
- discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
427
+ discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId, ctx.filters),
382
428
  DISCOVERY_TIMEOUT_MS,
383
429
  )
384
430
  if (built && Object.keys(built).length > 0) {
@@ -478,6 +524,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
478
524
  const storedKey = await getOpenCodeStoredApiKey(providerId)
479
525
  const apiKey = configuredKey ?? envKey ?? storedKey
480
526
  const customHeaders = readCustomHeaders(options)
527
+ const filters = readModelFilters(options)
481
528
 
482
529
  // Resolve base URL
483
530
  let baseURL: string | null = null
@@ -537,7 +584,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
537
584
 
538
585
  // Remember how to reach this proxy so the `event` hook can
539
586
  // revalidate its cache in the background on new sessions.
540
- refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, providerId })
587
+ refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, filters, providerId })
541
588
 
542
589
  // Repeat config-hook invocations within a run are a no-op once
543
590
  // we've injected this provider's models.
@@ -569,7 +616,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
569
616
  // persist for subsequent startups. Capped by a timeout so a slow
570
617
  // proxy never blocks boot.
571
618
  const built = await withTimeout(
572
- discoverModels(baseURL, apiKey, customHeaders, providerId),
619
+ discoverModels(baseURL, apiKey, customHeaders, providerId, filters),
573
620
  DISCOVERY_TIMEOUT_MS,
574
621
  )
575
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'
@@ -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
+ }