dsh-model-capability-sync 0.1.0 → 0.2.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/match.ts CHANGED
@@ -10,10 +10,86 @@ import type { Catalog, CatalogEntry } from './catalog.ts'
10
10
  import type { MatchInfo, MatchVia } from './types.ts'
11
11
 
12
12
  /**
13
- * Variant suffixes a gateway appends to one upstream model. Stripping them
14
- * turns `gemini-3.8-flash-high` back into the catalog's `gemini-3.8-flash`.
13
+ * Variant suffixes a gateway appends to one upstream model.
14
+ *
15
+ * A gateway re-labels the same upstream with its own selling point: `-high`,
16
+ * `-max` (a bigger window), `-tiered`, `-trial` (a trial tier), `-official`
17
+ * (the vendor's own route rather than an aggregator's), `-free`, `-it` (an
18
+ * instruction-tuned build), `-reasoning`, `-disabled` (a model the vendor
19
+ * publishes but will not serve). None of these changes what the model *is*, so
20
+ * stripping them turns `gemini-3.8-flash-tiered` back into the catalog's
21
+ * `gemini-3.8-flash` — which is what its capability facts describe.
22
+ */
23
+ const VARIANT_SUFFIX = /[-_](high|low|medium|minimal|max|xhigh|thinking|preview|latest|chat|tiered|disabled|trial|official|free|stable|experimental|reasoning|it|instruct|base|pro|flash|mini|nano|small|large)$/i
24
+
25
+ /**
26
+ * A reseller's route tag: `:free`, `:beta`, `:nitro`. It rides on the end of an
27
+ * id and says how the model is sold, never what it is.
28
+ */
29
+ const ROUTE_TAG = /:[a-z0-9][a-z0-9_-]*$/i
30
+
31
+ /**
32
+ * A trailing build number: `kimi-k3-1`, `deepseek-v4-2`.
33
+ *
34
+ * Gateways stamp a revision onto an id without changing the model, and the
35
+ * catalog usually holds only the unnumbered one. Only a bare integer tail is
36
+ * stripped, so `claude-sonnet-4-5` (where `5` is part of the version) is left
37
+ * for the dotted/named rules to handle first.
38
+ */
39
+ const BUILD_NUMBER = /-\d{1,2}$/
40
+
41
+ /**
42
+ * A reseller's own namespace wrapped around an upstream id: `sn-glm-5-3`.
43
+ *
44
+ * Aggregators (raccoon and friends) put a two-to-four letter tag in front of the
45
+ * upstream id to mark which of their pools it comes from. `sn` is not a provider
46
+ * id in the catalog — it is the reseller's abbreviation — so the tag carries no
47
+ * information about the model. Only a tag that, once removed, leaves the exact
48
+ * upstream id is accepted (see {@link resolveVendorPrefix}), which is what keeps
49
+ * a genuinely namespaced id like `kimi-k3` from being mistaken for a prefixed
50
+ * one.
51
+ */
52
+ const VENDOR_PREFIX = /^([a-z]{2,4})-(.+)$/i
53
+
54
+ /**
55
+ * Strip every variant marker from one key, repeatedly.
56
+ *
57
+ * Gateways stack markers (`gemma-4-26b-a4b-it:free` carries both `-it` and
58
+ * `:free`, `nemotron-3-nano-omni-30b-a3b-reasoning:free` both again), so one
59
+ * pass is not enough. The loop is bounded: each pass must shorten the key, and
60
+ * a key stripped to nothing is abandoned rather than searched as `''`.
61
+ * @param key - one candidate id.
62
+ * @returns the shortest key the markers allow, or undefined when none came off.
15
63
  */
