opencode-plugin-litellm 1.0.1 → 1.2.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,8 @@ 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. |
81
+ | 🎚️ **Capability overrides** | `modelCapabilities` forces or retracts per-model capability flags (`supports_vision`, `supports_function_calling`, …) when `/v1/model/info` is unavailable or disagrees with your deployment. |
80
82
  | ⏱️ **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
83
  | 📝 **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
84
  | 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
@@ -246,6 +248,64 @@ If your LiteLLM proxy is behind Cloudflare Access or another gateway that requir
246
248
 
247
249
  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
250
 
251
+ ### Splitting one proxy into multiple providers (`includeModels` / `excludeModels`)
252
+
253
+ 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:
254
+
255
+ ```jsonc
256
+ {
257
+ "provider": {
258
+ "litellm": {
259
+ "npm": "@ai-sdk/openai-compatible",
260
+ "name": "Prod",
261
+ "options": {
262
+ "baseURL": "http://localhost:4000/v1",
263
+ "includeModels": ["prod/*"]
264
+ }
265
+ },
266
+ "litellm-staging": {
267
+ "npm": "@ai-sdk/openai-compatible",
268
+ "name": "Staging",
269
+ "options": {
270
+ "baseURL": "http://localhost:4000/v1",
271
+ "includeModels": ["staging/*"],
272
+ "excludeModels": ["staging/*-canary"]
273
+ }
274
+ }
275
+ }
276
+ }
277
+ ```
278
+
279
+ - `includeModels` is evaluated first — only ids matching at least one pattern are kept. Omit it to keep everything.
280
+ - `excludeModels` is evaluated after and always wins, even over `includeModels`.
281
+ - Patterns support only `*` (any run of characters); everything else is matched literally, so dots in ids like `gpt-4.1` need no escaping.
282
+ - Filtering happens before the on-disk cache is written, so each provider's cached view respects its own filters.
283
+
284
+ ### Correcting capability flags (`modelCapabilities`)
285
+
286
+ Model classification (tool-call badge, attachments, reasoning, input modalities) leans on the capability flags LiteLLM reports via `/v1/model/info`. If your proxy doesn't expose that endpoint, or reports a flag that doesn't match your deployment, override flags per model id:
287
+
288
+ ```jsonc
289
+ {
290
+ "provider": {
291
+ "litellm": {
292
+ "options": {
293
+ "baseURL": "http://localhost:4000/v1",
294
+ "modelCapabilities": {
295
+ "te-gpt-5.4-mini": { "supports_function_calling": true },
296
+ "openai/gpt-4o": { "supports_vision": false }
297
+ }
298
+ }
299
+ }
300
+ }
301
+ }
302
+ ```
303
+
304
+ - Overrides apply on top of whatever the proxy reports, with an explicit `false` winning — a flag the proxy never reported can be forced on just the same.
305
+ - Keys are exact model ids as they appear in `/v1/models` (not globs).
306
+ - Overridden flags flow into the picker exactly like natively reported ones, and the adjusted view is what gets persisted to the model cache.
307
+ - Changing `modelCapabilities` (or `includeModels`/`excludeModels`) starts a fresh discovery on the next start — the cache is scoped by that config — so the picker reflects the new flags immediately.
308
+
249
309
  ## 🔧 How it works
250
310
 
251
311
  ```mermaid
@@ -410,9 +470,11 @@ src/
410
470
  │ ├── litellm-api.ts # health check, discovery (/v1/models + /v1/model/info), auto-detect
411
471
  │ ├── format-model-name.ts # name formatting, categorization
412
472
  │ ├── model-cache.ts # stale-while-revalidate on-disk model cache
473
+ │ ├── model-filter.ts # includeModels/excludeModels glob filtering
474
+ │ ├── model-capabilities.ts # per-model capability flag overrides
413
475
  │ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
414
476
  └── plugin/
415
- └── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering)
477
+ └── index.ts # LiteLLMPlugin entry (config hook, enrichment, filtering, capability overrides)
416
478
 
417
479
  test/ # vitest suite for the pure logic
418
480
  ```
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.2.0",
5
5
  "description": "OpenCode plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
@@ -13,7 +13,16 @@ import {
13
13
  } from '../utils/format-model-name'
14
14
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
15
15
  import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
