opencode-plugin-litellm 1.4.2 → 1.5.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 @@ also shows how to configure a provider directly in `opencode.json`.
77
77
  | 🧠 **Modality-aware** | Enriches `/v1/models` entries with `/v1/model/info` (`mode`, token limits, capability flags) and hides embedding / image / audio models from the picker. |
78
78
  | 💵 **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. |
79
79
  | 🧩 **Reasoning-effort variants** | When LiteLLM reports per-model effort support (`supports_low_reasoning_effort`, …), the plugin surfaces each level as a picker variant automatically. |
80
+ | 🧭 **Responses-API routing** | Models LiteLLM reports with `mode: "responses"` are invoked through `/v1/responses` instead of `/v1/chat/completions`, with no extra configuration. OpenCode 2 overrides the runtime package per model; OpenCode 1 gets a `<provider>-responses` sibling. |
80
81
  | 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, `providers.litellm.settings.apiKey`, and OpenCode `/connect` credentials on the V1 server path. |
81
82
  | 🌐 **Gateway-friendly** | Supports provider `headers` (and the legacy `customHeaders` option) for proxies behind Cloudflare Access or other API gateways. |
82
83
  | 🧩 **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. |
@@ -208,8 +209,11 @@ Here, `openai/gpt-4o` keeps your custom name; every other model from the proxy i
208
209
 
209
210
  ### Reasoning models and effort variants
210
211
 
