opencode-plugin-litellm 0.9.0 → 0.11.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 +5 -2
- package/package.json +1 -1
- package/src/plugin/index.ts +264 -114
- package/src/utils/model-cache.ts +123 -0
- package/src/utils/opencode-auth.ts +83 -0
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
1
3
|
<div align="center">
|
|
2
4
|
|
|
3
5
|
<img src="https://raw.githubusercontent.com/yuseferi/opencode-litellm/main/assets/logo.svg" alt="opencode-litellm logo" width="128" height="128" />
|
|
@@ -244,8 +246,9 @@ If your LiteLLM proxy requires a master key, expose it via either approach:
|
|
|
244
246
|
| Env var | `export LITELLM_API_KEY=sk-...` |
|
|
245
247
|
| Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
|
|
246
248
|
| Config | `"options": { "apiKey": "{env:LITELLM_API_KEY}" }` |
|
|
249
|
+
| OpenCode `/connect` | Run `/connect`, search for your `litellm` provider entry, and paste the key |
|
|
247
250
|
|
|
248
|
-
The env var path lets you commit `opencode.json` without leaking secrets.
|
|
251
|
+
The env var path lets you commit `opencode.json` without leaking secrets. The `/connect` path is useful when you'd rather manage the credential through OpenCode's own auth store (`~/.local/share/opencode/auth.json`) instead of an env var or config file — the plugin reads that file as a fallback and applies the stored key to its own health-check, model-discovery, and completion-time provider requests, so a key-only proxy works end to end.
|
|
249
252
|
|
|
250
253
|
### Custom headers (Cloudflare Access, API gateways)
|
|
251
254
|
|
|
@@ -307,7 +310,7 @@ sequenceDiagram
|
|
|
307
310
|
|
|
308
311
|
## 📋 Requirements
|
|
309
312
|
|
|
310
|
-
- [OpenCode](https://opencode.ai) ≥ 0.1.x with plugin support (`@opencode-ai/plugin ^1.0
|
|
313
|
+
- [OpenCode](https://opencode.ai) ≥ 0.1.x with plugin support (`@opencode-ai/plugin ^1.14.0`)
|
|
311
314
|
- A running [LiteLLM](https://github.com/BerriAI/litellm) proxy:
|
|
312
315
|
```bash
|
|
313
316
|
pip install 'litellm[proxy]'
|
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": "0.
|
|
4
|
+
"version": "0.11.0",
|
|
5
5
|
"description": "OpenCode plugin for LiteLLM proxy support with auto-detection and dynamic model discovery",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./src/index.ts",
|
package/src/plugin/index.ts
CHANGED
|
@@ -11,11 +11,16 @@ import {
|
|
|
11
11
|
categorizeModel,
|
|
12
12
|
} from '../utils/format-model-name'
|
|
13
13
|
import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
|
|
14
|
+
import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
|
|
15
|
+
import { readModelCache, writeModelCache, readModelCacheSavedAt } from '../utils/model-cache'
|
|
14
16
|
|
|
15
17
|
const CHAT_PROVIDER_ID = 'litellm'
|
|
16
18
|
// Covers the sequential 3 s health check plus the parallel 15 s
|
|
17
19
|
// models/model-info fetch phase, with headroom.
|
|
18
20
|
const DISCOVERY_TIMEOUT_MS = 20000
|
|
21
|
+
// Don't revalidate a baseURL's cache more often than this, so a burst
|
|
22
|
+
// of `session.created` events can't generate repeated discovery traffic.
|
|
23
|
+
const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000 // 5 minutes
|
|
19
24
|
|
|
20
25
|
/**
|
|
21
26
|
* OpenCode invokes the `config` hook several times per run with a
|
|
@@ -25,6 +30,37 @@ const DISCOVERY_TIMEOUT_MS = 20000
|
|
|
25
30
|
*/
|
|
26
31
|
const injectedModelIds = new Map<string, Set<string>>()
|
|
27
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Per-baseURL fetch context captured during the `config` hook, so the
|
|
35
|
+
* `event` hook can revalidate the cache in the background (SWR) without
|
|
36
|
+
* re-deriving auth/headers.
|
|
37
|
+
*/
|
|
38
|
+
interface RefreshContext {
|
|
39
|
+
apiKey?: string
|
|
40
|
+
customHeaders?: Record<string, string>
|
|
41
|
+
providerId: string
|
|
42
|
+
}
|
|
43
|
+
const refreshContexts = new Map<string, RefreshContext>()
|
|
44
|
+
|
|
45
|
+
/** baseURLs with an in-flight background refresh, to avoid pile-ups. */
|
|
46
|
+
const refreshInFlight = new Set<string>()
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Race a promise against a timeout, resolving to `null` if the timeout
|
|
50
|
+
* wins. Clears the timer either way so a resolved discovery can't keep
|
|
51
|
+
* a short-lived process alive waiting on a pending `setTimeout`.
|
|
52
|
+
*/
|
|
53
|
+
function withTimeout<T>(
|
|
54
|
+
promise: Promise<T>,
|
|
55
|
+
timeoutMs: number,
|
|
56
|
+
): Promise<T | null> {
|
|
57
|
+
let timer: ReturnType<typeof setTimeout>
|
|
58
|
+
const timeout = new Promise<null>((resolve) => {
|
|
59
|
+
timer = setTimeout(() => resolve(null), timeoutMs)
|
|
60
|
+
})
|
|
61
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
|
|
62
|
+
}
|
|
63
|
+
|
|
28
64
|
/**
|
|
29
65
|
* Helper to determine if a provider ID or its configured options indicate
|
|
30
66
|
* compatibility with LiteLLM.
|
|
@@ -151,6 +187,161 @@ function toConfigModel(
|
|
|
151
187
|
return entry
|
|
152
188
|
}
|
|
153
189
|
|
|
190
|
+
/**
|
|
191
|
+
* Fetch and build OpenCode model entries from a LiteLLM proxy.
|
|
192
|
+
*
|
|
193
|
+
* Pure with respect to plugin config: it performs the network calls,
|
|
194
|
+
* classifies + formats each model, and returns a `{ id -> entry }` map.
|
|
195
|
+
* Returns `null` when the proxy is unreachable/unauthorized or exposes
|
|
196
|
+
* no models, so callers can distinguish "no data" from "empty result".
|
|
197
|
+
*/
|
|
198
|
+
async function discoverModels(
|
|
199
|
+
baseURL: string,
|
|
200
|
+
apiKey: string | undefined,
|
|
201
|
+
customHeaders: Record<string, string> | undefined,
|
|
202
|
+
providerId: string,
|
|
203
|
+
): Promise<Record<string, unknown> | null> {
|
|
204
|
+
if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
|
|
205
|
+
console.warn(
|
|
206
|
+
`[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
|
|
207
|
+
)
|
|
208
|
+
return null
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// `/v1/models` omits `mode` and capability metadata for
|
|
212
|
+
// database-defined models, so fetch `/v1/model/info` alongside
|
|
213
|
+
// it. The info call is best-effort: without it, classification
|
|
214
|
+
// falls back to id heuristics.
|
|
215
|
+
const [modelsResult, infoResult] = await Promise.allSettled([
|
|
216
|
+
discoverLiteLLMModels(baseURL, apiKey, customHeaders),
|
|
217
|
+
discoverLiteLLMModelInfo(baseURL, apiKey, customHeaders),
|
|
218
|
+
])
|
|
219
|
+
|
|
220
|
+
if (modelsResult.status === 'rejected') {
|
|
221
|
+
const error = modelsResult.reason
|
|
222
|
+
console.warn(
|
|
223
|
+
`[opencode-litellm] Model discovery failed for provider "${providerId}":`,
|
|
224
|
+
error instanceof Error ? error.message : String(error),
|
|
225
|
+
)
|
|
226
|
+
return null
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const discovered = modelsResult.value
|
|
230
|
+
let infoByName: Map<string, LiteLLMModelInfo> | null = null
|
|
231
|
+
if (infoResult.status === 'fulfilled') {
|
|
232
|
+
infoByName = infoResult.value
|
|
233
|
+
} else {
|
|
234
|
+
const reason = infoResult.reason
|
|
235
|
+
console.warn(
|
|
236
|
+
`[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only:`,
|
|
237
|
+
reason instanceof Error ? reason.message : String(reason),
|
|
238
|
+
)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (discovered.length === 0) {
|
|
242
|
+
console.warn(
|
|
243
|
+
`[opencode-litellm] LiteLLM responded for provider "${providerId}" but exposed zero models.`,
|
|
244
|
+
)
|
|
245
|
+
return null
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const built: Record<string, unknown> = {}
|
|
249
|
+
let skipped = 0
|
|
250
|
+
let wildcards = 0
|
|
251
|
+
const unmatched: string[] = []
|
|
252
|
+
for (const model of discovered) {
|
|
253
|
+
// Wildcard entries (`deepseek/*`) are access rules, not
|
|
254
|
+
// callable models — invoking one sends a literal `*` upstream.
|
|
255
|
+
if (model.id.includes('*')) {
|
|
256
|
+
wildcards++
|
|
257
|
+
continue
|
|
258
|
+
}
|
|
259
|
+
const info = infoByName?.get(model.id)
|
|
260
|
+
if (infoByName && !info) unmatched.push(model.id)
|
|
261
|
+
const entry = toConfigModel(info ? enrichModel(model, info) : model, info)
|
|
262
|
+
if (!entry) {
|
|
263
|
+
skipped++
|
|
264
|
+
continue
|
|
265
|
+
}
|
|
266
|
+
built[model.id] = entry
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (unmatched.length > 0) {
|
|
270
|
+
console.warn(
|
|
271
|
+
`[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s) on provider "${providerId}"; ` +
|
|
272
|
+
`classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
|
|
273
|
+
(unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
|
|
274
|
+
)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
console.log(
|
|
278
|
+
`[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
|
|
279
|
+
`(${Object.keys(built).length} built` +
|
|
280
|
+
(skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
|
|
281
|
+
(wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
|
|
282
|
+
')',
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
return built
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Merge freshly built model entries into a provider's `models` map
|
|
290
|
+
* without clobbering user-curated (or previously injected) entries.
|
|
291
|
+
* Returns the ids actually added by this call.
|
|
292
|
+
*/
|
|
293
|
+
function mergeModels(
|
|
294
|
+
models: Record<string, unknown>,
|
|
295
|
+
built: Record<string, unknown>,
|
|
296
|
+
): string[] {
|
|
297
|
+
const added: string[] = []
|
|
298
|
+
for (const [id, entry] of Object.entries(built)) {
|
|
299
|
+
if (Object.hasOwn(models, id)) continue
|
|
300
|
+
models[id] = entry
|
|
301
|
+
added.push(id)
|
|
302
|
+
}
|
|
303
|
+
// Remove the seed placeholder if real models were merged in.
|
|
304
|
+
if (Object.hasOwn(models, '_') && Object.keys(models).length > 1) {
|
|
305
|
+
delete models['_']
|
|
306
|
+
}
|
|
307
|
+
return added
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Revalidate a baseURL's model cache off the critical path (SWR). The
|
|
312
|
+
* refreshed entries land in the on-disk cache and surface on the next
|
|
313
|
+
* OpenCode start — OpenCode only reads provider config at startup, so
|
|
314
|
+
* we can't mutate the live picker here.
|
|
315
|
+
*/
|
|
316
|
+
async function backgroundRefresh(baseURL: string): Promise<void> {
|
|
317
|
+
if (refreshInFlight.has(baseURL)) return
|
|
318
|
+
const ctx = refreshContexts.get(baseURL)
|
|
319
|
+
if (!ctx) return
|
|
320
|
+
// Skip if the cache was refreshed recently — a burst of new sessions
|
|
321
|
+
// shouldn't hammer the proxy with health checks and discovery calls.
|
|
322
|
+
const savedAt = readModelCacheSavedAt(baseURL)
|
|
323
|
+
if (savedAt !== null && Date.now() - savedAt < REFRESH_MIN_INTERVAL_MS) {
|
|
324
|
+
return
|
|
325
|
+
}
|
|
326
|
+
refreshInFlight.add(baseURL)
|
|
327
|
+
try {
|
|
328
|
+
const built = await withTimeout(
|
|
329
|
+
discoverModels(baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
|
|
330
|
+
DISCOVERY_TIMEOUT_MS,
|
|
331
|
+
)
|
|
332
|
+
if (built && Object.keys(built).length > 0) {
|
|
333
|
+
writeModelCache(baseURL, built)
|
|
334
|
+
console.log(
|
|
335
|
+
`[opencode-litellm] Background-refreshed model cache for ${baseURL} (${Object.keys(built).length} models)`,
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
} catch {
|
|
339
|
+
// Best-effort — a failed refresh just leaves the stale cache in place.
|
|
340
|
+
} finally {
|
|
341
|
+
refreshInFlight.delete(baseURL)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
154
345
|
/**
|
|
155
346
|
* LiteLLM Plugin for OpenCode.
|
|
156
347
|
*
|
|
@@ -221,8 +412,17 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
|
|
|
221
412
|
? options.apiKey
|
|
222
413
|
: undefined
|
|
223
414
|
const envKey =
|
|
224
|
-
process.env.LITELLM_API_KEY
|
|
225
|
-
|
|
415
|
+
process.env.LITELLM_API_KEY || process.env.LITELLM_MASTER_KEY || undefined
|
|
416
|
+
/*
|
|
417
|
+
Falls back to the key OpenCode itself stored for this provider id via
|
|
418
|
+
'/connect' (~/.local/share/opencode/auth.json). For a custom provider
|
|
419
|
+
like this one there is no automatic auth.json injection (see below), so
|
|
420
|
+
the plugin reads the stored key here and applies it to both its own
|
|
421
|
+
discovery fetches and the completion-time provider options. Without it,
|
|
422
|
+
a key-only proxy would fail discovery even though chat works.
|
|
423
|
+
*/
|
|
424
|
+
const storedKey = await getOpenCodeStoredApiKey(providerId)
|
|
425
|
+
const apiKey = configuredKey ?? envKey ?? storedKey
|
|
226
426
|
const customHeaders = readCustomHeaders(options)
|
|
227
427
|
|
|
228
428
|
// Resolve base URL
|
|
@@ -251,12 +451,25 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
|
|
|
251
451
|
}
|
|
252
452
|
|
|
253
453
|
if (!actualProvider.options) {
|
|
254
|
-
actualProvider.options = {
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
454
|
+
actualProvider.options = {}
|
|
455
|
+
}
|
|
456
|
+
const actualOptions = actualProvider.options as Record<string, unknown>
|
|
457
|
+
if (!actualOptions.baseURL) {
|
|
458
|
+
actualOptions.baseURL = `${baseURL}/v1`
|
|
459
|
+
}
|
|
460
|
+
/*
|
|
461
|
+
For a fully custom, config-only provider like this one, OpenCode
|
|
462
|
+
builds the real completion-time AI SDK client straight from
|
|
463
|
+
`options` - there's no separate auth.json auto-injection for
|
|
464
|
+
arbitrary custom providers (that only applies to a handful of
|
|
465
|
+
models.dev-catalog providers with special-cased loaders). So the
|
|
466
|
+
`apiKey` resolved above (config > env var > OpenCode-stored
|
|
467
|
+
credential) must be written back here, or real chat completions
|
|
468
|
+
go out with no Authorization header even though discovery
|
|
469
|
+
succeeded using the same resolved key.
|
|
470
|
+
*/
|
|
471
|
+
if (!actualOptions.apiKey && apiKey) {
|
|
472
|
+
actualOptions.apiKey = apiKey
|
|
260
473
|
}
|
|
261
474
|
|
|
262
475
|
if (!actualProvider.models) {
|
|
@@ -265,117 +478,54 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
|
|
|
265
478
|
|
|
266
479
|
const models = actualProvider.models as Record<string, unknown>
|
|
267
480
|
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
)
|
|
282
|
-
return
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
// `/v1/models` omits `mode` and capability metadata for
|
|
286
|
-
// database-defined models, so fetch `/v1/model/info` alongside
|
|
287
|
-
// it. The info call is best-effort: without it, classification
|
|
288
|
-
// falls back to id heuristics.
|
|
289
|
-
const [modelsResult, infoResult] = await Promise.allSettled([
|
|
290
|
-
discoverLiteLLMModels(baseURL!, apiKey, customHeaders),
|
|
291
|
-
discoverLiteLLMModelInfo(baseURL!, apiKey, customHeaders),
|
|
292
|
-
])
|
|
293
|
-
|
|
294
|
-
if (modelsResult.status === 'rejected') {
|
|
295
|
-
const error = modelsResult.reason
|
|
296
|
-
console.warn(
|
|
297
|
-
`[opencode-litellm] Model discovery failed for provider "${providerId}":`,
|
|
298
|
-
error instanceof Error ? error.message : String(error),
|
|
299
|
-
)
|
|
300
|
-
return
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
const discovered = modelsResult.value
|
|
304
|
-
let infoByName: Map<string, LiteLLMModelInfo> | null = null
|
|
305
|
-
if (infoResult.status === 'fulfilled') {
|
|
306
|
-
infoByName = infoResult.value
|
|
307
|
-
} else {
|
|
308
|
-
const reason = infoResult.reason
|
|
309
|
-
console.warn(
|
|
310
|
-
`[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only:`,
|
|
311
|
-
reason instanceof Error ? reason.message : String(reason),
|
|
312
|
-
)
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
if (discovered.length === 0) {
|
|
316
|
-
console.warn(
|
|
317
|
-
`[opencode-litellm] LiteLLM responded for provider "${providerId}" but exposed zero models.`,
|
|
318
|
-
)
|
|
319
|
-
return
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
let added = 0
|
|
323
|
-
let skipped = 0
|
|
324
|
-
let wildcards = 0
|
|
325
|
-
const unmatched: string[] = []
|
|
326
|
-
for (const model of discovered) {
|
|
327
|
-
// Wildcard entries (`deepseek/*`) are access rules, not
|
|
328
|
-
// callable models — invoking one sends a literal `*` upstream.
|
|
329
|
-
if (model.id.includes('*')) {
|
|
330
|
-
wildcards++
|
|
331
|
-
continue
|
|
332
|
-
}
|
|
333
|
-
// Don't overwrite user-curated entries
|
|
334
|
-
if (models[model.id]) continue
|
|
335
|
-
const info = infoByName?.get(model.id)
|
|
336
|
-
if (infoByName && !info) unmatched.push(model.id)
|
|
337
|
-
const entry = toConfigModel(
|
|
338
|
-
info ? enrichModel(model, info) : model,
|
|
339
|
-
info,
|
|
340
|
-
)
|
|
341
|
-
if (!entry) {
|
|
342
|
-
skipped++
|
|
343
|
-
continue
|
|
344
|
-
}
|
|
345
|
-
models[model.id] = entry
|
|
346
|
-
added++
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
if (unmatched.length > 0) {
|
|
350
|
-
console.warn(
|
|
351
|
-
`[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s) on provider "${providerId}"; ` +
|
|
352
|
-
`classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
|
|
353
|
-
(unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
|
|
354
|
-
)
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// Remove the seed placeholder if real models were discovered
|
|
358
|
-
if (models['_'] && Object.keys(models).length > 1) {
|
|
359
|
-
delete models['_']
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
injectedModelIds.set(baseURL!, new Set(Object.keys(models)))
|
|
481
|
+
// Remember how to reach this proxy so the `event` hook can
|
|
482
|
+
// revalidate its cache in the background on new sessions.
|
|
483
|
+
refreshContexts.set(baseURL, { apiKey, customHeaders, providerId })
|
|
484
|
+
|
|
485
|
+
// Repeat config-hook invocations within a run are a no-op once
|
|
486
|
+
// we've injected this baseURL's models.
|
|
487
|
+
const alreadyInjected = injectedModelIds.get(baseURL)
|
|
488
|
+
if (
|
|
489
|
+
alreadyInjected &&
|
|
490
|
+
[...alreadyInjected].every((id) => Object.hasOwn(models, id))
|
|
491
|
+
) {
|
|
492
|
+
continue
|
|
493
|
+
}
|
|
363
494
|
|
|
495
|
+
// SWR fast path: serve cached entries synchronously so startup
|
|
496
|
+
// isn't blocked on the network. A background refresh (see the
|
|
497
|
+
// `event` hook) keeps the cache fresh for the next launch.
|
|
498
|
+
const cached = readModelCache(baseURL)
|
|
499
|
+
if (cached && Object.keys(cached).length > 0) {
|
|
500
|
+
const added = mergeModels(models, cached)
|
|
501
|
+
injectedModelIds.set(baseURL, new Set(added))
|
|
364
502
|
console.log(
|
|
365
|
-
`[opencode-litellm]
|
|
366
|
-
`(${added} added` +
|
|
367
|
-
(skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
|
|
368
|
-
(wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
|
|
369
|
-
')',
|
|
503
|
+
`[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
|
|
370
504
|
)
|
|
505
|
+
continue
|
|
371
506
|
}
|
|
372
507
|
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
),
|
|
378
|
-
|
|
508
|
+
// Cold cache: do a live fetch (slow first run only), inject, and
|
|
509
|
+
// persist for subsequent startups. Capped by a timeout so a slow
|
|
510
|
+
// proxy never blocks boot.
|
|
511
|
+
const built = await withTimeout(
|
|
512
|
+
discoverModels(baseURL, apiKey, customHeaders, providerId),
|
|
513
|
+
DISCOVERY_TIMEOUT_MS,
|
|
514
|
+
)
|
|
515
|
+
if (built && Object.keys(built).length > 0) {
|
|
516
|
+
const added = mergeModels(models, built)
|
|
517
|
+
injectedModelIds.set(baseURL, new Set(added))
|
|
518
|
+
writeModelCache(baseURL, built)
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
event: async ({ event }) => {
|
|
523
|
+
// Revalidate model caches off the critical path when a new session
|
|
524
|
+
// opens. Fresh data lands in the cache and surfaces on the next
|
|
525
|
+
// OpenCode start (SWR).
|
|
526
|
+
if (event.type !== 'session.created') return
|
|
527
|
+
for (const baseURL of refreshContexts.keys()) {
|
|
528
|
+
void backgroundRefresh(baseURL)
|
|
379
529
|
}
|
|
380
530
|
},
|
|
381
531
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFileSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node:fs'
|
|
3
|
+
import { homedir, tmpdir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Bump when the shape of a cached model entry changes so stale caches
|
|
8
|
+
* from older plugin versions are ignored rather than deserialized into
|
|
9
|
+
* an incompatible structure.
|
|
10
|
+
*/
|
|
11
|
+
const CACHE_VERSION = 1
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Maximum age of a cache entry before it's treated as a miss. Without a
|
|
15
|
+
* bound, a proxy that goes away permanently would keep serving the same
|
|
16
|
+
* stale model list on every launch. A background refresh normally keeps
|
|
17
|
+
* entries fresh well within this window.
|
|
18
|
+
*/
|
|
19
|
+
const CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
|
|
20
|
+
|
|
21
|
+
/** The on-disk shape of a per-baseURL model cache file. */
|
|
22
|
+
interface ModelCacheFile {
|
|
23
|
+
version: number
|
|
24
|
+
savedAt: number
|
|
25
|
+
models: Record<string, unknown>
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Directory where SWR model caches live. Honours `XDG_CACHE_HOME`,
|
|
30
|
+
* falling back to `~/.cache`, and finally the OS temp dir if the home
|
|
31
|
+
* directory is somehow unavailable.
|
|
32
|
+
*/
|
|
33
|
+
function cacheDir(): string {
|
|
34
|
+
const home = homedir()
|
|
35
|
+
const base =
|
|
36
|
+
process.env.XDG_CACHE_HOME || (home ? join(home, '.cache') : tmpdir())
|
|
37
|
+
return join(base, 'opencode-litellm')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Stable, filesystem-safe filename derived from the normalized baseURL. */
|
|
41
|
+
function cacheFile(baseURL: string): string {
|
|
42
|
+
const hash = createHash('sha256').update(baseURL).digest('hex').slice(0, 16)
|
|
43
|
+
return join(cacheDir(), `models-${hash}.json`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Read cached model entries for a baseURL. Returns `null` on any
|
|
48
|
+
* problem (missing file, parse error, version mismatch, or an entry
|
|
49
|
+
* older than `CACHE_MAX_AGE_MS`) — the caller treats that as a cache
|
|
50
|
+
* miss and falls back to a live fetch.
|
|
51
|
+
*/
|
|
52
|
+
export function readModelCache(
|
|
53
|
+
baseURL: string,
|
|
54
|
+
): Record<string, unknown> | null {
|
|
55
|
+
try {
|
|
56
|
+
const raw = readFileSync(cacheFile(baseURL), 'utf8')
|
|
57
|
+
const parsed = JSON.parse(raw) as ModelCacheFile
|
|
58
|
+
if (parsed.version !== CACHE_VERSION) return null
|
|
59
|
+
if (!parsed.models || typeof parsed.models !== 'object') return null
|
|
60
|
+
if (
|
|
61
|
+
typeof parsed.savedAt !== 'number' ||
|
|
62
|
+
Date.now() - parsed.savedAt > CACHE_MAX_AGE_MS
|
|
63
|
+
) {
|
|
64
|
+
return null
|
|
65
|
+
}
|
|
66
|
+
return parsed.models
|
|
67
|
+
} catch {
|
|
68
|
+
return null
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Return the `savedAt` timestamp (epoch ms) of a baseURL's cache entry,
|
|
74
|
+
* or `null` if there's no readable/valid cache. Used to throttle
|
|
75
|
+
* background refreshes so still-fresh caches aren't re-fetched.
|
|
76
|
+
*/
|
|
77
|
+
export function readModelCacheSavedAt(baseURL: string): number | null {
|
|
78
|
+
try {
|
|
79
|
+
const raw = readFileSync(cacheFile(baseURL), 'utf8')
|
|
80
|
+
const parsed = JSON.parse(raw) as ModelCacheFile
|
|
81
|
+
if (parsed.version !== CACHE_VERSION) return null
|
|
82
|
+
if (typeof parsed.savedAt !== 'number') return null
|
|
83
|
+
return parsed.savedAt
|
|
84
|
+
} catch {
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Persist model entries for a baseURL. Best-effort: never throws, so a
|
|
91
|
+
* read-only or full filesystem can't break discovery.
|
|
92
|
+
*/
|
|
93
|
+
export function writeModelCache(
|
|
94
|
+
baseURL: string,
|
|
95
|
+
models: Record<string, unknown>,
|
|
96
|
+
): void {
|
|
97
|
+
try {
|
|
98
|
+
mkdirSync(cacheDir(), { recursive: true })
|
|
99
|
+
const payload: ModelCacheFile = {
|
|
100
|
+
version: CACHE_VERSION,
|
|
101
|
+
savedAt: Date.now(),
|
|
102
|
+
models,
|
|
103
|
+
}
|
|
104
|
+
// Write to a temp file and rename so concurrent OpenCode processes
|
|
105
|
+
// never observe a partially-written JSON file (rename is atomic on
|
|
106
|
+
// the same filesystem).
|
|
107
|
+
const target = cacheFile(baseURL)
|
|
108
|
+
const tmp = `${target}.${process.pid}.tmp`
|
|
109
|
+
try {
|
|
110
|
+
writeFileSync(tmp, JSON.stringify(payload), 'utf8')
|
|
111
|
+
renameSync(tmp, target)
|
|
112
|
+
} catch (err) {
|
|
113
|
+
try {
|
|
114
|
+
rmSync(tmp, { force: true })
|
|
115
|
+
} catch {
|
|
116
|
+
// Ignore cleanup failure.
|
|
117
|
+
}
|
|
118
|
+
throw err
|
|
119
|
+
}
|
|
120
|
+
} catch {
|
|
121
|
+
// Ignore — the cache is an optimization, not a requirement.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Shape of an `api`-type entry in OpenCode's own credential store. OpenCode
|
|
7
|
+
* also stores `oauth` and `wellknown` entries there, but LiteLLM proxies
|
|
8
|
+
* only ever use a plain API key, so that's the only variant we care about.
|
|
9
|
+
*/
|
|
10
|
+
interface OpenCodeApiAuthEntry {
|
|
11
|
+
type: 'api'
|
|
12
|
+
key: string
|
|
13
|
+
metadata?: Record<string, string>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type OpenCodeAuthEntry = OpenCodeApiAuthEntry | { type: string; [key: string]: unknown }
|
|
17
|
+
type OpenCodeAuthFile = Record<string, OpenCodeAuthEntry>
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* OpenCode stores credentials added via the `/connect` command (or
|
|
21
|
+
* `opencode auth login`) in this file, keyed by provider id. The location
|
|
22
|
+
* is fixed and identical across macOS, Linux, and Windows — see
|
|
23
|
+
* https://opencode.ai/docs/troubleshooting/#storage.
|
|
24
|
+
*/
|
|
25
|
+
function resolveAuthPath(): string {
|
|
26
|
+
return join(homedir(), '.local', 'share', 'opencode', 'auth.json')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Read once per process. The `config` hook can fire multiple times per
|
|
30
|
+
// run (see plugin/index.ts), and re-reading a credentials file from disk
|
|
31
|
+
// on every invocation is both wasteful and unnecessary — a `/connect` run
|
|
32
|
+
// mid-session wouldn't be picked up by the already-running plugin anyway
|
|
33
|
+
// (model discovery itself is cached per baseURL for the same reason).
|
|
34
|
+
let cachedAuthFile: Promise<OpenCodeAuthFile | null> | null = null
|
|
35
|
+
|
|
36
|
+
async function loadOpenCodeAuthFile(): Promise<OpenCodeAuthFile | null> {
|
|
37
|
+
if (!cachedAuthFile) {
|
|
38
|
+
cachedAuthFile = (async () => {
|
|
39
|
+
try {
|
|
40
|
+
const raw = await readFile(resolveAuthPath(), 'utf-8')
|
|
41
|
+
const parsed: unknown = JSON.parse(raw)
|
|
42
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
43
|
+
return parsed as OpenCodeAuthFile
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
// File doesn't exist, isn't readable, or isn't valid JSON — treat
|
|
47
|
+
// as "no stored credentials" rather than failing plugin startup.
|
|
48
|
+
}
|
|
49
|
+
return null
|
|
50
|
+
})()
|
|
51
|
+
}
|
|
52
|
+
return cachedAuthFile
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Look up the API key OpenCode itself stored for a given provider id via
|
|
57
|
+
* the `/connect` command. This is entirely separate from this plugin's
|
|
58
|
+
* own `options.apiKey` / `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`
|
|
59
|
+
* configuration: for a custom provider like this one, OpenCode does not
|
|
60
|
+
* inject stored credentials automatically, so the plugin reads the file
|
|
61
|
+
* directly and applies the key to its own health-check / `/v1/models`
|
|
62
|
+
* discovery fetches and to the completion-time provider `options` (see
|
|
63
|
+
* plugin/index.ts) as a fallback credential source.
|
|
64
|
+
*
|
|
65
|
+
* Returns `undefined` if the file is missing/unreadable, or has no
|
|
66
|
+
* `type: "api"` entry for `providerId`.
|
|
67
|
+
*/
|
|
68
|
+
export async function getOpenCodeStoredApiKey(providerId: string): Promise<string | undefined> {
|
|
69
|
+
const auth = await loadOpenCodeAuthFile()
|
|
70
|
+
const entry = auth?.[providerId]
|
|
71
|
+
if (entry && entry.type === 'api' && typeof (entry as OpenCodeApiAuthEntry).key === 'string') {
|
|
72
|
+
const key = (entry as OpenCodeApiAuthEntry).key
|
|
73
|
+
if (key.length > 0) {
|
|
74
|
+
return key
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return undefined
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Test-only: force the next read to hit disk again. */
|
|
81
|
+
export function __resetOpenCodeAuthCacheForTests(): void {
|
|
82
|
+
cachedAuthFile = null
|
|
83
|
+
}
|