opencode-plugin-litellm 1.4.3 → 1.6.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,10 +77,12 @@ 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. |
83
84
  | 🎚️ **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. |
85
+ | 💾 **Prompt caching (OpenCode 2.0.28+)** | Chat models whose deployment accepts Anthropic `cache_control` markers are registered with `compatibility.cacheFormat: "anthropic"`, so OpenCode 2 places cache breakpoints as it does for a native Anthropic provider. `modelCompatibility` corrects this per model. |
84
86
  | ⏱️ **Bounded startup** | Health checks fail fast (3 s); discovery fetches are capped at **15 s** (configurable via `LITELLM_REQUEST_TIMEOUT_MS`) for slow remote proxies. V2 model refresh runs in the background. |
85
87
  | 📝 **OpenCode logging** | V1 logs go through OpenCode's log API; V2 logs use the V2 plugin host's console logging. |
86
88
  | 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
@@ -208,8 +210,11 @@ Here, `openai/gpt-4o` keeps your custom name; every other model from the proxy i
208
210
 
209
211
  ### Reasoning models and effort variants
210
212
 
211
- All discovered models — reasoning-tier included — register under your single
212
- LiteLLM provider and are invoked through `/v1/chat/completions`.
213
+ All discovered models register under your single LiteLLM provider, and models
214
+ LiteLLM reports with `mode: "responses"` are invoked through the OpenAI
215
+ Responses API (`/v1/responses`) instead of `/v1/chat/completions`. See
216
+ [Responses API models](#responses-api-models) for how that routing is applied
217
+ on each OpenCode version.
213
218
 
214
219
  If LiteLLM reports per-model reasoning-effort support, the plugin automatically
215
220
  surfaces it as OpenCode variants. Explicit `reasoning_effort_levels` (or
@@ -236,11 +241,59 @@ between effort levels from the model picker without hand-curating every entry.
236
241
 
237
242
  > **Note**: OpenAI's reasoning-tier models (gpt-5, o1, o3, o4) reject
238
243
  > 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.
244
+ > `/v1/chat/completions`. When LiteLLM reports such a model with
245
+ > `mode: "responses"` the plugin routes it to `/v1/responses` automatically;
246
+ > otherwise reach it without `reasoningEffort`. See the FAQ entry below.
247
+
248
+ ### Responses API models
249
+
250
+ LiteLLM reports `mode` per model on `/v1/model/info` (the plugin fetches it
251
+ alongside `/v1/models`). When a model's `mode` is `responses`, the plugin routes
252
+ that model to `/v1/responses` instead of `/v1/chat/completions`. Only the
253
+ reported `mode` is used; the plugin does not guess from the model id, so an alias
254
+ that merely looks like a reasoning model stays on the transport LiteLLM actually
255
+ serves it from.
256
+
257
+ `mode` comes from LiteLLM's model cost map / the model's configured mode, not
258
+ from `use_responses_api`. If a model you expect to be routed isn't, check
259
+ `GET /v1/model/info` and confirm its `model_info.mode` is `responses` for the
260
+ deployment the proxy exposes under that id.
261
+
262
+ The routing is applied without any extra configuration, and it differs by
263
+ OpenCode version because the two versions pick a runtime package differently:
264
+
265
+ - **OpenCode 2** chooses the runtime per model. A Responses model keeps its
266
+ provider id and simply overrides the package to
267
+ `@opencode/ai/providers/openai/responses`. Chat models are untouched, and no
268
+ additional provider appears.
269
+ - **OpenCode 1** chooses the runtime per provider, so the plugin adds a sibling
270
+ provider named `<provider>-responses` (for the default `litellm` provider,
271
+ `litellm-responses`) using the `@ai-sdk/openai` package, which defaults to the
272
+ Responses API. It reuses the same endpoint, credentials, and custom headers,
273
+ and is created only when at least one model needs it.
274
+
275
+ Because the OpenCode 1 sibling occupies the `-responses` id suffix, the plugin
276
+ does not manage any provider whose id ends with `-responses`; pick a different
277
+ name if you want the plugin to discover models into a provider of your own.
278
+ Selecting a Responses model on OpenCode 1 therefore means picking
279
+ `<provider>-responses/<model>` rather than `<provider>/<model>`.
280
+
281
+ > **Upgrading on OpenCode 1 (model-id change).** Before this routing existed, a
282
+ > Responses-tier model was reachable as `<provider>/<model>` (over Chat
283
+ > Completions). It now lives under `<provider>-responses/<model>`. Any saved
284
+ > session, agent, or `opencode.json` reference that hard-codes the old
285
+ > `<provider>/<model>` id needs to be repointed, or it will fail to resolve.
286
+ > OpenCode 2 is unaffected — the model keeps its provider id.
287
+
288
+ > **Hand-curated models on OpenCode 1.** OpenCode 1 chooses the runtime per
289
+ > provider, so routing a model to the Responses API means putting it in the
290
+ > `<provider>-responses` provider. The plugin only relocates models it
291
+ > discovered itself; entries you hand-defined under the chat provider keep
292
+ > their place and stay on Chat Completions. To route a hand-defined model
293
+ > through the Responses API on OpenCode 1, define it under the
294
+ > `<provider>-responses` provider (or omit it and let discovery add it).
295
+ > OpenCode 2 needs no relocation because it overrides the runtime per model, so
296
+ > the same model keeps its provider id either way.
244
297
 
245
298
  ### Authentication
246
299
 
@@ -371,6 +424,33 @@ By default the plugin prettifies each discovered id into a display name — `ant
371
424
  - Like the other options above, `formatModelNames` is part of the cache identity, so toggling it triggers a fresh discovery on the next start instead of serving previously cached names.
372
425
  - To rename just a handful of models while keeping smart formatting for the rest, use the per-model `name` override described in [Overriding or curating individual models](#overriding-or-curating-individual-models-optional).
373
426
 
427
+ ### Prompt caching (`modelCompatibility`)
428
+
429
+ On OpenCode 2.0.28+ (earlier 2.x releases ignore the setting), the OpenAI-compatible Chat Completions runtime only places Anthropic-style `cache_control` breakpoints when a model declares `compatibility.cacheFormat: "anthropic"`. The plugin sets that for every discovered Chat Completions model whose `/v1/model/info` entry lists `cache_control` under `supported_openai_params` — which LiteLLM reports for Anthropic and Vertex AI Anthropic deployments — so prompt caching keeps working for Claude behind the proxy. Only the Chat Completions runtimes read this setting: the Anthropic Messages runtime adds its own cache breakpoints, and the Responses runtimes do not use it, so models on those packages are left alone.
430
+
431
+ To correct the inference per model id, set `cacheFormat` to `"anthropic"`, `"alibaba"`, or `null` to remove it:
432
+
433
+ ```jsonc
434
+ {
435
+ "providers": {
436
+ "litellm": {
437
+ "settings": {
438
+ "baseURL": "http://localhost:4000/v1",
439
+ "modelCompatibility": {
440
+ "bedrock/claude-sonnet-4": { "cacheFormat": "anthropic" },
441
+ "gateway/claude-opus": { "cacheFormat": null }
442
+ }
443
+ }
444
+ }
445
+ }
446
+ }
447
+ ```
448
+
449
+ - Keys are exact model ids as they appear in `/v1/models` (not globs). Only `cacheFormat`, the one key the plugin sets, is accepted.
450
+ - OpenCode's own `providers.<id>.models.<model>.compatibility` is merged over the plugin's value, so it can add or change a key but not remove one the plugin inferred; that is what `null` here is for.
451
+ - Overrides are applied when models are registered, not during discovery, so changing them does not start a new discovery.
452
+ - Neither applies on OpenCode 1.
453
+
374
454
  ## 🔧 How it works
375
455
 
376
456
  ```mermaid
@@ -519,10 +599,10 @@ The `customHeaders` map works for any gateway that requires extra HTTP headers
519
599
  <details>
520
600
  <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
601
 
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:
602
+ 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
603
 
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).
604
+ - 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.
605
+ - 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
606
 
527
607
  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
608
  </details>
@@ -549,6 +629,7 @@ src/
549
629
  │ ├── model-cache.ts # stale-while-revalidate on-disk model cache
550
630
  │ ├── model-filter.ts # includeModels/excludeModels glob filtering
551
631
  │ ├── model-capabilities.ts # per-model capability flag overrides
632
+ │ ├── model-compatibility.ts # cacheFormat inference and per-model overrides
552
633
  │ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
553
634
  └── plugin/
554
635
  ├── index.ts # OpenCode 1 server entry and shared discovery logic
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.3",
4
+ "version": "1.6.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,13 @@ 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'
17
+ import type { ModelHints } from '../utils/model-cache'
16
18
  import {
17
19
  buildCacheKey,
18
- readModelCache,
20
+ readModelCacheEntry,
19
21
  writeModelCache,
20
22
  readModelCacheSavedAt,
21
23
  } from '../utils/model-cache'
@@ -25,6 +27,13 @@ import { applyCapabilityOverrides, parseModelCapabilities } from '../utils/model
25
27
  import type { ModelCapabilities } from '../utils/model-capabilities'
26
28
 
27
29
  const CHAT_PROVIDER_ID = 'litellm'
30
+ // The OpenCode 1 config hook can only choose a runtime package per provider,
31
+ // so models that need the Responses API get a sibling provider. OpenCode 2
32
+ // selects the runtime per model instead (see plugin/v2.ts) and never creates
33
+ // this provider. The suffix is reserved: the config hook skips ids that end
34
+ // with it so it never treats its own sibling as a chat provider.
35
+ const RESPONSES_PROVIDER_SUFFIX = '-responses'
36
+ const RESPONSES_NPM = '@ai-sdk/openai'
28
37
  // Covers the 3 s health check plus the parallel models/model-info fetch
29
38
  // phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
30
39
  // proxies aren't cut off by the overall cap either (issue #20).
@@ -150,6 +159,27 @@ export function readCustomHeaders(
150
159
  return undefined
151
160
  }
152
161
 
162
+ /**
163
+ * Collect the gateway headers a provider needs on *every* request — both the
164
+ * plugin's own discovery fetches and the completion-time runtime.
165
+ *
166
+ * OpenCode 1 hands the provider's native `options.headers` to the runtime
167
+ * package, but the plugin's discovery fetches historically read only the
168
+ * legacy `customHeaders` key. A gateway that authenticates via
169
+ * `options.headers` (e.g. Cloudflare Access) would therefore serve
170
+ * completions while every discovery call 401s. Merge both here, with
171
+ * `customHeaders` winning on conflict, so discovery and runtime agree.
172
+ */
173
+ export function readProviderHeaders(
174
+ options: Record<string, unknown>,
175
+ ): Record<string, string> | undefined {
176
+ const merged = {
177
+ ...readHeaderMap(options.headers),
178
+ ...(readCustomHeaders(options) ?? {}),
179
+ }
180
+ return Object.keys(merged).length > 0 ? merged : undefined
181
+ }
182
+
153
183
  /**
154
184
  * Read the `includeModels`/`excludeModels` glob filters from a provider
155
185
  * options block (issue #21's feature: split one proxy's catalog across
@@ -296,16 +326,31 @@ export function toConfigModel(
296
326
  return entry
297
327
  }
298
328
 
329
+ /**
330
+ * Result of discovering a LiteLLM proxy's models.
331
+ *
332
+ * `models` is the `{ id -> entry }` map written into an OpenCode provider
333
+ * config (or translated into `Model.Info` on OpenCode 2). `responsesIds`
334
+ * lists the subset that must be invoked through the OpenAI Responses API;
335
+ * callers route those accordingly without inspecting each entry. `hints`
336
+ * carries per-model upstream facts OpenCode 2 maps to `compatibility`.
337
+ */
338
+ export interface DiscoveredModels {
339
+ models: Record<string, unknown>
340
+ responsesIds: string[]
341
+ hints: Record<string, ModelHints>
342
+ }
343
+
299
344
  /**
300
345
  * Fetch and build OpenCode model entries from a LiteLLM proxy.
301
346
  *
302
347
  * 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.
348
+ * classifies + formats each model, and returns the built entries plus the
349
+ * ids that require the Responses API and per-model hints. The provider's
350
+ * `includeModels`/`excludeModels` filters, `modelCapabilities` overrides and
351
+ * `formatModelNames` choice are applied here (not at merge time) so every
352
+ * path that persists or serves a cache — cold discovery and background
353
+ * refresh — writes the same adjusted view.
309
354
  *
310
355
  * Returns `null` when the proxy is unreachable/unauthorized or exposes
311
356
  * no models, so callers can distinguish "no data" from "empty result".
@@ -318,7 +363,7 @@ export async function discoverModels(
318
363
  filters: ModelFilters = {},
319
364
  capabilities: ModelCapabilities = {},
320
365
  formatModelNames = true,
321
- ): Promise<Record<string, unknown> | null> {
366
+ ): Promise<DiscoveredModels | null> {
322
367
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
323
368
  log(
324
369
  'warn',
@@ -368,6 +413,8 @@ export async function discoverModels(
368
413
  }
369
414
 
370
415
  const built: Record<string, unknown> = {}
416
+ const responsesIds: string[] = []
417
+ const hints: Record<string, ModelHints> = {}
371
418
  let skipped = 0
372
419
  let wildcards = 0
373
420
  let filtered = 0
@@ -389,16 +436,18 @@ export async function discoverModels(
389
436
  }
390
437
  const info = infoByName?.get(model.id)
391
438
  if (infoByName && !info) unmatched.push(model.id)
392
- const entry = toConfigModel(
393
- enrichModel(model, info, capabilities[model.id]),
394
- info,
395
- formatModelNames,
396
- )
439
+ const enriched = enrichModel(model, info, capabilities[model.id])
440
+ const entry = toConfigModel(enriched, info, formatModelNames)
397
441
  if (!entry) {
398
442
  skipped++
399
443
  continue
400
444
  }
401
445
  built[model.id] = entry
446
+ if (requiresResponsesAPI(enriched)) responsesIds.push(model.id)
447
+ const params = info?.supported_openai_params
448
+ hints[model.id] = {
449
+ acceptsCacheControl: Array.isArray(params) && params.includes('cache_control'),
450
+ }
402
451
  }
403
452
 
404
453
  if (unmatched.length > 0) {
@@ -430,7 +479,7 @@ export async function discoverModels(
430
479
  ')',
431
480
  )
432
481
 
433
- return built
482
+ return { models: built, responsesIds, hints }
434
483
  }
435
484
 
436
485
  /**
@@ -455,6 +504,134 @@ function mergeModels(
455
504
  return added
456
505
  }
457
506
 
507
+ /**
508
+ * Ensure the sibling provider that carries Responses-API models exists in
509
+ * the OpenCode 1 config, mirroring the chat provider's endpoint and
510
+ * credentials. Returns its `models` map.
511
+ *
512
+ * The Responses runtime is `@ai-sdk/openai` (AI SDK 5's OpenAI provider
513
+ * defaults to `/v1/responses`). The sibling is only materialized when at
514
+ * least one discovered model needs it, so chat-only proxies keep a single
515
+ * provider and never pay for the extra entry.
516
+ */
517
+ function ensureResponsesProvider(
518
+ config: { provider: Record<string, unknown> },
519
+ baseProviderId: string,
520
+ baseProvider: Record<string, unknown>,
521
+ baseURL: string,
522
+ apiKey: string | undefined,
523
+ customHeaders: Record<string, string> | undefined,
524
+ ): Record<string, unknown> {
525
+ const id = `${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`
526
+ if (!config.provider[id] || typeof config.provider[id] !== 'object') {
527
+ config.provider[id] = {}
528
+ }
529
+ const provider = config.provider[id] as Record<string, unknown>
530
+ if (!provider.npm) provider.npm = RESPONSES_NPM
531
+ if (typeof provider.name !== 'string' || !provider.name) {
532
+ const baseName =
533
+ typeof baseProvider.name === 'string' && baseProvider.name
534
+ ? baseProvider.name
535
+ : 'LiteLLM (proxy)'
536
+ provider.name = `${baseName} Responses`
537
+ }
538
+ if (!provider.options || typeof provider.options !== 'object') {
539
+ provider.options = {}
540
+ }
541
+ const options = provider.options as Record<string, unknown>
542
+ if (!options.baseURL) options.baseURL = `${baseURL}/v1`
543
+ if (!options.apiKey && apiKey) options.apiKey = apiKey
544
+ // OpenCode 1 reads provider headers from `options.headers` and hands them to
545
+ // the runtime package (`@ai-sdk/openai` here); it has no `customHeaders` key.
546
+ // Mirror the chat provider's native headers and promote the plugin's
547
+ // `customHeaders` so Responses requests carry the same gateway headers.
548
+ const baseOptions = (baseProvider.options ?? {}) as Record<string, unknown>
549
+ const mergedHeaders = {
550
+ ...readHeaderMap(baseOptions.headers),
551
+ ...(customHeaders ?? {}),
552
+ ...readHeaderMap(options.headers),
553
+ }
554
+ if (Object.keys(mergedHeaders).length > 0) {
555
+ options.headers = mergedHeaders
556
+ }
557
+ if (!provider.models || typeof provider.models !== 'object') {
558
+ provider.models = {}
559
+ }
560
+ return provider.models as Record<string, unknown>
561
+ }
562
+
563
+ /**
564
+ * Extract a `string -> string` header map from an arbitrary provider option
565
+ * value, ignoring anything that isn't a string. Returns an empty map for
566
+ * missing or malformed input.
567
+ */
568
+ function readHeaderMap(value: unknown): Record<string, string> {
569
+ const out: Record<string, string> = {}
570
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
571
+ for (const [key, header] of Object.entries(value as Record<string, unknown>)) {
572
+ if (typeof header === 'string') out[key] = header
573
+ }
574
+ }
575
+ return out
576
+ }
577
+
578
+ /**
579
+ * Split freshly discovered entries into the chat provider and the Responses
580
+ * sibling, injecting each side without clobbering curated entries. Returns
581
+ * every id this call added, across both providers, so the config hook's
582
+ * idempotency check sees a single set.
583
+ */
584
+ function injectDiscoveredModels(
585
+ config: { provider: Record<string, unknown> },
586
+ baseProviderId: string,
587
+ baseProvider: Record<string, unknown>,
588
+ baseModels: Record<string, unknown>,
589
+ entries: Record<string, unknown>,
590
+ responsesIds: readonly string[],
591
+ baseURL: string,
592
+ apiKey: string | undefined,
593
+ customHeaders: Record<string, string> | undefined,
594
+ ): string[] {
595
+ const responsesSet = new Set(responsesIds)
596
+ const existingSibling = config.provider[`${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`]
597
+ const siblingModelsExisting: Record<string, unknown> =
598
+ existingSibling &&
599
+ typeof existingSibling === 'object' &&
600
+ (existingSibling as Record<string, unknown>).models &&
601
+ typeof (existingSibling as Record<string, unknown>).models === 'object'
602
+ ? ((existingSibling as Record<string, unknown>).models as Record<string, unknown>)
603
+ : {}
604
+
605
+ const chatEntries: Record<string, unknown> = {}
606
+ const responsesEntries: Record<string, unknown> = {}
607
+ for (const [id, entry] of Object.entries(entries)) {
608
+ // A model already present under the other provider was curated there (or
609
+ // injected by an earlier run); leave it alone instead of duplicating it
610
+ // across both providers.
611
+ if (responsesSet.has(id)) {
612
+ if (Object.hasOwn(baseModels, id)) continue
613
+ responsesEntries[id] = entry
614
+ } else {
615
+ if (Object.hasOwn(siblingModelsExisting, id)) continue
616
+ chatEntries[id] = entry
617
+ }
618
+ }
619
+
620
+ const added = mergeModels(baseModels, chatEntries)
621
+ if (Object.keys(responsesEntries).length > 0) {
622
+ const siblingModels = ensureResponsesProvider(
623
+ config,
624
+ baseProviderId,
625
+ baseProvider,
626
+ baseURL,
627
+ apiKey,
628
+ customHeaders,
629
+ )
630
+ added.push(...mergeModels(siblingModels, responsesEntries))
631
+ }
632
+ return added
633
+ }
634
+
458
635
  /**
459
636
  * Revalidate a provider's model cache off the critical path (SWR). The
460
637
  * refreshed entries land in the on-disk cache and surface on the next
@@ -473,7 +650,7 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
473
650
  }
474
651
  refreshInFlight.add(cacheKey)
475
652
  try {
476
- const built = await withTimeout(
653
+ const discovered = await withTimeout(
477
654
  discoverModels(
478
655
  ctx.baseURL,
479
656
  ctx.apiKey,
@@ -485,11 +662,11 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
485
662
  ),
486
663
  DISCOVERY_TIMEOUT_MS,
487
664
  )
488
- if (built && Object.keys(built).length > 0) {
489
- writeModelCache(cacheKey, built)
665
+ if (discovered && Object.keys(discovered.models).length > 0) {
666
+ writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
490
667
  log(
491
668
  'info',
492
- `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(built).length} models)`,
669
+ `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(discovered.models).length} models)`,
493
670
  )
494
671
  }
495
672
  } catch {
@@ -535,6 +712,9 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
535
712
  const liteLLMProviders: Array<{ id: string; provider: Record<string, unknown> }> = []
536
713
 
537
714
  for (const id of providerIds) {
715
+ // The Responses sibling is created and populated below; never treat
716
+ // it as a chat provider (that would recurse into `…-responses-responses`).
717
+ if (id.endsWith(RESPONSES_PROVIDER_SUFFIX)) continue
538
718
  const provider = config.provider[id]
539
719
  if (provider && typeof provider === 'object') {
540
720
  const options = (provider.options ?? {}) as Record<string, unknown>
@@ -581,7 +761,10 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
581
761
  */