16
- import { readModelCache, writeModelCache, readModelCacheSavedAt } from '../utils/model-cache'
16
+ import {
17
+ buildCacheKey,
18
+ readModelCache,
19
+ writeModelCache,
20
+ readModelCacheSavedAt,
21
+ } from '../utils/model-cache'
22
+ import { passesModelFilter } from '../utils/model-filter'
23
+ import type { ModelFilters } from '../utils/model-filter'
24
+ import { applyCapabilityOverrides, parseModelCapabilities } from '../utils/model-capabilities'
25
+ import type { ModelCapabilities } from '../utils/model-capabilities'
17
26
 
18
27
  const CHAT_PROVIDER_ID = 'litellm'
19
28
  // Covers the 3 s health check plus the parallel models/model-info fetch
@@ -70,6 +79,8 @@ interface RefreshContext {
70
79
  baseURL: string
71
80
  apiKey?: string
72
81
  customHeaders?: Record<string, string>
82
+ filters: ModelFilters
83
+ capabilities: ModelCapabilities
73
84
  providerId: string
74
85
  }
75
86
  const refreshContexts = new Map<string, RefreshContext>()
@@ -128,31 +139,60 @@ function readCustomHeaders(
128
139
  }
129
140
 
130
141
  /**
131
- * Overlay metadata from `/v1/model/info` onto a `/v1/models` entry.
132
- * Fields already present on the lean entry win; the info block only
133
- * fills gaps (notably `mode`, which `/v1/models` omits for
134
- * database-defined models).
142
+ * Read the `includeModels`/`excludeModels` glob filters from a provider
143
+ * options block (issue #21's feature: split one proxy's catalog across
144
+ * several OpenCode providers). Non-string entries are dropped; an empty
145
+ * result means "don't filter".
135
146
  */
