opencode-plugin-litellm 1.6.0 → 1.7.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 +39 -4
- package/package.json +2 -3
- package/src/plugin/index.ts +4 -1
- package/src/plugin/integration.ts +122 -0
- package/src/plugin/v2.ts +178 -21
- package/src/types/index.ts +2 -0
- package/src/utils/model-cache.ts +17 -5
package/README.md
CHANGED
|
@@ -78,7 +78,7 @@ also shows how to configure a provider directly in `opencode.json`.
|
|
|
78
78
|
| 💵 **Real pricing** | Maps `input_cost_per_token` / `output_cost_per_token` (and cache read/write costs) from `/v1/model/info` into OpenCode's `cost` field, so the picker and `/cost` show what the proxy actually bills instead of `$0.00`. Models LiteLLM has no price for are left unpriced, not falsely marked free. |
|
|
79
79
|
| 🧩 **Reasoning-effort variants** | When LiteLLM reports per-model effort support (`supports_low_reasoning_effort`, …), the plugin surfaces each level as a picker variant automatically. |
|
|
80
80
|
| 🧭 **Responses-API routing** | Models LiteLLM reports with `mode: "responses"` are invoked through `/v1/responses` instead of `/v1/chat/completions`, with no extra configuration. OpenCode 2 overrides the runtime package per model; OpenCode 1 gets a `<provider>-responses` sibling. |
|
|
81
|
-
| 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, `providers.litellm.settings.apiKey`,
|
|
81
|
+
| 🔐 **Auth-aware** | Honours `LITELLM_API_KEY` / `LITELLM_MASTER_KEY`, `providers.litellm.settings.apiKey`, OpenCode `/connect` credentials, and (OpenCode 2) a **LiteLLM** entry in the connect-provider dialog — key plus optional base URL, entered entirely from the web UI. |
|
|
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. |
|
|
@@ -245,6 +245,31 @@ between effort levels from the model picker without hand-curating every entry.
|
|
|
245
245
|
> `mode: "responses"` the plugin routes it to `/v1/responses` automatically;
|
|
246
246
|
> otherwise reach it without `reasoningEffort`. See the FAQ entry below.
|
|
247
247
|
|
|
248
|
+
On OpenCode 2, models whose effective package is `@opencode/ai/providers/anthropic`
|
|
249
|
+
or `@opencode/ai/providers/anthropic-compatible` get the same levels in the
|
|
250
|
+
shape that runtime reads, `{ thinking: { type: "adaptive", display: "summarized" }, effort }`,
|
|
251
|
+
for models LiteLLM reports with `supports_adaptive_thinking`, with `none`
|
|
252
|
+
becoming `thinking: { type: "disabled" }` (dropped when `thinking_always_on`).
|
|
253
|
+
Models without adaptive thinking get no variants on those packages, since
|
|
254
|
+
`reasoningEffort` would be ignored there. To reach Claude over the proxy's
|
|
255
|
+
`/v1/messages` while the rest of the catalog keeps its usual transport, split it
|
|
256
|
+
with [`includeModels`/`excludeModels`](#splitting-one-proxy-into-multiple-providers-includemodels--excludemodels):
|
|
257
|
+
|
|
258
|
+
```jsonc
|
|
259
|
+
{
|
|
260
|
+
"providers": {
|
|
261
|
+
"litellm": {
|
|
262
|
+
"package": "@opencode/ai/providers/openai-compatible",
|
|
263
|
+
"settings": { "baseURL": "http://localhost:4000/v1", "excludeModels": ["*claude*"] }
|
|
264
|
+
},
|
|
265
|
+
"litellm-claude": {
|
|
266
|
+
"package": "@opencode/ai/providers/anthropic-compatible",
|
|
267
|
+
"settings": { "baseURL": "http://localhost:4000/v1", "includeModels": ["*claude*"] }
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
```
|
|
272
|
+
|
|
248
273
|
### Responses API models
|
|
249
274
|
|
|
250
275
|
LiteLLM reports `mode` per model on `/v1/model/info` (the plugin fetches it
|
|
@@ -297,17 +322,27 @@ Selecting a Responses model on OpenCode 1 therefore means picking
|
|
|
297
322
|
|
|
298
323
|
### Authentication
|
|
299
324
|
|
|
300
|
-
If your LiteLLM proxy requires a master key, expose it via
|
|
325
|
+
If your LiteLLM proxy requires a master key, expose it via any of these approaches:
|
|
301
326
|
|
|
302
327
|
| Method | Example |
|
|
303
328
|
|---|---|
|
|
329
|
+
| Web UI / `/connect` | Run `/connect` (or use the Desktop providers view), pick **LiteLLM**, paste the key, and optionally fill in the base URL and provider id |
|
|
304
330
|
| Env var (base URL) | `LITELLM_BASE_URL=https://litellm.internal.example.com/v1` |
|
|
305
331
|
| Env var | `export LITELLM_API_KEY=sk-...` |
|
|
306
332
|
| Env var (alias) | `export LITELLM_MASTER_KEY=sk-...` |
|
|
307
333
|
| Config | `"settings": { "apiKey": "{env:LITELLM_API_KEY}" }` |
|
|
308
|
-
| OpenCode `/connect` | Run `/connect`, search for your `litellm` provider entry, and paste the key |
|
|
309
334
|
|
|
310
|
-
The env var path lets you commit `opencode.json` without leaking secrets. On OpenCode 1, `/connect` credentials are read from OpenCode's auth store (`~/.local/share/opencode/auth.json`) and applied to health checks, model discovery, and completion-time requests. OpenCode 2 users can use `settings.apiKey` with an environment substitution or set `LITELLM_API_KEY` on the background service as shown in the Quickstart.
|
|
335
|
+
The env var path lets you commit `opencode.json` without leaking secrets. On OpenCode 1, `/connect` credentials are read from OpenCode's auth store (`~/.local/share/opencode/auth.json`) and applied to health checks, model discovery, and completion-time requests. On OpenCode 2, a credential saved through `/connect` is a first-class integration connection: the plugin registers the **LiteLLM** integration with an API-key form, uses the stored key for discovery, and lets OpenCode inject it into completion requests — the key never appears in `opencode.json` or provider settings. OpenCode 2 users can still use `settings.apiKey` with an environment substitution or set `LITELLM_API_KEY` on the background service as shown in the Quickstart.
|
|
336
|
+
|
|
337
|
+
#### Web UI connect (OpenCode 2)
|
|
338
|
+
|
|
339
|
+
With no configuration at all, `/connect` → **LiteLLM** is enough:
|
|
340
|
+
|
|
341
|
+
1. Enter the API key when prompted.
|
|
342
|
+
2. Optionally fill the form: **Base URL** (e.g. `https://llm.example.com/v1`) and **Provider ID** (defaults to `litellm`; pick a different id when your config already defines a `litellm` provider, so the connected gateway gets its own entry). Reconnecting with a different id moves the gateway to that provider.
|
|
343
|
+
3. Models appear in the picker without editing `opencode.json` or restarting.
|
|
344
|
+
|
|
345
|
+
Precedence when several sources are configured: explicit provider/plugin settings always win. For the key, the environment (`LITELLM_API_KEY`/`LITELLM_MASTER_KEY`) is consulted before the dialog credential; for the base URL, the dialog answer beats `LITELLM_BASE_URL` and local port auto-detection. A provider defined in `opencode.json` (without its own key) picks the saved credential up on the next start, while providers created from the dialog update immediately — reconnecting re-points them in place, including a changed base URL or provider id.
|
|
311
346
|
|
|
312
347
|
### Slow proxies (`LITELLM_REQUEST_TIMEOUT_MS`)
|
|
313
348
|
|
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.7.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",
|
|
@@ -14,8 +14,7 @@
|
|
|
14
14
|
"scripts": {
|
|
15
15
|
"typecheck": "tsc --noEmit",
|
|
16
16
|
"test": "vitest run",
|
|
17
|
-
"
|
|
18
|
-
"prepublishOnly": "npm run build"
|
|
17
|
+
"prepublishOnly": "npm run typecheck"
|
|
19
18
|
},
|
|
20
19
|
"keywords": [
|
|
21
20
|
"opencode",
|
package/src/plugin/index.ts
CHANGED
|
@@ -333,7 +333,8 @@ export function toConfigModel(
|
|
|
333
333
|
* config (or translated into `Model.Info` on OpenCode 2). `responsesIds`
|
|
334
334
|
* lists the subset that must be invoked through the OpenAI Responses API;
|
|
335
335
|
* callers route those accordingly without inspecting each entry. `hints`
|
|
336
|
-
* carries per-model upstream facts OpenCode 2 maps to `compatibility
|
|
336
|
+
* carries per-model upstream facts OpenCode 2 maps to `compatibility` and
|
|
337
|
+
* `variants`.
|
|
337
338
|
*/
|
|
338
339
|
export interface DiscoveredModels {
|
|
339
340
|
models: Record<string, unknown>
|
|
@@ -447,6 +448,8 @@ export async function discoverModels(
|
|
|
447
448
|
const params = info?.supported_openai_params
|
|
448
449
|
hints[model.id] = {
|
|
449
450
|
acceptsCacheControl: Array.isArray(params) && params.includes('cache_control'),
|
|
451
|
+
adaptiveThinking: info?.supports_adaptive_thinking === true,
|
|
452
|
+
thinkingAlwaysOn: info?.thinking_always_on === true,
|
|
450
453
|
}
|
|
451
454
|
}
|
|
452
455
|
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { Context } from '@opencode/plugin/promise/plugin'
|
|
2
|
+
|
|
3
|
+
// OpenCode 2 exposes no log API through the plugin context (see
|
|
4
|
+
// initV2Logging); the host captures console output into its log files, so a
|
|
5
|
+
// plain console write with the `[opencode-litellm]` prefix is the house
|
|
6
|
+
// pattern for V2 modules (same as logInfo in plugin/v2.ts).
|
|
7
|
+
function logInfo(message: string): void {
|
|
8
|
+
console.log(message)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Integration id the plugin registers with OpenCode's connect-provider dialog.
|
|
13
|
+
*
|
|
14
|
+
* Deliberately identical to the default provider id (`CHAT_PROVIDER_ID` in
|
|
15
|
+
* `plugin/v2.ts`) so a credential saved through `/connect` lines up with the
|
|
16
|
+
* `litellm` provider without extra wiring; providers registered under other
|
|
17
|
+
* ids still resolve the same credential because the plugin stamps
|
|
18
|
+
* `info.integrationID` on them.
|
|
19
|
+
*/
|
|
20
|
+
export const LITELLM_INTEGRATION_ID = 'litellm'
|
|
21
|
+
|
|
22
|
+
/** A credential saved through the connect dialog, with its form answers. */
|
|
23
|
+
export interface ConnectedLiteLLM {
|
|
24
|
+
/** Key resolved from the active connection's credential. */
|
|
25
|
+
apiKey: string | undefined
|
|
26
|
+
/** Base URL typed into the dialog's form, when present. */
|
|
27
|
+
baseURL: string | undefined
|
|
28
|
+
/** Provider id typed into the dialog's form, when present. */
|
|
29
|
+
providerID: string | undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function readAnswer(
|
|
33
|
+
configuration: Record<string, unknown> | undefined,
|
|
34
|
+
key: string,
|
|
35
|
+
): string | undefined {
|
|
36
|
+
const value = configuration?.[key]
|
|
37
|
+
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Registers the LiteLLM integration so gateways can be connected from the
|
|
42
|
+
* web UI instead of hand-edited config: the dialog collects the API key as a
|
|
43
|
+
* credential plus a small form for the proxy base URL and an optional
|
|
44
|
+
* provider id.
|
|
45
|
+
*
|
|
46
|
+
* Returns the transform registration, or undefined when the host has no
|
|
47
|
+
* integration API (OpenCode 1.18.x's embedded v2 host) or registration
|
|
48
|
+
* fails — model discovery must keep working without the dialog entry.
|
|
49
|
+
*/
|
|
50
|
+
export async function registerLiteLLMIntegration(
|
|
51
|
+
context: Context,
|
|
52
|
+
): Promise<{ dispose(): Promise<void> } | undefined> {
|
|
53
|
+
if (!context.integration?.transform) return undefined
|
|
54
|
+
try {
|
|
55
|
+
return await context.integration.transform((editor) => {
|
|
56
|
+
editor.update(LITELLM_INTEGRATION_ID, (integration) => {
|
|
57
|
+
integration.name = 'LiteLLM'
|
|
58
|
+
})
|
|
59
|
+
editor.method.update({
|
|
60
|
+
integrationID: LITELLM_INTEGRATION_ID,
|
|
61
|
+
method: {
|
|
62
|
+
type: 'key',
|
|
63
|
+
label: 'API Key',
|
|
64
|
+
form: [
|
|
65
|
+
{
|
|
66
|
+
key: 'baseURL',
|
|
67
|
+
type: 'string',
|
|
68
|
+
format: 'uri',
|
|
69
|
+
title: 'Base URL',
|
|
70
|
+
description:
|
|
71
|
+
'Where the LiteLLM proxy runs, including the /v1 suffix. Leave empty to use LITELLM_BASE_URL or auto-detect a local proxy.',
|
|
72
|
+
placeholder: 'https://llm.example.com/v1',
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
key: 'providerID',
|
|
76
|
+
type: 'string',
|
|
77
|
+
title: 'Provider ID',
|
|
78
|
+
description:
|
|
79
|
+
'Provider the discovered models appear under. Pick a different id when your config already defines a "litellm" provider, so the connected gateway gets its own entry. Reconnecting with a different id moves the gateway there.',
|
|
80
|
+
default: LITELLM_INTEGRATION_ID,
|
|
81
|
+
},
|
|
82
|
+
],
|
|
83
|
+
},
|
|
84
|
+
})
|
|
85
|
+
})
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
88
|
+
logInfo(`[opencode-litellm] Could not register the connect dialog integration: ${message}`)
|
|
89
|
+
return undefined
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Resolves the active credential for an integration into the values the
|
|
95
|
+
* plugin needs: the API key plus the dialog's form answers.
|
|
96
|
+
*
|
|
97
|
+
* Returns undefined when the integration has no connection, the credential
|
|
98
|
+
* is not a key, or the host lacks the connection API. Errors are swallowed
|
|
99
|
+
* on purpose — a missing or unrelated integration must never prevent other
|
|
100
|
+
* auth sources from working.
|
|
101
|
+
*/
|
|
102
|
+
export async function readConnectedConfig(
|
|
103
|
+
context: Context,
|
|
104
|
+
integrationID: string,
|
|
105
|
+
): Promise<ConnectedLiteLLM | undefined> {
|
|
106
|
+
const connection = context.integration?.connection
|
|
107
|
+
if (!connection) return undefined
|
|
108
|
+
try {
|
|
109
|
+
const active = await connection.active(integrationID)
|
|
110
|
+
if (!active) return undefined
|
|
111
|
+
const credential = await connection.resolve(active)
|
|
112
|
+
if (!credential || credential.type !== 'key') return undefined
|
|
113
|
+
const configuration = credential.configuration as Record<string, unknown> | undefined
|
|
114
|
+
return {
|
|
115
|
+
apiKey: credential.key,
|
|
116
|
+
baseURL: readAnswer(configuration, 'baseURL'),
|
|
117
|
+
providerID: readAnswer(configuration, 'providerID'),
|
|
118
|
+
}
|
|
119
|
+
} catch {
|
|
120
|
+
return undefined
|
|
121
|
+
}
|
|
122
|
+
}
|
package/src/plugin/v2.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Model, Plugin, Provider } from '@opencode/plugin'
|
|
1
|
+
import { Integration, Model, Plugin, Provider } from '@opencode/plugin'
|
|
2
2
|
import type { Context } from '@opencode/plugin/promise/plugin'
|
|
3
3
|
import type { PluginInput } from '@opencode-ai/plugin'
|
|
4
4
|
import {
|
|
@@ -12,6 +12,12 @@ import {
|
|
|
12
12
|
withTimeout,
|
|
13
13
|
LiteLLMPlugin,
|
|
14
14
|
} from './index'
|
|
15
|
+
import {
|
|
16
|
+
LITELLM_INTEGRATION_ID,
|
|
17
|
+
readConnectedConfig,
|
|
18
|
+
registerLiteLLMIntegration,
|
|
19
|
+
type ConnectedLiteLLM,
|
|
20
|
+
} from './integration'
|
|
15
21
|
import {
|
|
16
22
|
buildCacheKey,
|
|
17
23
|
readModelCacheEntry,
|
|
@@ -39,6 +45,11 @@ const CHAT_COMPLETIONS_PACKAGES = new Set([
|
|
|
39
45
|
OPENAI_COMPATIBLE_PACKAGE,
|
|
40
46
|
'@opencode/ai/providers/openai/chat',
|
|
41
47
|
])
|
|
48
|
+
const ANTHROPIC_PACKAGES = new Set([
|
|
49
|
+
'@opencode/ai/providers/anthropic',
|
|
50
|
+
'@opencode/ai/providers/anthropic-compatible',
|
|
51
|
+
])
|
|
52
|
+
const ADAPTIVE_THINKING = { type: 'adaptive', display: 'summarized' }
|
|
42
53
|
// Runtime package that talks to `/v1/responses`. OpenCode 2 lets one model
|
|
43
54
|
// override the provider's package, so Responses models stay under their
|
|
44
55
|
// original provider id and no sibling provider is needed here.
|
|
@@ -126,6 +137,29 @@ function numberOrZero(value: unknown): number {
|
|
|
126
137
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
127
138
|
}
|
|
128
139
|
|
|
140
|
+
/**
|
|
141
|
+
* Discovery spells every effort level as `{ reasoningEffort }`, which the
|
|
142
|
+
* OpenAI runtimes read. The Anthropic runtimes read `thinking` and `effort`
|
|
143
|
+
* instead, so on those packages the levels are respelled the way OpenCode's
|
|
144
|
+
* own catalog does for adaptive-thinking Claude models. A model that does
|
|
145
|
+
* not report adaptive thinking gets no variants rather than inert ones.
|
|
146
|
+
*/
|
|
147
|
+
function anthropicVariants(
|
|
148
|
+
variants: Model.Info['variants'],
|
|
149
|
+
hints: ModelHints | undefined,
|
|
150
|
+
): Model.Info['variants'] {
|
|
151
|
+
if (!hints?.adaptiveThinking) return []
|
|
152
|
+
return variants.flatMap((variant) => {
|
|
153
|
+
const effort = variant.settings?.reasoningEffort
|
|
154
|
+
if (typeof effort !== 'string') return []
|
|
155
|
+
if (effort === 'none') {
|
|
156
|
+
if (hints.thinkingAlwaysOn) return []
|
|
157
|
+
return [{ ...variant, settings: { thinking: { type: 'disabled' } } }]
|
|
158
|
+
}
|
|
159
|
+
return [{ ...variant, settings: { thinking: ADAPTIVE_THINKING, effort } }]
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
129
163
|
interface ToProviderModelsOptions {
|
|
130
164
|
/** The provider's runtime package; models not overridden inherit it. */
|
|
131
165
|
providerPackage: string
|
|
@@ -172,11 +206,14 @@ function toProviderModels(
|
|
|
172
206
|
: []
|
|
173
207
|
|
|
174
208
|
const rawVariants = asRecord(entry.variants)
|
|
175
|
-
const
|
|
209
|
+
const openAIVariants = Object.entries(rawVariants).map(([id, settings]) => ({
|
|
176
210
|
id: id as Model.VariantID,
|
|
177
211
|
settings: asRecord(settings),
|
|
178
212
|
})) as Model.Info['variants']
|
|
179
213
|
const pkg = responsesIds.has(modelID) ? RESPONSES_PACKAGE : options.providerPackage
|
|
214
|
+
const variants = ANTHROPIC_PACKAGES.has(pkg)
|
|
215
|
+
? anthropicVariants(openAIVariants, hints[modelID])
|
|
216
|
+
: openAIVariants
|
|
180
217
|
const compatibility = resolveCompatibility(
|
|
181
218
|
inferCompatibility(hints[modelID], CHAT_COMPLETIONS_PACKAGES.has(pkg)),
|
|
182
219
|
Object.hasOwn(overrides, modelID) ? overrides[modelID] : undefined,
|
|
@@ -282,41 +319,53 @@ async function makeProviderSource(
|
|
|
282
319
|
provider: ProviderInfo | undefined,
|
|
283
320
|
pluginOptions: Record<string, unknown>,
|
|
284
321
|
): Promise<ProviderSource | null> {
|
|
285
|
-
const id = provider?.id ?? readString(pluginOptions.providerID) ?? CHAT_PROVIDER_ID
|
|
286
322
|
const providerSettings = asRecord(provider?.settings)
|
|
287
323
|
const settings = { ...pluginOptions, ...providerSettings }
|
|
288
|
-
const configuredBaseURL = readString(settings.baseURL)
|
|
289
324
|
const customHeaders = {
|
|
290
325
|
...readHeaders(pluginOptions.customHeaders),
|
|
291
326
|
...readCustomHeaders(settings),
|
|
292
327
|
...readHeaders(provider?.headers),
|
|
293
328
|
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
329
|
+
// Credential plus dialog form answers. A provider wired to its own
|
|
330
|
+
// integration keeps using exactly that one; otherwise the plugin's
|
|
331
|
+
// registered integration is consulted, so a gateway can be connected
|
|
332
|
+
// entirely from the web UI with no hand-written config.
|
|
333
|
+
const connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
|
|
334
|
+
context,
|
|
335
|
+
provider?.integrationID ?? LITELLM_INTEGRATION_ID,
|
|
336
|
+
)
|
|
337
|
+
const id =
|
|
338
|
+
provider?.id ??
|
|
339
|
+
readString(pluginOptions.providerID) ??
|
|
340
|
+
connected?.providerID ??
|
|
341
|
+
CHAT_PROVIDER_ID
|
|
342
|
+
const configuredBaseURL = readString(settings.baseURL)
|
|
343
|
+
const connectedApiKey = connected?.apiKey
|
|
306
344
|
const configuredApiKey =
|
|
307
345
|
readString(providerSettings.apiKey) ??
|
|
308
346
|
readString(pluginOptions.apiKey) ??
|
|
309
347
|
process.env.LITELLM_API_KEY ??
|
|
310
348
|
process.env.LITELLM_MASTER_KEY
|
|
311
|
-
|
|
349
|
+
// A provider bound to an integration relies on OpenCode for its credential
|
|
350
|
+
// even before one is connected. The plugin's own integration only counts
|
|
351
|
+
// once it actually resolved a key, so env/config setups are unaffected.
|
|
352
|
+
const usesConnectionCredential =
|
|
353
|
+
!configuredApiKey && Boolean(provider?.integrationID ?? connectedApiKey)
|
|
354
|
+
const integrationID =
|
|
355
|
+
provider?.integrationID ??
|
|
356
|
+
(usesConnectionCredential && connectedApiKey ? LITELLM_INTEGRATION_ID : undefined)
|
|
312
357
|
const apiKey = configuredApiKey ?? connectedApiKey
|
|
313
358
|
const filters = readModelFilters(settings)
|
|
314
359
|
const capabilities = parseModelCapabilities(settings.modelCapabilities)
|
|
315
360
|
const compatibility = parseModelCompatibility(settings.modelCompatibility)
|
|
316
361
|
const formatModelNames = readFormatModelNames(settings)
|
|
362
|
+
// Explicit config beats the URL typed into the dialog, which beats the
|
|
363
|
+
// environment and local port probing.
|
|
317
364
|
const detectedBaseURL = configuredBaseURL
|
|
318
365
|
? normalizeBaseURL(configuredBaseURL)
|
|
319
|
-
:
|
|
366
|
+
: connected?.baseURL
|
|
367
|
+
? normalizeBaseURL(connected.baseURL)
|
|
368
|
+
: await autoDetectLiteLLM(apiKey, customHeaders)
|
|
320
369
|
|
|
321
370
|
if (!detectedBaseURL) {
|
|
322
371
|
return null
|
|
@@ -368,7 +417,7 @@ async function makeProviderSource(
|
|
|
368
417
|
package: providerPackage,
|
|
369
418
|
settings,
|
|
370
419
|
headers: customHeaders,
|
|
371
|
-
integrationID
|
|
420
|
+
integrationID,
|
|
372
421
|
usesConnectionCredential,
|
|
373
422
|
credentialReloadRequired: false,
|
|
374
423
|
refreshRequired: false,
|
|
@@ -571,6 +620,62 @@ async function reconcileProviderSources(
|
|
|
571
620
|
return changed
|
|
572
621
|
}
|
|
573
622
|
|
|
623
|
+
/**
|
|
624
|
+
* Build and publish a source from the dialog's active credential.
|
|
625
|
+
*
|
|
626
|
+
* Called for the first connect with nothing bound yet, and to rebuild
|
|
627
|
+
* dialog-built sources after a credential switch — a reconnect may move the
|
|
628
|
+
* gateway to a new base URL or provider id, so those sources are re-derived
|
|
629
|
+
* wholesale instead of key-refreshed.
|
|
630
|
+
*
|
|
631
|
+
* An existing source for the same id is left untouched unless it is a pure
|
|
632
|
+
* auto-detection/dialog-built fallback (no explicit baseURL in
|
|
633
|
+
* options/config): a fallback only stands in until a real endpoint is
|
|
634
|
+
* known, so the dialog's answers take over from it. Explicit option/env
|
|
635
|
+
* baseURLs — and host-registered providers — keep winning and are never
|
|
636
|
+
* replaced. Replaced sources' owned model ids carry over so models the
|
|
637
|
+
* gateway no longer serves are dropped on the next merge, and sources
|
|
638
|
+
* replaced under a different id are dropped from `sources` and marked in
|
|
639
|
+
* `staleProviderIds` for removal from the provider registry.
|
|
640
|
+
*/
|
|
641
|
+
async function publishConnectedSource(
|
|
642
|
+
context: Context,
|
|
643
|
+
pluginOptions: Record<string, unknown>,
|
|
644
|
+
sources: Map<string, ProviderSource>,
|
|
645
|
+
staleProviderIds: Set<string>,
|
|
646
|
+
replacing: ProviderSource[] = [],
|
|
647
|
+
): Promise<void> {
|
|
648
|
+
try {
|
|
649
|
+
const source = await makeProviderSource(context, undefined, pluginOptions)
|
|
650
|
+
if (!source) return
|
|
651
|
+
const existing = sources.get(source.id)
|
|
652
|
+
if (existing && !(existing.fromFallback && !readString(existing.settings.baseURL))) return
|
|
653
|
+
const previous = existing ?? replacing.find((candidate) => candidate.id === source.id)
|
|
654
|
+
if (previous) source.ownedModelIds = new Set(previous.ownedModelIds)
|
|
655
|
+
for (const previousSource of replacing) {
|
|
656
|
+
if (previousSource.id === source.id) continue
|
|
657
|
+
const mapped = sources.get(previousSource.id)
|
|
658
|
+
if (mapped === previousSource) sources.delete(previousSource.id)
|
|
659
|
+
// Absent from the map means an earlier attempt already removed it but
|
|
660
|
+
// failed before reloading — still owed a registry removal. A different
|
|
661
|
+
// live source under the id (e.g. a host-registered provider took over)
|
|
662
|
+
// is left entirely alone.
|
|
663
|
+
if (mapped === previousSource || mapped === undefined) {
|
|
664
|
+
staleProviderIds.add(previousSource.id)
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
sources.set(source.id, source)
|
|
668
|
+
await context.provider.reload()
|
|
669
|
+
source.pendingPublication = false
|
|
670
|
+
logInfo(
|
|
671
|
+
`[opencode-litellm] Registered provider "${source.id}" from the connected LiteLLM credential.`,
|
|
672
|
+
)
|
|
673
|
+
} catch (error) {
|
|
674
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
675
|
+
logInfo(`[opencode-litellm] Could not register the connected provider: ${message}`)
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
574
679
|
const definition = Plugin.define({
|
|
575
680
|
id: 'opencode-litellm',
|
|
576
681
|
async setup(context) {
|
|
@@ -584,6 +689,14 @@ const definition = Plugin.define({
|
|
|
584
689
|
|
|
585
690
|
const pluginOptions = asRecord(context.options)
|
|
586
691
|
const sources = new Map<string, ProviderSource>()
|
|
692
|
+
// Providers the dialog replaced under a new id; the transform below
|
|
693
|
+
// removes them from the registry on the next reload.
|
|
694
|
+
const staleProviderIds = new Set<string>()
|
|
695
|
+
|
|
696
|
+
// Surface LiteLLM in the connect-provider dialog so gateways can be
|
|
697
|
+
// connected from the web UI. Purely additive: a host without the
|
|
698
|
+
// integration API, or a failed registration, keeps every other auth path.
|
|
699
|
+
const integrationRegistration = await registerLiteLLMIntegration(context)
|
|
587
700
|
|
|
588
701
|
// First pass. On OpenCode 2 the host has not registered user-configured
|
|
589
702
|
// providers yet, so this typically finds only built-ins; the event loop
|
|
@@ -602,12 +715,21 @@ const definition = Plugin.define({
|
|
|
602
715
|
}
|
|
603
716
|
|
|
604
717
|
const providerRegistration = await context.provider.transform((editor) => {
|
|
718
|
+
// Sources replaced under a different id leave their registry entries
|
|
719
|
+
// behind; drop them before publishing the current sources.
|
|
720
|
+
for (const id of staleProviderIds) editor.remove(id)
|
|
721
|
+
staleProviderIds.clear()
|
|
605
722
|
for (const source of sources.values()) {
|
|
606
723
|
const current = editor.get(source.id)
|
|
607
724
|
if (current) {
|
|
608
725
|
editor.update(source.id, (provider) => {
|
|
609
726
|
provider.package = source.package
|
|
610
727
|
provider.name = source.name
|
|
728
|
+
// Bind the provider to the integration its credential comes from,
|
|
729
|
+
// so OpenCode keeps injecting the key after a credential switch.
|
|
730
|
+
if (source.usesConnectionCredential && source.integrationID) {
|
|
731
|
+
provider.integrationID = Integration.ID.make(source.integrationID)
|
|
732
|
+
}
|
|
611
733
|
const settings = {
|
|
612
734
|
...(provider.settings ?? {}),
|
|
613
735
|
...runtimeSettings(source),
|
|
@@ -637,6 +759,12 @@ const definition = Plugin.define({
|
|
|
637
759
|
package: source.package,
|
|
638
760
|
settings: runtimeSettings(source),
|
|
639
761
|
headers: source.headers,
|
|
762
|
+
// With `integrationID` set, OpenCode resolves the API key from
|
|
763
|
+
// the connected credential at request time — the key itself
|
|
764
|
+
// never enters provider settings.
|
|
765
|
+
...(source.usesConnectionCredential && source.integrationID
|
|
766
|
+
? { integrationID: Integration.ID.make(source.integrationID) }
|
|
767
|
+
: {}),
|
|
640
768
|
},
|
|
641
769
|
models: source.models,
|
|
642
770
|
})
|
|
@@ -713,6 +841,18 @@ const definition = Plugin.define({
|
|
|
713
841
|
continue
|
|
714
842
|
}
|
|
715
843
|
if (event.type === 'credential.switched') {
|
|
844
|
+
// Sources the plugin built from the dialog re-derive everything
|
|
845
|
+
// (key, baseURL, provider id) from the active connection, so a
|
|
846
|
+
// reconnect can legitimately move them to a different gateway.
|
|
847
|
+
// Configured sources only refresh their key: config outranks the
|
|
848
|
+
// dialog for everything but the key.
|
|
849
|
+
const dialogBuilt = [...sources.values()].filter(
|
|
850
|
+
(source) =>
|
|
851
|
+
source.integrationID === event.data.integrationID &&
|
|
852
|
+
source.fromFallback &&
|
|
853
|
+
source.usesConnectionCredential &&
|
|
854
|
+
!readString(source.settings.baseURL),
|
|
855
|
+
)
|
|
716
856
|
const changedSources = (await Promise.all(
|
|
717
857
|
[...sources.values()]
|
|
718
858
|
.filter((source) => source.integrationID === event.data.integrationID)
|
|
@@ -724,8 +864,24 @@ const definition = Plugin.define({
|
|
|
724
864
|
source.credentialReloadRequired = true
|
|
725
865
|
source.refreshRequired = true
|
|
726
866
|
}
|
|
727
|
-
|
|
728
|
-
|
|
867
|
+
const keyOnlySources = changedSources.filter((source) => !dialogBuilt.includes(source))
|
|
868
|
+
if (keyOnlySources.length > 0) {
|
|
869
|
+
await refreshProviderSources(context, keyOnlySources, inFlight)
|
|
870
|
+
}
|
|
871
|
+
if (
|
|
872
|
+
event.data.integrationID === LITELLM_INTEGRATION_ID &&
|
|
873
|
+
(dialogBuilt.length > 0 || changedSources.length === 0)
|
|
874
|
+
) {
|
|
875
|
+
// Rebuild dialog-built sources from the fresh credential — or,
|
|
876
|
+
// when no source is bound yet, publish the first one, taking
|
|
877
|
+
// over from a keyless auto-detection fallback if one exists.
|
|
878
|
+
await publishConnectedSource(
|
|
879
|
+
context,
|
|
880
|
+
pluginOptions,
|
|
881
|
+
sources,
|
|
882
|
+
staleProviderIds,
|
|
883
|
+
dialogBuilt,
|
|
884
|
+
)
|
|
729
885
|
}
|
|
730
886
|
continue
|
|
731
887
|
}
|
|
@@ -751,6 +907,7 @@ const definition = Plugin.define({
|
|
|
751
907
|
return async () => {
|
|
752
908
|
controller.abort()
|
|
753
909
|
await providerRegistration.dispose()
|
|
910
|
+
await integrationRegistration?.dispose()
|
|
754
911
|
}
|
|
755
912
|
},
|
|
756
913
|
})
|
package/src/types/index.ts
CHANGED
|
@@ -71,6 +71,8 @@ export interface LiteLLMModelInfo {
|
|
|
71
71
|
supported_openai_params?: string[] | null
|
|
72
72
|
supports_pdf_input?: boolean
|
|
73
73
|
supports_audio_input?: boolean
|
|
74
|
+
supports_adaptive_thinking?: boolean
|
|
75
|
+
thinking_always_on?: boolean
|
|
74
76
|
input_cost_per_token?: number
|
|
75
77
|
output_cost_per_token?: number
|
|
76
78
|
cache_read_input_token_cost?: number
|
package/src/utils/model-cache.ts
CHANGED
|
@@ -5,8 +5,9 @@ import { join } from 'node:path'
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Facts about a discovered model's upstream that OpenCode 2 turns into
|
|
8
|
-
* `Model.Info.compatibility`. They ride alongside the
|
|
9
|
-
* entries (which have no field for them) through
|
|
8
|
+
* `Model.Info.compatibility` and `variants`. They ride alongside the
|
|
9
|
+
* config-shaped model entries (which have no field for them) through
|
|
10
|
+
* discovery and the cache.
|
|
10
11
|
*/
|
|
11
12
|
export interface ModelHints {
|
|
12
13
|
/**
|
|
@@ -14,6 +15,13 @@ export interface ModelHints {
|
|
|
14
15
|
* Chat Completions (`supported_openai_params` lists `cache_control`).
|
|
15
16
|
*/
|
|
16
17
|
acceptsCacheControl: boolean
|
|
18
|
+
/**
|
|
19
|
+
* The model takes `thinking: { type: "adaptive" }` plus an `effort` level
|
|
20
|
+
* (`supports_adaptive_thinking`).
|
|
21
|
+
*/
|
|
22
|
+
adaptiveThinking: boolean
|
|
23
|
+
/** Thinking cannot be turned off (`thinking_always_on`). */
|
|
24
|
+
thinkingAlwaysOn: boolean
|
|
17
25
|
}
|
|
18
26
|
|
|
19
27
|
/**
|
|
@@ -21,7 +29,7 @@ export interface ModelHints {
|
|
|
21
29
|
* from older plugin versions are ignored rather than deserialized into
|
|
22
30
|
* an incompatible structure.
|
|
23
31
|
*/
|
|
24
|
-
const CACHE_VERSION =
|
|
32
|
+
const CACHE_VERSION = 5
|
|
25
33
|
|
|
26
34
|
/**
|
|
27
35
|
* Maximum age of a cache entry before it's treated as a miss. Without a
|
|
@@ -158,8 +166,12 @@ function normalizeHints(value: unknown): Record<string, ModelHints> {
|
|
|
158
166
|
const out: Record<string, ModelHints> = {}
|
|
159
167
|
for (const [id, hint] of Object.entries(value as Record<string, unknown>)) {
|
|
160
168
|
if (!hint || typeof hint !== 'object' || Array.isArray(hint)) continue
|
|
161
|
-
const { acceptsCacheControl } = hint as Record<string, unknown>
|
|
162
|
-
out[id] = {
|
|
169
|
+
const { acceptsCacheControl, adaptiveThinking, thinkingAlwaysOn } = hint as Record<string, unknown>
|
|
170
|
+
out[id] = {
|
|
171
|
+
acceptsCacheControl: acceptsCacheControl === true,
|
|
172
|
+
adaptiveThinking: adaptiveThinking === true,
|
|
173
|
+
thinkingAlwaysOn: thinkingAlwaysOn === true,
|
|
174
|
+
}
|
|
163
175
|
}
|
|
164
176
|
return out
|
|
165
177
|
}
|