chompyy 0.5.0 → 0.6.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.
Files changed (154) hide show
  1. package/README.md +11 -0
  2. package/dist/agentlimits.js +77 -0
  3. package/dist/agentusage.js +96 -0
  4. package/dist/appstate.js +63 -3
  5. package/dist/away.js +44 -5
  6. package/dist/blueprint.js +3 -7
  7. package/dist/board.js +1 -0
  8. package/dist/cli.js +263 -5
  9. package/dist/codexquota.js +106 -0
  10. package/dist/codexusage.js +10 -0
  11. package/dist/config.js +2 -0
  12. package/dist/context.js +30 -0
  13. package/dist/costs.js +1 -0
  14. package/dist/demon.js +20 -0
  15. package/dist/label.js +33 -0
  16. package/dist/menu.js +17 -0
  17. package/dist/nightcap.js +60 -0
  18. package/dist/nudge.js +47 -18
  19. package/dist/pacing.js +16 -1
  20. package/dist/questions.js +71 -0
  21. package/dist/recap.js +74 -0
  22. package/dist/receipt.js +48 -0
  23. package/dist/recipe.js +79 -0
  24. package/dist/stamps.js +14 -0
  25. package/dist/triggers.js +5 -0
  26. package/dist/usage.js +21 -1
  27. package/dist/vendor/codeburn/antigravity.js +309 -0
  28. package/dist/vendor/codeburn/codex.js +429 -0
  29. package/dist/vendor/codeburn/copilot.js +292 -0
  30. package/dist/vendor/codeburn/gemini.js +195 -0
  31. package/dist/vendor/codeburn/grokbot.js +182 -0
  32. package/dist/vendor/codeburn/kimi.js +178 -0
  33. package/dist/vendor/codeburn/shims/chalk.js +14 -0
  34. package/dist/vendor/codeburn/shims/strip-ansi.js +6 -0
  35. package/dist/vendor/codeburn/src/act/backup.js +83 -0
  36. package/dist/vendor/codeburn/src/act/model-defaults.js +151 -0
  37. package/dist/vendor/codeburn/src/act/types.js +37 -0
  38. package/dist/vendor/codeburn/src/bash-utils.js +204 -0
  39. package/dist/vendor/codeburn/src/behavioral-weight.js +47 -0
  40. package/dist/vendor/codeburn/src/cache-dir.js +26 -0
  41. package/dist/vendor/codeburn/src/cache-refresh-lock.js +543 -0
  42. package/dist/vendor/codeburn/src/cache-sweep.js +67 -0
  43. package/dist/vendor/codeburn/src/classifier.js +209 -0
  44. package/dist/vendor/codeburn/src/claude-identity.js +223 -0
  45. package/dist/vendor/codeburn/src/codex-cache.js +377 -0
  46. package/dist/vendor/codeburn/src/codex-fork-replay.js +232 -0
  47. package/dist/vendor/codeburn/src/codex-jsonl-fields.js +99 -0
  48. package/dist/vendor/codeburn/src/codex-session-index.js +113 -0
  49. package/dist/vendor/codeburn/src/codex-throughput.js +544 -0
  50. package/dist/vendor/codeburn/src/compare-stats.js +405 -0
  51. package/dist/vendor/codeburn/src/config.js +145 -0
  52. package/dist/vendor/codeburn/src/content-utils.js +56 -0
  53. package/dist/vendor/codeburn/src/context-tree-codex.js +329 -0
  54. package/dist/vendor/codeburn/src/context-tree.js +664 -0
  55. package/dist/vendor/codeburn/src/copilot-aiu.js +16 -0
  56. package/dist/vendor/codeburn/src/currency.js +189 -0
  57. package/dist/vendor/codeburn/src/cursor-cache.js +238 -0
  58. package/dist/vendor/codeburn/src/cursor-import.js +402 -0
  59. package/dist/vendor/codeburn/src/cursor-sync.js +256 -0
  60. package/dist/vendor/codeburn/src/daily-cache.js +2036 -0
  61. package/dist/vendor/codeburn/src/data/litellm-snapshot.json +1 -0
  62. package/dist/vendor/codeburn/src/data/pricing-fallback.json +1 -0
  63. package/dist/vendor/codeburn/src/day-aggregator.js +327 -0
  64. package/dist/vendor/codeburn/src/editor-data-dir.js +11 -0
  65. package/dist/vendor/codeburn/src/fetch-utils.js +18 -0
  66. package/dist/vendor/codeburn/src/format.js +118 -0
  67. package/dist/vendor/codeburn/src/fs-utils.js +270 -0
  68. package/dist/vendor/codeburn/src/git-origin.js +334 -0
  69. package/dist/vendor/codeburn/src/granular-history.js +328 -0
  70. package/dist/vendor/codeburn/src/hermes-session-ledger.js +512 -0
  71. package/dist/vendor/codeburn/src/launcher-homes.js +142 -0
  72. package/dist/vendor/codeburn/src/live-sessions.js +358 -0
  73. package/dist/vendor/codeburn/src/math-utils.js +8 -0
  74. package/dist/vendor/codeburn/src/menubar-json.js +294 -0
  75. package/dist/vendor/codeburn/src/models.js +1879 -0
  76. package/dist/vendor/codeburn/src/optimize-one-hour-cache.js +92 -0
  77. package/dist/vendor/codeburn/src/optimize.js +4110 -0
  78. package/dist/vendor/codeburn/src/parse-workers.js +219 -0
  79. package/dist/vendor/codeburn/src/parser.js +6953 -0
  80. package/dist/vendor/codeburn/src/path-privacy.js +26 -0
  81. package/dist/vendor/codeburn/src/plans.js +135 -0
  82. package/dist/vendor/codeburn/src/pr-signals.js +132 -0
  83. package/dist/vendor/codeburn/src/project-filter-warnings.js +33 -0
  84. package/dist/vendor/codeburn/src/provider-issues.js +30 -0
  85. package/dist/vendor/codeburn/src/providers/amp.js +286 -0
  86. package/dist/vendor/codeburn/src/providers/antigravity.js +1731 -0
  87. package/dist/vendor/codeburn/src/providers/claude.js +551 -0
  88. package/dist/vendor/codeburn/src/providers/cline-cli.js +401 -0
  89. package/dist/vendor/codeburn/src/providers/cline.js +63 -0
  90. package/dist/vendor/codeburn/src/providers/codebuff.js +336 -0
  91. package/dist/vendor/codeburn/src/providers/codewhale.js +442 -0
  92. package/dist/vendor/codeburn/src/providers/codex.js +1720 -0
  93. package/dist/vendor/codeburn/src/providers/command-code.js +196 -0
  94. package/dist/vendor/codeburn/src/providers/copilot.js +3278 -0
  95. package/dist/vendor/codeburn/src/providers/crush.js +226 -0
  96. package/dist/vendor/codeburn/src/providers/cursor-agent.js +837 -0
  97. package/dist/vendor/codeburn/src/providers/cursor.js +1163 -0
  98. package/dist/vendor/codeburn/src/providers/devin.js +569 -0
  99. package/dist/vendor/codeburn/src/providers/droid.js +324 -0
  100. package/dist/vendor/codeburn/src/providers/dsh.js +690 -0
  101. package/dist/vendor/codeburn/src/providers/forge.js +245 -0
  102. package/dist/vendor/codeburn/src/providers/gemini.js +230 -0
  103. package/dist/vendor/codeburn/src/providers/goose.js +252 -0
  104. package/dist/vendor/codeburn/src/providers/grok.js +581 -0
  105. package/dist/vendor/codeburn/src/providers/grokbot.js +290 -0
  106. package/dist/vendor/codeburn/src/providers/hermes.js +771 -0
  107. package/dist/vendor/codeburn/src/providers/ibm-bob.js +53 -0
  108. package/dist/vendor/codeburn/src/providers/index.js +360 -0
  109. package/dist/vendor/codeburn/src/providers/kilo-code.js +50 -0
  110. package/dist/vendor/codeburn/src/providers/kimi.js +363 -0
  111. package/dist/vendor/codeburn/src/providers/kimicode.js +402 -0
  112. package/dist/vendor/codeburn/src/providers/kiro.js +1174 -0
  113. package/dist/vendor/codeburn/src/providers/lingtai-tui.js +372 -0
  114. package/dist/vendor/codeburn/src/providers/mistral-vibe-unified.js +236 -0
  115. package/dist/vendor/codeburn/src/providers/mistral-vibe.js +405 -0
  116. package/dist/vendor/codeburn/src/providers/mux.js +242 -0
  117. package/dist/vendor/codeburn/src/providers/open-design.js +217 -0
  118. package/dist/vendor/codeburn/src/providers/openclaude.js +309 -0
  119. package/dist/vendor/codeburn/src/providers/openclaw.js +442 -0
  120. package/dist/vendor/codeburn/src/providers/opencode-file-parser.js +131 -0
  121. package/dist/vendor/codeburn/src/providers/opencode.js +91 -0
  122. package/dist/vendor/codeburn/src/providers/pi.js +429 -0
  123. package/dist/vendor/codeburn/src/providers/quickdesk.js +491 -0
  124. package/dist/vendor/codeburn/src/providers/qwen.js +193 -0
  125. package/dist/vendor/codeburn/src/providers/session-message.js +118 -0
  126. package/dist/vendor/codeburn/src/providers/sqlite-session-parser.js +457 -0
  127. package/dist/vendor/codeburn/src/providers/types.js +5 -0
  128. package/dist/vendor/codeburn/src/providers/vercel-gateway.js +135 -0
  129. package/dist/vendor/codeburn/src/providers/vscode-cline-parser.js +212 -0
  130. package/dist/vendor/codeburn/src/providers/warp.js +575 -0
  131. package/dist/vendor/codeburn/src/providers/zcode.js +249 -0
  132. package/dist/vendor/codeburn/src/providers/zed.js +187 -0
  133. package/dist/vendor/codeburn/src/providers/zerostack.js +139 -0
  134. package/dist/vendor/codeburn/src/quota/antigravity.js +310 -0
  135. package/dist/vendor/codeburn/src/quota/claude.js +244 -0
  136. package/dist/vendor/codeburn/src/quota/cursor.js +301 -0
  137. package/dist/vendor/codeburn/src/quota/security.js +299 -0
  138. package/dist/vendor/codeburn/src/quota/types.js +1 -0
  139. package/dist/vendor/codeburn/src/scan-facts.js +99 -0
  140. package/dist/vendor/codeburn/src/session-cache.js +3040 -0
  141. package/dist/vendor/codeburn/src/session-count-label.js +14 -0
  142. package/dist/vendor/codeburn/src/session-output.js +139 -0
  143. package/dist/vendor/codeburn/src/session-population.js +30 -0
  144. package/dist/vendor/codeburn/src/sessions-report.js +1342 -0
  145. package/dist/vendor/codeburn/src/sqlite.js +528 -0
  146. package/dist/vendor/codeburn/src/sync/otlp.js +420 -0
  147. package/dist/vendor/codeburn/src/telemetry-snapshot.js +244 -0
  148. package/dist/vendor/codeburn/src/token-estimate.js +5 -0
  149. package/dist/vendor/codeburn/src/types.js +16 -0
  150. package/dist/vendor/codeburn/src/work-units.js +126 -0
  151. package/dist/vendor/codeburn/src/workflow-insights.js +228 -0
  152. package/dist/vendor/codeburn/src/wsl.js +198 -0
  153. package/dist/vendor/codeburn/src/yield.js +666 -0
  154. package/package.json +1 -1
