mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
* 0.9.25: correctness + provider fixes, energy guard, logo, default DMG CLI/engine fixes: local-model savings count reasoning; ZCode reasoning billed; codex-credits version-boundary tiering; GLM alias repointed to z.ai discounted rate; openclaw/pi/qwen timestamp mtime fallback; hermes delta timestamp; sqlite/warp/hermes busy+permission reclassified as failed (no sealed empty); codex-cache dev+ino; cursor-cache WAL; antigravity server TTL; quota timeout+ grokbot footer+claude near-expiry; serve RSS guard env+hysteresis; CSV export subfolder; providers pane fixed window; Warp credit-based cost. Desktop/menubar: unified flame logo; default DMG; docs signed+notarized. * menubar: one running instance, self-relaunch on language change The single-instance guard only retired strictly older copies, so two login items starting in the same instant both survived, and a copy whose bundle identity did not survive install was never seen at all. The decision is now total (newest launch wins, ties break on pid) and peers are matched on bundle id or executable name. --keep-both opts one launch out. Language changes no longer have the desktop app quit and reopen the menu bar, which made macOS attribute the new process to the desktop app and re-ask for the data-access grant. The menu bar relaunches itself via the existing remote command key; older menu bars that do not watch the key fall back to the old path after 5s. * desktop: export toast shows the saved path; resource buckets on app_close The export toast showed the folder that was picked, not the dated subfolder the files land in. The handler already parsed the CLI's saved line; it now returns that path and the toast uses it. app_close carries cpu/mem (and serveCpu/serveMem when serve reported) as bucket labels, sampled on the existing flush interval. serve adds cpuSec and peak rssMb to its answer frames. Unmeasured figures are omitted, never sent as zero. * menubar guard never leaves zero instances; installer replaces in place; JSON export into folder Guard: an unreadable launch date on either side could make two copies retire each other. Unreadable peers now count only when their pid is lower, and a copy that cannot read its own date retires lower pids only, so a disagreement keeps at least one instance. Installer: an existing bundle in /Applications or ~/Applications is replaced where it lives instead of a second copy being added. The old bundle is moved aside and restored on any failure; a cross-volume move falls back to a copy that is re-verified with codesign. An unwritable location is never escalated: the install goes to ~/Applications and the leftover is named. Export: -o pointing at an existing folder writes the JSON inside it. Short sessions omit the cpu buckets. setLanguage reopens the menu bar if its own relaunch never comes back. AppRelaunch passes the bundle path as an argument. * menubar guard orders by kernel start time; installer opens the copy that exists and recovers a killed install Guard: launch dates could be unreadable and pid order can disagree with start order after pid reuse, so two copies could still retire each other. Ordering now uses the kernel-reported process start time, which both sides read identically. A copy whose start time cannot be read is left out, so the worst case is two menu bars, never none. Installer: with the only copy in an unwritable /Applications, a plain run tried to open a path that did not exist. It now opens the installed copy. A placement killed mid-way is recovered on the next run, a concurrent install is refused, and a failed restore names where the previous bundle is. Process matching uses the exact executable name. Export: a trailing separator names a folder. Telemetry cpu is measured from telemetry start. * installer: a recycled pid can no longer block installs; language change waits for the replacement process An aside left by an earlier install counted as an active install whenever its pid was live, so once that pid was reused every install was refused for good. It now also has to be recent (ctime within 10 minutes), a pid we may not signal is not ours, the refusal names the file, and an orphan that cannot be cleared is reported instead of aborting the install. setLanguage confirmed the relaunch with a matcher the dying process still satisfied, so the reopen fallback never fired. It now waits for a pid that was not running before. * desktop: only the headline refreshes live; act, yield and the optimize scan move to slower tiers An open window ran act report (a fresh CLI process each time), yield and an optimize scan on every refresh. The headline poll now passes --no-optimize and takes the snapshot path; act report refreshes on mount, on manual refresh and every 10 minutes, yield every 5. The optimize scan runs at most once a day per query scope, is stored in userData with its time, and is forced fresh by the Optimize page or a manual refresh. Figures that are not live show their age, and no stored scan means no savings clause rather than a zero. On battery the live interval doubles; the chosen cadence stays the base. * desktop: a stored optimize scan is only valid on the day it was computed; cadence changes no longer refetch The scan cache is keyed on the argv, which says 'today' or '30days', not a date, so yesterday's scan was served as today's. It is now reused only on the same local day. Stored findings in Signals carry their age, a failed scan shows the error instead of scanning forever, and the cold-boot label uses the time the app received the payload. usePolled fetched immediately whenever its interval changed, so every power transition (and launching on battery) refetched every live hook and could spawn an extra act report. Fetching and timer arming are now separate effects. Optimize's yield is on the same 5 minute tier as Overview. * desktop: re-ask for the optimize scan on the first render of a new local day An app left open across midnight kept yesterday's stored savings under Today, because the scan was only requested on mount, scope change or manual refresh. The local day is now one of the hook's triggers; the previous day's figure is dropped while the new scan runs. * serve: a menubar poll is never answered from the status snapshot Inside its settle window the status snapshot returns the pre-change payload on purpose. The resident serve process then memoized that answer as clean, so after a single write followed by quiet the headline stayed on the old figure until the next write or the five minute memo cap. The snapshot is for one-shot runs; the resident process already holds the parsed state, so it now skips it. * tests stop writing the real serve pid file; superseded caches are swept; installer notes reach the desktop card ServeConnection takes its pid file as a parameter, so the Swift tests no longer share ~/.cache/codeburn/menubar-serve.pid with a running menu bar, and the reaper only signals a record that is a serve --stdio command. Superseded session-cache, codex-results and cursor-results files (100MB+ each) are removed once untouched for 14 days, at most once a day. daily-cache and the hermes ledger are never swept: they carry sealed days a version bump adopts. The menu bar installer's leftover-copy advice is emitted as a marked line under CODEBURN_PROGRESS and shown on the desktop card. The skipped-refresh NSLog is debug only. The app's vitest workers turn off Node's built-in web storage. * menubar: anonymous usage statistics, under the same consent as the desktop and the Windows tray The Swift menu bar sent nothing, so every codeburn-menubar row was a Windows tray. It now follows the desktop's telemetry.v1.json when that exists (read only: same install id, same on/off, onboarded required) and otherwise keeps its own state with the same region default (off in EU/EEA/UK/CH and when the region is unknown). Settings gains one Privacy toggle, disabled when the desktop owns the choice. Events use the tray's names; the daily usage snapshot is the CLI's block passed through a sanitizer and is left to the desktop when it is the consent source. Debug builds never send. A resident CLI that gets disabled for the run now says so in the log. * menubar statistics: private network session, abandoned batch on opt-out, a desktop No survives the desktop going away The sender used URLSession.shared, so a server or CDN cookie and the default User-Agent rode along and would have outlived an opt-out. It now owns an ephemeral session with no cookies, no cache, a fixed agent string and no redirects. A batch that is out when the toggle goes off is dropped rather than re-queued under the fresh id. The desktop's answer is recorded locally, so a missing or damaged state file never falls back to the region default, and the standalone id is persisted when minted. The toggle stays usable as a local off switch under desktop consent. Copy states what this app actually sends. * vercel gateway spend is shown on its own row and kept out of totals by default The gateway reports daily aggregates per model, with nothing to match against the local tools that were pointed at it, so every headline counted that traffic twice. Totals now leave the gateway slice out when all providers are shown; the row keeps its full amount and is marked not in total, --provider vercel-gateway is unchanged, and codeburn gateway-totals include folds it back in. The daily cache still stores the slice, so the choice applies retroactively. Reports with no gateway credential are byte-identical. The gateway's request_count now feeds the call count instead of each daily row counting as one call. Hermes: a mid-session price change lands on the day it is observed and sealed days are never rewritten; stated in the code and changelog. * gateway exclusion applies to every report through the parse, and the detail panels follow the headline The first pass narrowed only the day totals, so By tool, top models, top projects, activities, status json projects and any project-filtered table still carried gateway spend next to a headline that did not, and By tool shares could pass 100%. The rule now lives in parseAllSessions: with all providers in scope and the opt-in off, aggregate-only sessions are dropped after the memo, and the callers that derive cached days opt out so stored slices are unchanged. day.projects is reduced like models. The gateway stays visible once, as a labelled not-in-total row with no share, and standalone reports note the excluded amount on stderr so machine output is unchanged. * dashboard: the background history index follows the gateway exclusion too The index keeps the whole corpus so it can fill the daily cache, but its per-period projection handed that unfiltered list to the project, model and activity panels, so they regained gateway spend once the index landed. * ci: a hung lock suite fails in 90s and retries once with a warning; slow Windows tests get measured limits The cache-lock step failed 6 of the last 60 runs with no output for five minutes after the vitest banner; passing runs take 12-18s on every Node version. Each attempt is now capped at 90s and retried once, with a warning whenever that happens. On windows-latest a single CLI spawn takes 1.4-12s, so the four-spawn status snapshot test and the c6 parser suite get limits taken from those runs, each with its reason. Both test jobs print their ten slowest cases. * desktop: Privacy & data uses the same rows as the rest of Settings The pane mixed two static claims with two controls in its own layout. It now uses the about-row pattern every other pane uses: title and hint on the left, one control on the right. The claims became the subtitle. Rows: anonymous usage statistics (toggle, link to what is sent), device sharing state with Manage, local report snapshots with Clear, export with Open export. * desktop: Privacy & data keeps one bounded column and rows that never squeeze The card stretched with the window, stranding each control hundreds of pixels from its text. This pane's heading, subtitle and card now share a 760px column and one text measure. Rows stack on their own width, because the window can never be narrow enough for the old viewport rule to fire; row buttons do not wrap. The what-is-sent link sits on its own line, and the snapshot and export descriptions fit their measure and say this machine. * menubar tests clean up their scratch defaults and leave the real Keychain alone Four test files never removed their UserDefaults suites and the rest removed the domain but left the plist, so thousands of files piled up in ~/Library/Preferences. A shared helper forgets a suite and deletes its file, and every test that makes a suite now uses it. cfprefsd still rewrites an empty plist when the test process exits, so a run leaves about a hundred 42-byte files with no test data in them. The real-Keychain round trip only runs with CODEBURN_TEST_REAL_KEYCHAIN=1. * desktop: the resident parser retires after 15 idle minutes and restarts on demand The renderer stops polling while the window is hidden, but the serve child stayed resident with its parsed cache, one to two GB on a large corpus. After 15 minutes without a request it is stopped the way a settings restart stops it, without spending the unexpected-death budget, and the next request starts a new resident through the existing lazy path, never a one-shot. CODEBURN_SERVE_IDLE_MS tunes or disables it. * desktop: every settings pane keeps a bounded column, and dark buttons have an edge Cards stretched with the window, so on a wide display controls sat up to 1300px from their labels and intro lines ran past 140 characters. All panes now share one left-aligned column (760px, 980px for projects, aliases and pricing, which hold wide rows) and one text measure. Rows stack on their own width instead of a viewport rule the 900px minimum window could never reach, and a long path in Projects no longer overflows the pane. In dark mode the secondary button matched or sat below its surface, and was invisible on the plugin install dialog. It gets a face and a border from two new tokens; light is unchanged. The onboarding consent label matches Settings. * desktop: this device shows its fingerprint on its own line The local name and the fingerprint are two adjacent inline spans, so they read as one run of text. * menubar: the resident parser retires after 15 idle minutes and restarts on demand The menu bar kept its serve child, and the parsed cache with it, for the whole run, even with the popover closed and nothing changing. After 15 minutes without a request the child is retired without counting as a death, and the next request starts a new resident through ensureStarted, never the one-shot fallback, whose snapshot settle window would make the figure lag a whole tick. The window sits above the longest gap between real requests, so a child stays warm while work is happening. CodeBurnServeIdleSeconds tunes or disables it. * serve: a poll re-checks only what the watcher saw change, and shard writes are coalesced With a session being written, every poll re-listed about 2,400 directories and re-fingerprinted about 6,000 transcripts, then rewrote the whole current-month shard (49MB on a large corpus) and read it back on the next poll. The resident process now reuses the previous listing and fingerprints for paths its root watcher proves untouched, and falls back to the full sweep whenever the watcher is missing, unhealthy, overflowed, armed after the sweep, does not cover the path, the memo is older than 4.5 minutes, or the process was suspended. Shard publication is held for up to 90s and flushed when stdin closes; a held write is dropped rather than written over something another process published. One-shot runs are unchanged. Active poll cost 0.71 to 0.33 CPU-s at a 30s cadence; time-to-reflect unchanged at about 1.2s across append, new dir, new file, delete, rename-over, in-flight, watcher overflow and unhealthy watcher. Changelog: state the telemetry default as it is in this version. * a retired parser gets to publish its held shards, and durable providers are never held Both apps retired the serve child with SIGTERM before its stdin-close flush could run, so every retire discarded the coalesced window. They now close stdin, give the child a bounded grace to publish and exit, and signal it only if it is still running; a settings restart does the same. Measured: flushed 0/5 before, 5/5 after, for both clients. copilot's cache entries are the only record once Copilot prunes its own files, so a held window that was dropped (retire, crash, kill -9) before the source was pruned lost that spend for good. A window that a durable provider dirtied is published on the poll that parsed it, as before coalescing existed. The RSS guard publishes a held window before it clears the caches instead of discarding it. * serve: release the lifetime parse after the fill, and make the collection real The RSS guard dropped its memos and then called globalThis.gc, which exists only under --expose-gc; no launcher passes it, so the collection had never run and the freed pages never went back. On a cold start the resident idled at 2.2GB with 364MB of live heap: clearing every memo moved RSS by 0MB, a collection alone by 700MB. After the background fill has sealed its summaries the process now publishes any held shard window, drops the memos it can re-read from disk (the cold start had loaded the cache with scope 'all', which then served every later poll), and collects; it collects again a minute later for as long as a pass returns 64MB, at most four times. Cold idle 2198MB to 700MB, warm 900MB to 781MB. Reports are leaf-identical cold and warm, time-to-reflect unchanged, a released month scope reloads in 0.3-0.5s. * warp: the billed cost reaches reports and survives the cache The provider derived a dollar cost from Warp's own billing record (provider cents, charged usage, or credits), but warp was missing from the reported-cost pass-through, so the cached call kept no cost and every report, cold or warm, priced the conversation from its tokens. A fixture billed at $1.22 reported $0.15. A call whose cost came from a billing record now keeps it; a call that only has the token floor stores none and is still re-priced when prices change. Warp entries re-parse once (provider parse version), and the daily cache moves to v34 so days whose Warp source still exists re-derive; call counts do not move, so nothing is double counted or dropped. * openclaw and pi: a reported cost survives the cache like every other reported cost Both providers read the cost their tool recorded for a message, and both were missing from the reported-cost pass-through, so reports priced every call from tokens instead. Fixtures reported $0.011 against $0.056 (openclaw) and $0.013 against $0.410 (pi). A call with a reported cost now keeps it; a call with none, or an explicit zero, stores none and is still re-priced when prices change. omp had been added to the list in #1150 and pi, the same parser, was never revisited. The provider list is one named set, the unreachable providerCallToTurn is gone, and both providers re-parse once; the v34 daily cache re-derives their days with call counts unchanged. * test: pin parse count per report and per resident poll
1668 lines
76 KiB
TypeScript
1668 lines
76 KiB
TypeScript
import { readFile, writeFile, mkdir } from 'fs/promises'
|
||
import { join } from 'path'
|
||
import { createHash } from 'crypto'
|
||
|
||
import { getCodeburnCacheDir } from './cache-dir.js'
|
||
import snapshotData from './data/litellm-snapshot.json' with { type: 'json' }
|
||
import fallbackData from './data/pricing-fallback.json' with { type: 'json' }
|
||
import { fetchWithTimeout } from './fetch-utils.js'
|
||
|
||
export type ModelCosts = {
|
||
inputCostPerToken: number
|
||
outputCostPerToken: number
|
||
cacheWriteCostPerToken: number
|
||
cacheReadCostPerToken: number
|
||
webSearchCostPerRequest: number
|
||
fastMultiplier: number
|
||
/// True only when the pricing source carried a real cache-write rate. When
|
||
/// absent/false, `cacheWriteCostPerToken` is the fabricated `1.25 x input`
|
||
/// default, which is right for Anthropic-style pricing but would invent a
|
||
/// surcharge on providers that charge nothing extra to write cache. Callers
|
||
/// that decide WHICH bucket to put tokens in (rather than what to multiply
|
||
/// them by) must consult this before routing tokens to the cache-write
|
||
/// bucket. Optional so an incomplete literal defaults to the safe answer.
|
||
cacheWriteCostIsExplicit?: boolean
|
||
}
|
||
|
||
/// Providers whose reported `reasoningTokens` are a SUBSET of `outputTokens`
|
||
/// rather than a separate bucket to add on top. OpenAI bills reasoning as part
|
||
/// of output (every codex `token_count` event satisfies input + output ==
|
||
/// total), and Anthropic folds thinking into output the same way, so summing
|
||
/// the two double-counts both the cost and the displayed output tokens. Copilot
|
||
/// is the same case: its per-request token_details_json prices input/cache/output
|
||
/// and nothing else, and its supplementary store-row/shutdown calls carry
|
||
/// reasoningTokens with outputTokens 0 while the per-turn assistant.message call
|
||
/// bills the full output, so adding reasoning on top bills it twice.
|
||
/// DSH TokenUsage includes reasoning in output too; see the pinned contract:
|
||
/// https://github.com/deepseek-ai/deepseek-harness/blob/c291e7961a515f6d7af9304e7fd1d257929aef26/docs/subsystems/llm-streaming.md#tokenusage
|
||
const REASONING_INCLUDED_IN_OUTPUT = new Set(['claude', 'codex', 'copilot', 'dsh'])
|
||
|
||
/// Output tokens to bill and display for one call. Single source of truth so
|
||
/// the pricing sites and the display sums can never disagree about whether a
|
||
/// provider's reasoning tokens are already inside its output count (#1075).
|
||
export function billableOutputTokens(provider: string, outputTokens: number, reasoningTokens: number): number {
|
||
return REASONING_INCLUDED_IN_OUTPUT.has(provider) ? outputTokens : outputTokens + reasoningTokens
|
||
}
|
||
|
||
type PriceOverrideRates = {
|
||
input: number
|
||
output: number
|
||
cacheRead?: number
|
||
cacheCreation?: number
|
||
}
|
||
|
||
type LiteLLMEntry = {
|
||
input_cost_per_token?: number
|
||
output_cost_per_token?: number
|
||
cache_creation_input_token_cost?: number
|
||
cache_read_input_token_cost?: number
|
||
provider_specific_entry?: { fast?: number }
|
||
}
|
||
|
||
// [input, output, cacheWrite, cacheRead, fastMultiplier]. The trailing fast
|
||
// multiplier is carried straight from LiteLLM's provider_specific_entry.fast so
|
||
// new models pick it up automatically — no hand-maintained per-model table.
|
||
type SnapshotEntry = [number, number, number | null, number | null, (number | null)?]
|
||
|
||
const LITELLM_URL = 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json'
|
||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000
|
||
// Bump whenever a ModelCosts field changes pricing behavior (cacheWriteCostIsExplicit,
|
||
// added in #1075/#1078). A cache written under an older/missing version is treated as a
|
||
// miss instead of read verbatim, so a stale on-disk file can't reintroduce a killed bug
|
||
// for up to CACHE_TTL_MS after an upgrade.
|
||
// Also folded into getPricingGenerationKey() below: a resident/snapshot-caching
|
||
// consumer needs the same "pricing behavior changed" signal this already gives
|
||
// the on-disk LiteLLM cache, not just the on-disk cache itself.
|
||
export const CACHE_SCHEMA_VERSION = 3
|
||
const WEB_SEARCH_COST = 0.01
|
||
const ONE_HOUR_CACHE_WRITE_MULTIPLIER_FROM_FIVE_MINUTE_RATE = 1.6
|
||
|
||
// Explicit USD/token prices that must override LiteLLM/cache data. Cursor
|
||
// publishes house-model rates in the models table at cursor.com/docs/models
|
||
// (provider "Cursor", USD per 1M tokens): composer-2/2.5: $0.50 input, $2.50
|
||
// output, $0.20 cache read; composer-1.5: $3.50/$17.50/$0.35; composer-1:
|
||
// $1.25/$10/$0.125. Cursor publishes no separate cache-write rate for these,
|
||
// so cache write uses the input rate.
|
||
const BUILTIN_PRICE_OVERRIDES: Record<string, SnapshotEntry> = {
|
||
'composer-2.5': [0.5e-6, 2.5e-6, 0.5e-6, 0.2e-6],
|
||
'composer-2': [0.5e-6, 2.5e-6, 0.5e-6, 0.2e-6],
|
||
'composer-1.5': [3.5e-6, 17.5e-6, 3.5e-6, 0.35e-6],
|
||
'composer-1': [1.25e-6, 10e-6, 1.25e-6, 0.125e-6],
|
||
}
|
||
|
||
// Assemble a ModelCosts, applying the cache-cost heuristics (write = 1.25x
|
||
// input, read = 0.1x input) when a source omits them. Shared by the bundled
|
||
// tuple path (tupleToCosts) and the live LiteLLM path (parseLiteLLMEntry) so the
|
||
// multipliers live in exactly one place.
|
||
function buildCosts(
|
||
input: number,
|
||
output: number,
|
||
cacheWrite: number | null | undefined,
|
||
cacheRead: number | null | undefined,
|
||
fast: number | null | undefined,
|
||
): ModelCosts {
|
||
return {
|
||
inputCostPerToken: input,
|
||
outputCostPerToken: output,
|
||
cacheWriteCostPerToken: cacheWrite ?? input * 1.25,
|
||
cacheReadCostPerToken: cacheRead ?? input * 0.1,
|
||
webSearchCostPerRequest: WEB_SEARCH_COST,
|
||
fastMultiplier: fast ?? 1,
|
||
cacheWriteCostIsExplicit: cacheWrite !== null && cacheWrite !== undefined,
|
||
}
|
||
}
|
||
// For grok-4.6, prompt tokens mean input tokens plus cached input tokens for a
|
||
// request. At 200k prompt tokens, xAI prices every priced bucket at this high
|
||
// tier rather than applying a marginal rate. Cache creation stays unset because
|
||
// xAI publishes no separate cache-write rate.
|
||
const GROK_4_6_PROMPT_TOKEN_THRESHOLD = 200_000
|
||
const GROK_4_6_HIGH_PROMPT_COSTS = buildCosts(4e-6, 12e-6, null, 1e-6, null)
|
||
|
||
// Swap in the vendor's high tier when a request's prompt crosses the published
|
||
// threshold. A user-set exact priceOverride still wins over the built-in tier.
|
||
// Kept as a helper so the next tiered model extends this one branch instead of
|
||
// copy-pasting the inline condition.
|
||
function tieredCostsFor(model: string, baseCosts: ModelCosts, promptTokens: number): ModelCosts {
|
||
if (exactPriceOverrideFor(model)) return baseCosts
|
||
if (resolveCanonicalModelId(model) === 'grok-4.6' && promptTokens >= GROK_4_6_PROMPT_TOKEN_THRESHOLD) {
|
||
return GROK_4_6_HIGH_PROMPT_COSTS
|
||
}
|
||
return baseCosts
|
||
}
|
||
|
||
|
||
function tupleToCosts(raw: SnapshotEntry): ModelCosts {
|
||
const [input, output, cacheWrite, cacheRead, fast] = raw
|
||
return buildCosts(input, output, cacheWrite, cacheRead, fast)
|
||
}
|
||
|
||
function applyBuiltinPriceOverrides(pricing: Map<string, ModelCosts>): Map<string, ModelCosts> {
|
||
for (const [name, raw] of Object.entries(BUILTIN_PRICE_OVERRIDES)) {
|
||
pricing.set(name, tupleToCosts(raw))
|
||
}
|
||
return pricing
|
||
}
|
||
|
||
function loadSnapshot(): Map<string, ModelCosts> {
|
||
const map = new Map<string, ModelCosts>()
|
||
for (const [name, raw] of Object.entries(snapshotData as unknown as Record<string, SnapshotEntry>)) {
|
||
map.set(name, tupleToCosts(raw))
|
||
}
|
||
return map
|
||
}
|
||
|
||
// Gap-fill pricing from models.dev / OpenRouter, keyed lowercase. Consulted ONLY
|
||
// as the last-resort fallback in getModelCosts (never for exact/canonical/prefix
|
||
// matches), so a reseller variant name can't shadow a real canonical entry.
|
||
const fallbackCosts: Map<string, ModelCosts> = (() => {
|
||
const map = new Map<string, ModelCosts>()
|
||
for (const [name, raw] of Object.entries(fallbackData as unknown as Record<string, SnapshotEntry>)) {
|
||
const lk = name.toLowerCase()
|
||
if (!map.has(lk)) map.set(lk, tupleToCosts(raw))
|
||
}
|
||
return map
|
||
})()
|
||
|
||
let pricingCache: Map<string, ModelCosts> = applyBuiltinPriceOverrides(loadSnapshot())
|
||
let sortedPricingKeys: string[] | null = null
|
||
let lowercasePricingIndex: Map<string, ModelCosts> | null = null
|
||
|
||
function getSortedPricingKeys(): string[] {
|
||
if (sortedPricingKeys === null) {
|
||
sortedPricingKeys = Array.from(pricingCache.keys()).sort((a, b) => b.length - a.length)
|
||
}
|
||
return sortedPricingKeys
|
||
}
|
||
|
||
// Case-insensitive index, built lazily. Lets a session model like `MiniMax-M3`
|
||
// resolve to a gap-filled OpenRouter key like `minimax-m3` (lowercase slug).
|
||
// First key wins on a lowercase collision so it stays deterministic.
|
||
//
|
||
// Zero-priced entries are excluded: LiteLLM ships `[0,0]` stubs (e.g.
|
||
// `GigaChat-2-Max`) for models it lists but has no price for. Indexing those
|
||
// would let a case-mismatched query (`gigachat-2-max`) resolve to a silent $0
|
||
// instead of returning null, which suppresses the unknown-model warning and
|
||
// hides real spend. A case-EXACT query still finds the stub via the normal
|
||
// pipeline; only the fuzzy case-insensitive path skips them.
|
||
function getLowercasePricingIndex(): Map<string, ModelCosts> {
|
||
if (lowercasePricingIndex === null) {
|
||
lowercasePricingIndex = new Map()
|
||
const priced = (c: ModelCosts) => c.inputCostPerToken > 0 || c.outputCostPerToken > 0
|
||
// The live pricing data wins on any lowercase collision; the gap-fill only
|
||
// fills names that resolve to nothing through the normal pipeline.
|
||
for (const [key, costs] of pricingCache) {
|
||
const lk = key.toLowerCase()
|
||
if (priced(costs) && !lowercasePricingIndex.has(lk)) lowercasePricingIndex.set(lk, costs)
|
||
}
|
||
for (const [lk, costs] of fallbackCosts) {
|
||
if (priced(costs) && !lowercasePricingIndex.has(lk)) lowercasePricingIndex.set(lk, costs)
|
||
}
|
||
}
|
||
return lowercasePricingIndex
|
||
}
|
||
|
||
function getCachePath(): string {
|
||
return join(getCodeburnCacheDir(), 'litellm-pricing.json')
|
||
}
|
||
|
||
/// Clamp a per-token rate to a sane non-negative value. Defense in depth
|
||
/// against a tampered LiteLLM JSON shipping a negative `input_cost_per_token`,
|
||
/// which would otherwise produce negative costs that subtract from totals.
|
||
/// We use Number.isFinite to also reject NaN/Infinity, and cap at $1/token
|
||
/// (well above the most expensive frontier model) so a stray decimal-place
|
||
/// shift in the upstream JSON can't wildly inflate spend numbers either.
|
||
function safePerTokenRate(n: number | undefined): number | null {
|
||
if (n === undefined || !Number.isFinite(n) || n < 0) return null
|
||
if (n > 1) return 1
|
||
return n
|
||
}
|
||
|
||
export function parseLiteLLMEntry(entry: LiteLLMEntry): ModelCosts | null {
|
||
// The live LiteLLM map is remote JSON; a null (or non-object) value for a
|
||
// model would make the field reads below throw and abort the whole pricing
|
||
// load. Treat it as unparseable, like any other bad entry.
|
||
if (!entry || typeof entry !== 'object') return null
|
||
const inputCost = safePerTokenRate(entry.input_cost_per_token)
|
||
const outputCost = safePerTokenRate(entry.output_cost_per_token)
|
||
if (inputCost === null || outputCost === null) return null
|
||
return buildCosts(
|
||
inputCost,
|
||
outputCost,
|
||
safePerTokenRate(entry.cache_creation_input_token_cost),
|
||
safePerTokenRate(entry.cache_read_input_token_cost),
|
||
entry.provider_specific_entry?.fast,
|
||
)
|
||
}
|
||
|
||
// Timestamp of whichever live LiteLLM data (freshly fetched or read back from
|
||
// the on-disk cache) is currently loaded into pricingCache; null when nothing
|
||
// live is loaded and pricing is purely the bundled snapshot (offline/first
|
||
// run, CODEBURN_PRICING_SNAPSHOT_ONLY, or a failed fetch with no cache hit).
|
||
// Read by getPricingGenerationKey() so a consumer that persists rendered
|
||
// costs across process invocations (the menubar's status snapshot) can tell
|
||
// "the live pricing data actually changed" apart from "nothing changed" —
|
||
// this module has no other way to signal that across a fresh CLI process.
|
||
let livePricingTimestamp: number | null = null
|
||
|
||
async function fetchAndCachePricing(): Promise<Map<string, ModelCosts>> {
|
||
// Bounded: runs on every CLI invocation (the menubar shells out and blocks on
|
||
// it). Without a timeout a half-open network after wake-from-sleep makes
|
||
// fetch() hang forever, wedging the menubar's loading spinner. On timeout the
|
||
// caller's catch falls back to the bundled price snapshot.
|
||
const response = await fetchWithTimeout(LITELLM_URL)
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
||
const data = await response.json() as Record<string, LiteLLMEntry>
|
||
const pricing = new Map<string, ModelCosts>()
|
||
|
||
for (const [name, entry] of Object.entries(data)) {
|
||
const costs = parseLiteLLMEntry(entry)
|
||
if (!costs) continue
|
||
pricing.set(name, costs)
|
||
// Also index by stripped name so lookups work without provider prefix:
|
||
// 'anthropic/claude-opus-4-6' is also queryable as 'claude-opus-4-6'.
|
||
// First write wins so direct-provider entries take precedence over re-hosters.
|
||
const stripped = name.replace(/^[^/]+\//, '')
|
||
if (stripped !== name && !pricing.has(stripped)) pricing.set(stripped, costs)
|
||
}
|
||
|
||
const timestamp = Date.now()
|
||
await mkdir(getCodeburnCacheDir(), { recursive: true })
|
||
await writeFile(getCachePath(), JSON.stringify({
|
||
version: CACHE_SCHEMA_VERSION,
|
||
timestamp,
|
||
data: Object.fromEntries(pricing),
|
||
}))
|
||
livePricingTimestamp = timestamp
|
||
|
||
return pricing
|
||
}
|
||
|
||
async function loadCachedPricing(): Promise<Map<string, ModelCosts> | null> {
|
||
try {
|
||
const raw = await readFile(getCachePath(), 'utf-8')
|
||
const cached = JSON.parse(raw) as { version?: number; timestamp: number; data: Record<string, ModelCosts> }
|
||
if (cached.version !== CACHE_SCHEMA_VERSION) return null
|
||
if (Date.now() - cached.timestamp > CACHE_TTL_MS) return null
|
||
livePricingTimestamp = cached.timestamp
|
||
return new Map(Object.entries(cached.data))
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
function mergeSnapshotFallbacks(pricing: Map<string, ModelCosts>): Map<string, ModelCosts> {
|
||
for (const [name, costs] of loadSnapshot()) {
|
||
if (!pricing.has(name)) pricing.set(name, costs)
|
||
}
|
||
return applyBuiltinPriceOverrides(pricing)
|
||
}
|
||
|
||
function setPricingCache(pricing: Map<string, ModelCosts>): void {
|
||
pricingCache = pricing
|
||
sortedPricingKeys = null
|
||
lowercasePricingIndex = null
|
||
knownNamespaces = null
|
||
}
|
||
|
||
export async function loadPricing(): Promise<void> {
|
||
const cached = await loadCachedPricing()
|
||
if (cached) {
|
||
setPricingCache(mergeSnapshotFallbacks(cached))
|
||
return
|
||
}
|
||
|
||
// Test-only escape hatch, set for the whole suite in
|
||
// tests/setup/env-isolation.ts: skip the live LiteLLM fetch and price purely
|
||
// off the bundled snapshot, so an upstream reprice can't turn tests red.
|
||
if (process.env['CODEBURN_PRICING_SNAPSHOT_ONLY']) {
|
||
livePricingTimestamp = null
|
||
setPricingCache(mergeSnapshotFallbacks(new Map()))
|
||
return
|
||
}
|
||
|
||
try {
|
||
setPricingCache(mergeSnapshotFallbacks(await fetchAndCachePricing()))
|
||
} catch {
|
||
// snapshot already loaded at init; nothing more to do
|
||
livePricingTimestamp = null
|
||
}
|
||
}
|
||
|
||
// Content digest of the two bundled pricing files, computed once and memoized
|
||
// (they're static imports; nothing in-process can change them). Changes only
|
||
// when `scripts/bundle-litellm.mjs` regenerates litellm-snapshot.json /
|
||
// pricing-fallback.json and that regeneration ships in a new codeburn build —
|
||
// exactly the "bundled data" staleness class getPricingGenerationKey exists
|
||
// to catch, distinct from the live cache's own timestamp.
|
||
let bundledPricingDigest: string | null = null
|
||
function getBundledPricingDigest(): string {
|
||
if (bundledPricingDigest === null) {
|
||
bundledPricingDigest = createHash('sha256')
|
||
.update(JSON.stringify(snapshotData))
|
||
.update(JSON.stringify(fallbackData))
|
||
.digest('hex')
|
||
}
|
||
return bundledPricingDigest
|
||
}
|
||
|
||
/// Stable signature of everything that can silently change a session's
|
||
/// RENDERED cost with no session file ever changing: the live LiteLLM cache's
|
||
/// freshness (a repricing fetch, or its absence), the bundled snapshot's own
|
||
/// content (a repriced model shipped in a new build), and this module's
|
||
/// pricing-behavior version (CACHE_SCHEMA_VERSION). A caller that persists a
|
||
/// fully-rendered payload across process invocations (the menubar's status
|
||
/// snapshot) must fold this into its own cache key the same way it already
|
||
/// folds the four *ConfigHash getters above — those cover user-editable
|
||
/// pricing CONFIG, this covers upstream/bundled pricing DATA and code version,
|
||
/// a different staleness gap with no other invalidation path of its own.
|
||
export function getPricingGenerationKey(): string {
|
||
return `${CACHE_SCHEMA_VERSION}:${livePricingTimestamp ?? 'bundled'}:${getBundledPricingDigest()}`
|
||
}
|
||
|
||
// Known model name variants that providers emit but LiteLLM/fallback don't index under.
|
||
// OMP emits 'anthropic--claude-4.6-opus' (double-dash, dot version, tier-last).
|
||
// getCanonicalName strips a KNOWN vendor/router prefix first unless the
|
||
// full cleaned id itself is an alias (orcarouter/fusion). Post-strip forms
|
||
// still cover every other entry here.
|
||
const BUILTIN_ALIASES: Record<string, string> = {
|
||
'anthropic--claude-4.6-opus': 'claude-opus-4-6',
|
||
'anthropic--claude-4.6-sonnet': 'claude-sonnet-4-6',
|
||
'anthropic--claude-4.5-opus': 'claude-opus-4-5',
|
||
'anthropic--claude-4.5-sonnet': 'claude-sonnet-4-5',
|
||
'anthropic--claude-4.5-haiku': 'claude-haiku-4-5',
|
||
// #1093: copilot session-store.db writes 'claude-haiku-4.5' (tier-first, dot)
|
||
'claude-haiku-4.5': 'claude-haiku-4-5',
|
||
'claude-sonnet-4.6': 'claude-sonnet-4-6',
|
||
'claude-sonnet-4.5': 'claude-sonnet-4-5',
|
||
'claude-opus-4.7': 'claude-opus-4-7',
|
||
'claude-opus-4.6': 'claude-opus-4-6',
|
||
'claude-opus-4.5': 'claude-opus-4-5',
|
||
'cursor-auto': 'claude-sonnet-4-5',
|
||
'cursor-agent-auto': 'claude-sonnet-4-5',
|
||
'copilot-auto': 'claude-sonnet-4-5',
|
||
'copilot-openai-auto': 'gpt-5.3-codex',
|
||
'copilot-anthropic-auto': 'claude-sonnet-4-5',
|
||
'openai-codex:gpt-5.5': 'gpt-5.5',
|
||
'ibm-bob-auto': 'claude-sonnet-4-5',
|
||
'kiro-auto': 'claude-sonnet-4-5',
|
||
'quickdesk-auto': 'claude-sonnet-4-5',
|
||
'cline-auto': 'claude-sonnet-4-5',
|
||
'openclaw-auto': 'claude-sonnet-4-5',
|
||
'warp-auto-efficient': 'gpt-5.3-codex',
|
||
'warp-auto-powerful': 'claude-opus-4-6',
|
||
// Codex activity ids are product surfaces, not subscription SKUs and not
|
||
// LiteLLM rows. OpenAI's tracker (openai/codex#32224) says auto review
|
||
// consumes normal model usage. Public evidence: review_model defaults to
|
||
// the session model; GPT-5.5 is the currently recommended review model.
|
||
// Price as that existing bundled row. Do not invent a rate. Do not treat
|
||
// the id as honestly $0 — it draws from the same credit pool. Display
|
||
// stays on autoModelNames (same class as cursor-auto / copilot-openai-auto).
|
||
// Only alias ids observed in Codex source / real rollouts. Do not infer
|
||
// `codex-code-review` from the activity name "code review".
|
||
'codex-auto-review': 'gpt-5.5',
|
||
'grok-build': 'grok-build-0.1',
|
||
// Grok Bot's desktop app serves opaque `sand-*` aliases and records no model
|
||
// id at all, so there is nothing truthful to price it by. It is xAI's own
|
||
// product, so it prices at xAI's published grok-4.6 rate ($2.00/M in,
|
||
// $6.00/M out, $0.50/M cached). Every grokbot call is costIsEstimated.
|
||
'grokbot-auto': 'grok-4.6',
|
||
'GPT-5.3 Codex (low reasoning)': 'gpt-5.3-codex',
|
||
'GPT-5.3 Codex (medium reasoning)': 'gpt-5.3-codex',
|
||
'GPT-5.3 Codex (high reasoning)': 'gpt-5.3-codex',
|
||
'GPT-5.3 Codex (extra high reasoning)': 'gpt-5.3-codex',
|
||
'Claude Sonnet 4.6': 'claude-sonnet-4-6',
|
||
'Claude Sonnet 4.5': 'claude-sonnet-4-5',
|
||
'Claude Haiku 4.5': 'claude-haiku-4-5',
|
||
'Claude Opus 4.6': 'claude-opus-4-6',
|
||
'claude-4-6-sonnet-high': 'claude-sonnet-4-6',
|
||
'claude-4-6-sonnet-low': 'claude-sonnet-4-6',
|
||
'claude-4-6-sonnet-medium': 'claude-sonnet-4-6',
|
||
'claude-4-6-sonnet-high-fast': 'claude-sonnet-4-6',
|
||
'claude-4-7-opus-xhigh': 'claude-opus-4-7',
|
||
'claude-4-7-opus-xhigh-fast': 'claude-opus-4-7',
|
||
'qwen-auto': 'claude-sonnet-4-5',
|
||
// OrcaRouter fusion routes. Provenance: live OrcaRouter completion `model`
|
||
// field, 2026-08 (community #1058 / house #1118). Re-verify if the gateway
|
||
// rotates targets. `orcarouter/auto` is intentionally unaliased: the smart
|
||
// route currently lands on a Qwen/Llama flash model, so a Sonnet alias
|
||
// would overprice ~3–30×. Fail closed until a live probe pins that target.
|
||
'orcarouter/fusion': 'openai/gpt-oss-120b',
|
||
'orcarouter/fusion-flash': 'openai/gpt-oss-120b',
|
||
'orcarouter/fusion-mini': 'openai/gpt-oss-120b',
|
||
'kimi-auto': 'kimi-k2-thinking',
|
||
'kimi-code': 'kimi-k2-thinking',
|
||
'kimi-for-coding': 'kimi-k2-thinking',
|
||
// Kimi Code wires report the bare `k3` id in llm.request.model; without an
|
||
// alias those calls priced at $0 and the provider looked absent in the UI.
|
||
'k3': 'kimi-k3',
|
||
// Kimi desktop/IDE embedded runtime serves `k3-agent` / `k2d6-agent`.
|
||
'k3-agent': 'kimi-k3',
|
||
'k2d6-agent': 'kimi-k2p6',
|
||
'mimo-v2-flash': 'xiaomi/mimo-v2-flash',
|
||
// Hermes / Xiaomi token-plan sessions store the bare id. LiteLLM's row is
|
||
// namespaced. Same class as mimo-v2-flash above — do not invent a rate.
|
||
'mimo-v2.5-pro': 'xiaomi/mimo-v2.5-pro',
|
||
'mimo-v2.5': 'xiaomi/mimo-v2.5',
|
||
'kat-coder-pro-v1': 'kwaipilot/kat-coder-pro',
|
||
// Cursor emits dot-version tier-last names plus tier/reasoning suffixes
|
||
// that LiteLLM does not index (`-high`, `-low`, `-medium`, `-thinking`,
|
||
// `-high-thinking`, `-fast-mode`). Missing aliases here surface as $0 in
|
||
// the dashboard for users on non-Auto models (issue #159). Sources: the
|
||
// display map at `src/providers/cursor.ts:modelDisplayNames`, Cursor's
|
||
// public model docs at https://cursor.com/docs/models, and forum bug
|
||
// reports that quote literal slugs (e.g. forum.cursor.com/t/154933).
|
||
'claude-4-sonnet': 'claude-sonnet-4',
|
||
'claude-4-sonnet-1m': 'claude-sonnet-4',
|
||
'claude-4-sonnet-thinking': 'claude-sonnet-4',
|
||
'claude-4.5-sonnet': 'claude-sonnet-4-5',
|
||
'claude-4.5-sonnet-thinking': 'claude-sonnet-4-5',
|
||
'claude-4.6-sonnet': 'claude-sonnet-4-6',
|
||
'claude-4.6-sonnet-high': 'claude-sonnet-4-6',
|
||
'claude-4.6-sonnet-low': 'claude-sonnet-4-6',
|
||
'claude-4.6-sonnet-thinking': 'claude-sonnet-4-6',
|
||
'claude-4.6-sonnet-high-thinking':'claude-sonnet-4-6',
|
||
'claude-4-opus': 'claude-opus-4',
|
||
'claude-4.5-opus': 'claude-opus-4-5',
|
||
'claude-4.5-opus-high': 'claude-opus-4-5',
|
||
'claude-4.5-opus-low': 'claude-opus-4-5',
|
||
'claude-4.5-opus-medium': 'claude-opus-4-5',
|
||
'claude-4.5-opus-high-thinking': 'claude-opus-4-5',
|
||
'claude-4.6-opus': 'claude-opus-4-6',
|
||
'claude-4.6-opus-fast-mode': 'claude-opus-4-6',
|
||
'claude-4.6-opus-high': 'claude-opus-4-6',
|
||
'claude-4.6-opus-low': 'claude-opus-4-6',
|
||
'claude-4.6-opus-medium': 'claude-opus-4-6',
|
||
'claude-4.6-opus-high-thinking': 'claude-opus-4-6',
|
||
'claude-4.7-opus': 'claude-opus-4-7',
|
||
// Dash form (NOT dot) seen in forum.cursor.com/t/158597.
|
||
'claude-opus-4-7-thinking-high': 'claude-opus-4-7',
|
||
'claude-4.5-haiku': 'claude-haiku-4-5',
|
||
'claude-4.6-haiku': 'claude-haiku-4-5',
|
||
// Cursor house composer models use Cursor-published rates in
|
||
// BUILTIN_PRICE_OVERRIDES; keep them out of this alias map so they do not
|
||
// inherit Claude Sonnet proxy pricing.
|
||
// Cursor's "fast" routing variant of GPT-5 is the same model behind a
|
||
// lower-latency endpoint; price as base GPT-5 until LiteLLM tracks it.
|
||
'gpt-5-fast': 'gpt-5',
|
||
'gpt-4.1': 'gpt-4.1',
|
||
'gpt-5.2-low': 'gpt-5',
|
||
'gpt-5.1-codex-high': 'gpt-5.3-codex',
|
||
// Antigravity Gemini model IDs resolve to preview-priced entries.
|
||
'gemini-3.1-pro': 'gemini-3.1-pro-preview',
|
||
'gemini-3-flash': 'gemini-3-flash-preview',
|
||
'gemini-3.1-pro-high': 'gemini-3.1-pro-preview',
|
||
'gemini-3.1-pro-low': 'gemini-3.1-pro-preview',
|
||
'gemini-3-flash-agent': 'gemini-3-flash-preview',
|
||
'gemini-3.5-flash-high': 'gemini-3.5-flash',
|
||
'gemini-3.5-flash-medium': 'gemini-3.5-flash',
|
||
'gemini-3.5-flash-low': 'gemini-3.5-flash',
|
||
'Gemini 3.5 Flash (High)': 'gemini-3.5-flash',
|
||
'Gemini 3.5 Flash (Medium)': 'gemini-3.5-flash',
|
||
'Gemini 3.5 Flash (Low)': 'gemini-3.5-flash',
|
||
'gemini-3-pro': 'gemini-3-pro-preview',
|
||
'gemini-3.1-flash-image': 'gemini-3.1-flash-image-preview',
|
||
'gemini-3.1-flash-lite': 'gemini-3.1-flash-lite-preview',
|
||
// ZCode reports GLM-5.2/5.3 capitalized; Hermes/Cline use lowercase. The
|
||
// snapshot's bare `glm-5.2`/`glm-5.3` rows carry the LIST rate ($1.4/$4.4);
|
||
// z.ai's own `z-ai/glm-5.2`/`z-ai/glm-5.3` rows are the discounted rate we
|
||
// actually pay. Point every spelling at the z-ai rows.
|
||
'glm-5.2': 'z-ai/glm-5.2',
|
||
'GLM-5.2': 'z-ai/glm-5.2',
|
||
'glm-5.3': 'z-ai/glm-5.3',
|
||
'GLM-5.3': 'z-ai/glm-5.3',
|
||
}
|
||
|
||
let userAliases: Record<string, string> = {}
|
||
let userPriceOverrides: Map<string, ModelCosts> = new Map()
|
||
let userPriceOverridesConfig: Record<string, PriceOverrideRates> = {}
|
||
let sortedPriceOverrideKeys: string[] | null = null
|
||
let lowercasePriceOverrideIndex: Map<string, ModelCosts> | null = null
|
||
|
||
// Called once during CLI startup after config is loaded.
|
||
// User aliases take precedence over built-ins.
|
||
export function setModelAliases(aliases: Record<string, string>): void {
|
||
userAliases = aliases
|
||
}
|
||
|
||
function priceOverrideRatePerToken(usdPerMillion: number | undefined): number | null {
|
||
if (typeof usdPerMillion !== 'number') return null
|
||
return safePerTokenRate(usdPerMillion / 1_000_000)
|
||
}
|
||
|
||
// Called once during CLI startup after config is loaded.
|
||
// Config/CLI rates are USD per 1,000,000 tokens; ModelCosts stores USD/token.
|
||
export function setPriceOverrides(overrides: Record<string, PriceOverrideRates>): void {
|
||
const next = new Map<string, ModelCosts>()
|
||
const nextConfig: Record<string, PriceOverrideRates> = {}
|
||
for (const [model, rates] of Object.entries(overrides)) {
|
||
if (!model || !rates || typeof rates !== 'object') continue
|
||
nextConfig[model] = { ...rates }
|
||
const input = priceOverrideRatePerToken(rates.input)
|
||
const output = priceOverrideRatePerToken(rates.output)
|
||
if (input === null || output === null) continue
|
||
next.set(model, buildCosts(
|
||
input,
|
||
output,
|
||
priceOverrideRatePerToken(rates.cacheCreation),
|
||
priceOverrideRatePerToken(rates.cacheRead),
|
||
undefined,
|
||
))
|
||
}
|
||
userPriceOverrides = next
|
||
userPriceOverridesConfig = nextConfig
|
||
sortedPriceOverrideKeys = null
|
||
lowercasePriceOverrideIndex = null
|
||
}
|
||
|
||
function getSortedPriceOverrideKeys(): string[] {
|
||
if (sortedPriceOverrideKeys === null) {
|
||
sortedPriceOverrideKeys = Array.from(userPriceOverrides.keys()).sort((a, b) => b.length - a.length)
|
||
}
|
||
return sortedPriceOverrideKeys
|
||
}
|
||
|
||
function getLowercasePriceOverrideIndex(): Map<string, ModelCosts> {
|
||
if (lowercasePriceOverrideIndex === null) {
|
||
lowercasePriceOverrideIndex = new Map()
|
||
for (const [key, costs] of userPriceOverrides) {
|
||
const lk = key.toLowerCase()
|
||
if (!lowercasePriceOverrideIndex.has(lk)) lowercasePriceOverrideIndex.set(lk, costs)
|
||
}
|
||
}
|
||
return lowercasePriceOverrideIndex
|
||
}
|
||
|
||
function getPriceOverrideExact(...keys: string[]): ModelCosts | null {
|
||
for (const key of keys) {
|
||
const costs = userPriceOverrides.get(key)
|
||
if (costs) return costs
|
||
}
|
||
return null
|
||
}
|
||
|
||
function getPriceOverridePrefix(canonical: string): ModelCosts | null {
|
||
for (const key of getSortedPriceOverrideKeys()) {
|
||
if (canonical.startsWith(key + '-') || canonical === key) {
|
||
return userPriceOverrides.get(key)!
|
||
}
|
||
}
|
||
return null
|
||
}
|
||
|
||
function getPriceOverrideCaseInsensitive(canonical: string, withPrefix: string): ModelCosts | null {
|
||
const lowerIndex = getLowercasePriceOverrideIndex()
|
||
return lowerIndex.get(canonical.toLowerCase()) ?? lowerIndex.get(withPrefix.toLowerCase()) ?? null
|
||
}
|
||
|
||
// Local-model savings config. Kept separate from userAliases: a `modelAliases`
|
||
// entry rewrites a model's identity for actual cost; a `localModelSavings`
|
||
// entry keeps the model cost at $0 and reports the *avoided* spend against a
|
||
// paid baseline. Set during preAction from `config.localModelSavings`.
|
||
let userLocalModelSavings: Record<string, string> = {}
|
||
|
||
export function setLocalModelSavings(mappings: Record<string, string>): void {
|
||
userLocalModelSavings = { ...mappings }
|
||
}
|
||
|
||
export function getLocalSavingsBaseline(rawModel: string): string | undefined {
|
||
if (!rawModel || typeof rawModel !== 'string') return undefined
|
||
// Defensive: bracket-accessing user-controlled keys on a plain object
|
||
// exposes the prototype chain (`__proto__` would resolve to Object.prototype).
|
||
// Use Object.hasOwn so a hostile JSONL model name cannot piggyback into
|
||
// Object.prototype either through the alias map or here.
|
||
if (!Object.hasOwn(userLocalModelSavings, rawModel)) return undefined
|
||
return userLocalModelSavings[rawModel]
|
||
}
|
||
|
||
/// Compute the hypothetical baseline cost for a local call. The baseline
|
||
/// model is priced through the normal `calculateCost` pipeline (so it can
|
||
/// be aliased / canonicalized). Returns `null` when the source model has
|
||
/// no savings mapping, the baseline is unknown to the pricing snapshot, or
|
||
/// any input is unusable — callers should treat null as "no savings
|
||
/// recorded for this call" rather than a hard error.
|
||
export function calculateLocalModelSavings(
|
||
rawModel: string,
|
||
inputTokens: number,
|
||
outputTokens: number,
|
||
cacheCreationTokens: number,
|
||
cacheReadTokens: number,
|
||
webSearchRequests: number,
|
||
speed: 'standard' | 'fast' = 'standard',
|
||
oneHourCacheCreationTokens = 0,
|
||
): { savingsUSD: number; baselineModel: string } | null {
|
||
const baseline = getLocalSavingsBaseline(rawModel)
|
||
if (!baseline) return null
|
||
if (!getModelCosts(baseline)) return null
|
||
const savingsUSD = calculateCost(
|
||
baseline,
|
||
inputTokens,
|
||
outputTokens,
|
||
cacheCreationTokens,
|
||
cacheReadTokens,
|
||
webSearchRequests,
|
||
speed,
|
||
oneHourCacheCreationTokens,
|
||
)
|
||
return { savingsUSD, baselineModel: baseline }
|
||
}
|
||
|
||
/// Stable hash of the current savings config so the daily cache can detect
|
||
/// "user changed their baseline mapping" and rebuild instead of presenting
|
||
/// stale saved-spend numbers. Two configs with the same key→baseline pairs
|
||
/// in any order collapse to the same hash.
|
||
export function getLocalModelSavingsConfigHash(): string {
|
||
const keys = Object.keys(userLocalModelSavings).sort()
|
||
if (keys.length === 0) return ''
|
||
const parts = keys.map(k => `${k}\u0001${userLocalModelSavings[k]}`)
|
||
return parts.join('\u0002')
|
||
}
|
||
|
||
// Subscription / flat-rate product SKUs. $0 is the correct cost; aliasing
|
||
// them onto a per-token row fabricates spend (#968). Distinct from
|
||
// model-savings (counterfactual local baseline) and from a zero-rate
|
||
// price-override (user-declared free). Built-in families plus a user hatch.
|
||
let userFlatRateModels = new Set<string>()
|
||
let userFlatRateLeaves = new Set<string>()
|
||
let userFlatRateRemoved = new Set<string>()
|
||
let userFlatRateRemovedLeaves = new Set<string>()
|
||
|
||
function flatRateLeaf(model: string): string {
|
||
const trimmed = model.trim().replace(/@.*$/, '').replace(/-\d{8}$/, '')
|
||
const leaf = trimmed.includes('/') ? trimmed.slice(trimmed.lastIndexOf('/') + 1) : trimmed
|
||
return leaf.toLowerCase()
|
||
}
|
||
|
||
function fillFlatRateSet(
|
||
models: Iterable<string>,
|
||
): { ids: Set<string>; leaves: Set<string> } {
|
||
const ids = new Set<string>()
|
||
const leaves = new Set<string>()
|
||
for (const model of models) {
|
||
if (!model || typeof model !== 'string') continue
|
||
ids.add(model)
|
||
const leaf = flatRateLeaf(model)
|
||
if (leaf) leaves.add(leaf)
|
||
}
|
||
return { ids, leaves }
|
||
}
|
||
|
||
export function setFlatRateModels(models: Iterable<string>): void {
|
||
const filled = fillFlatRateSet(models)
|
||
userFlatRateModels = filled.ids
|
||
userFlatRateLeaves = filled.leaves
|
||
}
|
||
|
||
export function setFlatRateRemoved(models: Iterable<string>): void {
|
||
const filled = fillFlatRateSet(models)
|
||
userFlatRateRemoved = filled.ids
|
||
userFlatRateRemovedLeaves = filled.leaves
|
||
}
|
||
|
||
export function getFlatRateModelsConfigHash(): string {
|
||
const added = [...userFlatRateModels].sort().join('\u0002')
|
||
const removed = [...userFlatRateRemoved].sort().join('\u0002')
|
||
if (!removed) return added
|
||
return `${added}\u0003${removed}`
|
||
}
|
||
|
||
export function getFlatRateModels(): string[] {
|
||
return [...userFlatRateModels]
|
||
}
|
||
|
||
export function getFlatRateRemoved(): string[] {
|
||
return [...userFlatRateRemoved]
|
||
}
|
||
|
||
export function isSameFlatRateModel(a: string, b: string): boolean {
|
||
if (!a || !b) return false
|
||
if (a === b) return true
|
||
const leaf = flatRateLeaf(a)
|
||
return leaf.length > 0 && leaf === flatRateLeaf(b)
|
||
}
|
||
|
||
function isUserFlatRateModel(model: string): boolean {
|
||
if (userFlatRateModels.has(model)) return true
|
||
const leaf = flatRateLeaf(model)
|
||
return leaf.length > 0 && userFlatRateLeaves.has(leaf)
|
||
}
|
||
|
||
function isFlatRateRemoved(model: string): boolean {
|
||
if (userFlatRateRemoved.has(model)) return true
|
||
const leaf = flatRateLeaf(model)
|
||
return leaf.length > 0 && userFlatRateRemovedLeaves.has(leaf)
|
||
}
|
||
|
||
/// Product SKUs billed as a subscription, not missing LiteLLM rows.
|
||
/// Match raw ids and path-prefixed ids (`cline-pass/auto-genius`). Display
|
||
/// names from getShortModelName are matched only when the aggregation key
|
||
/// is not the raw leaf (Warp Auto *, Grok Composer *).
|
||
export function isBuiltInFlatRateModel(model: string): boolean {
|
||
const leaf = flatRateLeaf(model)
|
||
// Warp's product SKU is the bare id `auto`. Kiro rewrites its own `auto`
|
||
// to `kiro-auto` before pricing, so this leaf does not swallow Kiro.
|
||
if (
|
||
leaf === 'auto'
|
||
|| leaf === 'auto-genius'
|
||
|| leaf === 'kimi-for-coding-highspeed'
|
||
) return true
|
||
if (leaf.startsWith('grok-composer-')) return true
|
||
if (leaf.startsWith('warp-auto-')) return true
|
||
const display = model.trim()
|
||
if (/^grok composer\b/i.test(display)) return true
|
||
if (/^warp auto\b/i.test(display)) return true
|
||
return false
|
||
}
|
||
|
||
export function isFlatRateModel(model: string): boolean {
|
||
if (!model) return false
|
||
if (isFlatRateRemoved(model)) return false
|
||
return isUserFlatRateModel(model) || isBuiltInFlatRateModel(model)
|
||
}
|
||
|
||
/// Shared unpriced-warning copy. Never tell the user to alias unconditionally:
|
||
/// mapping a subscription SKU onto a priced row invents spend. Optional `model`
|
||
/// interpolates the sanitized id so the verbose calculateCost path names the
|
||
/// same two hatches.
|
||
export function unpricedModelHint(model = '<model>'): string {
|
||
const safe = model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200)
|
||
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}".`
|
||
}
|
||
|
||
/// Stable hash of the model-alias map, for the same staleness class as the
|
||
/// hashes below: a resident process (codeburn serve) must not serve memoized
|
||
/// parse results priced under aliases the user has since changed.
|
||
export function getModelAliasesConfigHash(): string {
|
||
const keys = Object.keys(userAliases).sort()
|
||
if (keys.length === 0) return ''
|
||
return keys.map(k => `${k}\u0001${userAliases[k]}`).join('\u0002')
|
||
}
|
||
|
||
export function getPriceOverridesConfigHash(): string {
|
||
// The builtin overrides participate so editing BUILTIN_PRICE_OVERRIDES in a
|
||
// release invalidates cached daily costs the same way a user override does.
|
||
const builtin = `builtin:${JSON.stringify(BUILTIN_PRICE_OVERRIDES)}`
|
||
const keys = Object.keys(userPriceOverridesConfig).sort()
|
||
if (keys.length === 0) return builtin
|
||
const parts = keys.map(k => {
|
||
const rates = userPriceOverridesConfig[k]
|
||
return [
|
||
k,
|
||
rates.input,
|
||
rates.output,
|
||
rates.cacheRead ?? '',
|
||
rates.cacheCreation ?? '',
|
||
].join('\u0001')
|
||
})
|
||
return [builtin, ...parts].join('\u0002')
|
||
}
|
||
|
||
// Absolute directory prefixes whose sessions are routed through a
|
||
// subscription-backed proxy (config `proxyPaths`). Stored already-normalized so
|
||
// the per-project match is a cheap compare. Set during preAction. See
|
||
// CodeburnConfig.proxyPaths for the product rationale.
|
||
let userProxyPaths: string[] = []
|
||
|
||
/// Normalize a path for prefix comparison: backslashes -> forward slashes
|
||
/// (Windows configs / cwds), strip leading AND trailing slashes, fold case on
|
||
/// case-insensitive filesystems. Leading slashes are stripped because provider
|
||
/// project paths arrive in two forms — Claude keeps the absolute "/Users/x"
|
||
/// while Codex (sanitizeProject) and the unsanitizePath fallback drop the
|
||
/// leading slash to "Users/x". Folding both to a slashless form (mirroring
|
||
/// crossProviderKey) makes matching agnostic to which provider produced the
|
||
/// path, so the same directory is flagged whether or not a Claude session
|
||
/// happens to co-exist there. Case is folded only on macOS/Windows; on Linux
|
||
/// "/home/Me" and "/home/me" are different dirs, so folding would risk
|
||
/// crediting unrelated spend. A path that normalizes to empty (e.g. "/" or "")
|
||
/// is dropped by callers so it can never match everything. Exported so the CLI
|
||
/// dedupes with the same rule.
|
||
export function normalizeProxyPath(p: string): string {
|
||
const s = p.trim().replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+$/, '')
|
||
return (process.platform === 'darwin' || process.platform === 'win32') ? s.toLowerCase() : s
|
||
}
|
||
|
||
export function setProxyPaths(paths: string[]): void {
|
||
userProxyPaths = (Array.isArray(paths) ? paths : [])
|
||
.filter((p): p is string => typeof p === 'string')
|
||
.map(normalizeProxyPath)
|
||
.filter(p => p !== '')
|
||
}
|
||
|
||
/// True when `cwd` is at or under a configured proxy path. Prefix match is
|
||
/// anchored to a path-segment boundary so "/a/proj" matches "/a/proj" and
|
||
/// "/a/proj/sub" but NOT "/a/project-x". Empty/undefined cwd or empty config
|
||
/// never matches (so a misconfig can't silently zero unrelated spend).
|
||
export function isProxiedPath(cwd: string | undefined | null): boolean {
|
||
if (!cwd || typeof cwd !== 'string') return false
|
||
if (userProxyPaths.length === 0) return false
|
||
const c = normalizeProxyPath(cwd)
|
||
if (c === '') return false
|
||
return userProxyPaths.some(p => c === p || c.startsWith(p + '/'))
|
||
}
|
||
|
||
/// Stable hash of the active proxy-path config. Project-level proxy attribution
|
||
/// is computed live from this set and then cached in the in-memory session
|
||
/// cache, so the cache key must vary with it — otherwise a long-lived process
|
||
/// (menubar) that re-reads config could serve attribution from a stale set.
|
||
export function getProxyPathsConfigHash(): string {
|
||
if (userProxyPaths.length === 0) return ''
|
||
return [...userProxyPaths].sort().join('')
|
||
}
|
||
|
||
function resolveAlias(model: string): string {
|
||
if (Object.hasOwn(userAliases, model)) return userAliases[model]!
|
||
if (Object.hasOwn(BUILTIN_ALIASES, model)) return BUILTIN_ALIASES[model]!
|
||
const lowercase = model.toLowerCase()
|
||
if (lowercase !== model && Object.hasOwn(BUILTIN_ALIASES, lowercase)) return BUILTIN_ALIASES[lowercase]!
|
||
return model
|
||
}
|
||
function getCanonicalName(model: string): string {
|
||
const cleaned = model
|
||
.replace(/@.*$/, '')
|
||
.replace(/-\d{8}$/, '')
|
||
.replace(/\[[^\]]*\]$/, '')
|
||
// Full-id aliases (orcarouter/fusion) must stay visible so resolveAlias can
|
||
// see them. Stripping first would leave a leaf (`fusion`) with no mapping.
|
||
// Nested wrappers without an alias still peel as before.
|
||
if (Object.hasOwn(userAliases, cleaned) || Object.hasOwn(BUILTIN_ALIASES, cleaned)) {
|
||
return cleaned
|
||
}
|
||
const lowercase = cleaned.toLowerCase()
|
||
if (lowercase !== cleaned && Object.hasOwn(BUILTIN_ALIASES, lowercase)) {
|
||
return cleaned
|
||
}
|
||
return stripKnownFirstNamespace(cleaned)
|
||
}
|
||
|
||
/// Alias-resolved identity for report merge. Display names stay cosmetic —
|
||
/// prefix matches in SHORT_NAMES must not fold distinct SKUs into one row.
|
||
/// Path-form ids (`accounts/fireworks/models/<slug>`, `cline-pass/<slug>`)
|
||
/// peel to the leaf so they share a bucket with the bare slug.
|
||
export function resolveCanonicalModelId(model: string): string {
|
||
const viaUser = Object.hasOwn(userAliases, model) ? userAliases[model]! : model
|
||
const aliased = resolveAlias(getCanonicalName(viaUser))
|
||
if (!aliased.includes('/')) return aliased
|
||
const leaf = aliased.slice(aliased.lastIndexOf('/') + 1)
|
||
if (!leaf) return aliased
|
||
return resolveAlias(getCanonicalName(leaf))
|
||
}
|
||
|
||
// Namespaces the pricing catalog itself uses, plus the ones below. An unknown
|
||
// `provider/model` must stay unpriced — do not treat `/` as authority. Derived
|
||
// rather than hand-listed so a vendor LiteLLM already knows (`x-ai/`, `qwen/`,
|
||
// `nousresearch/`, …) is never dropped by a stale list.
|
||
const EXTRA_NAMESPACES = [
|
||
// Routing wrappers (see ROUTER_PREFIXES); no catalog lists them. `cliproxy/`
|
||
// is codex-cliproxy-gateway's default route prefix over CLIProxyAPI.
|
||
'cp', 'cline-pass', 'cline-free', 'cmd', 'antigravity', 'orcarouter', 'cliproxy',
|
||
// LiteLLM route prefixes that never appear as a key prefix.
|
||
'litellm_proxy', 'openai_like',
|
||
// Vendor spellings the catalog indexes under another name: `zhipu` is `z-ai`,
|
||
// `mimo` is `xiaomi` (BUILTIN_ALIASES maps the bare MiMo ids to `xiaomi/`),
|
||
// and `kimi/` is a client-side prefix (Codex records `kimi/k3[1m]`).
|
||
// `zcode/` is CLIProxyAPI's provider spelling for the Z.ai coding plans; the
|
||
// bare `glm-*` leaf already prices via its own catalog row, which carries an explicit zero cache-write cost.
|
||
'zhipu', 'mimo', 'kimi', 'zcode',
|
||
]
|
||
|
||
// Local runners. Their catalog rows are $0 stubs, so an unlisted local tag must
|
||
// not strip down to a priced cloud row and invent spend (#968).
|
||
const LOCAL_NAMESPACES = ['ollama']
|
||
|
||
let knownNamespaces: Set<string> | null = null
|
||
|
||
function getKnownNamespaces(): Set<string> {
|
||
if (knownNamespaces) return knownNamespaces
|
||
const set = new Set(EXTRA_NAMESPACES)
|
||
for (const keys of [pricingCache.keys(), fallbackCosts.keys()]) {
|
||
for (const key of keys) {
|
||
const idx = key.indexOf('/')
|
||
if (idx > 0) set.add(key.slice(0, idx).toLowerCase())
|
||
}
|
||
}
|
||
for (const local of LOCAL_NAMESPACES) set.delete(local)
|
||
knownNamespaces = set
|
||
return set
|
||
}
|
||
|
||
function stripKnownFirstNamespace(model: string): string {
|
||
const idx = model.indexOf('/')
|
||
if (idx <= 0) return model
|
||
const head = model.slice(0, idx).toLowerCase()
|
||
if (getKnownNamespaces().has(head)) return model.slice(idx + 1)
|
||
return model
|
||
}
|
||
|
||
// Routing wrappers (OmniRoute, Cline Pass, cmd/, …) are not model ids.
|
||
// Peel them so any plan/gateway spelling of the same model shares one price.
|
||
// OrcaRouter is a gateway that routes to many vendors. Its catalog exposes
|
||
// route ids (`orcarouter/auto`, `orcarouter/fusion`, …) and plain vendor ids
|
||
// (`deepseek/deepseek-v4-pro`); a route id can also spell a nested upstream
|
||
// (`orcarouter/deepseek/deepseek-v4-pro`), and the completion response's
|
||
// `model` field reports the upstream id that actually ran. Peeling the prefix
|
||
// lets every routed spelling price at the upstream row.
|
||
const ROUTER_PREFIXES = [
|
||
/^omniroute:/i,
|
||
/^cp\//i,
|
||
/^cline-pass\//i,
|
||
/^cline-free\//i,
|
||
/^cmd\//i,
|
||
/^antigravity\//i,
|
||
/^orcarouter\//i,
|
||
// codex-cliproxy-gateway keeps Codex's own OAuth routing native and forwards
|
||
// only `cliproxy/*` ids to CLIProxyAPI, so a routed session records
|
||
// `cliproxy/<id>` — and `<id>` can itself be a provider path
|
||
// (`cliproxy/zcode/glm-5.3-flash`). Peeling the wrapper lets the one
|
||
// known-namespace strip in getCanonicalName reach the priced leaf.
|
||
/^cliproxy\//i,
|
||
// `xiaomi/` is NOT peeled: it is the vendor namespace LiteLLM prices under,
|
||
// and BUILTIN_ALIASES maps the bare MiMo ids INTO it. Peeling would pull the
|
||
// opposite way. It stays a known namespace via the catalog-derived set.
|
||
]
|
||
|
||
function routedModelCandidates(model: string): string[] {
|
||
const ids: string[] = []
|
||
const seen = new Set<string>()
|
||
const push = (value: string) => {
|
||
if (!value || seen.has(value)) return
|
||
seen.add(value)
|
||
ids.push(value)
|
||
}
|
||
push(model)
|
||
let current = model
|
||
let peeled = true
|
||
while (peeled) {
|
||
peeled = false
|
||
for (const prefix of ROUTER_PREFIXES) {
|
||
const next = current.replace(prefix, '')
|
||
if (next && next !== current) {
|
||
current = next
|
||
push(current)
|
||
peeled = true
|
||
}
|
||
}
|
||
}
|
||
// One known-vendor strip only (anthropic/foo → foo). Unknown
|
||
// provider/model trees stay intact and therefore unpriced.
|
||
push(getCanonicalName(current))
|
||
return ids
|
||
}
|
||
|
||
function stripKnownPricingVariantSuffix(model: string): string | null {
|
||
const withoutColonSuffix = model.replace(/:(thinking|cloud)$/i, '')
|
||
if (withoutColonSuffix !== model) return withoutColonSuffix
|
||
|
||
const withoutTeeSuffix = model.replace(/-TEE$/i, '')
|
||
if (withoutTeeSuffix !== model) return withoutTeeSuffix
|
||
|
||
return null
|
||
}
|
||
|
||
export function getModelCosts(model: string): ModelCosts | null {
|
||
// Try with provider prefix preserved (azure/gpt-5.4, openrouter/anthropic/claude-opus-4.6)
|
||
const withPrefix = model.replace(/@.*$/, '').replace(/-\d{8}$/, '')
|
||
const canonicalName = getCanonicalName(model)
|
||
const canonical = resolveAlias(canonicalName)
|
||
|
||
const override = getPriceOverrideExact(model, withPrefix, canonicalName, canonical)
|
||
if (override) return override
|
||
|
||
// An explicit alias for a bare (un-prefixed) model name is authoritative: it
|
||
// must win over a coincidental stripped reseller key of the same name. LiteLLM
|
||
// ships `snowflake/claude-4-opus` ($5), which the bundler strips to a bare
|
||
// `claude-4-opus` key; without this, that would shadow the curated alias
|
||
// `claude-4-opus -> claude-opus-4` ($15 official Anthropic price).
|
||
if (canonical !== canonicalName && withPrefix === canonicalName && pricingCache.has(canonical)) {
|
||
return pricingCache.get(canonical)!
|
||
}
|
||
|
||
if (pricingCache.has(withPrefix)) return pricingCache.get(withPrefix)!
|
||
|
||
if (pricingCache.has(canonical)) return pricingCache.get(canonical)!
|
||
|
||
for (const candidate of routedModelCandidates(model)) {
|
||
const aliased = resolveAlias(candidate)
|
||
// A user's declared price for the bare id must win over the catalog row a
|
||
// routed spelling of it would otherwise hit.
|
||
const candidateOverride = getPriceOverrideExact(candidate, aliased)
|
||
if (candidateOverride) return candidateOverride
|
||
if (pricingCache.has(aliased)) return pricingCache.get(aliased)!
|
||
if (pricingCache.has(candidate)) return pricingCache.get(candidate)!
|
||
}
|
||
|
||
const prefixOverride = getPriceOverridePrefix(canonical)
|
||
if (prefixOverride) return prefixOverride
|
||
|
||
// Iterate keys longest-first so a model id like `gpt-5-mini` matches the
|
||
// `gpt-5-mini` entry rather than collapsing to the shorter `gpt-5` entry
|
||
// due to dictionary insertion order.
|
||
for (const key of getSortedPricingKeys()) {
|
||
if (canonical.startsWith(key + '-') || canonical === key) {
|
||
return pricingCache.get(key)!
|
||
}
|
||
}
|
||
|
||
const caseInsensitiveOverride = getPriceOverrideCaseInsensitive(canonical, withPrefix)
|
||
if (caseInsensitiveOverride) return caseInsensitiveOverride
|
||
|
||
// Case-insensitive fallback: gap-filled keys from OpenRouter are lowercase
|
||
// slugs (e.g. `minimax-m3`), but sessions report `MiniMax-M3`. Only consulted
|
||
// after the exact/canonical/prefix attempts, so it never changes a match that
|
||
// already resolved above.
|
||
const lowerIndex = getLowercasePricingIndex()
|
||
const byCanonical = lowerIndex.get(canonical.toLowerCase())
|
||
if (byCanonical) return byCanonical
|
||
const byPrefix = lowerIndex.get(withPrefix.toLowerCase())
|
||
if (byPrefix) return byPrefix
|
||
|
||
const withPrefixVariant = stripKnownPricingVariantSuffix(withPrefix)
|
||
if (withPrefixVariant && withPrefixVariant !== withPrefix) {
|
||
const variantCosts = getModelCosts(withPrefixVariant)
|
||
if (variantCosts) return variantCosts
|
||
}
|
||
|
||
const canonicalVariant = stripKnownPricingVariantSuffix(canonical)
|
||
if (canonicalVariant && canonicalVariant !== canonical && canonicalVariant !== withPrefixVariant) {
|
||
const variantCosts = getModelCosts(canonicalVariant)
|
||
if (variantCosts) return variantCosts
|
||
}
|
||
|
||
return null
|
||
}
|
||
|
||
// Warn at most once per unknown model name per process. Without this, a model
|
||
// missing from the pricing snapshot would silently price at $0 for every
|
||
// session that used it, hiding real spend until the user noticed.
|
||
const warnedUnknownModels = new Set<string>()
|
||
|
||
/// Heuristic for "this looks like a local model that will never be in LiteLLM's
|
||
/// pricing JSON". We suppress the unknown-model warning for these because the
|
||
/// "update codeburn" advice can't help — local Ollama models, llama.cpp tags,
|
||
/// LM Studio loads, etc. are billed locally and don't have public pricing.
|
||
/// Users still get $0 in cost reports for them (correct — local inference is
|
||
/// effectively free); the warning was just noise.
|
||
function looksLikeLocalModel(name: string): boolean {
|
||
// Bedrock foundation-model ids end in a `-[v]<major>:<minor>` version
|
||
// (`anthropic.claude-haiku-4-5-20251001-v1:0`, `openai.gpt-oss-120b-1:0`).
|
||
// That colon is a version, not an Ollama tag: such a model is metered, and
|
||
// one with no price must reach the unpriced list rather than be treated as
|
||
// free local inference.
|
||
if (/-v?\d+:\d+$/.test(name)) return false
|
||
// Bedrock provisioned-model / custom-model ARNs carry colons from the ARN
|
||
// structure (arn:aws:bedrock:<region>:<account>:provisioned-model/<id>), but
|
||
// they are metered Bedrock, not local: an unpriced one must reach the
|
||
// unpriced list rather than be hidden as free local inference.
|
||
if (/^arn:aws:bedrock:/i.test(name)) return false
|
||
// Ollama and LM Studio tags include `:tag` (e.g. qwen3.6:35b-a3b-bf16).
|
||
if (name.includes(':') && !name.startsWith('http')) return true
|
||
// GGUF / quantized fingerprints commonly seen in local inference.
|
||
if (/[-_](q[2-8](_[a-z0-9]+)?|bf16|fp16|gguf|f16|f32)$/i.test(name)) return true
|
||
return false
|
||
}
|
||
|
||
export interface UnpricedModelUsage {
|
||
model: string
|
||
calls: number
|
||
tokens: number
|
||
}
|
||
|
||
function hasBillableRate(costs: ModelCosts): boolean {
|
||
return costs.inputCostPerToken > 0
|
||
|| costs.outputCostPerToken > 0
|
||
|| costs.cacheWriteCostPerToken > 0
|
||
|| costs.cacheReadCostPerToken > 0
|
||
}
|
||
|
||
// Exact-override lookup with the same key derivation getModelCosts uses. Lets
|
||
// the unpriced detector distinguish "explicitly declared free by the user" (a
|
||
// zero-rate override) from a zero-rate LiteLLM stub, which means "listed but
|
||
// unknown price" and must still be flagged. Only the EXACT override form is
|
||
// consulted: getModelCosts checks it before any table hit, so when one exists
|
||
// it is provably what priced the model. Prefix and case-insensitive overrides
|
||
// resolve AFTER table hits and so cannot prove the $0 was intentional; a
|
||
// zero-rate stub shadowed by one still gets flagged (the honest direction).
|
||
function exactPriceOverrideFor(model: string): ModelCosts | null {
|
||
const withPrefix = model.replace(/@.*$/, '').replace(/-\d{8}$/, '')
|
||
const canonicalName = getCanonicalName(model)
|
||
const canonical = resolveAlias(canonicalName)
|
||
return getPriceOverrideExact(model, withPrefix, canonicalName, canonical)
|
||
}
|
||
|
||
// Render-time unpriced detection (#638): flag aggregated model rows that carry
|
||
// usage but $0 cost AND whose pricing lookup yields no billable rate right
|
||
// now. Cost is computed at parse time and cached, so a parse-time registry
|
||
// would miss cached sessions; a render-time check covers both and heals the
|
||
// moment pricing data, an alias, or a price override arrives.
|
||
//
|
||
// Rows with cost > 0 are never flagged: aggregation keys rows by DISPLAY name
|
||
// (parser.ts keys modelBreakdown via getShortModelName), which the pricing
|
||
// lookup misses, so a priced model like "Opus 4.8" would otherwise false-flag.
|
||
// $0 display-name rows ARE flagged even when the raw id would price today:
|
||
// those tokens really did enter the report at $0 (a provider priced a
|
||
// transformed name, or the session was cached before its model's pricing
|
||
// landed). Conservative by design: a display key merging priced and unpriced
|
||
// raw ids carries cost > 0 and is not flagged. Local-looking models and
|
||
// models with a local-savings mapping are excluded because $0 is their
|
||
// correct cost, as are zero-rate USER overrides (explicitly declared free).
|
||
/// Models whose $0 cost is CORRECT rather than a pricing gap, mirroring the
|
||
/// exclusions findUnpricedModels applies: local-looking models, models mapped
|
||
/// to a local-savings baseline, subscription / flat-rate product SKUs, and
|
||
/// models an exact zero-rate user override declares free. Used to keep their
|
||
/// calls out of the pricing-coverage denominator — otherwise a 95%-ollama
|
||
/// user reads high coverage while every genuinely cost-bearing call is unpriced.
|
||
export function isExpectedFreeModel(model: string): boolean {
|
||
if (looksLikeLocalModel(model)) return true
|
||
if (getLocalSavingsBaseline(model)) return true
|
||
const costs = getModelCosts(model)
|
||
// A builtin/user alias can still attach a billable rate to a subscription
|
||
// SKU (warp-auto-* today). Those calls are priced, so they stay in the
|
||
// coverage denominator. Only the $0 / no-rate case is expected-free.
|
||
if (isFlatRateModel(model) && (!costs || !hasBillableRate(costs))) return true
|
||
if (costs && !hasBillableRate(costs) && exactPriceOverrideFor(model)) return true
|
||
return false
|
||
}
|
||
|
||
export function findUnpricedModels(
|
||
rows: Iterable<{ model: string; calls: number; cost: number; tokens?: number }>,
|
||
): UnpricedModelUsage[] {
|
||
const out: UnpricedModelUsage[] = []
|
||
for (const row of rows) {
|
||
const { model } = row
|
||
const tokens = row.tokens ?? 0
|
||
if (!model || model === '<synthetic>') continue
|
||
if (row.calls <= 0 && tokens <= 0) continue
|
||
if (row.cost > 0) continue
|
||
if (looksLikeLocalModel(model)) continue
|
||
if (getLocalSavingsBaseline(model)) continue
|
||
if (isFlatRateModel(model)) continue
|
||
const costs = getModelCosts(model)
|
||
if (costs && hasBillableRate(costs)) continue
|
||
if (costs && exactPriceOverrideFor(model)) continue
|
||
out.push({ model, calls: row.calls, tokens })
|
||
}
|
||
return out.sort((a, b) => (b.tokens - a.tokens) || (b.calls - a.calls)
|
||
|| (a.model < b.model ? -1 : a.model > b.model ? 1 : 0))
|
||
}
|
||
|
||
function shouldWarnAboutUnknownModel(name: string): boolean {
|
||
if (!name || name === '<synthetic>') return false
|
||
if (warnedUnknownModels.has(name)) return false
|
||
// Suppress for local/quantized models — the "update codeburn" hint is
|
||
// actively misleading there. Users who need cost visibility for local
|
||
// inference can still set an alias via `codeburn model-alias`.
|
||
if (looksLikeLocalModel(name)) return false
|
||
if (isFlatRateModel(name)) return false
|
||
// The warning fired on every CLI invocation (including the default
|
||
// dashboard) which made first launches look broken — three "no pricing
|
||
// data" lines greet a user before the dashboard even draws. Now opt-in
|
||
// via --verbose. The unknown model still costs $0 in reports; users who
|
||
// suspect missing models run `codeburn --verbose` to see the list.
|
||
if (process.env['CODEBURN_VERBOSE'] !== '1') return false
|
||
return true
|
||
}
|
||
|
||
/** Render provider-supplied model IDs without terminal control characters. */
|
||
export function sanitizeModelForDisplay(model: string): string {
|
||
return model.replace(/[\x00-\x1F\x7F-\x9F]/g, '?').slice(0, 200)
|
||
}
|
||
|
||
export function calculateCost(
|
||
model: string,
|
||
inputTokens: number,
|
||
outputTokens: number,
|
||
cacheCreationTokens: number,
|
||
cacheReadTokens: number,
|
||
webSearchRequests: number,
|
||
speed: 'standard' | 'fast' = 'standard',
|
||
oneHourCacheCreationTokens = 0,
|
||
): number {
|
||
const costs = getModelCosts(model)
|
||
if (!costs) {
|
||
if (shouldWarnAboutUnknownModel(model)) {
|
||
warnedUnknownModels.add(model)
|
||
// Strip control characters and cap length: model names come from JSONL
|
||
// payloads written by external tools, so a hostile or corrupt file
|
||
// could embed terminal escape sequences here.
|
||
const safeName = sanitizeModelForDisplay(model)
|
||
process.stderr.write(
|
||
`codeburn: no pricing data for model "${safeName}" — costs for this model will show $0. ` +
|
||
`${unpricedModelHint(safeName)} Or track local-model savings with: codeburn model-savings "${safeName}" <baseline-model>, or update with: npx codeburn@latest.\n`,
|
||
)
|
||
}
|
||
return 0
|
||
}
|
||
|
||
const safe = (n: number) => (Number.isFinite(n) && n > 0 ? n : 0)
|
||
const safeOneHourCacheCreation = safe(oneHourCacheCreationTokens)
|
||
const safeCacheCreation = Math.max(safe(cacheCreationTokens), safeOneHourCacheCreation)
|
||
const safeFiveMinuteCacheCreation = Math.max(0, safeCacheCreation - safeOneHourCacheCreation)
|
||
const promptTokens = safe(inputTokens) + safe(cacheReadTokens)
|
||
const tieredCosts = tieredCostsFor(model, costs, promptTokens)
|
||
const multiplier = speed === 'fast' ? tieredCosts.fastMultiplier : 1
|
||
|
||
// Clamp negative inputs to 0. A corrupt JSONL that emits a negative token
|
||
// count would otherwise produce a negative cost that silently subtracts
|
||
// from real spend in aggregate totals. NaN is also handled here; the
|
||
// arithmetic below short-circuits to 0 when any operand is non-finite.
|
||
return multiplier * (
|
||
safe(inputTokens) * tieredCosts.inputCostPerToken +
|
||
safe(outputTokens) * tieredCosts.outputCostPerToken +
|
||
safeFiveMinuteCacheCreation * tieredCosts.cacheWriteCostPerToken +
|
||
safeOneHourCacheCreation * tieredCosts.cacheWriteCostPerToken * ONE_HOUR_CACHE_WRITE_MULTIPLIER_FROM_FIVE_MINUTE_RATE +
|
||
safe(cacheReadTokens) * tieredCosts.cacheReadCostPerToken +
|
||
safe(webSearchRequests) * tieredCosts.webSearchCostPerRequest
|
||
)
|
||
}
|
||
|
||
const autoModelNames: Record<string, string> = {
|
||
'glm-5.2': 'GLM-5.2',
|
||
'GLM-5.2': 'GLM-5.2',
|
||
'glm-5.3': 'GLM-5.3',
|
||
'GLM-5.3': 'GLM-5.3',
|
||
'cursor-auto': 'Cursor (auto)',
|
||
'cursor-agent-auto': 'Cursor (auto)',
|
||
'copilot-auto': 'Copilot (auto)',
|
||
'copilot-openai-auto': 'Copilot (OpenAI)',
|
||
'copilot-anthropic-auto': 'Copilot (Anthropic)',
|
||
'ibm-bob-auto': 'IBM Bob (auto)',
|
||
'kiro-auto': 'Kiro (auto)',
|
||
'quickdesk-auto': 'Quick Desktop (auto)',
|
||
'grokbot-auto': 'Grok Bot (auto)',
|
||
'cline-auto': 'Cline (auto)',
|
||
'openclaw-auto': 'OpenClaw (auto)',
|
||
'qwen-auto': 'Qwen (auto)',
|
||
'kimi-auto': 'Kimi (auto)',
|
||
'codex-auto-review': 'Codex Auto Review',
|
||
}
|
||
|
||
const SHORT_NAMES: Record<string, string> = {
|
||
// Modern claude-<family>-<major>-<minor> ids are derived in deriveClaudeShortName.
|
||
// Only the legacy 3.x ids (family-last) need explicit mapping.
|
||
'claude-3-7-sonnet': 'Sonnet 3.7',
|
||
'claude-3-5-sonnet': 'Sonnet 3.5',
|
||
'claude-3-5-haiku': 'Haiku 3.5',
|
||
'gpt-4o-mini': 'GPT-4o Mini',
|
||
'gpt-4o': 'GPT-4o',
|
||
'gpt-4.1-nano': 'GPT-4.1 Nano',
|
||
'gpt-4.1-mini': 'GPT-4.1 Mini',
|
||
'gpt-4.1': 'GPT-4.1',
|
||
'codex-auto-review': 'Codex Auto Review',
|
||
'gpt-5.5-pro': 'GPT-5.5 Pro',
|
||
'gpt-5.5': 'GPT-5.5',
|
||
'gpt-5.4-pro': 'GPT-5.4 Pro',
|
||
'gpt-5.4-nano': 'GPT-5.4 Nano',
|
||
'gpt-5.4-mini': 'GPT-5.4 Mini',
|
||
'gpt-5.4': 'GPT-5.4',
|
||
'gpt-5.3-codex-spark': 'GPT-5.3 Codex Spark',
|
||
'gpt-5.3-codex': 'GPT-5.3 Codex',
|
||
'gpt-5.3': 'GPT-5.3',
|
||
'gpt-5.2-pro': 'GPT-5.2 Pro',
|
||
'gpt-5.2-low': 'GPT-5.2 Low',
|
||
'gpt-5.2': 'GPT-5.2',
|
||
'gpt-5.1-codex-mini': 'GPT-5.1 Codex Mini',
|
||
'gpt-5.1-codex': 'GPT-5.1 Codex',
|
||
'gpt-5.1': 'GPT-5.1',
|
||
'gpt-5-pro': 'GPT-5 Pro',
|
||
'gpt-5-nano': 'GPT-5 Nano',
|
||
'gpt-5-mini': 'GPT-5 Mini',
|
||
'gpt-5': 'GPT-5',
|
||
'gemini-3.5-flash': 'Gemini 3.5 Flash',
|
||
'gemini-3.1-pro-preview': 'Gemini 3.1 Pro',
|
||
'gemini-3-flash-preview': 'Gemini 3 Flash',
|
||
'gemini-2.5-pro': 'Gemini 2.5 Pro',
|
||
'gemini-2.5-flash': 'Gemini 2.5 Flash',
|
||
'kimi-k2-thinking-turbo': 'Kimi K2 Thinking Turbo',
|
||
'kimi-k2-thinking': 'Kimi K2 Thinking',
|
||
'kimi-k3': 'Kimi K3',
|
||
'kimi-k2p6': 'Kimi K2.6',
|
||
'kimi-thinking-preview': 'Kimi Thinking',
|
||
'kimi-k2.6': 'Kimi K2.6',
|
||
'kimi-k2.5': 'Kimi K2.5',
|
||
'kimi-k2p5': 'Kimi K2.5',
|
||
'kimi-k2-instruct': 'Kimi K2 Instruct',
|
||
'kimi-k2-0905': 'Kimi K2',
|
||
'kimi-k2': 'Kimi K2',
|
||
'kimi-latest': 'Kimi Latest',
|
||
'moonshot-v1': 'Moonshot v1',
|
||
'deepseek-v4-pro': 'DeepSeek v4 Pro',
|
||
'deepseek-v4-flash': 'DeepSeek v4 Flash',
|
||
'deepseek-coder-max': 'DeepSeek Coder Max',
|
||
'deepseek-coder': 'DeepSeek Coder',
|
||
'deepseek-r1': 'DeepSeek R1',
|
||
'o4-mini': 'o4-mini',
|
||
'o3': 'o3',
|
||
'MiniMax-M2.7-highspeed': 'MiniMax M2.7 Highspeed',
|
||
'MiniMax-M2.7': 'MiniMax M2.7',
|
||
// Grok (xAI) and GLM ids that otherwise surface raw or as a pricing key in
|
||
// reports. grok-build and GLM-5.2 price via sibling aliases, so
|
||
// getShortModelName resolves to the pricing key before this lookup; map each
|
||
// back to the real model name. grok-composer has no alias, it just lacked an
|
||
// entry.
|
||
'glm-5p1': 'GLM-5.2', // ZCode/Hermes run GLM-5.2 (priced as the GLM-5.1 sibling)
|
||
'grok-build-0.1': 'Grok Build', // Grok Build prices through the 0.1 sibling
|
||
'grok-composer-2.5-fast': 'Grok Composer 2.5 Fast',
|
||
// Fireworks-hosted fleet models arrive as `accounts/fireworks/models/<slug>`;
|
||
// getShortModelName's path fallback strips to the bare slug and re-resolves it
|
||
// through this table. Display-only — getModelCosts prices off the full path,
|
||
// so these entries do not move any dollar amounts. (deepseek-v4-pro/-flash
|
||
// already have entries above and resolve the same way.)
|
||
'glm-5p2': 'GLM-5.2',
|
||
'qwen3p7-plus': 'Qwen 3.7 Plus',
|
||
'kimi-k2p7-code': 'Kimi K2.7 Code',
|
||
// Ids that price correctly but had no display entry, so reports showed the
|
||
// raw slug. All display-only. The GPT-5.6 variants are listed individually
|
||
// rather than as a bare `gpt-5.6`: a base entry would swallow every future
|
||
// `gpt-5.6-*` via the prefix match and hide the variant, which is exactly
|
||
// what getShortModelName's version-boundary rule is there to prevent.
|
||
'gpt-5.6-sol': 'GPT-5.6 Sol',
|
||
'gpt-5.6-terra': 'GPT-5.6 Terra',
|
||
'gpt-5.6-luna': 'GPT-5.6 Luna',
|
||
// The Grok Build harness reports the model it runs (`grok-4.5`), so this is
|
||
// the model's own name; `grok-build*` ids still resolve to "Grok Build".
|
||
'grok-4.5': 'Grok 4.5',
|
||
// The harness also reports a `-build` variant of that model. It is a distinct
|
||
// id and reports bucket by id, so without its own entry the prefix match gave
|
||
// it the same name as `grok-4.5` and the report showed two identical rows.
|
||
'grok-4.5-build': 'Grok 4.5 (build)',
|
||
// ClinePass routes models as `cline-pass/<slug>`; getShortModelName's path
|
||
// fallback strips the prefix and re-resolves the bare slug through this
|
||
// table, the same way it handles `accounts/fireworks/models/<slug>`.
|
||
'qwen3.7-max': 'Qwen 3.7 Max',
|
||
'mimo-v2.5-pro': 'MiMo v2.5 Pro',
|
||
'mimo-v2.5': 'MiMo v2.5',
|
||
'mimo-v2-flash': 'MiMo v2 Flash',
|
||
// Both spellings occur in the wild: OpenRouter gap-filled keys are lowercase
|
||
// slugs while sessions report the capitalized name (see the case-insensitive
|
||
// pricing index above). SHORT_NAMES matching is case-sensitive, so map both.
|
||
'minimax-m3': 'MiniMax M3',
|
||
'MiniMax-M3': 'MiniMax M3',
|
||
}
|
||
|
||
// Sorted longest-first so more-specific prefixes match before shorter ones.
|
||
// Without this, `gpt-5-mini` could resolve to "GPT-5" (the entry for `gpt-5`)
|
||
// if it happened to be iterated before `gpt-5-mini`, hiding a distinct model
|
||
// behind the wrong display name and pricing tier.
|
||
const SORTED_SHORT_NAMES: [string, string][] = Object.entries(SHORT_NAMES)
|
||
.sort((a, b) => b[0].length - a[0].length)
|
||
|
||
// Anthropic's id scheme is `claude-<family>-<major>[-<minor>]`, so every new
|
||
// version is derivable — no hand-maintained entry per release. (Legacy 3.x ids
|
||
// put the family last, e.g. `claude-3-5-sonnet`, and stay in SHORT_NAMES.)
|
||
const CLAUDE_FAMILY: Record<string, string> = {
|
||
opus: 'Opus',
|
||
sonnet: 'Sonnet',
|
||
haiku: 'Haiku',
|
||
fable: 'Fable',
|
||
mythos: 'Mythos',
|
||
}
|
||
function deriveClaudeShortName(canonical: string): string | undefined {
|
||
const m = canonical.match(/^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d+))?/)
|
||
if (!m) return undefined
|
||
const [, family, major, minor] = m
|
||
return `${CLAUDE_FAMILY[family]} ${major}${minor ? `.${minor}` : ''}`
|
||
}
|
||
|
||
function lookupShortName(id: string): string | undefined {
|
||
const claude = deriveClaudeShortName(id)
|
||
if (claude) return claude
|
||
for (const [key, name] of SORTED_SHORT_NAMES) {
|
||
if (id === key || id.startsWith(key + '-')) return name
|
||
}
|
||
return undefined
|
||
}
|
||
|
||
// Public API stays unary so Array.map/forEach cannot feed index as cycle state.
|
||
export function getShortModelName(model: string): string {
|
||
return shortModelName(model, new Set())
|
||
}
|
||
|
||
// --- Billing routes ---------------------------------------------------------
|
||
//
|
||
// The same model can be billed through more than one door: Claude through
|
||
// Anthropic's API or through AWS Bedrock, Codex through OpenAI or a reseller.
|
||
// Reports key model rows by display name, so without a route the Bedrock and
|
||
// the direct spend of one model merge into a single row and "how much metered
|
||
// API usage am I incurring on top of my subscriptions?" has no answer.
|
||
//
|
||
// A route has two possible sources, feeding one field on the call:
|
||
// * the model id, when the door renames the model (Bedrock writes
|
||
// `anthropic.claude-…-v1:0` where a direct call writes `claude-…`);
|
||
// * the provider's own endpoint column, when it does not (Hermes records
|
||
// `billing_provider = bedrock` next to the plain vendor id).
|
||
// Pricing never consults the route: it runs on the raw id, and LiteLLM already
|
||
// carries the routed rows. The route only decides which row the cost lands on.
|
||
|
||
/// Who pays for a call: a metered API account bills per call, a subscription
|
||
/// has already paid for it. Exactly these two — a call whose evidence names
|
||
/// neither carries no mode at all rather than being guessed into one.
|
||
export type BillingMode = 'metered' | 'subscription'
|
||
|
||
export type ModelRoute = {
|
||
/// Stable key, safe for filters and JSON (`bedrock`).
|
||
id: string
|
||
/// Suffix appended to the display name: "Fable 5.1 (Bedrock)".
|
||
label: string
|
||
/// How this door bills when the call itself says nothing: every registered
|
||
/// door is a metered API account. A call's own recorded basis still wins
|
||
/// (see `callBillingMode`) — this is the default, not an override.
|
||
billing: BillingMode
|
||
}
|
||
|
||
type RouteEntry = ModelRoute & {
|
||
/// Spellings a provider's endpoint column uses for this door, lowercased.
|
||
providerFields: readonly string[]
|
||
}
|
||
|
||
// Doors other than the vendor's own API. The direct door has no entry: the
|
||
// unsuffixed row IS the direct row. Subscription doors (a ChatGPT plan, a
|
||
// Claude Max plan) are not routes either — they do not change which row a
|
||
// model lands on. Only doors with real sessions on disk are listed, the same
|
||
// rule the id shapes follow.
|
||
const ROUTES: readonly RouteEntry[] = [
|
||
{ id: 'bedrock', label: 'Bedrock', billing: 'metered', providerFields: ['bedrock', 'amazon-bedrock'] },
|
||
{ id: 'openrouter', label: 'OpenRouter', billing: 'metered', providerFields: ['openrouter'] },
|
||
]
|
||
|
||
const ROUTES_BY_ID = new Map(ROUTES.map(route => [route.id, route]))
|
||
const ROUTES_BY_FIELD = new Map(ROUTES.flatMap(route => route.providerFields.map(field => [field, route] as const)))
|
||
|
||
// Bedrock foundation-model ids: `<vendor>.<model>[-v<major>:<minor>]`, with an
|
||
// optional cross-region inference-profile prefix (`us.`, `eu.`, `global.`).
|
||
// Only the two vendors with coding transcripts on disk are recognised; a
|
||
// dotted id from any other first segment (`gpt-4.1-mini`, `glm-4.7`,
|
||
// `deepseek.v3.2`) is left alone. The version suffix is the one #1463 exempts
|
||
// from the local-tag rule.
|
||
const BEDROCK_ID = /^(?:(us|eu|apac|global|jp|au|us-gov)\.)?(anthropic|openai)\.([a-z0-9][a-z0-9.-]*?)(?:-v\d+:\d+)?$/i
|
||
|
||
export type RoutedModel = ModelRoute & {
|
||
/// The vendor's own id for the model, with the door's wrapping removed:
|
||
/// `anthropic.claude-haiku-4-5-20251001-v1:0` → `claude-haiku-4-5-20251001`.
|
||
/// What the same model is called through the direct door, so its short
|
||
/// name is the same one the direct row uses.
|
||
baseModel: string
|
||
/// The door's own SKU variant, when the id names one: Bedrock's cross-region
|
||
/// inference-profile prefix (`us`, `eu`, `global`, …). A profile is priced
|
||
/// above the single-region id, so it is a distinct SKU and keeps its own
|
||
/// row (#1053) — the label reads "Haiku 4.5 (Bedrock us)". Undefined for
|
||
/// the bare id.
|
||
variant?: string
|
||
}
|
||
|
||
/// The billing door a model id names, or undefined for a plain vendor id.
|
||
/// Pure: no catalog lookup, safe on the parse path.
|
||
export function getModelRoute(model: string): RoutedModel | undefined {
|
||
const bedrock = BEDROCK_ID.exec(model)
|
||
if (bedrock) {
|
||
const variant = bedrock[1]?.toLowerCase()
|
||
return { ...ROUTES_BY_ID.get('bedrock')!, baseModel: bedrock[3]!, ...(variant ? { variant } : {}) }
|
||
}
|
||
return undefined
|
||
}
|
||
|
||
/// The route a provider's endpoint field names (`billing_provider` in Hermes,
|
||
/// `providerID` in OpenCode), or undefined when the value is the direct door or
|
||
/// unknown. Direct doors (`anthropic`, `openai`, `google`, …) deliberately
|
||
/// have no route: the unsuffixed row IS the direct row.
|
||
export function routeFromProviderField(value: string | null | undefined): ModelRoute | undefined {
|
||
if (!value) return undefined
|
||
const normalized = value.trim().toLowerCase()
|
||
// Only the literal values exist in usage-bearing OpenCode/OpenRouter sessions.
|
||
// Keep Hermes' shipped `bedrock` case/whitespace normalization, but do not
|
||
// invent aliases for the provider spellings OpenCode records.
|
||
if ((normalized === 'openrouter' || normalized === 'amazon-bedrock') && value !== normalized) return undefined
|
||
return ROUTES_BY_FIELD.get(normalized)
|
||
}
|
||
|
||
/// Route by stable id, for consumers that persisted the id (cached calls).
|
||
export function getRouteById(id: string | null | undefined): ModelRoute | undefined {
|
||
return id ? ROUTES_BY_ID.get(id) : undefined
|
||
}
|
||
|
||
/// Every registered route id, for a CLI that validates a `--route` value
|
||
/// before it parses anything.
|
||
export function registeredRouteIds(): string[] {
|
||
return ROUTES.map(route => route.id)
|
||
}
|
||
|
||
/// The door a call actually went through: the route the provider recorded
|
||
/// when it recorded one, else the one the model id names, else null for the
|
||
/// direct door. Null also covers a persisted id no route registers, so an
|
||
/// unrecognised value degrades to direct rather than to a phantom door.
|
||
export function effectiveRouteId(model: string, route?: string | null): string | null {
|
||
return getRouteById(route)?.id ?? getModelRoute(model)?.id ?? null
|
||
}
|
||
|
||
/// A billing mode from a persisted or user-supplied value, or undefined when
|
||
/// it is neither mode. The single gate every validator and conversion uses,
|
||
/// so `metered|subscription` cannot drift between the CLI, the cache and the
|
||
/// providers.
|
||
export function parseBillingMode(value: string | null | undefined): BillingMode | undefined {
|
||
return value === 'metered' || value === 'subscription' ? value : undefined
|
||
}
|
||
|
||
/// Who billed a call, from the call's own evidence. A mode the provider
|
||
/// observed (Hermes' resolved cost basis: `included` is subscription-covered,
|
||
/// `actual` is a recorded invoice amount) is a fact and wins outright. Only
|
||
/// when the call states no fact does an effective registered route supply its
|
||
/// default. A direct call whose cost is estimated or calculated stays
|
||
/// unknown: an estimate says nothing about which account was charged.
|
||
export function callBillingMode(call: { model: string; route?: string | null; billing?: string | null }): BillingMode | undefined {
|
||
const observed = parseBillingMode(call.billing)
|
||
if (observed) return observed
|
||
const route = effectiveRouteId(call.model, call.route)
|
||
return route ? ROUTES_BY_ID.get(route)!.billing : undefined
|
||
}
|
||
|
||
/// The parenthetical a routed row carries after its short name — "(Bedrock)",
|
||
/// "(Bedrock us)" — or an empty string for the direct door.
|
||
/// `route` is the call's persisted route id when the provider supplied one;
|
||
/// otherwise the id shape decides. Exported so a provider-first label
|
||
/// (models-report) can append exactly what modelRowKey appends.
|
||
export function routeSuffix(model: string, route?: string | null): string {
|
||
const shaped = getModelRoute(model)
|
||
const resolved = getRouteById(route) ?? shaped
|
||
if (!resolved) return ''
|
||
const variant = shaped?.variant
|
||
return `(${resolved.label}${variant ? ` ${variant}` : ''})`
|
||
}
|
||
|
||
/// The key every report keys a model row on. One SKU through one door is one
|
||
/// row: `"Haiku 4.5"` for the direct call, `"Haiku 4.5 (Bedrock)"` for the
|
||
/// single-region Bedrock id, `"Haiku 4.5 (Bedrock us)"` for the cross-region
|
||
/// profile that prices above it. Without a route this is exactly
|
||
/// `getShortModelName`, so ids that name no door keep their existing rows.
|
||
/// Idempotent: a key fed back in (an adopted pre-v33 daily row) returns itself.
|
||
export function modelRowKey(model: string, route?: string | null): string {
|
||
// A user alias on the full id is a deliberate remap and wins over any door.
|
||
if (Object.hasOwn(userAliases, model)) return getShortModelName(model)
|
||
const suffix = routeSuffix(model, route)
|
||
if (!suffix) return getShortModelName(model)
|
||
const name = getShortModelName(getModelRoute(model)?.baseModel ?? model)
|
||
return `${name} ${suffix}`
|
||
}
|
||
|
||
/// Provider-first display name. Local labels win (Cursor estimated suffixes,
|
||
/// provider tables that intentionally override the global map). If the provider
|
||
/// echoed the raw id, it missed — fall back to the global resolver instead of
|
||
/// showing `gpt-5.6-sol` / `accounts/fireworks/models/kimi-k2p6`.
|
||
export function fallbackRawModelDisplayName(localLabel: string, rawModel: string): string {
|
||
return localLabel === rawModel ? getShortModelName(rawModel) : localLabel
|
||
}
|
||
|
||
function shortModelName(model: string, seen: Set<string>): string {
|
||
if (autoModelNames[model]) return autoModelNames[model]
|
||
if (seen.has(model)) {
|
||
const leaf = model.includes('/') ? model.slice(model.lastIndexOf('/') + 1) : model
|
||
return lookupShortName(leaf) ?? leaf
|
||
}
|
||
seen.add(model)
|
||
|
||
// User aliases win over built-in display names. A remap of gpt-4o must
|
||
// show the target, not "GPT-4o".
|
||
if (Object.hasOwn(userAliases, model)) {
|
||
return shortModelName(userAliases[model]!, seen)
|
||
}
|
||
|
||
const stripped = getCanonicalName(model)
|
||
// Before aliasing: `glm-5.3` prices via the `glm-5p2` sibling, so resolving
|
||
// first would label a namespaced GLM-5.3 as "GLM-5.2".
|
||
if (autoModelNames[stripped]) return autoModelNames[stripped]
|
||
if (stripped !== model) {
|
||
if (Object.hasOwn(userAliases, stripped)) {
|
||
return shortModelName(userAliases[stripped]!, seen)
|
||
}
|
||
const knownStripped = lookupShortName(stripped)
|
||
if (knownStripped && !Object.hasOwn(BUILTIN_ALIASES, stripped) && !Object.hasOwn(BUILTIN_ALIASES, stripped.toLowerCase())) {
|
||
return knownStripped
|
||
}
|
||
}
|
||
|
||
const canonical = resolveAlias(stripped)
|
||
const known = lookupShortName(canonical)
|
||
if (known) return known
|
||
|
||
if (canonical.includes('/')) {
|
||
const segment = canonical.slice(canonical.lastIndexOf('/') + 1)
|
||
if (!segment || seen.has(segment) || segment === stripped) {
|
||
return lookupShortName(segment) ?? segment
|
||
}
|
||
return shortModelName(segment, seen)
|
||
}
|
||
return lookupShortName(canonical) ?? canonical
|
||
}
|
||
|
||
// Pricing is process-global state assembled at CLI startup from the cached
|
||
// LiteLLM snapshot plus user config. A parse worker thread starts with none of
|
||
// it, and re-running loadPricing() there would mean N more disk reads (or, on a
|
||
// cold pricing cache, N network fetches). Ship the resolved state across
|
||
// instead, so every thread prices a call exactly as the main thread would.
|
||
export type PricingSnapshot = {
|
||
pricing: Map<string, ModelCosts>
|
||
aliases: Record<string, string>
|
||
priceOverrides: Record<string, PriceOverrideRates>
|
||
localModelSavings: Record<string, string>
|
||
flatRateModels?: string[]
|
||
flatRateModelsRemoved?: string[]
|
||
}
|
||
|
||
export function snapshotPricingState(): PricingSnapshot {
|
||
return {
|
||
pricing: pricingCache,
|
||
aliases: userAliases,
|
||
priceOverrides: userPriceOverridesConfig,
|
||
localModelSavings: userLocalModelSavings,
|
||
flatRateModels: getFlatRateModels(),
|
||
flatRateModelsRemoved: getFlatRateRemoved(),
|
||
}
|
||
}
|
||
|
||
export function restorePricingState(snapshot: PricingSnapshot): void {
|
||
pricingCache = snapshot.pricing
|
||
sortedPricingKeys = null
|
||
lowercasePricingIndex = null
|
||
knownNamespaces = null
|
||
setModelAliases(snapshot.aliases)
|
||
setPriceOverrides(snapshot.priceOverrides)
|
||
setLocalModelSavings(snapshot.localModelSavings)
|
||
setFlatRateModels(snapshot.flatRateModels ?? [])
|
||
setFlatRateRemoved(snapshot.flatRateModelsRemoved ?? [])
|
||
}
|