opencode-plugin-litellm 1.5.0 → 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 +29 -0
- package/package.json +1 -1
- package/src/plugin/index.ts +13 -5
- package/src/plugin/v2.ts +58 -11
- package/src/utils/model-cache.ts +46 -6
- package/src/utils/model-compatibility.ts +65 -0
package/README.md
CHANGED
|
@@ -82,6 +82,7 @@ also shows how to configure a provider directly in `opencode.json`.
|
|
|
82
82
|
| 🌐 **Gateway-friendly** | Supports provider `headers` (and the legacy `customHeaders` option) for proxies behind Cloudflare Access or other API gateways. |
|
|
83
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. |
|
|
84
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. |
|
|
85
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. |
|
|
86
87
|
| 📝 **OpenCode logging** | V1 logs go through OpenCode's log API; V2 logs use the V2 plugin host's console logging. |
|
|
87
88
|
| 🤝 **Non-destructive merge** | Only adds models you don't already have configured. Hand-curated entries are preserved verbatim. |
|
|
@@ -423,6 +424,33 @@ By default the plugin prettifies each discovered id into a display name — `ant
|
|
|
423
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.
|
|
424
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).
|
|
425
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
|
+
|
|
426
454
|
## 🔧 How it works
|
|
427
455
|
|
|
428
456
|
```mermaid
|
|
@@ -601,6 +629,7 @@ src/
|
|
|
601
629
|
│ ├── model-cache.ts # stale-while-revalidate on-disk model cache
|
|
602
630
|
│ ├── model-filter.ts # includeModels/excludeModels glob filtering
|
|
603
631
|
│ ├── model-capabilities.ts # per-model capability flag overrides
|
|
632
|
+
│ ├── model-compatibility.ts # cacheFormat inference and per-model overrides
|
|
604
633
|
│ └── opencode-auth.ts # fallback to OpenCode's /connect-stored credentials
|
|
605
634
|
└── plugin/
|
|
606
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
|
+
"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",
|
package/src/plugin/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
import { requiresResponsesAPI } from '../utils/transport'
|
|
15
15
|
import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
|
|
16
16
|
import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
|
|
17
|
+
import type { ModelHints } from '../utils/model-cache'
|
|
17
18
|
import {
|
|
18
19
|
buildCacheKey,
|
|
19
20
|
readModelCacheEntry,
|
|
@@ -331,11 +332,13 @@ export function toConfigModel(
|
|
|
331
332
|
* `models` is the `{ id -> entry }` map written into an OpenCode provider
|
|
332
333
|
* config (or translated into `Model.Info` on OpenCode 2). `responsesIds`
|
|
333
334
|
* lists the subset that must be invoked through the OpenAI Responses API;
|
|
334
|
-
* callers route those accordingly without inspecting each entry.
|
|
335
|
+
* callers route those accordingly without inspecting each entry. `hints`
|
|
336
|
+
* carries per-model upstream facts OpenCode 2 maps to `compatibility`.
|
|
335
337
|
*/
|
|
336
338
|
export interface DiscoveredModels {
|
|
337
339
|
models: Record<string, unknown>
|
|
338
340
|
responsesIds: string[]
|
|
341
|
+
hints: Record<string, ModelHints>
|
|
339
342
|
}
|
|
340
343
|
|
|
341
344
|
/**
|
|
@@ -343,7 +346,7 @@ export interface DiscoveredModels {
|
|
|
343
346
|
*
|
|
344
347
|
* Pure with respect to plugin config: it performs the network calls,
|
|
345
348
|
* classifies + formats each model, and returns the built entries plus the
|
|
346
|
-
* ids that require the Responses API. The provider's
|
|
349
|
+
* ids that require the Responses API and per-model hints. The provider's
|
|
347
350
|
* `includeModels`/`excludeModels` filters, `modelCapabilities` overrides and
|
|
348
351
|
* `formatModelNames` choice are applied here (not at merge time) so every
|
|
349
352
|
* path that persists or serves a cache — cold discovery and background
|
|
@@ -411,6 +414,7 @@ export async function discoverModels(
|
|
|
411
414
|
|
|
412
415
|
const built: Record<string, unknown> = {}
|
|
413
416
|
const responsesIds: string[] = []
|
|
417
|
+
const hints: Record<string, ModelHints> = {}
|
|
414
418
|
let skipped = 0
|
|
415
419
|
let wildcards = 0
|
|
416
420
|
let filtered = 0
|
|
@@ -440,6 +444,10 @@ export async function discoverModels(
|
|
|
440
444
|
}
|
|
441
445
|
built[model.id] = entry
|
|
442
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
|
+
}
|
|
443
451
|
}
|
|
444
452
|
|
|
445
453
|
if (unmatched.length > 0) {
|
|
@@ -471,7 +479,7 @@ export async function discoverModels(
|
|
|
471
479
|
')',
|
|
472
480
|
)
|
|
473
481
|
|
|
474
|
-
return { models: built, responsesIds }
|
|
482
|
+
return { models: built, responsesIds, hints }
|
|
475
483
|
}
|
|
476
484
|
|
|
477
485
|
/**
|
|
@@ -655,7 +663,7 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
|
|
|
655
663
|
DISCOVERY_TIMEOUT_MS,
|
|
656
664
|
)
|
|
657
665
|
if (discovered && Object.keys(discovered.models).length > 0) {
|
|
658
|
-
writeModelCache(cacheKey, discovered.models, discovered.responsesIds)
|
|
666
|
+
writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
|
|
659
667
|
log(
|
|
660
668
|
'info',
|
|
661
669
|
`[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(discovered.models).length} models)`,
|
|
@@ -913,7 +921,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
913
921
|
customHeaders,
|
|
914
922
|
)
|
|
915
923
|
injectedModelIds.set(cacheKey, new Set(added))
|
|
916
|
-
writeModelCache(cacheKey, discovered.models, discovered.responsesIds)
|
|
924
|
+
writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
|
|
917
925
|
}
|
|
918
926
|
}
|
|
919
927
|
},
|
package/src/plugin/v2.ts
CHANGED
|
@@ -21,10 +21,24 @@ import {
|
|
|
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
|
+
])
|
|
28
42
|
// Runtime package that talks to `/v1/responses`. OpenCode 2 lets one model
|
|
29
43
|
// override the provider's package, so Responses models stay under their
|
|
30
44
|
// original provider id and no sibling provider is needed here.
|
|
@@ -78,6 +92,7 @@ interface ProviderSource {
|
|
|
78
92
|
pendingPublication: boolean
|
|
79
93
|
filters: ModelFilters
|
|
80
94
|
capabilities: ModelCapabilities
|
|
95
|
+
compatibility: ModelCompatibility
|
|
81
96
|
formatModelNames: boolean
|
|
82
97
|
cacheKey: string
|
|
83
98
|
models: Model.Info[]
|
|
@@ -111,12 +126,21 @@ function numberOrZero(value: unknown): number {
|
|
|
111
126
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
112
127
|
}
|
|
113
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
|
+
|
|
114
137
|
function toProviderModels(
|
|
115
138
|
providerID: string,
|
|
116
139
|
entries: Record<string, unknown>,
|
|
117
|
-
|
|
140
|
+
options: ToProviderModelsOptions,
|
|
118
141
|
): Model.Info[] {
|
|
119
142
|
const provider = Provider.ID.make(providerID)
|
|
143
|
+
const { responsesIds, hints, compatibility: overrides } = options
|
|
120
144
|
|
|
121
145
|
return Object.entries(entries).flatMap(([modelID, value]) => {
|
|
122
146
|
const entry = asRecord(value)
|
|
@@ -152,6 +176,11 @@ function toProviderModels(
|
|
|
152
176
|
id: id as Model.VariantID,
|
|
153
177
|
settings: asRecord(settings),
|
|
154
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
|
+
)
|
|
155
184
|
return [
|
|
156
185
|
{
|
|
157
186
|
...defaults,
|
|
@@ -159,6 +188,11 @@ function toProviderModels(
|
|
|
159
188
|
// runtime package for itself, so it keeps the provider id while
|
|
160
189
|
// still reaching the Responses API.
|
|
161
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
|
+
: {}),
|
|
162
196
|
name: readString(entry.name) ?? modelID,
|
|
163
197
|
limit: {
|
|
164
198
|
context: numberOrDefault(limit.context, defaults.limit.context),
|
|
@@ -228,6 +262,7 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
|
|
|
228
262
|
'includeModels',
|
|
229
263
|
'excludeModels',
|
|
230
264
|
'modelCapabilities',
|
|
265
|
+
'modelCompatibility',
|
|
231
266
|
'formatModelNames',
|
|
232
267
|
'providerID',
|
|
233
268
|
]) {
|
|
@@ -277,6 +312,7 @@ async function makeProviderSource(
|
|
|
277
312
|
const apiKey = configuredApiKey ?? connectedApiKey
|
|
278
313
|
const filters = readModelFilters(settings)
|
|
279
314
|
const capabilities = parseModelCapabilities(settings.modelCapabilities)
|
|
315
|
+
const compatibility = parseModelCompatibility(settings.modelCompatibility)
|
|
280
316
|
const formatModelNames = readFormatModelNames(settings)
|
|
281
317
|
const detectedBaseURL = configuredBaseURL
|
|
282
318
|
? normalizeBaseURL(configuredBaseURL)
|
|
@@ -293,6 +329,7 @@ async function makeProviderSource(
|
|
|
293
329
|
const cacheEntry = readModelCacheEntry(cacheKey)
|
|
294
330
|
let entries = cacheEntry?.models ?? null
|
|
295
331
|
let responsesIds = cacheEntry?.responsesIds ?? []
|
|
332
|
+
let hints = cacheEntry?.hints ?? {}
|
|
296
333
|
|
|
297
334
|
if (!entries || Object.keys(entries).length === 0) {
|
|
298
335
|
const discovered = await withTimeout(
|
|
@@ -310,10 +347,12 @@ async function makeProviderSource(
|
|
|
310
347
|
if (discovered && Object.keys(discovered.models).length > 0) {
|
|
311
348
|
entries = discovered.models
|
|
312
349
|
responsesIds = discovered.responsesIds
|
|
313
|
-
|
|
350
|
+
hints = discovered.hints
|
|
351
|
+
writeModelCache(cacheKey, entries, responsesIds, hints)
|
|
314
352
|
} else {
|
|
315
353
|
entries = null
|
|
316
354
|
responsesIds = []
|
|
355
|
+
hints = {}
|
|
317
356
|
}
|
|
318
357
|
} else {
|
|
319
358
|
logInfo(
|
|
@@ -321,11 +360,12 @@ async function makeProviderSource(
|
|
|
321
360
|
)
|
|
322
361
|
}
|
|
323
362
|
|
|
363
|
+
const providerPackage = provider?.package || OPENAI_COMPATIBLE_PACKAGE
|
|
324
364
|
return {
|
|
325
365
|
id,
|
|
326
366
|
name: provider?.name || 'LiteLLM (proxy)',
|
|
327
367
|
activation: provider?.activation ?? 'enabled',
|
|
328
|
-
package:
|
|
368
|
+
package: providerPackage,
|
|
329
369
|
settings,
|
|
330
370
|
headers: customHeaders,
|
|
331
371
|
integrationID: provider?.integrationID,
|
|
@@ -339,9 +379,15 @@ async function makeProviderSource(
|
|
|
339
379
|
customHeaders: Object.keys(customHeaders).length > 0 ? customHeaders : undefined,
|
|
340
380
|
filters,
|
|
341
381
|
capabilities,
|
|
382
|
+
compatibility,
|
|
342
383
|
formatModelNames,
|
|
343
384
|
cacheKey,
|
|
344
|
-
models: toProviderModels(id, entries ?? {},
|
|
385
|
+
models: toProviderModels(id, entries ?? {}, {
|
|
386
|
+
providerPackage,
|
|
387
|
+
responsesIds: new Set(responsesIds),
|
|
388
|
+
hints,
|
|
389
|
+
compatibility,
|
|
390
|
+
}),
|
|
345
391
|
ownedModelIds: new Set<string>(),
|
|
346
392
|
}
|
|
347
393
|
}
|
|
@@ -395,13 +441,14 @@ async function refreshProviderSource(
|
|
|
395
441
|
return
|
|
396
442
|
}
|
|
397
443
|
|
|
398
|
-
const models = toProviderModels(
|
|
399
|
-
source.
|
|
400
|
-
discovered.
|
|
401
|
-
|
|
402
|
-
|
|
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
|
+
})
|
|
403
450
|
if (JSON.stringify(models) === JSON.stringify(source.models)) {
|
|
404
|
-
writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds)
|
|
451
|
+
writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
|
|
405
452
|
source.refreshRequired = false
|
|
406
453
|
return
|
|
407
454
|
}
|
|
@@ -415,7 +462,7 @@ async function refreshProviderSource(
|
|
|
415
462
|
throw error
|
|
416
463
|
}
|
|
417
464
|
|
|
418
|
-
writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds)
|
|
465
|
+
writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
|
|
419
466
|
source.refreshRequired = false
|
|
420
467
|
logInfo(
|
|
421
468
|
`[opencode-litellm] Refreshed ${models.length} models for provider "${source.id}"; the provider registry was reloaded.`,
|
package/src/utils/model-cache.ts
CHANGED
|
@@ -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 =
|
|
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
|
|
@@ -29,6 +42,11 @@ interface ModelCacheFile {
|
|
|
29
42
|
* no transport marker (their shape is the user-facing OpenCode config).
|
|
30
43
|
*/
|
|
31
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>
|
|
32
50
|
}
|
|
33
51
|
|
|
34
52
|
/**
|
|
@@ -134,6 +152,18 @@ function normalizeResponsesIds(value: unknown): string[] {
|
|
|
134
152
|
return value.filter((id): id is string => typeof id === 'string')
|
|
135
153
|
}
|
|
136
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
|
+
|
|
137
167
|
/**
|
|
138
168
|
* Read cached model entries for a cache key. Returns `null` on any
|
|
139
169
|
* problem (missing file, parse error, version mismatch, or an entry
|
|
@@ -155,14 +185,18 @@ export function readModelCache(
|
|
|
155
185
|
}
|
|
156
186
|
|
|
157
187
|
/**
|
|
158
|
-
* Read the models
|
|
159
|
-
* parse. Returns `null` under the same conditions as
|
|
160
|
-
* {@link readModelCache} (missing/expired cache), so the
|
|
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
|
|
161
191
|
* disagree within a single lookup.
|
|
162
192
|
*/
|
|
163
193
|
export function readModelCacheEntry(
|
|
164
194
|
cacheKey: string,
|
|
165
|
-
): {
|
|
195
|
+
): {
|
|
196
|
+
models: Record<string, unknown>
|
|
197
|
+
responsesIds: string[]
|
|
198
|
+
hints: Record<string, ModelHints>
|
|
199
|
+
} | null {
|
|
166
200
|
const parsed = readCacheFile(cacheKey)
|
|
167
201
|
if (!parsed) return null
|
|
168
202
|
if (
|
|
@@ -171,7 +205,11 @@ export function readModelCacheEntry(
|
|
|
171
205
|
) {
|
|
172
206
|
return null
|
|
173
207
|
}
|
|
174
|
-
return {
|
|
208
|
+
return {
|
|
209
|
+
models: parsed.models,
|
|
210
|
+
responsesIds: normalizeResponsesIds(parsed.responsesIds),
|
|
211
|
+
hints: normalizeHints(parsed.hints),
|
|
212
|
+
}
|
|
175
213
|
}
|
|
176
214
|
|
|
177
215
|
/**
|
|
@@ -204,6 +242,7 @@ export function writeModelCache(
|
|
|
204
242
|
cacheKey: string,
|
|
205
243
|
models: Record<string, unknown>,
|
|
206
244
|
responsesIds: readonly string[] = [],
|
|
245
|
+
hints: Record<string, ModelHints> = {},
|
|
207
246
|
): void {
|
|
208
247
|
try {
|
|
209
248
|
mkdirSync(cacheDir(), { recursive: true })
|
|
@@ -212,6 +251,7 @@ export function writeModelCache(
|
|
|
212
251
|
savedAt: Date.now(),
|
|
213
252
|
models,
|
|
214
253
|
responsesIds: [...responsesIds],
|
|
254
|
+
hints,
|
|
215
255
|
}
|
|
216
256
|
// Write to a temp file and rename so concurrent OpenCode processes
|
|
217
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
|
+
}
|