dsh-token-dash 2.0.2 → 2.1.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/core.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Pure aggregation: day/month keys, provider/model buckets, budgets, currencies.
3
3
  * No file or clock reads; `now` is injected.
4
4
  */
5
- import { priceFor } from './pricing.js'
5
+ import { explainPriceMiss, resolvePrice } from './pricing.js'
6
6
  import {
7
7
  canBeSubscription,
8
8
  defaultModelFor,
@@ -12,6 +12,7 @@ import {
12
12
  pricingLinks,
13
13
  providerCurrency,
14
14
  providerFromModel,
15
+ providerKind,
15
16
  providerLabel,
16
17
  } from './providers.js'
17
18
 
@@ -40,16 +41,16 @@ export function isPeak(ts) {
40
41
  return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
41
42
  }
42
43
 
43
- export { normalizeProvider, providerLabel, normalizeModel, priceFor }
44
+ export { normalizeProvider, providerLabel, normalizeModel, resolvePrice }
44
45
  export const displayModel = modelLabel
45
46
 
46
- export function priceForRecord(provider, model, ts) {
47
- return priceFor(provider, model, ts)
47
+ export function priceForRecord(model, provider, ts) {
48
+ return resolvePrice(model, provider, ts)
48
49
  }
49
50
 
50
51
  /** Undefined price returns 0; the caller marks `priced=false`. */
51
52
  export function costOf(record) {
52
- const price = priceFor(record.provider ?? 'unknown', record.model, record.ts)
53
+ const price = resolvePrice(record.model, record.provider ?? 'unknown', record.ts)
53
54
  if (price === null) return 0
54
55
  return (
55
56
  (num(record.input) * price.input +
@@ -63,7 +64,7 @@ export function costOf(record) {
63
64
  export function emptyState() {
64
65
  return {
65
66
  version: 1,
66
- costVersion: 3,
67
+ costVersion: 4,
67
68
  days: {},
68
69
  watermarks: {},
69
70
  headers: {},
@@ -81,9 +82,10 @@ function dayStartTs(dayKey) {
81
82
  /**
82
83
  * 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
83
84
  * 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
85
+ * 重算同样走「形态先于计价 + 币种不匹配不计价」,订阅行与零消耗行保持原状态。
84
86
  */
85
- export function repriceState(state) {
86
- if (state.costVersion === 3) return { repriced: false, rows: 0 }
87
+ export function repriceState(state, kindOf = (id) => providerKind(id)) {
88
+ if (state.costVersion === 4) return { repriced: false, rows: 0 }
87
89
  let rows = 0
88
90
  for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
89
91
  const ts = dayStartTs(dayKey)
@@ -92,17 +94,29 @@ export function repriceState(state) {
92
94
  for (const [model, row] of Object.entries(providerBucket?.models ?? {})) {
93
95
  // unknown 行只影响计价归属;展示层仍按模型前缀归因
94
96
  const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
95
- const price = owner === null ? null : priceFor(owner, model, ts)
96
- const missing = price === null || price.input === null || price.output === null
97
- row.cost = missing
97
+ // 形态先于计价:订阅 provider 的行保持原值,重算不得写成金额
98
+ if (owner !== null && kindOf(owner) !== 'api') continue
99
+ const empty = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output) === 0
100
+ const price = owner === null ? null : resolvePrice(model, owner, ts)
101
+ const missing = price === null || price.mismatch === true || price.input === null || price.output === null
102
+ row.cost = missing || empty
98
103
  ? 0
99
104
  : costOf({ ts, provider: owner ?? providerId, model, input: row.input, cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output })
100
- row.priced = !missing
105
+ if (empty) {
106
+ row.priced = 'empty'
107
+ delete row.reason
108
+ } else if (missing) {
109
+ row.priced = false
110
+ row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
111
+ } else {
112
+ row.priced = true
113
+ delete row.reason
114
+ }
101
115
  rows += 1
102
116
  }
103
117
  }
104
118
  }
105
- state.costVersion = 3
119
+ state.costVersion = 4
106
120
  return { repriced: true, rows }
107
121
  }
108
122
 
@@ -140,7 +154,7 @@ export function reattributeUnknown(state, providerByModel) {
140
154
  }
141
155
  }
142
156
 
143
- export function addRecord(state, record) {
157
+ export function addRecord(state, record, kindOf = (id) => providerKind(id)) {
144
158
  const day = localDayKey(record.ts)
145
159
  const bucket = dayBucket(state, day)
146
160
  if (bucket.providers === undefined) {
@@ -164,13 +178,82 @@ export function addRecord(state, record) {
164
178
  row.cacheWrite += num(record.cacheWrite)
165
179
  row.output += num(record.output)
166
180
  row.requests += 1
167
- const price = priceFor(provider, model, record.ts)
168
- const priceMissing = price === null || price.input === null || price.output === null
169
- if (priceMissing) row.priced = false
170
- row.cost += priceMissing ? 0 : costOf({ ...record, provider })
181
+ // 形态先于计价:订阅套餐按套餐结算,套模型价会把 USD 订阅算成 RMB 用量费(REQ-12)。
182
+ if (kindOf(provider) === 'subscription') {
183
+ row.priced = 'subscription'
184
+ delete row.reason
185
+ } else {
186
+ const price = resolvePrice(model, provider, record.ts)
187
+ // 币种不匹配按未定价处理:宁可空着,也不把 CNY 报价写进 USD 桶(REQ-03)
188
+ if (price === null || price.mismatch === true) {
189
+ row.priced = false
190
+ row.reason = price === null ? explainPriceMiss(model) : 'currency-mismatch'
191
+ } else {
192
+ row.priced = true
193
+ delete row.reason
194
+ row.cost += (
195
+ num(record.input) * price.input +
196
+ num(record.cacheRead) * price.cacheRead +
197
+ num(record.cacheWrite) * price.cacheWrite +
198
+ num(record.output) * price.output
199
+ ) / 1e6
200
+ }
201
+ }
202
+ // 零消耗行与"真缺价"必须可区分:最后写,覆盖上面两种结果(REQ-10)。
203
+ if (row.input + row.cacheRead + row.cacheWrite + row.output === 0) row.priced = 'empty'
171
204
  state.currentProvider = provider
172
205
  }
173
206
 
207
+ /**
208
+ * 只补 `priced === false` 的行;`true` / `'subscription'` / `'empty'` 一律不动。
209
+ * `unknown` 桶按模型前缀归因,避免"展示有归属、补算却跳过"。
210
+ */
211
+ export function repriceUnpriced(state, scope, kindOf = (id) => providerKind(id)) {
212
+ const month = typeof scope?.month === 'string' && /^\d{4}-\d{2}$/.test(scope.month) ? scope.month : null
213
+ const result = { scope: scope?.month ?? 'all', rows: 0, skipped: { 'no-owner': 0, kind: 0, 'no-price': 0, currency: 0 } }
214
+ for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
215
+ if (month !== null && !dayKey.startsWith(`${month}-`)) continue
216
+ const ts = dayStartTs(dayKey)
217
+ if (ts === null) continue
218
+ for (const [providerId, providerBucket] of Object.entries(bucket?.providers ?? {})) {
219
+ for (const [rawModel, row] of Object.entries(providerBucket?.models ?? {})) {
220
+ if (row?.priced !== false) continue
221
+ const model = normalizeModel(rawModel)
222
+ const owner = providerId === 'unknown' ? providerFromModel(model) : providerId
223
+ if (owner === null) {
224
+ result.skipped['no-owner'] += 1
225
+ continue
226
+ }
227
+ if (kindOf(owner) !== 'api') {
228
+ result.skipped.kind += 1
229
+ continue
230
+ }
231
+ const price = resolvePrice(model, owner, ts)
232
+ if (price === null) {
233
+ result.skipped['no-price'] += 1
234
+ continue
235
+ }
236
+ // 币种不符的行保持未定价,只把原因改写清楚,等用户补 USD 单价后再补算
237
+ if (price.mismatch === true) {
238
+ result.skipped.currency += 1
239
+ row.reason = 'currency-mismatch'
240
+ continue
241
+ }
242
+ row.cost = (
243
+ num(row.input) * price.input +
244
+ num(row.cacheRead) * price.cacheRead +
245
+ num(row.cacheWrite) * price.cacheWrite +
246
+ num(row.output) * price.output
247
+ ) / 1e6
248
+ row.priced = true
249
+ delete row.reason
250
+ result.rows += 1
251
+ }
252
+ }
253
+ }
254
+ return result
255
+ }
256
+
174
257
  /** 未填写时的默认预算,按 provider 币种;只在 VM 内生效,不写盘。 */
175
258
  export const DEFAULT_BUDGET = 100
176
259
 
@@ -193,11 +276,11 @@ function budgetFor(prefs, providerId, currency) {
193
276
  }
194
277
  }
195
278
 
196
- function providerEmpty(providerId) {
279
+ function providerEmpty(providerId, kind = 'api') {
197
280
  return {
198
281
  id: providerId,
199
282
  name: providerLabel(providerId),
200
- kind: 'api',
283
+ kind,
201
284
  canSubscribe: canBeSubscription(providerId),
202
285
  currency: providerCurrency(providerId),
203
286
  usage: { todayTokens: 0, monthTokens: 0, todayCost: 0, monthCost: 0, requests: 0 },
@@ -218,14 +301,27 @@ function emptyTotals() {
218
301
  return { cost: 0, requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, hitRate: null }
219
302
  }
220
303
 
221
- /** 行内与 0 桶共用:快照币种优先,缺失回退 registry,不写死 CNY。 */
222
- function usageCurrency(providerId, meta) {
304
+ /** 行内与 0 桶共用:声明 > 快照 > registry,不写死 CNY。 */
305
+ function usageCurrency(providerId, meta, prefs) {
306
+ const declared = prefs?.providerCurrency?.[providerId]
307
+ if (declared === 'USD' || declared === 'CNY') return declared
223
308
  if (meta?.currency === 'USD') return 'USD'
224
309
  if (meta?.currency === 'CNY') return 'CNY'
225
310
  return providerCurrency(providerId)
226
311
  }
227
312
 
228
- /** prefs 显式覆盖 > 快照确定的 mode > 历史固化值 > 快照 kind > api。 */
313
+ /** 币种来源只影响展示文案,不参与计算(BND-10)。 */
314
+ function currencySourceOf(prefs, providerId, meta) {
315
+ const declared = prefs?.providerCurrency?.[providerId]
316
+ if (declared === 'USD' || declared === 'CNY') return 'prefs'
317
+ if (meta?.currency === 'USD' || meta?.currency === 'CNY') return 'snapshot'
318
+ return 'community'
319
+ }
320
+
321
+ /**
322
+ * prefs 显式覆盖 > 快照确定的 mode > 历史固化值 > registry 静态声明 > api。
323
+ * `meta.kind` 是 adapter 规整后的回声值(非订阅一律 `api`),不能当作"探测到了 api"的证据。
324
+ */
229
325
  export function resolveProviderKind(state, prefs, providerId, meta) {
230
326
  const id = normalizeProvider(providerId)
231
327
  const explicit = prefs?.billingModes?.[id]
@@ -233,7 +329,7 @@ export function resolveProviderKind(state, prefs, providerId, meta) {
233
329
  if (BILLING_MODES.has(meta?.mode)) return meta.mode
234
330
  const stamped = state?.providerKinds?.[id]
235
331
  if (BILLING_MODES.has(stamped)) return stamped
236
- return meta?.kind === 'subscription' ? 'subscription' : 'api'
332
+ return providerKind(id)
237
333
  }
238
334
 
239
335
  /** 只固化"探测确定"的形态;unknown 不覆盖历史,返回是否有变化。 */
@@ -280,7 +376,7 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
280
376
  const meta = info.get(providerId)
281
377
  const kind = resolveProviderKind(state, prefs, providerId, meta)
282
378
  const billable = kind === 'api'
283
- const currency = usageCurrency(providerId, meta)
379
+ const currency = usageCurrency(providerId, meta, prefs)
284
380
  const key = `${providerId}:${modelId}`
285
381
  const entry = models.get(key) ?? {
286
382
  providerId,
@@ -307,8 +403,11 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
307
403
  // 订阅模型按目录价算出的 cost 不是真实支出,VM 内归零,保证费用框与 Tokens 框同一集合
308
404
  entry.cost += billable ? num(row.cost) : 0
309
405
  if (row.priced === false) entry.priced = false
406
+ if (row.priced === 'empty') entry.emptyRows = (entry.emptyRows ?? 0) + 1
407
+ entry.rows = (entry.rows ?? 0) + 1
310
408
  entry.kind = kind
311
409
  entry.currency = currency
410
+ entry.currencySource = currencySourceOf(prefs, providerId, meta)
312
411
  models.set(key, entry)
313
412
  }
314
413
 
@@ -346,7 +445,12 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
346
445
  },
347
446
  hitRate: denominator > 0 ? entry.cacheRead / denominator : null,
348
447
  cost: round2(entry.cost),
349
- approximate: entry.billable && priceFor(entry.providerId, entry.modelId, now)?.approximate === true,
448
+ approximate: entry.billable && resolvePrice(entry.modelId, entry.providerId, now)?.approximate === true,
449
+ priced: entry.priced !== false
450
+ ? (entry.rows > 0 && (entry.emptyRows ?? 0) < entry.rows ? true : 'empty')
451
+ : false,
452
+ rows: undefined,
453
+ emptyRows: undefined,
350
454
  }
351
455
  })
352
456
  rows.sort((a, b) => b.cost - a.cost)
@@ -417,15 +521,18 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
417
521
  const { plans: legacyPlans, mode: _mode, ...info } = item
418
522
  const id = normalizeProvider(info.id ?? info.provider)
419
523
  if (id === 'unknown' || hidden.has(id)) continue
420
- const base = providerMap.get(id) ?? providerEmpty(id)
524
+ const kind = resolveProviderKind(state, prefs, id, item)
525
+ const currency = usageCurrency(id, item, prefs)
526
+ const base = providerMap.get(id) ?? providerEmpty(id, kind)
421
527
  providerMap.set(id, {
422
528
  ...base,
423
529
  ...info,
424
530
  id,
425
531
  name: info.name ?? providerLabel(id),
426
- kind: resolveProviderKind(state, prefs, id, item),
532
+ kind,
427
533
  canSubscribe: canBeSubscription(id),
428
- currency: info.currency === 'USD' ? 'USD' : (info.currency === 'CNY' ? 'CNY' : providerCurrency(id)),
534
+ currency,
535
+ currencySource: currencySourceOf(prefs, id, item),
429
536
  usage: { ...base.usage, ...(info.usage ?? {}) },
430
537
  balance: info.balance ?? base.balance,
431
538
  windows: info.windows ?? legacyPlans ?? base.windows ?? [],
@@ -433,8 +540,11 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
433
540
  }
434
541
 
435
542
  // #41/#42:unknown 行按模型名前缀视图层归因(不改 daily.json);models 与 provider.usage 均为当月口径(#42 回退跨月累计)
543
+ const unpriced = []
436
544
  const accumulate = (providerId, modelId, row, isToday) => {
437
- const provider = providerMap.get(providerId) ?? providerEmpty(providerId)
545
+ const meta = providerInfo.find((item) => normalizeProvider(item.id ?? item.provider) === providerId)
546
+ const kind = resolveProviderKind(state, prefs, providerId, meta)
547
+ const provider = providerMap.get(providerId) ?? providerEmpty(providerId, kind)
438
548
  providerMap.set(providerId, provider)
439
549
  const key = `${providerId}:${modelId}`
440
550
  const entry = modelsMap.get(key) ?? {
@@ -443,34 +553,53 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
443
553
  providerId,
444
554
  providerName: providerLabel(providerId),
445
555
  displayName: modelLabel(modelId),
446
- kind: provider.kind,
556
+ kind,
447
557
  currency: provider.currency,
558
+ currencySource: provider.currencySource,
448
559
  priced: true,
449
560
  approximate: false,
561
+ reason: null,
450
562
  requests: 0,
451
563
  input: 0,
452
564
  cacheRead: 0,
453
565
  cacheWrite: 0,
454
566
  output: 0,
455
567
  cost: 0,
568
+ rows: 0,
456
569
  }
457
570
  entry.requests += num(row.requests)
458
571
  entry.input += num(row.input)
459
572
  entry.cacheRead += num(row.cacheRead)
460
573
  entry.cacheWrite += num(row.cacheWrite)
461
574
  entry.output += num(row.output)
462
- entry.cost += num(row.cost)
463
- if (row.priced === false) entry.priced = false
464
- const price = priceFor(providerId, modelId, now)
575
+ entry.rows += 1
576
+ // 订阅行按套餐结算:历史里存下的目录价不算支出(REQ-12)
577
+ const billable = kind === 'api'
578
+ entry.cost += billable ? num(row.cost) : 0
579
+ if (row.priced === false) {
580
+ entry.priced = false
581
+ entry.reason ??= row.reason ?? 'no-model-price'
582
+ }
583
+ if (row.priced === 'empty') entry.emptyRows = (entry.emptyRows ?? 0) + 1
584
+ if (billable && row.priced === false) {
585
+ unpriced.push({
586
+ modelId,
587
+ providerId,
588
+ tokens: num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output),
589
+ requests: num(row.requests),
590
+ reason: row.reason ?? 'no-model-price',
591
+ })
592
+ }
593
+ const price = resolvePrice(modelId, providerId, now)
465
594
  if (price?.approximate === true) entry.approximate = true
466
595
  modelsMap.set(key, entry)
467
596
  const tokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
468
597
  provider.usage.monthTokens += tokens
469
- provider.usage.monthCost += num(row.cost)
598
+ provider.usage.monthCost += billable ? num(row.cost) : 0
470
599
  provider.usage.requests += num(row.requests)
471
600
  if (isToday) {
472
601
  provider.usage.todayTokens += tokens
473
- provider.usage.todayCost += num(row.cost)
602
+ provider.usage.todayCost += billable ? num(row.cost) : 0
474
603
  }
475
604
  provider.models.push(entry.modelId)
476
605
  }
@@ -516,14 +645,17 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
516
645
  displayName: modelLabel(fallbackModel),
517
646
  kind: provider?.kind === 'subscription' ? 'subscription' : 'api',
518
647
  currency: provider?.currency ?? providerCurrency(id),
519
- priced: true,
648
+ currencySource: provider?.currencySource ?? 'community',
649
+ priced: 'empty',
520
650
  approximate: false,
651
+ reason: null,
521
652
  requests: 0,
522
653
  input: 0,
523
654
  cacheRead: 0,
524
655
  cacheWrite: 0,
525
656
  output: 0,
526
657
  cost: 0,
658
+ rows: 0,
527
659
  })
528
660
  }
529
661
 
@@ -535,6 +667,13 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
535
667
  : null
536
668
  entry.cost = round2(entry.cost)
537
669
  entry.share = 0
670
+ // 四态收敛:任一行真缺价 → false;全是零消耗行 → 'empty';其余 true
671
+ if (entry.priced !== false) {
672
+ entry.priced = entry.rows > 0 && (entry.emptyRows ?? 0) < entry.rows ? true : 'empty'
673
+ }
674
+ if (entry.priced !== false) entry.reason = null
675
+ delete entry.rows
676
+ delete entry.emptyRows
538
677
  return entry
539
678
  })
540
679
  models.sort((a, b) => b.cost - a.cost)
@@ -618,7 +757,7 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
618
757
  total: totalTokens,
619
758
  hitRate,
620
759
  },
621
- cost: { estimated: totalCost, currency: 'CNY', unpricedModels },
760
+ cost: { estimated: totalCost, currency: 'CNY', unpricedModels, unpriced },
622
761
  today: { tokens: today.tokens, cost: round2(today.cost), requests: today.requests },
623
762
  requests: { month: totals.requests, today: today.requests },
624
763
  providers,
package/src/match.js ADDED
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Model-name matching: pure functions over catalog entries.
3
+ * Knows nothing about providers, credentials or overrides — those belong to
4
+ * `pricing.js` (which has the provider string) and `core.js` (which decides
5
+ * whether a row is billable at all).
6
+ */
7
+ import { normalizeModel } from './providers.js'
8
+
9
+ /** Words that change the price tier: never stripped, never matched loosely. */
10
+ const SIGNIFICANT = new Set([
11
+ 'flash', 'pro', 'max', 'mini', 'air', 'plus', 'turbo', 'lite',
12
+ 'coder', 'code', 'reasoner', 'chat', 'vision',
13
+ ])
14
+
15
+ /** Deployment noise: stripped for fuzzy matching, kept as evidence in logs. */
16
+ const NOISE = new Set([
17
+ 'ioa', 'exp', 'experimental', 'preview', 'beta', 'alpha', 'rc', 'dev', 'test',
18
+ 'latest', 'stable', 'prod', 'production', 'free', 'ga',
19
+ ])
20
+
21
+ /** A bare `v` left over after removing the version segment is a marker, not a family word. */
22
+ const VERSION_MARK = 'v'
23
+
24
+ /** Non-leading digit runs of 3+ chars are dates / build ids, not family names. */
25
+ function isNumericNoise(part) {
26
+ return /^\d{3,}$/.test(part)
27
+ }
28
+
29
+ /**
30
+ * Split a model id into `{ version, family, tags }`.
31
+ * `deepseek-v4.1-flash-ioa` → version `4.1`, family `deepseek`, tags `{flash, ioa}`.
32
+ */
33
+ export function parseModelId(raw) {
34
+ const id = normalizeModel(raw)
35
+ if (id === 'unknown') return null
36
+ const version = id.match(/\d+(?:\.\d+)*/)?.[0] ?? null
37
+ const rest = version === null ? id : id.replace(version, '|')
38
+ const parts = rest.split(/[-_|]/).filter((part) => part !== '')
39
+ const family = []
40
+ const tags = new Set()
41
+ parts.forEach((part) => {
42
+ if (part === VERSION_MARK) return
43
+ if (SIGNIFICANT.has(part) || NOISE.has(part) || isNumericNoise(part)) {
44
+ tags.add(part)
45
+ return
46
+ }
47
+ family.push(part)
48
+ })
49
+ return { version, family: family.join('-'), tags }
50
+ }
51
+
52
+ /** Table-provided regexes are pre-compiled in `catalog.js`. */
53
+ function patternByModel(modelId, entries) {
54
+ for (const entry of entries) {
55
+ for (const regexp of entry.regexps) {
56
+ if (regexp.test(modelId)) return entry
57
+ }
58
+ }
59
+ return null
60
+ }
61
+
62
+ function parsedOf(entry) {
63
+ entry.parsed ??= parseModelId(entry.modelId)
64
+ return entry.parsed
65
+ }
66
+
67
+ /**
68
+ * Fuzzy candidates: same version segment, same family, candidate tags covered by
69
+ * the request, every extra request tag either significant-free or known noise.
70
+ */
71
+ function fuzzyCandidates(modelId, entries) {
72
+ const req = parseModelId(modelId)
73
+ if (req === null) return []
74
+ return entries.filter((entry) => {
75
+ const parsed = parsedOf(entry)
76
+ if (parsed === null) return false
77
+ if (parsed.version !== req.version || parsed.family !== req.family) return false
78
+ for (const tag of parsed.tags) {
79
+ if (!req.tags.has(tag)) return false
80
+ }
81
+ for (const tag of req.tags) {
82
+ if (!parsed.tags.has(tag) && !NOISE.has(tag)) return false
83
+ }
84
+ return true
85
+ })
86
+ }
87
+
88
+ /**
89
+ * Four-level short-circuit: exact → alias → pattern → fuzzy.
90
+ * Returns `{ entry, confidence, deltaTags }` or null; never guesses on ties.
91
+ */
92
+ export function resolveMatch(model, entries) {
93
+ const modelId = normalizeModel(model)
94
+ if (modelId === 'unknown') return null
95
+
96
+ const exact = entries.find((entry) => entry.modelId === modelId)
97
+ if (exact !== undefined) return { entry: exact, confidence: 'exact', deltaTags: [] }
98
+
99
+ const alias = entries.find((entry) => entry.aliases.includes(modelId))
100
+ if (alias !== undefined) return { entry: alias, confidence: 'alias', deltaTags: [] }
101
+
102
+ const pattern = patternByModel(modelId, entries)
103
+ if (pattern !== null) return { entry: pattern, confidence: 'pattern', deltaTags: [] }
104
+
105
+ const candidates = fuzzyCandidates(modelId, entries)
106
+ if (candidates.length !== 1) return null
107
+ const entry = candidates[0]
108
+ const reqTags = parseModelId(modelId)?.tags ?? new Set()
109
+ const entryTags = parsedOf(entry)?.tags ?? new Set()
110
+ const deltaTags = [...reqTags].filter((tag) => !entryTags.has(tag))
111
+ return { entry, confidence: 'fuzzy', deltaTags }
112
+ }
113
+
114
+ /** Why did `resolveMatch` fail? `ambiguous` vs `no-model-price` (for `reason`). */
115
+ export function explainMiss(model, entries) {
116
+ const modelId = normalizeModel(model)
117
+ if (modelId === 'unknown') return 'invalid-model'
118
+ return fuzzyCandidates(modelId, entries).length > 1 ? 'ambiguous' : 'no-model-price'
119
+ }