opencode-plugin-litellm 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plugin/v2.ts CHANGED
@@ -9,14 +9,17 @@ import {
9
9
  readCustomHeaders,
10
10
  readFormatModelNames,
11
11
  readModelFilters,
12
+ readModelNameTemplate,
12
13
  withTimeout,
13
14
  LiteLLMPlugin,
14
15
  } from './index'
15
16
  import {
16
17
  LITELLM_INTEGRATION_ID,
18
+ connectionApiKey,
17
19
  readConnectedConfig,
18
20
  registerLiteLLMIntegration,
19
21
  type ConnectedLiteLLM,
22
+ type SignInTarget,
20
23
  } from './integration'
21
24
  import {
22
25
  buildCacheKey,
@@ -26,6 +29,7 @@ import {
26
29
  } from '../utils/model-cache'
27
30
  import { normalizeBaseURL, autoDetectLiteLLM } from '../utils/litellm-api'
28
31
  import { getOpenCodeStoredApiKey } from '../utils/opencode-auth'
32
+ import { sameProxy } from '../utils/sso'
29
33
  import { parseModelCapabilities } from '../utils/model-capabilities'
30
34
  import type { ModelCapabilities } from '../utils/model-capabilities'
31
35
  import {
@@ -106,14 +110,40 @@ interface ProviderSource {
106
110
  capabilities: ModelCapabilities
107
111
  compatibility: ModelCompatibility
108
112
  formatModelNames: boolean
113
+ modelNameTemplate?: string
114
+ providerName: string
109
115
  cacheKey: string
110
116
  models: Model.Info[]
111
117
  /**
112
118
  * Model ids this plugin injected into the provider registry (as opposed
113
119
  * to ids the user curated in config). Only these are eligible to be
114
- * 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).
115
123
  */
116
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
117
147
  }
118
148
 
119
149
  function asRecord(value: unknown): Record<string, unknown> {
@@ -256,39 +286,176 @@ function numberOrDefault(value: unknown, fallback: number): number {
256
286
  : fallback
257
287
  }
258
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
+
259
354
  /**
260
355
  * Merge freshly discovered models into a provider's current model set.
261
356
  *
262
- * Previously-discovered ids owned by this plugin are replaced/removed so a
263
- * refresh reflects LiteLLM's current inventory; ids the user curated
264
- * themselves are never removed. Returns the merged list plus the set of
265
- * 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.
266
384
  */
267
385
  function mergeProviderModels(
268
386
  configured: Iterable<Model.Info>,
269
387
  discovered: readonly Model.Info[],
270
388
  owned: ReadonlySet<string>,
271
- ): { 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> } {
272
392
  const discoveredIds = new Set(discovered.map((model) => model.id))
273
393
  const result = new Map<string, Model.Info>()
274
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)
275
400
 
276
401
  for (const model of configured) {
277
- // Drop plugin-injected models that LiteLLM no longer returns; curated
278
- // models are not in `owned`, so they always survive.
279
- 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.
280
436
  result.set(model.id, model)
281
- if (owned.has(model.id)) nextOwned.add(model.id)
437
+ nextOwned.add(model.id)
438
+ if (carriedSnapshot !== undefined) carriedSnapshots.set(model.id, carriedSnapshot)
282
439
  }
283
440
 
284
441
  for (const model of discovered) {
285
442
  if (!result.has(model.id)) {
286
443
  result.set(model.id, model)
287
444
  nextOwned.add(model.id)
445
+ carriedSnapshots.set(model.id, recordEntry(model))
288
446
  }
289
447
  }
290
448
 
291
- 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 }
292
459
  }
293
460
 
294
461
  function runtimeSettings(source: ProviderSource): Record<string, unknown> {
@@ -304,6 +471,7 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
304
471
  'modelCapabilities',
305
472
  'modelCompatibility',
306
473
  'formatModelNames',
474
+ 'modelNameTemplate',
307
475
  'providerID',
308
476
  ]) {
309
477
  delete settings[key]
@@ -317,6 +485,45 @@ function runtimeSettings(source: ProviderSource): Record<string, unknown> {
317
485
  return settings
318
486
  }
319
487
 
488
+ function providerHeaders(
489
+ pluginOptions: Record<string, unknown>,
490
+ settings: Record<string, unknown>,
491
+ provider: ProviderInfo | undefined,
492
+ ): Record<string, string> {
493
+ return {
494
+ ...readHeaders(pluginOptions.customHeaders),
495
+ ...readCustomHeaders(settings),
496
+ ...readHeaders(provider?.headers),
497
+ }
498
+ }
499
+
500
+ /** The proxy URL and headers a sign-in uses: the configured provider's, else the plugin options'. */
501
+ async function signInTarget(
502
+ context: Context,
503
+ pluginOptions: Record<string, unknown>,
504
+ providerID: string,
505
+ ): Promise<SignInTarget> {
506
+ const providers = await listMatchingProviders(context)
507
+ const provider = providers.find((candidate) => candidate.id === providerID)
508
+ const settings = { ...pluginOptions, ...asRecord(provider?.settings) }
509
+ return {
510
+ baseURL: readString(settings.baseURL),
511
+ headers: providerHeaders(pluginOptions, settings, provider),
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Whether a sign-in may go to `baseURL`. Its token only goes to the proxy that issued it, as on
517
+ * OpenCode 1; a sign-in that names no proxy (OIDC) goes where the provider points.
518
+ */
519
+ function signInReaches(signedInTo: string | undefined, baseURL: string | undefined): boolean {
520
+ if (!signedInTo || !baseURL || sameProxy(signedInTo, baseURL)) return true
521
+ logInfo(
522
+ `[opencode-litellm] Not using the LiteLLM sign-in for ${signedInTo}: ${baseURL} must not receive its token.`,
523
+ )
524
+ return false
525
+ }
526
+
320
527
  async function makeProviderSource(
321
528
  context: Context,
322
529
  provider: ProviderInfo | undefined,
@@ -324,25 +531,25 @@ async function makeProviderSource(
324
531
  ): Promise<ProviderSource | null> {
325
532
  const providerSettings = asRecord(provider?.settings)
326
533
  const settings = { ...pluginOptions, ...providerSettings }
327
- const customHeaders = {
328
- ...readHeaders(pluginOptions.customHeaders),
329
- ...readCustomHeaders(settings),
330
- ...readHeaders(provider?.headers),
331
- }
534
+ const customHeaders = providerHeaders(pluginOptions, settings, provider)
535
+ const configuredBaseURL = readString(settings.baseURL)
332
536
  // Credential plus dialog form answers. A provider wired to its own
333
537
  // integration keeps using exactly that one; otherwise the plugin's
334
538
  // registered integration is consulted, so a gateway can be connected
335
539
  // entirely from the web UI with no hand-written config.
336
- const connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
540
+ let connected: ConnectedLiteLLM | undefined = await readConnectedConfig(
337
541
  context,
338
542
  provider?.integrationID ?? LITELLM_INTEGRATION_ID,
339
543
  )
544
+ // A base URL configured for another proxy turns the sign-in off.
545
+ if (connected?.credentialID && !signInReaches(connected.baseURL, configuredBaseURL)) {
546
+ connected = undefined
547
+ }
340
548
  const id =
341
549
  provider?.id ??
342
550
  readString(pluginOptions.providerID) ??
343
551
  connected?.providerID ??
344
552
  CHAT_PROVIDER_ID
345
- const configuredBaseURL = readString(settings.baseURL)
346
553
  const connectedApiKey = connected?.apiKey
347
554
  // Precedence rule: an explicit settings/plugin-options apiKey is the
348
555
  // operator's deliberate config and stays first; then a credential the user
@@ -367,13 +574,25 @@ async function makeProviderSource(
367
574
  const capabilities = parseModelCapabilities(settings.modelCapabilities)
368
575
  const compatibility = parseModelCompatibility(settings.modelCompatibility)
369
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 }
370
583
  // Explicit config beats the URL typed into the dialog, which beats the
371
584
  // environment and local port probing.
372
585
  const detectedBaseURL = configuredBaseURL
373
586
  ? normalizeBaseURL(configuredBaseURL)
374
587
  : connected?.baseURL
375
588
  ? normalizeBaseURL(connected.baseURL)
376
- : await autoDetectLiteLLM(apiKey, customHeaders)
589
+ : await autoDetectLiteLLM(
590
+ apiKey,
591
+ customHeaders,
592
+ // A sign-in only goes to a proxy named for it: probing local ports
593
+ // would hand its token to whatever answers there.
594
+ usesConnectionCredential && connected?.credentialID ? [] : undefined,
595
+ )
377
596
 
378
597
  if (!detectedBaseURL) {
379
598
  return null
@@ -382,10 +601,9 @@ async function makeProviderSource(
382
601
  const baseURL = normalizeBaseURL(detectedBaseURL)
383
602
  // The cache key is isolated by the effective credential (a fingerprint, never
384
603
  // the raw key): a credential change starts a fresh discovery instead of
385
- // serving another credential's cached model list.
386
- const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, {
387
- formatModelNames,
388
- }, apiKey)
604
+ // serving another credential's cached model list. A sign-in is keyed by its
605
+ // credential id, because its access token rotates on every refresh.
606
+ const cacheKey = buildCacheKey(id, baseURL, filters, capabilities, naming, (usesConnectionCredential ? connected?.credentialID : undefined) ?? apiKey)
389
607
  const cacheEntry = readModelCacheEntry(cacheKey)
390
608
  let entries = cacheEntry?.models ?? null
391
609
  let responsesIds = cacheEntry?.responsesIds ?? []
@@ -400,7 +618,7 @@ async function makeProviderSource(
400
618
  id,
401
619
  filters,
402
620
  capabilities,
403
- formatModelNames,
621
+ naming,
404
622
  ),
405
623
  DISCOVERY_TIMEOUT_MS,
406
624
  )
@@ -441,6 +659,8 @@ async function makeProviderSource(
441
659
  capabilities,
442
660
  compatibility,
443
661
  formatModelNames,
662
+ modelNameTemplate,
663
+ providerName,
444
664
  cacheKey,
445
665
  models: toProviderModels(id, entries ?? {}, {
446
666
  providerPackage,
@@ -449,6 +669,8 @@ async function makeProviderSource(
449
669
  compatibility,
450
670
  }),
451
671
  ownedModelIds: new Set<string>(),
672
+ publishedModels: new Map<string, Model.Info>(),
673
+ supersededModels: undefined,
452
674
  }
453
675
  }
454
676
 
@@ -477,10 +699,21 @@ async function refreshProviderSource(
477
699
  return
478
700
  }
479
701
 
480
- const apiKey = source.apiKey
481
702
  let refresh!: Promise<void>
482
703
  refresh = (async () => {
483
704
  try {
705
+ // A sign-in's access token rotates; resolving the connection refreshes an
706
+ // expiring one, so discovery does not run with a token that has expired.
707
+ if (source.usesConnectionCredential && source.integrationID) {
708
+ const connected = await readConnectedConfig(context, source.integrationID)
709
+ if (
710
+ connected?.apiKey &&
711
+ (!connected.credentialID || signInReaches(connected.baseURL, source.baseURL))
712
+ ) {
713
+ source.apiKey = connected.apiKey
714
+ }
715
+ }
716
+ const apiKey = source.apiKey
484
717
  const discovered = await withTimeout(
485
718
  discoverModels(
486
719
  source.baseURL,
@@ -489,7 +722,12 @@ async function refreshProviderSource(
489
722
  source.id,
490
723
  source.filters,
491
724
  source.capabilities,
492
- source.formatModelNames,
725
+ {
726
+ formatModelNames: source.formatModelNames,
727
+ modelNameTemplate: source.modelNameTemplate,
728
+ providerId: source.id,
729
+ providerName: source.providerName,
730
+ },
493
731
  ),
494
732
  DISCOVERY_TIMEOUT_MS,
495
733
  )
@@ -552,7 +790,15 @@ async function refreshConnectionCredential(
552
790
  const credential = connection
553
791
  ? await context.integration.connection.resolve(connection)
554
792
  : undefined
555
- const connectionKey = credential?.type === 'key' ? credential.key : undefined
793
+ let connectionKey = connectionApiKey(credential)
794
+ // A new sign-in may be for another proxy than the one this source points to.
795
+ if (
796
+ connectionKey !== undefined &&
797
+ credential?.type === 'oauth' &&
798
+ !signInReaches(readString(credential.metadata?.baseURL), source.baseURL)
799
+ ) {
800
+ connectionKey = undefined
801
+ }
556
802
  const settingsApiKey = readString(source.settings.apiKey)
557
803
  let nextKey: string | undefined
558
804
  let nextUsesConnection: boolean
@@ -649,6 +895,18 @@ async function reconcileProviderSources(
649
895
  if (existing && !existing.fromFallback && !existing.pendingPublication) continue
650
896
  const source = await makeProviderSource(context, provider, pluginOptions)
651
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
652
910
  sources.set(source.id, source)
653
911
  changed.push(source)
654
912
  }
@@ -668,8 +926,9 @@ async function reconcileProviderSources(
668
926
  * options/config): a fallback only stands in until a real endpoint is
669
927
  * known, so the dialog's answers take over from it. Explicit option/env
670
928
  * baseURLs — and host-registered providers — keep winning and are never
671
- * replaced. Replaced sources' owned model ids carry over so models the
672
- * gateway no longer serves are dropped on the next merge, and sources
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
673
932
  * replaced under a different id are dropped from `sources` and marked in
674
933
  * `staleProviderIds` for removal from the provider registry.
675
934
  */
@@ -686,7 +945,13 @@ async function publishConnectedSource(
686
945
  const existing = sources.get(source.id)
687
946
  if (existing && !(existing.fromFallback && !readString(existing.settings.baseURL))) return
688
947
  const previous = existing ?? replacing.find((candidate) => candidate.id === source.id)
689
- if (previous) source.ownedModelIds = new Set(previous.ownedModelIds)
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
+ }
690
955
  for (const previousSource of replacing) {
691
956
  if (previousSource.id === source.id) continue
692
957
  const mapped = sources.get(previousSource.id)
@@ -731,7 +996,9 @@ const definition = Plugin.define({
731
996
  // Surface LiteLLM in the connect-provider dialog so gateways can be
732
997
  // connected from the web UI. Purely additive: a host without the
733
998
  // integration API, or a failed registration, keeps every other auth path.
734
- const integrationRegistration = await registerLiteLLMIntegration(context)
999
+ const integrationRegistration = await registerLiteLLMIntegration(context, (providerID) =>
1000
+ signInTarget(context, pluginOptions, providerID),
1001
+ )
735
1002
 
736
1003
  // First pass. On OpenCode 2 the host has not registered user-configured
737
1004
  // providers yet, so this typically finds only built-ins; the event loop
@@ -781,11 +1048,23 @@ const definition = Plugin.define({
781
1048
  current.models.values(),
782
1049
  source.models,
783
1050
  source.ownedModelIds,
1051
+ source.supersededModels,
1052
+ source.publishedModels,
784
1053
  )
785
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
786
1059
  editor.models.set(source.id, merged.models)
787
1060
  } else {
788
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
789
1068
  editor.add({
790
1069
  info: {
791
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
+ }
@@ -157,15 +157,19 @@ export async function discoverLiteLLMModelInfo(
157
157
  }
158
158
 
159
159
  /**
160
- * Use an explicit LITELLM_BASE_URL when set; otherwise try the most common
161
- * ports. The default `litellm --port` is 4000, with 8000 and 8080 also common.
160
+ * Use an explicit LITELLM_BASE_URL when set; otherwise try `ports` on localhost,
161
+ * by default the most common ones. The default `litellm --port` is 4000, with
162
+ * 8000 and 8080 also common.
162
163
  */
163
- export async function autoDetectLiteLLM(apiKey?: string, customHeaders?: Record<string, string>): Promise<string | null> {
164
+ export async function autoDetectLiteLLM(
165
+ apiKey?: string,
166
+ customHeaders?: Record<string, string>,
167
+ ports: readonly number[] = [4000, 8000, 8080],
168
+ ): Promise<string | null> {
164
169
  const configuredBaseURL = process.env.LITELLM_BASE_URL?.trim()
165
170
  if (configuredBaseURL) return normalizeBaseURL(configuredBaseURL)
166
171
 
167
- const commonPorts = [4000, 8000, 8080]
168
- for (const port of commonPorts) {
172
+ for (const port of ports) {
169
173
  const baseURL = `http://localhost:${port}`
170
174
  if (await checkLiteLLMHealth(baseURL, apiKey, customHeaders)) {
171
175
  return baseURL