211
- All discovered models — reasoning-tier included — register under your single
212
- LiteLLM provider and are invoked through `/v1/chat/completions`.
212
+ All discovered models register under your single LiteLLM provider, and models
213
+ LiteLLM reports with `mode: "responses"` are invoked through the OpenAI
214
+ Responses API (`/v1/responses`) instead of `/v1/chat/completions`. See
215
+ [Responses API models](#responses-api-models) for how that routing is applied
216
+ on each OpenCode version.
213
217
 
214
218
  If LiteLLM reports per-model reasoning-effort support, the plugin automatically
215
219
  surfaces it as OpenCode variants. Explicit `reasoning_effort_levels` (or
@@ -236,11 +240,59 @@ between effort levels from the model picker without hand-curating every entry.
236
240
 
237
241
  > **Note**: OpenAI's reasoning-tier models (gpt-5, o1, o3, o4) reject
238
242
  > requests that combine `reasoning_effort` with function tools on
239
- > `/v1/chat/completions`. If you hit that error, fix it on the LiteLLM
240
- > side — e.g. enable the Responses API for that model
241
- > (`use_responses_api: true` in its `litellm_params`) — or leave
242
- > `reasoningEffort` unset for that model in OpenCode. See the FAQ entry
243
- > below.
243
+ > `/v1/chat/completions`. When LiteLLM reports such a model with
244
+ > `mode: "responses"` the plugin routes it to `/v1/responses` automatically;
245
+ > otherwise reach it without `reasoningEffort`. See the FAQ entry below.
246
+
247
+ ### Responses API models
248
+
249
+ LiteLLM reports `mode` per model on `/v1/model/info` (the plugin fetches it
250
+ alongside `/v1/models`). When a model's `mode` is `responses`, the plugin routes
251
+ that model to `/v1/responses` instead of `/v1/chat/completions`. Only the
252
+ reported `mode` is used; the plugin does not guess from the model id, so an alias
253
+ that merely looks like a reasoning model stays on the transport LiteLLM actually
254
+ serves it from.
255
+
256
+ `mode` comes from LiteLLM's model cost map / the model's configured mode, not
257
+ from `use_responses_api`. If a model you expect to be routed isn't, check
258
+ `GET /v1/model/info` and confirm its `model_info.mode` is `responses` for the
259
+ deployment the proxy exposes under that id.
260
+
261
+ The routing is applied without any extra configuration, and it differs by
262
+ OpenCode version because the two versions pick a runtime package differently:
263
+
264
+ - **OpenCode 2** chooses the runtime per model. A Responses model keeps its
265
+ provider id and simply overrides the package to
266
+ `@opencode/ai/providers/openai/responses`. Chat models are untouched, and no
267
+ additional provider appears.
268
+ - **OpenCode 1** chooses the runtime per provider, so the plugin adds a sibling
269
+ provider named `<provider>-responses` (for the default `litellm` provider,
270
+ `litellm-responses`) using the `@ai-sdk/openai` package, which defaults to the
271
+ Responses API. It reuses the same endpoint, credentials, and custom headers,
272
+ and is created only when at least one model needs it.
273
+
274
+ Because the OpenCode 1 sibling occupies the `-responses` id suffix, the plugin
275
+ does not manage any provider whose id ends with `-responses`; pick a different
276
+ name if you want the plugin to discover models into a provider of your own.
277
+ Selecting a Responses model on OpenCode 1 therefore means picking
278
+ `<provider>-responses/<model>` rather than `<provider>/<model>`.
279
+
280
+ > **Upgrading on OpenCode 1 (model-id change).** Before this routing existed, a
281
+ > Responses-tier model was reachable as `<provider>/<model>` (over Chat
282
+ > Completions). It now lives under `<provider>-responses/<model>`. Any saved
283
+ > session, agent, or `opencode.json` reference that hard-codes the old
284
+ > `<provider>/<model>` id needs to be repointed, or it will fail to resolve.
285
+ > OpenCode 2 is unaffected — the model keeps its provider id.
286
+
287
+ > **Hand-curated models on OpenCode 1.** OpenCode 1 chooses the runtime per
288
+ > provider, so routing a model to the Responses API means putting it in the
289
+ > `<provider>-responses` provider. The plugin only relocates models it
290
+ > discovered itself; entries you hand-defined under the chat provider keep
291
+ > their place and stay on Chat Completions. To route a hand-defined model
292
+ > through the Responses API on OpenCode 1, define it under the
293
+ > `<provider>-responses` provider (or omit it and let discovery add it).
294
+ > OpenCode 2 needs no relocation because it overrides the runtime per model, so
295
+ > the same model keeps its provider id either way.
244
296
 
245
297
  ### Authentication
246
298
 
@@ -519,10 +571,10 @@ The `customHeaders` map works for any gateway that requires extra HTTP headers
519
571
  <details>
520
572
  <summary><b>I get <code>Function tools with reasoning_effort are not supported … in /v1/chat/completions</code> — what do I do?</b></summary>
521
573
 
522
- 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:
574
+ 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. When LiteLLM reports such a model with `mode: "responses"`, the plugin sends that model to `/v1/responses` and the error goes away. See [Responses API models](#responses-api-models).
523
575
 
524
- - Enable the Responses API for that model in your LiteLLM config (e.g. `use_responses_api: true` in its `litellm_params`), or
525
- - Leave the model's `reasoningEffort` unset in OpenCode (don't pick a reasoning-effort variant for it).
576
+ - If the model isn't routed, confirm `/v1/model/info` reports `model_info.mode: "responses"` for it. `mode` comes from LiteLLM's model cost map / the model's configured mode — setting `use_responses_api: true` in `litellm_params` does not by itself change it. The plugin acts only on the reported `mode` and does not guess from the model id.
577
+ - If you'd rather stay on Chat Completions, leave the model's `reasoningEffort` unset in OpenCode (don't pick a reasoning-effort variant for it).
526
578
 
527
579
  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.
528
580
  </details>
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.4.2",
4
+ "version": "1.5.0",
5
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",
@@ -11,11 +11,12 @@ import {
11
11
  formatModelName,
12
12
  categorizeModel,
13
13
  } from '../utils/format-model-name'
14
+ import { requiresResponsesAPI } from '../utils/transport'
14
15
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
15
16
  import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
16
17
  import {
17
18
  buildCacheKey,
18
- readModelCache,
19
+ readModelCacheEntry,
19
20
  writeModelCache,
20
21
  readModelCacheSavedAt,
21
22
  } from '../utils/model-cache'
@@ -25,6 +26,13 @@ import { applyCapabilityOverrides, parseModelCapabilities } from '../utils/model
25
26
  import type { ModelCapabilities } from '../utils/model-capabilities'
26
27
 
27
28
  const CHAT_PROVIDER_ID = 'litellm'
29
+ // The OpenCode 1 config hook can only choose a runtime package per provider,
30
+ // so models that need the Responses API get a sibling provider. OpenCode 2
31
+ // selects the runtime per model instead (see plugin/v2.ts) and never creates
32
+ // this provider. The suffix is reserved: the config hook skips ids that end
33
+ // with it so it never treats its own sibling as a chat provider.
34
+ const RESPONSES_PROVIDER_SUFFIX = '-responses'
35
+ const RESPONSES_NPM = '@ai-sdk/openai'
28
36
  // Covers the 3 s health check plus the parallel models/model-info fetch
29
37
  // phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
30
38
  // proxies aren't cut off by the overall cap either (issue #20).
@@ -150,6 +158,27 @@ export function readCustomHeaders(
150
158
  return undefined
151
159
  }
152
160
 
161
+ /**
162
+ * Collect the gateway headers a provider needs on *every* request — both the
163
+ * plugin's own discovery fetches and the completion-time runtime.
164
+ *
165
+ * OpenCode 1 hands the provider's native `options.headers` to the runtime
166
+ * package, but the plugin's discovery fetches historically read only the
167
+ * legacy `customHeaders` key. A gateway that authenticates via
168
+ * `options.headers` (e.g. Cloudflare Access) would therefore serve
169
+ * completions while every discovery call 401s. Merge both here, with
170
+ * `customHeaders` winning on conflict, so discovery and runtime agree.
171
+ */
172
+ export function readProviderHeaders(
173
+ options: Record<string, unknown>,
174
+ ): Record<string, string> | undefined {
175
+ const merged = {
176
+ ...readHeaderMap(options.headers),
177
+ ...(readCustomHeaders(options) ?? {}),
178
+ }
179
+ return Object.keys(merged).length > 0 ? merged : undefined
180
+ }
181
+
153
182
  /**
154
183
  * Read the `includeModels`/`excludeModels` glob filters from a provider
155
184
  * options block (issue #21's feature: split one proxy's catalog across
@@ -296,16 +325,29 @@ export function toConfigModel(
296
325
  return entry
297
326
  }
298
327
 
328
+ /**
329
+ * Result of discovering a LiteLLM proxy's models.
330
+ *
331
+ * `models` is the `{ id -> entry }` map written into an OpenCode provider
332
+ * config (or translated into `Model.Info` on OpenCode 2). `responsesIds`
333
+ * lists the subset that must be invoked through the OpenAI Responses API;
334
+ * callers route those accordingly without inspecting each entry.
335
+ */
336
+ export interface DiscoveredModels {
337
+ models: Record<string, unknown>
338
+ responsesIds: string[]
339
+ }
340
+
299
341
  /**
300
342
  * Fetch and build OpenCode model entries from a LiteLLM proxy.
301
343
  *
302
344
  * Pure with respect to plugin config: it performs the network calls,
303
- * classifies + formats each model, and returns a `{ id -> entry }` map.
304
- * The provider's `includeModels`/`excludeModels` filters,
305
- * `modelCapabilities` overrides and `formatModelNames` choice are
306
- * applied here (not at merge time) so every path that persists or
307
- * serves a cache — cold discovery and background refresh — writes the
308
- * same adjusted view.
345
+ * classifies + formats each model, and returns the built entries plus the
346
+ * ids that require the Responses API. The provider's
347
+ * `includeModels`/`excludeModels` filters, `modelCapabilities` overrides and
348
+ * `formatModelNames` choice are applied here (not at merge time) so every
349
+ * path that persists or serves a cache — cold discovery and background
350
+ * refresh — writes the same adjusted view.
309
351
  *
310
352
  * Returns `null` when the proxy is unreachable/unauthorized or exposes
311
353
  * no models, so callers can distinguish "no data" from "empty result".
@@ -318,7 +360,7 @@ export async function discoverModels(
318
360
  filters: ModelFilters = {},
319
361
  capabilities: ModelCapabilities = {},
320
362
  formatModelNames = true,
321
- ): Promise<Record<string, unknown> | null> {
363
+ ): Promise<DiscoveredModels | null> {
322
364
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
323
365
  log(
324
366
  'warn',
@@ -368,6 +410,7 @@ export async function discoverModels(
368
410
  }
369
411
 
370
412
  const built: Record<string, unknown> = {}
413
+ const responsesIds: string[] = []
371
414
  let skipped = 0
372
415
  let wildcards = 0
373
416
  let filtered = 0
@@ -389,16 +432,14 @@ export async function discoverModels(
389
432
  }
390
433
  const info = infoByName?.get(model.id)
391
434
  if (infoByName && !info) unmatched.push(model.id)
392
- const entry = toConfigModel(
393
- enrichModel(model, info, capabilities[model.id]),
394
- info,
395
- formatModelNames,
396
- )
435
+ const enriched = enrichModel(model, info, capabilities[model.id])
436
+ const entry = toConfigModel(enriched, info, formatModelNames)
397
437
  if (!entry) {
398
438
  skipped++
399
439
  continue
400
440
  }
401
441
  built[model.id] = entry
442
+ if (requiresResponsesAPI(enriched)) responsesIds.push(model.id)
402
443
  }
403
444
 
404
445
  if (unmatched.length > 0) {
@@ -430,7 +471,7 @@ export async function discoverModels(
430
471
  ')',
431
472
  )
432
473
 
433
- return built
474
+ return { models: built, responsesIds }
434
475
  }
435
476
 
436
477
  /**
@@ -455,6 +496,134 @@ function mergeModels(
455
496
  return added
456
497
  }
457
498
 
499
+ /**
500
+ * Ensure the sibling provider that carries Responses-API models exists in
501
+ * the OpenCode 1 config, mirroring the chat provider's endpoint and
502
+ * credentials. Returns its `models` map.
503
+ *
504
+ * The Responses runtime is `@ai-sdk/openai` (AI SDK 5's OpenAI provider
505
+ * defaults to `/v1/responses`). The sibling is only materialized when at
506
+ * least one discovered model needs it, so chat-only proxies keep a single
507
+ * provider and never pay for the extra entry.
508
+ */
509
+ function ensureResponsesProvider(
510
+ config: { provider: Record<string, unknown> },
511
+ baseProviderId: string,
512
+ baseProvider: Record<string, unknown>,
513
+ baseURL: string,
514
+ apiKey: string | undefined,
515
+ customHeaders: Record<string, string> | undefined,
516
+ ): Record<string, unknown> {
517
+ const id = `${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`
518
+ if (!config.provider[id] || typeof config.provider[id] !== 'object') {
519
+ config.provider[id] = {}
520
+ }
521
+ const provider = config.provider[id] as Record<string, unknown>
522
+ if (!provider.npm) provider.npm = RESPONSES_NPM
523
+ if (typeof provider.name !== 'string' || !provider.name) {
524
+ const baseName =
525
+ typeof baseProvider.name === 'string' && baseProvider.name
526
+ ? baseProvider.name
527
+ : 'LiteLLM (proxy)'
528
+ provider.name = `${baseName} Responses`
529
+ }
530
+ if (!provider.options || typeof provider.options !== 'object') {
531
+ provider.options = {}
532
+ }
533
+ const options = provider.options as Record<string, unknown>
534
+ if (!options.baseURL) options.baseURL = `${baseURL}/v1`
535
+ if (!options.apiKey && apiKey) options.apiKey = apiKey
536
+ // OpenCode 1 reads provider headers from `options.headers` and hands them to
537
+ // the runtime package (`@ai-sdk/openai` here); it has no `customHeaders` key.
538
+ // Mirror the chat provider's native headers and promote the plugin's
539
+ // `customHeaders` so Responses requests carry the same gateway headers.
540
+ const baseOptions = (baseProvider.options ?? {}) as Record<string, unknown>
541
+ const mergedHeaders = {
542
+ ...readHeaderMap(baseOptions.headers),
543
+ ...(customHeaders ?? {}),
544
+ ...readHeaderMap(options.headers),
545
+ }
546
+ if (Object.keys(mergedHeaders).length > 0) {
547
+ options.headers = mergedHeaders
548
+ }
549
+ if (!provider.models || typeof provider.models !== 'object') {
550
+ provider.models = {}
551
+ }
552
+ return provider.models as Record<string, unknown>
553
+ }
554
+
555
+ /**
556
+ * Extract a `string -> string` header map from an arbitrary provider option
557
+ * value, ignoring anything that isn't a string. Returns an empty map for
558
+ * missing or malformed input.
559
+ */
560
+ function readHeaderMap(value: unknown): Record<string, string> {
561
+ const out: Record<string, string> = {}
562
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
563
+ for (const [key, header] of Object.entries(value as Record<string, unknown>)) {
564
+ if (typeof header === 'string') out[key] = header
565
+ }
566
+ }
567
+ return out
568
+ }
569
+
570
+ /**
571
+ * Split freshly discovered entries into the chat provider and the Responses
572
+ * sibling, injecting each side without clobbering curated entries. Returns
573
+ * every id this call added, across both providers, so the config hook's
574
+ * idempotency check sees a single set.
575
+ */
576
+ function injectDiscoveredModels(
577
+ config: { provider: Record<string, unknown> },
578
+ baseProviderId: string,
579
+ baseProvider: Record<string, unknown>,
580
+ baseModels: Record<string, unknown>,
581
+ entries: Record<string, unknown>,
582
+ responsesIds: readonly string[],
583
+ baseURL: string,
584
+ apiKey: string | undefined,
585
+ customHeaders: Record<string, string> | undefined,
586
+ ): string[] {
587
+ const responsesSet = new Set(responsesIds)
588
+ const existingSibling = config.provider[`${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`]
589
+ const siblingModelsExisting: Record<string, unknown> =
590
+ existingSibling &&
591
+ typeof existingSibling === 'object' &&
592
+ (existingSibling as Record<string, unknown>).models &&
593
+ typeof (existingSibling as Record<string, unknown>).models === 'object'
594
+ ? ((existingSibling as Record<string, unknown>).models as Record<string, unknown>)
595
+ : {}
596
+
597
+ const chatEntries: Record<string, unknown> = {}
598
+ const responsesEntries: Record<string, unknown> = {}
599
+ for (const [id, entry] of Object.entries(entries)) {
600
+ // A model already present under the other provider was curated there (or
601
+ // injected by an earlier run); leave it alone instead of duplicating it
602
+ // across both providers.
603
+ if (responsesSet.has(id)) {
604
+ if (Object.hasOwn(baseModels, id)) continue
605
+ responsesEntries[id] = entry
606
+ } else {
607
+ if (Object.hasOwn(siblingModelsExisting, id)) continue
608
+ chatEntries[id] = entry
609
+ }
610
+ }
611
+
612
+ const added = mergeModels(baseModels, chatEntries)
613
+ if (Object.keys(responsesEntries).length > 0) {
614
+ const siblingModels = ensureResponsesProvider(
615
+ config,
616
+ baseProviderId,
617
+ baseProvider,
618
+ baseURL,
619
+ apiKey,
620
+ customHeaders,
621
+ )
622
+ added.push(...mergeModels(siblingModels, responsesEntries))
623
+ }
624
+ return added
625
+ }
626
+
458
627
  /**
459
628
  * Revalidate a provider's model cache off the critical path (SWR). The
460
629
  * refreshed entries land in the on-disk cache and surface on the next
@@ -473,7 +642,7 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
473
642
  }
474
643
  refreshInFlight.add(cacheKey)
475
644
  try {
476
- const built = await withTimeout(
645
+ const discovered = await withTimeout(
477
646
  discoverModels(
478
647
  ctx.baseURL,
479
648
  ctx.apiKey,
@@ -485,11 +654,11 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
485
654
  ),
486
655
  DISCOVERY_TIMEOUT_MS,
487
656
  )
488
- if (built && Object.keys(built).length > 0) {
489
- writeModelCache(cacheKey, built)
657
+ if (discovered && Object.keys(discovered.models).length > 0) {
658
+ writeModelCache(cacheKey, discovered.models, discovered.responsesIds)
490
659
  log(
491
660
  'info',
492
- `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(built).length} models)`,
661
+ `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(discovered.models).length} models)`,
493
662
  )
494
663
  }
495
664
  } catch {
@@ -535,6 +704,9 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
535
704
  const liteLLMProviders: Array<{ id: string; provider: Record<string, unknown> }> = []
536
705
 
537
706
  for (const id of providerIds) {
707
+ // The Responses sibling is created and populated below; never treat
708
+ // it as a chat provider (that would recurse into `…-responses-responses`).
709
+ if (id.endsWith(RESPONSES_PROVIDER_SUFFIX)) continue
538
710
  const provider = config.provider[id]
539
711
  if (provider && typeof provider === 'object') {
540
712
  const options = (provider.options ?? {}) as Record<string, unknown>
@@ -581,7 +753,10 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
581
753
  */
582
754
  const storedKey = await getOpenCodeStoredApiKey(providerId)
583
755
  const apiKey = configuredKey ?? envKey ?? storedKey
584
- const customHeaders = readCustomHeaders(options)
756
+ // Native `options.headers` and the legacy `customHeaders` both reach
757
+ // discovery and the runtime, so a gateway that only sets one still
758
+ // authenticates the plugin's own fetches.
759
+ const customHeaders = readProviderHeaders(options)
585
760
  const filters = readModelFilters(options)
586
761
  const capabilities = parseModelCapabilities(options.modelCapabilities)
587
762
  const formatModelNames = readFormatModelNames(options)
@@ -659,12 +834,27 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
659
834
  providerId,
660
835
  })
