opencode-plugin-litellm 0.9.0 → 0.10.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/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.9.0",
4
+ "version": "0.10.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",
@@ -11,11 +11,15 @@ import {
11
11
  categorizeModel,
12
12
  } from '../utils/format-model-name'
13
13
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
14
+ import { readModelCache, writeModelCache, readModelCacheSavedAt } from '../utils/model-cache'
14
15
 
15
16
  const CHAT_PROVIDER_ID = 'litellm'
16
17
  // Covers the sequential 3 s health check plus the parallel 15 s
17
18
  // models/model-info fetch phase, with headroom.
18
19
  const DISCOVERY_TIMEOUT_MS = 20000
20
+ // Don't revalidate a baseURL's cache more often than this, so a burst
21
+ // of `session.created` events can't generate repeated discovery traffic.
22
+ const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000 // 5 minutes
19
23
 
20
24
  /**
21
25
  * OpenCode invokes the `config` hook several times per run with a
@@ -25,6 +29,37 @@ const DISCOVERY_TIMEOUT_MS = 20000
25
29
  */
26
30
  const injectedModelIds = new Map<string, Set<string>>()
27
31
 
32
+ /**
33
+ * Per-baseURL fetch context captured during the `config` hook, so the
34
+ * `event` hook can revalidate the cache in the background (SWR) without
35
+ * re-deriving auth/headers.
36
+ */
37
+ interface RefreshContext {
38
+ apiKey?: string
39
+ customHeaders?: Record<string, string>
40
+ providerId: string
41
+ }
42
+ const refreshContexts = new Map<string, RefreshContext>()
43
+
44
+ /** baseURLs with an in-flight background refresh, to avoid pile-ups. */
45
+ const refreshInFlight = new Set<string>()
46
+
47
+ /**
48
+ * Race a promise against a timeout, resolving to `null` if the timeout
49
+ * wins. Clears the timer either way so a resolved discovery can't keep
50
+ * a short-lived process alive waiting on a pending `setTimeout`.
51
+ */
52
+ function withTimeout<T>(
53
+ promise: Promise<T>,
54
+ timeoutMs: number,
55
+ ): Promise<T | null> {
56
+ let timer: ReturnType<typeof setTimeout>
57
+ const timeout = new Promise<null>((resolve) => {
58
+ timer = setTimeout(() => resolve(null), timeoutMs)
59
+ })
60
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
61
+ }
62
+
28
63
  /**
29
64
  * Helper to determine if a provider ID or its configured options indicate
30
65
  * compatibility with LiteLLM.
@@ -151,6 +186,161 @@ function toConfigModel(
151
186
  return entry
152
187
  }
153
188
 
189
+ /**
190
+ * Fetch and build OpenCode model entries from a LiteLLM proxy.
191
+ *
192
+ * Pure with respect to plugin config: it performs the network calls,
193
+ * classifies + formats each model, and returns a `{ id -> entry }` map.
194
+ * Returns `null` when the proxy is unreachable/unauthorized or exposes
195
+ * no models, so callers can distinguish "no data" from "empty result".
196
+ */
197
+ async function discoverModels(
198
+ baseURL: string,
199
+ apiKey: string | undefined,
200
+ customHeaders: Record<string, string> | undefined,
201
+ providerId: string,
202
+ ): Promise<Record<string, unknown> | null> {
203
+ if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
204
+ console.warn(
205
+ `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
206
+ )
207
+ return null
208
+ }
209
+
210
+ // `/v1/models` omits `mode` and capability metadata for
211
+ // database-defined models, so fetch `/v1/model/info` alongside
212
+ // it. The info call is best-effort: without it, classification
213
+ // falls back to id heuristics.
214
+ const [modelsResult, infoResult] = await Promise.allSettled([
215
+ discoverLiteLLMModels(baseURL, apiKey, customHeaders),
216
+ discoverLiteLLMModelInfo(baseURL, apiKey, customHeaders),
217
+ ])
218
+
219
+ if (modelsResult.status === 'rejected') {
220
+ const error = modelsResult.reason
221
+ console.warn(
222
+ `[opencode-litellm] Model discovery failed for provider "${providerId}":`,
223
+ error instanceof Error ? error.message : String(error),
224
+ )
225
+ return null
226
+ }
227
+
228
+ const discovered = modelsResult.value
229
+ let infoByName: Map<string, LiteLLMModelInfo> | null = null
230
+ if (infoResult.status === 'fulfilled') {
231
+ infoByName = infoResult.value
232
+ } else {
233
+ const reason = infoResult.reason
234
+ console.warn(
235
+ `[opencode-litellm] /v1/model/info unavailable for provider "${providerId}"; non-chat model filtering will use id heuristics only:`,
236
+ reason instanceof Error ? reason.message : String(reason),
237
+ )
238
+ }
239
+
240
+ if (discovered.length === 0) {
241
+ console.warn(
242
+ `[opencode-litellm] LiteLLM responded for provider "${providerId}" but exposed zero models.`,
243
+ )
244
+ return null
245
+ }
246
+
247
+ const built: Record<string, unknown> = {}
248
+ let skipped = 0
249
+ let wildcards = 0
250
+ const unmatched: string[] = []
251
+ for (const model of discovered) {
252
+ // Wildcard entries (`deepseek/*`) are access rules, not
253
+ // callable models — invoking one sends a literal `*` upstream.
254
+ if (model.id.includes('*')) {
255
+ wildcards++
256
+ continue
257
+ }
258
+ const info = infoByName?.get(model.id)
259
+ if (infoByName && !info) unmatched.push(model.id)
260
+ const entry = toConfigModel(info ? enrichModel(model, info) : model, info)
261
+ if (!entry) {
262
+ skipped++
263
+ continue
264
+ }
265
+ built[model.id] = entry
266
+ }
267
+
268
+ if (unmatched.length > 0) {
269
+ console.warn(
270
+ `[opencode-litellm] /v1/model/info has no entry for ${unmatched.length} model(s) on provider "${providerId}"; ` +
271
+ `classification uses id heuristics for: ${unmatched.slice(0, 5).join(', ')}` +
272
+ (unmatched.length > 5 ? `, +${unmatched.length - 5} more` : ''),
273
+ )
274
+ }
275
+
276
+ console.log(
277
+ `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
278
+ `(${Object.keys(built).length} built` +
279
+ (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
280
+ (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
281
+ ')',
282
+ )
283
+
284
+ return built
285
+ }
286
+
287
+ /**
288
+ * Merge freshly built model entries into a provider's `models` map
289
+ * without clobbering user-curated (or previously injected) entries.
290
+ * Returns the ids actually added by this call.
291
+ */
292
+ function mergeModels(
293
+ models: Record<string, unknown>,
294
+ built: Record<string, unknown>,
295
+ ): string[] {
296
+ const added: string[] = []
297
+ for (const [id, entry] of Object.entries(built)) {
298
+ if (Object.hasOwn(models, id)) continue
299
+ models[id] = entry
300
+ added.push(id)
301
+ }
302
+ // Remove the seed placeholder if real models were merged in.
303
+ if (Object.hasOwn(models, '_') && Object.keys(models).length > 1) {
304
+ delete models['_']
305
+ }
306
+ return added
307
+ }
308
+
309
+ /**
310
+ * Revalidate a baseURL's model cache off the critical path (SWR). The
311
+ * refreshed entries land in the on-disk cache and surface on the next
312
+ * OpenCode start — OpenCode only reads provider config at startup, so
313
+ * we can't mutate the live picker here.
314
+ */
315
+ async function backgroundRefresh(baseURL: string): Promise<void> {
316
+ if (refreshInFlight.has(baseURL)) return
317
+ const ctx = refreshContexts.get(baseURL)
318
+ if (!ctx) return
319
+ // Skip if the cache was refreshed recently — a burst of new sessions
320
+ // shouldn't hammer the proxy with health checks and discovery calls.
321
+ const savedAt = readModelCacheSavedAt(baseURL)
322
+ if (savedAt !== null && Date.now() - savedAt < REFRESH_MIN_INTERVAL_MS) {
323
+ return
324
+ }
325
+ refreshInFlight.add(baseURL)
326
+ try {
327
+ const built = await withTimeout(
328
+ discoverModels(baseURL, ctx.apiKey, ctx.customHeaders, ctx.providerId),
329
+ DISCOVERY_TIMEOUT_MS,
330
+ )
331
+ if (built && Object.keys(built).length > 0) {
332
+ writeModelCache(baseURL, built)
333
+ console.log(
334
+ `[opencode-litellm] Background-refreshed model cache for ${baseURL} (${Object.keys(built).length} models)`,
335
+ )
336
+ }
337
+ } catch {
338
+ // Best-effort — a failed refresh just leaves the stale cache in place.
339
+ } finally {
340
+ refreshInFlight.delete(baseURL)
341
+ }
342
+ }
343
+
154
344
  /**
155
345
  * LiteLLM Plugin for OpenCode.
156
346
  *
@@ -265,117 +455,54 @@ export const LiteLLMPlugin: Plugin = async (_input: PluginInput) => {
265
455
 
266
456
  const models = actualProvider.models as Record<string, unknown>
267
457
 
268
- // Discover models with timeout
269
- const work = async () => {
270
- const alreadyInjected = injectedModelIds.get(baseURL!)
271
- if (
272
- alreadyInjected &&
273
- [...alreadyInjected].every((id) => models[id])
274
- ) {
275
- return
276
- }
277
-
278
- if (!(await checkLiteLLMHealth(baseURL!, apiKey, customHeaders))) {
279
- console.warn(
280
- `[opencode-litellm] LiteLLM appears offline or unauthorized for provider "${providerId}" at ${baseURL}`,
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)))
458
+ // Remember how to reach this proxy so the `event` hook can
459
+ // revalidate its cache in the background on new sessions.
460
+ refreshContexts.set(baseURL, { apiKey, customHeaders, providerId })
461
+
462
+ // Repeat config-hook invocations within a run are a no-op once
463
+ // we've injected this baseURL's models.
464
+ const alreadyInjected = injectedModelIds.get(baseURL)
465
+ if (
466
+ alreadyInjected &&
467
+ [...alreadyInjected].every((id) => Object.hasOwn(models, id))
468
+ ) {
469
+ continue
470
+ }
363
471
 
472
+ // SWR fast path: serve cached entries synchronously so startup
473
+ // isn't blocked on the network. A background refresh (see the
474
+ // `event` hook) keeps the cache fresh for the next launch.
475
+ const cached = readModelCache(baseURL)
476
+ if (cached && Object.keys(cached).length > 0) {
477
+ const added = mergeModels(models, cached)
478
+ injectedModelIds.set(baseURL, new Set(added))
364
479
  console.log(
365
- `[opencode-litellm] Discovered ${discovered.length} models for provider "${providerId}" from ${baseURL} ` +
366
- `(${added} added` +
367
- (skipped > 0 ? `, ${skipped} non-chat hidden` : '') +
368
- (wildcards > 0 ? `, ${wildcards} wildcard ignored` : '') +
369
- ')',
480
+ `[opencode-litellm] Loaded ${Object.keys(cached).length} models from cache for provider "${providerId}" (${baseURL}); refresh happens in the background on new sessions.`,
370
481
  )
482
+ continue
371
483
  }
372
484
 
373
- await Promise.race([
374
- work(),
375
- new Promise<void>((resolve) =>
376
- setTimeout(resolve, DISCOVERY_TIMEOUT_MS),
377
- ),
378
- ])
485
+ // Cold cache: do a live fetch (slow first run only), inject, and
486
+ // persist for subsequent startups. Capped by a timeout so a slow
487
+ // proxy never blocks boot.
488
+ const built = await withTimeout(
489
+ discoverModels(baseURL, apiKey, customHeaders, providerId),
490
+ DISCOVERY_TIMEOUT_MS,
491
+ )
492
+ if (built && Object.keys(built).length > 0) {
493
+ const added = mergeModels(models, built)
494
+ injectedModelIds.set(baseURL, new Set(added))
495
+ writeModelCache(baseURL, built)
496
+ }
497
+ }
498
+ },
499
+ event: async ({ event }) => {
500
+ // Revalidate model caches off the critical path when a new session
501
+ // opens. Fresh data lands in the cache and surfaces on the next
502
+ // OpenCode start (SWR).
503
+ if (event.type !== 'session.created') return
504
+ for (const baseURL of refreshContexts.keys()) {
505
+ void backgroundRefresh(baseURL)
379
506
  }
380
507
  },
381
508
  }
@@ -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
+ }