16
- const VARIANT_SUFFIX = /-(high|low|medium|minimal|max|xhigh|thinking|preview|latest|chat)$/
64
+ function stripMarkers(key: string): string | undefined {
65
+ let current = key
66
+ for (let pass = 0; pass < 6; pass += 1) {
67
+ const next = current.replace(ROUTE_TAG, '').replace(VARIANT_SUFFIX, '').replace(BUILD_NUMBER, '')
68
+ if (next === current || next.length === 0) break
69
+ current = next
70
+ }
71
+ return current === key ? undefined : current
72
+ }
73
+
74
+ /**
75
+ * How a display name is reduced to the thing worth looking up.
76
+ *
77
+ * The name-redirect section appends `【qoder】` to a label, and people annotate
78
+ * by hand in other ways (`Qwen3.8-Flash (qoder)`, `[cn] Qwen3.8-Flash`). Those
79
+ * annotations are provenance, not model identity: `qoder` is a gateway, and if
80
+ * the annotation were left in, this plugin's own renaming would change what it
81
+ * resolves. Bracketed segments go; the rest is trimmed to one line.
82
+ */
83
+ const SOURCE_ANNOTATION = /【[^】]*】|\([^)]*\)|\[[^\]]*\]/g
84
+
85
+ /**
86
+ * Reduce a display name to its model part.
87
+ * @param name - the configured label.
88
+ * @returns the label without source annotations or stray whitespace.
89
+ */
90
+ export function cleanDisplayName(name: string): string {
91
+ return name.replace(SOURCE_ANNOTATION, ' ').replace(/\s+/g, ' ').trim()
92
+ }
17
93
 
18
94
  /**
19
95
  * First-party vendor provider ids in the models.dev catalog. The same model
@@ -63,15 +139,90 @@ function basename(id: string): string {
63
139
  return slash === -1 ? id : id.slice(slash + 1)
64
140
  }
65
141
 
66
- /** Look one key up exactly, then case-insensitively. */
142
+ /**
143
+ * Look one key up exactly, then case-insensitively.
144
+ *
145
+ * When the key exists verbatim, every entry with the same id ignoring case is
146
+ * offered as well. Providers disagree about casing for the same model
147
+ * (`alibaba` publishes `qwen3.8-flash` while `scnet-token-plan` publishes
148
+ * `Qwen3.8-Flash`), and picking from the verbatim set alone would hand the
149
+ * choice to whichever reseller happens to capitalise like the label — even when
150
+ * a first-party entry with better facts exists. The rule reported is still
151
+ * `exact`: the id did match verbatim, it just is not the only candidate.
152
+ * @param catalog - the indexed catalog.
153
+ * @param key - one candidate id.
154
+ * @returns the entries to choose from and the rule that found them.
155
+ */
67
156
  function lookup(catalog: Catalog, key: string): { entries: readonly CatalogEntry[]; via: MatchVia } | undefined {
68
157
  const exact = catalog.byId.get(key)
69
- if (exact !== undefined) return { entries: exact, via: 'exact' }
158
+ if (exact !== undefined) {
159
+ const folded = catalog.byFolded.get(key.toLowerCase())
160
+ // `folded` is the same ids with any casing, so it always covers `exact`
161
+ // when both exist; prefer it to widen the choice, never to narrow it.
162
+ return { entries: folded !== undefined && folded.length > exact.length ? folded : exact, via: 'exact' }
163
+ }
70
164
  const folded = catalog.byFolded.get(key.toLowerCase())
71
165
  if (folded !== undefined) return { entries: folded, via: 'folded' }
72
166
  return undefined
73
167
  }
74
168
 
