dsh-model-capability-sync 0.0.0-stage → 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 ADDED
@@ -0,0 +1,431 @@
1
+ /**
2
+ * Matching one configured gateway model id against the models.dev catalog.
3
+ *
4
+ * A gateway aggregates arbitrary upstreams and invents its own ids, so the
5
+ * match walks from strict to loose and reports which rule fired — the UI shows
6
+ * it, and an explicit alias always wins.
7
+ * @module dsh-model-capability-sync/match
8
+ */
9
+ import type { Catalog, CatalogEntry } from './catalog.ts'
10
+ import type { MatchInfo, MatchVia } from './types.ts'
11
+
12
+ /**
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.
63
+ */
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
+ }
93
+
94
+ /**
95
+ * First-party vendor provider ids in the models.dev catalog. The same model
96
+ * appears under dozens of aggregators whose capacity numbers disagree, so a
97
+ * vendor entry outranks every reseller when both exist.
98
+ */
99
+ const FIRST_PARTY = new Set([
100
+ 'openai', 'anthropic', 'google', 'deepseek', 'xai', 'meta', 'mistral', 'cohere',
101
+ 'moonshotai', 'moonshotai-cn', 'zai', 'zhipuai', 'alibaba', 'alibaba-cn', 'qwen',
102
+ 'sensenova', 'minimax', 'stepfun', 'bytedance', 'baidu', 'nvidia', 'microsoft',
103
+ 'amazon', 'ai21', 'perplexity', 'upstage', '01-ai', 'inclusionai', 'tencent', 'kuaishou',
104
+ ])
105
+
106
+ /** How complete an entry's facts are; the most complete wins a tie. */
107
+ function score(entry: CatalogEntry): number {
108
+ const model = entry.model
109
+ let value = 0
110
+ if (FIRST_PARTY.has(entry.provider)) value += 5
111
+ if (model.limit?.context !== undefined || model.limit?.output !== undefined) value += 2
112
+ if (model.modalities?.input !== undefined) value += 2
113
+ if (model.reasoning_options !== undefined) value += 1
114
+ if (model.name !== undefined) value += 1
115
+ return value
116
+ }
117
+
118
+ /**
119
+ * Pick the best of several provider entries for the same id: the one carrying
120
+ * the most facts, then the alphabetically first provider so repeated runs are
121
+ * stable.
122
+ */
123
+ function pickBest(entries: readonly CatalogEntry[]): CatalogEntry | undefined {
124
+ let best: CatalogEntry | undefined
125
+ let bestScore = -1
126
+ for (const entry of entries) {
127
+ const value = score(entry)
128
+ if (value > bestScore || value === bestScore && best !== undefined && entry.provider < best.provider) {
129
+ best = entry
130
+ bestScore = value
131
+ }
132
+ }
133
+ return best
134
+ }
135
+
136
+ /** The id without its vendor path prefix (`qoder-gj/DeepSeek-Flash` → `DeepSeek-Flash`). */
137
+ function basename(id: string): string {
138
+ const slash = id.lastIndexOf('/')
139
+ return slash === -1 ? id : id.slice(slash + 1)
140
+ }
141
+
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
+ */
156
+ function lookup(catalog: Catalog, key: string): { entries: readonly CatalogEntry[]; via: MatchVia } | undefined {
157
+ const exact = catalog.byId.get(key)
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
+ }
164
+ const folded = catalog.byFolded.get(key.toLowerCase())
165
+ if (folded !== undefined) return { entries: folded, via: 'folded' }
166
+ return undefined
167
+ }
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
+
226
+ /** Build the public match record for one chosen entry. */
227
+ function describe(entry: CatalogEntry, via: MatchVia): MatchInfo {
228
+ return {
229
+ provider: entry.provider,
230
+ modelId: entry.id,
231
+ via,
232
+ firstParty: FIRST_PARTY.has(entry.provider),
233
+ ...entry.model.name === undefined ? {} : { name: entry.model.name },
234
+ }
235
+ }
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
+
360
+ /**
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.
368
+ * @param catalog - the indexed catalog.
369
+ * @param id - the gateway model id exactly as configured.
370
+ * @param aliases - explicit gateway id → catalog id overrides.
371
+ * @param name - the configured display name, when there is one.
372
+ * @returns the match, or `undefined` when nothing fits.
373
+ */
374
+ export function matchModel(
375
+ catalog: Catalog,
376
+ id: string,
377
+ aliases: Readonly<Record<string, string>> = {},
378
+ name = '',
379
+ ): MatchInfo | undefined {
380
+ const onId = resolveId(catalog, id)
381
+ if (onId !== undefined) return describe(onId.entry, onId.via)
382
+
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)
394
+ }
395
+
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
+ }
420
+ }
421
+ }
422
+
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')
428
+ }
429
+
430
+ return undefined
431
+ }
package/src/sort.ts ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Ordering for one provider's model list.
3
+ *
4
+ * A gateway id carries its vendor as a path prefix (`qoder-gj/Qwen3.8-Flash`),
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.
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.
14
+ *
15
+ * Comparison is case-insensitive, with the raw id as the final tie-break, so
16
+ * two runs on the same configuration always produce the same array.
17
+ * @module dsh-model-capability-sync/sort
18
+ */
19
+
20
+ /** How a model list is ordered. */
21
+ export type SortMode = 'prefix' | 'redirected'
22
+
23
+
24
+ /** The two ordering keys of one id: the vendor group, then the model name. */
25
+ export interface ModelSortKey {
26
+ /** The prefix before the last slash, or the whole id when there is none. */
27
+ group: string
28
+ /** The part after the last slash, or the whole id when there is none. */
29
+ name: string
30
+ }
31
+
32
+ /**
33
+ * Split one id into its ordering keys.
34
+ * @param id - the gateway model id exactly as configured.
35
+ * @returns folded keys; the caller compares them, never displays them.
36
+ */
37
+ export function modelSortKey(id: string): ModelSortKey {
38
+ const slash = id.lastIndexOf('/')
39
+ if (slash === -1) {
40
+ const folded = id.toLowerCase()
41
+ return { group: folded, name: folded }
42
+ }
43
+ return { group: id.slice(0, slash).toLowerCase(), name: id.slice(slash + 1).toLowerCase() }
44
+ }
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
+
113
+ /**
114
+ * Compare two ids in display order.
115
+ * @param left - first id.
116
+ * @param right - second id.
117
+ * @returns negative when `left` sorts first, positive when `right` does.
118
+ */
119
+ export function compareModelIds(left: string, right: string): number {
120
+ const a = modelSortKey(left)
121
+ const b = modelSortKey(right)
122
+ if (a.group !== b.group) return a.group < b.group ? -1 : 1
123
+ if (a.name !== b.name) return a.name < b.name ? -1 : 1
124
+ // Same folded pair: keep the raw spelling as the tie-break so the result is
125
+ // deterministic instead of depending on the input order.
126
+ if (left === right) return 0
127
+ return left < right ? -1 : 1
128
+ }
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
+
154
+ /**
155
+ * Return a sorted copy of a model list.
156
+ * @param items - entries in any order; the input array is never mutated.
157
+ * @param idOf - reads the model id out of one entry.
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.
161
+ */
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)))
174
+ }