661
836
 
837
+ // The Responses sibling (if any) holds a disjoint set of ids, so the
838
+ // idempotency check has to look at both providers.
839
+ const responsesProviderId = `${providerId}${RESPONSES_PROVIDER_SUFFIX}`
840
+ const responsesModels = (): Record<string, unknown> => {
841
+ const sibling = config.provider[responsesProviderId]
842
+ if (!sibling || typeof sibling !== 'object') return {}
843
+ const candidate = (sibling as Record<string, unknown>).models
844
+ return candidate && typeof candidate === 'object'
845
+ ? (candidate as Record<string, unknown>)
846
+ : {}
847
+ }
848
+
662
849
  // Repeat config-hook invocations within a run are a no-op once
663
850
  // we've injected this provider's models.
664
851
  const alreadyInjected = injectedModelIds.get(cacheKey)
665
852
  if (
666
853
  alreadyInjected &&
667
- [...alreadyInjected].every((id) => Object.hasOwn(models, id))
854
+ [...alreadyInjected].every(
855
+ (id) =>
856
+ Object.hasOwn(models, id) || Object.hasOwn(responsesModels(), id),
857
+ )
668
858
  ) {
669
859
  continue
670
860
  }
@@ -674,13 +864,23 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
674
864
  // `event` hook) keeps the cache fresh for the next launch.