169
+ /**
170
+ * Index the catalog's ids by their leading text, so a truncated key can find
171
+ * the full ids that begin with it.
172
+ *
173
+ * A gateway trims the tail of an upstream id: `nemotron-3.5-lightning` for the
174
+ * catalog's `nemotron-3.5-lightning-30b-a3b`, `north-mini-code` for
175
+ * `north-mini-code-1-0`. That tail is a parameter count or a build stamp, which
176
+ * does not change the capability facts, so a prefix hit is a real match.
177
+ * @param catalog - the indexed catalog.
178
+ * @returns prefix → the entries whose id starts with it.
179
+ */
180
+ function buildPrefixIndex(catalog: Catalog): Map<string, CatalogEntry[]> {
181
+ const index = new Map<string, CatalogEntry[]>()
182
+ for (const [id, entries] of catalog.byFolded) {
183
+ for (let length = 4; length <= id.length; length += 1) {
184
+ const key = id.slice(0, length)
185
+ const bucket = index.get(key)
186
+ if (bucket === undefined) index.set(key, [...entries])
187
+ else bucket.push(...entries)
188
+ }
189
+ }
190
+ return index
191
+ }
192
+
193
+ /** The prefix index of the last catalog it was built for. */
194
+ let prefixCache: { catalog: Catalog; index: Map<string, CatalogEntry[]> } | undefined
195
+
196
+ /**
197
+ * The prefix index for one catalog, built on first use and reused afterwards.
198
+ * @param catalog - the indexed catalog.
199
+ * @returns the prefix → entries map.
200
+ */
201
+ function prefixesOf(catalog: Catalog): Map<string, CatalogEntry[]> {
202
+ if (prefixCache !== undefined && prefixCache.catalog === catalog) return prefixCache.index
203
+ const index = buildPrefixIndex(catalog)
204
+ prefixCache = { catalog, index }
205
+ return index
206
+ }
207
+
208
+ /**
209
+ * Every spelling of a version inside one key: dash form and dot form.
210
+ *
211
+ * Vendors publish either spelling for the same model and the catalog holds only
212
+ * one of them: `claude-sonnet-4.5` sits beside `claude-sonnet-4-5`, and a
213
+ * reseller may use the opposite one from the entry it wraps
214
+ * (`sn-sensenova-6-8-flash-lite` against the catalog's
215
+ * `sensenova-6.8-flash-lite`). Only a separator between two digits is rewritten,
216
+ * so `gpt-4.1-mini` folds while a word boundary like `gpt-4-mini` is untouched.
217
+ * @param key - one candidate id.
218
+ * @returns the key first, then its folded spellings.
219
+ */
220
+ function versionSpellings(key: string): string[] {
221
+ const dashed = key.replace(/(\d)[-_.](\d)/g, '$1-$2')
222
+ const dotted = key.replace(/(\d)[-_.](\d)/g, '$1.$2')
223
+ return [...new Set([key, dashed, dotted])]
224
+ }
225
+
75
226
  /** Build the public match record for one chosen entry. */
