opencode-plugin-litellm 1.9.0 → 1.11.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 CHANGED
@@ -73,7 +73,7 @@ also shows how to configure a provider directly in `opencode.json`.
73
73
  | 🔍 **Auto-detection** | Probes `localhost:4000`, `:8000`, `:8080` and adopts the first responsive proxy. |
74
74
  | 📡 **Dynamic discovery** | Queries `/v1/models` so your OpenCode model picker always reflects your live `model_list`. |
75
75
  | ⚡ **Stale-while-revalidate** | A warm disk cache supplies models without a network request. New sessions trigger a background refresh, and cache entries expire after 7 days. |
76
- | 🏷️ **Smart formatting** | Turns `anthropic/claude-3-5-sonnet` into `Claude 3.5 Sonnet` in the picker — handles versions, sizes, quantizations, and brand-cased names like `gpt-4o`. Set `formatModelNames: false` to keep the raw LiteLLM ids instead. |
76
+ | 🏷️ **Smart formatting** | Uses LiteLLM's `model_info.display_name` when set; otherwise turns `anthropic/claude-3-5-sonnet` into `Claude 3.5 Sonnet` in the picker — handles versions, sizes, quantizations, and brand-cased names like `gpt-4o`. Set `formatModelNames: false` to keep the raw LiteLLM ids instead. |
77
77
  | 🧠 **Modality-aware** | Enriches `/v1/models` entries with `/v1/model/info` (`mode`, token limits, capability flags) and hides embedding / image / audio models from the picker. Declares `temperature` support only for models whose `supported_openai_params` lists it, so OpenCode applies (and the user can set) a sampling temperature on exactly those models. |
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. |
@@ -472,7 +472,7 @@ Model classification (tool-call badge, attachments, reasoning, input modalities)
472
472
 
473
473
  ### Keeping raw model ids in the picker (`formatModelNames`)
474
474
 
475
- By default the plugin prettifies each discovered id into a display name — `anthropic/claude-3-5-sonnet` shows up as `Claude 3.5 Sonnet`. If you'd rather see your LiteLLM `model_list` aliases verbatim (for example because your team refers to models by those exact names, or the formatter mangles an internal naming scheme), turn formatting off:
475
+ By default the plugin uses the name LiteLLM reports in `model_info.display_name` when it is set, and otherwise prettifies the id — `anthropic/claude-3-5-sonnet` shows up as `Claude 3.5 Sonnet`. If you'd rather see your LiteLLM `model_list` aliases verbatim (for example because your team refers to models by those exact names, or the formatter mangles an internal naming scheme), turn formatting off:
476
476
 
477
477
  ```jsonc
478
478
  {
@@ -487,11 +487,57 @@ By default the plugin prettifies each discovered id into a display name — `ant
487
487
  }
