tokenusage-cli 0.1.0 → 0.2.1

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.
Files changed (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,456 +1,456 @@
1
- // Pure pricing-lookup logic. No I/O, no async. Tested in isolation.
2
- //
3
- // Resolve order:
4
- // 0. CURATED source exact match (source-specific pricing)
5
- // 1. CURATED exact match (self-defined aliases like kiro-*, hy3-*)
6
- // 2. LiteLLM exact match (mainstream claude/gpt-5/gemini)
7
- // 3. CURATED alias (e.g. "auto" -> "composer-1")
8
- // 4. CURATED fuzzy substring (e.g. "kiro-future-xyz" matches via "kiro")
9
- // 5. LiteLLM suffix-strip (gpt-5-codex-high-fast -> gpt-5-codex)
10
- // 5b. LiteLLM provider-prefix strip (mimo-v2.5-pro -> openrouter/xiaomi/mimo-v2.5-pro)
11
- // 6. LiteLLM reverse substring (longest-key first)
12
- // 7. null (caller decides what to do — typically zero-pricing + negative cache)
13
-
14
- const SUFFIX_STRIP_PATTERNS = [
15
- /-xhigh-fast$/,
16
- /-high-fast$/,
17
- /-medium-fast$/,
18
- /-low-fast$/,
19
- /-xhigh$/,
20
- /-high$/,
21
- /-medium$/,
22
- /-low$/,
23
- /-fast$/,
24
- ];
25
-
26
- function stripReasoningSuffix(model) {
27
- for (const re of SUFFIX_STRIP_PATTERNS) {
28
- if (re.test(model)) return model.replace(re, "");
29
- }
30
- return model;
31
- }
32
-
33
- function normalizeAntigravityModel(model) {
34
- if (!model || typeof model !== "string") return model;
35
- let lower = model
36
- .trim()
37
- .replace(/\([^)]*\)/g, " ")
38
- .replace(/\b(thinking|xhigh|high|medium|low|fast)\b/gi, " ")
39
- .toLowerCase()
40
- .replace(/[^a-z0-9.]+/g, "-")
41
- .replace(/^-+|-+$/g, "")
42
- .replace(/-{2,}/g, "-");
43
- lower = stripReasoningSuffix(lower);
44
-
45
- if (lower.startsWith("gemini-claude-") || lower.startsWith("gemini-gpt-")) {
46
- lower = lower.substring(7);
47
- }
48
-
49
- if (/^gemini-3\.\d+-flash-lite/.test(lower)) return "gemini-2.5-flash-lite";
50
- if (/^gemini-3\.\d+-flash/.test(lower)) return "gemini-2.5-flash";
51
- if (/^gemini-3\.\d+-pro/.test(lower)) return "gemini-2.5-pro";
52
- if (/^claude-(sonnet|opus|haiku)-4\.\d+/.test(lower)) {
53
- return lower.replace(/^claude-(sonnet|opus|haiku)-4\.(\d+)/, "claude-$1-4-$2");
54
- }
55
- if (lower.startsWith("gpt-oss-120b")) return "antigravity-gpt-oss-120b";
56
-
57
- return lower;
58
- }
59
-
60
- // Zed stores model names inconsistently across versions and providers: a mix
61
- // of canonical ids (`gpt-5.5`, `claude-opus-4.8`) and human display names
62
- // (`Claude Sonnet 4`, `GPT-5 (Preview)`, `Gemini 3 Pro (Preview)`). Map both to
63
- // the pricing engine's keys for cost lookup ONLY — the raw name is still what
64
- // gets stored/displayed. Unlike normalizeAntigravityModel we must NOT strip the
65
- // word "fast" (it is part of `grok-code-fast-1`) and we keep dotted GPT minors
66
- // (`gpt-5.2`) while hyphenating Claude minors (`claude-opus-4.8` ->
67
- // `claude-opus-4-8`) to match each family's LiteLLM/curated key style.
68
- function normalizeZedModel(model) {
69
- if (!model || typeof model !== "string") return model;
70
- let m = model
71
- .trim()
72
- .replace(/\([^)]*\)/g, " ") // drop "(Preview)" and similar qualifiers
73
- .toLowerCase()
74
- .replace(/[^a-z0-9./]+/g, "-") // spaces/underscores -> hyphen; keep . and /
75
- .replace(/^-+|-+$/g, "")
76
- .replace(/-{2,}/g, "-");
77
- if (/^claude-(sonnet|opus|haiku)-\d+\.\d+/.test(m)) {
78
- m = m.replace(/^(claude-(?:sonnet|opus|haiku)-\d+)\.(\d+)/, "$1-$2");
79
- }
80
- return m;
81
- }
82
-
83
- // Claude desktop/CLI sometimes reports display-style names such as
84
- // `claude-opus-4.8` or `Claude Opus 4.8`, while curated keys use Anthropic's
85
- // historical dash style (`claude-opus-4-8`). Relay/gateway backends (OpenRouter
86
- // and API proxies) add a provider path prefix and may invert tier/version order
87
- // — e.g. `anthropic/claude-4.6-opus-20260205` — which previously rendered $0
88
- // because the prefix slash got flattened to a dash and the order never matched.
89
- function normalizeClaudeModel(model) {
90
- if (!model || typeof model !== "string") return model;
91
- // Drop the provider path prefix relays prepend ("anthropic/...",
92
- // "openrouter/anthropic/...") so only the bare Claude id reaches the cleanup
93
- // and lookups below. Without this the "/" is flattened to "-" by the regex
94
- // step, breaking both the exact and provider-prefix-strip matches.
95
- const base = model.includes("/") ? model.slice(model.lastIndexOf("/") + 1) : model;
96
- let m = base
97
- .trim()
98
- .replace(/\([^)]*\)/g, " ")
99
- .toLowerCase()
100
- .replace(/[^a-z0-9.]+/g, "-")
101
- .replace(/^-+|-+$/g, "")
102
- .replace(/-{2,}/g, "-");
103
-
104
- if (/^claude-(sonnet|opus|haiku)-\d+\.\d+/.test(m)) {
105
- return m.replace(/^(claude-(?:sonnet|opus|haiku)-\d+)\.(\d+)/, "$1-$2");
106
- }
107
- if (/^(sonnet|opus|haiku)-\d+[.-]\d+/.test(m)) {
108
- return m
109
- .replace(/^(sonnet|opus|haiku)-/, "claude-$1-")
110
- .replace(/^(claude-(?:sonnet|opus|haiku)-\d+)\.(\d+)/, "$1-$2");
111
- }
112
- // Some relays invert tier/version order (`claude-4.6-opus` instead of the
113
- // canonical `claude-opus-4-6`). Restore it ONLY for major>=4 — Claude 3.x is
114
- // genuinely version-first (`claude-3-5-sonnet`, `claude-3-opus`) and must stay
115
- // untouched.
116
- if (/^claude-(?:[4-9]|\d{2,})[.-]\d+-(?:sonnet|opus|haiku)/.test(m)) {
117
- return m.replace(/^claude-(\d+)[.-](\d+)-(sonnet|opus|haiku)/, "claude-$3-$1-$2");
118
- }
119
-
120
- return m;
121
- }
122
-
123
- // Cursor decorates model ids with reasoning effort and sometimes places the
124
- // Claude version before the tier. Normalize those lookup-only aliases while
125
- // preserving Cursor Grok Fast SKUs (4.5/4.6/4.7 Fast rates are not the base
126
- // rates). Gemini 4 Argon effort suffixes (-high/-medium/-low/-minimal) are
127
- // stripped with the shared decorations set below.
128
- function normalizeCursorModel(model) {
129
- if (!model || typeof model !== "string") return model;
130
- let m = model
131
- .trim()
132
- .replace(/\([^)]*\)/g, " ")
133
- .toLowerCase()
134
- .replace(/[^a-z0-9.]+/g, "-")
135
- .replace(/^-+|-+$/g, "")
136
- .replace(/-{2,}/g, "-");
137
- const parts = m.split("-");
138
- const isFast = parts.includes("fast");
139
-
140
- if (/^(?:cursor-)?grok-4[.-]7(?:-|$)/.test(m)) {
141
- return isFast ? "cursor-grok-4.7-fast" : "cursor-grok-4.7";
142
- }
143
- if (/^(?:cursor-)?grok-4[.-]6(?:-|$)/.test(m)) {
144
- return isFast ? "cursor-grok-4.6-fast" : "cursor-grok-4.6";
145
- }
146
- if (/^(?:cursor-)?grok-4[.-]5(?:-|$)/.test(m)) {
147
- return isFast ? "cursor-grok-4.5-fast" : "cursor-grok-4.5";
148
- }
149
-
150
- // `fast` can be a separately priced SKU (for example composer-2-fast and
151
- // claude-opus-5-fast). Preserve it for the exact lookups below; when it is
152
- // merely a decoration, lookupPricing's later suffix-strip still falls back
153
- // to the base LiteLLM model. Gemini Argon uses "minimal" as an effort level.
154
- const decorations = new Set(["thinking", "xhigh", "high", "medium", "low", "minimal"]);
155
- m = parts.filter((part) => !decorations.has(part)).join("-");
156
- if (m.startsWith("claude-")) return normalizeClaudeModel(m);
157
- return m;
158
- }
159
-
160
- // WorkBuddy's auto-router records the model as the literal "auto" and never
161
- // exposes the underlying model it picked. That collides with Cursor's curated
162
- // alias ("auto" -> "composer-1"), which would misprice WorkBuddy usage as
163
- // Cursor's Composer. Map it instead to hy3-preview-agent — WorkBuddy's default
164
- // Tencent Hunyuan model — mirroring how Cursor's "auto" maps to its own default
165
- // (composer-1). The auto-router can pick pricier models, so this can slightly
166
- // under-count, but it tracks the token cost of WorkBuddy's representative model
167
- // rather than an unrelated vendor's. (The raw "auto" string is still
168
- // stored/displayed; only the pricing lookup is remapped.)
169
- function normalizeWorkbuddyModel(model) {
170
- if (typeof model === "string" && model.trim().toLowerCase() === "auto") {
171
- return "hy3-preview-agent";
172
- }
173
- return model;
174
- }
175
-
176
- function normalizeIFlytekMaasModel(model) {
177
- if (!model || typeof model !== "string") return model;
178
- const trimmed = model.trim();
179
- const lower = trimmed.toLowerCase();
180
- // The default Agent slug maps to the Spark X2 service in the supplied price list.
181
- if (lower === "xsparkx2agent") return "xsparkx2";
182
- return trimmed;
183
- }
184
-
185
- // Unsloth Studio can mix local engines and paid API providers in one database.
186
- // The parser qualifies metered models with their provider and marks local,
187
- // subscription-backed, or ambiguous custom routes as unpriced. Returning a
188
- // sentinel here prevents the generic reverse-substring matcher from mistaking
189
- // a locally hosted model name for the similarly named cloud SKU.
190
- function normalizeUnslothModel(model) {
191
- if (typeof model !== "string") return model;
192
- const lower = model.trim().toLowerCase();
193
- if (lower.startsWith("local/") || lower.startsWith("unpriced/")) {
194
- return "__tokenusage_unpriced_unsloth_model__";
195
- }
196
- return model;
197
- }
198
-
199
- // Per-source model-name normalizers, applied at pricing-lookup time only (the
200
- // raw model name is preserved for storage/display). Add a source here when its
201
- // model strings don't match the LiteLLM/curated keys verbatim.
202
- const SOURCE_MODEL_NORMALIZERS = {
203
- acode: normalizeIFlytekMaasModel,
204
- antigravity: normalizeAntigravityModel,
205
- claude: normalizeClaudeModel,
206
- cursor: normalizeCursorModel,
207
- "pi-anthropic": normalizeClaudeModel,
208
- "prime-agent-anthropic": normalizeClaudeModel,
209
- zed: normalizeZedModel,
210
- unsloth: normalizeUnslothModel,
211
- workbuddy: normalizeWorkbuddyModel,
212
- };
213
-
214
- // Memoise the sorted-by-length LiteLLM key list. Reverse-substring scan walks
215
- // this once per uncached model; ~2k keys × negligible per-iteration cost, but
216
- // computing the sort on every call would add up across a sync.
217
- const sortedKeysCache = new WeakMap();
218
- function getSortedKeys(litellm) {
219
- let cached = sortedKeysCache.get(litellm);
220
- if (!cached) {
221
- cached = Object.keys(litellm).sort((a, b) => b.length - a.length);
222
- sortedKeysCache.set(litellm, cached);
223
- }
224
- return cached;
225
- }
226
-
227
- function buildDotRestoredModel(model) {
228
- if (typeof model !== "string") return "";
229
- const lower = model.toLowerCase();
230
- const restored = lower.replace(/(\d+)-(\d+)/g, "$1.$2");
231
- return restored === lower ? "" : restored;
232
- }
233
-
234
- function lookupExactCaseInsensitive(table, model) {
235
- if (!table || !model) return null;
236
- if (table[model]) return table[model];
237
- const lower = model.toLowerCase();
238
- for (const key of Object.keys(table)) {
239
- if (key.toLowerCase() === lower) return table[key];
240
- }
241
- return null;
242
- }
243
-
244
- function lookupContainedExactCaseInsensitive(table, model) {
245
- if (!table || !model) return null;
246
- const lower = model.toLowerCase();
247
- const keys = Object.keys(table).sort((a, b) => b.length - a.length);
248
- for (const key of keys) {
249
- const start = lower.indexOf(key.toLowerCase());
250
- if (start < 0) continue;
251
- // A model generation must not match a later numeric version (Opus 5.5
252
- // is a separate SKU from Opus 5). Dated and provider suffixes still work.
253
- const suffix = lower.slice(start + key.length);
254
- if (/^[.\d]/.test(suffix)) continue;
255
- return table[key];
256
- }
257
- return null;
258
- }
259
-
260
- function lookupPricing(model, { curated, litellm, source } = {}) {
261
- if (!model || typeof model !== "string") {
262
- return { hit: false, source: "empty", value: null };
263
- }
264
- const normalize =
265
- typeof source === "string" ? SOURCE_MODEL_NORMALIZERS[source.toLowerCase()] : null;
266
- const lookupModel = normalize ? normalize(model) : model;
267
- const lower = lookupModel.toLowerCase();
268
- const dotForm = buildDotRestoredModel(lookupModel);
269
-
270
- // 0. CURATED source exact. Source-specific prices apply only to their source,
271
- // preventing collisions with public prices for same-named models from other CLIs.
272
- const sourceKey = typeof source === "string" ? source.toLowerCase() : "";
273
- if (sourceKey === "workbuddy-ai" && lower.trim() === "auto") {
274
- return { hit: false, source: "miss", value: null };
275
- }
276
- if (sourceKey === "cline" && lower.endsWith(":free")) {
277
- return {
278
- hit: true,
279
- source: "curated:cline-free-suffix",
280
- value: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
281
- };
282
- }
283
- // OpenCode Zen free models carry a `-free` suffix on the paid model id
284
- // (`deepseek-v4.1-flash-free`); the base-name fuzzy match must not bill them.
285
- if (sourceKey === "opencode" && lower.endsWith("-free")) {
286
- return {
287
- hit: true,
288
- source: "curated:opencode-free-suffix",
289
- value: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
290
- };
291
- }
292
- // AStudio does not disclose its routed model. Stop before generic aliases
293
- // and fuzzy matching can turn an unresolved router into a priced model.
294
- if (sourceKey === "acode" && (lower === "auto" || lower.endsWith("-auto"))) {
295
- return { hit: false, source: "miss", value: null };
296
- }
297
- const sourceExact = curated.source_exact?.[sourceKey];
298
- if (sourceExact) {
299
- const sourceValue = lookupExactCaseInsensitive(sourceExact, lookupModel);
300
- if (sourceValue) {
301
- return { hit: true, source: "curated:source-exact", value: sourceValue };
302
- }
303
- }
304
-
305
- // 1. CURATED exact
306
- // Qwen Flash's provider-qualified and dated IDs share the reference SKU.
307
- // Keep the boundary strict: Flash-Next and Max have independent prices.
308
- if (/(?:^|\/)qwen3[.-]8-flash(?:-\d{4}-\d{2}-\d{2})?$/.test(lower.trim()) && curated.exact?.["qwen3.8-flash"]) {
309
- return { hit: true, source: "curated:exact", value: curated.exact["qwen3.8-flash"] };
310
- }
311
- if (curated.exact && curated.exact[lookupModel]) {
312
- return { hit: true, source: "curated:exact", value: curated.exact[lookupModel] };
313
- }
314
- const curatedDotExact = lookupExactCaseInsensitive(curated.exact, dotForm);
315
- if (curatedDotExact) {
316
- return { hit: true, source: "curated:exact-dot", value: curatedDotExact };
317
- }
318
-
319
- // 2. LiteLLM exact
320
- if (litellm && litellm[lookupModel]) {
321
- return { hit: true, source: "litellm:exact", value: litellm[lookupModel] };
322
- }
323
- const litellmDotExact = lookupExactCaseInsensitive(litellm, dotForm);
324
- if (litellmDotExact) {
325
- return { hit: true, source: "litellm:exact-dot", value: litellmDotExact };
326
- }
327
- const curatedDotContainedExact = lookupContainedExactCaseInsensitive(curated.exact, dotForm);
328
- if (curatedDotContainedExact) {
329
- return { hit: true, source: "curated:exact-dot", value: curatedDotContainedExact };
330
- }
331
-
332
- // 3. CURATED alias (literal mapping like "auto" -> "composer-1")
333
- if (curated.alias && curated.alias[lookupModel] && curated.exact[curated.alias[lookupModel]]) {
334
- return {
335
- hit: true,
336
- source: "curated:alias",
337
- value: curated.exact[curated.alias[lookupModel]],
338
- };
339
- }
340
-
341
- // 4. CURATED fuzzy substring. Also try a dot-restored variant of the input
342
- // (digits separated by `-` rejoined as `.`) so providers that dash-normalize
343
- // numeric segments — Droid emits `glm-5-1-0` for upstream `GLM-5.1` — still
344
- // resolve against dot-keyed curated entries like `glm-5.1`, `glm-4.6`, etc.
345
- // The regex only fires on digit-dash-digit, so `claude-3-7-sonnet`,
346
- // `gpt-5-codex`, `gemini-2-5-pro` are unaffected (no digit-pair to rejoin or
347
- // no matching curated key).
348
- if (Array.isArray(curated.fuzzy)) {
349
- for (const { match, ref } of curated.fuzzy) {
350
- if (!match || !ref) continue;
351
- const needle = match.toLowerCase();
352
- if (!curated.exact[ref]) continue;
353
- if (lower.includes(needle)) {
354
- return { hit: true, source: "curated:fuzzy", value: curated.exact[ref] };
355
- }
356
- if (dotForm && dotForm.includes(needle)) {
357
- return { hit: true, source: "curated:fuzzy", value: curated.exact[ref] };
358
- }
359
- }
360
- }
361
-
362
- // 5. LiteLLM suffix-strip
363
- if (litellm) {
364
- const stripped = stripReasoningSuffix(lookupModel);
365
- if (stripped !== lookupModel && litellm[stripped]) {
366
- return { hit: true, source: "litellm:strip", value: litellm[stripped] };
367
- }
368
- }
369
-
370
- // 5b. LiteLLM provider-prefix strip. Queue rows store the bare model name
371
- // (e.g. "mimo-v2.5-pro"), but LiteLLM keys are provider-qualified (e.g.
372
- // "openrouter/xiaomi/mimo-v2.5-pro"), so the exact lookups above miss. Match
373
- // any key whose path suffix equals the bare model. When several providers
374
- // expose the same model, pick the lexicographically smallest key so the
375
- // resolved price is deterministic and independent of JSON ordering. Runs
376
- // AFTER curated alias/fuzzy so e.g. Cursor's "auto" still resolves to
377
- // composer-1 rather than a LiteLLM "*/auto" entry.
378
- if (litellm) {
379
- const suffix = "/" + lower;
380
- let best = null;
381
- for (const key of Object.keys(litellm)) {
382
- if (key.length > suffix.length && key.toLowerCase().endsWith(suffix)) {
383
- if (best === null || key < best) best = key;
384
- }
385
- }
386
- if (best) return { hit: true, source: "litellm:prefix-strip", value: litellm[best] };
387
- }
388
-
389
- // 6. LiteLLM reverse substring (longest-key first)
390
- if (litellm) {
391
- const sorted = getSortedKeys(litellm);
392
- for (const key of sorted) {
393
- const keyLower = key.toLowerCase();
394
- // Only accept if model is a superset of key (model contains key), to
395
- // avoid e.g. "gpt-5" matching "gpt-5-pro" in the wrong direction.
396
- if (lower.includes(keyLower) || (dotForm && dotForm.includes(keyLower))) {
397
- return { hit: true, source: "litellm:fuzzy", value: litellm[key] };
398
- }
399
- }
400
- }
401
-
402
- return { hit: false, source: "miss", value: null };
403
- }
404
-
405
- // Convert one LiteLLM entry (per-token) to internal per-million USD shape.
406
- // Missing fields stay missing — callers default with `(pricing.x || 0)`.
407
- //
408
- // Why the round: floating-point math means 1e-7 * 1e6 = 0.09999999999999999.
409
- // Rounding to 10 significant decimals ($0.0000000001 / MTok) is well below
410
- // any realistic price step but cleans up the printed/asserted numbers.
411
- function roundToTenDecimals(n) {
412
- return Math.round(n * 1e10) / 1e10;
413
- }
414
-
415
- function convertLitellmEntry(entry) {
416
- if (!entry || typeof entry !== "object") return null;
417
- const out = {};
418
- if (typeof entry.input_cost_per_token === "number") {
419
- out.input = roundToTenDecimals(entry.input_cost_per_token * 1_000_000);
420
- }
421
- if (typeof entry.output_cost_per_token === "number") {
422
- out.output = roundToTenDecimals(entry.output_cost_per_token * 1_000_000);
423
- }
424
- if (typeof entry.cache_read_input_token_cost === "number") {
425
- out.cache_read = roundToTenDecimals(entry.cache_read_input_token_cost * 1_000_000);
426
- }
427
- if (typeof entry.cache_creation_input_token_cost === "number") {
428
- out.cache_write = roundToTenDecimals(entry.cache_creation_input_token_cost * 1_000_000);
429
- }
430
- return Object.keys(out).length ? out : null;
431
- }
432
-
433
- // Build a per-million-USD map from a LiteLLM raw map (or seed snapshot which
434
- // uses the same field names). Skips meta keys starting with "_".
435
- function buildLitellmPerMillionMap(rawData) {
436
- if (!rawData || typeof rawData !== "object") return {};
437
- const out = {};
438
- for (const [name, entry] of Object.entries(rawData)) {
439
- if (name.startsWith("_")) continue;
440
- const converted = convertLitellmEntry(entry);
441
- if (converted) out[name] = converted;
442
- }
443
- return out;
444
- }
445
-
446
- module.exports = {
447
- lookupPricing,
448
- stripReasoningSuffix,
449
- normalizeAntigravityModel,
450
- normalizeIFlytekMaasModel,
451
- normalizeClaudeModel,
452
- normalizeCursorModel,
453
- normalizeZedModel,
454
- convertLitellmEntry,
455
- buildLitellmPerMillionMap,
456
- };
1
+ // Pure pricing-lookup logic. No I/O, no async. Tested in isolation.
2
+ //
3
+ // Resolve order:
4
+ // 0. CURATED source exact match (source-specific pricing)
5
+ // 1. CURATED exact match (self-defined aliases like kiro-*, hy3-*)
6
+ // 2. LiteLLM exact match (mainstream claude/gpt-5/gemini)
7
+ // 3. CURATED alias (e.g. "auto" -> "composer-1")
8
+ // 4. CURATED fuzzy substring (e.g. "kiro-future-xyz" matches via "kiro")
9
+ // 5. LiteLLM suffix-strip (gpt-5-codex-high-fast -> gpt-5-codex)
10
+ // 5b. LiteLLM provider-prefix strip (mimo-v2.5-pro -> openrouter/xiaomi/mimo-v2.5-pro)
11
+ // 6. LiteLLM reverse substring (longest-key first)
12
+ // 7. null (caller decides what to do — typically zero-pricing + negative cache)
13
+
14
+ const SUFFIX_STRIP_PATTERNS = [
15
+ /-xhigh-fast$/,
16
+ /-high-fast$/,
17
+ /-medium-fast$/,
18
+ /-low-fast$/,
19
+ /-xhigh$/,
20
+ /-high$/,
21
+ /-medium$/,
22
+ /-low$/,
23
+ /-fast$/,
24
+ ];
25
+
26
+ function stripReasoningSuffix(model) {
27
+ for (const re of SUFFIX_STRIP_PATTERNS) {
28
+ if (re.test(model)) return model.replace(re, "");
29
+ }
30
+ return model;
31
+ }
32
+
33
+ function normalizeAntigravityModel(model) {
34
+ if (!model || typeof model !== "string") return model;
35
+ let lower = model
36
+ .trim()
37
+ .replace(/\([^)]*\)/g, " ")
38
+ .replace(/\b(thinking|xhigh|high|medium|low|fast)\b/gi, " ")
39
+ .toLowerCase()
40
+ .replace(/[^a-z0-9.]+/g, "-")
41
+ .replace(/^-+|-+$/g, "")
42
+ .replace(/-{2,}/g, "-");
43
+ lower = stripReasoningSuffix(lower);
44
+
45
+ if (lower.startsWith("gemini-claude-") || lower.startsWith("gemini-gpt-")) {
46
+ lower = lower.substring(7);
47
+ }
48
+
49
+ if (/^gemini-3\.\d+-flash-lite/.test(lower)) return "gemini-2.5-flash-lite";
50
+ if (/^gemini-3\.\d+-flash/.test(lower)) return "gemini-2.5-flash";
51
+ if (/^gemini-3\.\d+-pro/.test(lower)) return "gemini-2.5-pro";
52
+ if (/^claude-(sonnet|opus|haiku)-4\.\d+/.test(lower)) {
53
+ return lower.replace(/^claude-(sonnet|opus|haiku)-4\.(\d+)/, "claude-$1-4-$2");
54
+ }
55
+ if (lower.startsWith("gpt-oss-120b")) return "antigravity-gpt-oss-120b";
56
+
57
+ return lower;
58
+ }
59
+
60
+ // Zed stores model names inconsistently across versions and providers: a mix
61
+ // of canonical ids (`gpt-5.5`, `claude-opus-4.8`) and human display names
62
+ // (`Claude Sonnet 4`, `GPT-5 (Preview)`, `Gemini 3 Pro (Preview)`). Map both to
63
+ // the pricing engine's keys for cost lookup ONLY — the raw name is still what
64
+ // gets stored/displayed. Unlike normalizeAntigravityModel we must NOT strip the
65
+ // word "fast" (it is part of `grok-code-fast-1`) and we keep dotted GPT minors
66
+ // (`gpt-5.2`) while hyphenating Claude minors (`claude-opus-4.8` ->
67
+ // `claude-opus-4-8`) to match each family's LiteLLM/curated key style.
68
+ function normalizeZedModel(model) {
69
+ if (!model || typeof model !== "string") return model;
70
+ let m = model
71
+ .trim()
72
+ .replace(/\([^)]*\)/g, " ") // drop "(Preview)" and similar qualifiers
73
+ .toLowerCase()
74
+ .replace(/[^a-z0-9./]+/g, "-") // spaces/underscores -> hyphen; keep . and /
75
+ .replace(/^-+|-+$/g, "")
76
+ .replace(/-{2,}/g, "-");
77
+ if (/^claude-(sonnet|opus|haiku)-\d+\.\d+/.test(m)) {
78
+ m = m.replace(/^(claude-(?:sonnet|opus|haiku)-\d+)\.(\d+)/, "$1-$2");
79
+ }
80
+ return m;
81
+ }
82
+
83
+ // Claude desktop/CLI sometimes reports display-style names such as
84
+ // `claude-opus-4.8` or `Claude Opus 4.8`, while curated keys use Anthropic's
85
+ // historical dash style (`claude-opus-4-8`). Relay/gateway backends (OpenRouter
86
+ // and API proxies) add a provider path prefix and may invert tier/version order
87
+ // — e.g. `anthropic/claude-4.6-opus-20260205` — which previously rendered $0
88
+ // because the prefix slash got flattened to a dash and the order never matched.
89
+ function normalizeClaudeModel(model) {
90
+ if (!model || typeof model !== "string") return model;
91
+ // Drop the provider path prefix relays prepend ("anthropic/...",
92
+ // "openrouter/anthropic/...") so only the bare Claude id reaches the cleanup
93
+ // and lookups below. Without this the "/" is flattened to "-" by the regex
94
+ // step, breaking both the exact and provider-prefix-strip matches.
95
+ const base = model.includes("/") ? model.slice(model.lastIndexOf("/") + 1) : model;
96
+ let m = base
97
+ .trim()
98
+ .replace(/\([^)]*\)/g, " ")
99
+ .toLowerCase()
100
+ .replace(/[^a-z0-9.]+/g, "-")
101
+ .replace(/^-+|-+$/g, "")
102
+ .replace(/-{2,}/g, "-");
103
+
104
+ if (/^claude-(sonnet|opus|haiku)-\d+\.\d+/.test(m)) {
105
+ return m.replace(/^(claude-(?:sonnet|opus|haiku)-\d+)\.(\d+)/, "$1-$2");
106
+ }
107
+ if (/^(sonnet|opus|haiku)-\d+[.-]\d+/.test(m)) {
108
+ return m
109
+ .replace(/^(sonnet|opus|haiku)-/, "claude-$1-")
110
+ .replace(/^(claude-(?:sonnet|opus|haiku)-\d+)\.(\d+)/, "$1-$2");
111
+ }
112
+ // Some relays invert tier/version order (`claude-4.6-opus` instead of the
113
+ // canonical `claude-opus-4-6`). Restore it ONLY for major>=4 — Claude 3.x is
114
+ // genuinely version-first (`claude-3-5-sonnet`, `claude-3-opus`) and must stay
115
+ // untouched.
116
+ if (/^claude-(?:[4-9]|\d{2,})[.-]\d+-(?:sonnet|opus|haiku)/.test(m)) {
117
+ return m.replace(/^claude-(\d+)[.-](\d+)-(sonnet|opus|haiku)/, "claude-$3-$1-$2");
118
+ }
119
+
120
+ return m;
121
+ }
122
+
123
+ // Cursor decorates model ids with reasoning effort and sometimes places the
124
+ // Claude version before the tier. Normalize those lookup-only aliases while
125
+ // preserving Cursor Grok Fast SKUs (4.5/4.6/4.7 Fast rates are not the base
126
+ // rates). Gemini 4 Argon effort suffixes (-high/-medium/-low/-minimal) are
127
+ // stripped with the shared decorations set below.
128
+ function normalizeCursorModel(model) {
129
+ if (!model || typeof model !== "string") return model;
130
+ let m = model
131
+ .trim()
132
+ .replace(/\([^)]*\)/g, " ")
133
+ .toLowerCase()
134
+ .replace(/[^a-z0-9.]+/g, "-")
135
+ .replace(/^-+|-+$/g, "")
136
+ .replace(/-{2,}/g, "-");
137
+ const parts = m.split("-");
138
+ const isFast = parts.includes("fast");
139
+
140
+ if (/^(?:cursor-)?grok-4[.-]7(?:-|$)/.test(m)) {
141
+ return isFast ? "cursor-grok-4.7-fast" : "cursor-grok-4.7";
142
+ }
143
+ if (/^(?:cursor-)?grok-4[.-]6(?:-|$)/.test(m)) {
144
+ return isFast ? "cursor-grok-4.6-fast" : "cursor-grok-4.6";
145
+ }
146
+ if (/^(?:cursor-)?grok-4[.-]5(?:-|$)/.test(m)) {
147
+ return isFast ? "cursor-grok-4.5-fast" : "cursor-grok-4.5";
148
+ }
149
+
150
+ // `fast` can be a separately priced SKU (for example composer-2-fast and
151
+ // claude-opus-5-fast). Preserve it for the exact lookups below; when it is
152
+ // merely a decoration, lookupPricing's later suffix-strip still falls back
153
+ // to the base LiteLLM model. Gemini Argon uses "minimal" as an effort level.
154
+ const decorations = new Set(["thinking", "xhigh", "high", "medium", "low", "minimal"]);
155
+ m = parts.filter((part) => !decorations.has(part)).join("-");
156
+ if (m.startsWith("claude-")) return normalizeClaudeModel(m);
157
+ return m;
158
+ }
159
+
160
+ // WorkBuddy's auto-router records the model as the literal "auto" and never
161
+ // exposes the underlying model it picked. That collides with Cursor's curated
162
+ // alias ("auto" -> "composer-1"), which would misprice WorkBuddy usage as
163
+ // Cursor's Composer. Map it instead to hy3-preview-agent — WorkBuddy's default
164
+ // Tencent Hunyuan model — mirroring how Cursor's "auto" maps to its own default
165
+ // (composer-1). The auto-router can pick pricier models, so this can slightly
166
+ // under-count, but it tracks the token cost of WorkBuddy's representative model
167
+ // rather than an unrelated vendor's. (The raw "auto" string is still
168
+ // stored/displayed; only the pricing lookup is remapped.)
169
+ function normalizeWorkbuddyModel(model) {
170
+ if (typeof model === "string" && model.trim().toLowerCase() === "auto") {
171
+ return "hy3-preview-agent";
172
+ }
173
+ return model;
174
+ }
175
+
176
+ function normalizeIFlytekMaasModel(model) {
177
+ if (!model || typeof model !== "string") return model;
178
+ const trimmed = model.trim();
179
+ const lower = trimmed.toLowerCase();
180
+ // The default Agent slug maps to the Spark X2 service in the supplied price list.
181
+ if (lower === "xsparkx2agent") return "xsparkx2";
182
+ return trimmed;
183
+ }
184
+
185
+ // Unsloth Studio can mix local engines and paid API providers in one database.
186
+ // The parser qualifies metered models with their provider and marks local,
187
+ // subscription-backed, or ambiguous custom routes as unpriced. Returning a
188
+ // sentinel here prevents the generic reverse-substring matcher from mistaking
189
+ // a locally hosted model name for the similarly named cloud SKU.
190
+ function normalizeUnslothModel(model) {
191
+ if (typeof model !== "string") return model;
192
+ const lower = model.trim().toLowerCase();
193
+ if (lower.startsWith("local/") || lower.startsWith("unpriced/")) {
194
+ return "__tokenusage_unpriced_unsloth_model__";
195
+ }
196
+ return model;
197
+ }
198
+
199
+ // Per-source model-name normalizers, applied at pricing-lookup time only (the
200
+ // raw model name is preserved for storage/display). Add a source here when its
201
+ // model strings don't match the LiteLLM/curated keys verbatim.
202
+ const SOURCE_MODEL_NORMALIZERS = {
203
+ acode: normalizeIFlytekMaasModel,
204
+ antigravity: normalizeAntigravityModel,
205
+ claude: normalizeClaudeModel,
206
+ cursor: normalizeCursorModel,
207
+ "pi-anthropic": normalizeClaudeModel,
208
+ "prime-agent-anthropic": normalizeClaudeModel,
209
+ zed: normalizeZedModel,
210
+ unsloth: normalizeUnslothModel,
211
+ workbuddy: normalizeWorkbuddyModel,
212
+ };
213
+
214
+ // Memoise the sorted-by-length LiteLLM key list. Reverse-substring scan walks
215
+ // this once per uncached model; ~2k keys × negligible per-iteration cost, but
216
+ // computing the sort on every call would add up across a sync.
217
+ const sortedKeysCache = new WeakMap();
218
+ function getSortedKeys(litellm) {
219
+ let cached = sortedKeysCache.get(litellm);
220
+ if (!cached) {
221
+ cached = Object.keys(litellm).sort((a, b) => b.length - a.length);
222
+ sortedKeysCache.set(litellm, cached);
223
+ }
224
+ return cached;
225
+ }
226
+
227
+ function buildDotRestoredModel(model) {
228
+ if (typeof model !== "string") return "";
229
+ const lower = model.toLowerCase();
230
+ const restored = lower.replace(/(\d+)-(\d+)/g, "$1.$2");
231
+ return restored === lower ? "" : restored;
232
+ }
233
+
234
+ function lookupExactCaseInsensitive(table, model) {
235
+ if (!table || !model) return null;
236
+ if (table[model]) return table[model];
237
+ const lower = model.toLowerCase();
238
+ for (const key of Object.keys(table)) {
239
+ if (key.toLowerCase() === lower) return table[key];
240
+ }
241
+ return null;
242
+ }
243
+
244
+ function lookupContainedExactCaseInsensitive(table, model) {
245
+ if (!table || !model) return null;
246
+ const lower = model.toLowerCase();
247
+ const keys = Object.keys(table).sort((a, b) => b.length - a.length);
248
+ for (const key of keys) {
249
+ const start = lower.indexOf(key.toLowerCase());
250
+ if (start < 0) continue;
251
+ // A model generation must not match a later numeric version (Opus 5.5
252
+ // is a separate SKU from Opus 5). Dated and provider suffixes still work.
253
+ const suffix = lower.slice(start + key.length);
254
+ if (/^[.\d]/.test(suffix)) continue;
255
+ return table[key];
256
+ }
257
+ return null;
258
+ }
259
+
260
+ function lookupPricing(model, { curated, litellm, source } = {}) {
261
+ if (!model || typeof model !== "string") {
262
+ return { hit: false, source: "empty", value: null };
263
+ }
264
+ const normalize =
265
+ typeof source === "string" ? SOURCE_MODEL_NORMALIZERS[source.toLowerCase()] : null;
266
+ const lookupModel = normalize ? normalize(model) : model;
267
+ const lower = lookupModel.toLowerCase();
268
+ const dotForm = buildDotRestoredModel(lookupModel);
269
+
270
+ // 0. CURATED source exact. Source-specific prices apply only to their source,
271
+ // preventing collisions with public prices for same-named models from other CLIs.
272
+ const sourceKey = typeof source === "string" ? source.toLowerCase() : "";
273
+ if (sourceKey === "workbuddy-ai" && lower.trim() === "auto") {
274
+ return { hit: false, source: "miss", value: null };
275
+ }
276
+ if (sourceKey === "cline" && lower.endsWith(":free")) {
277
+ return {
278
+ hit: true,
279
+ source: "curated:cline-free-suffix",
280
+ value: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
281
+ };
282
+ }
283
+ // OpenCode Zen free models carry a `-free` suffix on the paid model id
284
+ // (`deepseek-v4.1-flash-free`); the base-name fuzzy match must not bill them.
285
+ if (sourceKey === "opencode" && lower.endsWith("-free")) {
286
+ return {
287
+ hit: true,
288
+ source: "curated:opencode-free-suffix",
289
+ value: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
290
+ };
291
+ }
292
+ // AStudio does not disclose its routed model. Stop before generic aliases
293
+ // and fuzzy matching can turn an unresolved router into a priced model.
294
+ if (sourceKey === "acode" && (lower === "auto" || lower.endsWith("-auto"))) {
295
+ return { hit: false, source: "miss", value: null };
296
+ }
297
+ const sourceExact = curated.source_exact?.[sourceKey];
298
+ if (sourceExact) {
299
+ const sourceValue = lookupExactCaseInsensitive(sourceExact, lookupModel);
300
+ if (sourceValue) {
301
+ return { hit: true, source: "curated:source-exact", value: sourceValue };
302
+ }
303
+ }
304
+
305
+ // 1. CURATED exact
306
+ // Qwen Flash's provider-qualified and dated IDs share the reference SKU.
307
+ // Keep the boundary strict: Flash-Next and Max have independent prices.
308
+ if (/(?:^|\/)qwen3[.-]8-flash(?:-\d{4}-\d{2}-\d{2})?$/.test(lower.trim()) && curated.exact?.["qwen3.8-flash"]) {
309
+ return { hit: true, source: "curated:exact", value: curated.exact["qwen3.8-flash"] };
310
+ }
311
+ if (curated.exact && curated.exact[lookupModel]) {
312
+ return { hit: true, source: "curated:exact", value: curated.exact[lookupModel] };
313
+ }
314
+ const curatedDotExact = lookupExactCaseInsensitive(curated.exact, dotForm);
315
+ if (curatedDotExact) {
316
+ return { hit: true, source: "curated:exact-dot", value: curatedDotExact };
317
+ }
318
+
319
+ // 2. LiteLLM exact
320
+ if (litellm && litellm[lookupModel]) {
321
+ return { hit: true, source: "litellm:exact", value: litellm[lookupModel] };
322
+ }
323
+ const litellmDotExact = lookupExactCaseInsensitive(litellm, dotForm);
324
+ if (litellmDotExact) {
325
+ return { hit: true, source: "litellm:exact-dot", value: litellmDotExact };
326
+ }
327
+ const curatedDotContainedExact = lookupContainedExactCaseInsensitive(curated.exact, dotForm);
328
+ if (curatedDotContainedExact) {
329
+ return { hit: true, source: "curated:exact-dot", value: curatedDotContainedExact };
330
+ }
331
+
332
+ // 3. CURATED alias (literal mapping like "auto" -> "composer-1")
333
+ if (curated.alias && curated.alias[lookupModel] && curated.exact[curated.alias[lookupModel]]) {
334
+ return {
335
+ hit: true,
336
+ source: "curated:alias",
337
+ value: curated.exact[curated.alias[lookupModel]],
338
+ };
339
+ }
340
+
341
+ // 4. CURATED fuzzy substring. Also try a dot-restored variant of the input
342
+ // (digits separated by `-` rejoined as `.`) so providers that dash-normalize
343
+ // numeric segments — Droid emits `glm-5-1-0` for upstream `GLM-5.1` — still
344
+ // resolve against dot-keyed curated entries like `glm-5.1`, `glm-4.6`, etc.
345
+ // The regex only fires on digit-dash-digit, so `claude-3-7-sonnet`,
346
+ // `gpt-5-codex`, `gemini-2-5-pro` are unaffected (no digit-pair to rejoin or
347
+ // no matching curated key).
348
+ if (Array.isArray(curated.fuzzy)) {
349
+ for (const { match, ref } of curated.fuzzy) {
350
+ if (!match || !ref) continue;
351
+ const needle = match.toLowerCase();
352
+ if (!curated.exact[ref]) continue;
353
+ if (lower.includes(needle)) {
354
+ return { hit: true, source: "curated:fuzzy", value: curated.exact[ref] };
355
+ }
356
+ if (dotForm && dotForm.includes(needle)) {
357
+ return { hit: true, source: "curated:fuzzy", value: curated.exact[ref] };
358
+ }
359
+ }
360
+ }
361
+
362
+ // 5. LiteLLM suffix-strip
363
+ if (litellm) {
364
+ const stripped = stripReasoningSuffix(lookupModel);
365
+ if (stripped !== lookupModel && litellm[stripped]) {
366
+ return { hit: true, source: "litellm:strip", value: litellm[stripped] };
367
+ }
368
+ }
369
+
370
+ // 5b. LiteLLM provider-prefix strip. Queue rows store the bare model name
371
+ // (e.g. "mimo-v2.5-pro"), but LiteLLM keys are provider-qualified (e.g.
372
+ // "openrouter/xiaomi/mimo-v2.5-pro"), so the exact lookups above miss. Match
373
+ // any key whose path suffix equals the bare model. When several providers
374
+ // expose the same model, pick the lexicographically smallest key so the
375
+ // resolved price is deterministic and independent of JSON ordering. Runs
376
+ // AFTER curated alias/fuzzy so e.g. Cursor's "auto" still resolves to
377
+ // composer-1 rather than a LiteLLM "*/auto" entry.
378
+ if (litellm) {
379
+ const suffix = "/" + lower;
380
+ let best = null;
381
+ for (const key of Object.keys(litellm)) {
382
+ if (key.length > suffix.length && key.toLowerCase().endsWith(suffix)) {
383
+ if (best === null || key < best) best = key;
384
+ }
385
+ }
386
+ if (best) return { hit: true, source: "litellm:prefix-strip", value: litellm[best] };
387
+ }
388
+
389
+ // 6. LiteLLM reverse substring (longest-key first)
390
+ if (litellm) {
391
+ const sorted = getSortedKeys(litellm);
392
+ for (const key of sorted) {
393
+ const keyLower = key.toLowerCase();
394
+ // Only accept if model is a superset of key (model contains key), to
395
+ // avoid e.g. "gpt-5" matching "gpt-5-pro" in the wrong direction.
396
+ if (lower.includes(keyLower) || (dotForm && dotForm.includes(keyLower))) {
397
+ return { hit: true, source: "litellm:fuzzy", value: litellm[key] };
398
+ }
399
+ }
400
+ }
401
+
402
+ return { hit: false, source: "miss", value: null };
403
+ }
404
+
405
+ // Convert one LiteLLM entry (per-token) to internal per-million USD shape.
406
+ // Missing fields stay missing — callers default with `(pricing.x || 0)`.
407
+ //
408
+ // Why the round: floating-point math means 1e-7 * 1e6 = 0.09999999999999999.
409
+ // Rounding to 10 significant decimals ($0.0000000001 / MTok) is well below
410
+ // any realistic price step but cleans up the printed/asserted numbers.
411
+ function roundToTenDecimals(n) {
412
+ return Math.round(n * 1e10) / 1e10;
413
+ }
414
+
415
+ function convertLitellmEntry(entry) {
416
+ if (!entry || typeof entry !== "object") return null;
417
+ const out = {};
418
+ if (typeof entry.input_cost_per_token === "number") {
419
+ out.input = roundToTenDecimals(entry.input_cost_per_token * 1_000_000);
420
+ }
421
+ if (typeof entry.output_cost_per_token === "number") {
422
+ out.output = roundToTenDecimals(entry.output_cost_per_token * 1_000_000);
423
+ }
424
+ if (typeof entry.cache_read_input_token_cost === "number") {
425
+ out.cache_read = roundToTenDecimals(entry.cache_read_input_token_cost * 1_000_000);
426
+ }
427
+ if (typeof entry.cache_creation_input_token_cost === "number") {
428
+ out.cache_write = roundToTenDecimals(entry.cache_creation_input_token_cost * 1_000_000);
429
+ }
430
+ return Object.keys(out).length ? out : null;
431
+ }
432
+
433
+ // Build a per-million-USD map from a LiteLLM raw map (or seed snapshot which
434
+ // uses the same field names). Skips meta keys starting with "_".
435
+ function buildLitellmPerMillionMap(rawData) {
436
+ if (!rawData || typeof rawData !== "object") return {};
437
+ const out = {};
438
+ for (const [name, entry] of Object.entries(rawData)) {
439
+ if (name.startsWith("_")) continue;
440
+ const converted = convertLitellmEntry(entry);
441
+ if (converted) out[name] = converted;
442
+ }
443
+ return out;
444
+ }
445
+
446
+ module.exports = {
447
+ lookupPricing,
448
+ stripReasoningSuffix,
449
+ normalizeAntigravityModel,
450
+ normalizeIFlytekMaasModel,
451
+ normalizeClaudeModel,
452
+ normalizeCursorModel,
453
+ normalizeZedModel,
454
+ convertLitellmEntry,
455
+ buildLitellmPerMillionMap,
456
+ };