136
- function enrichModel(model: LiteLLMModel, info: LiteLLMModelInfo): LiteLLMModel {
147
+ function readModelFilters(options: Record<string, unknown>): ModelFilters {
148
+ const readPatterns = (raw: unknown): string[] | undefined => {
149
+ if (!Array.isArray(raw)) return undefined
150
+ const out = raw.filter((v): v is string => typeof v === 'string')
151
+ return out.length > 0 ? out : undefined
152
+ }
137
153
  return {
138
- ...model,
139
- mode: model.mode ?? info.mode,
140
- max_tokens: model.max_tokens ?? info.max_tokens,
141
- max_input_tokens: model.max_input_tokens ?? info.max_input_tokens,
142
- max_output_tokens: model.max_output_tokens ?? info.max_output_tokens,
143
- supports_function_calling: model.supports_function_calling ?? info.supports_function_calling,
144
- supports_vision: model.supports_vision ?? info.supports_vision,
145
- supports_reasoning: model.supports_reasoning ?? info.supports_reasoning,
146
- supports_pdf_input: model.supports_pdf_input ?? info.supports_pdf_input,
147
- supports_audio_input: model.supports_audio_input ?? info.supports_audio_input,
148
- input_cost_per_token: model.input_cost_per_token ?? info.input_cost_per_token,
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,
154
+ includeModels: readPatterns(options.includeModels),
155
+ excludeModels: readPatterns(options.excludeModels),
153
156
  }
154
157
  }
155
158
 
159
+ /**
160
+ * Overlay metadata onto a `/v1/models` entry in three tiers: the entry's
161
+ * own fields win, `/v1/model/info` fills gaps (notably `mode`, which
162
+ * `/v1/models` omits for database-defined models), and finally
163
+ * user-configured `modelCapabilities` overrides apply — explicit
164
+ * `false` included — because the user knows their deployment better
165
+ * than either endpoint (issue #25).
166
+ */
167
+ function enrichModel(
168
+ model: LiteLLMModel,
169
+ info: LiteLLMModelInfo | undefined,
170
+ overrides?: Record<string, boolean>,
171
+ ): LiteLLMModel {
172
+ return applyCapabilityOverrides(
173
+ {
174
+ ...model,
175
+ mode: model.mode ?? info?.mode,
176
+ max_tokens: model.max_tokens ?? info?.max_tokens,
177
+ max_input_tokens: model.max_input_tokens ?? info?.max_input_tokens,
178
+ max_output_tokens: model.max_output_tokens ?? info?.max_output_tokens,
179
+ supports_function_calling:
180
+ model.supports_function_calling ?? info?.supports_function_calling,
181
+ supports_vision: model.supports_vision ?? info?.supports_vision,
182
+ supports_reasoning: model.supports_reasoning ?? info?.supports_reasoning,
183
+ supports_pdf_input: model.supports_pdf_input ?? info?.supports_pdf_input,
184
+ supports_audio_input: model.supports_audio_input ?? info?.supports_audio_input,
185
+ input_cost_per_token: model.input_cost_per_token ?? info?.input_cost_per_token,
186
+ output_cost_per_token: model.output_cost_per_token ?? info?.output_cost_per_token,
187
+ cache_read_input_token_cost:
188
+ model.cache_read_input_token_cost ?? info?.cache_read_input_token_cost,
189
+ cache_creation_input_token_cost:
190
+ model.cache_creation_input_token_cost ?? info?.cache_creation_input_token_cost,
191
+ },
192
+ overrides,
193
+ )
194
+ }
195
+
156
196
  /**
157
197
  * OpenCode's `cost` config field is USD per **million** tokens (the
158
198
  * models.dev convention); LiteLLM's `/v1/model/info` reports USD per
@@ -237,6 +277,11 @@ function toConfigModel(
237
277
  *
238
278
  * Pure with respect to plugin config: it performs the network calls,
239
279
  * classifies + formats each model, and returns a `{ id -> entry }` map.
280
+ * The provider's `includeModels`/`excludeModels` filters and
281
+ * `modelCapabilities` overrides are applied here (not at merge time) so
282
+ * every path that persists or serves a cache — cold discovery and
283
+ * background refresh — writes the same adjusted view.
284
+ *
240
285
  * Returns `null` when the proxy is unreachable/unauthorized or exposes
241
286
  * no models, so callers can distinguish "no data" from "empty result".
242
287
  */
@@ -245,6 +290,8 @@ async function discoverModels(
245
290
  apiKey: string | undefined,
246
291
  customHeaders: Record<string, string> | undefined,
247
292
  providerId: string,
293
+ filters: ModelFilters = {},
294
+ capabilities: ModelCapabilities = {},
248
295
  ): Promise<Record<string, unknown> | null> {
249
296
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
250
297
  log(
@@ -297,6 +344,7 @@ async function discoverModels(
297
344
  const built: Record<string, unknown> = {}
298
345
  let skipped = 0
299
346
  let wildcards = 0
347
+ let filtered = 0
300
348
  const unmatched: string[] = []
301
349
  for (const model of discovered) {
302
350
  // `deepseek/*` is an access rule, not a callable model. But a
@@ -306,9 +354,16 @@ async function discoverModels(
306
354
  wildcards++
307
355
  continue
308
356
  }
357
+ // `includeModels`/`excludeModels` let one LiteLLM proxy be split
358
+ // across several OpenCode providers (e.g. by upstream naming
359
+ // prefix) without hand-maintaining a model list.
360
+ if (!passesModelFilter(model.id, filters.includeModels, filters.excludeModels)) {
361
+ filtered++
362
+ continue
363
+ }
309
364
  const info = infoByName?.get(model.id)
310
365
  if (infoByName && !info) unmatched.push(model.id)
311
- const entry = toConfigModel(info ? enrichModel(model, info) : model, info)
366
+ const entry = toConfigModel(enrichModel(model, info, capabilities[model.id]), info)
312
367
  if (!entry) {
313
368
  skipped++
314
369
  continue
@@ -325,12 +380,23 @@ async function discoverModels(
325
380
  )
326
381
  }
327
382
 
383
+ // Only blame the filters when every non-wildcard model was rejected by
384
+ // them — if some hit `skipped` (non-chat) instead, `built` being empty
385
+ // has an unrelated cause and this warning would misdirect the user.
386
+ if (filtered > 0 && filtered + wildcards === discovered.length) {
387
+ log(
388
+ 'warn',
389
+ `[opencode-litellm] includeModels/excludeModels filtered out all ${filtered} model(s) discovered for provider "${providerId}" — check the glob patterns in options.includeModels/options.excludeModels.`,
390
+ )
391
+ }
392
+
328
393
  log(
329
394
  'info',
330
395
  `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
331
396
  `(${Object.keys(built).length} built` +
332
397
  (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
333
398
  (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
399
+ (filtered > 0 ? `, ${filtered} filtered by includeModels/excludeModels` : '') +
334
400
  ')',
335
401
  )
336
402
 
@@ -378,7 +444,14 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
378
444
  refreshInFlight.add(cacheKey)
379
445
  try {
380
446
  const built = await withTimeout(
381
- discoverModels(ctx.baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
447
+ discoverModels(
448
+ ctx.baseURL,
449
+ ctx.apiKey,
450
+ ctx.customHeaders,
451
+ ctx.providerId,
452
+ ctx.filters,
453
+ ctx.capabilities,
454
+ ),
382
455
  DISCOVERY_TIMEOUT_MS,
383
456
  )
384
457
  if (built && Object.keys(built).length > 0) {
@@ -478,6 +551,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
478
551
  const storedKey = await getOpenCodeStoredApiKey(providerId)
479
552
  const apiKey = configuredKey ?? envKey ?? storedKey
480
553
  const customHeaders = readCustomHeaders(options)
554
+ const filters = readModelFilters(options)
555
+ const capabilities = parseModelCapabilities(options.modelCapabilities)
481
556
 
482
557
  // Resolve base URL
483
558
  let baseURL: string | null = null
@@ -533,11 +608,21 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
533
608
 
534
609
  const models = actualProvider.models as Record<string, unknown>
535
610
 
536
- const cacheKey = `${providerId}@${baseURL}`
611
+ // Identity includes the filter/capability config: those are
612
+ // baked into cached entries, so changing them must start a
613
+ // fresh discovery instead of serving the old adjusted view.
614
+ const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities)
537
615
 
538
616
  // Remember how to reach this proxy so the `event` hook can
539
617
  // revalidate its cache in the background on new sessions.
540
- refreshContexts.set(cacheKey, { baseURL, apiKey, customHeaders, providerId })
618
+ refreshContexts.set(cacheKey, {
619
+ baseURL,
620
+ apiKey,
621
+ customHeaders,
622
+ filters,
623
+ capabilities,
624
+ providerId,
625
+ })
541
626
 
542
627
  // Repeat config-hook invocations within a run are a no-op once
543
628
  // we've injected this provider's models.
@@ -569,7 +654,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
569
654
  // persist for subsequent startups. Capped by a timeout so a slow
570
655
  // proxy never blocks boot.
571
656
  const built = await withTimeout(
572
- discoverModels(baseURL, apiKey, customHeaders, providerId),
657
+ discoverModels(baseURL, apiKey, customHeaders, providerId, filters, capabilities),
573
658
  DISCOVERY_TIMEOUT_MS,
574
659
  )
575
660
  if (built && Object.keys(built).length > 0) {
@@ -1,2 +1,4 @@
1
1
  export * from './litellm-api'
2
2
  export * from './format-model-name'
3
+ export * from './model-capabilities'
4
+ export * from './model-filter'
@@ -1,4 +1,5 @@
1
1
  import type { LiteLLMModel, LiteLLMModelInfo, LiteLLMModelInfoResponse, LiteLLMModelsResponse } from '../types'
2
+ import { CAPABILITY_FLAGS } from './model-capabilities'
2
3
 
3
4
  export const DEFAULT_LITELLM_URL = 'http://localhost:4000'
4
5
  const MODELS_ENDPOINT = '/v1/models'
@@ -128,14 +129,7 @@ export async function discoverLiteLLMModelInfo(
128
129
  // Some deployments set capability flags on the params block rather
129
130
  // than inside model_info. Fill those gaps so enrichment sees them.
130
131
  const info: LiteLLMModelInfo = { ...entry.model_info }
131
- const capabilityFlags = [
132
- 'supports_vision',
133
- 'supports_function_calling',
134
- 'supports_reasoning',
135
- 'supports_pdf_input',
136
- 'supports_audio_input',
137
- ] as const
138
- for (const flag of capabilityFlags) {
132
+ for (const flag of CAPABILITY_FLAGS) {
139
133
  const paramsValue = entry.litellm_params?.[flag]
140
134
  if (info[flag] == null && typeof paramsValue === 'boolean') {
141
135
  info[flag] = paramsValue
@@ -47,6 +47,57 @@ function cacheFile(cacheKey: string): string {
47
47
  return join(cacheDir(), `models-${hash}.json`)
48
48
  }
49
49
 
50
+ /**
51
+ * Canonical JSON serialization (object keys sorted) so semantically
52
+ * identical filter/capability configs fingerprint identically no matter
53
+ * the key order in the user's `opencode.json`.
54
+ */
55
+ function canonicalize(value: unknown): string {
56
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`
57
+ if (value && typeof value === 'object') {
58
+ const entries = Object.entries(value as Record<string, unknown>)
59
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
60
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`)
61
+ return `{${entries.join(',')}}`
62
+ }
63
+ return JSON.stringify(value)
64
+ }
65
+
66
+ /**
67
+ * Cache identity for a provider's model view. `providerId@baseURL`
68
+ * alone isn't enough: `includeModels`/`excludeModels` and
69
+ * `modelCapabilities` are baked into cached entries by discovery, so a
70
+ * config change must not reuse the old cache — it would keep serving
71
+ * the previous adjusted view until a second restart. A fingerprint is
72
+ * appended whenever adjustments exist (pattern order ignored); default
73
+ * configs keep the plain key so existing caches stay warm across
74
+ * plugin upgrades.
75
+ */
76
+ export function buildCacheKey(
77
+ providerId: string,
78
+ baseURL: string,
79
+ filters: { includeModels?: string[]; excludeModels?: string[] },
80
+ capabilities: Record<string, Record<string, boolean>>,
81
+ ): string {
82
+ const base = `${providerId}@${baseURL}`
83
+ const hasAdjustments =
84
+ (filters.includeModels?.length ?? 0) > 0 ||
85
+ (filters.excludeModels?.length ?? 0) > 0 ||
86
+ Object.keys(capabilities).length > 0
87
+ if (!hasAdjustments) return base
88
+ const fingerprint = createHash('sha256')
89
+ .update(
90
+ canonicalize({
91
+ includeModels: filters.includeModels ? [...filters.includeModels].sort() : undefined,
92
+ excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
93
+ capabilities,
94
+ }),
95
+ )
96
+ .digest('hex')
97
+ .slice(0, 12)
98
+ return `${base}@${fingerprint}`
99
+ }
100
+
50
101
  /**
51
102
  * Read cached model entries for a cache key. Returns `null` on any
52
103
  * problem (missing file, parse error, version mismatch, or an entry
@@ -0,0 +1,50 @@
1
+ export const CAPABILITY_FLAGS = [
2
+ 'supports_vision',
3
+ 'supports_function_calling',
4
+ 'supports_reasoning',
5
+ 'supports_pdf_input',
6
+ 'supports_audio_input',
7
+ ] as const
8
+
9
+ export type CapabilityFlag = (typeof CAPABILITY_FLAGS)[number]
10
+
11
+ /**
12
+ * Per-model boolean capability overrides keyed by exact model id
13
+ * (`provider.litellm.options.modelCapabilities`). Keys of the inner
14
+ * record are not restricted to `CapabilityFlag`: any boolean capability
15
+ * key LiteLLM reports is accepted, so future flags work without a
16
+ * plugin change.
17
+ */
18
+ export type ModelCapabilities = Record<string, Record<string, boolean>>
19
+
20
+ /**
21
+ * Defensively parse the `modelCapabilities` provider option. Non-object
22
+ * input, non-object per-model values, and non-boolean flag values are
23
+ * dropped; everything else (including explicit `false`) is kept.
24
+ */
25
+ export function parseModelCapabilities(raw: unknown): ModelCapabilities {
26
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
27
+ const out: ModelCapabilities = {}
28
+ for (const [modelId, flags] of Object.entries(raw as Record<string, unknown>)) {
29
+ if (!flags || typeof flags !== 'object' || Array.isArray(flags)) continue
30
+ const parsed: Record<string, boolean> = {}
31
+ for (const [flag, value] of Object.entries(flags as Record<string, unknown>)) {
32
+ if (typeof value === 'boolean') parsed[flag] = value
33
+ }
34
+ if (Object.keys(parsed).length > 0) out[modelId] = parsed
35
+ }
36
+ return out
37
+ }
38
+
39
+ /**
40
+ * Overlay user-configured capability flags onto a (possibly enriched)
41
+ * model entry. Explicit `false` wins over whatever the proxy reported,
42
+ * and unknown-to-the-proxy flags are added outright.
43
+ */
44
+ export function applyCapabilityOverrides<T extends object>(
45
+ model: T,
46
+ overrides?: Readonly<Record<string, boolean>>,
47
+ ): T {
48
+ if (!overrides || Object.keys(overrides).length === 0) return model
49
+ return Object.assign({}, model, overrides)
50
+ }
@@ -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
+ }