488
488
  ```
489
489
 
490
- - The display name becomes the exact model id as returned by `/v1/models` (provider prefix, version suffixes and all). Nothing else changes — ids, capability flags, pricing and filtering behave exactly as before.
490
+ - With formatting off, the display name becomes the exact model id as returned by `/v1/models` (provider prefix, version suffixes and all). Nothing else changes — ids, capability flags, pricing and filtering behave exactly as before.
491
+ - With formatting on, a valid `model_info.display_name` replaces the formatted id. Empty, whitespace-only and non-string values are ignored.
492
+ - An explicit `models.<id>.name` always wins; `formatModelNames: false` keeps the raw id even when `display_name` is set.
491
493
  - Only a boolean `false` disables formatting; omitting the option or setting anything else keeps the default.
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.
494
+ - 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. A changed `display_name` is picked up by the existing background refresh (on OpenCode 1 it appears after the following start).
493
495
  - 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
496
 
497
+ ### Naming models per provider (`modelNameTemplate`)
498
+
499
+ 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:
500
+
501
+ ```jsonc
502
+ {
503
+ "providers": {
504
+ "litellm-team-a": {
505
+ "name": "Team A",
506
+ "settings": {
507
+ "baseURL": "https://litellm.example.com/v1",
508
+ "apiKey": "{env:KEY_A}",
509
+ "modelNameTemplate": "{name} ({provider_name})"
510
+ }
511
+ },
512
+ "litellm-team-b": {
513
+ "name": "Team B",
514
+ "settings": {
515
+ "baseURL": "https://litellm.example.com/v1",
516
+ "apiKey": "{env:KEY_B}",
517
+ "modelNameTemplate": "[B] {name}"
518
+ }
519
+ }
520
+ }
521
+ }
522
+ ```
523
+
524
+ `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.
525
+
526
+ | Placeholder | Value |
527
+ | --- | --- |
528
+ | `{name}` | The display name the plugin resolved — LiteLLM's `display_name` when valid, otherwise the formatted id, or the raw id when `formatModelNames: false` |
529
+ | `{id}` | The model id exactly as `/v1/models` returned it |
530
+ | `{provider_id}` | The OpenCode provider id, for example `litellm-team-a` |
531
+ | `{provider_name}` | The provider's configured `name`, or its id when no name is set |
532
+
533
+ - The default is `{name}`, so omitting the setting changes nothing.
534
+ - An explicit `models.<id>.name` still wins and is never templated.
535
+ - Unknown placeholders are left as written, and substitution is single-pass: a placeholder that appears inside a resolved value stays literal.
536
+ - Non-string and empty values are ignored.
537
+ - 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`).
538
+ - 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.
539
+ - Model ids, capability flags, pricing and filtering are unaffected.
540
+
495
541
  ### Prompt caching (`modelCompatibility`)
496
542
 
497
543
  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.
@@ -559,7 +605,7 @@ sequenceDiagram
559
605
  2. If `providers.litellm` exists, its `settings.baseURL` is used. Otherwise common ports are probed — that probe is the only health check (3 s fail-fast per port).
560
606
  3. With a configured `baseURL` the proxy is not contacted during startup unless the cache is cold; the discovery fetch itself fails fast if the proxy is unreachable.
561
607
  4. **Fast path:** if a fresh on-disk cache exists (≤ 7 days old), its models are registered synchronously — startup does not wait on network discovery.
562
- 5. **Cold path:** `/v1/models` and `/v1/model/info` are fetched in parallel. Models are enriched with info metadata (`mode`, token limits, capability flags, per-token pricing — `/v1/models` omits these for database-defined models) and converted into OpenCode model entries with formatted `name`, inferred `modalities`, and `cost` (USD/1M tokens, converted from LiteLLM's USD/token). Non-chat models (embedding / image / audio) are excluded from the picker.
608
+ 5. **Cold path:** `/v1/models` and `/v1/model/info` are fetched in parallel. Models are enriched with info metadata (`mode`, token limits, capability flags, per-token pricing — `/v1/models` omits these for database-defined models) and converted into OpenCode model entries with a resolved `name`, inferred `modalities`, and `cost` (USD/1M tokens, converted from LiteLLM's USD/token). Non-chat models (embedding / image / audio) are excluded from the picker.
563
609
  6. Discovered models are added alongside user-defined models — never overwriting them — and persisted to the cache.
564
610
  7. On `session.created`, the cache is revalidated in the background (throttled to once per 5 minutes). V2 calls `provider.reload()` when the inventory changes; V1 surfaces refreshed entries on the next OpenCode start. The cold path is capped by a 20 s timeout.
565
611
 
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.9.0",
4
+ "version": "1.11.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",
@@ -8,8 +8,12 @@ import {
8
8
  normalizeBaseURL,
9
9
  } from '../utils/litellm-api'
10
10
  import {
11
- formatModelName,
11
+ applyModelNameTemplate,
12
+ DEFAULT_MODEL_NAME_TEMPLATE,
13
+ normalizeModelDisplayName,
14
+ resolveModelDisplayName,
12
15
  categorizeModel,
16
+ type ModelNaming,
13
17
  } from '../utils/format-model-name'
14
18
  import { requiresResponsesAPI } from '../utils/transport'
15
19
  import type { LiteLLMModel, LiteLLMModelInfo } from '../types'
@@ -114,6 +118,8 @@ interface RefreshContext {
114
118
  filters: ModelFilters
115
119
  capabilities: ModelCapabilities
116
120
  formatModelNames: boolean
121
+ modelNameTemplate?: string
122
+ providerName: string
117
123
  providerId: string
118
124
  }
119
125
  const refreshContexts = new Map<string, RefreshContext>()
@@ -231,6 +237,20 @@ export function readFormatModelNames(options: Record<string, unknown>): boolean
231
237
  return options.formatModelNames !== false
232
238
  }
233
239
 
240
+ /**
241
+ * Read the optional display-name template. Non-strings are ignored. An empty
242
+ * string, or the `"{name}"` default spelled out, counts as unset so those
243
+ * configs keep the same cache identity (and the same warm cache) as before
244
+ * the setting existed.
245
+ */
246
+ export function readModelNameTemplate(options: Record<string, unknown>): string | undefined {
247
+ const value = options.modelNameTemplate
248
+ if (typeof value !== 'string') return undefined
249
+ const trimmed = value.trim()
250
+ if (trimmed === '' || trimmed === DEFAULT_MODEL_NAME_TEMPLATE) return undefined
251
+ return value
252
+ }
253
+
234
254
  /**
235
255
  * Overlay metadata onto a `/v1/models` entry in three tiers: the entry's
236
256
  * own fields win, `/v1/model/info` fills gaps (notably `mode`, which
@@ -276,6 +296,19 @@ function enrichModel(
276
296
  */
277
297
  const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
278
298
 
299
+ /**
300
+ * The display name a model gets before any provider template is applied —
301
+ * LiteLLM's `model_info.display_name` when valid, the plugin's default
302
+ * formatting, or the raw `/v1/models` id when formatting is disabled.
303
+ */
304
+ function baseDisplayName(
305
+ model: { id: string },
306
+ formatModelNames: boolean,
307
+ displayName?: unknown,
308
+ ): string {
309
+ return resolveModelDisplayName(model, { formatModelNames, displayName })
310
+ }
311
+
279
312
  /**
280
313
  * Convert a discovered LiteLLM model into an OpenCode config-level
281
314
  * model entry (the shape used in `provider.*.models` inside
@@ -283,20 +316,34 @@ const USD_PER_TOKEN_TO_PER_MILLION = 1_000_000
283
316
  * image, audio) — they can't be used as primary chat models and would
284
317
  * clutter the picker.
285
318
  *
286
- * Exported for tests: `formatModelNames` decides whether the display
287
- * name is the prettified id or the raw `/v1/models` id verbatim.
319
+ * Exported for tests: the display name comes from `info.display_name` when
320
+ * valid, otherwise the prettified id or the raw `/v1/models` id when
321
+ * formatting is disabled, optionally wrapped in the provider's
322
+ * `modelNameTemplate`.
288
323
  */
289
324
  export function toConfigModel(
290
325
  model: LiteLLMModel,
291
326
  info?: LiteLLMModelInfo,
292
- formatModelNames = true,
327
+ naming: ModelNaming = {},
293
328
  ): Record<string, unknown> | null {
294
329
  const type = categorizeModel(model)
295
330
  if (type === 'embedding' || type === 'image' || type === 'audio') {
296
331
  return null
297
332
  }
333
+ const providerId = naming.providerId ?? ''
298
334
  const entry: Record<string, unknown> = {
299
- name: formatModelNames ? formatModelName(model) : model.id,
335
+ name: applyModelNameTemplate(naming.modelNameTemplate, {
336
+ name: baseDisplayName(
337
+ model,
338
+ naming.formatModelNames !== false,
339
+ info?.display_name,
340
+ ),
341
+ id: model.id,
342
+ providerId,
343
+ // Without a configured display name the picker falls back to the id,
344
+ // so the placeholder resolves to the same thing the user sees.
345
+ providerName: naming.providerName ?? providerId,
346
+ }),
300
347
  }
301
348
  // Some deployments only report the OpenAI-style `max_tokens` total;
302
349
  // use it as the context limit when `max_input_tokens` is absent.
@@ -374,12 +421,16 @@ export function toConfigModel(
374
421
  * lists the subset that must be invoked through the OpenAI Responses API;
375
422
  * callers route those accordingly without inspecting each entry. `hints`
376
423
  * carries per-model upstream facts OpenCode 2 maps to `compatibility` and
377
- * `variants`.
424
+ * `variants`. `displayNames` records each model's valid
425
+ * `model_info.display_name` (when formatting is enabled), so a cached model
426
+ * can be re-rendered for the Responses sibling without losing it; an explicit
427
+ * `models.<id>.name` still wins at merge time.
378
428
  */
379
429
  export interface DiscoveredModels {
380
430
  models: Record<string, unknown>
381
431
  responsesIds: string[]
382
432
  hints: Record<string, ModelHints>
433
+ displayNames: Record<string, string>
383
434
  }
384
435
 
385
436
  /**
@@ -389,9 +440,9 @@ export interface DiscoveredModels {
389
440
  * classifies + formats each model, and returns the built entries plus the
390
441
  * ids that require the Responses API and per-model hints. The provider's
391
442
  * `includeModels`/`excludeModels` filters, `modelCapabilities` overrides and
392
- * `formatModelNames` choice are applied here (not at merge time) so every
393
- * path that persists or serves a cache — cold discovery and background
394
- * refresh — writes the same adjusted view.
443
+ * naming choices (`formatModelNames`, `modelNameTemplate`) are applied here
444
+ * (not at merge time) so every path that persists or serves a cache — cold
445
+ * discovery and background refresh — writes the same adjusted view.
395
446
  *
396
447
  * Returns `null` when the proxy is unreachable/unauthorized or exposes
397
448
  * no models, so callers can distinguish "no data" from "empty result".
@@ -403,7 +454,7 @@ export async function discoverModels(
403
454
  providerId: string,
404
455
  filters: ModelFilters = {},
405
456
  capabilities: ModelCapabilities = {},
406
- formatModelNames = true,
457
+ naming: ModelNaming = {},
407
458
  ): Promise<DiscoveredModels | null> {
408
459
  if (!(await checkLiteLLMHealth(baseURL, apiKey, customHeaders))) {
409
460
  log(
@@ -456,6 +507,7 @@ export async function discoverModels(
456
507
  const built: Record<string, unknown> = {}
457
508
  const responsesIds: string[] = []
458
509
  const hints: Record<string, ModelHints> = {}
510
+ const displayNames: Record<string, string> = {}
459
511
  let skipped = 0
460
512
  let wildcards = 0
461
513
  let filtered = 0
@@ -478,12 +530,19 @@ export async function discoverModels(
478
530
  const info = infoByName?.get(model.id)
479
531
  if (infoByName && !info) unmatched.push(model.id)
480
532
  const enriched = enrichModel(model, info, capabilities[model.id])
481
- const entry = toConfigModel(enriched, info, formatModelNames)
533
+ const entry = toConfigModel(enriched, info, { ...naming, providerId })
482
534
  if (!entry) {
483
535
  skipped++
484
536
  continue
485
537
  }
486
538
  built[model.id] = entry
539
+ // Record the display name for every built model: an explicit
540
+ // models.<id>.name still wins at merge time, and with formatting
541
+ // disabled the raw id wins, so nothing is recorded.
542
+ if (naming.formatModelNames !== false) {
543
+ const displayName = normalizeModelDisplayName(info?.display_name)
544
+ if (displayName) displayNames[model.id] = displayName
545
+ }
487
546
  if (requiresResponsesAPI(enriched)) responsesIds.push(model.id)
488
547
  const params = info?.supported_openai_params
489
548
  hints[model.id] = {
@@ -522,7 +581,7 @@ export async function discoverModels(
522
581
  ')',
523
582
  )
524
583
 
525
- return { models: built, responsesIds, hints }
584
+ return { models: built, responsesIds, hints, displayNames }
526
585
  }
527
586
 
528
587
  /**
@@ -573,10 +632,14 @@ function ensureResponsesProvider(
573
632
  const provider = config.provider[id] as Record<string, unknown>
574
633
  if (!provider.npm) provider.npm = RESPONSES_NPM
575
634
  if (typeof provider.name !== 'string' || !provider.name) {
635
+ // Mirror how the base provider is labelled: its configured name, or its
636
+ // id when none is set (which is what the picker falls back to). This keeps
637
+ // `{provider_name}` in the sibling's model names equal to the sibling's
638
+ // visible label.
576
639
  const baseName =
577
640
  typeof baseProvider.name === 'string' && baseProvider.name
578
641
  ? baseProvider.name
579
- : 'LiteLLM (proxy)'
642
+ : baseProviderId
580
643
  provider.name = `${baseName} Responses`
581
644
  }
582
645
  if (!provider.options || typeof provider.options !== 'object') {
@@ -626,6 +689,42 @@ function readHeaderMap(value: unknown): Record<string, string> {
626
689
  return out
627
690
  }
628
691
 
692
+ /**
693
+ * Re-render one discovered entry's name for the provider it is about to be
694
+ * injected into.
695
+ *
696
+ * OpenCode 1 moves Responses models into a `${baseProviderId}-responses`
697
+ * sibling, so a template that uses `{provider_id}`/`{provider_name}` must
698
+ * resolve to the provider the user actually selects. The entry in the cache
699
+ * stays as discovered — OpenCode 2 reads the same cache with a single
700
+ * provider — so this returns a copy instead of mutating it. `displayName` is
701
+ * the LiteLLM value recorded during discovery (when any), so re-rendering
702
+ * does not lose it.
703
+ */
704
+ function renameForProvider(
705
+ entry: Record<string, unknown>,
706
+ modelId: string,
707
+ naming: ModelNaming,
708
+ providerId: string,
709
+ providerName: string,
710
+ displayName?: string,
711
+ ): Record<string, unknown> {
712
+ if (naming.modelNameTemplate === undefined) return entry
713
+ return {
714
+ ...entry,
715
+ name: applyModelNameTemplate(naming.modelNameTemplate, {
716
+ name: baseDisplayName(
717
+ { id: modelId },
718
+ naming.formatModelNames !== false,
719
+ displayName,
720
+ ),
721
+ id: modelId,
722
+ providerId,
723
+ providerName,
724
+ }),
725
+ }
726
+ }
727
+
629
728
  /**
630
729
  * Split freshly discovered entries into the chat provider and the Responses
631
730
  * sibling, injecting each side without clobbering curated entries. Returns
@@ -639,30 +738,42 @@ function injectDiscoveredModels(
639
738
  baseModels: Record<string, unknown>,
640
739
  entries: Record<string, unknown>,
641
740
  responsesIds: readonly string[],
741
+ displayNames: Record<string, string>,
642
742
  baseURL: string,
643
743
  apiKey: string | undefined,
644
744
  customHeaders: Record<string, string> | undefined,
645
- runtimeFetch?: typeof fetch,
745
+ runtimeFetch: typeof fetch | undefined,
746
+ naming: ModelNaming,
646
747
  ): string[] {
647
748
  const responsesSet = new Set(responsesIds)
648
- const existingSibling = config.provider[`${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`]
749
+ const responsesProviderId = `${baseProviderId}${RESPONSES_PROVIDER_SUFFIX}`
750
+ const existingSibling =
751
+ config.provider[responsesProviderId] &&
752
+ typeof config.provider[responsesProviderId] === 'object'
753
+ ? (config.provider[responsesProviderId] as Record<string, unknown>)
754
+ : undefined
755
+ // A name the user (or an earlier run) already gave the sibling, captured
756
+ // before `ensureResponsesProvider` generates one.
757
+ const configuredSiblingName =
758
+ typeof existingSibling?.name === 'string' && existingSibling.name
759
+ ? existingSibling.name
760
+ : undefined
649
761
  const siblingModelsExisting: Record<string, unknown> =
650
762
  existingSibling &&
651
- typeof existingSibling === 'object' &&
652
- (existingSibling as Record<string, unknown>).models &&
653
- typeof (existingSibling as Record<string, unknown>).models === 'object'
654
- ? ((existingSibling as Record<string, unknown>).models as Record<string, unknown>)
763
+ existingSibling.models &&
764
+ typeof existingSibling.models === 'object'
765
+ ? (existingSibling.models as Record<string, unknown>)
655
766
  : {}
656
767
 
657
768
  const chatEntries: Record<string, unknown> = {}
658
- const responsesEntries: Record<string, unknown> = {}
769
+ const responsesIdsToInject: string[] = []
659
770
  for (const [id, entry] of Object.entries(entries)) {
660
771
  // A model already present under the other provider was curated there (or
661
772
  // injected by an earlier run); leave it alone instead of duplicating it
662
773
  // across both providers.
663
774
  if (responsesSet.has(id)) {
664
775
  if (Object.hasOwn(baseModels, id)) continue
665
- responsesEntries[id] = entry
776
+ responsesIdsToInject.push(id)
666
777
  } else {
667
778
  if (Object.hasOwn(siblingModelsExisting, id)) continue
668
779
  chatEntries[id] = entry
@@ -670,7 +781,7 @@ function injectDiscoveredModels(
670
781
  }
671
782
 
672
783
  const added = mergeModels(baseModels, chatEntries)
673
- if (Object.keys(responsesEntries).length > 0) {
784
+ if (responsesIdsToInject.length > 0) {
674
785
  const siblingModels = ensureResponsesProvider(
675
786
  config,
676
787
  baseProviderId,
@@ -680,6 +791,27 @@ function injectDiscoveredModels(
680
791
  customHeaders,
681
792
  runtimeFetch,
682
793
  )
794
+ // The sibling generates its name from the base provider's, so read it
795
+ // back; a user-configured name (from this run or an earlier one) wins.
796
+ // `{provider_name}` must equal the label the picker shows for the sibling
797
+ // because that is the provider the model is selected through.
798
+ const sibling = config.provider[responsesProviderId] as Record<string, unknown> | undefined
799
+ const siblingName =
800
+ configuredSiblingName ??
801
+ (sibling && typeof sibling.name === 'string' && sibling.name
802
+ ? sibling.name
803
+ : responsesProviderId)
804
+ const responsesEntries: Record<string, unknown> = {}
805
+ for (const id of responsesIdsToInject) {
806
+ responsesEntries[id] = renameForProvider(
807
+ entries[id] as Record<string, unknown>,
808
+ id,
809
+ naming,
810
+ responsesProviderId,
811
+ siblingName,
812
+ displayNames[id],
813
+ )
814
+ }
683
815
  added.push(...mergeModels(siblingModels, responsesEntries))
684
816
  }
685
817
  return added
@@ -712,12 +844,23 @@ async function backgroundRefresh(cacheKey: string): Promise<void> {
712
844
  ctx.providerId,
713
845
  ctx.filters,
714
846
  ctx.capabilities,
715
- ctx.formatModelNames,
847
+ {
848
+ formatModelNames: ctx.formatModelNames,
849
+ modelNameTemplate: ctx.modelNameTemplate,
850
+ providerId: ctx.providerId,
851
+ providerName: ctx.providerName,
852
+ },
716
853
  ),
717
854
  DISCOVERY_TIMEOUT_MS,
718
855
  )
719
856
  if (discovered && Object.keys(discovered.models).length > 0) {
720
- writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
857
+ writeModelCache(
858
+ cacheKey,
859
+ discovered.models,
860
+ discovered.responsesIds,
861
+ discovered.hints,
862
+ discovered.displayNames,
863
+ )
721
864
  log(
722
865
  'info',
723
866
  `[opencode-litellm] Background-refreshed model cache for ${ctx.baseURL} (${Object.keys(discovered.models).length} models)`,
@@ -870,6 +1013,12 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
870
1013
  const filters = readModelFilters(options)
871
1014
  const capabilities = parseModelCapabilities(options.modelCapabilities)
872
1015
  const formatModelNames = readFormatModelNames(options)
1016
+ const modelNameTemplate = readModelNameTemplate(options)
1017
+ // `{provider_name}` resolves to what the picker labels the provider
1018
+ // with; OpenCode falls back to the id when no name is configured.
1019
+ const providerName =
1020
+ typeof provider.name === 'string' && provider.name ? provider.name : providerId
1021
+ const naming = { formatModelNames, modelNameTemplate, providerId, providerName }
873
1022
 
874
1023
  // Resolve base URL
875
1024
  let baseURL: string | null = null
@@ -944,6 +1093,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
944
1093
  // the provider keeps its models and can be reconnected from `/connect`.
945
1094
  const cacheKey = buildCacheKey(providerId, baseURL, filters, capabilities, {
946
1095
  formatModelNames,
1096
+ modelNameTemplate,
1097
+ providerName,
947
1098
  }, sso ? ssoIdentity(sso) : apiKey)
948
1099
 
949
1100
  // Remember how to reach this proxy so the `event` hook can
@@ -960,6 +1111,8 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
960
1111
  filters,
961
1112
  capabilities,
962
1113
  formatModelNames,
1114
+ modelNameTemplate,
1115
+ providerName,
963
1116
  providerId,
964
1117
  })
965
1118
 
@@ -1002,10 +1155,12 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1002
1155
  models,
1003
1156
  cached.models,
1004
1157
  cached.responsesIds,
1158
+ cached.displayNames,
1005
1159
  baseURL,
1006
1160
  runtimeKey,
1007
1161
  customHeaders,
1008
1162
  runtimeFetch,
1163
+ naming,
1009
1164
  )
1010
1165
  injectedModelIds.set(cacheKey, new Set(added))
1011
1166
  log(
@@ -1026,7 +1181,7 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1026
1181
  providerId,
1027
1182
  filters,
1028
1183
  capabilities,
1029
- formatModelNames,
1184
+ { formatModelNames, modelNameTemplate, providerId, providerName },
1030
1185
  ),
1031
1186
  DISCOVERY_TIMEOUT_MS,
1032
1187
  )
@@ -1038,13 +1193,21 @@ export const LiteLLMPlugin: Plugin = async (input: PluginInput) => {
1038
1193
  models,
1039
1194
  discovered.models,
1040
1195
  discovered.responsesIds,
1196
+ discovered.displayNames,
1041
1197
  baseURL,
1042
1198
  runtimeKey,
1043
1199
  customHeaders,
1044
1200
  runtimeFetch,
1201
+ naming,
1045
1202
  )
1046
1203
  injectedModelIds.set(cacheKey, new Set(added))
1047
- writeModelCache(cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
1204
+ writeModelCache(
1205
+ cacheKey,
1206
+ discovered.models,
1207
+ discovered.responsesIds,
1208
+ discovered.hints,
1209
+ discovered.displayNames,
1210
+ )
1048
1211
  }
1049
1212
  }
1050
1213
  },
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 replaced/removed so a
266
- * refresh reflects LiteLLM's current inventory; ids the user curated
267
- * themselves are never removed. Returns the merged list plus the set of
268
- * ids the plugin now owns.
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
- ): { models: Model.Info[]; owned: Set<string> } {
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
- // Drop plugin-injected models that LiteLLM no longer returns; curated
281
- // models are not in `owned`, so they always survive.
282
- if (owned.has(model.id) && !discoveredIds.has(model.id)) continue
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
- if (owned.has(model.id)) nextOwned.add(model.id)
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
- return { models: [...result.values()], owned: nextOwned }
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
- formatModelNames,
621
+ naming,
453
622
  ),
454
623
  DISCOVERY_TIMEOUT_MS,
455
624
  )
@@ -457,7 +626,7 @@ async function makeProviderSource(
457
626
  entries = discovered.models
458
627
  responsesIds = discovered.responsesIds
459
628
  hints = discovered.hints
460
- writeModelCache(cacheKey, entries, responsesIds, hints)
629
+ writeModelCache(cacheKey, entries, responsesIds, hints, discovered.displayNames)
461
630
  } else {
462
631
  entries = null
463
632
  responsesIds = []
@@ -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
- source.formatModelNames,
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
  )
@@ -568,7 +746,13 @@ async function refreshProviderSource(
568
746
  compatibility: source.compatibility,
569
747
  })
570
748
  if (JSON.stringify(models) === JSON.stringify(source.models)) {
571
- writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
749
+ writeModelCache(
750
+ source.cacheKey,
751
+ discovered.models,
752
+ discovered.responsesIds,
753
+ discovered.hints,
754
+ discovered.displayNames,
755
+ )
572
756
  source.refreshRequired = false
573
757
  return
574
758
  }
@@ -582,7 +766,13 @@ async function refreshProviderSource(
582
766
  throw error
583
767
  }
584
768
 
585
- writeModelCache(source.cacheKey, discovered.models, discovered.responsesIds, discovered.hints)
769
+ writeModelCache(
770
+ source.cacheKey,
771
+ discovered.models,
772
+ discovered.responsesIds,
773
+ discovered.hints,
774
+ discovered.displayNames,
775
+ )
586
776
  source.refreshRequired = false
587
777
  logInfo(
588
778
  `[opencode-litellm] Refreshed ${models.length} models for provider "${source.id}"; the provider registry was reloaded.`,
@@ -717,6 +907,18 @@ async function reconcileProviderSources(
717
907
  if (existing && !existing.fromFallback && !existing.pendingPublication) continue
718
908
  const source = await makeProviderSource(context, provider, pluginOptions)
719
909
  if (!source) continue
910
+ // A source replacing this id's predecessor inherits its provenance
911
+ // record: the exact entries the predecessor published (or an inherited
912
+ // snapshot the predecessor itself had not spent yet). `providerName` and
913
+ // `modelNameTemplate` are baked into discovered names at discovery time,
914
+ // and ids alone cannot distinguish the plugin's stale rendering from an
915
+ // entry the user curated under the same id — so the successor carries the
916
+ // entries themselves, and its first merge replaces only entries that
917
+ // still match (see mergeProviderModels). For a fallback predecessor this
918
+ // is what re-renders its output with the configured provider's naming;
919
+ // for a pending configured one it can only affect entries the failed
920
+ // attempt actually published.
921
+ if (existing) source.supersededModels = existing.supersededModels ?? existing.publishedModels
720
922
  sources.set(source.id, source)
721
923
  changed.push(source)
722
924
  }
@@ -736,8 +938,9 @@ async function reconcileProviderSources(
736
938
  * options/config): a fallback only stands in until a real endpoint is
737
939
  * known, so the dialog's answers take over from it. Explicit option/env
738
940
  * baseURLs — and host-registered providers — keep winning and are never
739
- * replaced. Replaced sources' owned model ids carry over so models the
740
- * gateway no longer serves are dropped on the next merge, and sources
941
+ * replaced. Replaced sources carry their provenance record (the exact
942
+ * entries they published) so the successor's first merge re-renders its own
943
+ * stale output while preserving curated entries, and sources
741
944
  * replaced under a different id are dropped from `sources` and marked in
742
945
  * `staleProviderIds` for removal from the provider registry.
743
946
  */
@@ -754,7 +957,13 @@ async function publishConnectedSource(
754
957
  const existing = sources.get(source.id)
755
958
  if (existing && !(existing.fromFallback && !readString(existing.settings.baseURL))) return
756
959
  const previous = existing ?? replacing.find((candidate) => candidate.id === source.id)
757
- if (previous) source.ownedModelIds = new Set(previous.ownedModelIds)
960
+ // Same carry as a configured provider replacing a fallback: the exact
961
+ // entries the predecessor published let the first merge replace only
962
+ // the predecessor's own output and preserve curated entries.
963
+ if (previous) {
964
+ source.ownedModelIds = new Set(previous.ownedModelIds)
965
+ source.supersededModels = previous.supersededModels ?? previous.publishedModels
966
+ }
758
967
  for (const previousSource of replacing) {
759
968
  if (previousSource.id === source.id) continue
760
969
  const mapped = sources.get(previousSource.id)
@@ -851,11 +1060,23 @@ const definition = Plugin.define({
851
1060
  current.models.values(),
852
1061
  source.models,
853
1062
  source.ownedModelIds,
1063
+ source.supersededModels,
1064
+ source.publishedModels,
854
1065
  )
855
1066
  source.ownedModelIds = merged.owned
1067
+ source.publishedModels = merged.published
1068
+ // The one-shot replacement snapshot is spent: later merges on this
1069
+ // source use the steady-state semantics alone.
1070
+ source.supersededModels = undefined
856
1071
  editor.models.set(source.id, merged.models)
857
1072
  } else {
858
1073
  source.ownedModelIds = new Set(source.models.map((model) => model.id))
1074
+ source.publishedModels = new Map(
1075
+ source.models.map((model) => [model.id, recordEntry(model)]),
1076
+ )
1077
+ // Nothing to replace under a brand-new provider id: any inherited
1078
+ // snapshot is spent here too, so it never leaks into a later merge.
1079
+ source.supersededModels = undefined
859
1080
  editor.add({
860
1081
  info: {
861
1082
  ...Provider.Info.empty(Provider.ID.make(source.id)),
@@ -59,6 +59,12 @@ export interface LiteLLMModelInfo {
59
59
  db_model?: boolean
60
60
  /** Alias LiteLLM assigns to the model; mirrors the `/v1/models` id. */
61
61
  key?: string
62
+ /**
63
+ * Human-readable name configured on the deployment
64
+ * (`model_info.display_name`). Display-only: never used as the model id or
65
+ * in API requests. Absent or malformed values fall back to id formatting.
66
+ */
67
+ display_name?: string | null
62
68
  mode?: string
63
69
  max_tokens?: number
64
70
  max_input_tokens?: number
@@ -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,94 @@ export function formatModelName(model: LiteLLMModel): string {
196
196
 
197
197
  return tokens.join(' ') || id
198
198
  }
199
+
200
+ /**
201
+ * Normalise a LiteLLM `model_info.display_name` into a display name.
202
+ *
203
+ * Only a non-empty string counts. The value is trimmed so surrounding
204
+ * whitespace never reaches the picker; everything else (undefined, null,
205
+ * empty, whitespace-only, numbers, objects) is treated as "no display name"
206
+ * and lets the caller fall back to id formatting.
207
+ */
208
+ export function normalizeModelDisplayName(value: unknown): string | undefined {
209
+ if (typeof value !== 'string') return undefined
210
+ const trimmed = value.trim()
211
+ return trimmed === '' ? undefined : trimmed
212
+ }
213
+
214
+ /**
215
+ * Resolve the display name for a discovered model before any provider
216
+ * template is applied.
217
+ *
218
+ * Precedence:
219
+ * 1. `formatModelNames: false` keeps the raw `/v1/models` id, as before.
220
+ * 2. A valid LiteLLM `model_info.display_name`.
221
+ * 3. The prettified id (`formatModelName`).
222
+ *
223
+ * `display_name` is display-only: callers keep using `model.id` for the
224
+ * model id, requests, routing and filtering.
225
+ */
226
+ export function resolveModelDisplayName(
227
+ model: Pick<LiteLLMModel, 'id'>,
228
+ options: { formatModelNames?: boolean; displayName?: unknown } = {},
229
+ ): string {
230
+ if (options.formatModelNames === false) return model.id
231
+ return normalizeModelDisplayName(options.displayName) ?? formatModelName(model)
232
+ }
233
+
234
+ /**
235
+ * The naming choices that decide how a discovered model is displayed. They
236
+ * are baked into cached model entries, so the same object also feeds the
237
+ * cache identity (see `buildCacheKey` in `model-cache.ts`).
238
+ */
239
+ export interface ModelNaming {
240
+ /**
241
+ * Prettify a model id into a display name. A valid LiteLLM
242
+ * `model_info.display_name` takes precedence; `false` keeps the raw id and
243
+ * ignores the display name too.
244
+ */
245
+ formatModelNames?: boolean
246
+ /**
247
+ * Template applied to every discovered model's display name. Unset (or
248
+ * `"{name}"`) leaves today's names untouched. Known placeholders:
249
+ * `{name}`, `{id}`, `{provider_id}` and `{provider_name}`.
250
+ */
251
+ modelNameTemplate?: string
252
+ /** Provider id/name used by the template's provider placeholders. */
253
+ providerId?: string
254
+ providerName?: string
255
+ }
256
+
257
+ /** The template that reproduces today's names, so it counts as "unset". */
258
+ export const DEFAULT_MODEL_NAME_TEMPLATE = '{name}'
259
+
260
+ const NAME_TEMPLATE_PLACEHOLDER = /\{(name|id|provider_id|provider_name)\}/g
261
+
262
+ /**
263
+ * Fill a `modelNameTemplate` with one model's values.
264
+ *
265
+ * Substitution is single-pass, so a value that itself contains a placeholder
266
+ * (`{id}` inside a display name, say) is inserted literally rather than
267
+ * expanded again. Unknown placeholders stay as written, which makes a typo
268
+ * visible in the picker instead of silently dropping the model's name.
269
+ */
270
+ export function applyModelNameTemplate(
271
+ template: string | undefined,
272
+ values: { name: string; id: string; providerId: string; providerName: string },
273
+ ): string {
274
+ if (template === undefined || template.trim() === '') return values.name
275
+ return template.replace(NAME_TEMPLATE_PLACEHOLDER, (placeholder: string, key: string) => {
276
+ switch (key) {
277
+ case 'name':
278
+ return values.name
279
+ case 'id':
280
+ return values.id
281
+ case 'provider_id':
282
+ return values.providerId
283
+ case 'provider_name':
284
+ return values.providerName
285
+ default:
286
+ return placeholder
287
+ }
288
+ })
289
+ }
@@ -102,10 +102,11 @@ export async function discoverLiteLLMModels(
102
102
  }
103
103
 
104
104
  /**
105
- * Fetch per-model metadata (`mode`, token limits, capability flags)
106
- * from `/v1/model/info`, keyed by model name. `/v1/models` omits these
107
- * fields for database-defined models, so classification (e.g. filtering
108
- * out embedding models) relies on this endpoint.
105
+ * Fetch per-model metadata (`mode`, token limits, capability flags and the
106
+ * optional `display_name`) from `/v1/model/info`, keyed by model name.
107
+ * `/v1/models` omits these fields for database-defined models, so
108
+ * classification (e.g. filtering out embedding models) relies on this
109
+ * endpoint.
109
110
  */
110
111
  export async function discoverLiteLLMModelInfo(
111
112
  baseURL: string = DEFAULT_LITELLM_URL,
@@ -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 { normalizeModelDisplayName, type ModelNaming } from './format-model-name'
5
6
 
6
7
  /**
7
8
  * Facts about a discovered model's upstream that OpenCode 2 turns into
@@ -29,7 +30,7 @@ export interface ModelHints {
29
30
  * from older plugin versions are ignored rather than deserialized into
30
31
  * an incompatible structure.
31
32
  */
32
- const CACHE_VERSION = 6
33
+ const CACHE_VERSION = 7
33
34
 
34
35
  /**
35
36
  * Maximum age of a cache entry before it's treated as a miss. Without a
@@ -55,6 +56,13 @@ interface ModelCacheFile {
55
56
  * no place in a provider-config entry (see `ModelHints`).
56
57
  */
57
58
  hints?: Record<string, ModelHints>
59
+ /**
60
+ * LiteLLM `model_info.display_name` values that were used for a model's
61
+ * display name. The templated name is already baked into `models`, but
62
+ * OpenCode 1's Responses sibling re-renders names with its own provider
63
+ * placeholders and needs the pre-template display name to do so.
64
+ */
65
+ displayNames?: Record<string, string>
58
66
  }
59
67
 
60
68
  /**
@@ -98,19 +106,23 @@ function canonicalize(value: unknown): string {
98
106
  /**
99
107
  * Cache identity for a provider's model view. `providerId@baseURL`
100
108
  * alone isn't enough: `includeModels`/`excludeModels`,
101
- * `modelCapabilities` and `formatModelNames` are baked into cached
102
- * entries by discovery, so a config change must not reuse the old cache
103
- * — it would keep serving the previous adjusted view until a second
104
- * restart. A fingerprint is appended whenever adjustments exist
105
- * (pattern order ignored); default configs keep the plain key so
106
- * existing caches stay warm across plugin upgrades.
109
+ * `modelCapabilities` and the naming choices (`formatModelNames`,
110
+ * `modelNameTemplate`) are baked into cached entries by discovery, so a
111
+ * config change must not reuse the old cache — it would keep serving the
112
+ * previous adjusted view until a second restart. A fingerprint is appended
113
+ * whenever adjustments exist (pattern order ignored); default configs keep
114
+ * the plain key so existing caches stay warm across plugin upgrades.
115
+ *
116
+ * `providerName` only matters when a template is set: `{provider_name}`
117
+ * resolves to it, so renaming a provider must start a fresh discovery too.
118
+ * The provider id is already part of the base key.
107
119
  */
108
120
  export function buildCacheKey(
109
121
  providerId: string,
110
122
  baseURL: string,
111
123
  filters: { includeModels?: string[]; excludeModels?: string[] },
112
124
  capabilities: Record<string, Record<string, boolean>>,
113
- naming: { formatModelNames?: boolean } = {},
125
+ naming: ModelNaming = {},
114
126
  credential?: string,
115
127
  ): string {
116
128
  let base = `${providerId}@${baseURL}`
@@ -122,21 +134,31 @@ export function buildCacheKey(
122
134
  base += `@${createHash('sha256').update(credential).digest('hex').slice(0, 12)}`
123
135
  }
124
136
  const rawNames = naming.formatModelNames === false
137
+ const template = naming.modelNameTemplate
125
138
  const hasAdjustments =
126
139
  (filters.includeModels?.length ?? 0) > 0 ||
127
140
  (filters.excludeModels?.length ?? 0) > 0 ||
128
141
  Object.keys(capabilities).length > 0 ||
129
- rawNames
142
+ rawNames ||
143
+ template !== undefined
130
144
  if (!hasAdjustments) return base
145
+ // Omitted keys stay out of the hash entirely: `undefined` would serialize
146
+ // as the literal string "undefined" and change every existing cache key.
147
+ const namingFingerprint: Record<string, unknown> = {}
148
+ // Omitted (not `true`) when formatting is on, so keys for configs that
149
+ // never touch this option are unchanged.
150
+ if (rawNames) namingFingerprint.formatModelNames = false
151
+ if (template !== undefined) {
152
+ namingFingerprint.modelNameTemplate = template
153
+ namingFingerprint.providerName = naming.providerName
154
+ }
131
155
  const fingerprint = createHash('sha256')
132
156
  .update(
133
157
  canonicalize({
134
158
  includeModels: filters.includeModels ? [...filters.includeModels].sort() : undefined,
135
159
  excludeModels: filters.excludeModels ? [...filters.excludeModels].sort() : undefined,
136
160
  capabilities,
137
- // Omitted (not `true`) when formatting is on, so keys for
138
- // configs that never touch this option are unchanged.
139
- formatModelNames: rawNames ? false : undefined,
161
+ ...namingFingerprint,
140
162
  }),
141
163
  )
142
164
  .digest('hex')
@@ -168,6 +190,17 @@ function normalizeResponsesIds(value: unknown): string[] {
168
190
  return value.filter((id): id is string => typeof id === 'string')
169
191
  }
170
192
 
193
+ /** Keep only non-empty string entries of a cached `displayNames` map. */
194
+ function normalizeDisplayNames(value: unknown): Record<string, string> {
195
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {}
196
+ const out: Record<string, string> = {}
197
+ for (const [id, name] of Object.entries(value as Record<string, unknown>)) {
198
+ const normalized = normalizeModelDisplayName(name)
199
+ if (normalized !== undefined) out[id] = normalized
200
+ }
201
+ return out
202
+ }
203
+
171
204
  /** Keep only well-formed entries of a cached `hints` map. */
172
205
  function normalizeHints(value: unknown): Record<string, ModelHints> {
173
206
  if (!value || typeof value !== 'object' || Array.isArray(value)) return {}
@@ -205,10 +238,10 @@ export function readModelCache(
205
238
  }
206
239
 
207
240
  /**
208
- * Read the models, Responses-API model ids and model hints for a cache key
209
- * in one parse. Returns `null` under the same conditions as
210
- * {@link readModelCache} (missing/expired cache), so the three can't
211
- * disagree within a single lookup.
241
+ * Read the models, Responses-API model ids, model hints and LiteLLM display
242
+ * names for a cache key in one parse. Returns `null` under the same
243
+ * conditions as {@link readModelCache} (missing/expired cache), so the four
244
+ * can't disagree within a single lookup.
212
245
  */
213
246
  export function readModelCacheEntry(
214
247
  cacheKey: string,
@@ -216,6 +249,7 @@ export function readModelCacheEntry(
216
249
  models: Record<string, unknown>
217
250
  responsesIds: string[]
218
251
  hints: Record<string, ModelHints>
252
+ displayNames: Record<string, string>
219
253
  } | null {
220
254
  const parsed = readCacheFile(cacheKey)
221
255
  if (!parsed) return null
@@ -229,6 +263,7 @@ export function readModelCacheEntry(
229
263
  models: parsed.models,
230
264
  responsesIds: normalizeResponsesIds(parsed.responsesIds),
231
265
  hints: normalizeHints(parsed.hints),
266
+ displayNames: normalizeDisplayNames(parsed.displayNames),
232
267
  }
233
268
  }
234
269
 
@@ -263,6 +298,7 @@ export function writeModelCache(
263
298
  models: Record<string, unknown>,
264
299
  responsesIds: readonly string[] = [],
265
300
  hints: Record<string, ModelHints> = {},
301
+ displayNames: Record<string, string> = {},
266
302
  ): void {
267
303
  try {
268
304
  mkdirSync(cacheDir(), { recursive: true })
@@ -272,6 +308,7 @@ export function writeModelCache(
272
308
  models,
273
309
  responsesIds: [...responsesIds],
274
310
  hints,
311
+ displayNames,
275
312
  }
276
313
  // Write to a temp file and rename so concurrent OpenCode processes
277
314
  // never observe a partially-written JSON file (rename is atomic on