opencode-plugin-litellm 1.2.0 → 1.4.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 +151 -89
- package/package.json +3 -2
- package/src/index.ts +1 -0
- package/src/plugin/index.ts +71 -28
- package/src/plugin/v2.ts +540 -0
- package/src/utils/litellm-api.ts +5 -3
- package/src/utils/model-cache.ts +15 -9
package/src/plugin/v2.ts
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
import { Model, Plugin, Provider } from '@opencode/plugin'
|
|
2
|
+
import type { Context } from '@opencode/plugin/promise/plugin'
|
|
3
|
+
import type { PluginInput } from '@opencode-ai/plugin'
|
|
4
|
+
import {
|
|
5
|
+
DISCOVERY_TIMEOUT_MS,
|
|
6
|
+
discoverModels,
|
|
7
|
+
initV2Logging,
|
|
8
|
+
isLiteLLMProvider,
|
|
9
|
+
readCustomHeaders,
|
|
10
|
+
readFormatModelNames,
|
|
11
|
+
readModelFilters,
|
|
12
|
+
withTimeout,
|
|
13
|
+
LiteLLMPlugin,
|
|
14
|
+
} from './index'
|
|
15
|
+
import {
|
|
16
|
+
buildCacheKey,
|
|
17
|
+
readModelCache,
|
|
18
|
+
readModelCacheSavedAt,
|
|
19
|
+
writeModelCache,
|
|
20
|
+
} from '../utils/model-cache'
|
|
21
|
+
import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
|
|
22
|
+
import { parseModelCapabilities } from '../utils/model-capabilities'
|
|
23
|
+
import type { ModelCapabilities } from '../utils/model-capabilities'
|
|
24
|
+
import type { ModelFilters } from '../utils/model-filter'
|
|
25
|
+
|
|
26
|
+
const CHAT_PROVIDER_ID = 'litellm'
|
|
27
|
+
const OPENAI_COMPATIBLE_PACKAGE = '@opencode/ai/providers/openai-compatible'
|
|
28
|
+
const REFRESH_MIN_INTERVAL_MS = 5 * 60 * 1000
|
|
29
|
+
|
|
30
|
+
type ProviderInfo = Awaited<ReturnType<Context['provider']['list']>>['data'][number]
|
|
31
|
+
|
|
32
|
+
interface ProviderSource {
|
|
33
|
+
id: string
|
|
34
|
+
name: string
|
|
35
|
+
activation: ProviderInfo['activation']
|
|
36
|
+
package: string
|
|
37
|
+
settings: Record<string, unknown>
|
|
38
|
+
headers: Record<string, string>
|
|
39
|
+
integrationID?: string
|
|
40
|
+
usesConnectionCredential: boolean
|
|
41
|
+
baseURL: string
|
|
42
|
+
apiKey?: string
|
|
43
|
+
customHeaders?: Record<string, string>
|
|
44
|
+
credentialReloadRequired: boolean
|
|
45
|
+
refreshRequired: boolean
|
|
46
|
+
filters: ModelFilters
|
|
47
|
+
capabilities: ModelCapabilities
|
|
48
|
+
formatModelNames: boolean
|
|
49
|
+
cacheKey: string
|
|
50
|
+
models: Model.Info[]
|
|
51
|
+
/**
|
|
52
|
+
* Model ids this plugin injected into the provider registry (as opposed
|
|
53
|
+
* to ids the user curated in config). Only these are eligible to be
|
|
54
|
+
* removed when a later refresh no longer discovers them.
|
|
55
|
+
*/
|
|
56
|
+
ownedModelIds: Set<string>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function asRecord(value: unknown): Record<string, unknown> {
|
|
60
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
61
|
+
? (value as Record<string, unknown>)
|
|
62
|
+
: {}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readHeaders(value: unknown): Record<string, string> {
|
|
66
|
+
const result: Record<string, string> = {}
|
|
67
|
+
for (const [key, header] of Object.entries(asRecord(value))) {
|
|
68
|
+
if (typeof header === 'string') result[key] = header
|
|
69
|
+
}
|
|
70
|
+
return result
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function readString(value: unknown): string | undefined {
|
|
74
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function numberOrZero(value: unknown): number {
|
|
78
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function toProviderModels(
|
|
82
|
+
providerID: string,
|
|
83
|
+
entries: Record<string, unknown>,
|
|
84
|
+
): Model.Info[] {
|
|
85
|
+
const provider = Provider.ID.make(providerID)
|
|
86
|
+
|
|
87
|
+
return Object.entries(entries).flatMap(([modelID, value]) => {
|
|
88
|
+
const entry = asRecord(value)
|
|
89
|
+
if (Object.keys(entry).length === 0) return []
|
|
90
|
+
|
|
91
|
+
const limit = asRecord(entry.limit)
|
|
92
|
+
const defaults = Model.Info.default(provider, Model.ID.make(modelID))
|
|
93
|
+
const modalities = asRecord(entry.modalities)
|
|
94
|
+
const input = Array.isArray(modalities.input)
|
|
95
|
+
? modalities.input.filter((item): item is string => typeof item === 'string')
|
|
96
|
+
: defaults.capabilities.input
|
|
97
|
+
const output = Array.isArray(modalities.output)
|
|
98
|
+
? modalities.output.filter((item): item is string => typeof item === 'string')
|
|
99
|
+
: defaults.capabilities.output
|
|
100
|
+
|
|
101
|
+
const rawCost = asRecord(entry.cost)
|
|
102
|
+
const cost: Model.Info['cost'] =
|
|
103
|
+
typeof rawCost.input === 'number' || typeof rawCost.output === 'number'
|
|
104
|
+
? [
|
|
105
|
+
{
|
|
106
|
+
input: numberOrZero(rawCost.input) as Model.Info['cost'][number]['input'],
|
|
107
|
+
output: numberOrZero(rawCost.output) as Model.Info['cost'][number]['output'],
|
|
108
|
+
cache: {
|
|
109
|
+
read: numberOrZero(rawCost.cache_read) as Model.Info['cost'][number]['cache']['read'],
|
|
110
|
+
write: numberOrZero(rawCost.cache_write) as Model.Info['cost'][number]['cache']['write'],
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
]
|
|
114
|
+
: []
|
|
115
|
+
|
|
116
|
+
const rawVariants = asRecord(entry.variants)
|
|
117
|
+
const variants = Object.entries(rawVariants).map(([id, settings]) => ({
|
|
118
|
+
id: id as Model.VariantID,
|
|
119
|
+
settings: asRecord(settings),
|
|
120
|
+
})) as Model.Info['variants']
|
|
121
|
+
return [
|
|
122
|
+
{
|
|
123
|
+
...defaults,
|
|
124
|
+
name: readString(entry.name) ?? modelID,
|
|
125
|
+
limit: {
|
|
126
|
+
context: numberOrDefault(limit.context, defaults.limit.context),
|
|
127
|
+
output: numberOrDefault(limit.output, defaults.limit.output),
|
|
128
|
+
},
|
|
129
|
+
capabilities: {
|
|
130
|
+
tools: entry.tool_call === undefined ? defaults.capabilities.tools : entry.tool_call === true,
|
|
131
|
+
input,
|
|
132
|
+
output,
|
|
133
|
+
},
|
|
134
|
+
cost,
|
|
135
|
+
variants,
|
|
136
|
+
},
|
|
137
|
+
]
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function numberOrDefault(value: unknown, fallback: number): number {
|
|
142
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
143
|
+
? value
|
|
144
|
+
: fallback
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Merge freshly discovered models into a provider's current model set.
|
|
149
|
+
*
|
|
150
|
+
* Previously-discovered ids owned by this plugin are replaced/removed so a
|
|
151
|
+
* refresh reflects LiteLLM's current inventory; ids the user curated
|
|
152
|
+
* themselves are never removed. Returns the merged list plus the set of
|
|
153
|
+
* ids the plugin now owns.
|
|
154
|
+
*/
|
|
155
|
+
function mergeProviderModels(
|
|
156
|
+
configured: Iterable<Model.Info>,
|
|
157
|
+
discovered: readonly Model.Info[],
|
|
158
|
+
owned: ReadonlySet<string>,
|
|
159
|
+
): { models: Model.Info[]; owned: Set<string> } {
|
|
160
|
+
const discoveredIds = new Set(discovered.map((model) => model.id))
|
|
161
|
+
const result = new Map<string, Model.Info>()
|
|
162
|
+
const nextOwned = new Set<string>()
|
|
163
|
+
|
|
164
|
+
for (const model of configured) {
|
|
165
|
+
// Drop plugin-injected models that LiteLLM no longer returns; curated
|
|
166
|
+
// models are not in `owned`, so they always survive.
|
|
167
|
+
if (owned.has(model.id) && !discoveredIds.has(model.id)) continue
|
|
168
|
+
result.set(model.id, model)
|
|
169
|
+
if (owned.has(model.id)) nextOwned.add(model.id)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
for (const model of discovered) {
|
|
173
|
+
if (!result.has(model.id)) {
|
|
174
|
+
result.set(model.id, model)
|
|
175
|
+
nextOwned.add(model.id)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { models: [...result.values()], owned: nextOwned }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function runtimeSettings(source: ProviderSource): Record<string, unknown> {
|
|
183
|
+
const settings = { ...source.settings }
|
|
184
|
+
for (const key of [
|
|
185
|
+
'litellm',
|
|
186
|
+
'litellmCompatible',
|
|
187
|
+
'litellm-compatible',
|
|
188
|
+
'litellm_compatible',
|
|
189
|
+
'customHeaders',
|
|
190
|
+
'includeModels',
|
|
191
|
+
'excludeModels',
|
|
192
|
+
'modelCapabilities',
|
|
193
|
+
'formatModelNames',
|
|
194
|
+
'providerID',
|
|
195
|
+
]) {
|
|
196
|
+
delete settings[key]
|
|
197
|
+
}
|
|
198
|
+
settings.baseURL = `${source.baseURL}/v1`
|
|
199
|
+
// Connection-managed credentials are resolved only for discovery. They
|
|
200
|
+
// must not be materialized into provider settings: OpenCode owns
|
|
201
|
+
// credential injection for integrated providers. Explicit credentials
|
|
202
|
+
// (provider settings, plugin options, env) still flow through.
|
|
203
|
+
if (source.apiKey && !source.usesConnectionCredential) settings.apiKey = source.apiKey
|
|
204
|
+
return settings
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function makeProviderSource(
|
|
208
|
+
context: Context,
|
|
209
|
+
provider: ProviderInfo | undefined,
|
|
210
|
+
pluginOptions: Record<string, unknown>,
|
|
211
|
+
): Promise<ProviderSource | null> {
|
|
212
|
+
const id = provider?.id ?? readString(pluginOptions.providerID) ?? CHAT_PROVIDER_ID
|
|
213
|
+
const providerSettings = asRecord(provider?.settings)
|
|
214
|
+
const settings = { ...pluginOptions, ...providerSettings }
|
|
215
|
+
const configuredBaseURL = readString(settings.baseURL)
|
|
216
|
+
const customHeaders = {
|
|
217
|
+
...readHeaders(pluginOptions.customHeaders),
|
|
218
|
+
...readCustomHeaders(settings),
|
|
219
|
+
...readHeaders(provider?.headers),
|
|
220
|
+
}
|
|
221
|
+
let connectedApiKey: string | undefined
|
|
222
|
+
if (provider?.integrationID) {
|
|
223
|
+
try {
|
|
224
|
+
const connection = await context.integration.connection.active(provider.integrationID)
|
|
225
|
+
const credential = connection
|
|
226
|
+
? await context.integration.connection.resolve(connection)
|
|
227
|
+
: undefined
|
|
228
|
+
if (credential?.type === 'key') connectedApiKey = credential.key
|
|
229
|
+
} catch {
|
|
230
|
+
// A missing or unrelated integration does not prevent other auth sources.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const configuredApiKey =
|
|
234
|
+
readString(providerSettings.apiKey) ??
|
|
235
|
+
readString(pluginOptions.apiKey) ??
|
|
236
|
+
process.env.LITELLM_API_KEY ??
|
|
237
|
+
process.env.LITELLM_MASTER_KEY
|
|
238
|
+
const usesConnectionCredential = !configuredApiKey && Boolean(provider?.integrationID)
|
|
239
|
+
const apiKey = configuredApiKey ?? connectedApiKey
|
|
240
|
+
const filters = readModelFilters(settings)
|
|
241
|
+
const capabilities = parseModelCapabilities(settings.modelCapabilities)
|
|
242
|
+
const formatModelNames = readFormatModelNames(settings)
|
|
243
|
+
const detectedBaseURL = configuredBaseURL
|
|
244
|
+
? normalizeBaseURL(configuredBaseURL)
|
|
245
|
+
: await autoDetectLiteLLM(apiKey, customHeaders)
|
|
246
|
+
|
|
247
|
+
if (!detectedBaseURL) {
|
|
248
|
+
return null
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const baseURL = normalizeBaseURL(detectedBaseURL)
|
|
252
|
+
const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
|
|
253
|
+
formatModelNames,
|
|
254
|
+
})
|
|
255
|
+
let entries = readModelCache(cacheKey)
|
|
256
|
+
|
|
257
|
+
if (!entries || Object.keys(entries).length === 0) {
|
|
258
|
+
entries = await withTimeout(
|
|
259
|
+
discoverModels(
|
|
260
|
+
baseURL,
|
|
261
|
+
apiKey,
|
|
262
|
+
customHeaders,
|
|
263
|
+
id,
|
|
264
|
+
filters,
|
|
265
|
+
capabilities,
|
|
266
|
+
formatModelNames,
|
|
267
|
+
),
|
|
268
|
+
DISCOVERY_TIMEOUT_MS,
|
|
269
|
+
)
|
|
270
|
+
if (entries && Object.keys(entries).length > 0) writeModelCache(cacheKey, entries)
|
|
271
|
+
} else {
|
|
272
|
+
logInfo(
|
|
273
|
+
`[opencode-litellm] Loaded ${Object.keys(entries).length} models from cache for provider "${id}" (${baseURL}); refresh happens in the background on new sessions.`,
|
|
274
|
+
)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return {
|
|
278
|
+
id,
|
|
279
|
+
name: provider?.name || 'LiteLLM (proxy)',
|
|
280
|
+
activation: provider?.activation ?? 'enabled',
|
|
281
|
+
package: provider?.package || OPENAI_COMPATIBLE_PACKAGE,
|
|
282
|
+
settings,
|
|
283
|
+
headers: customHeaders,
|
|
284
|
+
integrationID: provider?.integrationID,
|
|
285
|
+
usesConnectionCredential,
|
|
286
|
+
credentialReloadRequired: false,
|
|
287
|
+
refreshRequired: false,
|
|
288
|
+
baseURL,
|
|
289
|
+
apiKey,
|
|
290
|
+
customHeaders: Object.keys(customHeaders).length > 0 ? customHeaders : undefined,
|
|
291
|
+
filters,
|
|
292
|
+
capabilities,
|
|
293
|
+
formatModelNames,
|
|
294
|
+
cacheKey,
|
|
295
|
+
models: toProviderModels(id, entries ?? {}),
|
|
296
|
+
ownedModelIds: new Set<string>(),
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function logInfo(message: string): void {
|
|
301
|
+
console.log(message)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function refreshProviderSource(
|
|
305
|
+
context: Context,
|
|
306
|
+
source: ProviderSource,
|
|
307
|
+
inFlight: Map<string, Promise<void>>,
|
|
308
|
+
): Promise<void> {
|
|
309
|
+
const activeRefresh = inFlight.get(source.cacheKey)
|
|
310
|
+
if (activeRefresh) {
|
|
311
|
+
await activeRefresh
|
|
312
|
+
if (source.refreshRequired) await refreshProviderSource(context, source, inFlight)
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const savedAt = readModelCacheSavedAt(source.cacheKey)
|
|
317
|
+
if (
|
|
318
|
+
!source.refreshRequired &&
|
|
319
|
+
savedAt !== null &&
|
|
320
|
+
Date.now() - savedAt < REFRESH_MIN_INTERVAL_MS
|
|
321
|
+
) {
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const apiKey = source.apiKey
|
|
326
|
+
let refresh!: Promise<void>
|
|
327
|
+
refresh = (async () => {
|
|
328
|
+
try {
|
|
329
|
+
const entries = await withTimeout(
|
|
330
|
+
discoverModels(
|
|
331
|
+
source.baseURL,
|
|
332
|
+
apiKey,
|
|
333
|
+
source.customHeaders,
|
|
334
|
+
source.id,
|
|
335
|
+
source.filters,
|
|
336
|
+
source.capabilities,
|
|
337
|
+
source.formatModelNames,
|
|
338
|
+
),
|
|
339
|
+
DISCOVERY_TIMEOUT_MS,
|
|
340
|
+
)
|
|
341
|
+
if (!entries || Object.keys(entries).length === 0 || apiKey !== source.apiKey) return
|
|
342
|
+
|
|
343
|
+
const models = toProviderModels(source.id, entries)
|
|
344
|
+
if (JSON.stringify(models) === JSON.stringify(source.models)) {
|
|
345
|
+
writeModelCache(source.cacheKey, entries)
|
|
346
|
+
source.refreshRequired = false
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const previousModels = source.models
|
|
351
|
+
source.models = models
|
|
352
|
+
try {
|
|
353
|
+
await context.provider.reload()
|
|
354
|
+
} catch (error) {
|
|
355
|
+
source.models = previousModels
|
|
356
|
+
throw error
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
writeModelCache(source.cacheKey, entries)
|
|
360
|
+
source.refreshRequired = false
|
|
361
|
+
logInfo(
|
|
362
|
+
`[opencode-litellm] Refreshed ${models.length} models for provider "${source.id}"; the provider registry was reloaded.`,
|
|
363
|
+
)
|
|
364
|
+
} catch (error) {
|
|
365
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
366
|
+
logInfo(`[opencode-litellm] Background refresh failed for provider "${source.id}": ${message}`)
|
|
367
|
+
} finally {
|
|
368
|
+
if (inFlight.get(source.cacheKey) === refresh) inFlight.delete(source.cacheKey)
|
|
369
|
+
}
|
|
370
|
+
})()
|
|
371
|
+
inFlight.set(source.cacheKey, refresh)
|
|
372
|
+
await refresh
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function refreshConnectionCredential(
|
|
376
|
+
context: Context,
|
|
377
|
+
source: ProviderSource,
|
|
378
|
+
): Promise<boolean> {
|
|
379
|
+
if (!source.integrationID || !source.usesConnectionCredential) return false
|
|
380
|
+
|
|
381
|
+
try {
|
|
382
|
+
const connection = await context.integration.connection.active(source.integrationID)
|
|
383
|
+
const credential = connection
|
|
384
|
+
? await context.integration.connection.resolve(connection)
|
|
385
|
+
: undefined
|
|
386
|
+
const apiKey = credential?.type === 'key' ? credential.key : undefined
|
|
387
|
+
if (apiKey === source.apiKey) return false
|
|
388
|
+
source.apiKey = apiKey
|
|
389
|
+
return true
|
|
390
|
+
} catch (error) {
|
|
391
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
392
|
+
logInfo(`[opencode-litellm] Could not refresh credentials for provider "${source.id}": ${message}`)
|
|
393
|
+
return false
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function refreshProviderSources(
|
|
398
|
+
context: Context,
|
|
399
|
+
sources: ProviderSource[],
|
|
400
|
+
inFlight: Map<string, Promise<void>>,
|
|
401
|
+
): Promise<void> {
|
|
402
|
+
const pendingCredentialReload = sources.filter((source) => source.credentialReloadRequired)
|
|
403
|
+
if (pendingCredentialReload.length > 0) {
|
|
404
|
+
try {
|
|
405
|
+
await context.provider.reload()
|
|
406
|
+
for (const source of pendingCredentialReload) source.credentialReloadRequired = false
|
|
407
|
+
} catch (error) {
|
|
408
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
409
|
+
logInfo(`[opencode-litellm] Could not reload providers after a credential switch: ${message}`)
|
|
410
|
+
return
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
await Promise.all(sources.map((source) => refreshProviderSource(context, source, inFlight)))
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const definition = Plugin.define({
|
|
418
|
+
id: 'opencode-litellm',
|
|
419
|
+
async setup(context) {
|
|
420
|
+
initV2Logging()
|
|
421
|
+
|
|
422
|
+
const pluginOptions = asRecord(context.options)
|
|
423
|
+
let providers: ProviderInfo[] = []
|
|
424
|
+
try {
|
|
425
|
+
providers = (await context.provider.list()).data
|
|
426
|
+
} catch (error) {
|
|
427
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
428
|
+
logInfo(`[opencode-litellm] Could not read configured providers: ${message}`)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const matchingProviders = providers.filter((provider) =>
|
|
432
|
+
isLiteLLMProvider(provider.id, asRecord(provider.settings)),
|
|
433
|
+
)
|
|
434
|
+
const candidates: Array<ProviderInfo | undefined> = matchingProviders.length
|
|
435
|
+
? matchingProviders
|
|
436
|
+
: [undefined]
|
|
437
|
+
const sources: ProviderSource[] = []
|
|
438
|
+
|
|
439
|
+
for (const candidate of candidates) {
|
|
440
|
+
const source = await makeProviderSource(context, candidate, pluginOptions)
|
|
441
|
+
if (source) sources.push(source)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
if (sources.length === 0) {
|
|
445
|
+
logInfo(
|
|
446
|
+
'[opencode-litellm] No LiteLLM proxy found. Configure providers.litellm.settings.baseURL or start LiteLLM on port 4000/8000/8080.',
|
|
447
|
+
)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const providerRegistration = await context.provider.transform((editor) => {
|
|
451
|
+
for (const source of sources) {
|
|
452
|
+
const current = editor.get(source.id)
|
|
453
|
+
if (current) {
|
|
454
|
+
editor.update(source.id, (provider) => {
|
|
455
|
+
provider.package = source.package
|
|
456
|
+
provider.name = source.name
|
|
457
|
+
const settings = {
|
|
458
|
+
...(provider.settings ?? {}),
|
|
459
|
+
...runtimeSettings(source),
|
|
460
|
+
}
|
|
461
|
+
// Integration-managed credentials never belong in settings,
|
|
462
|
+
// even if a stale apiKey was materialized there previously.
|
|
463
|
+
if (source.usesConnectionCredential) delete settings.apiKey
|
|
464
|
+
provider.settings = settings
|
|
465
|
+
if (Object.keys(source.headers).length > 0) {
|
|
466
|
+
provider.headers = { ...provider.headers, ...source.headers }
|
|
467
|
+
}
|
|
468
|
+
})
|
|
469
|
+
const merged = mergeProviderModels(
|
|
470
|
+
current.models.values(),
|
|
471
|
+
source.models,
|
|
472
|
+
source.ownedModelIds,
|
|
473
|
+
)
|
|
474
|
+
source.ownedModelIds = merged.owned
|
|
475
|
+
editor.models.set(source.id, merged.models)
|
|
476
|
+
} else {
|
|
477
|
+
source.ownedModelIds = new Set(source.models.map((model) => model.id))
|
|
478
|
+
editor.add({
|
|
479
|
+
info: {
|
|
480
|
+
...Provider.Info.empty(Provider.ID.make(source.id)),
|
|
481
|
+
name: source.name,
|
|
482
|
+
activation: source.activation,
|
|
483
|
+
package: source.package,
|
|
484
|
+
settings: runtimeSettings(source),
|
|
485
|
+
headers: source.headers,
|
|
486
|
+
},
|
|
487
|
+
models: source.models,
|
|
488
|
+
})
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
})
|
|
492
|
+
|
|
493
|
+
const controller = new AbortController()
|
|
494
|
+
const inFlight = new Map<string, Promise<void>>()
|
|
495
|
+
void (async () => {
|
|
496
|
+
try {
|
|
497
|
+
for await (const event of context.event.subscribe({ signal: controller.signal })) {
|
|
498
|
+
if (event.type === 'credential.switched') {
|
|
499
|
+
const changedSources = (await Promise.all(
|
|
500
|
+
sources
|
|
501
|
+
.filter((source) => source.integrationID === event.data.integrationID)
|
|
502
|
+
.map(async (source) =>
|
|
503
|
+
(await refreshConnectionCredential(context, source)) ? source : undefined,
|
|
504
|
+
),
|
|
505
|
+
)).filter((source): source is ProviderSource => source !== undefined)
|
|
506
|
+
for (const source of changedSources) {
|
|
507
|
+
source.credentialReloadRequired = true
|
|
508
|
+
source.refreshRequired = true
|
|
509
|
+
}
|
|
510
|
+
if (changedSources.length > 0) {
|
|
511
|
+
await refreshProviderSources(context, changedSources, inFlight)
|
|
512
|
+
}
|
|
513
|
+
continue
|
|
514
|
+
}
|
|
515
|
+
if (event.type !== 'session.created') continue
|
|
516
|
+
void refreshProviderSources(context, sources, inFlight)
|
|
517
|
+
}
|
|
518
|
+
} catch (error) {
|
|
519
|
+
if (controller.signal.aborted) return
|
|
520
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
521
|
+
logInfo(`[opencode-litellm] Event subscription failed: ${message}`)
|
|
522
|
+
}
|
|
523
|
+
})()
|
|
524
|
+
|
|
525
|
+
return async () => {
|
|
526
|
+
controller.abort()
|
|
527
|
+
await providerRegistration.dispose()
|
|
528
|
+
}
|
|
529
|
+
},
|
|
530
|
+
})
|
|
531
|
+
|
|
532
|
+
export const LiteLLMPluginDefinition = {
|
|
533
|
+
...definition,
|
|
534
|
+
// OpenCode 1.18.29+ accepts object-form plugin exports with a server().
|
|
535
|
+
async server(input: PluginInput) {
|
|
536
|
+
return LiteLLMPlugin(input)
|
|
537
|
+
},
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export default LiteLLMPluginDefinition
|
package/src/utils/litellm-api.ts
CHANGED
|
@@ -172,11 +172,13 @@ export async function discoverLiteLLMModelInfo(
|
|
|
172
172
|
}
|
|
173
173
|
|
|
174
174
|
/**
|
|
175
|
-
*
|
|
176
|
-
* The default `litellm --port` is 4000,
|
|
177
|
-
* and 8080 is a common reverse-proxy default.
|
|
175
|
+
* Use an explicit LITELLM_BASE_URL when set; otherwise try the most common
|
|
176
|
+
* ports. The default `litellm --port` is 4000, with 8000 and 8080 also common.
|
|
178
177
|
*/
|
|
179
178
|
export async function autoDetectLiteLLM(apiKey?: string, customHeaders?: Record<string, string>): Promise<string | null> {
|
|
179
|
+
const configuredBaseURL = process.env.LITELLM_BASE_URL?.trim()
|
|
180
|
+
if (configuredBaseURL) return normalizeBaseURL(configuredBaseURL)
|
|
181
|
+
|
|
180
182
|
const commonPorts = [4000, 8000, 8080]
|
|
181
183
|
for (const port of commonPorts) {
|
|
182
184
|
const baseURL = `http://localhost:${port}`
|
package/src/utils/model-cache.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { join } from 'node:path'
|
|
|
8
8
|
* from older plugin versions are ignored rather than deserialized into
|
|
9
9
|
* an incompatible structure.
|
|
10
10
|
*/
|
|
11
|
-
const CACHE_VERSION =
|
|
11
|
+
const CACHE_VERSION = 2
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
14
|
* Maximum age of a cache entry before it's treated as a miss. Without a
|
|
@@ -65,25 +65,28 @@ function canonicalize(value: unknown): string {
|
|
|
65
65
|
|
|
66
66
|
/**
|
|
67
67
|
* Cache identity for a provider's model view. `providerId@baseURL`
|
|
68
|
-
* alone isn't enough: `includeModels`/`excludeModels
|
|
69
|
-
* `modelCapabilities` are baked into cached
|
|
70
|
-
* config change must not reuse the old cache
|
|
71
|
-
* the previous adjusted view until a second
|
|
72
|
-
* appended whenever adjustments exist
|
|
73
|
-
* configs keep the plain key so
|
|
74
|
-
* plugin upgrades.
|
|
68
|
+
* alone isn't enough: `includeModels`/`excludeModels`,
|
|
69
|
+
* `modelCapabilities` and `formatModelNames` are baked into cached
|
|
70
|
+
* entries by discovery, so a config change must not reuse the old cache
|
|
71
|
+
* — it would keep serving the previous adjusted view until a second
|
|
72
|
+
* restart. A fingerprint is appended whenever adjustments exist
|
|
73
|
+
* (pattern order ignored); default configs keep the plain key so
|
|
74
|
+
* existing caches stay warm across plugin upgrades.
|
|
75
75
|
*/
|
|
76
76
|
export function buildCacheKey(
|
|
77
77
|
providerId: string,
|
|
78
78
|
baseURL: string,
|
|
79
79
|
filters: { includeModels?: string[]; excludeModels?: string[] },
|
|
80
80
|
capabilities: Record<string, Record<string, boolean>>,
|
|
81
|
+
naming: { formatModelNames?: boolean } = {},
|
|
81
82
|
): string {
|
|
82
83
|
const base = `${providerId}@${baseURL}`
|
|
84
|
+
const rawNames = naming.formatModelNames === false
|
|
83
85
|
const hasAdjustments =
|
|
84
86
|
(filters.includeModels?.length ?? 0) > 0 ||
|
|
85
87
|
(filters.excludeModels?.length ?? 0) > 0 ||
|
|
86
|
-
Object.keys(capabilities).length > 0
|
|
88
|
+
Object.keys(capabilities).length > 0 ||
|
|
89
|
+
rawNames
|
|
87
90
|
if (!hasAdjustments) return base
|
|
88
91
|
const fingerprint = createHash('sha256')
|
|
89
92
|
.update(
|
|
@@ -91,6 +94,9 @@ export function buildCacheKey(
|
|
|
91
94
|
includeModels: filters.includeModels ? [...filters.includeModels].sort() : undefined,
|
|
92
95
|
excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
|
|
93
96
|
capabilities,
|
|
97
|
+
// Omitted (not `true`) when formatting is on, so keys for
|
|
98
|
+
// configs that never touch this option are unchanged.
|
|
99
|
+
formatModelNames: rawNames ? false : undefined,
|
|
94
100
|
}),
|
|
95
101
|
)
|
|
96
102
|
.digest('hex')
|