opencode-plugin-litellm 1.4.0 → 1.4.2

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
@@ -6,7 +6,7 @@
6
6
 
7
7
  # opencode-litellm
8
8
 
9
- **[OpenCode V1 + V2](https://opencode.ai) + [LiteLLM](https://github.com/BerriAI/litellm) provider with zero configuration.**
9
+ **[OpenCode CLI (v1 and v2) and Desktop](https://opencode.ai) + [LiteLLM](https://github.com/BerriAI/litellm) provider with zero configuration.**
10
10
 
11
11
  [![Works with OpenCode](https://img.shields.io/badge/works%20with-OpenCode-7C5CFF?style=flat-square)](https://opencode.ai)
12
12
  [![OpenCode V1 + V2](https://img.shields.io/badge/OpenCode%20V1%20%2B%20V2-supported-16A34A?style=flat-square)](https://opencode.ai)
@@ -211,12 +211,28 @@ Here, `openai/gpt-4o` keeps your custom name; every other model from the proxy i
211
211
  All discovered models — reasoning-tier included — register under your single
212
212
  LiteLLM provider and are invoked through `/v1/chat/completions`.
213
213
 
214
- If LiteLLM reports per-model reasoning-effort support (e.g.
215
- `supports_low_reasoning_effort`, `supports_medium_reasoning_effort`,
216
- `supports_high_reasoning_effort` in `model_info`), the plugin automatically
217
- surfaces those as OpenCode variants under the discovered model. Each variant
218
- sets `reasoningEffort` to the reported level, so you can switch between
219
- effort levels from the model picker without hand-curating every entry.
214
+ If LiteLLM reports per-model reasoning-effort support, the plugin automatically
215
+ surfaces it as OpenCode variants. Explicit `reasoning_effort_levels` (or
216
+ `supports_reasoning_efforts`) lists take precedence, including empty lists.
217
+ Otherwise, per-level `supports_*_reasoning_effort` flags enable discovery:
218
+ `low`, `medium`, and `high` are included unless explicitly disabled, while
219
+ optional levels such as `none`, `minimal`, `xhigh`, and `max` require an explicit
220
+ `true`. This handles sparse metadata such as GPT-6 Astra's `xhigh`/`max` flags
221
+ without losing its baseline levels. No levels are inferred from
222
+ `supports_reasoning: true` alone, or from negative-only effort flags when
223
+ reasoning support is unknown. Inferred variants are also suppressed when
224
+ `supported_openai_params` lists neither `reasoning_effort` nor `reasoning`.
225
+ Metadata is read from `model_info`, falling back to `litellm_params` for
226
+ missing/null values.
227
+
228
+ When explicit effort lists are absent, known GPT-5 Pro restrictions also apply:
229
+ GPT-5 Pro is limited to `high`, and GPT-5.2 Pro / GPT-5.4 Pro to `medium`, `high`,
230
+ and explicitly supported `xhigh`. These restrictions use the upstream model key
231
+ or `litellm_params.model`, including provider prefixes and dated snapshots, so
232
+ deployment aliases work too. An explicit effort list can override this fallback.
233
+
234
+ Each variant sets `reasoningEffort` to the reported level, so you can switch
235
+ between effort levels from the model picker without hand-curating every entry.
220
236
 
221
237
  > **Note**: OpenAI's reasoning-tier models (gpt-5, o1, o3, o4) reject
222
238
  > requests that combine `reasoning_effort` with function tools on
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-plugin-litellm",
4
- "version": "1.4.0",
5
- "description": "OpenCode plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
4
+ "version": "1.4.2",
5
+ "description": "OpenCode CLI (v1 and v2) and Desktop plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
6
6
  "type": "module",
7
7
  "main": "./src/index.ts",
8
8
  "exports": {
package/src/plugin/v2.ts CHANGED
@@ -43,6 +43,23 @@ interface ProviderSource {
43
43
  customHeaders?: Record<string, string>
44
44
  credentialReloadRequired: boolean
45
45
  refreshRequired: boolean
46
+ /**
47
+ * True when this source came from option/env/port auto-detection rather than
48
+ * a host-registered provider. A fallback only stands in until the real
49
+ * provider appears; reconcile replaces it at that point so the user's
50
+ * `providers.<id>.settings.baseURL` wins over the guessed endpoint.
51
+ *
52
+ * Distinct from {@link pendingPublication}: a fallback source is always
53
+ * pending until a configured provider supersedes it, whereas a configured
54
+ * source is pending only until its first successful `reload()`.
55
+ */
56
+ fromFallback: boolean
57
+ /**
58
+ * True until this source has been published to the provider registry by a
59
+ * successful `reload()`. Reconciliation retries (and re-adds) any source
60
+ * still pending, so a transient reload failure does not strand it.
61
+ */
62
+ pendingPublication: boolean
46
63
  filters: ModelFilters
47
64
  capabilities: ModelCapabilities
48
65
  formatModelNames: boolean
@@ -285,6 +302,8 @@ async function makeProviderSource(
285
302
  usesConnectionCredential,
286
303
  credentialReloadRequired: false,
287
304
  refreshRequired: false,
305
+ fromFallback: provider === undefined,
306
+ pendingPublication: true,
288
307
  baseURL,
289
308
  apiKey,
290
309
  customHeaders: Object.keys(customHeaders).length > 0 ? customHeaders : undefined,
@@ -414,41 +433,83 @@ async function refreshProviderSources(
414
433
  await Promise.all(sources.map((source) => refreshProviderSource(context, source, inFlight)))
415
434
  }
416
435
 
436
+ /**
437
+ * LiteLLM-shaped providers the host currently exposes.
438
+ *
439
+ * OpenCode 2 registers user-configured providers *after* plugin setup, so the
440
+ * list has to be re-read on later `provider.updated` events instead of being
441
+ * trusted once at startup. Otherwise a `providers.litellm.settings.baseURL`
442
+ * config is invisible to the plugin and discovery silently falls back to
443
+ * auto-detection.
444
+ */
445
+ async function listMatchingProviders(context: Context): Promise<ProviderInfo[]> {
446
+ try {
447
+ const providers = (await context.provider.list()).data
448
+ return providers.filter((provider) =>
449
+ isLiteLLMProvider(provider.id, asRecord(provider.settings)),
450
+ )
451
+ } catch (error) {
452
+ const message = error instanceof Error ? error.message : String(error)
453
+ logInfo(`[opencode-litellm] Could not read configured providers: ${message}`)
454
+ return []
455
+ }
456
+ }
457
+
458
+ /**
459
+ * Discover and add sources for LiteLLM providers that have appeared since the
460
+ * last reconciliation. Ids already present are left untouched *unless* the
461
+ * existing entry is a fallback that never came from a host-registered
462
+ * provider — in that case it is replaced, so merging a late provider overrides
463
+ * the option/env/auto-detected endpoint (including its baseURL and
464
+ * credentials). Safe to call repeatedly (startup, `provider.updated`,
465
+ * `session.created`). Returns sources that still need publishing via
466
+ * `reload()` (new providers plus any whose previous publication failed).
467
+ */
468
+ async function reconcileProviderSources(
469
+ context: Context,
470
+ pluginOptions: Record<string, unknown>,
471
+ sources: Map<string, ProviderSource>,
472
+ ): Promise<ProviderSource[]> {
473
+ const changed: ProviderSource[] = []
474
+ for (const provider of await listMatchingProviders(context)) {
475
+ const existing = sources.get(provider.id)
476
+ // Skip sources that are both configured (not a fallback) and already
477
+ // published; a pending configured source must be returned so it is retried.
478
+ if (existing && !existing.fromFallback && !existing.pendingPublication) continue
479
+ const source = await makeProviderSource(context, provider, pluginOptions)
480
+ if (!source) continue
481
+ sources.set(source.id, source)
482
+ changed.push(source)
483
+ }
484
+ return changed
485
+ }
486
+
417
487
  const definition = Plugin.define({
418
488
  id: 'opencode-litellm',
419
489
  async setup(context) {
420
490
  initV2Logging()
421
491
 
422
492
  const pluginOptions = asRecord(context.options)
423
- let providers: ProviderInfo[] = []
424
- try {
425
- providers = (await context.provider.list()).data
426
- } catch (error) {
427
- const message = error instanceof Error ? error.message : String(error)
428
- logInfo(`[opencode-litellm] Could not read configured providers: ${message}`)
493
+ const sources = new Map<string, ProviderSource>()
494
+
495
+ // First pass. On OpenCode 2 the host has not registered user-configured
496
+ // providers yet, so this typically finds only built-ins; the event loop
497
+ // below reconciles again when they appear.
498
+ await reconcileProviderSources(context, pluginOptions, sources)
499
+ // With no configured provider, fall back to purely option/env-driven
500
+ // discovery so `LITELLM_BASE_URL` and plugin options keep working.
501
+ if (sources.size === 0) {
502
+ const fallback = await makeProviderSource(context, undefined, pluginOptions)
503
+ if (fallback) sources.set(fallback.id, fallback)
429
504
  }
430
-
431
- const matchingProviders = providers.filter((provider) =>
432
- isLiteLLMProvider(provider.id, asRecord(provider.settings)),
433
- )
434
- const candidates: Array<ProviderInfo | undefined> = matchingProviders.length
435
- ? matchingProviders
436
- : [undefined]
437
- const sources: ProviderSource[] = []
438
-
439
- for (const candidate of candidates) {
440
- const source = await makeProviderSource(context, candidate, pluginOptions)
441
- if (source) sources.push(source)
442
- }
443
-
444
- if (sources.length === 0) {
505
+ if (sources.size === 0) {
445
506
  logInfo(
446
507
  '[opencode-litellm] No LiteLLM proxy found. Configure providers.litellm.settings.baseURL or start LiteLLM on port 4000/8000/8080.',
447
508
  )
448
509
  }
449
510
 
450
511
  const providerRegistration = await context.provider.transform((editor) => {
451
- for (const source of sources) {
512
+ for (const source of sources.values()) {
452
513
  const current = editor.get(source.id)
453
514
  if (current) {
454
515
  editor.update(source.id, (provider) => {
@@ -488,16 +549,79 @@ const definition = Plugin.define({
488
549
  })
489
550
  }
490
551
  }
552
+ // The initial transform is itself the publication step for sources built
553
+ // during setup, so they are no longer "pending" after this point.
554
+ for (const source of sources.values()) source.pendingPublication = false
491
555
  })
492
556
 
493
557
  const controller = new AbortController()
494
558
  const inFlight = new Map<string, Promise<void>>()
559
+
560
+ // Reconciliation is kicked off from the event loop, which must not block on
561
+ // discovery. Overlapping triggers are folded into one follow-up pass, so a
562
+ // provider that shows up mid-discovery is neither missed nor discovered
563
+ // twice.
564
+ let reconcileRunning: Promise<void> | null = null
565
+ let reconcileAgain = false
566
+
567
+ const reconcileOnce = async (): Promise<void> => {
568
+ // A newly built source is only "published" once `reload()` succeeds. Until
569
+ // then it stays `pendingPublication`, so the next pass returns and retries
570
+ // it instead of skipping it forever after a transient reload failure.
571
+ let pending: ProviderSource[]
572
+ try {
573
+ pending = await reconcileProviderSources(context, pluginOptions, sources)
574
+ } catch (error) {
575
+ const message = error instanceof Error ? error.message : String(error)
576
+ logInfo(`[opencode-litellm] Could not reconcile configured providers: ${message}`)
577
+ return
578
+ }
579
+ if (pending.length === 0) return
580
+ try {
581
+ await context.provider.reload()
582
+ for (const source of pending) source.pendingPublication = false
583
+ logInfo(
584
+ `[opencode-litellm] Registered ${pending.length} newly configured LiteLLM provider(s).`,
585
+ )
586
+ } catch (error) {
587
+ // Leave `pendingPublication` set so the next trigger retries instead of
588
+ // treating these sources as already published.
589
+ const message = error instanceof Error ? error.message : String(error)
590
+ logInfo(
591
+ `[opencode-litellm] Could not reload providers after discovering a new provider; will retry: ${message}`,
592
+ )
593
+ }
594
+ }
595
+
596
+ const reconcileAndReload = async (): Promise<void> => {
597
+ if (reconcileRunning) {
598
+ reconcileAgain = true
599
+ return reconcileRunning
600
+ }
601
+ reconcileRunning = (async () => {
602
+ do {
603
+ reconcileAgain = false
604
+ await reconcileOnce()
605
+ } while (reconcileAgain)
606
+ })().finally(() => {
607
+ reconcileRunning = null
608
+ // A trigger can land in the gap between the loop's final check and this
609
+ // continuation. Without re-checking, that update would be dropped.
610
+ if (reconcileAgain) void reconcileAndReload()
611
+ })
612
+ return reconcileRunning
613
+ }
614
+
495
615
  void (async () => {
496
616
  try {
497
617
  for await (const event of context.event.subscribe({ signal: controller.signal })) {
618
+ if (event.type === 'provider.updated') {
619
+ void reconcileAndReload()
620
+ continue
621
+ }
498
622
  if (event.type === 'credential.switched') {
499
623
  const changedSources = (await Promise.all(
500
- sources
624
+ [...sources.values()]
501
625
  .filter((source) => source.integrationID === event.data.integrationID)
502
626
  .map(async (source) =>
503
627
  (await refreshConnectionCredential(context, source)) ? source : undefined,
@@ -513,7 +637,10 @@ const definition = Plugin.define({
513
637
  continue
514
638
  }
515
639
  if (event.type !== 'session.created') continue
516
- void refreshProviderSources(context, sources, inFlight)
640
+ void (async () => {
641
+ await reconcileAndReload()
642
+ await refreshProviderSources(context, [...sources.values()], inFlight)
643
+ })()
517
644
  }
518
645
  } catch (error) {
519
646
  if (controller.signal.aborted) return
@@ -522,6 +649,12 @@ const definition = Plugin.define({
522
649
  }
523
650
  })()
524
651
 
652
+ // A provider can register during setup's own auto-detection probes, before
653
+ // the subscription above is established; that `provider.updated` would be
654
+ // lost until the next session. One idempotent pass right after subscribing
655
+ // closes that window.
656
+ void reconcileAndReload()
657
+
525
658
  return async () => {
526
659
  controller.abort()
527
660
  await providerRegistration.dispose()
@@ -67,6 +67,8 @@ export interface LiteLLMModelInfo {
67
67
  supports_vision?: boolean
68
68
  supports_reasoning?: boolean
69
69
  supports_reasoning_efforts?: string[]
70
+ reasoning_effort_levels?: string[] | null
71
+ supported_openai_params?: string[] | null
70
72
  supports_pdf_input?: boolean
71
73
  supports_audio_input?: boolean
72
74
  input_cost_per_token?: number
@@ -1,5 +1,6 @@
1
1
  import type { LiteLLMModel, LiteLLMModelInfo, LiteLLMModelInfoResponse, LiteLLMModelsResponse } from '../types'
2
2
  import { CAPABILITY_FLAGS } from './model-capabilities'
3
+ import { resolveReasoningEfforts } from './reasoning-efforts'
3
4
 
4
5
  export const DEFAULT_LITELLM_URL = 'http://localhost:4000'
5
6
  const MODELS_ENDPOINT = '/v1/models'
@@ -136,23 +137,7 @@ export async function discoverLiteLLMModelInfo(
136
137
  }
137
138
  }
138
139
 
139
- // Add supports reasoning efforts if present in litellm_params
140
- const reasoningEffortPattern = /^supports_([a-z]+)_reasoning_effort$/
141
- const efforts = new Set<string>()
142
- for (const source of [info, entry.litellm_params]) {
143
- if (!source || typeof source !== 'object') continue
144
- for (const [key, value] of Object.entries(source)) {
145
- const match = key.match(reasoningEffortPattern)
146
- if (match && value === true) {
147
- efforts.add(match[1])
148
- }
149
- }
150
- }
151
- if (efforts.size > 0) {
152
- info.supports_reasoning_efforts = [
153
- ...new Set([...(info.supports_reasoning_efforts ?? []), ...efforts]),
154
- ]
155
- }
140
+ info.supports_reasoning_efforts = resolveReasoningEfforts(info, entry.litellm_params)
156
141
 
157
142
  // Index under every alias LiteLLM may use for this model — the
158
143
  // `/v1/models` id can match any of them depending on how the
@@ -0,0 +1,90 @@
1
+ import type { LiteLLMModelInfo } from '../types'
2
+
3
+ // LiteLLM's sparse flags do not encode these provider restrictions reliably.
4
+ // Constrain inference only; explicit deployment effort lists still win.
5
+ // https://developers.openai.com/api/docs/models/gpt-5-pro
6
+ // https://developers.openai.com/api/docs/models/gpt-5.2-pro
7
+ // https://developers.openai.com/api/docs/models/gpt-5.4-pro
8
+ const RESTRICTED_EFFORTS = new Map<string, readonly string[]>([
9
+ ['gpt-5-pro', ['high']],
10
+ ['gpt-5.2-pro', ['medium', 'high', 'xhigh']],
11
+ ['gpt-5.4-pro', ['medium', 'high', 'xhigh']],
12
+ ])
13
+
14
+ function restrictedReasoningEfforts(...identifiers: unknown[]): readonly string[] | undefined {
15
+ for (const identifier of identifiers) {
16
+ if (typeof identifier !== 'string') continue
17
+ // Keys can include provider/region prefixes or dated OpenAI snapshots.
18
+ const model = identifier.split('/').pop()?.replace(/-\d{4}-\d{2}-\d{2}$/, '')
19
+ if (!model) continue
20
+ const efforts = RESTRICTED_EFFORTS.get(model)
21
+ if (efforts) return efforts
22
+ }
23
+ return undefined
24
+ }
25
+
26
+ /** Resolve discovery metadata without assuming every reasoning model accepts effort options. */
27
+ export function resolveReasoningEfforts(
28
+ info: LiteLLMModelInfo,
29
+ params?: Record<string, unknown>,
30
+ ): string[] | undefined {
31
+ const metadata: Record<string, unknown> = { ...params }
32
+ for (const [key, value] of Object.entries(info)) {
33
+ if (value != null) metadata[key] = value
34
+ }
35
+
36
+ if (metadata.supports_reasoning === false) return []
37
+
38
+ // Explicit lists are authoritative, including an empty list. In particular,
39
+ // reasoning_effort_levels can describe models that do not accept medium.
40
+ for (const key of ['reasoning_effort_levels', 'supports_reasoning_efforts']) {
41
+ const levels = metadata[key]
42
+ if (Array.isArray(levels)) {
43
+ return [...new Set(levels.filter((level): level is string => typeof level === 'string'))]
44
+ }
45
+ }
46
+
47
+ // Some search models carry effort flags even though their request handler
48
+ // rejects reasoning altogether. Accept either chat or Responses API naming.
49
+ const supportedParams = metadata.supported_openai_params
50
+ if (
51
+ Array.isArray(supportedParams) &&
52
+ !supportedParams.includes('reasoning_effort') &&
53
+ !supportedParams.includes('reasoning')
54
+ ) return []
55
+
56
+ const flags = new Map<string, boolean>()
57
+ for (const [key, value] of Object.entries(metadata)) {
58
+ const match = key.match(/^supports_([a-z]+)_reasoning_effort$/)
59
+ if (match && typeof value === 'boolean') flags.set(match[1], value)
60
+ }
61
+ if (flags.size === 0) return undefined
62
+ // Negative flags only rule out levels; they do not establish reasoning support.
63
+ if (metadata.supports_reasoning !== true && ![...flags.values()].includes(true)) return undefined
64
+
65
+ // LiteLLM's per-level flags are sparse: medium/high have no standard flags,
66
+ // and low is opt-out. Requiring an explicit true hides these baseline levels
67
+ // on models such as GPT-6 Astra, whose only positive flags are xhigh/max.
68
+ // Keep optional levels opt-in rather than guessing none/minimal support.
69
+ // See litellm/router_utils/reasoning_effort_capability.py upstream.
70
+ const efforts = new Set<string>()
71
+ for (const effort of ['low', 'medium', 'high']) {
72
+ if (flags.get(effort) !== false) efforts.add(effort)
73
+ }
74
+ for (const [effort, supported] of flags) {
75
+ if (supported) efforts.add(effort)
76
+ }
77
+
78
+ const restricted = restrictedReasoningEfforts(metadata.key, params?.model)
79
+ if (restricted) {
80
+ for (const effort of efforts) {
81
+ if (!restricted.includes(effort)) efforts.delete(effort)
82
+ }
83
+ }
84
+
85
+ const order = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
86
+ return [
87
+ ...order.filter((effort) => efforts.has(effort)),
88
+ ...[...efforts].filter((effort) => !order.includes(effort)),
89
+ ]
90
+ }