76
227
  function describe(entry: CatalogEntry, via: MatchVia): MatchInfo {
77
228
  return {
@@ -83,47 +234,197 @@ function describe(entry: CatalogEntry, via: MatchVia): MatchInfo {
83
234
  }
84
235
  }
85
236
 
237
+ /**
238
+ * Look one key up, then the same key with its word gaps written as dashes.
239
+ * @param catalog - the indexed catalog.
240
+ * @param key - one candidate id.
241
+ * @returns the chosen entry and the rule, or undefined.
242
+ */
243
+ function lookupSpelling(catalog: Catalog, key: string): { entry: CatalogEntry; via: MatchVia } | undefined {
244
+ const exact = lookupExact(catalog, key)
245
+ if (exact !== undefined) return exact
246
+ const dashed = spellGapsAsDashes(key)
247
+ if (dashed === undefined) return undefined
248
+ const hit = lookupExact(catalog, dashed)
249
+ return hit === undefined ? undefined : { entry: hit.entry, via: 'spelling' }
250
+ }
251
+
252
+ /**
253
+ * Look a key up through every id-only rule, strictest first.
254
+ *
255
+ * The ladder is: exact → version spelled the other way → variant markers
256
+ * stripped → a reseller's namespace peeled off, then the same rules again on
257
+ * what is left. Each step only widens the net, and the step that fired is
258
+ * reported so the table can say how sure the answer is.
259
+ * @param catalog - the indexed catalog.
260
+ * @param key - one candidate id.
261
+ * @returns the chosen entry and the rule that found it, or undefined.
262
+ */
263
+ function resolveId(catalog: Catalog, key: string): { entry: CatalogEntry; via: MatchVia } | undefined {
264
+ const exact = lookupSpelling(catalog, key)
265
+ if (exact !== undefined) return exact
266
+
267
+ const withoutMarkers = stripMarkers(key)
268
+ if (withoutMarkers !== undefined) {
269
+ const hit = lookupSpelling(catalog, withoutMarkers)
270
+ if (hit !== undefined) return { entry: hit.entry, via: hit.via === 'spelling' ? 'spelling' : 'suffix' }
271
+
272
+ // A gateway that truncates the tail (`nemotron-3.5-lightning` for the
273
+ // catalog's `nemotron-3.5-lightning-30b-a3b`) leaves a prefix of a longer
274
+ // catalog id. A label's word gaps count as dashes here too, so
275
+ // `Nemotron 3.5 Lightning` reaches the same entry.
276
+ const prefixes = prefixesOf(catalog)
277
+ for (const candidate of [withoutMarkers, spellGapsAsDashes(withoutMarkers)]) {
278
+ if (candidate === undefined) continue
279
+ const prefixed = prefixes.get(candidate.toLowerCase())
280
+ if (prefixed === undefined) continue
281
+ const entry = pickBest(prefixed)
282
+ if (entry !== undefined) return { entry, via: 'prefix' }
283
+ }
284
+ }
285
+
286
+ // A reseller wraps the upstream id in its own namespace (`sn-glm-5-3` for
287
+ // `glm-5-3`). This runs last among the id rules because it removes real text:
288
+ // the guard is that only a key which then resolves *exactly* is accepted, so
289
+ // `raccoon-19b265` is not silently turned into `19b265`.
290
+ const peeled = peelVendorNamespace(key)
291
+ if (peeled !== undefined) {
292
+ const hit = lookupSpelling(catalog, peeled)
293
+ if (hit !== undefined) return { entry: hit.entry, via: 'vendor' }
294
+
295
+ const peeledStripped = stripMarkers(peeled)
296
+ if (peeledStripped !== undefined) {
297
+ const again = lookupSpelling(catalog, peeledStripped)
298
+ if (again !== undefined) return { entry: again.entry, via: 'vendor' }
299
+ }
300
+ }
301
+
302
+ return undefined
303
+ }
304
+
305
+ /**
306
+ * Write a label's word gaps as dashes: `Qwen3.8 Flash` → `Qwen3.8-Flash`.
307
+ *
308
+ * A display name is prose and uses spaces where the catalog uses separators.
309
+ * `Qwen3.8 Flash` is the catalog's `qwen3.8-flash`, and no case, version or
310
+ * marker rule can bridge a space — the two strings share no common form. Only
311
+ * the candidate is rewritten, and the result still has to match exactly, so a
312
+ * name whose words carry meaning (`Dots Studio: …`) is left unmatched rather
313
+ * than bent into something else.
314
+ * @param key - one candidate id.
315
+ * @returns the gap-free spelling, or undefined when there was no space.
316
+ */
317
+ function spellGapsAsDashes(key: string): string | undefined {
318
+ const dashed = key.replace(/\s+/g, '-')
319
+ return dashed === key ? undefined : dashed
320
+ }
321
+
322
+ /**
323
+ * Exact, case-folded, and version-spelled-the-other-way lookup, in that order.
324
+ * @param catalog - the indexed catalog.
325
+ * @param key - one candidate id.
326
+ * @returns the chosen entry and the rule, or undefined.
327
+ */
328
+ function lookupExact(catalog: Catalog, key: string): { entry: CatalogEntry; via: MatchVia } | undefined {
329
+ const spellings = versionSpellings(key)
330
+ for (const [position, spelling] of spellings.entries()) {
331
+ const hit = lookup(catalog, spelling)
332
+ if (hit === undefined) continue
333
+ const entry = pickBest(hit.entries)
334
+ if (entry === undefined) continue
335
+ // The key's own spelling keeps the rule that matched it; a folded spelling
336
+ // is reported as `folded`.
337
+ return { entry, via: position === 0 ? hit.via : 'folded' }
338
+ }
339
+ return undefined
340
+ }
341
+
342
+ /**
343
+ * Remove a reseller's leading namespace from one id.
344
+ *
345
+ * Only the shape `xxx-rest` is considered, where `xxx` is two to four letters —
346
+ * long enough to be an abbreviation, short enough to not be a model family.
347
+ * The caller must verify the result resolves exactly; without that check this
348
+ * would happily split `raccoon-chat-ml-5-5` into the meaningless `chat-ml-5-5`.
349
+ * @param key - one candidate id.
350
+ * @returns the id without its namespace, or undefined when there is none.
351
+ */
352
+ function peelVendorNamespace(key: string): string | undefined {
353
+ const match = VENDOR_PREFIX.exec(key)
354
+ if (match === null) return undefined
355
+ const rest: string | undefined = match[2]
356
+ if (rest === undefined || rest.length < 3) return undefined
357
+ return rest
358
+ }
359
+
86
360
  /**
87
361
  * Resolve one gateway model id.
362
+ *
363
+ * The walk is strict to loose: the id itself, then the id without its vendor
364
+ * prefix, then the configured display name — each of those through the full
365
+ * ladder in {@link resolveId}. An explicit alias is tried last: it is a
366
+ * hand-made fallback, and an alias applied to a name would be inherited by
367
+ * every row that name resolves, which is the opposite of an override.
88
368
  * @param catalog - the indexed catalog.
89
369
  * @param id - the gateway model id exactly as configured.
90
370
  * @param aliases - explicit gateway id → catalog id overrides.
371
+ * @param name - the configured display name, when there is one.
91
372
  * @returns the match, or `undefined` when nothing fits.
92
373
  */
93
374
  export function matchModel(
94
375
  catalog: Catalog,
95
376
  id: string,
96
377
  aliases: Readonly<Record<string, string>> = {},
378
+ name = '',
97
379
  ): MatchInfo | undefined {
98
- const alias = aliases[id]
99
- if (alias !== undefined && alias.length > 0) {
100
- const hit = lookup(catalog, alias)
101
- const entry = hit === undefined ? undefined : pickBest(hit.entries)
102
- if (entry !== undefined) return describe(entry, 'alias')
103
- }
380
+ const onId = resolveId(catalog, id)
381
+ if (onId !== undefined) return describe(onId.entry, onId.via)
104
382
 
105
- const exact = lookup(catalog, id)
106
- if (exact !== undefined) {
107
- const entry = pickBest(exact.entries)
108
- if (entry !== undefined) return describe(entry, exact.via)
383
+ // Peel the vendor prefix one segment at a time. A gateway nests its own
384
+ // namespace in front of the upstream's path (`cline/dots-studio/dots-3-note
385
+ // -preview:free` around the catalog's `dots-studio/dots-3-note-preview`), so
386
+ // the useful key is not always the basename: sometimes it is everything after
387
+ // the first segment, sometimes after the second.
388
+ const segments = id.split('/')
389
+ for (let drop = 1; drop < segments.length; drop += 1) {
390
+ const rest = segments.slice(drop).join('/')
391
+ if (rest.length === 0) continue
392
+ const onRest = resolveId(catalog, rest)
393
+ if (onRest !== undefined) return describe(onRest.entry, onRest.via === 'exact' ? 'basename' : onRest.via)
109
394
  }
110
395
 
111
- const base = basename(id)
112
- if (base !== id) {
113
- const hit = lookup(catalog, base)
114
- if (hit !== undefined) {
115
- const entry = pickBest(hit.entries)
116
- if (entry !== undefined) return describe(entry, 'basename')
396
+ // From here the name speaks for the id: try it as-is, then its last segment
397
+ // (`qoder/DeepSeek-Flash【qoder】` → `DeepSeek-Flash`). The bracketed
398
+ // annotation is dropped first, so whether the name-redirect section ran never
399
+ // changes the answer.
400
+ const label = cleanDisplayName(name)
401
+ if (label.length > 0) {
402
+ const onName = resolveId(catalog, label)
403
+ if (onName !== undefined) {
404
+ return {
405
+ ...describe(onName.entry, onName.via === 'exact' ? 'name' : onName.via === 'folded' ? 'name' : 'nameSuffix'),
406
+ matchedName: label,
407
+ nameSource: 'name',
408
+ }
409
+ }
410
+ const tail = basename(label)
411
+ if (tail !== label && tail.length > 0) {
412
+ const onTail = resolveId(catalog, tail)
413
+ if (onTail !== undefined) {
414
+ return {
415
+ ...describe(onTail.entry, onTail.via === 'exact' ? 'name' : onTail.via === 'folded' ? 'name' : 'nameSuffix'),
416
+ matchedName: tail,
417
+ nameSource: 'name',
418
+ }
419
+ }
117
420
  }
118
421
  }
119
422
 
120
- const stripped = base.replace(VARIANT_SUFFIX, '')
121
- if (stripped !== base && stripped.length > 0) {
122
- const hit = lookup(catalog, stripped)
123
- if (hit !== undefined) {
124
- const entry = pickBest(hit.entries)
125
- if (entry !== undefined) return describe(entry, 'suffix')
126
- }
423
+ const alias = aliases[id]
424
+ if (alias !== undefined && alias.length > 0) {
425
+ const hit = lookup(catalog, alias)
426
+ const entry = hit === undefined ? undefined : pickBest(hit.entries)
427
+ if (entry !== undefined) return describe(entry, 'alias')
127
428
  }
128
429
 
129
430
  return undefined
package/src/sort.ts CHANGED
@@ -3,15 +3,24 @@
3
3
  *
4
4
  * A gateway id carries its vendor as a path prefix (`qoder-gj/Qwen3.8-Flash`),
5
5
  * so sorting on the whole id would group by nothing useful: the model family
6
- * is the part after the slash, and the vendor is what a reader scans for. The
7
- * order is therefore: vendor prefix first, then the model name inside it. An
8
- * id without a prefix has only its name to sort on.
6
+ * is the part after the slash, and the vendor is what a reader scans for.
7
+ *
8
+ * Two orders are offered, because two different questions get asked of the
9
+ * same list. `prefix` groups by vendor -- the right shape when the list is
10
+ * arranged around who serves what. `redirected` sorts on the name a picker
11
+ * shows once the source prefix has been moved to the end
12
+ * (`Qwen3.8-Flash【qoder】`, literally with full-width brackets),
13
+ * which reads as one alphabetical model list instead of one silo per vendor.
9
14
  *
10
15
  * Comparison is case-insensitive, with the raw id as the final tie-break, so
11
16
  * two runs on the same configuration always produce the same array.
12
17
  * @module dsh-model-capability-sync/sort
13
18
  */
14
19
 
20
+ /** How a model list is ordered. */
21
+ export type SortMode = 'prefix' | 'redirected'
22
+
23
+
15
24
  /** The two ordering keys of one id: the vendor group, then the model name. */
16
25
  export interface ModelSortKey {
17
26
  /** The prefix before the last slash, or the whole id when there is none. */
@@ -34,6 +43,73 @@ export function modelSortKey(id: string): ModelSortKey {
34
43
  return { group: id.slice(0, slash).toLowerCase(), name: id.slice(slash + 1).toLowerCase() }
35
44
  }
36
45
 
46
+ /**
47
+ * The prefix a redirect would append, i.e. the vendor segment of the id.
48
+ * @param id - the gateway model id exactly as configured.
49
+ * @returns the first path segment, or `''` when the id has none.
50
+ */
51
+ export function sourcePrefix(id: string): string {
52
+ const slash = id.indexOf('/')
53
+ return slash <= 0 ? '' : id.slice(0, slash)
54
+ }
55
+
56
+ /**
57
+ * The redirected sort key for one model: the source prefix (in brackets) as the primary key.
58
+ *
59
+ * When models are redirected to have the source prefix at the beginning in full-width
60
+ * brackets (`【workbuddy】 GLM-5.3-Flash`), a natural sort is to group by that
61
+ * prefix first (so all `【workbuddy】` together), then sort within the group by
62
+ * the model name. Models without a source prefix use `【other】` as their group.
63
+ * This gives the appearance of a list organized by vendor, with a readable name
64
+ * for each.
65
+ *
66
+ * The prefix is extracted from the displayed name if present; if absent,
67
+ * the ID prefix is used (or 'other' if the ID has no prefix).
68
+ *
69
+ * @param id - the gateway model id exactly as configured.
70
+ * @param name - the configured display name; `''` when unset.
71
+ * @returns a tuple `[prefix, modelName]` for two-level sort: first by prefix,
72
+ * then by name, both lower-cased.
73
+ */
74
+ export function redirectedSortKey(id: string, name: string): [string, string] {
75
+ const idPrefix = sourcePrefix(id)
76
+ const displayName = name !== '' ? name : id
77
+
78
+ // Extract the bracketed prefix from the beginning or end of the display name.
79
+ // Patterns: 【vendor】 (new, at start), (vendor) at start, or [vendor]
80
+ let extracted = ''
81
+ let cleaned = displayName
82
+
83
+ // Try leading full-width 【vendor】 first (the new format)
84
+ const leadingFullWidthMatch = displayName.match(/^【([^】]+)】\s*/)
85
+ if (leadingFullWidthMatch) {
86
+ extracted = leadingFullWidthMatch[1] ?? ''
87
+ cleaned = displayName.slice(leadingFullWidthMatch[0].length).trim()
88
+ } else {
89
+ // Try trailing full-width 【vendor】 (old format, backward compatibility)
90
+ const trailingFullWidthMatch = displayName.match(/【([^】]+)】\s*$/)
91
+ if (trailingFullWidthMatch) {
92
+ extracted = trailingFullWidthMatch[1] ?? ''
93
+ cleaned = displayName.slice(0, -trailingFullWidthMatch[0].length).trim()
94
+ } else {
95
+ // Try half-width () or [] at any position
96
+ const halfWidthMatch = displayName.match(/[([]\s*([^)\]]*)\s*[)\]]\s*/)
97
+ if (halfWidthMatch) {
98
+ extracted = halfWidthMatch[1] ?? ''
99
+ // Remove the matched half-width from cleaned
100
+ cleaned = displayName.replace(halfWidthMatch[0], '').trim()
101
+ }
102
+ }
103
+ }
104
+
105
+ // If no prefix was found in the name, use the ID prefix (or 'other' if none)
106
+ const sortPrefix = extracted !== '' ? extracted : (idPrefix !== '' ? idPrefix : 'other')
107
+ // If the cleaned name is empty, use the ID without its prefix as fallback
108
+ const sortName = cleaned !== '' ? cleaned : (idPrefix !== '' ? id.slice(idPrefix.length + 1) : id)
109
+
110
+ return [sortPrefix.toLowerCase(), sortName.toLowerCase()]
111
+ }
112
+
37
113
  /**
38
114
  * Compare two ids in display order.
39
115
  * @param left - first id.
@@ -51,12 +127,48 @@ export function compareModelIds(left: string, right: string): number {
51
127
  return left < right ? -1 : 1
52
128
  }
53
129
 
130
+ /**
131
+ * Compare two ids as `redirected` order would list them: group by source
132
+ * prefix (from the bracketed annotation), then sort by model name within group.
133
+ * @param left - first id.
134
+ * @param right - second id.
135
+ * @param nameOf - reads one id's display name.
136
+ * @returns negative when `left` sorts first, positive when `right` does.
137
+ */
138
+ export function compareRedirected(
139
+ left: string,
140
+ right: string,
141
+ nameOf: (id: string) => string,
142
+ ): number {
143
+ const [aPrefix, aName] = redirectedSortKey(left, nameOf(left))
144
+ const [bPrefix, bName] = redirectedSortKey(right, nameOf(right))
145
+ // Primary sort: by prefix (vendor)
146
+ if (aPrefix !== bPrefix) return aPrefix < bPrefix ? -1 : 1
147
+ // Secondary sort: by model name within the same prefix
148
+ if (aName !== bName) return aName < bName ? -1 : 1
149
+ // Tie-break: raw IDs for determinism
150
+ if (left === right) return 0
151
+ return left < right ? -1 : 1
152
+ }
153
+
54
154
  /**
55
155
  * Return a sorted copy of a model list.
56
156
  * @param items - entries in any order; the input array is never mutated.
57
157
  * @param idOf - reads the model id out of one entry.
58
- * @returns the entries in vendor-then-name order.
158
+ * @param nameOf - reads the display name out of one entry.
159
+ * @param mode - `prefix` (vendor groups) or `redirected` (shown label).
160
+ * @returns the entries in the requested order.
59
161
  */
60
- export function sortByModelId<T>(items: readonly T[], idOf: (item: T) => string): T[] {
61
- return [...items].sort((left, right) => compareModelIds(idOf(left), idOf(right)))
162
+ export function sortByModelId<T>(
163
+ items: readonly T[],
164
+ idOf: (item: T) => string,
165
+ nameOf: (item: T) => string = () => '',
166
+ mode: SortMode = 'prefix',
167
+ ): T[] {
168
+ const copy = [...items]
169
+ if (mode === 'redirected') {
170
+ const names = new Map(copy.map(item => [idOf(item), nameOf(item)] as const))
171
+ return copy.sort((left, right) => compareRedirected(idOf(left), idOf(right), id => names.get(id) ?? ''))
172
+ }
173
+ return copy.sort((left, right) => compareModelIds(idOf(left), idOf(right)))
62
174
  }
package/src/types.ts CHANGED
@@ -31,7 +31,10 @@ export interface CapabilityFields {
31
31
  }
32
32
 
33
33
  /** How a gateway id was matched against the catalog. */
34
- export type MatchVia = 'alias' | 'exact' | 'folded' | 'basename' | 'suffix'
34
+ export type MatchVia = 'alias' | 'exact' | 'folded' | 'basename' | 'suffix' | 'prefix' | 'vendor' | 'spelling' | 'name' | 'nameSuffix'
35
+
36
+ /** Where the key a `name` match used came from: the stored display name, or its id as a last resort. */
37
+ export type NameSource = 'name' | 'id'
35
38
 
36
39
  /** The catalog entry a gateway id resolved to. */
37
40
  export interface MatchInfo {
@@ -41,6 +44,10 @@ export interface MatchInfo {
41
44
  modelId: string
42
45
  /** Which rule produced this match. */
43
46
  via: MatchVia
47
+ /** For a `name`/`nameSuffix` match: the label the id was resolved through. */
48
+ matchedName?: string
49
+ /** For a `name`/`nameSuffix` match: whether that label was the display name or the id. */
50
+ nameSource?: NameSource
44
51
  /** True when the entry belongs to the model's first-party vendor, not a reseller. */
45
52
  firstParty?: boolean
46
53
  /** Human name from the catalog, when present. */
@@ -51,6 +58,8 @@ export interface MatchInfo {
51
58
  export interface PreviewRow {
52
59
  /** The gateway model id exactly as configured. */
53
60
  id: string
61
+ /** The configured display name, when the request carried one. */
62
+ name?: string
54
63
  match?: MatchInfo
55
64
  fields?: CapabilityFields
56
65
  /** Why no capability could be resolved, when `fields` is absent. */
@@ -63,6 +72,13 @@ export interface PreviewRequest {
63
72
  ids: string[]
64
73
  /** Explicit gateway id → models.dev model id overrides, applied first. */
65
74
  aliases?: Record<string, string>
75
+ /**
76
+ * Display names by gateway id. A display name often carries facts the id
77
+ * does not — a gateway may expose `qoder/qfmodel` labelled `Qwen3.8-Flash`,
78
+ * or the label may keep the upstream id in front. When the id itself
79
+ * resolves to nothing, these are tried before giving up.
80
+ */
81
+ names?: Record<string, string>
66
82
  /** Forward-proxy URL for the catalog download. */
67
83
  proxyUrl?: string
68
84
  /** Bypass the in-memory catalog cache. */