582
762
  const storedKey = await getOpenCodeStoredApiKey(providerId)
583
763
  const apiKey = configuredKey ?? envKey ?? storedKey
584
- const customHeaders = readCustomHeaders(options)
764
+ // Native `options.headers` and the legacy `customHeaders` both reach
765
+ // discovery and the runtime, so a gateway that only sets one still
766
+ // authenticates the plugin's own fetches.
767
+ const customHeaders = readProviderHeaders(options)
585
768
  const filters = readModelFilters(options)
586
769
  const capabilities = parseModelCapabilities(options.modelCapabilities)
587
770
  const formatModelNames = readFormatModelNames(options)
@@ -659,12 +842,27 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
659
842
  providerId,
660
843
  })
661
844
 
845
+ // The Responses sibling (if any) holds a disjoint set of ids, so the
846
+ // idempotency check has to look at both providers.
847
+ const responsesProviderId = `${providerId}${RESPONSES_PROVIDER_SUFFIX}`
848
+ const responsesModels = (): Record<string, unknown> => {
849
+ const sibling = config.provider[responsesProviderId]
850
+ if (!sibling || typeof sibling !== 'object') return {}
851
+ const candidate = (sibling as Record<string, unknown>).models
852
+ return candidate && typeof candidate === 'object'
853
+ ? (candidate as Record<string, unknown>)
854
+ : {}
855
+ }
856
+
662
857
  // Repeat config-hook invocations within a run are a no-op once
