opencode-plugin-litellm 1.8.1 → 1.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/README.md +77 -1
- package/package.json +1 -1
- package/src/plugin/auth.ts +312 -0
- package/src/plugin/index.ts +252 -34
- package/src/plugin/integration.ts +226 -16
- package/src/plugin/v2.ts +310 -31
- package/src/utils/format-model-name.ts +54 -1
- package/src/utils/litellm-api.ts +9 -5
- package/src/utils/model-cache.ts +26 -11
- package/src/utils/opencode-auth.ts +70 -19
- package/src/utils/sso.ts +998 -0
package/src/plugin/index.ts
CHANGED
|
@@ -8,12 +8,23 @@ import {
|
|
|
8
8
|
normalizeBaseURL,
|
|
9
9
|
} from '../utils/litellm-api'
|
|
10
10
|
import {
|
|
11
|
+
applyModelNameTemplate,
|
|
12
|
+
DEFAULT_MODEL_NAME_TEMPLATE,
|
|
11
13
|
formatModelName,
|
|
12
14
|
categorizeModel,
|
|
15
|
+
type ModelNaming,
|
|
13
16
|
} from '../utils/format-model-name'
|
|
14
17
|
import { requiresResponsesAPI } from '../utils/transport'
|
|
15
18
|
import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
|
|
16
|
-
import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
|
|
19
|
+
import { getOpenCodeStoredApiKey, resetOpenCodeAuthCache } from '../utils/opencode-auth'
|
|
20
|
+
import { sameProxy, ssoIdentity } from '../utils/sso'
|
|
21
|
+
import {
|
|
22
|
+
createSsoSession,
|
|
23
|
+
liteLLMAuthHook,
|
|
24
|
+
ssoFetch,
|
|
25
|
+
type SignInTarget,
|
|
26
|
+
type SsoSession,
|
|
27
|
+
} from './auth'
|
|
17
28
|
import type { ModelHints } from '../utils/model-cache'
|
|
18
29
|
import {
|
|
19
30
|
buildCacheKey,
|
|
@@ -34,6 +45,8 @@ const CHAT_PROVIDER_ID = 'litellm'
|
|
|
34
45
|
// with it so it never treats its own sibling as a chat provider.
|
|
35
46
|
const RESPONSES_PROVIDER_SUFFIX = '-responses'
|
|
36
47
|
const RESPONSES_NPM = '@ai-sdk/openai'
|
|
48
|
+
// `@ai-sdk/openai` throws without an API key, even when the sign-in's `fetch` sends the real token.
|
|
49
|
+
const SIGN_IN_PLACEHOLDER = 'litellm-sign-in'
|
|
37
50
|
// Covers the 3 s health check plus the parallel models/model-info fetch
|
|
38
51
|
// phase, with headroom. Scales with LITELLM_REQUEST_TIMEOUT_MS so slow
|
|
39
52
|
// proxies aren't cut off by the overall cap either (issue #20).
|
|
@@ -98,14 +111,35 @@ const injectedModelIds = new Map<string, Set<string>>()
|
|
|
98
111
|
interface RefreshContext {
|
|
99
112
|
baseURL: string
|
|
100
113
|
apiKey?: string
|
|
114
|
+
/** A LiteLLM sign-in, whose rotating access token replaces `apiKey`. */
|
|
115
|
+
session?: SsoSession
|
|
101
116
|
customHeaders?: Record<string, string>
|
|
102
117
|
filters: ModelFilters
|
|
103
118
|
capabilities: ModelCapabilities
|
|
104
119
|
formatModelNames: boolean
|
|
120
|
+
modelNameTemplate?: string
|
|
121
|
+
providerName: string
|
|
105
122
|
providerId: string
|
|
106
123
|
}
|
|
107
124
|
const refreshContexts = new Map<string, RefreshContext>()
|
|
108
125
|
|
|
126
|
+
/**
|
|
127
|
+
* OpenCode 1 caches the global config for the whole process, so after a
|
|
128
|
+
* login rebuilds the instance a provider's options come back still holding
|
|
129
|
+
* what this plugin wrote. Only the values the user configured count as
|
|
130
|
+
* configuration: this snapshot is taken before the plugin first writes.
|
|
131
|
+
*/
|
|
132
|
+
const configuredOptions = new WeakMap<object, Record<string, unknown>>()
|
|
133
|
+
|
|
134
|
+
function userOptions(options: Record<string, unknown>): Record<string, unknown> {
|
|
135
|
+
let configured = configuredOptions.get(options)
|
|
136
|
+
if (!configured) {
|
|
137
|
+
configured = { ...options }
|
|
138
|
+
configuredOptions.set(options, configured)
|
|
139
|
+
}
|
|
140
|
+
return configured
|
|
141
|
+
}
|
|
142
|
+
|
|
109
143
|
/** Cache keys with an in-flight background refresh, to avoid pile-ups. */
|
|
110
144
|
const refreshInFlight = new Set<string>()
|
|
111
145
|
|
|
@@ -202,6 +236,20 @@ export function readFormatModelNames(options: Record<string, unknown>): boolean
|
|
|
202
236
|
return options.formatModelNames !== false
|
|
203
237
|
}
|
|
204
238
|
|
|
239
|
+
/**
|
|
240
|
+
* Read the optional display-name template. Non-strings are ignored. An empty
|
|
241
|
+
* string, or the `"{name}"` default spelled out, counts as unset so those
|
|
242
|
+
* configs keep the same cache identity (and the same warm cache) as before
|
|
243
|
+
* the setting existed.
|
|
244
|
+
*/
|
|
245
|
+
export function readModelNameTemplate(options: Record<string, unknown>): string | undefined {
|
|
246
|
+
const value = options.modelNameTemplate
|
|
247
|
+
if (typeof value !== 'string') return undefined
|
|
248
|
+
const trimmed = value.trim()
|
|
249
|
+
if (trimmed === '' || trimmed === DEFAULT_MODEL_NAME_TEMPLATE) return undefined
|
|
250
|
+
return value
|
|
251
|
+
}
|
|
252
|
+
|
|
205
253
|
/**
|
|
206
254
|
* Overlay metadata onto a `/v1/models` entry in three tiers: the entry's
|
|
207
255
|
* own fields win, `/v1/model/info` fills gaps (notably `mode`, which
|
|
@@ -247,6 +295,14 @@ function enrichModel(
|
|
|
247
295
|
*/
|
|
248
296
|
const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
|
|
249
297
|
|
|
298
|
+
/**
|
|
299
|
+
* The display name a model gets before any provider template is applied —
|
|
300
|
+
* the plugin's default formatting, or the raw `/v1/models` id.
|
|
301
|
+
*/
|
|
302
|
+
function baseDisplayName(model: { id: string }, formatModelNames: boolean): string {
|
|
303
|
+
return formatModelNames ? formatModelName(model) : model.id
|
|
304
|
+
}
|
|
305
|
+
|
|
250
306
|
/**
|
|
251
307
|
* Convert a discovered LiteLLM model into an OpenCode config-level
|
|
252
308
|
* model entry (the shape used in `provider.*.models` inside
|
|
@@ -254,20 +310,29 @@ const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
|
|
|
254
310
|
* image, audio) — they can't be used as primary chat models and would
|
|
255
311
|
* clutter the picker.
|
|
256
312
|
*
|
|
257
|
-
* Exported for tests: `
|
|
258
|
-
*
|
|
313
|
+
* Exported for tests: the `naming` options decide the display name — the
|
|
314
|
+
* prettified id or the raw `/v1/models` id, optionally wrapped in the
|
|
315
|
+
* provider's `modelNameTemplate`.
|
|
259
316
|
*/
|
|
260
317
|
export function toConfigModel(
|
|
261
318
|
model: LiteLLMModel,
|
|
262
319
|
info?: LiteLLMModelInfo,
|
|
263
|
-
|
|
320
|
+
naming: ModelNaming = {},
|
|
264
321
|
): Record<string, unknown> | null {
|
|
265
322
|
const type = categorizeModel(model)
|
|
266
323
|
if (type === 'embedding' || type === 'image' || type === 'audio') {
|
|
267
324
|
return null
|
|
268
325
|
}
|
|
326
|
+
const providerId = naming.providerId ?? ''
|
|
269
327
|
const entry: Record<string, unknown> = {
|
|
270
|
-
name:
|
|
328
|
+
name: applyModelNameTemplate(naming.modelNameTemplate, {
|
|
329
|
+
name: baseDisplayName(model, naming.formatModelNames !== false),
|
|
330
|
+
id: model.id,
|
|
331
|
+
providerId,
|
|
332
|
+
// Without a configured display name the picker falls back to the id,
|
|
333
|
+
// so the placeholder resolves to the same thing the user sees.
|
|
334
|
+
providerName: naming.providerName ?? providerId,
|
|
335
|
+
}),
|
|
271
336
|
}
|
|
272
337
|
// Some deployments only report the OpenAI-style `max_tokens` total;
|
|
273
338
|
// use it as the context limit when `max_input_tokens` is absent.
|
|
@@ -360,9 +425,9 @@ export interface DiscoveredModels {
|
|
|
360
425
|
* classifies + formats each model, and returns the built entries plus the
|
|
361
426
|
* ids that require the Responses API and per-model hints. The provider's
|
|
362
427
|
* `includeModels`/`excludeModels` filters, `modelCapabilities` overrides and
|
|
363
|
-
* `formatModelNames`
|
|
364
|
-
* path that persists or serves a cache — cold
|
|
365
|
-
* refresh — writes the same adjusted view.
|
|
428
|
+
* naming choices (`formatModelNames`, `modelNameTemplate`) are applied here
|
|
429
|
+
* (not at merge time) so every path that persists or serves a cache — cold
|
|
430
|
+
* discovery and background refresh — writes the same adjusted view.
|
|
366
431
|
*
|
|
367
432
|
* Returns `null` when the proxy is unreachable/unauthorized or exposes
|
|
368
433
|
* no models, so callers can distinguish "no data" from "empty result".
|
|
@@ -374,7 +439,7 @@ export async function discoverModels(
|
|
|
374
439
|
providerId: string,
|
|
375
440
|
filters: ModelFilters = {},
|
|
376
441
|
capabilities: ModelCapabilities = {},
|
|
377
|
-
|
|
442
|
+
naming: ModelNaming = {},
|
|
378
443
|
): Promise<DiscoveredModels | null> {
|
|
379
444
|
if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
|
|
380
445
|
log(
|
|
@@ -449,7 +514,7 @@ export async function discoverModels(
|
|
|
449
514
|
const info = infoByName?.get(model.id)
|
|
450
515
|
if (infoByName && !info) unmatched.push(model.id)
|
|
451
516
|
const enriched = enrichModel(model, info, capabilities[model.id])
|
|
452
|
-
const entry = toConfigModel(enriched, info,
|
|
517
|
+
const entry = toConfigModel(enriched, info, { ...naming, providerId })
|
|
453
518
|
if (!entry) {
|
|
454
519
|
skipped++
|
|
455
520
|
continue
|
|
@@ -535,6 +600,7 @@ function ensureResponsesProvider(
|
|
|
535
600
|
baseURL: string,
|
|
536
601
|
apiKey: string | undefined,
|
|
537
602
|
customHeaders: Record<string, string> | undefined,
|
|
603
|
+
runtimeFetch: typeof fetch | undefined,
|
|
538
604
|
): Record<string, unknown> {
|
|
539
605
|
const id = `${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`
|
|
540
606
|
if (!config.provider[id] || typeof config.provider[id] !== 'object') {
|
|
@@ -543,18 +609,29 @@ function ensureResponsesProvider(
|
|
|
543
609
|
const provider = config.provider[id] as Record<string, unknown>
|
|
544
610
|
if (!provider.npm) provider.npm = RESPONSES_NPM
|
|
545
611
|
if (typeof provider.name !== 'string' || !provider.name) {
|
|
612
|
+
// Mirror how the base provider is labelled: its configured name, or its
|
|
613
|
+
// id when none is set (which is what the picker falls back to). This keeps
|
|
614
|
+
// `{provider_name}` in the sibling's model names equal to the sibling's
|
|
615
|
+
// visible label.
|
|
546
616
|
const baseName =
|
|
547
617
|
typeof baseProvider.name === 'string' && baseProvider.name
|
|
548
618
|
? baseProvider.name
|
|
549
|
-
:
|
|
619
|
+
: baseProviderId
|
|
550
620
|
provider.name = `${baseName} Responses`
|
|
551
621
|
}
|
|
552
622
|
if (!provider.options || typeof provider.options !== 'object') {
|
|
553
623
|
provider.options = {}
|
|
554
624
|
}
|
|
555
625
|
const options = provider.options as Record<string, unknown>
|
|
556
|
-
|
|
557
|
-
if (!
|
|
626
|
+
const configured = userOptions(options)
|
|
627
|
+
if (!configured.baseURL) options.baseURL = `${baseURL}/v1`
|
|
628
|
+
if (!configured.apiKey) {
|
|
629
|
+
const key = apiKey ?? (runtimeFetch ? SIGN_IN_PLACEHOLDER : undefined)
|
|
630
|
+
if (key) options.apiKey = key
|
|
631
|
+
else delete options.apiKey
|
|
632
|
+
}
|
|
633
|
+
if (runtimeFetch) options.fetch = runtimeFetch
|
|
634
|
+
else if (configured.fetch === undefined) delete options.fetch
|
|
558
635
|
// OpenCode 1 reads provider headers from `options.headers` and hands them to
|
|
559
636
|
// the runtime package (`@ai-sdk/openai` here); it has no `customHeaders` key.
|
|
560
637
|
// Mirror the chat provider's native headers and promote the plugin's
|
|
@@ -589,6 +666,35 @@ function readHeaderMap(value: unknown): Record<string, string> {
|
|
|
589
666
|
return out
|
|
590
667
|
}
|
|
591
668
|
|
|
669
|
+
/**
|
|
670
|
+
* Re-render one discovered entry's name for the provider it is about to be
|
|
671
|
+
* injected into.
|
|
672
|
+
*
|
|
673
|
+
* OpenCode 1 moves Responses models into a `${baseProviderId}-responses`
|
|
674
|
+
* sibling, so a template that uses `{provider_id}`/`{provider_name}` must
|
|
675
|
+
* resolve to the provider the user actually selects. The entry in the cache
|
|
676
|
+
* stays as discovered — OpenCode 2 reads the same cache with a single
|
|
677
|
+
* provider — so this returns a copy instead of mutating it.
|
|
678
|
+
*/
|
|
679
|
+
function renameForProvider(
|
|
680
|
+
entry: Record<string, unknown>,
|
|
681
|
+
modelId: string,
|
|
682
|
+
naming: ModelNaming,
|
|
683
|
+
providerId: string,
|
|
684
|
+
providerName: string,
|
|
685
|
+
): Record<string, unknown> {
|
|
686
|
+
if (naming.modelNameTemplate === undefined) return entry
|
|
687
|
+
return {
|
|
688
|
+
...entry,
|
|
689
|
+
name: applyModelNameTemplate(naming.modelNameTemplate, {
|
|
690
|
+
name: baseDisplayName({ id: modelId }, naming.formatModelNames !== false),
|
|
691
|
+
id: modelId,
|
|
692
|
+
providerId,
|
|
693
|
+
providerName,
|
|
694
|
+
}),
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
592
698
|
/**
|
|
593
699
|
* Split freshly discovered entries into the chat provider and the Responses
|
|
594
700
|
* sibling, injecting each side without clobbering curated entries. Returns
|
|
@@ -605,26 +711,38 @@ function injectDiscoveredModels(
|
|
|
605
711
|
baseURL: string,
|
|
606
712
|
apiKey: string | undefined,
|
|
607
713
|
customHeaders: Record<string, string> | undefined,
|
|
714
|
+
runtimeFetch: typeof fetch | undefined,
|
|
715
|
+
naming: ModelNaming,
|
|
608
716
|
): string[] {
|
|
609
717
|
const responsesSet = new Set(responsesIds)
|
|
610
|
-
const
|
|
718
|
+
const responsesProviderId = `${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`
|
|
719
|
+
const existingSibling =
|
|
720
|
+
config.provider[responsesProviderId] &&
|
|
721
|
+
typeof config.provider[responsesProviderId] === 'object'
|
|
722
|
+
? (config.provider[responsesProviderId] as Record<string, unknown>)
|
|
723
|
+
: undefined
|
|
724
|
+
// A name the user (or an earlier run) already gave the sibling, captured
|
|
725
|
+
// before `ensureResponsesProvider` generates one.
|
|
726
|
+
const configuredSiblingName =
|
|
727
|
+
typeof existingSibling?.name === 'string' && existingSibling.name
|
|
728
|
+
? existingSibling.name
|
|
729
|
+
: undefined
|
|
611
730
|
const siblingModelsExisting: Record<string, unknown> =
|
|
612
731
|
existingSibling &&
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
? ((existingSibling as Record<string, unknown>).models as Record<string, unknown>)
|
|
732
|
+
existingSibling.models &&
|
|
733
|
+
typeof existingSibling.models === 'object'
|
|
734
|
+
? (existingSibling.models as Record<string, unknown>)
|
|
617
735
|
: {}
|
|
618
736
|
|
|
619
737
|
const chatEntries: Record<string, unknown> = {}
|
|
620
|
-
const
|
|
738
|
+
const responsesIdsToInject: string[] = []
|
|
621
739
|
for (const [id, entry] of Object.entries(entries)) {
|
|
622
740
|
// A model already present under the other provider was curated there (or
|
|
623
741
|
// injected by an earlier run); leave it alone instead of duplicating it
|
|
624
742
|
// across both providers.
|
|
625
743
|
if (responsesSet.has(id)) {
|
|
626
744
|
if (Object.hasOwn(baseModels, id)) continue
|
|
627
|
-
|
|
745
|
+
responsesIdsToInject.push(id)
|
|
628
746
|
} else {
|
|
629
747
|
if (Object.hasOwn(siblingModelsExisting, id)) continue
|
|
630
748
|
chatEntries[id] = entry
|
|
@@ -632,7 +750,7 @@ function injectDiscoveredModels(
|
|
|
632
750
|
}
|
|
633
751
|
|
|
634
752
|
const added = mergeModels(baseModels, chatEntries)
|
|
635
|
-
if (
|
|
753
|
+
if (responsesIdsToInject.length > 0) {
|
|
636
754
|
const siblingModels = ensureResponsesProvider(
|
|
637
755
|
config,
|
|
638
756
|
baseProviderId,
|
|
@@ -640,7 +758,28 @@ function injectDiscoveredModels(
|
|
|
640
758
|
baseURL,
|
|
641
759
|
apiKey,
|
|
642
760
|
customHeaders,
|
|
761
|
+
runtimeFetch,
|
|
643
762
|
)
|
|
763
|
+
// The sibling generates its name from the base provider's, so read it
|
|
764
|
+
// back; a user-configured name (from this run or an earlier one) wins.
|
|
765
|
+
// `{provider_name}` must equal the label the picker shows for the sibling
|
|
766
|
+
// because that is the provider the model is selected through.
|
|
767
|
+
const sibling = config.provider[responsesProviderId] as Record<string, unknown> | undefined
|
|
768
|
+
const siblingName =
|
|
769
|
+
configuredSiblingName ??
|
|
770
|
+
(sibling && typeof sibling.name === 'string' && sibling.name
|
|
771
|
+
? sibling.name
|
|
772
|
+
: responsesProviderId)
|
|
773
|
+
const responsesEntries: Record<string, unknown> = {}
|
|
774
|
+
for (const id of responsesIdsToInject) {
|
|
775
|
+
responsesEntries[id] = renameForProvider(
|
|
776
|
+
entries[id] as Record<string, unknown>,
|
|
777
|
+
id,
|
|
778
|
+
naming,
|
|
779
|
+
responsesProviderId,
|
|
780
|
+
siblingName,
|
|
781
|
+
)
|
|
782
|
+
}
|
|
644
783
|
added.push(...mergeModels(siblingModels, responsesEntries))
|
|
645
784
|
}
|
|
646
785
|
return added
|
|
@@ -664,15 +803,21 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
|
|
|
664
803
|
}
|
|
665
804
|
refreshInFlight.add(cacheKey)
|
|
666
805
|
try {
|
|
806
|
+
const apiKey = ctx.session ? await ctx.session.access(ctx.customHeaders) : ctx.apiKey
|
|
667
807
|
const discovered = await withTimeout(
|
|
668
808
|
discoverModels(
|
|
669
809
|
ctx.baseURL,
|
|
670
|
-
|
|
810
|
+
apiKey,
|
|
671
811
|
ctx.customHeaders,
|
|
672
812
|
ctx.providerId,
|
|
673
813
|
ctx.filters,
|
|
674
814
|
ctx.capabilities,
|
|
675
|
-
|
|
815
|
+
{
|
|
816
|
+
formatModelNames: ctx.formatModelNames,
|
|
817
|
+
modelNameTemplate: ctx.modelNameTemplate,
|
|
818
|
+
providerId: ctx.providerId,
|
|
819
|
+
providerName: ctx.providerName,
|
|
820
|
+
},
|
|
676
821
|
),
|
|
677
822
|
DISCOVERY_TIMEOUT_MS,
|
|
678
823
|
)
|
|
@@ -716,7 +861,13 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
|
|
|
716
861
|
*/
|
|
717
862
|
export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
718
863
|
initLogging(input.client)
|
|
864
|
+
// OpenCode rebuilds the plugin after a login; this instance must read the new credential.
|
|
865
|
+
resetOpenCodeAuthCache()
|
|
866
|
+
const warn = (message: string) => log('warn', message)
|
|
867
|
+
const session = createSsoSession(input.client, CHAT_PROVIDER_ID, warn)
|
|
868
|
+
let signInTarget: SignInTarget = { baseURL: undefined, previousURL: undefined, headers: {} }
|
|
719
869
|
return {
|
|
870
|
+
auth: liteLLMAuthHook(CHAT_PROVIDER_ID, () => signInTarget),
|
|
720
871
|
config: async (config: any) => {
|
|
721
872
|
// Ensure the provider entry exists
|
|
722
873
|
if (!config.provider) config.provider = {}
|
|
@@ -756,7 +907,9 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
756
907
|
|
|
757
908
|
// Process each matched provider
|
|
758
909
|
for (const { id: providerId, provider } of liteLLMProviders) {
|
|
759
|
-
|
|
910
|
+
// Snapshot the object this plugin writes into, so a later run recognizes those writes.
|
|
911
|
+
if (!provider.options || typeof provider.options !== 'object') provider.options = {}
|
|
912
|
+
const options = userOptions(provider.options as Record<string, unknown>)
|
|
760
913
|
const configuredBase =
|
|
761
914
|
typeof options.baseURL === 'string' ? options.baseURL : undefined
|
|
762
915
|
const configuredKey =
|
|
@@ -779,21 +932,67 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
779
932
|
override of a user's saved key.
|
|
780
933
|
*/
|
|
781
934
|
const storedKey = await getOpenCodeStoredApiKey(providerId)
|
|
782
|
-
const apiKey = configuredKey ?? storedKey ?? envKey
|
|
783
935
|
// Native `options.headers` and the legacy `customHeaders` both reach
|
|
784
936
|
// discovery and the runtime, so a gateway that only sets one still
|
|
785
937
|
// authenticates the plugin's own fetches.
|
|
786
938
|
const customHeaders = readProviderHeaders(options)
|
|
939
|
+
// A LiteLLM sign-in for the provider the auth hook serves is a stored
|
|
940
|
+
// credential too: it beats the environment, and a configured key beats it.
|
|
941
|
+
let sso =
|
|
942
|
+
providerId === CHAT_PROVIDER_ID && !configuredKey ? await session.stored() : undefined
|
|
943
|
+
const signedInTo = sso?.metadata.baseURL
|
|
944
|
+
if (configuredBase && typeof signedInTo === 'string' && !sameProxy(configuredBase, signedInTo)) {
|
|
945
|
+
// The provider points elsewhere, and that host must not receive this sign-in's token.
|
|
946
|
+
log(
|
|
947
|
+
'warn',
|
|
948
|
+
`[opencode-litellm] Not using the LiteLLM sign-in for ${signedInTo}: provider "${providerId}" is configured for ${configuredBase}.`,
|
|
949
|
+
)
|
|
950
|
+
sso = undefined
|
|
951
|
+
}
|
|
952
|
+
if (providerId === CHAT_PROVIDER_ID) {
|
|
953
|
+
const previousURL = sso?.metadata.baseURL
|
|
954
|
+
signInTarget = {
|
|
955
|
+
baseURL: configuredBase,
|
|
956
|
+
previousURL: typeof previousURL === 'string' ? previousURL : undefined,
|
|
957
|
+
headers: customHeaders ?? {},
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
const ssoKey = sso
|
|
961
|
+
? await session.access(customHeaders).catch((error: unknown) => {
|
|
962
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
963
|
+
log('warn', `[opencode-litellm] LiteLLM sign-in unusable: ${message}`)
|
|
964
|
+
return undefined
|
|
965
|
+
})
|
|
966
|
+
: undefined
|
|
967
|
+
// An unusable sign-in still outranks the environment: discovery goes without
|
|
968
|
+
// a key (an empty one also stops the discovery helpers' own environment
|
|
969
|
+
// fallback), and requests ask to connect again.
|
|
970
|
+
const apiKey = configuredKey ?? storedKey ?? (sso ? (ssoKey ?? '') : envKey)
|
|
971
|
+
// A sign-in's token rotates, so it goes out per request instead of
|
|
972
|
+
// sitting in `apiKey`.
|
|
973
|
+
const runtimeKey = sso ? undefined : apiKey
|
|
974
|
+
const runtimeFetch = sso ? ssoFetch(session, customHeaders) : undefined
|
|
787
975
|
const filters = readModelFilters(options)
|
|
788
976
|
const capabilities = parseModelCapabilities(options.modelCapabilities)
|
|
789
977
|
const formatModelNames = readFormatModelNames(options)
|
|
978
|
+
const modelNameTemplate = readModelNameTemplate(options)
|
|
979
|
+
// `{provider_name}` resolves to what the picker labels the provider
|
|
980
|
+
// with; OpenCode falls back to the id when no name is configured.
|
|
981
|
+
const providerName =
|
|
982
|
+
typeof provider.name === 'string' && provider.name ? provider.name : providerId
|
|
983
|
+
const naming = { formatModelNames, modelNameTemplate, providerId, providerName }
|
|
790
984
|
|
|
791
985
|
// Resolve base URL
|
|
792
986
|
let baseURL: string | null = null
|
|
793
987
|
if (configuredBase) {
|
|
794
988
|
baseURL = normalizeBaseURL(configuredBase)
|
|
989
|
+
} else if (typeof sso?.metadata.baseURL === 'string') {
|
|
990
|
+
// The proxy the sign-in was issued by.
|
|
991
|
+
baseURL = normalizeBaseURL(sso.metadata.baseURL)
|
|
795
992
|
} else {
|
|
796
|
-
|
|
993
|
+
// A sign-in only goes to a proxy named for it: probing local ports
|
|
994
|
+
// would hand its token to whatever answers there.
|
|
995
|
+
baseURL = await autoDetectLiteLLM(apiKey, customHeaders, sso ? [] : undefined)
|
|
797
996
|
}
|
|
798
997
|
|
|
799
998
|
if (!baseURL) {
|
|
@@ -818,7 +1017,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
818
1017
|
actualProvider.options = {}
|
|
819
1018
|
}
|
|
820
1019
|
const actualOptions = actualProvider.options as Record<string, unknown>
|
|
821
|
-
if (!
|
|
1020
|
+
if (!configuredBase) {
|
|
822
1021
|
actualOptions.baseURL = `${baseURL}/v1`
|
|
823
1022
|
}
|
|
824
1023
|
/*
|
|
@@ -832,9 +1031,13 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
832
1031
|
go out with no Authorization header even though discovery
|
|
833
1032
|
succeeded using the same resolved key.
|
|
834
1033
|
*/
|
|
835
|
-
|
|
836
|
-
|
|
1034
|
+
// Recomputed every run, so an earlier credential never lingers (see userOptions).
|
|
1035
|
+
if (!configuredKey) {
|
|
1036
|
+
if (runtimeKey) actualOptions.apiKey = runtimeKey
|
|
1037
|
+
else delete actualOptions.apiKey
|
|
837
1038
|
}
|
|
1039
|
+
if (runtimeFetch) actualOptions.fetch = runtimeFetch
|
|
1040
|
+
else if (options.fetch === undefined) delete actualOptions.fetch
|
|
838
1041
|
|
|
839
1042
|
if (!actualProvider.models) {
|
|
840
1043
|
actualProvider.models = {}
|
|
@@ -847,20 +1050,31 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
847
1050
|
// fresh discovery instead of serving the old adjusted view.
|
|
848
1051
|
// The cache key is isolated by the effective credential (a fingerprint,
|
|
849
1052
|
// never the raw key): a credential change starts a fresh discovery
|
|
850
|
-
// instead of serving another credential's cached model list.
|
|
1053
|
+
// instead of serving another credential's cached model list. A sign-in
|
|
1054
|
+
// keeps one key while its token rotates, and even once it expired, so
|
|
1055
|
+
// the provider keeps its models and can be reconnected from `/connect`.
|
|
851
1056
|
const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities, {
|
|
852
1057
|
formatModelNames,
|
|
853
|
-
|
|
1058
|
+
modelNameTemplate,
|
|
1059
|
+
providerName,
|
|
1060
|
+
}, sso ? ssoIdentity(sso) : apiKey)
|
|
854
1061
|
|
|
855
1062
|
// Remember how to reach this proxy so the `event` hook can
|
|
856
1063
|
// revalidate its cache in the background on new sessions.
|
|
1064
|
+
// Only this run's context refreshes in the background: an earlier one may hold another proxy.
|
|
1065
|
+
for (const [key, context] of refreshContexts) {
|
|
1066
|
+
if (context.providerId === providerId && key !== cacheKey) refreshContexts.delete(key)
|
|
1067
|
+
}
|
|
857
1068
|
refreshContexts.set(cacheKey, {
|
|
858
1069
|
baseURL,
|
|
859
1070
|
apiKey,
|
|
1071
|
+
session: sso ? session : undefined,
|
|
860
1072
|
customHeaders,
|
|
861
1073
|
filters,
|
|
862
1074
|
capabilities,
|
|
863
1075
|
formatModelNames,
|
|
1076
|
+
modelNameTemplate,
|
|
1077
|
+
providerName,
|
|
864
1078
|
providerId,
|
|
865
1079
|
})
|
|
866
1080
|
|
|
@@ -904,8 +1118,10 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
904
1118
|
cached.models,
|
|
905
1119
|
cached.responsesIds,
|
|
906
1120
|
baseURL,
|
|
907
|
-
|
|
1121
|
+
runtimeKey,
|
|
908
1122
|
customHeaders,
|
|
1123
|
+
runtimeFetch,
|
|
1124
|
+
naming,
|
|
909
1125
|
)
|
|
910
1126
|
injectedModelIds.set(cacheKey, new Set(added))
|
|
911
1127
|
log(
|
|
@@ -926,7 +1142,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
926
1142
|
providerId,
|
|
927
1143
|
filters,
|
|
928
1144
|
capabilities,
|
|
929
|
-
formatModelNames,
|
|
1145
|
+
{ formatModelNames, modelNameTemplate, providerId, providerName },
|
|
930
1146
|
),
|
|
931
1147
|
DISCOVERY_TIMEOUT_MS,
|
|
932
1148
|
)
|
|
@@ -939,8 +1155,10 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
939
1155
|
discovered.models,
|
|
940
1156
|
discovered.responsesIds,
|
|
941
1157
|
baseURL,
|
|
942
|
-
|
|
1158
|
+
runtimeKey,
|
|
943
1159
|
customHeaders,
|
|
1160
|
+
runtimeFetch,
|
|
1161
|
+
naming,
|
|
944
1162
|
)
|
|
945
1163
|
injectedModelIds.set(cacheKey, new Set(added))
|
|
946
1164
|
writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
|