opencode-plugin-litellm 1.9.0 → 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 +45 -0
- package/package.json +1 -1
- package/src/plugin/index.ts +138 -21
- package/src/plugin/v2.ts +228 -19
- package/src/utils/format-model-name.ts +54 -1
- package/src/utils/model-cache.ts +26 -11
package/README.md
CHANGED
|
@@ -492,6 +492,51 @@ By default the plugin prettifies each discovered id into a display name — `ant
|
|
|
492
492
|
- Like the other options above, `formatModelNames` is part of the cache identity, so toggling it triggers a fresh discovery on the next start instead of serving previously cached names.
|
|
493
493
|
- To rename just a handful of models while keeping smart formatting for the rest, use the per-model `name` override described in [Overriding or curating individual models](#overriding-or-curating-individual-models-optional).
|
|
494
494
|
|
|
495
|
+
### Naming models per provider (`modelNameTemplate`)
|
|
496
|
+
|
|
497
|
+
Several providers can point at the same LiteLLM proxy with different keys. Every key then exposes the same model ids, so the picker shows identical names under each provider and there is no way to tell which key a model will use. `modelNameTemplate` wraps every discovered model's display name with that provider's context:
|
|
498
|
+
|
|
499
|
+
```jsonc
|
|
500
|
+
{
|
|
501
|
+
"providers": {
|
|
502
|
+
"litellm-team-a": {
|
|
503
|
+
"name": "Team A",
|
|
504
|
+
"settings": {
|
|
505
|
+
"baseURL": "https://litellm.example.com/v1",
|
|
506
|
+
"apiKey": "{env:KEY_A}",
|
|
507
|
+
"modelNameTemplate": "{name} ({provider_name})"
|
|
508
|
+
}
|
|
509
|
+
},
|
|
510
|
+
"litellm-team-b": {
|
|
511
|
+
"name": "Team B",
|
|
512
|
+
"settings": {
|
|
513
|
+
"baseURL": "https://litellm.example.com/v1",
|
|
514
|
+
"apiKey": "{env:KEY_B}",
|
|
515
|
+
"modelNameTemplate": "[B] {name}"
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
`Claude 3.5 Sonnet` shows up as `Claude 3.5 Sonnet (Team A)` under the first provider and `[B] Claude 3.5 Sonnet` under the second.
|
|
523
|
+
|
|
524
|
+
| Placeholder | Value |
|
|
525
|
+
| --- | --- |
|
|
526
|
+
| `{name}` | The display name the plugin would produce anyway — formatted, or the raw id when `formatModelNames: false` |
|
|
527
|
+
| `{id}` | The model id exactly as `/v1/models` returned it |
|
|
528
|
+
| `{provider_id}` | The OpenCode provider id, for example `litellm-team-a` |
|
|
529
|
+
| `{provider_name}` | The provider's configured `name`, or its id when no name is set |
|
|
530
|
+
|
|
531
|
+
- The default is `{name}`, so omitting the setting changes nothing.
|
|
532
|
+
- The template runs after name formatting, so it composes with `formatModelNames: false`.
|
|
533
|
+
- An explicit `models.<id>.name` still wins and is never templated.
|
|
534
|
+
- Unknown placeholders are left as written, and substitution is single-pass: a placeholder that appears inside a resolved value stays literal.
|
|
535
|
+
- Non-string and empty values are ignored.
|
|
536
|
+
- On OpenCode 1, models that need the Responses API are served by a `<provider>-responses` sibling, so `{provider_id}` and `{provider_name}` resolve to that sibling for those models (for example `litellm-team-a-responses`).
|
|
537
|
+
- Like `formatModelNames`, the template is part of the cache identity — and so is the resolved provider name — so changing either starts a fresh discovery on the next start instead of serving previously cached names.
|
|
538
|
+
- Model ids, capability flags, pricing and filtering are unaffected.
|
|
539
|
+
|
|
495
540
|
### Prompt caching (`modelCompatibility`)
|
|
496
541
|
|
|
497
542
|
On OpenCode 2.0.28+ (earlier 2.x releases ignore the setting), the OpenAI-compatible Chat Completions runtime only places Anthropic-style `cache_control` breakpoints when a model declares `compatibility.cacheFormat: "anthropic"`. The plugin sets that for every discovered Chat Completions model whose `/v1/model/info` entry lists `cache_control` under `supported_openai_params` — which LiteLLM reports for Anthropic and Vertex AI Anthropic deployments — so prompt caching keeps working for Claude behind the proxy. Only the Chat Completions runtimes read this setting: the Anthropic Messages runtime adds its own cache breakpoints, and the Responses runtimes do not use it, so models on those packages are left alone.
|
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.10.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",
|
package/src/plugin/index.ts
CHANGED
|
@@ -8,8 +8,11 @@ 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'
|
|
@@ -114,6 +117,8 @@ interface RefreshContext {
|
|
|
114
117
|
filters: ModelFilters
|
|
115
118
|
capabilities: ModelCapabilities
|
|
116
119
|
formatModelNames: boolean
|
|
120
|
+
modelNameTemplate?: string
|
|
121
|
+
providerName: string
|
|
117
122
|
providerId: string
|
|
118
123
|
}
|
|
119
124
|
const refreshContexts = new Map<string, RefreshContext>()
|
|
@@ -231,6 +236,20 @@ export function readFormatModelNames(options: Record<string, unknown>): boolean
|
|
|
231
236
|
return options.formatModelNames !== false
|
|
232
237
|
}
|
|
233
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
|
+
|
|
234
253
|
/**
|
|
235
254
|
* Overlay metadata onto a `/v1/models` entry in three tiers: the entry's
|
|
236
255
|
* own fields win, `/v1/model/info` fills gaps (notably `mode`, which
|
|
@@ -276,6 +295,14 @@ function enrichModel(
|
|
|
276
295
|
*/
|
|
277
296
|
const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
|
|
278
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
|
+
|
|
279
306
|
/**
|
|
280
307
|
* Convert a discovered LiteLLM model into an OpenCode config-level
|
|
281
308
|
* model entry (the shape used in `provider.*.models` inside
|
|
@@ -283,20 +310,29 @@ const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
|
|
|
283
310
|
* image, audio) — they can't be used as primary chat models and would
|
|
284
311
|
* clutter the picker.
|
|
285
312
|
*
|
|
286
|
-
* Exported for tests: `
|
|
287
|
-
*
|
|
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`.
|
|
288
316
|
*/
|
|
289
317
|
export function toConfigModel(
|
|
290
318
|
model: LiteLLMModel,
|
|
291
319
|
info?: LiteLLMModelInfo,
|
|
292
|
-
|
|
320
|
+
naming: ModelNaming = {},
|
|
293
321
|
): Record<string, unknown> | null {
|
|
294
322
|
const type = categorizeModel(model)
|
|
295
323
|
if (type === 'embedding' || type === 'image' || type === 'audio') {
|
|
296
324
|
return null
|
|
297
325
|
}
|
|
326
|
+
const providerId = naming.providerId ?? ''
|
|
298
327
|
const entry: Record<string, unknown> = {
|
|
299
|
-
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
|
+
}),
|
|
300
336
|
}
|
|
301
337
|
// Some deployments only report the OpenAI-style `max_tokens` total;
|
|
302
338
|
// use it as the context limit when `max_input_tokens` is absent.
|
|
@@ -389,9 +425,9 @@ export interface DiscoveredModels {
|
|
|
389
425
|
* classifies + formats each model, and returns the built entries plus the
|
|
390
426
|
* ids that require the Responses API and per-model hints. The provider's
|
|
391
427
|
* `includeModels`/`excludeModels` filters, `modelCapabilities` overrides and
|
|
392
|
-
* `formatModelNames`
|
|
393
|
-
* path that persists or serves a cache — cold
|
|
394
|
-
* 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.
|
|
395
431
|
*
|
|
396
432
|
* Returns `null` when the proxy is unreachable/unauthorized or exposes
|
|
397
433
|
* no models, so callers can distinguish "no data" from "empty result".
|
|
@@ -403,7 +439,7 @@ export async function discoverModels(
|
|
|
403
439
|
providerId: string,
|
|
404
440
|
filters: ModelFilters = {},
|
|
405
441
|
capabilities: ModelCapabilities = {},
|
|
406
|
-
|
|
442
|
+
naming: ModelNaming = {},
|
|
407
443
|
): Promise<DiscoveredModels | null> {
|
|
408
444
|
if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
|
|
409
445
|
log(
|
|
@@ -478,7 +514,7 @@ export async function discoverModels(
|
|
|
478
514
|
const info = infoByName?.get(model.id)
|
|
479
515
|
if (infoByName && !info) unmatched.push(model.id)
|
|
480
516
|
const enriched = enrichModel(model, info, capabilities[model.id])
|
|
481
|
-
const entry = toConfigModel(enriched, info,
|
|
517
|
+
const entry = toConfigModel(enriched, info, { ...naming, providerId })
|
|
482
518
|
if (!entry) {
|
|
483
519
|
skipped++
|
|
484
520
|
continue
|
|
@@ -573,10 +609,14 @@ function ensureResponsesProvider(
|
|
|
573
609
|
const provider = config.provider[id] as Record<string, unknown>
|
|
574
610
|
if (!provider.npm) provider.npm = RESPONSES_NPM
|
|
575
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.
|
|
576
616
|
const baseName =
|
|
577
617
|
typeof baseProvider.name === 'string' && baseProvider.name
|
|
578
618
|
? baseProvider.name
|
|
579
|
-
:
|
|
619
|
+
: baseProviderId
|
|
580
620
|
provider.name = `${baseName} Responses`
|
|
581
621
|
}
|
|
582
622
|
if (!provider.options || typeof provider.options !== 'object') {
|
|
@@ -626,6 +666,35 @@ function readHeaderMap(value: unknown): Record<string, string> {
|
|
|
626
666
|
return out
|
|
627
667
|
}
|
|
628
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
|
+
|
|
629
698
|
/**
|
|
630
699
|
* Split freshly discovered entries into the chat provider and the Responses
|
|
631
700
|
* sibling, injecting each side without clobbering curated entries. Returns
|
|
@@ -642,27 +711,38 @@ function injectDiscoveredModels(
|
|
|
642
711
|
baseURL: string,
|
|
643
712
|
apiKey: string | undefined,
|
|
644
713
|
customHeaders: Record<string, string> | undefined,
|
|
645
|
-
runtimeFetch
|
|
714
|
+
runtimeFetch: typeof fetch | undefined,
|
|
715
|
+
naming: ModelNaming,
|
|
646
716
|
): string[] {
|
|
647
717
|
const responsesSet = new Set(responsesIds)
|
|
648
|
-
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
|
|
649
730
|
const siblingModelsExisting: Record<string, unknown> =
|
|
650
731
|
existingSibling &&
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
? ((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>)
|
|
655
735
|
: {}
|
|
656
736
|
|
|
657
737
|
const chatEntries: Record<string, unknown> = {}
|
|
658
|
-
const
|
|
738
|
+
const responsesIdsToInject: string[] = []
|
|
659
739
|
for (const [id, entry] of Object.entries(entries)) {
|
|
660
740
|
// A model already present under the other provider was curated there (or
|
|
661
741
|
// injected by an earlier run); leave it alone instead of duplicating it
|
|
662
742
|
// across both providers.
|
|
663
743
|
if (responsesSet.has(id)) {
|
|
664
744
|
if (Object.hasOwn(baseModels, id)) continue
|
|
665
|
-
|
|
745
|
+
responsesIdsToInject.push(id)
|
|
666
746
|
} else {
|
|
667
747
|
if (Object.hasOwn(siblingModelsExisting, id)) continue
|
|
668
748
|
chatEntries[id] = entry
|
|
@@ -670,7 +750,7 @@ function injectDiscoveredModels(
|
|
|
670
750
|
}
|
|
671
751
|
|
|
672
752
|
const added = mergeModels(baseModels, chatEntries)
|
|
673
|
-
if (
|
|
753
|
+
if (responsesIdsToInject.length > 0) {
|
|
674
754
|
const siblingModels = ensureResponsesProvider(
|
|
675
755
|
config,
|
|
676
756
|
baseProviderId,
|
|
@@ -680,6 +760,26 @@ function injectDiscoveredModels(
|
|
|
680
760
|
customHeaders,
|
|
681
761
|
runtimeFetch,
|
|
682
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
|
+
}
|
|
683
783
|
added.push(...mergeModels(siblingModels, responsesEntries))
|
|
684
784
|
}
|
|
685
785
|
return added
|
|
@@ -712,7 +812,12 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
|
|
|
712
812
|
ctx.providerId,
|
|
713
813
|
ctx.filters,
|
|
714
814
|
ctx.capabilities,
|
|
715
|
-
|
|
815
|
+
{
|
|
816
|
+
formatModelNames: ctx.formatModelNames,
|
|
817
|
+
modelNameTemplate: ctx.modelNameTemplate,
|
|
818
|
+
providerId: ctx.providerId,
|
|
819
|
+
providerName: ctx.providerName,
|
|
820
|
+
},
|
|
716
821
|
),
|
|
717
822
|
DISCOVERY_TIMEOUT_MS,
|
|
718
823
|
)
|
|
@@ -870,6 +975,12 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
870
975
|
const filters = readModelFilters(options)
|
|
871
976
|
const capabilities = parseModelCapabilities(options.modelCapabilities)
|
|
872
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 }
|
|
873
984
|
|
|
874
985
|
// Resolve base URL
|
|
875
986
|
let baseURL: string | null = null
|
|
@@ -944,6 +1055,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
944
1055
|
// the provider keeps its models and can be reconnected from `/connect`.
|
|
945
1056
|
const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities, {
|
|
946
1057
|
formatModelNames,
|
|
1058
|
+
modelNameTemplate,
|
|
1059
|
+
providerName,
|
|
947
1060
|
}, sso ? ssoIdentity(sso) : apiKey)
|
|
948
1061
|
|
|
949
1062
|
// Remember how to reach this proxy so the `event` hook can
|
|
@@ -960,6 +1073,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
960
1073
|
filters,
|
|
961
1074
|
capabilities,
|
|
962
1075
|
formatModelNames,
|
|
1076
|
+
modelNameTemplate,
|
|
1077
|
+
providerName,
|
|
963
1078
|
providerId,
|
|
964
1079
|
})
|
|
965
1080
|
|
|
@@ -1006,6 +1121,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
1006
1121
|
runtimeKey,
|
|
1007
1122
|
customHeaders,
|
|
1008
1123
|
runtimeFetch,
|
|
1124
|
+
naming,
|
|
1009
1125
|
)
|
|
1010
1126
|
injectedModelIds.set(cacheKey, new Set(added))
|
|
1011
1127
|
log(
|
|
@@ -1026,7 +1142,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
1026
1142
|
providerId,
|
|
1027
1143
|
filters,
|
|
1028
1144
|
capabilities,
|
|
1029
|
-
formatModelNames,
|
|
1145
|
+
{ formatModelNames, modelNameTemplate, providerId, providerName },
|
|
1030
1146
|
),
|
|
1031
1147
|
DISCOVERY_TIMEOUT_MS,
|
|
1032
1148
|
)
|
|
@@ -1042,6 +1158,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
|
|
|
1042
1158
|
runtimeKey,
|
|
1043
1159
|
customHeaders,
|
|
1044
1160
|
runtimeFetch,
|
|
1161
|
+
naming,
|
|
1045
1162
|
)
|
|
1046
1163
|
injectedModelIds.set(cacheKey, new Set(added))
|
|
1047
1164
|
writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
|
package/src/plugin/v2.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
readCustomHeaders,
|
|
10
10
|
readFormatModelNames,
|
|
11
11
|
readModelFilters,
|
|
12
|
+
readModelNameTemplate,
|
|
12
13
|
withTimeout,
|
|
13
14
|
LiteLLMPlugin,
|
|
14
15
|
} from './index'
|
|
@@ -109,14 +110,40 @@ interface ProviderSource {
|
|
|
109
110
|
capabilities: ModelCapabilities
|
|
110
111
|
compatibility: ModelCompatibility
|
|
111
112
|
formatModelNames: boolean
|
|
113
|
+
modelNameTemplate?: string
|
|
114
|
+
providerName: string
|
|
112
115
|
cacheKey: string
|
|
113
116
|
models: Model.Info[]
|
|
114
117
|
/**
|
|
115
118
|
* Model ids this plugin injected into the provider registry (as opposed
|
|
116
119
|
* to ids the user curated in config). Only these are eligible to be
|
|
117
|
-
* removed when a later refresh no longer discovers them
|
|
120
|
+
* removed when a later refresh no longer discovers them — and even then
|
|
121
|
+
* only while the merge can match the live entry against what the plugin
|
|
122
|
+
* last published for the id (see mergeProviderModels).
|
|
118
123
|
*/
|
|
119
124
|
ownedModelIds: Set<string>
|
|
125
|
+
/**
|
|
126
|
+
* Snapshots of the registry entries this plugin last published for the
|
|
127
|
+
* ids in {@link ownedModelIds}, as far as the last merge could recognize
|
|
128
|
+
* them. Bookkeeping for replacements: a source replacing a predecessor
|
|
129
|
+
* under the same id inherits this record so its first merge can tell the
|
|
130
|
+
* predecessor's own output from entries that were edited afterwards
|
|
131
|
+
* (see {@link supersededModels}). Content comparison is a heuristic, not
|
|
132
|
+
* proof of authorship — see mergeProviderModels for what that does and
|
|
133
|
+
* does not guarantee.
|
|
134
|
+
*/
|
|
135
|
+
publishedModels: Map<string, Model.Info>
|
|
136
|
+
/**
|
|
137
|
+
* Snapshot record inherited from the source this one replaced, spent by
|
|
138
|
+
* the first merge that runs after the swap. A live entry that still
|
|
139
|
+
* matches its snapshot is treated as the predecessor's own output and is
|
|
140
|
+
* re-rendered from the new source (or dropped when the new inventory no
|
|
141
|
+
* longer serves it); an entry that differs was changed afterwards — user
|
|
142
|
+
* curation or a host edit, the merge cannot tell which — and is kept
|
|
143
|
+
* untouched, with the id released. Undefined outside that first
|
|
144
|
+
* post-swap merge.
|
|
145
|
+
*/
|
|
146
|
+
supersededModels: ReadonlyMap<string, Model.Info> | undefined
|
|
120
147
|
}
|
|
121
148
|
|
|
122
149
|
function asRecord(value: unknown): Record<string, unknown> {
|
|
@@ -259,39 +286,176 @@ function numberOrDefault(value: unknown, fallback: number): number {
|
|
|
259
286
|
: fallback
|
|
260
287
|
}
|
|
261
288
|
|
|
289
|
+
/**
|
|
290
|
+
* Host-side id stamps: the registry keys entries by provider and model id and
|
|
291
|
+
* the host fills these fields itself when reading entries back, so they are
|
|
292
|
+
* excluded from content identity.
|
|
293
|
+
*/
|
|
294
|
+
const EXCLUDED_IDENTITY_FIELDS: ReadonlySet<string> = new Set(['providerID', 'modelID'])
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Content comparison between a live registry entry and a recorded snapshot.
|
|
298
|
+
* The plugin renders identical facts into structurally identical entries,
|
|
299
|
+
* so a match is treated as an indication the entry is this plugin's own
|
|
300
|
+
* earlier output — a heuristic, not proof. A user-curated entry almost
|
|
301
|
+
* always differs (most visibly in `name`, but also e.g. `enabled` or
|
|
302
|
+
* `settings`); a curated entry that happens to exactly match the plugin's
|
|
303
|
+
* rendering would be treated as plugin output and could be replaced or
|
|
304
|
+
* removed. An unanticipated host edit of
|
|
305
|
+
* any other field can only cause a missed match — the entry is then kept
|
|
306
|
+
* rather than replaced, which fails safe: user content is never deleted on
|
|
307
|
+
* a missed match, but could be replaced or removed on a spurious one.
|
|
308
|
+
*/
|
|
309
|
+
function sameEntry(a: Model.Info, b: Model.Info): boolean {
|
|
310
|
+
const keys = new Set([
|
|
311
|
+
...Object.keys(a as Record<string, unknown>),
|
|
312
|
+
...Object.keys(b as Record<string, unknown>),
|
|
313
|
+
])
|
|
314
|
+
for (const key of keys) {
|
|
315
|
+
if (EXCLUDED_IDENTITY_FIELDS.has(key)) continue
|
|
316
|
+
if (!deeplyEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) {
|
|
317
|
+
return false
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return true
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function deeplyEqual(a: unknown, b: unknown): boolean {
|
|
324
|
+
if (a === b) return true
|
|
325
|
+
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
|
|
326
|
+
return false
|
|
327
|
+
}
|
|
328
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
329
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
|
|
330
|
+
return a.every((item, index) => deeplyEqual(item, b[index]))
|
|
331
|
+
}
|
|
332
|
+
const recordA = a as Record<string, unknown>
|
|
333
|
+
const recordB = b as Record<string, unknown>
|
|
334
|
+
const keysA = Object.keys(recordA).sort()
|
|
335
|
+
const keysB = Object.keys(recordB).sort()
|
|
336
|
+
if (keysA.length !== keysB.length) return false
|
|
337
|
+
return keysA.every(
|
|
338
|
+
(key, index) => keysB[index] === key && deeplyEqual(recordA[key], recordB[key]),
|
|
339
|
+
)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Snapshot a registry entry for the provenance record. A deep clone, so a
|
|
344
|
+
* host (or a later transform) mutating the published entry in place cannot
|
|
345
|
+
* drag the record along with it — the recorded content stays what was
|
|
346
|
+
* actually published, and any such edit reads back as "no longer ours".
|
|
347
|
+
* Model entries are plain JSON-shaped schema data, so a JSON round-trip
|
|
348
|
+
* is a faithful clone.
|
|
349
|
+
*/
|
|
350
|
+
function recordEntry(model: Model.Info): Model.Info {
|
|
351
|
+
return JSON.parse(JSON.stringify(model)) as Model.Info
|
|
352
|
+
}
|
|
353
|
+
|
|
262
354
|
/**
|
|
263
355
|
* Merge freshly discovered models into a provider's current model set.
|
|
264
356
|
*
|
|
265
|
-
* Previously-discovered ids owned by this plugin are
|
|
266
|
-
* refresh reflects LiteLLM's current inventory;
|
|
267
|
-
*
|
|
268
|
-
*
|
|
357
|
+
* Previously-discovered ids owned by this plugin are kept/dropped so a
|
|
358
|
+
* refresh reflects LiteLLM's current inventory; distinguishable curated
|
|
359
|
+
* entries are preserved. Returns the merged list, the set of ids
|
|
360
|
+
* the plugin now owns, and the provenance record: snapshots of the last
|
|
361
|
+
* published entries for every owned id the merge could still recognize
|
|
362
|
+
* as the plugin's own output. Entries the merge kept but could no longer
|
|
363
|
+
* match (the live content changed after publication) stay owned per the
|
|
364
|
+
* steady-state semantics but drop out of the record, so a later
|
|
365
|
+
* replacement treats them as user-edited.
|
|
366
|
+
*
|
|
367
|
+
* A source that just replaced a predecessor carries the predecessor's
|
|
368
|
+
* provenance record in `superseded`. A live entry that matches its
|
|
369
|
+
* snapshot is treated as the predecessor's own stale output — the fresh
|
|
370
|
+
* discovery takes the id over (re-rendering it with the new provider's
|
|
371
|
+
* `providerName`/`modelNameTemplate`), or drops it when the new gateway
|
|
372
|
+
* no longer serves it. An entry that differs was changed after the
|
|
373
|
+
* predecessor published it — user curation or a host edit, which the
|
|
374
|
+
* merge cannot distinguish — and survives untouched, with the id
|
|
375
|
+
* released so later refreshes never remove it. The snapshot record is
|
|
376
|
+
* spent after this first post-swap merge, restoring the steady-state
|
|
377
|
+
* semantics for every later merge.
|
|
378
|
+
*
|
|
379
|
+
* Both recognitions rely on content comparison, a heuristic rather than
|
|
380
|
+
* proof of authorship. It errs toward keeping entries: deletion requires
|
|
381
|
+
* an owned id that still matches its last published snapshot, so user
|
|
382
|
+
* content is never deleted on a missed match. A curated entry that exactly
|
|
383
|
+
* matches the plugin's rendering can be replaced or removed.
|
|
269
384
|
*/
|
|
270
385
|
function mergeProviderModels(
|
|
271
386
|
configured: Iterable<Model.Info>,
|
|
272
387
|
discovered: readonly Model.Info[],
|
|
273
388
|
owned: ReadonlySet<string>,
|
|
274
|
-
|
|
389
|
+
superseded?: ReadonlyMap<string, Model.Info>,
|
|
390
|
+
published?: ReadonlyMap<string, Model.Info>,
|
|
391
|
+
): { models: Model.Info[]; owned: Set<string>; published: Map<string, Model.Info> } {
|
|
275
392
|
const discoveredIds = new Set(discovered.map((model) => model.id))
|
|
276
393
|
const result = new Map<string, Model.Info>()
|
|
277
394
|
const nextOwned = new Set<string>()
|
|
395
|
+
// Snapshots carried into this merge for owned ids: the predecessor's
|
|
396
|
+
// publications (first post-swap merge) or the plugin's own last published
|
|
397
|
+
// snapshots (steady state).
|
|
398
|
+
const carriedSnapshots = new Map<string, Model.Info>()
|
|
399
|
+
for (const [id, snapshot] of superseded ?? published ?? []) carriedSnapshots.set(id, snapshot)
|
|
278
400
|
|
|
279
401
|
for (const model of configured) {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
402
|
+
const snapshot = superseded?.get(model.id)
|
|
403
|
+
if (snapshot !== undefined) {
|
|
404
|
+
if (sameEntry(model, snapshot)) {
|
|
405
|
+
// Treated as the predecessor's own output: get out of the way; the
|
|
406
|
+
// discovery pass below takes the id over, or nothing does when the
|
|
407
|
+
// new gateway no longer serves it.
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
410
|
+
// The entry differs from what the predecessor published, so it was
|
|
411
|
+
// changed afterwards - curated by the user or edited by the host,
|
|
412
|
+
// which this merge cannot tell apart. Keep it untouched and release
|
|
413
|
+
// the id from plugin ownership.
|
|
414
|
+
carriedSnapshots.delete(model.id)
|
|
415
|
+
result.set(model.id, model)
|
|
416
|
+
continue
|
|
417
|
+
}
|
|
418
|
+
if (!owned.has(model.id)) {
|
|
419
|
+
result.set(model.id, model)
|
|
420
|
+
continue
|
|
421
|
+
}
|
|
422
|
+
const carriedSnapshot = carriedSnapshots.get(model.id)
|
|
423
|
+
if (!discoveredIds.has(model.id)) {
|
|
424
|
+
// Only drop an undiscovered entry while it still matches the plugin's
|
|
425
|
+
// last published snapshot for the id. An owned id without a match
|
|
426
|
+
// (e.g. ownership inherited by a replacement while the user had
|
|
427
|
+
// already curated the id) has no evidence it is plugin output, so it
|
|
428
|
+
// is kept and released, never deleted.
|
|
429
|
+
if (carriedSnapshot !== undefined && sameEntry(model, carriedSnapshot)) continue
|
|
430
|
+
result.set(model.id, model)
|
|
431
|
+
continue
|
|
432
|
+
}
|
|
433
|
+
// Still discovered and owned: keep the live entry (steady-state
|
|
434
|
+
// semantics keep it even when discovery would render different content)
|
|
435
|
+
// and keep the carried snapshot so provenance survives content changes.
|
|
283
436
|
result.set(model.id, model)
|
|
284
|
-
|
|
437
|
+
nextOwned.add(model.id)
|
|
438
|
+
if (carriedSnapshot !== undefined) carriedSnapshots.set(model.id, carriedSnapshot)
|
|
285
439
|
}
|
|
286
440
|
|
|
287
441
|
for (const model of discovered) {
|
|
288
442
|
if (!result.has(model.id)) {
|
|
289
443
|
result.set(model.id, model)
|
|
290
444
|
nextOwned.add(model.id)
|
|
445
|
+
carriedSnapshots.set(model.id, recordEntry(model))
|
|
291
446
|
}
|
|
292
447
|
}
|
|
293
448
|
|
|
294
|
-
|
|
449
|
+
// Rolling provenance record: every owned id keeps the snapshot of the
|
|
450
|
+
// last entry the plugin published for it.
|
|
451
|
+
const nextPublished = new Map<string, Model.Info>()
|
|
452
|
+
for (const [id, model] of result) {
|
|
453
|
+
if (!nextOwned.has(id)) continue
|
|
454
|
+
const snapshot = carriedSnapshots.get(id)
|
|
455
|
+
if (snapshot !== undefined) nextPublished.set(id, snapshot)
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
return { models: [...result.values()], owned: nextOwned, published: nextPublished }
|
|
295
459
|
}
|
|
296
460
|
|
|
297
461
|
function runtimeSettings(source: ProviderSource): Record<string, unknown> {
|
|
@@ -307,6 +471,7 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
|
|
|
307
471
|
'modelCapabilities',
|
|
308
472
|
'modelCompatibility',
|
|
309
473
|
'formatModelNames',
|
|
474
|
+
'modelNameTemplate',
|
|
310
475
|
'providerID',
|
|
311
476
|
]) {
|
|
312
477
|
delete settings[key]
|
|
@@ -409,6 +574,12 @@ async function makeProviderSource(
|
|
|
409
574
|
const capabilities = parseModelCapabilities(settings.modelCapabilities)
|
|
410
575
|
const compatibility = parseModelCompatibility(settings.modelCompatibility)
|
|
411
576
|
const formatModelNames = readFormatModelNames(settings)
|
|
577
|
+
const modelNameTemplate = readModelNameTemplate(settings)
|
|
578
|
+
// The provider's configured name, or its id when none is set — the same
|
|
579
|
+
// fallback `{provider_name}` documents, so two unnamed providers stay
|
|
580
|
+
// distinguishable.
|
|
581
|
+
const providerName = provider?.name || id
|
|
582
|
+
const naming = { formatModelNames, modelNameTemplate, providerId: id, providerName }
|
|
412
583
|
// Explicit config beats the URL typed into the dialog, which beats the
|
|
413
584
|
// environment and local port probing.
|
|
414
585
|
const detectedBaseURL = configuredBaseURL
|
|
@@ -432,9 +603,7 @@ async function makeProviderSource(
|
|
|
432
603
|
// the raw key): a credential change starts a fresh discovery instead of
|
|
433
604
|
// serving another credential's cached model list. A sign-in is keyed by its
|
|
434
605
|
// credential id, because its access token rotates on every refresh.
|
|
435
|
-
const cacheKey = buildCacheKey(id, baseURL, filters, capabilities,
|
|
436
|
-
formatModelNames,
|
|
437
|
-
}, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey)
|
|
606
|
+
const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, naming, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey)
|
|
438
607
|
const cacheEntry = readModelCacheEntry(cacheKey)
|
|
439
608
|
let entries = cacheEntry?.models ?? null
|
|
440
609
|
let responsesIds = cacheEntry?.responsesIds ?? []
|
|
@@ -449,7 +618,7 @@ async function makeProviderSource(
|
|
|
449
618
|
id,
|
|
450
619
|
filters,
|
|
451
620
|
capabilities,
|
|
452
|
-
|
|
621
|
+
naming,
|
|
453
622
|
),
|
|
454
623
|
DISCOVERY_TIMEOUT_MS,
|
|
455
624
|
)
|
|
@@ -490,6 +659,8 @@ async function makeProviderSource(
|
|
|
490
659
|
capabilities,
|
|
491
660
|
compatibility,
|
|
492
661
|
formatModelNames,
|
|
662
|
+
modelNameTemplate,
|
|
663
|
+
providerName,
|
|
493
664
|
cacheKey,
|
|
494
665
|
models: toProviderModels(id, entries ?? {}, {
|
|
495
666
|
providerPackage,
|
|
@@ -498,6 +669,8 @@ async function makeProviderSource(
|
|
|
498
669
|
compatibility,
|
|
499
670
|
}),
|
|
500
671
|
ownedModelIds: new Set<string>(),
|
|
672
|
+
publishedModels: new Map<string, Model.Info>(),
|
|
673
|
+
supersededModels: undefined,
|
|
501
674
|
}
|
|
502
675
|
}
|
|
503
676
|
|
|
@@ -549,7 +722,12 @@ async function refreshProviderSource(
|
|
|
549
722
|
source.id,
|
|
550
723
|
source.filters,
|
|
551
724
|
source.capabilities,
|
|
552
|
-
|
|
725
|
+
{
|
|
726
|
+
formatModelNames: source.formatModelNames,
|
|
727
|
+
modelNameTemplate: source.modelNameTemplate,
|
|
728
|
+
providerId: source.id,
|
|
729
|
+
providerName: source.providerName,
|
|
730
|
+
},
|
|
553
731
|
),
|
|
554
732
|
DISCOVERY_TIMEOUT_MS,
|
|
555
733
|
)
|
|
@@ -717,6 +895,18 @@ async function reconcileProviderSources(
|
|
|
717
895
|
if (existing && !existing.fromFallback && !existing.pendingPublication) continue
|
|
718
896
|
const source = await makeProviderSource(context, provider, pluginOptions)
|
|
719
897
|
if (!source) continue
|
|
898
|
+
// A source replacing this id's predecessor inherits its provenance
|
|
899
|
+
// record: the exact entries the predecessor published (or an inherited
|
|
900
|
+
// snapshot the predecessor itself had not spent yet). `providerName` and
|
|
901
|
+
// `modelNameTemplate` are baked into discovered names at discovery time,
|
|
902
|
+
// and ids alone cannot distinguish the plugin's stale rendering from an
|
|
903
|
+
// entry the user curated under the same id — so the successor carries the
|
|
904
|
+
// entries themselves, and its first merge replaces only entries that
|
|
905
|
+
// still match (see mergeProviderModels). For a fallback predecessor this
|
|
906
|
+
// is what re-renders its output with the configured provider's naming;
|
|
907
|
+
// for a pending configured one it can only affect entries the failed
|
|
908
|
+
// attempt actually published.
|
|
909
|
+
if (existing) source.supersededModels = existing.supersededModels ?? existing.publishedModels
|
|
720
910
|
sources.set(source.id, source)
|
|
721
911
|
changed.push(source)
|
|
722
912
|
}
|
|
@@ -736,8 +926,9 @@ async function reconcileProviderSources(
|
|
|
736
926
|
* options/config): a fallback only stands in until a real endpoint is
|
|
737
927
|
* known, so the dialog's answers take over from it. Explicit option/env
|
|
738
928
|
* baseURLs — and host-registered providers — keep winning and are never
|
|
739
|
-
* replaced. Replaced sources
|
|
740
|
-
*
|
|
929
|
+
* replaced. Replaced sources carry their provenance record (the exact
|
|
930
|
+
* entries they published) so the successor's first merge re-renders its own
|
|
931
|
+
* stale output while preserving curated entries, and sources
|
|
741
932
|
* replaced under a different id are dropped from `sources` and marked in
|
|
742
933
|
* `staleProviderIds` for removal from the provider registry.
|
|
743
934
|
*/
|
|
@@ -754,7 +945,13 @@ async function publishConnectedSource(
|
|
|
754
945
|
const existing = sources.get(source.id)
|
|
755
946
|
if (existing && !(existing.fromFallback && !readString(existing.settings.baseURL))) return
|
|
756
947
|
const previous = existing ?? replacing.find((candidate) => candidate.id === source.id)
|
|
757
|
-
|
|
948
|
+
// Same carry as a configured provider replacing a fallback: the exact
|
|
949
|
+
// entries the predecessor published let the first merge replace only
|
|
950
|
+
// the predecessor's own output and preserve curated entries.
|
|
951
|
+
if (previous) {
|
|
952
|
+
source.ownedModelIds = new Set(previous.ownedModelIds)
|
|
953
|
+
source.supersededModels = previous.supersededModels ?? previous.publishedModels
|
|
954
|
+
}
|
|
758
955
|
for (const previousSource of replacing) {
|
|
759
956
|
if (previousSource.id === source.id) continue
|
|
760
957
|
const mapped = sources.get(previousSource.id)
|
|
@@ -851,11 +1048,23 @@ const definition = Plugin.define({
|
|
|
851
1048
|
current.models.values(),
|
|
852
1049
|
source.models,
|
|
853
1050
|
source.ownedModelIds,
|
|
1051
|
+
source.supersededModels,
|
|
1052
|
+
source.publishedModels,
|
|
854
1053
|
)
|
|
855
1054
|
source.ownedModelIds = merged.owned
|
|
1055
|
+
source.publishedModels = merged.published
|
|
1056
|
+
// The one-shot replacement snapshot is spent: later merges on this
|
|
1057
|
+
// source use the steady-state semantics alone.
|
|
1058
|
+
source.supersededModels = undefined
|
|
856
1059
|
editor.models.set(source.id, merged.models)
|
|
857
1060
|
} else {
|
|
858
1061
|
source.ownedModelIds = new Set(source.models.map((model) => model.id))
|
|
1062
|
+
source.publishedModels = new Map(
|
|
1063
|
+
source.models.map((model) => [model.id, recordEntry(model)]),
|
|
1064
|
+
)
|
|
1065
|
+
// Nothing to replace under a brand-new provider id: any inherited
|
|
1066
|
+
// snapshot is spent here too, so it never leaks into a later merge.
|
|
1067
|
+
source.supersededModels = undefined
|
|
859
1068
|
editor.add({
|
|
860
1069
|
info: {
|
|
861
1070
|
...Provider.Info.empty(Provider.ID.make(source.id)),
|
|
@@ -140,7 +140,7 @@ export function categorizeModel(model: LiteLLMModel): 'chat' | 'embedding' | 'im
|
|
|
140
140
|
* "litellm/kimi-k2.5" -> "Kimi K2.5"
|
|
141
141
|
* "litellm/minimax-m2.5" -> "MiniMax M2.5"
|
|
142
142
|
*/
|
|
143
|
-
export function formatModelName(model: LiteLLMModel): string {
|
|
143
|
+
export function formatModelName(model: Pick<LiteLLMModel, 'id'>): string {
|
|
144
144
|
const { id } = model
|
|
145
145
|
|
|
146
146
|
// Drop provider prefix when present, but only the FIRST segment, so
|
|
@@ -196,3 +196,56 @@ export function formatModelName(model: LiteLLMModel): string {
|
|
|
196
196
|
|
|
197
197
|
return tokens.join(' ') || id
|
|
198
198
|
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The naming choices that decide how a discovered model is displayed. They
|
|
202
|
+
* are baked into cached model entries, so the same object also feeds the
|
|
203
|
+
* cache identity (see `buildCacheKey` in `model-cache.ts`).
|
|
204
|
+
*/
|
|
205
|
+
export interface ModelNaming {
|
|
206
|
+
/** Prettify a model id into a display name; `false` keeps the raw id. */
|
|
207
|
+
formatModelNames?: boolean
|
|
208
|
+
/**
|
|
209
|
+
* Template applied to every discovered model's display name. Unset (or
|
|
210
|
+
* `"{name}"`) leaves today's names untouched. Known placeholders:
|
|
211
|
+
* `{name}`, `{id}`, `{provider_id}` and `{provider_name}`.
|
|
212
|
+
*/
|
|
213
|
+
modelNameTemplate?: string
|
|
214
|
+
/** Provider id/name used by the template's provider placeholders. */
|
|
215
|
+
providerId?: string
|
|
216
|
+
providerName?: string
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The template that reproduces today's names, so it counts as "unset". */
|
|
220
|
+
export const DEFAULT_MODEL_NAME_TEMPLATE = '{name}'
|
|
221
|
+
|
|
222
|
+
const NAME_TEMPLATE_PLACEHOLDER = /\{(name|id|provider_id|provider_name)\}/g
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Fill a `modelNameTemplate` with one model's values.
|
|
226
|
+
*
|
|
227
|
+
* Substitution is single-pass, so a value that itself contains a placeholder
|
|
228
|
+
* (`{id}` inside a display name, say) is inserted literally rather than
|
|
229
|
+
* expanded again. Unknown placeholders stay as written, which makes a typo
|
|
230
|
+
* visible in the picker instead of silently dropping the model's name.
|
|
231
|
+
*/
|
|
232
|
+
export function applyModelNameTemplate(
|
|
233
|
+
template: string | undefined,
|
|
234
|
+
values: { name: string; id: string; providerId: string; providerName: string },
|
|
235
|
+
): string {
|
|
236
|
+
if (template === undefined || template.trim() === '') return values.name
|
|
237
|
+
return template.replace(NAME_TEMPLATE_PLACEHOLDER, (placeholder: string, key: string) => {
|
|
238
|
+
switch (key) {
|
|
239
|
+
case 'name':
|
|
240
|
+
return values.name
|
|
241
|
+
case 'id':
|
|
242
|
+
return values.id
|
|
243
|
+
case 'provider_id':
|
|
244
|
+
return values.providerId
|
|
245
|
+
case 'provider_name':
|
|
246
|
+
return values.providerName
|
|
247
|
+
default:
|
|
248
|
+
return placeholder
|
|
249
|
+
}
|
|
250
|
+
})
|
|
251
|
+
}
|
package/src/utils/model-cache.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto'
|
|
|
2
2
|
import { readFileSync, mkdirSync, writeFileSync, renameSync, rmSync } from 'node:fs'
|
|
3
3
|
import { homedir, tmpdir } from 'node:os'
|
|
4
4
|
import { join } from 'node:path'
|
|
5
|
+
import type { ModelNaming } from './format-model-name'
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Facts about a discovered model's upstream that OpenCode 2 turns into
|
|
@@ -98,19 +99,23 @@ function canonicalize(value: unknown): string {
|
|
|
98
99
|
/**
|
|
99
100
|
* Cache identity for a provider's model view. `providerId@baseURL`
|
|
100
101
|
* alone isn't enough: `includeModels`/`excludeModels`,
|
|
101
|
-
* `modelCapabilities` and
|
|
102
|
-
* entries by discovery, so a
|
|
103
|
-
*
|
|
104
|
-
* restart. A fingerprint is appended
|
|
105
|
-
* (pattern order ignored); default configs keep
|
|
106
|
-
* existing caches stay warm across plugin upgrades.
|
|
102
|
+
* `modelCapabilities` and the naming choices (`formatModelNames`,
|
|
103
|
+
* `modelNameTemplate`) are baked into cached entries by discovery, so a
|
|
104
|
+
* config change must not reuse the old cache — it would keep serving the
|
|
105
|
+
* previous adjusted view until a second restart. A fingerprint is appended
|
|
106
|
+
* whenever adjustments exist (pattern order ignored); default configs keep
|
|
107
|
+
* the plain key so existing caches stay warm across plugin upgrades.
|
|
108
|
+
*
|
|
109
|
+
* `providerName` only matters when a template is set: `{provider_name}`
|
|
110
|
+
* resolves to it, so renaming a provider must start a fresh discovery too.
|
|
111
|
+
* The provider id is already part of the base key.
|
|
107
112
|
*/
|
|
108
113
|
export function buildCacheKey(
|
|
109
114
|
providerId: string,
|
|
110
115
|
baseURL: string,
|
|
111
116
|
filters: { includeModels?: string[]; excludeModels?: string[] },
|
|
112
117
|
capabilities: Record<string, Record<string, boolean>>,
|
|
113
|
-
naming:
|
|
118
|
+
naming: ModelNaming = {},
|
|
114
119
|
credential?: string,
|
|
115
120
|
): string {
|
|
116
121
|
let base = `${providerId}@${baseURL}`
|
|
@@ -122,21 +127,31 @@ export function buildCacheKey(
|
|
|
122
127
|
base += `@${createHash('sha256').update(credential).digest('hex').slice(0, 12)}`
|
|
123
128
|
}
|
|
124
129
|
const rawNames = naming.formatModelNames === false
|
|
130
|
+
const template = naming.modelNameTemplate
|
|
125
131
|
const hasAdjustments =
|
|
126
132
|
(filters.includeModels?.length ?? 0) > 0 ||
|
|
127
133
|
(filters.excludeModels?.length ?? 0) > 0 ||
|
|
128
134
|
Object.keys(capabilities).length > 0 ||
|
|
129
|
-
rawNames
|
|
135
|
+
rawNames ||
|
|
136
|
+
template !== undefined
|
|
130
137
|
if (!hasAdjustments) return base
|
|
138
|
+
// Omitted keys stay out of the hash entirely: `undefined` would serialize
|
|
139
|
+
// as the literal string "undefined" and change every existing cache key.
|
|
140
|
+
const namingFingerprint: Record<string, unknown> = {}
|
|
141
|
+
// Omitted (not `true`) when formatting is on, so keys for configs that
|
|
142
|
+
// never touch this option are unchanged.
|
|
143
|
+
if (rawNames) namingFingerprint.formatModelNames = false
|
|
144
|
+
if (template !== undefined) {
|
|
145
|
+
namingFingerprint.modelNameTemplate = template
|
|
146
|
+
namingFingerprint.providerName = naming.providerName
|
|
147
|
+
}
|
|
131
148
|
const fingerprint = createHash('sha256')
|
|
132
149
|
.update(
|
|
133
150
|
canonicalize({
|
|
134
151
|
includeModels: filters.includeModels ? [...filters.includeModels].sort() : undefined,
|
|
135
152
|
excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
|
|
136
153
|
capabilities,
|
|
137
|
-
|
|
138
|
-
// configs that never touch this option are unchanged.
|
|
139
|
-
formatModelNames: rawNames ? false : undefined,
|
|
154
|
+
...namingFingerprint,
|
|
140
155
|
}),
|
|
141
156
|
)
|
|
142
157
|
.digest('hex')
|