663
858
  // we've injected this provider's models.
664
859
  const alreadyInjected = injectedModelIds.get(cacheKey)
665
860
  if (
666
861
  alreadyInjected &&
667
- [...alreadyInjected].every((id) => Object.hasOwn(models, id))
862
+ [...alreadyInjected].every(
863
+ (id) =>
864
+ Object.hasOwn(models, id) || Object.hasOwn(responsesModels(), id),
865
+ )
668
866
  ) {
669
867
  continue
670
868
  }
@@ -674,13 +872,23 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
674
872
  // `event` hook) keeps the cache fresh for the next launch.
675
873
  // The cache is scoped per provider so two providers pointing at
676
874
  // 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)
875
+ const cached = readModelCacheEntry(cacheKey)
876
+ if (cached && Object.keys(cached.models).length > 0) {
877
+ const added = injectDiscoveredModels(
878
+ config,
879
+ providerId,
880
+ actualProvider,
881
+ models,
882
+ cached.models,
883
+ cached.responsesIds,
884
+ baseURL,
885
+ apiKey,
886
+ customHeaders,
887
+ )
680
888
  injectedModelIds.set(cacheKey, new Set(added))
681
889
  log(
682
890
  'info',
683
- `[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
891
+ `[opencode-litellm] Loaded ${Object.keys(cached.models).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
684
892
  )
685
893
  continue
686
894
  }
@@ -688,7 +896,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
688
896
  // Cold cache: do a live fetch (slow first run only), inject, and
689
897
  // persist for subsequent startups. Capped by a timeout so a slow
690
898
  // proxy never blocks boot.
691
- const built = await withTimeout(
899
+ const discovered = await withTimeout(
692
900
  discoverModels(
693
901
  baseURL,
694
902
  apiKey,
@@ -700,10 +908,20 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
700
908
  ),
701
909
  DISCOVERY_TIMEOUT_MS,
702
910
  )
703
- if (built && Object.keys(built).length > 0) {
704
- const added = mergeModels(models, built)
911
+ if (discovered && Object.keys(discovered.models).length > 0) {
912
+ const added = injectDiscoveredModels(
913
+ config,
914
+ providerId,
915
+ actualProvider,
916
+ models,
917
+ discovered.models,
918
+ discovered.responsesIds,
919
+ baseURL,
920
+ apiKey,
921
+ customHeaders,
922
+ )
705
923
  injectedModelIds.set(cacheKey, new Set(added))
706
- writeModelCache(cacheKey, built)
924
+ writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
707
925
  }
708
926
  }
709
927
  },
package/src/plugin/v2.ts CHANGED
@@ -14,17 +14,47 @@ 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'
21
21
  import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
22
22
  import { parseModelCapabilities } from '../utils/model-capabilities'
23
23
  import type { ModelCapabilities } from '../utils/model-capabilities'
24
+ import {
25
+ inferCompatibility,
26
+ parseModelCompatibility,
27
+ resolveCompatibility,
28
+ } from '../utils/model-compatibility'
29
+ import type { ModelCompatibility } from '../utils/model-compatibility'
24
30
  import type { ModelFilters } from '../utils/model-filter'
31
+ import type { ModelHints } from '../utils/model-cache'
25
32
 
26
33
  const CHAT_PROVIDER_ID = 'litellm'
27
34
  const OPENAI_COMPATIBLE_PACKAGE = '@opencode/ai/providers/openai-compatible'
35
+ // Of the packages a LiteLLM provider uses, only the Chat Completions ones read
36
+ // `compatibility.cacheFormat`; `openai` (Responses by default), the Responses
37
+ // packages and the Anthropic packages do not.
38
+ const CHAT_COMPLETIONS_PACKAGES = new Set([
39
+ OPENAI_COMPATIBLE_PACKAGE,
40
+ '@opencode/ai/providers/openai/chat',
41
+ ])
42
+ // Runtime package that talks to `/v1/responses`. OpenCode 2 lets one model
43
+ // override the provider's package, so Responses models stay under their
44
+ // original provider id and no sibling provider is needed here.
45
+ //
46
+ // `@opencode/ai/providers/openai/responses` is the Responses runtime OpenCode
47
+ // bundles today; a plain OpenAI-compatible provider defaults to the Chat
48
+ // Completions runtime, so the override is what selects the Responses API.
49
+ //
50
+ // Note this is the OpenAI-specific runtime: it applies OpenAI request defaults
51
+ // (`store: false`, plus `reasoningEffort`/`reasoningSummary`/encrypted-reasoning
52
+ // `include` for `gpt-5*` ids) on top of the proxy endpoint. The provider-neutral
53
+ // `@opencode/ai/providers/openai-compatible/responses` is the closer match for a
54
+ // generic LiteLLM proxy, but it must actually load in the target OpenCode 2.x
55
+ // (`@opencode/ai@2.0.19` ships both). Verified live against the OpenAI runtime;
56
+ // switch here if the compatible variant becomes reliably available.
57
+ const RESPONSES_PACKAGE = '@opencode/ai/providers/openai/responses'
28
58
  const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000
29
59
 
30
60
  type ProviderInfo = Awaited<ReturnType<Context['provider']['list']>>['data'][number]
@@ -62,6 +92,7 @@ interface ProviderSource {
62
92
  pendingPublication: boolean
63
93
  filters: ModelFilters
64
94
  capabilities: ModelCapabilities
95
+ compatibility: ModelCompatibility
65
96
  formatModelNames: boolean
66
97
  cacheKey: string
67
98
  models: Model.Info[]
@@ -95,11 +126,21 @@ function numberOrZero(value: unknown): number {
95
126
  return typeof value === 'number' && Number.isFinite(value) ? value : 0
96
127
  }
97
128
 
129
+ interface ToProviderModelsOptions {
130
+ /** The provider's runtime package; models not overridden inherit it. */
131
+ providerPackage: string
132
+ responsesIds: ReadonlySet<string>
133
+ hints: Record<string, ModelHints>
134
+ compatibility: ModelCompatibility
135
+ }
136
+
98
137
  function toProviderModels(
99
138
  providerID: string,
100
139
  entries: Record<string, unknown>,
140
+ options: ToProviderModelsOptions,
101
141
  ): Model.Info[] {
102
142
  const provider = Provider.ID.make(providerID)
143
+ const { responsesIds, hints, compatibility: overrides } = options
103
144
 
104
145
  return Object.entries(entries).flatMap(([modelID, value]) => {
105
146
  const entry = asRecord(value)
@@ -135,9 +176,23 @@ function toProviderModels(
135
176
  id: id as Model.VariantID,
136
177
  settings: asRecord(settings),
137
178
  })) as Model.Info['variants']
179
+ const pkg = responsesIds.has(modelID) ? RESPONSES_PACKAGE : options.providerPackage
180
+ const compatibility = resolveCompatibility(
181
+ inferCompatibility(hints[modelID], CHAT_COMPLETIONS_PACKAGES.has(pkg)),
182
+ Object.hasOwn(overrides, modelID) ? overrides[modelID] : undefined,
183
+ )
138
184
  return [
139
185
  {
140
186
  ...defaults,
187
+ // A model that targets `/v1/responses` overrides the provider's
188
+ // runtime package for itself, so it keeps the provider id while
189
+ // still reaching the Responses API.
190
+ ...(responsesIds.has(modelID) ? { package: RESPONSES_PACKAGE } : {}),
191
+ // `cacheFormat` exists on the host's `Model.Compatibility` (2.0.28+)
192
+ // but not in the 2.0.15 schema this package compiles against.
193
+ ...(compatibility
194
+ ? { compatibility: compatibility as unknown as Model.Info['compatibility'] }
195
+ : {}),
141
196
  name: readString(entry.name) ?? modelID,
142
197
  limit: {
143
198
  context: numberOrDefault(limit.context, defaults.limit.context),
@@ -207,6 +262,7 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
207
262
  'includeModels',
208
263
  'excludeModels',
209
264
  'modelCapabilities',
265
+ 'modelCompatibility',
210
266
  'formatModelNames',
211
267
  'providerID',
212
268
  ]) {
@@ -256,6 +312,7 @@ async function makeProviderSource(
256
312
  const apiKey = configuredApiKey ?? connectedApiKey
257
313
  const filters = readModelFilters(settings)
258
314
  const capabilities = parseModelCapabilities(settings.modelCapabilities)
315
+ const compatibility = parseModelCompatibility(settings.modelCompatibility)
259
316
  const formatModelNames = readFormatModelNames(settings)
260
317
  const detectedBaseURL = configuredBaseURL
261
318
  ? normalizeBaseURL(configuredBaseURL)
@@ -269,10 +326,13 @@ async function makeProviderSource(
269
326
  const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
270
327
  formatModelNames,
271
328
  })
272
- let entries = readModelCache(cacheKey)
329
+ const cacheEntry = readModelCacheEntry(cacheKey)
330
+ let entries = cacheEntry?.models ?? null
331
+ let responsesIds = cacheEntry?.responsesIds ?? []
332
+ let hints = cacheEntry?.hints ?? {}
273
333
 
274
334
  if (!entries || Object.keys(entries).length === 0) {
275
- entries = await withTimeout(
335
+ const discovered = await withTimeout(
276
336
  discoverModels(
277
337
  baseURL,
278
338
  apiKey,
@@ -284,18 +344,28 @@ async function makeProviderSource(
284
344
  ),
285
345
  DISCOVERY_TIMEOUT_MS,
286
346
  )
287
- if (entries && Object.keys(entries).length > 0) writeModelCache(cacheKey, entries)
347
+ if (discovered && Object.keys(discovered.models).length > 0) {
348
+ entries = discovered.models
349
+ responsesIds = discovered.responsesIds
350
+ hints = discovered.hints
351
+ writeModelCache(cacheKey, entries, responsesIds, hints)
352
+ } else {
353
+ entries = null
354
+ responsesIds = []
355
+ hints = {}
356
+ }
288
357
  } else {
289
358
  logInfo(
290
359
  `[opencode-litellm] Loaded ${Object.keys(entries).length} models from cache for provider "${id}" (${baseURL}); refresh happens in the background on new sessions.`,
291
360
  )
292
361
  }
293
362
 
363
+ const providerPackage = provider?.package || OPENAI_COMPATIBLE_PACKAGE
294
364
  return {
295
365
  id,
296
366
  name: provider?.name || 'LiteLLM (proxy)',
297
367
  activation: provider?.activation ?? 'enabled',
298
- package: provider?.package || OPENAI_COMPATIBLE_PACKAGE,
368
+ package: providerPackage,
299
369
  settings,
300
370
  headers: customHeaders,
301
371
  integrationID: provider?.integrationID,
@@ -309,9 +379,15 @@ async function makeProviderSource(
309
379
  customHeaders: Object.keys(customHeaders).length > 0 ? customHeaders : undefined,
310
380
  filters,
311
381
  capabilities,
382
+ compatibility,
312
383
  formatModelNames,
313
384
  cacheKey,
314
- models: toProviderModels(id, entries ?? {}),
385
+ models: toProviderModels(id, entries ?? {}, {
386
+ providerPackage,
387
+ responsesIds: new Set(responsesIds),
388
+ hints,
389
+ compatibility,
390
+ }),
315
391
  ownedModelIds: new Set<string>(),
316
392
  }
317
393
  }
@@ -345,7 +421,7 @@ async function refreshProviderSource(
345
421
  let refresh!: Promise<void>
346
422
  refresh = (async () => {
347
423
  try {
348
- const entries = await withTimeout(
424
+ const discovered = await withTimeout(
349
425
  discoverModels(
350
426
  source.baseURL,
351
427
  apiKey,
@@ -357,11 +433,22 @@ async function refreshProviderSource(
357
433
  ),
358
434
  DISCOVERY_TIMEOUT_MS,
359
435
  )
360
- if (!entries || Object.keys(entries).length === 0 || apiKey !== source.apiKey) return
436
+ if (
437
+ !discovered ||
438
+ Object.keys(discovered.models).length === 0 ||
439
+ apiKey !== source.apiKey
440
+ ) {
441
+ return
442
+ }
361
443
 
362
- const models = toProviderModels(source.id, entries)
444
+ const models = toProviderModels(source.id, discovered.models, {
445
+ providerPackage: source.package,
446
+ responsesIds: new Set(discovered.responsesIds),
447
+ hints: discovered.hints,
448
+ compatibility: source.compatibility,
449
+ })
363
450
  if (JSON.stringify(models) === JSON.stringify(source.models)) {
364
- writeModelCache(source.cacheKey, entries)
451
+ writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
365
452
  source.refreshRequired = false
366
453
  return
367
454
  }
@@ -375,7 +462,7 @@ async function refreshProviderSource(
375
462
  throw error
376
463
  }
377
464
 
378
- writeModelCache(source.cacheKey, entries)
465
+ writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
379
466
  source.refreshRequired = false
380
467
  logInfo(
381
468
  `[opencode-litellm] Refreshed ${models.length} models for provider "${source.id}"; the provider registry was reloaded.`,
@@ -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'
@@ -3,12 +3,25 @@ import { readFileSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node
3
3
  import { homedir, tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
5
 
6
+ /**
7
+ * Facts about a discovered model's upstream that OpenCode 2 turns into
8
+ * `Model.Info.compatibility`. They ride alongside the config-shaped model
9
+ * entries (which have no field for them) through discovery and the cache.
10
+ */
11
+ export interface ModelHints {
12
+ /**
13
+ * The deployment accepts Anthropic-style `cache_control` markers on
14
+ * Chat Completions (`supported_openai_params` lists `cache_control`).
15
+ */
16
+ acceptsCacheControl: boolean
17
+ }
18
+
6
19
  /**
7
20
  * Bump when the shape of a cached model entry changes so stale caches
8
21
  * from older plugin versions are ignored rather than deserialized into
9
22
  * an incompatible structure.
10
23
  */
11
- const CACHE_VERSION = 2
24
+ const CACHE_VERSION = 4
12
25
 
13
26
  /**
14
27
  * Maximum age of a cache entry before it's treated as a miss. Without a
@@ -23,6 +36,17 @@ interface ModelCacheFile {
23
36
  version: number
24
37
  savedAt: number
25
38
  models: Record<string, unknown>
39
+ /**
40
+ * Model ids that must be invoked through the OpenAI Responses API. Kept
41
+ * alongside `models` because the provider-config entries themselves carry
42
+ * no transport marker (their shape is the user-facing OpenCode config).
43
+ */
44
+ responsesIds?: string[]
45
+ /**
46
+ * Per-model facts about the upstream that OpenCode 2 needs but that have
47
+ * no place in a provider-config entry (see `ModelHints`).
48
+ */
49
+ hints?: Record<string, ModelHints>
26
50
  }
27
51
 
28
52
  /**
@@ -104,6 +128,42 @@ export function buildCacheKey(
104
128
  return `${base}@${fingerprint}`
105
129
  }
106
130
 
131
+ /**
132
+ * Read and validate a cache file once. Returns `null` on any problem
133
+ * (missing file, parse error, version mismatch, or a missing `models`
134
+ * block). Every reader below shares this so a caller that needs both the
135
+ * models and the Responses ids parses the file a single time.
136
+ */
137
+ function readCacheFile(cacheKey: string): ModelCacheFile | null {
138
+ try {
139
+ const raw = readFileSync(cacheFile(cacheKey), 'utf8')
140
+ const parsed = JSON.parse(raw) as ModelCacheFile
141
+ if (parsed.version !== CACHE_VERSION) return null
142
+ if (!parsed.models || typeof parsed.models !== 'object') return null
143
+ return parsed
144
+ } catch {
145
+ return null
146
+ }
147
+ }
148
+
149
+ /** Keep only the string entries of a cached `responsesIds` list. */
150
+ function normalizeResponsesIds(value: unknown): string[] {
151
+ if (!Array.isArray(value)) return []
152
+ return value.filter((id): id is string => typeof id === 'string')
153
+ }
154
+
155
+ /** Keep only well-formed entries of a cached `hints` map. */
156
+ function normalizeHints(value: unknown): Record<string, ModelHints> {
157
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {}
158
+ const out: Record<string, ModelHints> = {}
159
+ for (const [id, hint] of Object.entries(value as Record<string, unknown>)) {
160
+ if (!hint || typeof hint !== 'object' || Array.isArray(hint)) continue
161
+ const { acceptsCacheControl } = hint as Record<string, unknown>
162
+ out[id] = { acceptsCacheControl: acceptsCacheControl === true }
163
+ }
164
+ return out
165
+ }
166
+
107
167
  /**
108
168
  * Read cached model entries for a cache key. Returns `null` on any
109
169
  * problem (missing file, parse error, version mismatch, or an entry
@@ -113,21 +173,43 @@ export function buildCacheKey(
113
173
  export function readModelCache(
114
174
  cacheKey: string,
115
175
  ): 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 {
176
+ const parsed = readCacheFile(cacheKey)
177
+ if (!parsed) return null
178
+ if (
179
+ typeof parsed.savedAt !== 'number' ||
180
+ Date.now() - parsed.savedAt > CACHE_MAX_AGE_MS
181
+ ) {
182
+ return null
183
+ }
184
+ return parsed.models
185
+ }
186
+
187
+ /**
188
+ * Read the models, Responses-API model ids and model hints for a cache key
189
+ * in one parse. Returns `null` under the same conditions as
190
+ * {@link readModelCache} (missing/expired cache), so the three can't
191
+ * disagree within a single lookup.
192
+ */
193
+ export function readModelCacheEntry(
194
+ cacheKey: string,
195
+ ): {
196
+ models: Record<string, unknown>
197
+ responsesIds: string[]
198
+ hints: Record<string, ModelHints>
199
+ } | null {
200
+ const parsed = readCacheFile(cacheKey)
201
+ if (!parsed) return null
202
+ if (
203
+ typeof parsed.savedAt !== 'number' ||
204
+ Date.now() - parsed.savedAt > CACHE_MAX_AGE_MS
205
+ ) {
129
206
  return null
130
207
  }
208
+ return {
209
+ models: parsed.models,
210
+ responsesIds: normalizeResponsesIds(parsed.responsesIds),
211
+ hints: normalizeHints(parsed.hints),
212
+ }
131
213
  }
132
214
 
133
215
  /**
@@ -136,15 +218,20 @@ export function readModelCache(
136
218
  * background refreshes so still-fresh caches aren't re-fetched.
137
219
  */
138
220
  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
- }
221
+ const parsed = readCacheFile(cacheKey)
222
+ if (!parsed || typeof parsed.savedAt !== 'number') return null
223
+ return parsed.savedAt
224
+ }
225
+
226
+ /**
227
+ * Return the cached Responses-API model ids for a cache key. Returns an
228
+ * empty array on any problem (missing file, parse error, version
229
+ * mismatch), matching {@link readModelCache}'s miss semantics.
230
+ */
231
+ export function readModelCacheResponsesIds(cacheKey: string): string[] {
232
+ const parsed = readCacheFile(cacheKey)
233
+ if (!parsed) return []
234
+ return normalizeResponsesIds(parsed.responsesIds)
148
235
  }
149
236
 
150
237
  /**
@@ -154,6 +241,8 @@ export function readModelCacheSavedAt(cacheKey: string): number | null {
154
241
  export function writeModelCache(
155
242
  cacheKey: string,
156
243
  models: Record<string, unknown>,
244
+ responsesIds: readonly string[] = [],
245
+ hints: Record<string, ModelHints> = {},
157
246
  ): void {
158
247
  try {
159
248
  mkdirSync(cacheDir(), { recursive: true })
@@ -161,6 +250,8 @@ export function writeModelCache(
161
250
  version: CACHE_VERSION,
162
251
  savedAt: Date.now(),
163
252
  models,
253
+ responsesIds: [...responsesIds],
254
+ hints,
164
255
  }
165
256
  // Write to a temp file and rename so concurrent OpenCode processes
166
257
  // never observe a partially-written JSON file (rename is atomic on
@@ -0,0 +1,65 @@
1
+ import type { ModelHints } from './model-cache'
2
+
3
+ /**
4
+ * Values `cacheFormat` accepts. Validated here because OpenCode validates
5
+ * plugin-registered models only when it serializes them, where one bad
6
+ * value fails the whole model list.
7
+ */
8
+ const CACHE_FORMATS: ReadonlySet<string> = new Set(['anthropic', 'alibaba'])
9
+
10
+ /** `null` removes the `cacheFormat` the plugin inferred. */
11
+ export interface CompatibilityOverride {
12
+ cacheFormat: string | null
13
+ }
14
+
15
+ /** Per-model compatibility overrides keyed by exact model id. */
16
+ export type ModelCompatibility = Record<string, CompatibilityOverride>
17
+
18
+ /**
19
+ * Defensively parse the `modelCompatibility` provider option. Non-object
20
+ * input, non-object per-model values and values outside the accepted set
21
+ * are dropped; `null` is kept.
22
+ */
23
+ export function parseModelCompatibility(raw: unknown): ModelCompatibility {
24
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
25
+ const out: ModelCompatibility = {}
26
+ for (const [modelId, entry] of Object.entries(raw as Record<string, unknown>)) {
27
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue
28
+ const { cacheFormat } = entry as Record<string, unknown>
29
+ if (cacheFormat === null || (typeof cacheFormat === 'string' && CACHE_FORMATS.has(cacheFormat))) {
30
+ out[modelId] = { cacheFormat }
31
+ }
32
+ }
33
+ return out
34
+ }
35
+
36
+ /**
37
+ * Compatibility OpenCode 2 needs for a discovered model, from what the
38
+ * proxy reported about its upstream. Only the Chat Completions runtimes
39
+ * read `cacheFormat`: Anthropic Messages adds its own cache breakpoints
40
+ * and the Responses runtimes do not use the setting.
41
+ */
42
+ export function inferCompatibility(
43
+ hints: ModelHints | undefined,
44
+ chatCompletions: boolean,
45
+ ): Record<string, string> {
46
+ if (chatCompletions && hints?.acceptsCacheControl) return { cacheFormat: 'anthropic' }
47
+ return {}
48
+ }
49
+
50
+ /**
51
+ * Overlay a user override on inferred compatibility. `null` deletes the
52
+ * key. Returns `undefined` when nothing remains so callers can leave
53
+ * `compatibility` unset.
54
+ */
55
+ export function resolveCompatibility(
56
+ inferred: Record<string, string>,
57
+ override?: CompatibilityOverride,
58
+ ): Record<string, string> | undefined {
59
+ const out: Record<string, string> = { ...inferred }
60
+ if (override) {
61
+ if (override.cacheFormat === null) delete out.cacheFormat
62
+ else out.cacheFormat = override.cacheFormat
63
+ }
64
+ return Object.keys(out).length > 0 ? out : undefined
65
+ }
@@ -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
+ }