@@ -0,0 +1,1879 @@
1
+ // @ts-nocheck: codeburn type-checks this under its own tsconfig; Chompyy adds noUncheckedIndexedAccess (see UPSTREAM.md)
2
+ import { readFile, writeFile, mkdir } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { createHash } from 'crypto';
5
+ import { getCodeburnCacheDir } from './cache-dir.js';
6
+ import snapshotData from './data/litellm-snapshot.json' with { type: 'json' };
7
+ import fallbackData from './data/pricing-fallback.json' with { type: 'json' };
8
+ import { fetchWithTimeout } from './fetch-utils.js';
9
+ /// Providers whose reported `reasoningTokens` are a SUBSET of `outputTokens`
10
+ /// rather than a separate bucket to add on top. OpenAI bills reasoning as part
11
+ /// of output (every codex `token_count` event satisfies input + output ==
12
+ /// total), and Anthropic folds thinking into output the same way, so summing
13
+ /// the two double-counts both the cost and the displayed output tokens. Copilot
14
+ /// is the same case: its per-request token_details_json prices input/cache/output
15
+ /// and nothing else, and its store-row/shutdown calls carry reasoningTokens
16
+ /// beside an output count that already includes them, so adding reasoning on
17
+ /// top bills it twice.
18
+ /// DSH TokenUsage includes reasoning in output too; see the pinned contract:
19
+ /// https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/docs/subsystems/llm-streaming.md#tokenusage
20
+ /// Hermes stores completion/output tokens as the API reports them, reasoning inside.
21
+ const REASONING_INCLUDED_IN_OUTPUT = new Set(['claude', 'codex', 'copilot', 'dsh', 'hermes']);
22
+ /// Output tokens to bill and display for one call. Single source of truth so
23
+ /// the pricing sites and the display sums can never disagree about whether a
24
+ /// provider's reasoning tokens are already inside its output count (#1075).
25
+ export function billableOutputTokens(provider, outputTokens, reasoningTokens) {
26
+ return REASONING_INCLUDED_IN_OUTPUT.has(provider) ? outputTokens : outputTokens + reasoningTokens;
27
+ }
28
+ const LITELLM_URL = 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
29
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
30
+ // Bump whenever a ModelCosts field changes pricing behavior (cacheWriteCostIsExplicit
31
+ // from #1075/#1078; longContextTier from #1076). A cache written under an older/missing
32
+ // version is treated as a miss instead of read verbatim, so a stale on-disk file can't
33
+ // reintroduce a killed bug for up to CACHE_TTL_MS after an upgrade.
34
+ // Also folded into getPricingGenerationKey() below: a resident/snapshot-caching
35
+ // consumer needs the same "pricing behavior changed" signal this already gives
36
+ // the on-disk LiteLLM cache, not just the on-disk cache itself.
37
+ // 4: calculateCost bills an implicit cache-write rate as input for non-Anthropic models.
38
+ // 5: longContextTier rides ModelCosts, so a cached costs object is tier-aware (#1076).
39
+ // 6: fastMultiplier is now derived from LiteLLM's `<rate>_priority` keys when the
40
+ // source publishes no `provider_specific_entry.fast` (#1616), so a cached costs
41
+ // object can carry a multiplier the pre-fix fetch left at 1.
42
+ // 7: ModelCosts carries the Flex tier's rates (`flex`), read from `<rate>_flex`.
43
+ // 8: a bare id takes the maker's row over a reseller's, and a reseller's priced
44
+ // row over a reseller's $0 one, so a cached map can still hold azure_ai's rate under `grok-4.6`.
45
+ // 9: ModelCosts carries ultrafastMultiplier, derived from `<rate>_ultrafast` keys.
46
+ export const CACHE_SCHEMA_VERSION = 9;
47
+ const WEB_SEARCH_COST = 0.01;
48
+ const ONE_HOUR_CACHE_WRITE_MULTIPLIER_FROM_FIVE_MINUTE_RATE = 1.6;
49
+ // Explicit USD/token prices that must override LiteLLM/cache data. Cursor
50
+ // publishes house-model rates in the models table at cursor.com/docs/models
51
+ // (provider "Cursor", USD per 1M tokens): composer-2/2.5: $0.50 input, $2.50
52
+ // output, $0.20 cache read; composer-1.5: $3.50/$17.50/$0.35; composer-1:
53
+ // $1.25/$10/$0.125. Cursor publishes no separate cache-write rate for these,
54
+ // so cache write uses the input rate.
55
+ // deepseek-v3.2: DeepSeek's last published price was $0.28 miss / $0.028 hit /
56
+ // $0.42 output; LiteLLM's deepseek/deepseek-v3.2 row says $0.40 output while its
57
+ // own deepseek-chat row says $0.42. Drop once upstream corrects it.
58
+ // swe-2: Cognition's list price at docs.devin.ai/desktop/models, $3 input, $15
59
+ // output, $0.30 cache read per 1M, no cache-write rate. Plan promotions (free on
60
+ // self-serve until 15 Oct 2026, 75% off for enterprise until 31 Dec 2026) are
61
+ // left out, as they depend on the plan.
62
+ const BUILTIN_PRICE_OVERRIDES = {
63
+ 'deepseek-v3.2': [0.28e-6, 0.42e-6, null, 0.028e-6],
64
+ 'swe-2': [3e-6, 15e-6, null, 0.3e-6],
65
+ 'composer-2.5': [0.5e-6, 2.5e-6, 0.5e-6, 0.2e-6],
66
+ 'composer-2': [0.5e-6, 2.5e-6, 0.5e-6, 0.2e-6],
67
+ 'composer-1.5': [3.5e-6, 17.5e-6, 3.5e-6, 0.35e-6],
68
+ 'composer-1': [1.25e-6, 10e-6, 1.25e-6, 0.125e-6],
69
+ // Moonshot's published rate (platform.kimi.ai/docs/pricing/chat): $1.90 miss,
70
+ // $0.38 hit, $8.00 output. LiteLLM only carries a reseller row for it.
71
+ 'kimi-k2.7-code-highspeed': [1.9e-6, 8e-6, null, 0.38e-6],
72
+ };
73
+ // Assemble a ModelCosts, applying the cache-cost heuristics (write = 1.25x
74
+ // input, read = 0.1x input) when a source omits them. Shared by the bundled
75
+ // tuple path (tupleToCosts) and the live LiteLLM path (parseLiteLLMEntry) so the
76
+ // multipliers live in exactly one place.
77
+ function buildCosts(input, output, cacheWrite, cacheRead, fast, tier, flex, ultrafast) {
78
+ return {
79
+ inputCostPerToken: input,
80
+ outputCostPerToken: output,
81
+ cacheWriteCostPerToken: cacheWrite ?? input * 1.25,
82
+ cacheReadCostPerToken: cacheRead ?? input * 0.1,
83
+ webSearchCostPerRequest: WEB_SEARCH_COST,
84
+ fastMultiplier: fast ?? 1,
85
+ cacheWriteCostIsExplicit: cacheWrite !== null && cacheWrite !== undefined,
86
+ ...(tier ? { longContextTier: {
87
+ thresholdTokens: tier.threshold,
88
+ inputCostPerToken: tier.input,
89
+ outputCostPerToken: tier.output,
90
+ ...(tier.cacheWrite !== null ? { cacheWriteCostPerToken: tier.cacheWrite } : {}),
91
+ ...(tier.cacheRead !== null ? { cacheReadCostPerToken: tier.cacheRead } : {}),
92
+ ...(tier.fast !== undefined ? { fastMultiplier: tier.fast } : {}),
93
+ } } : {}),
94
+ ...(flex ? { flex: tupleToCosts(flex) } : {}),
95
+ ...(ultrafast ? { ultrafastMultiplier: ultrafast } : {}),
96
+ };
97
+ }
98
+ // For grok-4.6, prompt tokens mean input tokens plus cached input tokens for a
99
+ // request. At 200k prompt tokens, xAI prices every priced bucket at this high
100
+ // tier rather than applying a marginal rate. Cache creation stays unset because
101
+ // xAI publishes no separate cache-write rate.
102
+ const GROK_4_6_PROMPT_TOKEN_THRESHOLD = 200_000;
103
+ const GROK_4_6_HIGH_PROMPT_COSTS = buildCosts(4e-6, 12e-6, null, 1e-6, null);
104
+ // Providers verified to pass the vendor's long-context surcharge through to
105
+ // the bill. The mechanism is data-driven (any model's tier rides its bundled
106
+ // or live rates), but APPLYING it is evidence-based: codex bills the OpenAI
107
+ // above-272k rate directly (#1076, measured on a real corpus), while a real
108
+ // Copilot session on gpt-5.6-terra with ~6M-token prompts billed at the base
109
+ // rate (tests/parser.test.ts "(c4) attributed cost tracks recomputed cost") —
110
+ // applying the tier there fabricates spend, the exact class #1075 warned
111
+ // about. Adding a provider here requires that kind of billing evidence AND
112
+ // threading its provider through every calculateCost site that prices it (the
113
+ // codex sites, the Claude journal paths and the parser.ts central recompute
114
+ // pass it; the copilot residual path does not, so a newly added provider whose
115
+ // calls flow through it would silently stay tierless).
116
+ // antigravity has no per-token bill of its own; its cost is the Gemini API
117
+ // equivalent, and the Gemini API bills the above-200k tier per request.
118
+ // claude: Anthropic's pricing page bills the published long-context tiers per
119
+ // request (Haiku 5.5 over 100k prompt tokens, Sonnet 4.5 over 200k).
120
+ export const TIERED_PRICING_PROVIDERS = new Set(['codex', 'antigravity', 'claude']);
121
+ // Swap in the vendor's high tier when a request's prompt crosses the published
122
+ // threshold. A user-set priceOverride wins over any tier: the override row
123
+ // is rebuilt without one, exact or aliased. The generic branch serves the
124
+ // models of TIERED_PRICING_PROVIDERS whose rates
125
+ // carry a longContextTier (OpenAI's above-272k family, Anthropic's above-200k);
126
+ // grok-4.6 predates the data plumbing and stays hardcoded. Each tier rate the
127
+ // source published replaces its base rate; omitted slots keep the base.
128
+ export function tieredCostsFor(model, baseCosts, promptTokens, provider) {
129
+ if (exactPriceOverrideFor(model))
130
+ return baseCosts;
131
+ if (resolveCanonicalModelId(model) === 'grok-4.6' && promptTokens >= GROK_4_6_PROMPT_TOKEN_THRESHOLD) {
132
+ return GROK_4_6_HIGH_PROMPT_COSTS;
133
+ }
134
+ const tier = provider !== undefined && TIERED_PRICING_PROVIDERS.has(provider)
135
+ ? baseCosts.longContextTier
136
+ : undefined;
137
+ if (tier && promptTokens > tier.thresholdTokens) {
138
+ return {
139
+ ...baseCosts,
140
+ inputCostPerToken: tier.inputCostPerToken,
141
+ outputCostPerToken: tier.outputCostPerToken,
142
+ ...(tier.cacheWriteCostPerToken !== undefined ? { cacheWriteCostPerToken: tier.cacheWriteCostPerToken } : {}),
143
+ ...(tier.cacheReadCostPerToken !== undefined ? { cacheReadCostPerToken: tier.cacheReadCostPerToken } : {}),
144
+ ...(tier.fastMultiplier !== undefined ? { fastMultiplier: tier.fastMultiplier } : {}),
145
+ };
146
+ }
147
+ return baseCosts;
148
+ }
149
+ function tupleToCosts(raw) {
150
+ const [input, output, cacheWrite, cacheRead, fast, tier, flex, ultrafast] = raw;
151
+ return buildCosts(input, output, cacheWrite, cacheRead, fast, tier, flex, ultrafast);
152
+ }
153
+ function applyBuiltinPriceOverrides(pricing) {
154
+ for (const [name, raw] of Object.entries(BUILTIN_PRICE_OVERRIDES)) {
155
+ pricing.set(name, tupleToCosts(raw));
156
+ }
157
+ return pricing;
158
+ }
159
+ function loadSnapshot() {
160
+ const map = new Map();
161
+ for (const [name, raw] of Object.entries(snapshotData)) {
162
+ map.set(name, tupleToCosts(raw));
163
+ }
164
+ return map;
165
+ }
166
+ // Gap-fill pricing from models.dev / OpenRouter, keyed lowercase. getModelCosts
167
+ // consults it only after every exact, canonical, alias and priced prefix
168
+ // lookup, so a reseller variant name can't shadow a real canonical entry; an
169
+ // exact fallback key only beats a $0 prefix sibling.
170
+ const fallbackCosts = (() => {
171
+ const map = new Map();
172
+ for (const [name, raw] of Object.entries(fallbackData)) {
173
+ const lk = name.toLowerCase();
174
+ if (!map.has(lk))
175
+ map.set(lk, tupleToCosts(raw));
176
+ }
177
+ return map;
178
+ })();
179
+ let pricingCache = applyBuiltinPriceOverrides(loadSnapshot());
180
+ let sortedPricingKeys = null;
181
+ let lowercasePricingIndex = null;
182
+ function getSortedPricingKeys() {
183
+ if (sortedPricingKeys === null) {
184
+ sortedPricingKeys = Array.from(pricingCache.keys()).sort((a, b) => b.length - a.length);
185
+ }
186
+ return sortedPricingKeys;
187
+ }
188
+ // Case-insensitive index, built lazily. Lets a session model like `MiniMax-M3`
189
+ // resolve to a gap-filled OpenRouter key like `minimax-m3` (lowercase slug).
190
+ // First key wins on a lowercase collision so it stays deterministic.
191
+ //
192
+ // Zero-priced entries are excluded: LiteLLM ships `[0,0]` stubs (e.g.
193
+ // `GigaChat-2-Max`) for models it lists but has no price for. Indexing those
194
+ // would let a case-mismatched query (`gigachat-2-max`) resolve to a silent $0
195
+ // instead of returning null, which suppresses the unknown-model warning and
196
+ // hides real spend. A case-EXACT query still finds the stub via the normal
197
+ // pipeline; only the fuzzy case-insensitive path skips them.
198
+ function getLowercasePricingIndex() {
199
+ if (lowercasePricingIndex === null) {
200
+ lowercasePricingIndex = new Map();
201
+ const priced = (c) => c.inputCostPerToken > 0 || c.outputCostPerToken > 0;
202
+ // The live pricing data wins on any lowercase collision; the gap-fill only
203
+ // fills names that resolve to nothing through the normal pipeline.
204
+ for (const [key, costs] of pricingCache) {
205
+ const lk = key.toLowerCase();
206
+ if (priced(costs) && !lowercasePricingIndex.has(lk))
207
+ lowercasePricingIndex.set(lk, costs);
208
+ }
209
+ for (const [lk, costs] of fallbackCosts) {
210
+ if (priced(costs) && !lowercasePricingIndex.has(lk))
211
+ lowercasePricingIndex.set(lk, costs);
212
+ }
213
+ }
214
+ return lowercasePricingIndex;
215
+ }
216
+ function getCachePath() {
217
+ return join(getCodeburnCacheDir(), 'litellm-pricing.json');
218
+ }
219
+ /// Clamp a per-token rate to a sane non-negative value. Defense in depth
220
+ /// against a tampered LiteLLM JSON shipping a negative `input_cost_per_token`,
221
+ /// which would otherwise produce negative costs that subtract from totals.
222
+ /// We use Number.isFinite to also reject NaN/Infinity, and cap at $1/token
223
+ /// (well above the most expensive frontier model) so a stray decimal-place
224
+ /// shift in the upstream JSON can't wildly inflate spend numbers either.
225
+ function safePerTokenRate(n) {
226
+ if (n === undefined || !Number.isFinite(n) || n < 0)
227
+ return null;
228
+ if (n > 1)
229
+ return 1;
230
+ return n;
231
+ }
232
+ // Plain context-length tiers only; mirrors scripts/bundle-litellm.mjs
233
+ // TIER_KEY_RE (service-tier `_priority`/`_flex` variants and the 1-hour
234
+ // combination are not context thresholds). The live path needs its own copy
235
+ // because the bundler is a standalone .mjs script.
236
+ const TIER_KEY_RE = /^(input_cost_per_token|output_cost_per_token|cache_read_input_token_cost|cache_creation_input_token_cost)_above_(\d+)k_tokens$/;
237
+ // OpenAI bills its priority processing tier through explicit `<rate>_priority`
238
+ // keys sat beside the standard ones (input/output/cache-read/cache-write, plus
239
+ // the `_above_<n>k_tokens_priority` variants for gpt-5.6's long-context tier).
240
+ // Codex's Fast speed setting runs on that tier (#1616), so those keys are where
241
+ // its multiplier comes from — LiteLLM publishes none as a
242
+ // `provider_specific_entry.fast` for OpenAI models. Derived, never invented:
243
+ // only a ratio the source publishes for EVERY bucket it prices is used, so a
244
+ // model with no priority keys (gpt-5-codex, gpt-5.1-codex) or one whose ratios
245
+ // disagree between buckets (azure/gpt-5.5: 2.5x base, 2x above 272k) stays at
246
+ // 1x. Where the tier publishes priority rates they join the same agreement
247
+ // check, so the one multiplier prices both regimes (gpt-5.6). Where it publishes
248
+ // none (gpt-5.4, gpt-5.5) OpenAI quotes no Fast long-context price, so the tier
249
+ // carries fast 1 and stays at its standard rates rather than a guessed product.
250
+ // `provider_specific_entry.fast` (Anthropic's own multiplier) always wins where
251
+ // the source ships one and is left to cover the tier as before.
252
+ const PRIORITY_KEY_SUFFIX = '_priority';
253
+ // Generous bound: the largest ratio any vendor actually publishes is 2.5x, so
254
+ // anything past this is a corrupted or hostile upstream row, not a price.
255
+ const MAX_DERIVED_FAST_MULTIPLIER = 100;
256
+ function priorityMultiplierOf(entry, suffix = PRIORITY_KEY_SUFFIX) {
257
+ const record = entry;
258
+ const ratios = [];
259
+ let inputRatio;
260
+ let outputRatio;
261
+ for (const [key, value] of Object.entries(record)) {
262
+ if (!key.endsWith(suffix))
263
+ continue;
264
+ const base = record[key.slice(0, -suffix.length)];
265
+ if (typeof value !== 'number' || typeof base !== 'number')
266
+ continue;
267
+ if (!Number.isFinite(value) || !Number.isFinite(base) || value <= 0 || base <= 0)
268
+ continue;
269
+ const ratio = value / base;
270
+ if (key === `input_cost_per_token${suffix}`)
271
+ inputRatio = ratio;
272
+ else if (key === `output_cost_per_token${suffix}`)
273
+ outputRatio = ratio;
274
+ ratios.push(ratio);
275
+ }
276
+ // No priority input AND output rate means there is no priority price to
277
+ // scale the bill by, whatever stray priority keys the row carries.
278
+ if (inputRatio === undefined || outputRatio === undefined)
279
+ return null;
280
+ // "Within rounding": published ratios agree exactly in the JSON but can pick
281
+ // up a few ulps in the division (2.5 vs 2.4999999999999996), so compare
282
+ // relatively rather than for bitwise equality.
283
+ const agreed = ratios.every(r => Math.abs(r - inputRatio) <= 1e-9 * Math.max(r, inputRatio));
284
+ // Rounded to 4 decimals so division noise (1.7999999999999998) never ships.
285
+ return agreed && inputRatio <= MAX_DERIVED_FAST_MULTIPLIER ? Math.round(inputRatio * 1e4) / 1e4 : null;
286
+ }
287
+ function tierOfLiteLLMEntry(entry) {
288
+ // Rates are read ONLY from the largest threshold a model carries, mirroring
289
+ // scripts/bundle-litellm.mjs tierOf, so a two-tier entry can never mix a
290
+ // smaller tier's rates under the bigger threshold.
291
+ const byThreshold = new Map();
292
+ for (const [key, value] of Object.entries(entry)) {
293
+ const match = TIER_KEY_RE.exec(key);
294
+ if (!match || typeof value !== 'number' || !Number.isFinite(value) || value < 0)
295
+ continue;
296
+ const tokens = Number(match[2]) * 1000;
297
+ const rates = byThreshold.get(tokens) ?? {};
298
+ rates[match[1]] = value;
299
+ byThreshold.set(tokens, rates);
300
+ }
301
+ if (byThreshold.size === 0)
302
+ return null;
303
+ const threshold = Math.max(...byThreshold.keys());
304
+ const rates = byThreshold.get(threshold);
305
+ if (rates.input_cost_per_token === undefined || rates.output_cost_per_token === undefined)
306
+ return null;
307
+ return {
308
+ threshold,
309
+ input: rates.input_cost_per_token,
310
+ output: rates.output_cost_per_token,
311
+ cacheWrite: rates.cache_creation_input_token_cost ?? null,
312
+ cacheRead: rates.cache_read_input_token_cost ?? null,
313
+ };
314
+ }
315
+ // OpenAI's Flex processing tier (Codex service_tier "flex") ships as explicit
316
+ // `<rate>_flex` keys, `_above_<n>k_tokens_flex` for the long-context tier.
317
+ // Read as rates, not one ratio: gpt-5.4's flex cache read is $0.13/M, not half
318
+ // of $0.25/M, so a priority-style agreement check would drop it. Without both
319
+ // input and output flex rates the row has no Flex price and Flex bills at
320
+ // standard; any other bucket without a flex rate keeps its standard rate.
321
+ // Mirrored in scripts/bundle-litellm.mjs flexOf.
322
+ const FLEX_KEY_SUFFIX = '_flex';
323
+ function flexOf(entry, cacheWrite, cacheRead, tier) {
324
+ const record = entry;
325
+ const rate = (key) => {
326
+ const value = record[key + FLEX_KEY_SUFFIX];
327
+ return typeof value === 'number' ? safePerTokenRate(value) : null;
328
+ };
329
+ const input = rate('input_cost_per_token');
330
+ const output = rate('output_cost_per_token');
331
+ if (input === null || output === null)
332
+ return null;
333
+ const above = (key) => `${key}_above_${tier.threshold / 1000}k_tokens`;
334
+ return [input, output, rate('cache_creation_input_token_cost') ?? cacheWrite, rate('cache_read_input_token_cost') ?? cacheRead, null, tier ? {
335
+ threshold: tier.threshold,
336
+ input: rate(above('input_cost_per_token')) ?? tier.input,
337
+ output: rate(above('output_cost_per_token')) ?? tier.output,
338
+ cacheWrite: rate(above('cache_creation_input_token_cost')) ?? tier.cacheWrite,
339
+ cacheRead: rate(above('cache_read_input_token_cost')) ?? tier.cacheRead,
340
+ } : null];
341
+ }
342
+ export function parseLiteLLMEntry(entry) {
343
+ // The live LiteLLM map is remote JSON; a null (or non-object) value for a
344
+ // model would make the field reads below throw and abort the whole pricing
345
+ // load. Treat it as unparseable, like any other bad entry.
346
+ if (!entry || typeof entry !== 'object')
347
+ return null;
348
+ const inputCost = safePerTokenRate(entry.input_cost_per_token);
349
+ const outputCost = safePerTokenRate(entry.output_cost_per_token);
350
+ if (inputCost === null || outputCost === null)
351
+ return null;
352
+ const explicitFast = entry.provider_specific_entry?.fast;
353
+ const priorityFast = explicitFast == null ? priorityMultiplierOf(entry) : null;
354
+ const tier = tierOfLiteLLMEntry(entry);
355
+ if (tier && priorityFast !== null && !Object.keys(entry).some(k => k.endsWith(`_above_${tier.threshold / 1000}k_tokens${PRIORITY_KEY_SUFFIX}`))) {
356
+ tier.fast = 1;
357
+ }
358
+ const cacheWrite = safePerTokenRate(entry.cache_creation_input_token_cost);
359
+ const cacheRead = safePerTokenRate(entry.cache_read_input_token_cost);
360
+ return buildCosts(inputCost, outputCost, cacheWrite, cacheRead, explicitFast ?? priorityFast, tier, flexOf(entry, cacheWrite, cacheRead, tier), priorityMultiplierOf(entry, '_ultrafast'));
361
+ }
362
+ // Timestamp of whichever live LiteLLM data (freshly fetched or read back from
363
+ // the on-disk cache) is currently loaded into pricingCache; null when nothing
364
+ // live is loaded and pricing is purely the bundled snapshot (offline/first
365
+ // run, CODEBURN_PRICING_SNAPSHOT_ONLY, or a failed fetch with no cache hit).
366
+ // Read by getPricingGenerationKey() so a consumer that persists rendered
367
+ // costs across process invocations (the menubar's status snapshot) can tell
368
+ // "the live pricing data actually changed" apart from "nothing changed" —
369
+ // this module has no other way to signal that across a fresh CLI process.
370
+ let livePricingTimestamp = null;
371
+ const MAKER_PREFIXES = new Set([
372
+ 'xai', 'mistral', 'cohere', 'anthropic', 'openai', 'gemini', 'deepseek', 'moonshot',
373
+ 'zai', 'minimax', 'ai21', 'perplexity', 'dashscope', 'meta_llama', 'xiaomi_mimo',
374
+ ]);
375
+ // Two segments only: `perplexity/openai/gpt-5.6-sol` is Perplexity reselling.
376
+ const isMakerRow = (name) => name.split('/').length === 2 && MAKER_PREFIXES.has(name.split('/')[0]);
377
+ const isFreeRow = (c) => c.inputCostPerToken === 0 && c.outputCostPerToken === 0;
378
+ async function fetchAndCachePricing() {
379
+ // Bounded: runs on every CLI invocation (the menubar shells out and blocks on
380
+ // it). Without a timeout a half-open network after wake-from-sleep makes
381
+ // fetch() hang forever, wedging the menubar's loading spinner. On timeout the
382
+ // caller's catch falls back to the bundled price snapshot.
383
+ const response = await fetchWithTimeout(LITELLM_URL);
384
+ if (!response.ok)
385
+ throw new Error(`HTTP ${response.status}`);
386
+ const data = await response.json();
387
+ const pricing = new Map();
388
+ const parsed = [];
389
+ for (const [name, entry] of Object.entries(data)) {
390
+ const costs = parseLiteLLMEntry(entry);
391
+ if (costs)
392
+ parsed.push([name, costs]);
393
+ }
394
+ // Also index by stripped name so lookups work without provider prefix:
395
+ // 'anthropic/claude-opus-4-6' is also queryable as 'claude-opus-4-6'. A
396
+ // direct entry of that name always wins; otherwise the maker's own row beats
397
+ // a reseller's whatever the JSON order, even at $0, and among resellers a
398
+ // $0/$0 row yields to any priced one. Mirrors scripts/bundle-litellm.mjs.
399
+ const bareClaims = new Map();
400
+ const makerClaimed = new Set();
401
+ for (const [name, costs] of [...parsed.filter(([n]) => isMakerRow(n)), ...parsed.filter(([n]) => !isMakerRow(n))]) {
402
+ const stripped = name.replace(/^[^/]+\//, '');
403
+ if (stripped === name)
404
+ continue;
405
+ const prev = bareClaims.get(stripped);
406
+ if (!prev || (!makerClaimed.has(stripped) && isFreeRow(prev) && !isFreeRow(costs)))
407
+ bareClaims.set(stripped, costs);
408
+ if (isMakerRow(name))
409
+ makerClaimed.add(stripped);
410
+ }
411
+ for (const [name, costs] of parsed) {
412
+ pricing.set(name, costs);
413
+ const stripped = name.replace(/^[^/]+\//, '');
414
+ if (stripped !== name && !pricing.has(stripped))
415
+ pricing.set(stripped, bareClaims.get(stripped));
416
+ }
417
+ const timestamp = Date.now();
418
+ await mkdir(getCodeburnCacheDir(), { recursive: true });
419
+ await writeFile(getCachePath(), JSON.stringify({
420
+ version: CACHE_SCHEMA_VERSION,
421
+ timestamp,
422
+ data: Object.fromEntries(pricing),
423
+ }));
424
+ livePricingTimestamp = timestamp;
425
+ return pricing;
426
+ }
427
+ async function loadCachedPricing() {
428
+ try {
429
+ const raw = await readFile(getCachePath(), 'utf-8');
430
+ const cached = JSON.parse(raw);
431
+ if (cached.version !== CACHE_SCHEMA_VERSION)
432
+ return null;
433
+ if (Date.now() - cached.timestamp > CACHE_TTL_MS)
434
+ return null;
435
+ livePricingTimestamp = cached.timestamp;
436
+ return new Map(Object.entries(cached.data));
437
+ }
438
+ catch {
439
+ return null;
440
+ }
441
+ }
442
+ function mergeSnapshotFallbacks(pricing) {
443
+ for (const [name, costs] of loadSnapshot()) {
444
+ if (!pricing.has(name))
445
+ pricing.set(name, costs);
446
+ }
447
+ return applyBuiltinPriceOverrides(pricing);
448
+ }
449
+ function setPricingCache(pricing) {
450
+ pricingCache = pricing;
451
+ sortedPricingKeys = null;
452
+ lowercasePricingIndex = null;
453
+ knownNamespaces = null;
454
+ shortNameMemo.clear();
455
+ }
456
+ export async function loadPricing() {
457
+ const cached = await loadCachedPricing();
458
+ if (cached) {
459
+ setPricingCache(mergeSnapshotFallbacks(cached));
460
+ return;
461
+ }
462
+ // Test-only escape hatch, set for the whole suite in
463
+ // tests/setup/env-isolation.ts: skip the live LiteLLM fetch and price purely
464
+ // off the bundled snapshot, so an upstream reprice can't turn tests red.
465
+ if (process.env['CODEBURN_PRICING_SNAPSHOT_ONLY']) {
466
+ livePricingTimestamp = null;
467
+ setPricingCache(mergeSnapshotFallbacks(new Map()));
468
+ return;
469
+ }
470
+ try {
471
+ setPricingCache(mergeSnapshotFallbacks(await fetchAndCachePricing()));
472
+ }
473
+ catch {
474
+ // snapshot already loaded at init; nothing more to do
475
+ livePricingTimestamp = null;
476
+ }
477
+ }
478
+ // Content digest of the two bundled pricing files, computed once and memoized
479
+ // (they're static imports; nothing in-process can change them). Changes only
480
+ // when `scripts/bundle-litellm.mjs` regenerates litellm-snapshot.json /
481
+ // pricing-fallback.json and that regeneration ships in a new codeburn build —
482
+ // exactly the "bundled data" staleness class getPricingGenerationKey exists
483
+ // to catch, distinct from the live cache's own timestamp.
484
+ let bundledPricingDigest = null;
485
+ function getBundledPricingDigest() {
486
+ if (bundledPricingDigest === null) {
487
+ bundledPricingDigest = createHash('sha256')
488
+ .update(JSON.stringify(snapshotData))
489
+ .update(JSON.stringify(fallbackData))
490
+ .digest('hex');
491
+ }
492
+ return bundledPricingDigest;
493
+ }
494
+ /// Stable signature of everything that can silently change a session's
495
+ /// RENDERED cost with no session file ever changing: the live LiteLLM cache's
496
+ /// freshness (a repricing fetch, or its absence), the bundled snapshot's own
497
+ /// content (a repriced model shipped in a new build), and this module's
498
+ /// pricing-behavior version (CACHE_SCHEMA_VERSION). A caller that persists a
499
+ /// fully-rendered payload across process invocations (the menubar's status
500
+ /// snapshot) must fold this into its own cache key the same way it already
501
+ /// folds the four *ConfigHash getters above — those cover user-editable
502
+ /// pricing CONFIG, this covers upstream/bundled pricing DATA and code version,
503
+ /// a different staleness gap with no other invalidation path of its own.
504
+ export function getPricingGenerationKey() {
505
+ return `${CACHE_SCHEMA_VERSION}:${livePricingTimestamp ?? 'bundled'}:${getBundledPricingDigest()}`;
506
+ }
507
+ // Known model name variants that providers emit but LiteLLM/fallback don't index under.
508
+ // OMP emits 'anthropic--claude-4.6-opus' (double-dash, dot version, tier-last).
509
+ // getCanonicalName strips a KNOWN vendor/router prefix first unless the
510
+ // full cleaned id itself is an alias (orcarouter/fusion). Post-strip forms
511
+ // still cover every other entry here.
512
+ const BUILTIN_ALIASES = {
513
+ 'anthropic--claude-4.6-opus': 'claude-opus-4-6',
514
+ 'anthropic--claude-4.6-sonnet': 'claude-sonnet-4-6',
515
+ 'anthropic--claude-4.5-opus': 'claude-opus-4-5',
516
+ 'anthropic--claude-4.5-sonnet': 'claude-sonnet-4-5',
517
+ 'anthropic--claude-4.5-haiku': 'claude-haiku-4-5',
518
+ // #1093: copilot session-store.db writes 'claude-haiku-4.5' (tier-first, dot)
519
+ 'claude-haiku-4.5': 'claude-haiku-4-5',
520
+ // Copilot's own spellings of the pre-2026 Claude SKUs (VS Code chat sessions, session-store.db)
521
+ 'claude-3.5-sonnet': 'claude-3-5-sonnet',
522
+ 'claude-3.7-sonnet': 'claude-3-7-sonnet',
523
+ 'claude-3.7-sonnet-thought': 'claude-3-7-sonnet',
524
+ 'claude-opus-4.1': 'claude-opus-4-1',
525
+ 'claude-sonnet-4.6': 'claude-sonnet-4-6',
526
+ 'claude-sonnet-4.5': 'claude-sonnet-4-5',
527
+ 'claude-opus-4.7': 'claude-opus-4-7',
528
+ 'claude-opus-4.6': 'claude-opus-4-6',
529
+ 'claude-opus-4.5': 'claude-opus-4-5',
530
+ 'cursor-auto': 'claude-sonnet-4-5',
531
+ 'cursor-agent-auto': 'claude-sonnet-4-5',
532
+ 'copilot-auto': 'claude-sonnet-4-5',
533
+ 'copilot-openai-auto': 'gpt-5.3-codex',
534
+ 'copilot-anthropic-auto': 'claude-sonnet-4-5',
535
+ 'openai-codex:gpt-5.5': 'gpt-5.5',
536
+ 'ibm-bob-auto': 'claude-sonnet-4-5',
537
+ 'kiro-auto': 'claude-sonnet-4-5',
538
+ 'quickdesk-auto': 'claude-sonnet-4-5',
539
+ 'cline-auto': 'claude-sonnet-4-5',
540
+ 'openclaw-auto': 'claude-sonnet-4-5',
541
+ 'warp-auto-efficient': 'gpt-5.3-codex',
542
+ 'warp-auto-powerful': 'claude-opus-4-6',
543
+ // `codex-auto-review` is a server-routed alias: rollouts record it in
544
+ // turn_context.model and nothing on disk names the real model. OpenAI moved
545
+ // auto review from GPT-5.4 to GPT-5.6 Luna on 30 Jul 2026 (announcement:
546
+ // "major price drop for 5.6 Terra and Luna"). This row is the forward
547
+ // default; pricingModelAt prices calls before 2026-07-30T00:00Z as gpt-5.4.
548
+ // A rollout that records the real model (API-key auth writes gpt-5.6-luna)
549
+ // is priced as recorded. Display stays on autoModelNames.
550
+ 'codex-auto-review': 'gpt-5.6-luna',
551
+ // Luna Reserve: the quota Codex falls back to once ordinary usage runs out
552
+ // (openai/codex#42372, LUNA_RESERVE_MODEL in codex-rs/tui/src/model_catalog.rs).
553
+ // The backend picks the real model and rollouts don't record it. GPT-5.6 Luna
554
+ // was the client fallback until 22 Sep 2026 (then GPT-6 Luna, half the
555
+ // price), so this is an upper-bound estimate and the codex parser marks it so.
556
+ 'gpt-reserve': 'gpt-5.6-luna',
557
+ // Short spelling of the only 5.3 Spark model (openai/codex uses it as a
558
+ // config model id in codex-rs/app-server/tests/suite/v2/config_rpc.rs).
559
+ 'gpt-5.3-spark': 'gpt-5.3-codex-spark',
560
+ 'grok-build': 'grok-build-0.1',
561
+ // Grok Bot's desktop app serves opaque `sand-*` aliases and records no model
562
+ // id at all, so there is nothing truthful to price it by. It is xAI's own
563
+ // product, so it prices at xAI's published grok-4.6 rate ($2.00/M in,
564
+ // $6.00/M out, $0.50/M cached). Every grokbot call is costIsEstimated.
565
+ 'grokbot-auto': 'grok-4.6',
566
+ // The same Grok Bot work as Cursor's usage export names it, per bot kind.
567
+ 'grok-bot-automation': 'grok-4.6',
568
+ 'grok-bot-cua': 'grok-4.6',
569
+ 'grok-bot-default': 'grok-4.6',
570
+ // Cursor-hosted Grok 4.6 as Cursor's usage export names it: the same model,
571
+ // so it takes grok-4.6's 200k-prompt tier like the local Cursor rows do.
572
+ 'grok-4.6-high': 'grok-4.6',
573
+ 'grok-4.6-high-fast': 'grok-4.6',
574
+ 'cursor-grok-4.6-high': 'grok-4.6',
575
+ 'cursor-grok-4.6-high-fast': 'grok-4.6',
576
+ 'GPT-5.3 Codex (low reasoning)': 'gpt-5.3-codex',
577
+ 'GPT-5.3 Codex (medium reasoning)': 'gpt-5.3-codex',
578
+ 'GPT-5.3 Codex (high reasoning)': 'gpt-5.3-codex',
579
+ 'GPT-5.3 Codex (extra high reasoning)': 'gpt-5.3-codex',
580
+ 'Claude Sonnet 4.6': 'claude-sonnet-4-6',
581
+ 'Claude Sonnet 4.5': 'claude-sonnet-4-5',
582
+ 'Claude Haiku 4.5': 'claude-haiku-4-5',
583
+ 'Claude Opus 4.6': 'claude-opus-4-6',
584
+ 'claude-4-6-sonnet-high': 'claude-sonnet-4-6',
585
+ 'claude-4-6-sonnet-low': 'claude-sonnet-4-6',
586
+ 'claude-4-6-sonnet-medium': 'claude-sonnet-4-6',
587
+ 'claude-4-6-sonnet-high-fast': 'claude-sonnet-4-6',
588
+ 'claude-4-7-opus-xhigh': 'claude-opus-4-7',
589
+ 'claude-4-7-opus-xhigh-fast': 'claude-opus-4-7',
590
+ 'qwen-auto': 'claude-sonnet-4-5',
591
+ // OrcaRouter fusion routes. Provenance: live OrcaRouter completion `model`
592
+ // field, 2026-08 (community #1058 / house #1118). Re-verify if the gateway
593
+ // rotates targets. `orcarouter/auto` is intentionally unaliased: the smart
594
+ // route currently lands on a Qwen/Llama flash model, so a Sonnet alias
595
+ // would overprice ~3–30×. Fail closed until a live probe pins that target.
596
+ 'orcarouter/fusion': 'openai/gpt-oss-120b',
597
+ 'orcarouter/fusion-flash': 'openai/gpt-oss-120b',
598
+ 'orcarouter/fusion-mini': 'openai/gpt-oss-120b',
599
+ 'kimi-auto': 'kimi-k2-thinking',
600
+ // `kimi-for-coding` is Kimi Code's moving alias; `kimi-code` is kimi-cli's
601
+ // spelling of the same SKU. pricingModelAt prices older calls by the model
602
+ // the alias served then. K2.8 Preview (11 Sep 2026 on) has no Open Platform
603
+ // price, so it stays on K2.7 Code's.
604
+ 'kimi-code': 'kimi-k2.7-code',
605
+ 'kimi-for-coding': 'kimi-k2.7-code',
606
+ // HighSpeed has been K2.7 Code HighSpeed since it launched on 9 Jul 2026.
607
+ 'kimi-for-coding-highspeed': 'kimi-k2.7-code-highspeed',
608
+ // Kimi Code wires report the bare `k3` id in llm.request.model; without an
609
+ // alias those calls priced at $0 and the provider looked absent in the UI.
610
+ 'k3': 'kimi-k3',
611
+ // Kimi desktop/IDE embedded runtime serves `k3-agent` / `k2d6-agent`.
612
+ 'k3-agent': 'kimi-k3',
613
+ 'k2d6-agent': 'kimi-k2p6',
614
+ 'mimo-v2-flash': 'xiaomi/mimo-v2-flash',
615
+ // Hermes / Xiaomi token-plan sessions store the bare id. LiteLLM's row is
616
+ // namespaced. Same class as mimo-v2-flash above — do not invent a rate.
617
+ 'mimo-v2.5-pro': 'xiaomi/mimo-v2.5-pro',
618
+ 'mimo-v2.5': 'xiaomi/mimo-v2.5',
619
+ 'kat-coder-pro-v1': 'kwaipilot/kat-coder-pro',
620
+ // Cursor emits dot-version tier-last names plus tier/reasoning suffixes
621
+ // that LiteLLM does not index (`-high`, `-low`, `-medium`, `-thinking`,
622
+ // `-high-thinking`, `-fast-mode`). Missing aliases here surface as $0 in
623
+ // the dashboard for users on non-Auto models (issue #159). Sources: the
624
+ // display map at `src/providers/cursor.ts:modelDisplayNames`, Cursor's
625
+ // public model docs at https://cursor.com/docs/models, and forum bug
626
+ // reports that quote literal slugs (e.g. forum.cursor.com/t/154933).
627
+ 'claude-4-sonnet': 'claude-sonnet-4',
628
+ 'claude-4-sonnet-1m': 'claude-sonnet-4',
629
+ 'claude-4-sonnet-thinking': 'claude-sonnet-4',
630
+ 'claude-4.5-sonnet': 'claude-sonnet-4-5',
631
+ 'claude-4.5-sonnet-thinking': 'claude-sonnet-4-5',
632
+ 'claude-4.6-sonnet': 'claude-sonnet-4-6',
633
+ 'claude-4.6-sonnet-high': 'claude-sonnet-4-6',
634
+ 'claude-4.6-sonnet-low': 'claude-sonnet-4-6',
635
+ 'claude-4.6-sonnet-thinking': 'claude-sonnet-4-6',
636
+ 'claude-4.6-sonnet-high-thinking': 'claude-sonnet-4-6',
637
+ 'claude-4-opus': 'claude-opus-4',
638
+ 'claude-4.5-opus': 'claude-opus-4-5',
639
+ 'claude-4.5-opus-high': 'claude-opus-4-5',
640
+ 'claude-4.5-opus-low': 'claude-opus-4-5',
641
+ 'claude-4.5-opus-medium': 'claude-opus-4-5',
642
+ 'claude-4.5-opus-high-thinking': 'claude-opus-4-5',
643
+ 'claude-4.6-opus': 'claude-opus-4-6',
644
+ 'claude-4.6-opus-fast-mode': 'claude-opus-4-6',
645
+ 'claude-4.6-opus-high': 'claude-opus-4-6',
646
+ 'claude-4.6-opus-low': 'claude-opus-4-6',
647
+ 'claude-4.6-opus-medium': 'claude-opus-4-6',
648
+ 'claude-4.6-opus-high-thinking': 'claude-opus-4-6',
649
+ 'claude-4.7-opus': 'claude-opus-4-7',
650
+ // Dash form (NOT dot) seen in forum.cursor.com/t/158597.
651
+ 'claude-opus-4-7-thinking-high': 'claude-opus-4-7',
652
+ 'claude-4.5-haiku': 'claude-haiku-4-5',
653
+ 'claude-4.6-haiku': 'claude-haiku-4-5',
654
+ // Cursor house composer models use Cursor-published rates in
655
+ // BUILTIN_PRICE_OVERRIDES; keep them out of this alias map so they do not
656
+ // inherit Claude Sonnet proxy pricing.
657
+ // Cursor's "fast" routing variant of GPT-5 is the same model behind a
658
+ // lower-latency endpoint; price as base GPT-5 until LiteLLM tracks it.
659
+ 'gpt-5-fast': 'gpt-5',
660
+ 'gpt-4.1': 'gpt-4.1',
661
+ 'gpt-5.2-low': 'gpt-5',
662
+ 'gpt-5.1-codex-high': 'gpt-5.3-codex',
663
+ // Antigravity Gemini model IDs resolve to preview-priced entries.
664
+ 'gemini-3.1-pro': 'gemini-3.1-pro-preview',
665
+ 'gemini-3-flash': 'gemini-3-flash-preview',
666
+ 'gemini-3.1-pro-high': 'gemini-3.1-pro-preview',
667
+ 'gemini-3.1-pro-low': 'gemini-3.1-pro-preview',
668
+ 'gemini-3-flash-agent': 'gemini-3-flash-preview',
669
+ 'gemini-3.5-flash-high': 'gemini-3.5-flash',
670
+ 'gemini-3.5-flash-medium': 'gemini-3.5-flash',
671
+ 'gemini-3.5-flash-low': 'gemini-3.5-flash',
672
+ 'Gemini 3.5 Flash (High)': 'gemini-3.5-flash',
673
+ 'Gemini 3.5 Flash (Medium)': 'gemini-3.5-flash',
674
+ 'Gemini 3.5 Flash (Low)': 'gemini-3.5-flash',
675
+ 'gemini-3-pro': 'gemini-3-pro-preview',
676
+ 'gemini-3.1-flash-image': 'gemini-3.1-flash-image-preview',
677
+ 'gemini-3.1-flash-lite': 'gemini-3.1-flash-lite-preview',
678
+ // ZCode reports GLM-5.2/5.3 capitalized; Hermes/Cline use lowercase. The
679
+ // snapshot's bare `glm-5.2`/`glm-5.3` rows carry the LIST rate ($1.4/$4.4);
680
+ // z.ai's own `z-ai/glm-5.2`/`z-ai/glm-5.3` rows are the discounted rate we
681
+ // actually pay. Point every spelling at the z-ai rows.
682
+ 'glm-5.2': 'z-ai/glm-5.2',
683
+ 'GLM-5.2': 'z-ai/glm-5.2',
684
+ 'glm-5.3': 'z-ai/glm-5.3',
685
+ 'GLM-5.3': 'z-ai/glm-5.3',
686
+ };
687
+ let userAliases = {};
688
+ let userPriceOverrides = new Map();
689
+ let userPriceOverridesConfig = {};
690
+ let sortedPriceOverrideKeys = null;
691
+ let lowercasePriceOverrideIndex = null;
692
+ // Called once during CLI startup after config is loaded.
693
+ // User aliases take precedence over built-ins.
694
+ export function setModelAliases(aliases) {
695
+ userAliases = aliases;
696
+ shortNameMemo.clear();
697
+ }
698
+ function priceOverrideRatePerToken(usdPerMillion) {
699
+ if (typeof usdPerMillion !== 'number')
700
+ return null;
701
+ return safePerTokenRate(usdPerMillion / 1_000_000);
702
+ }
703
+ // Called once during CLI startup after config is loaded.
704
+ // Config/CLI rates are USD per 1,000,000 tokens; ModelCosts stores USD/token.
705
+ export function setPriceOverrides(overrides) {
706
+ const next = new Map();
707
+ const nextConfig = {};
708
+ for (const [model, rates] of Object.entries(overrides)) {
709
+ if (!model || !rates || typeof rates !== 'object')
710
+ continue;
711
+ nextConfig[model] = { ...rates };
712
+ const input = priceOverrideRatePerToken(rates.input);
713
+ const output = priceOverrideRatePerToken(rates.output);
714
+ if (input === null || output === null)
715
+ continue;
716
+ next.set(model, buildCosts(input, output, priceOverrideRatePerToken(rates.cacheCreation), priceOverrideRatePerToken(rates.cacheRead), undefined));
717
+ }
718
+ userPriceOverrides = next;
719
+ userPriceOverridesConfig = nextConfig;
720
+ sortedPriceOverrideKeys = null;
721
+ lowercasePriceOverrideIndex = null;
722
+ }
723
+ function getSortedPriceOverrideKeys() {
724
+ if (sortedPriceOverrideKeys === null) {
725
+ sortedPriceOverrideKeys = Array.from(userPriceOverrides.keys()).sort((a, b) => b.length - a.length);
726
+ }
727
+ return sortedPriceOverrideKeys;
728
+ }
729
+ function getLowercasePriceOverrideIndex() {
730
+ if (lowercasePriceOverrideIndex === null) {
731
+ lowercasePriceOverrideIndex = new Map();
732
+ for (const [key, costs] of userPriceOverrides) {
733
+ const lk = key.toLowerCase();
734
+ if (!lowercasePriceOverrideIndex.has(lk))
735
+ lowercasePriceOverrideIndex.set(lk, costs);
736
+ }
737
+ }
738
+ return lowercasePriceOverrideIndex;
739
+ }
740
+ function getPriceOverrideExact(...keys) {
741
+ for (const key of keys) {
742
+ const costs = userPriceOverrides.get(key);
743
+ if (costs)
744
+ return costs;
745
+ }
746
+ return null;
747
+ }
748
+ // Keys run longest first. A 1-2 digit segment after the longest dash prefix is
749
+ // a minor version (claude-opus-4-9 is not claude-opus-4), the boundary
750
+ // modelKeyMatches applies to display names; every shorter key crosses it too.
751
+ function longestPricingPrefix(canonical, keys) {
752
+ for (const key of keys) {
753
+ if (canonical === key)
754
+ return key;
755
+ if (canonical.startsWith(key + '-')) {
756
+ return /^\d{1,2}(?:$|[-.])/.test(canonical.slice(key.length + 1)) ? null : key;
757
+ }
758
+ }
759
+ return null;
760
+ }
761
+ function getPriceOverridePrefix(canonical) {
762
+ const key = longestPricingPrefix(canonical, getSortedPriceOverrideKeys());
763
+ return key === null ? null : userPriceOverrides.get(key);
764
+ }
765
+ function getPriceOverrideCaseInsensitive(canonical, withPrefix) {
766
+ const lowerIndex = getLowercasePriceOverrideIndex();
767
+ return lowerIndex.get(canonical.toLowerCase()) ?? lowerIndex.get(withPrefix.toLowerCase()) ?? null;
768
+ }
769
+ export const DISCOUNT_KINDS = ['input', 'output', 'cacheWrite', 'cacheRead'];
770
+ export const NO_DISCOUNT = { input: 1, output: 1, cacheWrite: 1, cacheRead: 1, other: 1 };
771
+ let userDiscounts = {};
772
+ export function isValidDiscountPercent(percent) {
773
+ return typeof percent === 'number' && Number.isFinite(percent) && percent >= 0 && percent <= 100;
774
+ }
775
+ export function setPriceDiscounts(discounts) {
776
+ userDiscounts = Object.fromEntries(Object.entries(discounts).filter(([scope, percent]) => scope && isValidDiscountPercent(percent)));
777
+ }
778
+ export function hasPriceDiscounts() {
779
+ return Object.keys(userDiscounts).length > 0;
780
+ }
781
+ export function discountFactors(model, provider) {
782
+ const canonicalName = getCanonicalName(model);
783
+ const ids = [model, model.replace(/@.*$/, '').replace(/-\d{8}$/, ''), canonicalName, resolveAlias(canonicalName)];
784
+ const factor = (scopes) => {
785
+ const hit = scopes.find(scope => Object.hasOwn(userDiscounts, scope));
786
+ return hit === undefined ? 1 : 1 - userDiscounts[hit] / 100;
787
+ };
788
+ const base = [...ids, ...(provider ? [provider] : [])];
789
+ const out = { ...NO_DISCOUNT, other: factor(base) };
790
+ for (const kind of DISCOUNT_KINDS)
791
+ out[kind] = factor([...ids.map(id => `${id}:${kind}`), ...base]);
792
+ return out;
793
+ }
794
+ // Local-model savings config. Kept separate from userAliases: a `modelAliases`
795
+ // entry rewrites a model's identity for actual cost; a `localModelSavings`
796
+ // entry keeps the model cost at $0 and reports the *avoided* spend against a
797
+ // paid baseline. Set during preAction from `config.localModelSavings`.
798
+ let userLocalModelSavings = {};
799
+ export function setLocalModelSavings(mappings) {
800
+ userLocalModelSavings = { ...mappings };
801
+ }
802
+ export function getLocalSavingsBaseline(rawModel) {
803
+ if (!rawModel || typeof rawModel !== 'string')
804
+ return undefined;
805
+ // Defensive: bracket-accessing user-controlled keys on a plain object
806
+ // exposes the prototype chain (`__proto__` would resolve to Object.prototype).
807
+ // Use Object.hasOwn so a hostile JSONL model name cannot piggyback into
808
+ // Object.prototype either through the alias map or here.
809
+ if (!Object.hasOwn(userLocalModelSavings, rawModel))
810
+ return undefined;
811
+ return userLocalModelSavings[rawModel];
812
+ }
813
+ /// Compute the hypothetical baseline cost for a local call. The baseline
814
+ /// model is priced through the normal `calculateCost` pipeline (so it can
815
+ /// be aliased / canonicalized). Returns `null` when the source model has
816
+ /// no savings mapping, the baseline is unknown to the pricing snapshot, or
817
+ /// any input is unusable — callers should treat null as "no savings
818
+ /// recorded for this call" rather than a hard error.
819
+ export function calculateLocalModelSavings(rawModel, inputTokens, outputTokens, cacheCreationTokens, cacheReadTokens, webSearchRequests, speed = 'standard', oneHourCacheCreationTokens = 0) {
820
+ const baseline = getLocalSavingsBaseline(rawModel);
821
+ if (!baseline)
822
+ return null;
823
+ if (!getModelCosts(baseline))
824
+ return null;
825
+ const savingsUSD = calculateCost(baseline, inputTokens, outputTokens, cacheCreationTokens, cacheReadTokens, webSearchRequests, speed, oneHourCacheCreationTokens);
826
+ return { savingsUSD, baselineModel: baseline };
827
+ }
828
+ /// Stable hash of the current savings config so the daily cache can detect
829
+ /// "user changed their baseline mapping" and rebuild instead of presenting
830
+ /// stale saved-spend numbers. Two configs with the same key→baseline pairs
831
+ /// in any order collapse to the same hash.
832
+ export function getLocalModelSavingsConfigHash() {
833
+ const keys = Object.keys(userLocalModelSavings).sort();
834
+ if (keys.length === 0)
835
+ return '';
836
+ const parts = keys.map(k => `${k}\u0001${userLocalModelSavings[k]}`);
837
+ return parts.join('\u0002');
838
+ }
839
+ // Subscription / flat-rate product SKUs. $0 is the correct cost; aliasing
840
+ // them onto a per-token row fabricates spend (#968). Distinct from
841
+ // model-savings (counterfactual local baseline) and from a zero-rate
842
+ // price-override (user-declared free). Built-in families plus a user hatch.
843
+ let userFlatRateModels = new Set();
844
+ let userFlatRateLeaves = new Set();
845
+ let userFlatRateRemoved = new Set();
846
+ let userFlatRateRemovedLeaves = new Set();
847
+ function flatRateLeaf(model) {
848
+ const trimmed = model.trim().replace(/@.*$/, '').replace(/-\d{8}$/, '');
849
+ const leaf = trimmed.includes('/') ? trimmed.slice(trimmed.lastIndexOf('/') + 1) : trimmed;
850
+ return leaf.toLowerCase();
851
+ }
852
+ function fillFlatRateSet(models) {
853
+ const ids = new Set();
854
+ const leaves = new Set();
855
+ for (const model of models) {
856
+ if (!model || typeof model !== 'string')
857
+ continue;
858
+ ids.add(model);
859
+ const leaf = flatRateLeaf(model);
860
+ if (leaf)
861
+ leaves.add(leaf);
862
+ }
863
+ return { ids, leaves };
864
+ }
865
+ export function setFlatRateModels(models) {
866
+ const filled = fillFlatRateSet(models);
867
+ userFlatRateModels = filled.ids;
868
+ userFlatRateLeaves = filled.leaves;
869
+ }
870
+ export function setFlatRateRemoved(models) {
871
+ const filled = fillFlatRateSet(models);
872
+ userFlatRateRemoved = filled.ids;
873
+ userFlatRateRemovedLeaves = filled.leaves;
874
+ }
875
+ export function getFlatRateModelsConfigHash() {
876
+ const added = [...userFlatRateModels].sort().join('\u0002');
877
+ const removed = [...userFlatRateRemoved].sort().join('\u0002');
878
+ if (!removed)
879
+ return added;
880
+ return `${added}\u0003${removed}`;
881
+ }
882
+ export function getFlatRateModels() {
883
+ return [...userFlatRateModels];
884
+ }
885
+ export function getFlatRateRemoved() {
886
+ return [...userFlatRateRemoved];
887
+ }
888
+ export function isSameFlatRateModel(a, b) {
889
+ if (!a || !b)
890
+ return false;
891
+ if (a === b)
892
+ return true;
893
+ const leaf = flatRateLeaf(a);
894
+ return leaf.length > 0 && leaf === flatRateLeaf(b);
895
+ }
896
+ function isUserFlatRateModel(model) {
897
+ if (userFlatRateModels.has(model))
898
+ return true;
899
+ const leaf = flatRateLeaf(model);
900
+ return leaf.length > 0 && userFlatRateLeaves.has(leaf);
901
+ }
902
+ function isFlatRateRemoved(model) {
903
+ if (userFlatRateRemoved.has(model))
904
+ return true;
905
+ const leaf = flatRateLeaf(model);
906
+ return leaf.length > 0 && userFlatRateRemovedLeaves.has(leaf);
907
+ }
908
+ /// Product SKUs billed as a subscription, not missing LiteLLM rows.
909
+ /// Match raw ids and path-prefixed ids (`cline-pass/auto-genius`). Display
910
+ /// names from getShortModelName are matched only when the aggregation key
911
+ /// is not the raw leaf (Warp Auto *, Grok Composer *).
912
+ export function isBuiltInFlatRateModel(model) {
913
+ const leaf = flatRateLeaf(model);
914
+ // Warp's product SKU is the bare id `auto`. Kiro rewrites its own `auto`
915
+ // to `kiro-auto` before pricing, so this leaf does not swallow Kiro.
916
+ if (leaf === 'auto'
917
+ || leaf === 'auto-genius')
918
+ return true;
919
+ if (leaf.startsWith('grok-composer-'))
920
+ return true;
921
+ if (leaf.startsWith('warp-auto-'))
922
+ return true;
923
+ const display = model.trim();
924
+ if (/^grok composer\b/i.test(display))
925
+ return true;
926
+ if (/^warp auto\b/i.test(display))
927
+ return true;
928
+ return false;
929
+ }
930
+ export function isFlatRateModel(model) {
931
+ if (!model)
932
+ return false;
933
+ if (isFlatRateRemoved(model))
934
+ return false;
935
+ return isUserFlatRateModel(model) || isBuiltInFlatRateModel(model);
936
+ }
937
+ /// Shared unpriced-warning copy. Never tell the user to alias unconditionally:
938
+ /// mapping a subscription SKU onto a priced row invents spend. Optional `model`
939
+ /// interpolates the sanitized id so the verbose calculateCost path names the
940
+ /// same two hatches.
941
+ export function unpricedModelHint(model = '<model>') {
942
+ const safe = model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200);
943
+ return `If a model is billed per token, map it with: codeburn model-alias "${safe}" <known-model>. If $0 is correct (subscription / flat-rate): codeburn model-flat-rate "${safe}".`;
944
+ }
945
+ /// Stable hash of the model-alias map, for the same staleness class as the
946
+ /// hashes below: a resident process (codeburn serve) must not serve memoized
947
+ /// parse results priced under aliases the user has since changed.
948
+ export function getModelAliasesConfigHash() {
949
+ const keys = Object.keys(userAliases).sort();
950
+ if (keys.length === 0)
951
+ return '';
952
+ return keys.map(k => `${k}\u0001${userAliases[k]}`).join('\u0002');
953
+ }
954
+ export function getPriceOverridesConfigHash() {
955
+ // The builtin overrides participate so editing BUILTIN_PRICE_OVERRIDES in a
956
+ // release invalidates cached daily costs the same way a user override does.
957
+ const builtin = `builtin:${JSON.stringify(BUILTIN_PRICE_OVERRIDES)}`;
958
+ const keys = Object.keys(userPriceOverridesConfig).sort();
959
+ const discounts = Object.keys(userDiscounts).sort().map(k => `discount:${k}\u0001${userDiscounts[k]}`);
960
+ const parts = keys.map(k => {
961
+ const rates = userPriceOverridesConfig[k];
962
+ return [
963
+ k,
964
+ rates.input,
965
+ rates.output,
966
+ rates.cacheRead ?? '',
967
+ rates.cacheCreation ?? '',
968
+ ].join('\u0001');
969
+ });
970
+ return [builtin, ...parts, ...discounts].join('\u0002');
971
+ }
972
+ // Absolute directory prefixes whose sessions are routed through a
973
+ // subscription-backed proxy (config `proxyPaths`). Stored already-normalized so
974
+ // the per-project match is a cheap compare. Set during preAction. See
975
+ // CodeburnConfig.proxyPaths for the product rationale.
976
+ let userProxyPaths = [];
977
+ /// Normalize a path for prefix comparison: backslashes -> forward slashes
978
+ /// (Windows configs / cwds), strip leading AND trailing slashes, fold case on
979
+ /// case-insensitive filesystems. Leading slashes are stripped because provider
980
+ /// project paths arrive in two forms — Claude keeps the absolute "/Users/x"
981
+ /// while Codex (sanitizeProject) and the unsanitizePath fallback drop the
982
+ /// leading slash to "Users/x". Folding both to a slashless form (mirroring
983
+ /// crossProviderKey) makes matching agnostic to which provider produced the
984
+ /// path, so the same directory is flagged whether or not a Claude session
985
+ /// happens to co-exist there. Case is folded only on macOS/Windows; on Linux
986
+ /// "/home/Me" and "/home/me" are different dirs, so folding would risk
987
+ /// crediting unrelated spend. A path that normalizes to empty (e.g. "/" or "")
988
+ /// is dropped by callers so it can never match everything. Exported so the CLI
989
+ /// dedupes with the same rule.
990
+ export function normalizeProxyPath(p) {
991
+ const s = p.trim().replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+$/, '');
992
+ return (process.platform === 'darwin' || process.platform === 'win32') ? s.toLowerCase() : s;
993
+ }
994
+ export function setProxyPaths(paths) {
995
+ userProxyPaths = (Array.isArray(paths) ? paths : [])
996
+ .filter((p) => typeof p === 'string')
997
+ .map(normalizeProxyPath)
998
+ .filter(p => p !== '');
999
+ }
1000
+ /// True when `cwd` is at or under a configured proxy path. Prefix match is
1001
+ /// anchored to a path-segment boundary so "/a/proj" matches "/a/proj" and
1002
+ /// "/a/proj/sub" but NOT "/a/project-x". Empty/undefined cwd or empty config
1003
+ /// never matches (so a misconfig can't silently zero unrelated spend).
1004
+ export function isProxiedPath(cwd) {
1005
+ if (!cwd || typeof cwd !== 'string')
1006
+ return false;
1007
+ if (userProxyPaths.length === 0)
1008
+ return false;
1009
+ const c = normalizeProxyPath(cwd);
1010
+ if (c === '')
1011
+ return false;
1012
+ return userProxyPaths.some(p => c === p || c.startsWith(p + '/'));
1013
+ }
1014
+ /// Stable hash of the active proxy-path config. Project-level proxy attribution
1015
+ /// is computed live from this set and then cached in the in-memory session
1016
+ /// cache, so the cache key must vary with it — otherwise a long-lived process
1017
+ /// (menubar) that re-reads config could serve attribution from a stale set.
1018
+ export function getProxyPathsConfigHash() {
1019
+ if (userProxyPaths.length === 0)
1020
+ return '';
1021
+ return [...userProxyPaths].sort().join('');
1022
+ }
1023
+ function resolveAlias(model) {
1024
+ if (Object.hasOwn(userAliases, model))
1025
+ return userAliases[model];
1026
+ if (Object.hasOwn(BUILTIN_ALIASES, model))
1027
+ return BUILTIN_ALIASES[model];
1028
+ const lowercase = model.toLowerCase();
1029
+ if (lowercase !== model && Object.hasOwn(BUILTIN_ALIASES, lowercase))
1030
+ return BUILTIN_ALIASES[lowercase];
1031
+ return model;
1032
+ }
1033
+ function getCanonicalName(model) {
1034
+ const cleaned = model
1035
+ .replace(/@.*$/, '')
1036
+ .replace(/-\d{8}$/, '')
1037
+ .replace(/\[[^\]]*\]$/, '');
1038
+ // Full-id aliases (orcarouter/fusion) must stay visible so resolveAlias can
1039
+ // see them. Stripping first would leave a leaf (`fusion`) with no mapping.
1040
+ // Nested wrappers without an alias still peel as before.
1041
+ if (Object.hasOwn(userAliases, cleaned) || Object.hasOwn(BUILTIN_ALIASES, cleaned)) {
1042
+ return cleaned;
1043
+ }
1044
+ const lowercase = cleaned.toLowerCase();
1045
+ if (lowercase !== cleaned && Object.hasOwn(BUILTIN_ALIASES, lowercase)) {
1046
+ return cleaned;
1047
+ }
1048
+ return stripKnownFirstNamespace(cleaned);
1049
+ }
1050
+ /// Alias-resolved identity for report merge. Display names stay cosmetic —
1051
+ /// prefix matches in SHORT_NAMES must not fold distinct SKUs into one row.
1052
+ /// Path-form ids (`accounts/fireworks/models/<slug>`, `cline-pass/<slug>`)
1053
+ /// peel to the leaf so they share a bucket with the bare slug.
1054
+ export function resolveCanonicalModelId(model) {
1055
+ const viaUser = Object.hasOwn(userAliases, model) ? userAliases[model] : model;
1056
+ const aliased = resolveAlias(getCanonicalName(viaUser));
1057
+ if (!aliased.includes('/'))
1058
+ return aliased;
1059
+ const leaf = aliased.slice(aliased.lastIndexOf('/') + 1);
1060
+ if (!leaf)
1061
+ return aliased;
1062
+ return resolveAlias(getCanonicalName(leaf));
1063
+ }
1064
+ // Namespaces the pricing catalog itself uses, plus the ones below. An unknown
1065
+ // `provider/model` must stay unpriced — do not treat `/` as authority. Derived
1066
+ // rather than hand-listed so a vendor LiteLLM already knows (`x-ai/`, `qwen/`,
1067
+ // `nousresearch/`, …) is never dropped by a stale list.
1068
+ const EXTRA_NAMESPACES = [
1069
+ // Routing wrappers (see ROUTER_PREFIXES); no catalog lists them. `cliproxy/`
1070
+ // is codex-cliproxy-gateway's default route prefix over CLIProxyAPI.
1071
+ 'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', 'orcarouter', 'cliproxy',
1072
+ // LiteLLM route prefixes that never appear as a key prefix.
1073
+ 'litellm_proxy', 'openai_like',
1074
+ // Vendor spellings the catalog indexes under another name: `zhipu` is `z-ai`,
1075
+ // `mimo` is `xiaomi` (BUILTIN_ALIASES maps the bare MiMo ids to `xiaomi/`),
1076
+ // and `kimi/` is a client-side prefix (Codex records `kimi/k3[1m]`).
1077
+ // `zcode/` is CLIProxyAPI's provider spelling for the Z.ai coding plans; the
1078
+ // bare `glm-*` leaf already prices via its own catalog row, which carries an explicit zero cache-write cost.
1079
+ 'zhipu', 'mimo', 'kimi', 'zcode',
1080
+ ];
1081
+ // Local runners. Their catalog rows are $0 stubs, so an unlisted local tag must
1082
+ // not strip down to a priced cloud row and invent spend (#968).
1083
+ const LOCAL_NAMESPACES = ['ollama'];
1084
+ let knownNamespaces = null;
1085
+ function getKnownNamespaces() {
1086
+ if (knownNamespaces)
1087
+ return knownNamespaces;
1088
+ const set = new Set(EXTRA_NAMESPACES);
1089
+ for (const keys of [pricingCache.keys(), fallbackCosts.keys()]) {
1090
+ for (const key of keys) {
1091
+ const idx = key.indexOf('/');
1092
+ if (idx > 0)
1093
+ set.add(key.slice(0, idx).toLowerCase());
1094
+ }
1095
+ }
1096
+ for (const local of LOCAL_NAMESPACES)
1097
+ set.delete(local);
1098
+ knownNamespaces = set;
1099
+ return set;
1100
+ }
1101
+ function stripKnownFirstNamespace(model) {
1102
+ const idx = model.indexOf('/');
1103
+ if (idx <= 0)
1104
+ return model;
1105
+ const head = model.slice(0, idx).toLowerCase();
1106
+ if (getKnownNamespaces().has(head))
1107
+ return model.slice(idx + 1);
1108
+ return model;
1109
+ }
1110
+ // Routing wrappers (OmniRoute, Cline Pass, cmd/, …) are not model ids.
1111
+ // Peel them so any plan/gateway spelling of the same model shares one price.
1112
+ // OrcaRouter is a gateway that routes to many vendors. Its catalog exposes
1113
+ // route ids (`orcarouter/auto`, `orcarouter/fusion`, …) and plain vendor ids
1114
+ // (`deepseek/deepseek-v4-pro`); a route id can also spell a nested upstream
1115
+ // (`orcarouter/deepseek/deepseek-v4-pro`), and the completion response's
1116
+ // `model` field reports the upstream id that actually ran. Peeling the prefix
1117
+ // lets every routed spelling price at the upstream row.
1118
+ const ROUTER_PREFIXES = [
1119
+ /^omniroute:/i,
1120
+ /^cp\//i,
1121
+ /^cline-pass\//i,
1122
+ /^cline-free\//i,
1123
+ /^cmd\//i,
1124
+ /^antigravity\//i,
1125
+ /^orcarouter\//i,
1126
+ // codex-cliproxy-gateway keeps Codex's own OAuth routing native and forwards
1127
+ // only `cliproxy/*` ids to CLIProxyAPI, so a routed session records
1128
+ // `cliproxy/<id>` — and `<id>` can itself be a provider path
1129
+ // (`cliproxy/zcode/glm-5.3-flash`). Peeling the wrapper lets the one
1130
+ // known-namespace strip in getCanonicalName reach the priced leaf.
1131
+ /^cliproxy\//i,
1132
+ // `xiaomi/` is NOT peeled: it is the vendor namespace LiteLLM prices under,
1133
+ // and BUILTIN_ALIASES maps the bare MiMo ids INTO it. Peeling would pull the
1134
+ // opposite way. It stays a known namespace via the catalog-derived set.
1135
+ ];
1136
+ function routedModelCandidates(model) {
1137
+ const ids = [];
1138
+ const seen = new Set();
1139
+ const push = (value) => {
1140
+ if (!value || seen.has(value))
1141
+ return;
1142
+ seen.add(value);
1143
+ ids.push(value);
1144
+ };
1145
+ push(model);
1146
+ let current = model;
1147
+ let peeled = true;
1148
+ while (peeled) {
1149
+ peeled = false;
1150
+ for (const prefix of ROUTER_PREFIXES) {
1151
+ const next = current.replace(prefix, '');
1152
+ if (next && next !== current) {
1153
+ current = next;
1154
+ push(current);
1155
+ peeled = true;
1156
+ }
1157
+ }
1158
+ }
1159
+ // One known-vendor strip only (anthropic/foo → foo). Unknown
1160
+ // provider/model trees stay intact and therefore unpriced.
1161
+ push(getCanonicalName(current));
1162
+ return ids;
1163
+ }
1164
+ function stripKnownPricingVariantSuffix(model) {
1165
+ const withoutColonSuffix = model.replace(/:(thinking|cloud)$/i, '');
1166
+ if (withoutColonSuffix !== model)
1167
+ return withoutColonSuffix;
1168
+ const withoutTeeSuffix = model.replace(/-TEE$/i, '');
1169
+ if (withoutTeeSuffix !== model)
1170
+ return withoutTeeSuffix;
1171
+ return null;
1172
+ }
1173
+ const AUTO_REVIEW_LUNA_FROM = Date.parse('2026-07-30T00:00:00Z');
1174
+ // kimi-cli labelled the alias "powered by kimi-k2.5" from 27 Jan 2026 (1.2) and
1175
+ // dropped that on 13 Apr 2026 (#1860) as K2.6 rolled out; Kimi Code's What's
1176
+ // New dates K2.7 Code to 12 Jun 2026. What it served before K2.5 is unsourced,
1177
+ // so those calls keep the K2 Thinking rate they always had.
1178
+ const KIMI_CODING_K2_5_FROM = Date.parse('2026-01-27T00:00:00Z');
1179
+ const KIMI_CODING_K2_6_FROM = Date.parse('2026-04-13T00:00:00Z');
1180
+ const KIMI_CODING_K2_7_FROM = Date.parse('2026-06-12T00:00:00Z');
1181
+ const KIMI_CODING_K2_8_FROM = Date.parse('2026-09-11T00:00:00Z');
1182
+ /// The model a call is priced by. Only `codex-auto-review` and the Kimi Code
1183
+ /// alias depend on the call's date (see BUILTIN_ALIASES); a user alias for
1184
+ /// them still wins, and a missing or unparseable timestamp keeps the forward
1185
+ /// default.
1186
+ export function pricingModelAt(model, timestamp) {
1187
+ const id = model.toLowerCase();
1188
+ if (id !== 'codex-auto-review' && id !== 'kimi-for-coding' && id !== 'kimi-code')
1189
+ return model;
1190
+ if (Object.hasOwn(userAliases, model) || userPriceOverrides.has(model))
1191
+ return model;
1192
+ const at = Date.parse(timestamp ?? '');
1193
+ if (id === 'codex-auto-review')
1194
+ return at < AUTO_REVIEW_LUNA_FROM ? 'gpt-5.4' : model;
1195
+ if (at < KIMI_CODING_K2_5_FROM)
1196
+ return 'kimi-k2-thinking';
1197
+ if (at < KIMI_CODING_K2_6_FROM)
1198
+ return 'kimi-k2.5';
1199
+ return at < KIMI_CODING_K2_7_FROM ? 'kimi-k2.6' : model;
1200
+ }
1201
+ /// True when pricingModelAt stands in for a model with no published rate:
1202
+ /// Kimi Code's alias served K2.8 Preview from 11 Sep 2026, priced as K2.7 Code.
1203
+ /// A missing or unparseable timestamp gets the forward default, so it counts.
1204
+ export function isStandInPricedAt(model, timestamp) {
1205
+ const id = model.toLowerCase();
1206
+ if (id !== 'kimi-for-coding' && id !== 'kimi-code')
1207
+ return false;
1208
+ if (Object.hasOwn(userAliases, model) || userPriceOverrides.has(model))
1209
+ return false;
1210
+ const at = Date.parse(timestamp ?? '');
1211
+ return !(at < KIMI_CODING_K2_8_FROM);
1212
+ }
1213
+ export function getModelCosts(model) {
1214
+ // Try with provider prefix preserved (azure/gpt-5.4, openrouter/anthropic/claude-opus-4.6)
1215
+ const withPrefix = model.replace(/@.*$/, '').replace(/-\d{8}$/, '');
1216
+ const canonicalName = getCanonicalName(model);
1217
+ const canonical = resolveAlias(canonicalName);
1218
+ const override = getPriceOverrideExact(model, withPrefix, canonicalName, canonical);
1219
+ if (override)
1220
+ return override;
1221
+ // An explicit alias for a bare (un-prefixed) model name is authoritative: it
1222
+ // must win over a coincidental stripped reseller key of the same name. LiteLLM
1223
+ // ships `snowflake/claude-4-opus` ($5), which the bundler strips to a bare
1224
+ // `claude-4-opus` key; without this, that would shadow the curated alias
1225
+ // `claude-4-opus -> claude-opus-4` ($15 official Anthropic price).
1226
+ if (canonical !== canonicalName && withPrefix === canonicalName && pricingCache.has(canonical)) {
1227
+ return pricingCache.get(canonical);
1228
+ }
1229
+ if (pricingCache.has(withPrefix))
1230
+ return pricingCache.get(withPrefix);
1231
+ if (pricingCache.has(canonical))
1232
+ return pricingCache.get(canonical);
1233
+ for (const candidate of routedModelCandidates(model)) {
1234
+ const aliased = resolveAlias(candidate);
1235
+ // A user's declared price for the bare id must win over the catalog row a
1236
+ // routed spelling of it would otherwise hit.
1237
+ const candidateOverride = getPriceOverrideExact(candidate, aliased);
1238
+ if (candidateOverride)
1239
+ return candidateOverride;
1240
+ if (pricingCache.has(aliased))
1241
+ return pricingCache.get(aliased);
1242
+ if (pricingCache.has(candidate))
1243
+ return pricingCache.get(candidate);
1244
+ }
1245
+ const prefixOverride = getPriceOverridePrefix(canonical);
1246
+ if (prefixOverride)
1247
+ return prefixOverride;
1248
+ // Iterate keys longest-first so a model id like `gpt-5-mini` matches the
1249
+ // `gpt-5-mini` entry rather than collapsing to the shorter `gpt-5` entry
1250
+ // due to dictionary insertion order.
1251
+ const prefixKey = longestPricingPrefix(canonical, getSortedPricingKeys());
1252
+ if (prefixKey !== null) {
1253
+ const hit = pricingCache.get(prefixKey);
1254
+ // A $0 sibling (`chat` from a free gateway row) must not price an id that
1255
+ // has its own priced fallback row (`chat-bison`). A priced sibling still
1256
+ // wins: fallback rows are resale or carried figures, often staler than it.
1257
+ if (hit.inputCostPerToken === 0 && hit.outputCostPerToken === 0) {
1258
+ const own = fallbackCosts.get(withPrefix.toLowerCase()) ?? fallbackCosts.get(canonical.toLowerCase());
1259
+ if (own)
1260
+ return own;
1261
+ }
1262
+ return hit;
1263
+ }
1264
+ const caseInsensitiveOverride = getPriceOverrideCaseInsensitive(canonical, withPrefix);
1265
+ if (caseInsensitiveOverride)
1266
+ return caseInsensitiveOverride;
1267
+ // Case-insensitive fallback: gap-filled keys from OpenRouter are lowercase
1268
+ // slugs (e.g. `minimax-m3`), but sessions report `MiniMax-M3`. Only consulted
1269
+ // after the exact/canonical/prefix attempts, so it never changes a match that
1270
+ // already resolved above.
1271
+ const lowerIndex = getLowercasePricingIndex();
1272
+ const byCanonical = lowerIndex.get(canonical.toLowerCase());
1273
+ if (byCanonical)
1274
+ return byCanonical;
1275
+ const byPrefix = lowerIndex.get(withPrefix.toLowerCase());
1276
+ if (byPrefix)
1277
+ return byPrefix;
1278
+ const withPrefixVariant = stripKnownPricingVariantSuffix(withPrefix);
1279
+ if (withPrefixVariant && withPrefixVariant !== withPrefix) {
1280
+ const variantCosts = getModelCosts(withPrefixVariant);
1281
+ if (variantCosts)
1282
+ return variantCosts;
1283
+ }
1284
+ const canonicalVariant = stripKnownPricingVariantSuffix(canonical);
1285
+ if (canonicalVariant && canonicalVariant !== canonical && canonicalVariant !== withPrefixVariant) {
1286
+ const variantCosts = getModelCosts(canonicalVariant);
1287
+ if (variantCosts)
1288
+ return variantCosts;
1289
+ }
1290
+ return null;
1291
+ }
1292
+ // Warn at most once per unknown model name per process. Without this, a model
1293
+ // missing from the pricing snapshot would silently price at $0 for every
1294
+ // session that used it, hiding real spend until the user noticed.
1295
+ const warnedUnknownModels = new Set();
1296
+ /// Heuristic for "this looks like a local model that will never be in LiteLLM's
1297
+ /// pricing JSON". We suppress the unknown-model warning for these because the
1298
+ /// "update codeburn" advice can't help — local Ollama models, llama.cpp tags,
1299
+ /// LM Studio loads, etc. are billed locally and don't have public pricing.
1300
+ /// Users still get $0 in cost reports for them (correct — local inference is
1301
+ /// effectively free); the warning was just noise.
1302
+ function looksLikeLocalModel(name) {
1303
+ // Bedrock foundation-model ids end in a `-[v]<major>:<minor>` version
1304
+ // (`anthropic.claude-haiku-4-5-20251001-v1:0`, `openai.gpt-oss-120b-1:0`).
1305
+ // That colon is a version, not an Ollama tag: such a model is metered, and
1306
+ // one with no price must reach the unpriced list rather than be treated as
1307
+ // free local inference.
1308
+ if (/-v?\d+:\d+$/.test(name))
1309
+ return false;
1310
+ // Bedrock provisioned-model / custom-model ARNs carry colons from the ARN
1311
+ // structure (arn:aws:bedrock:<region>:<account>:provisioned-model/<id>), but
1312
+ // they are metered Bedrock, not local: an unpriced one must reach the
1313
+ // unpriced list rather than be hidden as free local inference.
1314
+ if (/^arn:aws:bedrock:/i.test(name))
1315
+ return false;
1316
+ // Ollama and LM Studio tags include `:tag` (e.g. qwen3.6:35b-a3b-bf16).
1317
+ if (name.includes(':') && !name.startsWith('http'))
1318
+ return true;
1319
+ // GGUF / quantized fingerprints commonly seen in local inference.
1320
+ if (/[-_](q[2-8](_[a-z0-9]+)?|bf16|fp16|gguf|f16|f32)$/i.test(name))
1321
+ return true;
1322
+ return false;
1323
+ }
1324
+ function hasBillableRate(costs) {
1325
+ return costs.inputCostPerToken > 0
1326
+ || costs.outputCostPerToken > 0
1327
+ || costs.cacheWriteCostPerToken > 0
1328
+ || costs.cacheReadCostPerToken > 0;
1329
+ }
1330
+ // Exact-override lookup with the same key derivation getModelCosts uses. Lets
1331
+ // the unpriced detector distinguish "explicitly declared free by the user" (a
1332
+ // zero-rate override) from a zero-rate LiteLLM stub, which means "listed but
1333
+ // unknown price" and must still be flagged. Only the EXACT override form is
1334
+ // consulted: getModelCosts checks it before any table hit, so when one exists
1335
+ // it is provably what priced the model. Prefix and case-insensitive overrides
1336
+ // resolve AFTER table hits and so cannot prove the $0 was intentional; a
1337
+ // zero-rate stub shadowed by one still gets flagged (the honest direction).
1338
+ function exactPriceOverrideFor(model) {
1339
+ const withPrefix = model.replace(/@.*$/, '').replace(/-\d{8}$/, '');
1340
+ const canonicalName = getCanonicalName(model);
1341
+ const canonical = resolveAlias(canonicalName);
1342
+ return getPriceOverrideExact(model, withPrefix, canonicalName, canonical);
1343
+ }
1344
+ // Render-time unpriced detection (#638): flag aggregated model rows that carry
1345
+ // usage but $0 cost AND whose pricing lookup yields no billable rate right
1346
+ // now. Cost is computed at parse time and cached, so a parse-time registry
1347
+ // would miss cached sessions; a render-time check covers both and heals the
1348
+ // moment pricing data, an alias, or a price override arrives.
1349
+ //
1350
+ // Rows with cost > 0 are never flagged: aggregation keys rows by DISPLAY name
1351
+ // (parser.ts keys modelBreakdown via getShortModelName), which the pricing
1352
+ // lookup misses, so a priced model like "Opus 4.8" would otherwise false-flag.
1353
+ // $0 display-name rows ARE flagged even when the raw id would price today:
1354
+ // those tokens really did enter the report at $0 (a provider priced a
1355
+ // transformed name, or the session was cached before its model's pricing
1356
+ // landed). Conservative by design: a display key merging priced and unpriced
1357
+ // raw ids carries cost > 0 and is not flagged. Local-looking models and
1358
+ // models with a local-savings mapping are excluded because $0 is their
1359
+ // correct cost, as are zero-rate USER overrides (explicitly declared free).
1360
+ /// Models whose $0 cost is CORRECT rather than a pricing gap, mirroring the
1361
+ /// exclusions findUnpricedModels applies: local-looking models, models mapped
1362
+ /// to a local-savings baseline, subscription / flat-rate product SKUs, and
1363
+ /// models an exact zero-rate user override declares free. Used to keep their
1364
+ /// calls out of the pricing-coverage denominator — otherwise a 95%-ollama
1365
+ /// user reads high coverage while every genuinely cost-bearing call is unpriced.
1366
+ export function isExpectedFreeModel(model) {
1367
+ if (looksLikeLocalModel(model))
1368
+ return true;
1369
+ if (getLocalSavingsBaseline(model))
1370
+ return true;
1371
+ const costs = getModelCosts(model);
1372
+ // A builtin/user alias can still attach a billable rate to a subscription
1373
+ // SKU (warp-auto-* today). Those calls are priced, so they stay in the
1374
+ // coverage denominator. Only the $0 / no-rate case is expected-free.
1375
+ if (isFlatRateModel(model) && (!costs || !hasBillableRate(costs)))
1376
+ return true;
1377
+ if (costs && !hasBillableRate(costs) && exactPriceOverrideFor(model))
1378
+ return true;
1379
+ return false;
1380
+ }
1381
+ /// The cost a tool recorded for a call CodeBurn prices at $0, unless $0 is the
1382
+ /// declared price (local, local-savings, flat-rate, zero-rate override).
1383
+ export function recordedCostFallback(model, costUSD, recorded) {
1384
+ return costUSD === 0 && typeof recorded === 'number' && recorded > 0 && !isExpectedFreeModel(model) ? recorded : undefined;
1385
+ }
1386
+ export function findUnpricedModels(rows) {
1387
+ const out = [];
1388
+ for (const row of rows) {
1389
+ const { model } = row;
1390
+ const tokens = row.tokens ?? 0;
1391
+ if (!model || model === '<synthetic>')
1392
+ continue;
1393
+ if (row.calls <= 0 && tokens <= 0)
1394
+ continue;
1395
+ if (row.cost > 0)
1396
+ continue;
1397
+ if (looksLikeLocalModel(model))
1398
+ continue;
1399
+ if (getLocalSavingsBaseline(model))
1400
+ continue;
1401
+ if (isFlatRateModel(model))
1402
+ continue;
1403
+ const costs = getModelCosts(model);
1404
+ if (costs && hasBillableRate(costs))
1405
+ continue;
1406
+ if (costs && exactPriceOverrideFor(model))
1407
+ continue;
1408
+ out.push({ model, calls: row.calls, tokens });
1409
+ }
1410
+ return out.sort((a, b) => (b.tokens - a.tokens) || (b.calls - a.calls)
1411
+ || (a.model < b.model ? -1 : a.model > b.model ? 1 : 0));
1412
+ }
1413
+ function shouldWarnAboutUnknownModel(name) {
1414
+ if (!name || name === '<synthetic>')
1415
+ return false;
1416
+ if (warnedUnknownModels.has(name))
1417
+ return false;
1418
+ // Suppress for local/quantized models — the "update codeburn" hint is
1419
+ // actively misleading there. Users who need cost visibility for local
1420
+ // inference can still set an alias via `codeburn model-alias`.
1421
+ if (looksLikeLocalModel(name))
1422
+ return false;
1423
+ if (isFlatRateModel(name))
1424
+ return false;
1425
+ // The warning fired on every CLI invocation (including the default
1426
+ // dashboard) which made first launches look broken — three "no pricing
1427
+ // data" lines greet a user before the dashboard even draws. Now opt-in
1428
+ // via --verbose. The unknown model still costs $0 in reports; users who
1429
+ // suspect missing models run `codeburn --verbose` to see the list.
1430
+ if (process.env['CODEBURN_VERBOSE'] !== '1')
1431
+ return false;
1432
+ return true;
1433
+ }
1434
+ /** Render provider-supplied model IDs without terminal control characters. */
1435
+ export function sanitizeModelForDisplay(model) {
1436
+ return model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200);
1437
+ }
1438
+ /// The fabricated 1.25x-input write rate only holds for Anthropic models. Any
1439
+ /// other model without a published write rate bills those tokens as plain
1440
+ /// input, the same rule codex.ts applies when it routes them.
1441
+ export function cacheWriteCostPerToken(model, costs) {
1442
+ if (costs.cacheWriteCostIsExplicit || /claude|anthropic/i.test(model))
1443
+ return costs.cacheWriteCostPerToken;
1444
+ return costs.inputCostPerToken;
1445
+ }
1446
+ export function calculateCost(model, inputTokens, outputTokens, cacheCreationTokens, cacheReadTokens, webSearchRequests, speed = 'standard', oneHourCacheCreationTokens = 0, provider, applyDiscount = false,
1447
+ // A slice of a call (one token class) is priced at the whole call's tier.
1448
+ tierPromptTokens) {
1449
+ const costs = getModelCosts(model);
1450
+ if (!costs) {
1451
+ if (shouldWarnAboutUnknownModel(model)) {
1452
+ warnedUnknownModels.add(model);
1453
+ // Strip control characters and cap length: model names come from JSONL
1454
+ // payloads written by external tools, so a hostile or corrupt file
1455
+ // could embed terminal escape sequences here.
1456
+ const safeName = sanitizeModelForDisplay(model);
1457
+ process.stderr.write(`codeburn: no pricing data for model "${safeName}" — costs for this model will show $0. ` +
1458
+ `${unpricedModelHint(safeName)} Or track local-model savings with: codeburn model-savings "${safeName}" <baseline-model>, or update with: npx codeburn@latest.\n`);
1459
+ }
1460
+ return 0;
1461
+ }
1462
+ const safe = (n) => (Number.isFinite(n) && n > 0 ? n : 0);
1463
+ const safeOneHourCacheCreation = safe(oneHourCacheCreationTokens);
1464
+ const safeCacheCreation = Math.max(safe(cacheCreationTokens), safeOneHourCacheCreation);
1465
+ const safeFiveMinuteCacheCreation = Math.max(0, safeCacheCreation - safeOneHourCacheCreation);
1466
+ const promptTokens = tierPromptTokens ?? safe(inputTokens) + safe(cacheReadTokens) + safeCacheCreation;
1467
+ const tieredCosts = tieredCostsFor(model, speed === 'flex' ? costs.flex ?? costs : costs, promptTokens, provider);
1468
+ const multiplier = speed === 'fast' ? tieredCosts.fastMultiplier : speed === 'ultrafast' ? tieredCosts.ultrafastMultiplier ?? 1 : 1;
1469
+ // Clamp negative inputs to 0. A corrupt JSONL that emits a negative token
1470
+ // count would otherwise produce a negative cost that silently subtracts
1471
+ // from real spend in aggregate totals. NaN is also handled here; the
1472
+ // arithmetic below short-circuits to 0 when any operand is non-finite.
1473
+ const cacheWriteRate = cacheWriteCostPerToken(model, tieredCosts);
1474
+ const d = applyDiscount && hasPriceDiscounts() ? discountFactors(model, provider) : NO_DISCOUNT;
1475
+ return multiplier * (safe(inputTokens) * tieredCosts.inputCostPerToken * d.input +
1476
+ safe(outputTokens) * tieredCosts.outputCostPerToken * d.output +
1477
+ safeFiveMinuteCacheCreation * cacheWriteRate * d.cacheWrite +
1478
+ safeOneHourCacheCreation * cacheWriteRate * ONE_HOUR_CACHE_WRITE_MULTIPLIER_FROM_FIVE_MINUTE_RATE * d.cacheWrite +
1479
+ safe(cacheReadTokens) * tieredCosts.cacheReadCostPerToken * d.cacheRead +
1480
+ safe(webSearchRequests) * tieredCosts.webSearchCostPerRequest * d.other);
1481
+ }
1482
+ export function ownValue(map, key) {
1483
+ return Object.hasOwn(map, key) ? map[key] : undefined;
1484
+ }
1485
+ const autoModelNames = {
1486
+ 'glm-5.2': 'GLM-5.2',
1487
+ 'GLM-5.2': 'GLM-5.2',
1488
+ 'glm-5.3': 'GLM-5.3',
1489
+ 'GLM-5.3': 'GLM-5.3',
1490
+ 'cursor-auto': 'Cursor (auto)',
1491
+ 'cursor-agent-auto': 'Cursor (auto)',
1492
+ 'copilot-auto': 'Copilot (auto)',
1493
+ 'copilot-openai-auto': 'Copilot (OpenAI)',
1494
+ 'copilot-anthropic-auto': 'Copilot (Anthropic)',
1495
+ 'ibm-bob-auto': 'IBM Bob (auto)',
1496
+ 'kiro-auto': 'Kiro (auto)',
1497
+ 'quickdesk-auto': 'Quick Desktop (auto)',
1498
+ 'grokbot-auto': 'Grok Bot (auto)',
1499
+ 'grok-bot-automation': 'Grok Bot (automation)',
1500
+ 'grok-bot-cua': 'Grok Bot (computer use)',
1501
+ 'grok-bot-default': 'Grok Bot (default)',
1502
+ 'grok-4.6-high': 'Grok 4.6 (high)',
1503
+ 'grok-4.6-high-fast': 'Grok 4.6 (high, fast)',
1504
+ 'cline-auto': 'Cline (auto)',
1505
+ 'openclaw-auto': 'OpenClaw (auto)',
1506
+ 'qwen-auto': 'Qwen (auto)',
1507
+ 'kimi-auto': 'Kimi (auto)',
1508
+ 'kimi-for-coding': 'Kimi for Coding',
1509
+ 'kimi-for-coding-highspeed': 'Kimi for Coding HighSpeed',
1510
+ 'codex-auto-review': 'Codex Auto Review',
1511
+ 'gpt-reserve': 'Luna Reserve',
1512
+ };
1513
+ const SHORT_NAMES = {
1514
+ // Modern claude-<family>-<major>-<minor> ids are derived in deriveClaudeShortName.
1515
+ // Only the legacy 3.x ids (family-last) need explicit mapping.
1516
+ 'claude-3-7-sonnet': 'Sonnet 3.7',
1517
+ 'claude-3-5-sonnet': 'Sonnet 3.5',
1518
+ 'claude-3-5-haiku': 'Haiku 3.5',
1519
+ 'gpt-4o-mini': 'GPT-4o Mini',
1520
+ 'gpt-4o': 'GPT-4o',
1521
+ 'gpt-4.1-nano': 'GPT-4.1 Nano',
1522
+ 'gpt-4.1-mini': 'GPT-4.1 Mini',
1523
+ 'gpt-4.1': 'GPT-4.1',
1524
+ 'codex-auto-review': 'Codex Auto Review',
1525
+ 'gpt-5.5-pro': 'GPT-5.5 Pro',
1526
+ 'gpt-5.5': 'GPT-5.5',
1527
+ 'gpt-5.4-pro': 'GPT-5.4 Pro',
1528
+ 'gpt-5.4-nano': 'GPT-5.4 Nano',
1529
+ 'gpt-5.4-mini': 'GPT-5.4 Mini',
1530
+ 'gpt-5.4': 'GPT-5.4',
1531
+ 'gpt-5.3-codex-spark': 'GPT-5.3 Codex Spark',
1532
+ 'gpt-5.3-codex': 'GPT-5.3 Codex',
1533
+ 'gpt-5.3': 'GPT-5.3',
1534
+ 'gpt-5.2-pro': 'GPT-5.2 Pro',
1535
+ 'gpt-5.2-low': 'GPT-5.2 Low',
1536
+ 'gpt-5.2': 'GPT-5.2',
1537
+ 'gpt-5.1-codex-mini': 'GPT-5.1 Codex Mini',
1538
+ 'gpt-5.1-codex': 'GPT-5.1 Codex',
1539
+ 'gpt-5.1': 'GPT-5.1',
1540
+ 'gpt-5-pro': 'GPT-5 Pro',
1541
+ 'gpt-5-nano': 'GPT-5 Nano',
1542
+ 'gpt-5-mini': 'GPT-5 Mini',
1543
+ 'gpt-5': 'GPT-5',
1544
+ 'gemini-3.8-flash': 'Gemini 3.8 Flash',
1545
+ 'gemini-3.5-flash': 'Gemini 3.5 Flash',
1546
+ 'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',
1547
+ 'gemini-3-flash-preview': 'Gemini 3 Flash',
1548
+ 'gemini-2.5-pro': 'Gemini 2.5 Pro',
1549
+ 'gemini-2.5-flash': 'Gemini 2.5 Flash',
1550
+ 'kimi-k2-thinking-turbo': 'Kimi K2 Thinking Turbo',
1551
+ 'kimi-k2-thinking': 'Kimi K2 Thinking',
1552
+ 'kimi-k3': 'Kimi K3',
1553
+ 'kimi-k2p6': 'Kimi K2.6',
1554
+ 'kimi-thinking-preview': 'Kimi Thinking',
1555
+ 'kimi-k2.6': 'Kimi K2.6',
1556
+ 'kimi-k2.5': 'Kimi K2.5',
1557
+ 'kimi-k2p5': 'Kimi K2.5',
1558
+ 'kimi-k2-instruct': 'Kimi K2 Instruct',
1559
+ 'kimi-k2-0905': 'Kimi K2',
1560
+ 'kimi-k2': 'Kimi K2',
1561
+ 'kimi-latest': 'Kimi Latest',
1562
+ 'moonshot-v1': 'Moonshot v1',
1563
+ 'deepseek-v4-pro': 'DeepSeek v4 Pro',
1564
+ 'deepseek-v4-flash': 'DeepSeek v4 Flash',
1565
+ 'deepseek-coder-max': 'DeepSeek Coder Max',
1566
+ 'deepseek-coder': 'DeepSeek Coder',
1567
+ 'deepseek-r1': 'DeepSeek R1',
1568
+ 'o4-mini': 'o4-mini',
1569
+ 'o3': 'o3',
1570
+ 'MiniMax-M2.7-highspeed': 'MiniMax M2.7 Highspeed',
1571
+ 'MiniMax-M2.7': 'MiniMax M2.7',
1572
+ // Grok (xAI) and GLM ids that otherwise surface raw or as a pricing key in
1573
+ // reports. grok-build and GLM-5.2 price via sibling aliases, so
1574
+ // getShortModelName resolves to the pricing key before this lookup; map each
1575
+ // back to the real model name. grok-composer has no alias, it just lacked an
1576
+ // entry.
1577
+ 'glm-5p1': 'GLM-5.2', // ZCode/Hermes run GLM-5.2 (priced as the GLM-5.1 sibling)
1578
+ 'grok-build-0.1': 'Grok Build', // Grok Build prices through the 0.1 sibling
1579
+ 'grok-composer-2.5-fast': 'Grok Composer 2.5 Fast',
1580
+ // Fireworks-hosted fleet models arrive as `accounts/fireworks/models/<slug>`;
1581
+ // getShortModelName's path fallback strips to the bare slug and re-resolves it
1582
+ // through this table. Display-only — getModelCosts prices off the full path,
1583
+ // so these entries do not move any dollar amounts. (deepseek-v4-pro/-flash
1584
+ // already have entries above and resolve the same way.)
1585
+ 'glm-5p2': 'GLM-5.2',
1586
+ 'qwen3p7-plus': 'Qwen 3.7 Plus',
1587
+ 'kimi-k2p7-code': 'Kimi K2.7 Code',
1588
+ // Ids that price correctly but had no display entry, so reports showed the
1589
+ // raw slug. All display-only. The GPT-5.6 variants are listed individually
1590
+ // rather than as a bare `gpt-5.6`: a base entry would swallow every future
1591
+ // `gpt-5.6-*` via the prefix match and hide the variant, which is exactly
1592
+ // what getShortModelName's version-boundary rule is there to prevent.
1593
+ 'gpt-5.6-sol': 'GPT-5.6 Sol',
1594
+ 'gpt-5.6-terra': 'GPT-5.6 Terra',
1595
+ 'gpt-5.6-luna': 'GPT-5.6 Luna',
1596
+ // The Grok Build harness reports the model it runs (`grok-4.5`), so this is
1597
+ // the model's own name; `grok-build*` ids still resolve to "Grok Build".
1598
+ 'grok-4.5': 'Grok 4.5',
1599
+ // The harness also reports a `-build` variant of that model. It is a distinct
1600
+ // id and reports bucket by id, so without its own entry the prefix match gave
1601
+ // it the same name as `grok-4.5` and the report showed two identical rows.
1602
+ 'grok-4.5-build': 'Grok 4.5 (build)',
1603
+ // ClinePass routes models as `cline-pass/<slug>`; getShortModelName's path
1604
+ // fallback strips the prefix and re-resolves the bare slug through this
1605
+ // table, the same way it handles `accounts/fireworks/models/<slug>`.
1606
+ 'qwen3.7-max': 'Qwen 3.7 Max',
1607
+ 'mimo-v2.5-pro': 'MiMo v2.5 Pro',
1608
+ 'mimo-v2.5': 'MiMo v2.5',
1609
+ 'mimo-v2-flash': 'MiMo v2 Flash',
1610
+ // Both spellings occur in the wild: OpenRouter gap-filled keys are lowercase
1611
+ // slugs while sessions report the capitalized name (see the case-insensitive
1612
+ // pricing index above). SHORT_NAMES matching is case-sensitive, so map both.
1613
+ 'minimax-m3': 'MiniMax M3',
1614
+ 'MiniMax-M3': 'MiniMax M3',
1615
+ };
1616
+ // Sorted longest-first so more-specific prefixes match before shorter ones.
1617
+ // Without this, `gpt-5-mini` could resolve to "GPT-5" (the entry for `gpt-5`)
1618
+ // if it happened to be iterated before `gpt-5-mini`, hiding a distinct model
1619
+ // behind the wrong display name and pricing tier.
1620
+ const SORTED_SHORT_NAMES = Object.entries(SHORT_NAMES)
1621
+ .sort((a, b) => b[0].length - a[0].length);
1622
+ // Anthropic's id scheme is `claude-<family>-<major>[-<minor>]`, so every new
1623
+ // version is derivable — no hand-maintained entry per release. (Legacy 3.x ids
1624
+ // put the family last, e.g. `claude-3-5-sonnet`, and stay in SHORT_NAMES.)
1625
+ // Some doors write the minor with a dot instead of a dash (GitHub Copilot's
1626
+ // session store: `claude-opus-4.8`), so both spellings derive the same name
1627
+ // (#1530); the dotted aliases in BUILTIN_ALIASES below predate this and stay
1628
+ // only because pricing also resolves through them.
1629
+ const CLAUDE_FAMILY = {
1630
+ opus: 'Opus',
1631
+ sonnet: 'Sonnet',
1632
+ haiku: 'Haiku',
1633
+ fable: 'Fable',
1634
+ mythos: 'Mythos',
1635
+ };
1636
+ function deriveClaudeShortName(canonical) {
1637
+ const m = canonical.match(/^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:[-.](\d+))?/);
1638
+ if (!m)
1639
+ return undefined;
1640
+ const [, family, major, minor] = m;
1641
+ return `${CLAUDE_FAMILY[family]} ${major}${minor ? `.${minor}` : ''}`;
1642
+ }
1643
+ // OpenAI's id scheme is `gpt-<version>[-<variant>]` with a numeric version and
1644
+ // lowercase variant segments, so it derives the same way Anthropic's does — a
1645
+ // new release needs no hand-maintained entry (#1530). Consulted only after
1646
+ // SHORT_NAMES misses, so curated labels (GPT-5 Pro, GPT-5.1 Codex Mini, the
1647
+ // individually listed GPT-5.6 variants) keep winning. Guarded to the modern
1648
+ // dotted-version scheme (`gpt-5.7-terra`): bare-major ids are the legacy
1649
+ // date-packaged shape (`gpt-4-1106-preview`) and stay raw, and purely numeric
1650
+ // segments (1106, 0125, 20261105) are packaging, not the model's name.
1651
+ const GPT_DERIVED_ID = /^gpt-(\d+\.\d+(?:\.\d+)*)(?:-([a-z0-9][a-z0-9-]*))?$/;
1652
+ function deriveGptShortName(id) {
1653
+ const m = id.match(GPT_DERIVED_ID);
1654
+ if (!m)
1655
+ return undefined;
1656
+ const [, version, variant] = m;
1657
+ const segments = (variant ?? '')
1658
+ .split('-')
1659
+ .filter(seg => seg !== '' && !/^\d+$/.test(seg))
1660
+ .map(seg => seg.charAt(0).toUpperCase() + seg.slice(1));
1661
+ return ['GPT-' + version, ...segments].join(' ');
1662
+ }
1663
+ function lookupShortName(id) {
1664
+ const claude = deriveClaudeShortName(id);
1665
+ if (claude)
1666
+ return claude;
1667
+ for (const [key, name] of SORTED_SHORT_NAMES) {
1668
+ if (id === key || id.startsWith(key + '-'))
1669
+ return name;
1670
+ }
1671
+ return deriveGptShortName(id);
1672
+ }
1673
+ /// Segment-boundary key match for provider display tables: `key` must be the
1674
+ /// whole id or a whole dash-segment of it, never mid-number or mid-version —
1675
+ /// so `gpt-5` cannot capture `gpt-5.5` or `gpt-5.6-luna`, exactly as the
1676
+ /// global table's `id === key || id.startsWith(key + '-')` cannot (#1530).
1677
+ /// Providers match their local tables with this so one model id resolves to
1678
+ /// one display name on every provider. A one- or two-digit dash segment is a
1679
+ /// minor version (`claude-sonnet-4-6`), not a suffix; dates are longer.
1680
+ export function modelKeyMatches(model, key) {
1681
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1682
+ return new RegExp(`(?<![\\w.-])${escaped}(?=$|-(?!\\d{1,2}(?:$|[-.])))`).test(model);
1683
+ }
1684
+ // Reports re-derive the display name of every cached call; the answer depends
1685
+ // only on the aliases and the pricing namespaces, which clear it when they change.
1686
+ const shortNameMemo = new Map();
1687
+ const SHORT_NAME_MEMO_MAX = 10_000;
1688
+ // Public API stays unary so Array.map/forEach cannot feed index as cycle state.
1689
+ export function getShortModelName(model) {
1690
+ let name = shortNameMemo.get(model);
1691
+ if (name === undefined) {
1692
+ name = shortModelName(model, new Set());
1693
+ if (shortNameMemo.size >= SHORT_NAME_MEMO_MAX)
1694
+ shortNameMemo.clear();
1695
+ shortNameMemo.set(model, name);
1696
+ }
1697
+ return name;
1698
+ }
1699
+ // Doors other than the vendor's own API. The direct door has no entry: the
1700
+ // unsuffixed row IS the direct row. Subscription doors (a ChatGPT plan, a
1701
+ // Claude Max plan) are not routes either — they do not change which row a
1702
+ // model lands on. Only doors with real sessions on disk are listed, the same
1703
+ // rule the id shapes follow.
1704
+ const ROUTES = [
1705
+ { id: 'bedrock', label: 'Bedrock', billing: 'metered', providerFields: ['bedrock', 'amazon-bedrock'] },
1706
+ { id: 'openrouter', label: 'OpenRouter', billing: 'metered', providerFields: ['openrouter'] },
1707
+ { id: 'vertex', label: 'Vertex', billing: 'metered', providerFields: ['google-vertex', 'google-vertex-anthropic'] },
1708
+ ];
1709
+ const ROUTES_BY_ID = new Map(ROUTES.map(route => [route.id, route]));
1710
+ const ROUTES_BY_FIELD = new Map(ROUTES.flatMap(route => route.providerFields.map(field => [field, route])));
1711
+ // Bedrock foundation-model ids: `<vendor>.<model>[-v<major>:<minor>]`, with an
1712
+ // optional cross-region inference-profile prefix (`us.`, `eu.`, `global.`).
1713
+ // Only the two vendors with coding transcripts on disk are recognised; a
1714
+ // dotted id from any other first segment (`gpt-4.1-mini`, `glm-4.7`,
1715
+ // `deepseek.v3.2`) is left alone. The version suffix is the one #1463 exempts
1716
+ // from the local-tag rule.
1717
+ const BEDROCK_ID = /^(?:(us|eu|apac|global|jp|au|us-gov)\.)?(anthropic|openai)\.([a-z0-9][a-z0-9.-]*?)(?:-v\d+:\d+)?$/i;
1718
+ /// The billing door a model id names, or undefined for a plain vendor id.
1719
+ /// Pure: no catalog lookup, safe on the parse path.
1720
+ export function getModelRoute(model) {
1721
+ const bedrock = BEDROCK_ID.exec(model);
1722
+ if (bedrock) {
1723
+ const variant = bedrock[1]?.toLowerCase();
1724
+ return { ...ROUTES_BY_ID.get('bedrock'), baseModel: bedrock[3], ...(variant ? { variant } : {}) };
1725
+ }
1726
+ return undefined;
1727
+ }
1728
+ /// The route a provider's endpoint field names (`billing_provider` in Hermes,
1729
+ /// `providerID` in OpenCode), or undefined when the value is the direct door or
1730
+ /// unknown. Direct doors (`anthropic`, `openai`, `google`, …) deliberately
1731
+ /// have no route: the unsuffixed row IS the direct row.
1732
+ export function routeFromProviderField(value) {
1733
+ if (!value)
1734
+ return undefined;
1735
+ const normalized = value.trim().toLowerCase();
1736
+ // Only the literal values exist in usage-bearing OpenCode/OpenRouter sessions.
1737
+ // Keep Hermes' shipped `bedrock` case/whitespace normalization, but do not
1738
+ // invent aliases for the provider spellings OpenCode records.
1739
+ if (normalized !== 'bedrock' && value !== normalized)
1740
+ return undefined;
1741
+ return ROUTES_BY_FIELD.get(normalized);
1742
+ }
1743
+ /// Route by stable id, for consumers that persisted the id (cached calls).
1744
+ export function getRouteById(id) {
1745
+ return id ? ROUTES_BY_ID.get(id) : undefined;
1746
+ }
1747
+ /// Every registered route id, for a CLI that validates a `--route` value
1748
+ /// before it parses anything.
1749
+ export function registeredRouteIds() {
1750
+ return ROUTES.map(route => route.id);
1751
+ }
1752
+ /// The door a call actually went through: the route the provider recorded
1753
+ /// when it recorded one, else the one the model id names, else null for the
1754
+ /// direct door. Null also covers a persisted id no route registers, so an
1755
+ /// unrecognised value degrades to direct rather than to a phantom door.
1756
+ export function effectiveRouteId(model, route) {
1757
+ return getRouteById(route)?.id ?? getModelRoute(model)?.id ?? null;
1758
+ }
1759
+ /// A billing mode from a persisted or user-supplied value, or undefined when
1760
+ /// it is neither mode. The single gate every validator and conversion uses,
1761
+ /// so `metered|subscription` cannot drift between the CLI, the cache and the
1762
+ /// providers.
1763
+ export function parseBillingMode(value) {
1764
+ return value === 'metered' || value === 'subscription' ? value : undefined;
1765
+ }
1766
+ /// Who billed a call, from the call's own evidence. A mode the provider
1767
+ /// observed (Hermes' resolved cost basis: `included` is subscription-covered,
1768
+ /// `actual` is a recorded invoice amount) is a fact and wins outright. Only
1769
+ /// when the call states no fact does an effective registered route supply its
1770
+ /// default. A direct call whose cost is estimated or calculated stays
1771
+ /// unknown: an estimate says nothing about which account was charged.
1772
+ export function callBillingMode(call) {
1773
+ const observed = parseBillingMode(call.billing);
1774
+ if (observed)
1775
+ return observed;
1776
+ const route = effectiveRouteId(call.model, call.route);
1777
+ return route ? ROUTES_BY_ID.get(route).billing : undefined;
1778
+ }
1779
+ /// The parenthetical a routed row carries after its short name — "(Bedrock)",
1780
+ /// "(Bedrock us)" — or an empty string for the direct door.
1781
+ /// `route` is the call's persisted route id when the provider supplied one;
1782
+ /// otherwise the id shape decides. Exported so a provider-first label
1783
+ /// (models-report) can append exactly what modelRowKey appends.
1784
+ export function routeSuffix(model, route) {
1785
+ const shaped = getModelRoute(model);
1786
+ const resolved = getRouteById(route) ?? shaped;
1787
+ if (!resolved)
1788
+ return '';
1789
+ const variant = shaped?.variant;
1790
+ return `(${resolved.label}${variant ? ` ${variant}` : ''})`;
1791
+ }
1792
+ /// The key every report keys a model row on. One SKU through one door is one
1793
+ /// row: `"Haiku 4.5"` for the direct call, `"Haiku 4.5 (Bedrock)"` for the
1794
+ /// single-region Bedrock id, `"Haiku 4.5 (Bedrock us)"` for the cross-region
1795
+ /// profile that prices above it. Without a route this is exactly
1796
+ /// `getShortModelName`, so ids that name no door keep their existing rows.
1797
+ /// Idempotent: a key fed back in (an adopted pre-v33 daily row) returns itself.
1798
+ export function modelRowKey(model, route) {
1799
+ // A user alias on the full id is a deliberate remap and wins over any door.
1800
+ if (Object.hasOwn(userAliases, model))
1801
+ return getShortModelName(model);
1802
+ const suffix = routeSuffix(model, route);
1803
+ if (!suffix)
1804
+ return getShortModelName(model);
1805
+ const name = getShortModelName(getModelRoute(model)?.baseModel ?? model);
1806
+ return `${name} ${suffix}`;
1807
+ }
1808
+ /// Provider-first display name. Local labels win (Cursor estimated suffixes,
1809
+ /// provider tables that intentionally override the global map). If the provider
1810
+ /// echoed the raw id, it missed — fall back to the global resolver instead of
1811
+ /// showing `gpt-5.6-sol` / `accounts/fireworks/models/kimi-k2p6`.
1812
+ export function fallbackRawModelDisplayName(localLabel, rawModel) {
1813
+ return localLabel === rawModel ? getShortModelName(rawModel) : localLabel;
1814
+ }
1815
+ function shortModelName(model, seen) {
1816
+ const auto = ownValue(autoModelNames, model);
1817
+ if (auto)
1818
+ return auto;
1819
+ if (seen.has(model)) {
1820
+ const leaf = model.includes('/') ? model.slice(model.lastIndexOf('/') + 1) : model;
1821
+ return lookupShortName(leaf) ?? leaf;
1822
+ }
1823
+ seen.add(model);
1824
+ // User aliases win over built-in display names. A remap of gpt-4o must
1825
+ // show the target, not "GPT-4o".
1826
+ if (Object.hasOwn(userAliases, model)) {
1827
+ return shortModelName(userAliases[model], seen);
1828
+ }
1829
+ const stripped = getCanonicalName(model);
1830
+ // Before aliasing: `glm-5.3` prices via the `glm-5p2` sibling, so resolving
1831
+ // first would label a namespaced GLM-5.3 as "GLM-5.2".
1832
+ const autoStripped = ownValue(autoModelNames, stripped);
1833
+ if (autoStripped)
1834
+ return autoStripped;
1835
+ if (stripped !== model) {
1836
+ if (Object.hasOwn(userAliases, stripped)) {
1837
+ return shortModelName(userAliases[stripped], seen);
1838
+ }
1839
+ const knownStripped = lookupShortName(stripped);
1840
+ if (knownStripped && !Object.hasOwn(BUILTIN_ALIASES, stripped) && !Object.hasOwn(BUILTIN_ALIASES, stripped.toLowerCase())) {
1841
+ return knownStripped;
1842
+ }
1843
+ }
1844
+ const canonical = resolveAlias(stripped);
1845
+ const known = lookupShortName(canonical);
1846
+ if (known)
1847
+ return known;
1848
+ if (canonical.includes('/')) {
1849
+ const segment = canonical.slice(canonical.lastIndexOf('/') + 1);
1850
+ if (!segment || seen.has(segment) || segment === stripped) {
1851
+ return lookupShortName(segment) ?? segment;
1852
+ }
1853
+ return shortModelName(segment, seen);
1854
+ }
1855
+ return lookupShortName(canonical) ?? canonical;
1856
+ }
1857
+ export function snapshotPricingState() {
1858
+ return {
1859
+ pricing: pricingCache,
1860
+ aliases: userAliases,
1861
+ priceOverrides: userPriceOverridesConfig,
1862
+ localModelSavings: userLocalModelSavings,
1863
+ flatRateModels: getFlatRateModels(),
1864
+ flatRateModelsRemoved: getFlatRateRemoved(),
1865
+ discounts: userDiscounts,
1866
+ };
1867
+ }
1868
+ export function restorePricingState(snapshot) {
1869
+ pricingCache = snapshot.pricing;
1870
+ sortedPricingKeys = null;
1871
+ lowercasePricingIndex = null;
1872
+ knownNamespaces = null;
1873
+ setModelAliases(snapshot.aliases);
1874
+ setPriceOverrides(snapshot.priceOverrides);
1875
+ setLocalModelSavings(snapshot.localModelSavings);
1876
+ setFlatRateModels(snapshot.flatRateModels ?? []);
1877
+ setFlatRateRemoved(snapshot.flatRateModelsRemoved ?? []);
1878
+ setPriceDiscounts(snapshot.discounts ?? {});
1879
+ }