675
865
  // The cache is scoped per provider so two providers pointing at
676
866
  // the same proxy (with different keys) don't share model lists.
677
- const cached = readModelCache(cacheKey)
678
- if (cached && Object.keys(cached).length > 0) {
679
- const added = mergeModels(models, cached)
867
+ const cached = readModelCacheEntry(cacheKey)
868
+ if (cached && Object.keys(cached.models).length > 0) {
869
+ const added = injectDiscoveredModels(
870
+ config,
871
+ providerId,
872
+ actualProvider,
873
+ models,
874
+ cached.models,
875
+ cached.responsesIds,
876
+ baseURL,
877
+ apiKey,
878
+ customHeaders,
879
+ )
680
880
  injectedModelIds.set(cacheKey, new Set(added))
681
881
  log(
682
882
  'info',
683
- `[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
883
+ `[opencode-litellm] Loaded ${Object.keys(cached.models).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
684
884
  )
685
885
  continue
686
886
  }
@@ -688,7 +888,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
688
888
  // Cold cache: do a live fetch (slow first run only), inject, and
689
889
  // persist for subsequent startups. Capped by a timeout so a slow
690
890
  // proxy never blocks boot.
691
- const built = await withTimeout(
891
+ const discovered = await withTimeout(
692
892
  discoverModels(
693
893
  baseURL,
694
894
  apiKey,
@@ -700,10 +900,20 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
700
900
  ),
701
901
  DISCOVERY_TIMEOUT_MS,
702
902
  )
703
- if (built && Object.keys(built).length > 0) {
704
- const added = mergeModels(models, built)
903
+ if (discovered && Object.keys(discovered.models).length > 0) {
904
+ const added = injectDiscoveredModels(
905
+ config,
906
+ providerId,
907
+ actualProvider,
908
+ models,
909
+ discovered.models,
910
+ discovered.responsesIds,
911
+ baseURL,
912
+ apiKey,
913
+ customHeaders,
914
+ )
705
915
  injectedModelIds.set(cacheKey, new Set(added))
706
- writeModelCache(cacheKey, built)
916
+ writeModelCache(cacheKey, discovered.models, discovered.responsesIds)
707
917
  }
708
918
  }
709
919
  },
package/src/plugin/v2.ts CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  } from './index'
15
15
  import {
16
16
  buildCacheKey,
17
- readModelCache,
17
+ readModelCacheEntry,
18
18
  readModelCacheSavedAt,
19
19
  writeModelCache,
20
20
  } from '../utils/model-cache'
@@ -25,6 +25,22 @@ import type { ModelFilters } from '../utils/model-filter'
25
25
 
26
26
  const CHAT_PROVIDER_ID = 'litellm'
27
27
  const OPENAI_COMPATIBLE_PACKAGE = '@opencode/ai/providers/openai-compatible'
28
+ // Runtime package that talks to `/v1/responses`. OpenCode 2 lets one model
29
+ // override the provider's package, so Responses models stay under their
30
+ // original provider id and no sibling provider is needed here.
31
+ //
32
+ // `@opencode/ai/providers/openai/responses` is the Responses runtime OpenCode
33
+ // bundles today; a plain OpenAI-compatible provider defaults to the Chat
34
+ // Completions runtime, so the override is what selects the Responses API.
35
+ //
36
+ // Note this is the OpenAI-specific runtime: it applies OpenAI request defaults
37
+ // (`store: false`, plus `reasoningEffort`/`reasoningSummary`/encrypted-reasoning
38
+ // `include` for `gpt-5*` ids) on top of the proxy endpoint. The provider-neutral
39
+ // `@opencode/ai/providers/openai-compatible/responses` is the closer match for a
40
+ // generic LiteLLM proxy, but it must actually load in the target OpenCode 2.x
41
+ // (`@opencode/ai@2.0.19` ships both). Verified live against the OpenAI runtime;
42
+ // switch here if the compatible variant becomes reliably available.
43
+ const RESPONSES_PACKAGE = '@opencode/ai/providers/openai/responses'
28
44
  const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000
29
45
 
30
46
  type ProviderInfo = Awaited<ReturnType<Context['provider']['list']>>['data'][number]
@@ -98,6 +114,7 @@ function numberOrZero(value: unknown): number {
98
114
  function toProviderModels(
99
115
  providerID: string,
100
116
  entries: Record<string, unknown>,
117
+ responsesIds: ReadonlySet<string> = new Set<string>(),
101
118
  ): Model.Info[] {
102
119
  const provider = Provider.ID.make(providerID)
103
120
 
@@ -138,6 +155,10 @@ function toProviderModels(
138
155
  return [
139
156
  {
140
157
  ...defaults,
158
+ // A model that targets `/v1/responses` overrides the provider's
159
+ // runtime package for itself, so it keeps the provider id while
160
+ // still reaching the Responses API.
161
+ ...(responsesIds.has(modelID) ? { package: RESPONSES_PACKAGE } : {}),
141
162
  name: readString(entry.name) ?? modelID,
142
163
  limit: {
143
164
  context: numberOrDefault(limit.context, defaults.limit.context),
@@ -269,10 +290,12 @@ async function makeProviderSource(
269
290
  const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
270
291
  formatModelNames,
271
292
  })
272
- let entries = readModelCache(cacheKey)
293
+ const cacheEntry = readModelCacheEntry(cacheKey)
294
+ let entries = cacheEntry?.models ?? null
295
+ let responsesIds = cacheEntry?.responsesIds ?? []
273
296
 
274
297
  if (!entries || Object.keys(entries).length === 0) {
275
- entries = await withTimeout(
298
+ const discovered = await withTimeout(
276
299
  discoverModels(
277
300
  baseURL,
278
301
  apiKey,
@@ -284,7 +307,14 @@ async function makeProviderSource(
284
307
  ),
285
308
  DISCOVERY_TIMEOUT_MS,
286
309
  )
287
- if (entries && Object.keys(entries).length > 0) writeModelCache(cacheKey, entries)
310
+ if (discovered && Object.keys(discovered.models).length > 0) {
311
+ entries = discovered.models
312
+ responsesIds = discovered.responsesIds
313
+ writeModelCache(cacheKey, entries, responsesIds)
314
+ } else {
315
+ entries = null
316
+ responsesIds = []
317
+ }
288
318
  } else {
289
319
  logInfo(
290
320
  `[opencode-litellm] Loaded ${Object.keys(entries).length} models from cache for provider "${id}" (${baseURL}); refresh happens in the background on new sessions.`,
@@ -311,7 +341,7 @@ async function makeProviderSource(
311
341
  capabilities,
312
342
  formatModelNames,
313
343
  cacheKey,
314
- models: toProviderModels(id, entries ?? {}),
344
+ models: toProviderModels(id, entries ?? {}, new Set(responsesIds)),
315
345
  ownedModelIds: new Set<string>(),
316
346
  }
317
347
  }
@@ -345,7 +375,7 @@ async function refreshProviderSource(
345
375
  let refresh!: Promise<void>
346
376
  refresh = (async () => {
347
377
  try {
348
- const entries = await withTimeout(
378
+ const discovered = await withTimeout(
349
379
  discoverModels(
350
380
  source.baseURL,
351
381
  apiKey,
@@ -357,11 +387,21 @@ async function refreshProviderSource(
357
387
  ),
358
388
  DISCOVERY_TIMEOUT_MS,
359
389
  )
360
- if (!entries || Object.keys(entries).length === 0 || apiKey !== source.apiKey) return
390
+ if (
391
+ !discovered ||
392
+ Object.keys(discovered.models).length === 0 ||
393
+ apiKey !== source.apiKey
394
+ ) {
395
+ return
396
+ }
361
397
 
362
- const models = toProviderModels(source.id, entries)
398
+ const models = toProviderModels(
399
+ source.id,
400
+ discovered.models,
401
+ new Set(discovered.responsesIds),
402
+ )
363
403
  if (JSON.stringify(models) === JSON.stringify(source.models)) {
364
- writeModelCache(source.cacheKey, entries)
404
+ writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds)
365
405
  source.refreshRequired = false
366
406
  return
367
407
  }
@@ -375,7 +415,7 @@ async function refreshProviderSource(
375
415
  throw error
376
416
  }
377
417
 
378
- writeModelCache(source.cacheKey, entries)
418
+ writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds)
379
419
  source.refreshRequired = false
380
420
  logInfo(
381
421
  `[opencode-litellm] Refreshed ${models.length} models for provider "${source.id}"; the provider registry was reloaded.`,
@@ -487,6 +527,12 @@ async function reconcileProviderSources(
487
527
  const definition = Plugin.define({
488
528
  id: 'opencode-litellm',
489
529
  async setup(context) {
530
+ // OpenCode 1.18.x embeds a v2 plugin host whose context has no `provider`
531
+ // domain. It still calls `setup` on any plugin that exports one, but those
532
+ // versions are served by the `server()` entrypoint below. Bail out before
533
+ // touching the logger so `server()`'s client-backed logging stays intact.
534
+ if (!context.provider) return
535
+
490
536
  initV2Logging()
491
537
 
492
538
  const pluginOptions = asRecord(context.options)
@@ -77,6 +77,10 @@ export function categorizeModel(model: LiteLLMModel): 'chat' | 'embedding' | 'im
77
77
  if (m.includes('image')) return 'image'
78
78
  if (m.includes('audio') || m.includes('speech') || m.includes('transcription')) return 'audio'
79
79
  if (m.includes('chat') || m.includes('completion')) return 'chat'
80
+ // `mode: 'responses'` (and anything else non-modal) is a chat-shaped
81
+ // model — it must fall through to the id heuristics and default to
82
+ // 'chat' below, never be dropped as non-chat. Transport routing is a
83
+ // separate concern (see utils/transport.ts).
80
84
  }
81
85
 
82
86
  const id = model.id.toLowerCase()
@@ -1,4 +1,5 @@
1
1
  export * from './litellm-api'
2
2
  export * from './format-model-name'
3
+ export * from './transport'
3
4
  export * from './model-capabilities'
4
5
  export * from './model-filter'
@@ -8,7 +8,7 @@ import { join } from 'node:path'
8
8
  * from older plugin versions are ignored rather than deserialized into
9
9
  * an incompatible structure.
10
10
  */
11
- const CACHE_VERSION = 2
11
+ const CACHE_VERSION = 3
12
12
 
13
13
  /**
14
14
  * Maximum age of a cache entry before it's treated as a miss. Without a
@@ -23,6 +23,12 @@ interface ModelCacheFile {
23
23
  version: number
24
24
  savedAt: number
25
25
  models: Record<string, unknown>
26
+ /**
27
+ * Model ids that must be invoked through the OpenAI Responses API. Kept
28
+ * alongside `models` because the provider-config entries themselves carry
29
+ * no transport marker (their shape is the user-facing OpenCode config).
30
+ */
31
+ responsesIds?: string[]
26
32
  }
27
33
 
28
34
  /**
@@ -104,6 +110,30 @@ export function buildCacheKey(
104
110
  return `${base}@${fingerprint}`
105
111
  }
106
112
 
113
+ /**
114
+ * Read and validate a cache file once. Returns `null` on any problem
115
+ * (missing file, parse error, version mismatch, or a missing `models`
116
+ * block). Every reader below shares this so a caller that needs both the
117
+ * models and the Responses ids parses the file a single time.
118
+ */
119
+ function readCacheFile(cacheKey: string): ModelCacheFile | null {
120
+ try {
121
+ const raw = readFileSync(cacheFile(cacheKey), 'utf8')
122
+ const parsed = JSON.parse(raw) as ModelCacheFile
123
+ if (parsed.version !== CACHE_VERSION) return null
124
+ if (!parsed.models || typeof parsed.models !== 'object') return null
125
+ return parsed
126
+ } catch {
127
+ return null
128
+ }
129
+ }
130
+
131
+ /** Keep only the string entries of a cached `responsesIds` list. */
132
+ function normalizeResponsesIds(value: unknown): string[] {
133
+ if (!Array.isArray(value)) return []
134
+ return value.filter((id): id is string => typeof id === 'string')
135
+ }
136
+
107
137
  /**
108
138
  * Read cached model entries for a cache key. Returns `null` on any
109
139
  * problem (missing file, parse error, version mismatch, or an entry
@@ -113,21 +143,35 @@ export function buildCacheKey(
113
143
  export function readModelCache(
114
144
  cacheKey: string,
115
145
  ): Record<string, unknown> | null {
116
- try {
117
- const raw = readFileSync(cacheFile(cacheKey), 'utf8')
118
- const parsed = JSON.parse(raw) as ModelCacheFile
119
- if (parsed.version !== CACHE_VERSION) return null
120
- if (!parsed.models || typeof parsed.models !== 'object') return null
121
- if (
122
- typeof parsed.savedAt !== 'number' ||
123
- Date.now() - parsed.savedAt > CACHE_MAX_AGE_MS
124
- ) {
125
- return null
126
- }
127
- return parsed.models
128
- } catch {
146
+ const parsed = readCacheFile(cacheKey)
147
+ if (!parsed) return null
148
+ if (
149
+ typeof parsed.savedAt !== 'number' ||
150
+ Date.now() - parsed.savedAt > CACHE_MAX_AGE_MS
151
+ ) {
152
+ return null
153
+ }
154
+ return parsed.models
155
+ }
156
+
157
+ /**
158
+ * Read the models and Responses-API model ids for a cache key in one
159
+ * parse. Returns `null` under the same conditions as
160
+ * {@link readModelCache} (missing/expired cache), so the two can't
161
+ * disagree within a single lookup.
162
+ */
163
+ export function readModelCacheEntry(
164
+ cacheKey: string,
165
+ ): { models: Record<string, unknown>; responsesIds: string[] } | null {
166
+ const parsed = readCacheFile(cacheKey)
167
+ if (!parsed) return null
168
+ if (
169
+ typeof parsed.savedAt !== 'number' ||
170
+ Date.now() - parsed.savedAt > CACHE_MAX_AGE_MS
171
+ ) {
129
172
  return null
130
173
  }
174
+ return { models: parsed.models, responsesIds: normalizeResponsesIds(parsed.responsesIds) }
131
175
  }
132
176
 
133
177
  /**
@@ -136,15 +180,20 @@ export function readModelCache(
136
180
  * background refreshes so still-fresh caches aren't re-fetched.
137
181
  */
138
182
  export function readModelCacheSavedAt(cacheKey: string): number | null {
139
- try {
140
- const raw = readFileSync(cacheFile(cacheKey), 'utf8')
141
- const parsed = JSON.parse(raw) as ModelCacheFile
142
- if (parsed.version !== CACHE_VERSION) return null
143
- if (typeof parsed.savedAt !== 'number') return null
144
- return parsed.savedAt
145
- } catch {
146
- return null
147
- }
183
+ const parsed = readCacheFile(cacheKey)
184
+ if (!parsed || typeof parsed.savedAt !== 'number') return null
185
+ return parsed.savedAt
186
+ }
187
+
188
+ /**
189
+ * Return the cached Responses-API model ids for a cache key. Returns an
190
+ * empty array on any problem (missing file, parse error, version
191
+ * mismatch), matching {@link readModelCache}'s miss semantics.
192
+ */
193
+ export function readModelCacheResponsesIds(cacheKey: string): string[] {
194
+ const parsed = readCacheFile(cacheKey)
195
+ if (!parsed) return []
196
+ return normalizeResponsesIds(parsed.responsesIds)
148
197
  }
149
198
 
150
199
  /**
@@ -154,6 +203,7 @@ export function readModelCacheSavedAt(cacheKey: string): number | null {
154
203
  export function writeModelCache(
155
204
  cacheKey: string,
156
205
  models: Record<string, unknown>,
206
+ responsesIds: readonly string[] = [],
157
207
  ): void {
158
208
  try {
159
209
  mkdirSync(cacheDir(), { recursive: true })
@@ -161,6 +211,7 @@ export function writeModelCache(
161
211
  version: CACHE_VERSION,
162
212
  savedAt: Date.now(),
163
213
  models,
214
+ responsesIds: [...responsesIds],
164
215
  }
165
216
  // Write to a temp file and rename so concurrent OpenCode processes
166
217
  // never observe a partially-written JSON file (rename is atomic on
@@ -0,0 +1,20 @@
1
+ import type { LiteLLMModel } from '../types'
2
+
3
+ /**
4
+ * Decide whether a model must be invoked through the OpenAI Responses API
5
+ * (`/v1/responses`) instead of `/v1/chat/completions`.
6
+ *
7
+ * The plugin registers every discovered model through the provider's runtime
8
+ * package. That package is chosen once per provider, so a model that targets a
9
+ * different API surface needs to be routed explicitly. LiteLLM reports this on
10
+ * `/v1/model/info` as `mode: "responses"` for deployments configured with the
11
+ * Responses API (for example `use_responses_api: true`).
12
+ *
13
+ * Only the explicit `mode` signal is used. Model-id heuristics (`gpt-5*`,
14
+ * `o1/o3/o4*`) are deliberately not applied: an alias that merely looks like a
15
+ * reasoning model may still be served through Chat Completions by the proxy,
16
+ * and misrouting it would break a deployment the proxy reports as `chat`.
17
+ */
18
+ export function requiresResponsesAPI(model: LiteLLMModel): boolean {
19
+ return model.mode?.trim().toLowerCase() === 'responses'
20
+ }