tokenusage-cli 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,379 +1,379 @@
1
- // Public pricing API. Replaces the hard-coded MODEL_PRICING table that used
2
- // to live in src/lib/local-api.js. Keeps the same synchronous shape so all
3
- // existing callers (computeRowCost, /api/functions/* handlers, tests) work
4
- // unchanged after `await ensurePricingLoaded()` is awaited once at startup.
5
-
6
- const fs = require("node:fs");
7
- const path = require("node:path");
8
- const os = require("node:os");
9
-
10
- const curatedOverrides = require("./curated-overrides.json");
11
- const {
12
- lookupPricing,
13
- buildLitellmPerMillionMap,
14
- } = require("./matcher");
15
- const { loadLitellmData } = require("./litellm-fetcher");
16
-
17
- const ZERO_PRICING = { input: 0, output: 0, cache_read: 0, cache_write: 0 };
18
- const PI_SUBSCRIPTION_SOURCES = new Set([
19
- "pi-github-copilot",
20
- "pi-copilot",
21
- "prime-agent-github-copilot",
22
- "prime-agent-copilot",
23
- ]);
24
- // LM Studio's server logs describe inference served by the local developer
25
- // server (including LM Link). Secure Cloud usage has a separate billing path
26
- // and is not present in these logs.
27
- const LOCAL_INFERENCE_SOURCES = new Set(["lmstudio"]);
28
- // OpenAI long-context pricing depends on a single request's raw input,
29
- // including cached tokens, never a session/day aggregate. Astra supports
30
- // a larger context window; only observed request subsets receive the premium.
31
- const OPENAI_LONG_CONTEXT_INPUT_THRESHOLD = 272_000;
32
- const SOURCES_WITH_AUTHORITATIVE_COST = new Set(["grok", "cline"]);
33
- const SEED_SNAPSHOT_PATH = path.resolve(__dirname, "seed-snapshot.json");
34
- const DEEPSEEK_TIME_PRICED_MODELS = [
35
- "deepseek-v4-flash",
36
- "deepseek-v4.1-flash",
37
- "deepseek-flash",
38
- "deepseek-v4-pro",
39
- ];
40
- // Sync seed load. Done at require-time so callers that haven't awaited
41
- // ensurePricingLoaded() (e.g. tests, vite mock startup, edge functions) still
42
- // get LiteLLM-backed pricing instead of all-zero. ensurePricingLoaded() will
43
- // later upgrade this to fresh disk cache or upstream data.
44
- function loadSeedSync() {
45
- try {
46
- const raw = fs.readFileSync(SEED_SNAPSHOT_PATH, "utf8");
47
- const parsed = JSON.parse(raw);
48
- delete parsed._meta;
49
- return parsed;
50
- } catch (e) {
51
- return {};
52
- }
53
- }
54
-
55
- const seedRaw = loadSeedSync();
56
-
57
- const state = {
58
- loaded: false,
59
- loadingPromise: null,
60
- revision: 0,
61
- litellmRawMap: seedRaw, // raw per-token; field shape from LiteLLM JSON
62
- litellmPerMillionMap: buildLitellmPerMillionMap(seedRaw), // USD/MTok
63
- source: Object.keys(seedRaw).length ? "seed-snapshot:sync" : null,
64
- // negativeCache prevents re-walking the LiteLLM map for models we've already
65
- // determined are unknown. Cleared on every reload.
66
- negativeCache: new Set(),
67
- };
68
-
69
- function defaultCachePath() {
70
- return path.join(os.homedir(), ".tokenusage", "cache", "pricing.json");
71
- }
72
-
73
- async function ensurePricingLoaded(opts = {}) {
74
- if (state.loaded) return state;
75
- if (state.loadingPromise) return state.loadingPromise;
76
-
77
- state.loadingPromise = (async () => {
78
- try {
79
- const cachePath = opts.cachePath || defaultCachePath();
80
- const { data, source } = await loadLitellmData({ ...opts, cachePath });
81
- state.litellmRawMap = data || {};
82
- state.litellmPerMillionMap = buildLitellmPerMillionMap(state.litellmRawMap);
83
- state.source = source;
84
- state.loaded = true;
85
- state.revision += 1;
86
- state.negativeCache.clear();
87
- return state;
88
- } finally {
89
- state.loadingPromise = null;
90
- }
91
- })();
92
-
93
- return state.loadingPromise;
94
- }
95
-
96
- // For tests: drop loaded state so a fresh call can re-load. Seeds with the
97
- // bundled snapshot so getModelPricing() still works without ensurePricingLoaded.
98
- function resetPricingForTests() {
99
- state.loaded = false;
100
- state.loadingPromise = null;
101
- state.litellmRawMap = seedRaw;
102
- state.litellmPerMillionMap = buildLitellmPerMillionMap(seedRaw);
103
- state.source = Object.keys(seedRaw).length ? "seed-snapshot:sync" : null;
104
- state.revision += 1;
105
- state.negativeCache.clear();
106
- }
107
-
108
- function getPricingRevision() {
109
- return state.revision;
110
- }
111
-
112
- function getModelPricing(model, opts = {}) {
113
- if (!model) return ZERO_PRICING;
114
- let lookupSource = null;
115
- if (typeof opts === "string") {
116
- lookupSource = opts.toLowerCase();
117
- } else if (typeof opts.source === "string") {
118
- lookupSource = opts.source.toLowerCase();
119
- }
120
- const cacheKey = lookupSource ? `${lookupSource}\0${model}` : model;
121
- if (state.negativeCache.has(cacheKey)) return ZERO_PRICING;
122
-
123
- const result = lookupPricing(model, {
124
- curated: curatedOverrides,
125
- litellm: state.litellmPerMillionMap,
126
- source: lookupSource,
127
- });
128
- if (result.hit) return result.value;
129
-
130
- state.negativeCache.add(cacheKey);
131
- return ZERO_PRICING;
132
- }
133
-
134
- // Callers hit this once per queue row, and a miss walks the whole LiteLLM map,
135
- // so results are memoized per pricing revision. Copies go out so a caller that
136
- // mutates its object cannot poison the cache.
137
- const pricingInfoCache = { revision: -1, entries: new Map() };
138
-
139
- // Preserve matcher provenance: a known zero rate is free, a missing model is
140
- // unpriced. Both return zero dollars, but they mean different things in the UI.
141
- function getModelPricingInfo(model, opts = {}) {
142
- const source = typeof opts === "string" ? opts : opts.source;
143
- const sourceKey = typeof source === "string" ? source.toLowerCase() : null;
144
- if (pricingInfoCache.revision !== state.revision) {
145
- pricingInfoCache.revision = state.revision;
146
- pricingInfoCache.entries.clear();
147
- }
148
- const cacheKey = `${sourceKey || ""}\0${model || ""}`;
149
- let info = pricingInfoCache.entries.get(cacheKey);
150
- if (!info) {
151
- info = computeModelPricingInfo(model, opts, sourceKey);
152
- pricingInfoCache.entries.set(cacheKey, info);
153
- }
154
- return { ...info };
155
- }
156
-
157
- function computeModelPricingInfo(model, opts, sourceKey) {
158
- if (LOCAL_INFERENCE_SOURCES.has(sourceKey) || PI_SUBSCRIPTION_SOURCES.has(sourceKey)) {
159
- return { status: "free", source: LOCAL_INFERENCE_SOURCES.has(sourceKey) ? "local_inference" : "subscription", ...ZERO_PRICING };
160
- }
161
- const result = lookupPricing(model, {
162
- curated: curatedOverrides,
163
- litellm: state.litellmPerMillionMap,
164
- source: sourceKey,
165
- });
166
- const rates = getModelPricing(model, opts);
167
- return {
168
- status: !result.hit ? "unpriced" : [rates.input, rates.output, rates.cache_read, rates.cache_write]
169
- .some((value) => Number(value) > 0) ? "priced" : "free",
170
- source: result.hit ? result.source : null,
171
- input: Number(rates.input) || 0,
172
- output: Number(rates.output) || 0,
173
- cache_read: Number(rates.cache_read) || 0,
174
- cache_write: Number(rates.cache_write) || 0,
175
- };
176
- }
177
-
178
- function isDeepSeekTimePricedModel(model) {
179
- const lower = String(model || "").toLowerCase();
180
- return DEEPSEEK_TIME_PRICED_MODELS.some((name) => lower.includes(name));
181
- }
182
-
183
- // From 00:00 Beijing time on 2026-08-23 — this instant — DeepSeek bills whole
184
- // Beijing weekends off-peak, peak hours included.
185
- // https://api-docs.deepseek.com/quick_start/pricing/
186
- const DEEPSEEK_WEEKEND_OFF_PEAK_FROM_MS = Date.UTC(2026, 7, 22, 16, 0, 0);
187
-
188
- // The weekend is bounded in Beijing time, so it runs 16:00Z Friday to 16:00Z
189
- // Sunday. Shifting the instant by +08:00 before reading the weekday is what puts
190
- // both of those edges in the right place; getUTCDay() on the raw instant marks a
191
- // different 48 hours. China has had no daylight saving since 1991, so the fixed
192
- // offset is exact.
193
- function isBeijingWeekendOffPeak(timestamp) {
194
- if (timestamp < DEEPSEEK_WEEKEND_OFF_PEAK_FROM_MS) return false;
195
- const beijingDay = new Date(timestamp + 8 * 60 * 60 * 1000).getUTCDay();
196
- return beijingDay === 0 || beijingDay === 6;
197
- }
198
-
199
- function isDeepSeekOffPeak(row) {
200
- if (row?.pricing_tier === "off_peak") return true;
201
- if (row?.pricing_tier === "peak") return false;
202
- const timestamp = Date.parse(String(row?.hour_start || ""));
203
- if (!Number.isFinite(timestamp)) return false;
204
- if (isBeijingWeekendOffPeak(timestamp)) return true;
205
- const hour = new Date(timestamp).getUTCHours();
206
- return !((hour >= 1 && hour < 4) || (hour >= 6 && hour < 10));
207
- }
208
-
209
- function getRowPricing(row) {
210
- const pricing = getModelPricing(row?.model, { source: row?.source });
211
- // AStudio uses iFlytek MaaS fixed prices and does not inherit DeepSeek public API
212
- // time-based discounts.
213
- if (String(row?.source || "").toLowerCase() === "acode") return pricing;
214
- if (!isDeepSeekTimePricedModel(row?.model) || !isDeepSeekOffPeak(row)) return pricing;
215
- return {
216
- ...pricing,
217
- input: (pricing.input || 0) * 0.5,
218
- output: (pricing.output || 0) * 0.5,
219
- cache_read: (pricing.cache_read || 0) * 0.5,
220
- cache_write: (pricing.cache_write || 0) * 0.5,
221
- };
222
- }
223
-
224
- // Same formula and Codex/every-code reasoning-folding rule as the previous
225
- // computeRowCost in src/lib/local-api.js. Moved here so vite mock + local
226
- // server share one source of truth.
227
- function computeRowCost(row) {
228
- if (LOCAL_INFERENCE_SOURCES.has(String(row?.source || "").toLowerCase())) return 0;
229
- // Pi can route a turn through a subscription-backed Copilot provider. Pi's
230
- // usage record reports a zero marginal cost for those turns; do not
231
- // reinterpret the Claude model name as an Anthropic API bill.
232
- if (PI_SUBSCRIPTION_SOURCES.has(String(row?.source || "").toLowerCase())) return 0;
233
- // Some providers (currently Grok) persist an exact server-reported cost on
234
- // the usage bucket. Prefer it when positive; zero remains the legacy
235
- // "unreported" sentinel and falls through to model pricing.
236
- const reportedCost = Number(row?.total_cost_usd);
237
- if (
238
- SOURCES_WITH_AUTHORITATIVE_COST.has(row?.source) &&
239
- Number.isFinite(reportedCost) &&
240
- reportedCost > 0
241
- ) return reportedCost;
242
- const pricing = getRowPricing(row);
243
- // OmO, like Codex, reports reasoning as a subset of `output` (its own
244
- // usage.cost bills no separate reasoning component), so charging it again
245
- // here would double-bill every reasoning token. Cline is the same: its
246
- // `outputTokens` is the AI SDK total (text + reasoning), so
247
- // reasoning_output_tokens is a subset marker, never a second line item.
248
- const reasoningIncludedInOutput =
249
- row.source === "codex" ||
250
- row.source === "acode" ||
251
- row.source === "every-code" ||
252
- row.source === "omo" ||
253
- row.source === "cline" ||
254
- row.source === "muse";
255
- const reasoningCost = reasoningIncludedInOutput
256
- ? 0
257
- : (row.reasoning_output_tokens || 0) * (pricing.output || 0);
258
- const baseCost = (
259
- ((row.input_tokens || 0) * (pricing.input || 0) +
260
- (row.output_tokens || 0) * (pricing.output || 0) +
261
- (row.cached_input_tokens || 0) * (pricing.cache_read || 0) +
262
- (row.cache_creation_input_tokens || 0) * (pricing.cache_write || 0) +
263
- reasoningCost) /
264
- 1_000_000
265
- );
266
-
267
- const model = String(row?.model || "").toLowerCase();
268
- const usesOpenAILongContextTier =
269
- model === "gpt-5.6" || model.includes("gpt-5.6-sol") || model.includes("gpt-6-astra") ||
270
- model.includes("gpt-6-sol") || model.includes("gpt-6.1-sol");
271
- // Only models whose curated entry carries an explicit Fast/priority rate get
272
- // the tier premium. The other OpenAI tiers have no published priority price,
273
- // and inventing one is worse than reporting Standard.
274
- const priorityMultiplier = Number(pricing.priority_multiplier);
275
- const hasPriorityRates = Number.isFinite(priorityMultiplier) && priorityMultiplier > 1;
276
- if (!usesOpenAILongContextTier && !hasPriorityRates) return baseCost;
277
-
278
- const bounded = (value, total) => Math.min(
279
- Math.max(0, Number(value) || 0),
280
- Math.max(0, Number(total) || 0),
281
- );
282
- // Both premium families below read "observed subset" columns: how much of the
283
- // row's own token columns came from requests with a given property. They are
284
- // annotations, never addends — total_tokens stays the sum of the base columns
285
- // whether or not they are present, and a legacy row that omits them prices
286
- // exactly as it did before.
287
- //
288
- // The parser records only usage from requests whose cache-inclusive input
289
- // exceeded 272K. OpenAI prices the whole such request at 2x input and 1.5x
290
- // output, so add the premium over the standard-rate base exactly once.
291
- const longInput = bounded(row.long_context_input_tokens, row.input_tokens);
292
- const longCached = bounded(row.long_context_cached_input_tokens, row.cached_input_tokens);
293
- const longCacheWrite = bounded(
294
- row.long_context_cache_creation_input_tokens,
295
- row.cache_creation_input_tokens,
296
- );
297
- const longOutput = bounded(row.long_context_output_tokens, row.output_tokens);
298
- const longReasoning = reasoningIncludedInOutput
299
- ? 0
300
- : bounded(row.long_context_reasoning_output_tokens, row.reasoning_output_tokens);
301
- const longContextPremium = usesOpenAILongContextTier ? (
302
- longInput * (pricing.input || 0) +
303
- longCached * (pricing.cache_read || 0) +
304
- longCacheWrite * (pricing.cache_write || 0) +
305
- 0.5 * longOutput * (pricing.output || 0) +
306
- 0.5 * longReasoning * (pricing.output || 0)
307
- ) / 1_000_000 : 0;
308
-
309
- if (!hasPriorityRates) return baseCost + longContextPremium;
310
-
311
- // Astra Fast is a flat multiple of whichever context tier the request was on
312
- // (short 10/1/12.5/50 -> 20/2/25/100; long 20/2/25/75 -> 40/4/50/150), so the
313
- // tier multiplier and the long-context premium are orthogonal: a request that
314
- // is both bills at the LONG rate times the multiplier, not standard times the
315
- // multiplier. That needs the intersection, which is why the parser records
316
- // priority_long_context_* alongside priority_*; without it (queue rows, which
317
- // carry no context-length subset at all) the overlap is 0 and the premium
318
- // falls back to the short-context multiple, matching the row's own base.
319
- const priorityInput = bounded(row.priority_input_tokens, row.input_tokens);
320
- const priorityCached = bounded(row.priority_cached_input_tokens, row.cached_input_tokens);
321
- const priorityCacheWrite = bounded(
322
- row.priority_cache_creation_input_tokens,
323
- row.cache_creation_input_tokens,
324
- );
325
- const priorityOutput = bounded(row.priority_output_tokens, row.output_tokens);
326
- const priorityReasoning = reasoningIncludedInOutput
327
- ? 0
328
- : bounded(row.priority_reasoning_output_tokens, row.reasoning_output_tokens);
329
- const priorityBase = (
330
- priorityInput * (pricing.input || 0) +
331
- priorityCached * (pricing.cache_read || 0) +
332
- priorityCacheWrite * (pricing.cache_write || 0) +
333
- priorityOutput * (pricing.output || 0) +
334
- priorityReasoning * (pricing.output || 0)
335
- ) / 1_000_000;
336
-
337
- const priorityLong = usesOpenAILongContextTier ? (
338
- bounded(row.priority_long_context_input_tokens, Math.min(priorityInput, longInput)) *
339
- (pricing.input || 0) +
340
- bounded(row.priority_long_context_cached_input_tokens, Math.min(priorityCached, longCached)) *
341
- (pricing.cache_read || 0) +
342
- bounded(
343
- row.priority_long_context_cache_creation_input_tokens,
344
- Math.min(priorityCacheWrite, longCacheWrite),
345
- ) * (pricing.cache_write || 0) +
346
- 0.5 * bounded(row.priority_long_context_output_tokens, Math.min(priorityOutput, longOutput)) *
347
- (pricing.output || 0) +
348
- 0.5 * bounded(
349
- row.priority_long_context_reasoning_output_tokens,
350
- Math.min(priorityReasoning, longReasoning),
351
- ) * (pricing.output || 0)
352
- ) / 1_000_000 : 0;
353
-
354
- const priorityPremium = (priorityMultiplier - 1) * (priorityBase + priorityLong);
355
- return baseCost + longContextPremium + priorityPremium;
356
- }
357
-
358
- // Backwards-compatible MODEL_PRICING export. Test at
359
- // test/model-breakdown.test.js:236 reads `localApi.MODEL_PRICING["kiro-agent"]`
360
- // and expects { input, output, cache_read, cache_write } shape. We expose the
361
- // CURATED.exact map (which contains the kiro entries by design); LiteLLM
362
- // entries are NOT included here because they're keyed dynamically and the old
363
- // table was authoritative for what is now CURATED.
364
- const MODEL_PRICING = curatedOverrides.exact;
365
-
366
- module.exports = {
367
- ensurePricingLoaded,
368
- getPricingRevision,
369
- getModelPricing,
370
- getModelPricingInfo,
371
- getRowPricing,
372
- computeRowCost,
373
- resetPricingForTests,
374
- MODEL_PRICING,
375
- ZERO_PRICING,
376
- OPENAI_LONG_CONTEXT_INPUT_THRESHOLD,
377
- // Internal hooks for tests.
378
- __getStateForTests: () => state,
379
- };
1
+ // Public pricing API. Replaces the hard-coded MODEL_PRICING table that used
2
+ // to live in src/lib/local-api.js. Keeps the same synchronous shape so all
3
+ // existing callers (computeRowCost, /api/functions/* handlers, tests) work
4
+ // unchanged after `await ensurePricingLoaded()` is awaited once at startup.
5
+
6
+ const fs = require("node:fs");
7
+ const path = require("node:path");
8
+ const os = require("node:os");
9
+
10
+ const curatedOverrides = require("./curated-overrides.json");
11
+ const {
12
+ lookupPricing,
13
+ buildLitellmPerMillionMap,
14
+ } = require("./matcher");
15
+ const { loadLitellmData } = require("./litellm-fetcher");
16
+
17
+ const ZERO_PRICING = { input: 0, output: 0, cache_read: 0, cache_write: 0 };
18
+ const PI_SUBSCRIPTION_SOURCES = new Set([
19
+ "pi-github-copilot",
20
+ "pi-copilot",
21
+ "prime-agent-github-copilot",
22
+ "prime-agent-copilot",
23
+ ]);
24
+ // LM Studio's server logs describe inference served by the local developer
25
+ // server (including LM Link). Secure Cloud usage has a separate billing path
26
+ // and is not present in these logs.
27
+ const LOCAL_INFERENCE_SOURCES = new Set(["lmstudio"]);
28
+ // OpenAI long-context pricing depends on a single request's raw input,
29
+ // including cached tokens, never a session/day aggregate. Astra supports
30
+ // a larger context window; only observed request subsets receive the premium.
31
+ const OPENAI_LONG_CONTEXT_INPUT_THRESHOLD = 272_000;
32
+ const SOURCES_WITH_AUTHORITATIVE_COST = new Set(["grok", "cline"]);
33
+ const SEED_SNAPSHOT_PATH = path.resolve(__dirname, "seed-snapshot.json");
34
+ const DEEPSEEK_TIME_PRICED_MODELS = [
35
+ "deepseek-v4-flash",
36
+ "deepseek-v4.1-flash",
37
+ "deepseek-flash",
38
+ "deepseek-v4-pro",
39
+ ];
40
+ // Sync seed load. Done at require-time so callers that haven't awaited
41
+ // ensurePricingLoaded() (e.g. tests, vite mock startup, edge functions) still
42
+ // get LiteLLM-backed pricing instead of all-zero. ensurePricingLoaded() will
43
+ // later upgrade this to fresh disk cache or upstream data.
44
+ function loadSeedSync() {
45
+ try {
46
+ const raw = fs.readFileSync(SEED_SNAPSHOT_PATH, "utf8");
47
+ const parsed = JSON.parse(raw);
48
+ delete parsed._meta;
49
+ return parsed;
50
+ } catch (e) {
51
+ return {};
52
+ }
53
+ }
54
+
55
+ const seedRaw = loadSeedSync();
56
+
57
+ const state = {
58
+ loaded: false,
59
+ loadingPromise: null,
60
+ revision: 0,
61
+ litellmRawMap: seedRaw, // raw per-token; field shape from LiteLLM JSON
62
+ litellmPerMillionMap: buildLitellmPerMillionMap(seedRaw), // USD/MTok
63
+ source: Object.keys(seedRaw).length ? "seed-snapshot:sync" : null,
64
+ // negativeCache prevents re-walking the LiteLLM map for models we've already
65
+ // determined are unknown. Cleared on every reload.
66
+ negativeCache: new Set(),
67
+ };
68
+
69
+ function defaultCachePath() {
70
+ return path.join(os.homedir(), ".tokenusage", "cache", "pricing.json");
71
+ }
72
+
73
+ async function ensurePricingLoaded(opts = {}) {
74
+ if (state.loaded) return state;
75
+ if (state.loadingPromise) return state.loadingPromise;
76
+
77
+ state.loadingPromise = (async () => {
78
+ try {
79
+ const cachePath = opts.cachePath || defaultCachePath();
80
+ const { data, source } = await loadLitellmData({ ...opts, cachePath });
81
+ state.litellmRawMap = data || {};
82
+ state.litellmPerMillionMap = buildLitellmPerMillionMap(state.litellmRawMap);
83
+ state.source = source;
84
+ state.loaded = true;
85
+ state.revision += 1;
86
+ state.negativeCache.clear();
87
+ return state;
88
+ } finally {
89
+ state.loadingPromise = null;
90
+ }
91
+ })();
92
+
93
+ return state.loadingPromise;
94
+ }
95
+
96
+ // For tests: drop loaded state so a fresh call can re-load. Seeds with the
97
+ // bundled snapshot so getModelPricing() still works without ensurePricingLoaded.
98
+ function resetPricingForTests() {
99
+ state.loaded = false;
100
+ state.loadingPromise = null;
101
+ state.litellmRawMap = seedRaw;
102
+ state.litellmPerMillionMap = buildLitellmPerMillionMap(seedRaw);
103
+ state.source = Object.keys(seedRaw).length ? "seed-snapshot:sync" : null;
104
+ state.revision += 1;
105
+ state.negativeCache.clear();
106
+ }
107
+
108
+ function getPricingRevision() {
109
+ return state.revision;
110
+ }
111
+
112
+ function getModelPricing(model, opts = {}) {
113
+ if (!model) return ZERO_PRICING;
114
+ let lookupSource = null;
115
+ if (typeof opts === "string") {
116
+ lookupSource = opts.toLowerCase();
117
+ } else if (typeof opts.source === "string") {
118
+ lookupSource = opts.source.toLowerCase();
119
+ }
120
+ const cacheKey = lookupSource ? `${lookupSource}\0${model}` : model;
121
+ if (state.negativeCache.has(cacheKey)) return ZERO_PRICING;
122
+
123
+ const result = lookupPricing(model, {
124
+ curated: curatedOverrides,
125
+ litellm: state.litellmPerMillionMap,
126
+ source: lookupSource,
127
+ });
128
+ if (result.hit) return result.value;
129
+
130
+ state.negativeCache.add(cacheKey);
131
+ return ZERO_PRICING;
132
+ }
133
+
134
+ // Callers hit this once per queue row, and a miss walks the whole LiteLLM map,
135
+ // so results are memoized per pricing revision. Copies go out so a caller that
136
+ // mutates its object cannot poison the cache.
137
+ const pricingInfoCache = { revision: -1, entries: new Map() };
138
+
139
+ // Preserve matcher provenance: a known zero rate is free, a missing model is
140
+ // unpriced. Both return zero dollars, but they mean different things in the UI.
141
+ function getModelPricingInfo(model, opts = {}) {
142
+ const source = typeof opts === "string" ? opts : opts.source;
143
+ const sourceKey = typeof source === "string" ? source.toLowerCase() : null;
144
+ if (pricingInfoCache.revision !== state.revision) {
145
+ pricingInfoCache.revision = state.revision;
146
+ pricingInfoCache.entries.clear();
147
+ }
148
+ const cacheKey = `${sourceKey || ""}\0${model || ""}`;
149
+ let info = pricingInfoCache.entries.get(cacheKey);
150
+ if (!info) {
151
+ info = computeModelPricingInfo(model, opts, sourceKey);
152
+ pricingInfoCache.entries.set(cacheKey, info);
153
+ }
154
+ return { ...info };
155
+ }
156
+
157
+ function computeModelPricingInfo(model, opts, sourceKey) {
158
+ if (LOCAL_INFERENCE_SOURCES.has(sourceKey) || PI_SUBSCRIPTION_SOURCES.has(sourceKey)) {
159
+ return { status: "free", source: LOCAL_INFERENCE_SOURCES.has(sourceKey) ? "local_inference" : "subscription", ...ZERO_PRICING };
160
+ }
161
+ const result = lookupPricing(model, {
162
+ curated: curatedOverrides,
163
+ litellm: state.litellmPerMillionMap,
164
+ source: sourceKey,
165
+ });
166
+ const rates = getModelPricing(model, opts);
167
+ return {
168
+ status: !result.hit ? "unpriced" : [rates.input, rates.output, rates.cache_read, rates.cache_write]
169
+ .some((value) => Number(value) > 0) ? "priced" : "free",
170
+ source: result.hit ? result.source : null,
171
+ input: Number(rates.input) || 0,
172
+ output: Number(rates.output) || 0,
173
+ cache_read: Number(rates.cache_read) || 0,
174
+ cache_write: Number(rates.cache_write) || 0,
175
+ };
176
+ }
177
+
178
+ function isDeepSeekTimePricedModel(model) {
179
+ const lower = String(model || "").toLowerCase();
180
+ return DEEPSEEK_TIME_PRICED_MODELS.some((name) => lower.includes(name));
181
+ }
182
+
183
+ // From 00:00 Beijing time on 2026-08-23 — this instant — DeepSeek bills whole
184
+ // Beijing weekends off-peak, peak hours included.
185
+ // https://api-docs.deepseek.com/quick_start/pricing/
186
+ const DEEPSEEK_WEEKEND_OFF_PEAK_FROM_MS = Date.UTC(2026, 7, 22, 16, 0, 0);
187
+
188
+ // The weekend is bounded in Beijing time, so it runs 16:00Z Friday to 16:00Z
189
+ // Sunday. Shifting the instant by +08:00 before reading the weekday is what puts
190
+ // both of those edges in the right place; getUTCDay() on the raw instant marks a
191
+ // different 48 hours. China has had no daylight saving since 1991, so the fixed
192
+ // offset is exact.
193
+ function isBeijingWeekendOffPeak(timestamp) {
194
+ if (timestamp < DEEPSEEK_WEEKEND_OFF_PEAK_FROM_MS) return false;
195
+ const beijingDay = new Date(timestamp + 8 * 60 * 60 * 1000).getUTCDay();
196
+ return beijingDay === 0 || beijingDay === 6;
197
+ }
198
+
199
+ function isDeepSeekOffPeak(row) {
200
+ if (row?.pricing_tier === "off_peak") return true;
201
+ if (row?.pricing_tier === "peak") return false;
202
+ const timestamp = Date.parse(String(row?.hour_start || ""));
203
+ if (!Number.isFinite(timestamp)) return false;
204
+ if (isBeijingWeekendOffPeak(timestamp)) return true;
205
+ const hour = new Date(timestamp).getUTCHours();
206
+ return !((hour >= 1 && hour < 4) || (hour >= 6 && hour < 10));
207
+ }
208
+
209
+ function getRowPricing(row) {
210
+ const pricing = getModelPricing(row?.model, { source: row?.source });
211
+ // AStudio uses iFlytek MaaS fixed prices and does not inherit DeepSeek public API
212
+ // time-based discounts.
213
+ if (String(row?.source || "").toLowerCase() === "acode") return pricing;
214
+ if (!isDeepSeekTimePricedModel(row?.model) || !isDeepSeekOffPeak(row)) return pricing;
215
+ return {
216
+ ...pricing,
217
+ input: (pricing.input || 0) * 0.5,
218
+ output: (pricing.output || 0) * 0.5,
219
+ cache_read: (pricing.cache_read || 0) * 0.5,
220
+ cache_write: (pricing.cache_write || 0) * 0.5,
221
+ };
222
+ }
223
+
224
+ // Same formula and Codex/every-code reasoning-folding rule as the previous
225
+ // computeRowCost in src/lib/local-api.js. Moved here so vite mock + local
226
+ // server share one source of truth.
227
+ function computeRowCost(row) {
228
+ if (LOCAL_INFERENCE_SOURCES.has(String(row?.source || "").toLowerCase())) return 0;
229
+ // Pi can route a turn through a subscription-backed Copilot provider. Pi's
230
+ // usage record reports a zero marginal cost for those turns; do not
231
+ // reinterpret the Claude model name as an Anthropic API bill.
232
+ if (PI_SUBSCRIPTION_SOURCES.has(String(row?.source || "").toLowerCase())) return 0;
233
+ // Some providers (currently Grok) persist an exact server-reported cost on
234
+ // the usage bucket. Prefer it when positive; zero remains the legacy
235
+ // "unreported" sentinel and falls through to model pricing.
236
+ const reportedCost = Number(row?.total_cost_usd);
237
+ if (
238
+ SOURCES_WITH_AUTHORITATIVE_COST.has(row?.source) &&
239
+ Number.isFinite(reportedCost) &&
240
+ reportedCost > 0
241
+ ) return reportedCost;
242
+ const pricing = getRowPricing(row);
243
+ // OmO, like Codex, reports reasoning as a subset of `output` (its own
244
+ // usage.cost bills no separate reasoning component), so charging it again
245
+ // here would double-bill every reasoning token. Cline is the same: its
246
+ // `outputTokens` is the AI SDK total (text + reasoning), so
247
+ // reasoning_output_tokens is a subset marker, never a second line item.
248
+ const reasoningIncludedInOutput =
249
+ row.source === "codex" ||
250
+ row.source === "acode" ||
251
+ row.source === "every-code" ||
252
+ row.source === "omo" ||
253
+ row.source === "cline" ||
254
+ row.source === "muse";
255
+ const reasoningCost = reasoningIncludedInOutput
256
+ ? 0
257
+ : (row.reasoning_output_tokens || 0) * (pricing.output || 0);
258
+ const baseCost = (
259
+ ((row.input_tokens || 0) * (pricing.input || 0) +
260
+ (row.output_tokens || 0) * (pricing.output || 0) +
261
+ (row.cached_input_tokens || 0) * (pricing.cache_read || 0) +
262
+ (row.cache_creation_input_tokens || 0) * (pricing.cache_write || 0) +
263
+ reasoningCost) /
264
+ 1_000_000
265
+ );
266
+
267
+ const model = String(row?.model || "").toLowerCase();
268
+ const usesOpenAILongContextTier =
269
+ model === "gpt-5.6" || model.includes("gpt-5.6-sol") || model.includes("gpt-6-astra") ||
270
+ model.includes("gpt-6-sol") || model.includes("gpt-6.1-sol");
271
+ // Only models whose curated entry carries an explicit Fast/priority rate get
272
+ // the tier premium. The other OpenAI tiers have no published priority price,
273
+ // and inventing one is worse than reporting Standard.
274
+ const priorityMultiplier = Number(pricing.priority_multiplier);
275
+ const hasPriorityRates = Number.isFinite(priorityMultiplier) && priorityMultiplier > 1;
276
+ if (!usesOpenAILongContextTier && !hasPriorityRates) return baseCost;
277
+
278
+ const bounded = (value, total) => Math.min(
279
+ Math.max(0, Number(value) || 0),
280
+ Math.max(0, Number(total) || 0),
281
+ );
282
+ // Both premium families below read "observed subset" columns: how much of the
283
+ // row's own token columns came from requests with a given property. They are
284
+ // annotations, never addends — total_tokens stays the sum of the base columns
285
+ // whether or not they are present, and a legacy row that omits them prices
286
+ // exactly as it did before.
287
+ //
288
+ // The parser records only usage from requests whose cache-inclusive input
289
+ // exceeded 272K. OpenAI prices the whole such request at 2x input and 1.5x
290
+ // output, so add the premium over the standard-rate base exactly once.
291
+ const longInput = bounded(row.long_context_input_tokens, row.input_tokens);
292
+ const longCached = bounded(row.long_context_cached_input_tokens, row.cached_input_tokens);
293
+ const longCacheWrite = bounded(
294
+ row.long_context_cache_creation_input_tokens,
295
+ row.cache_creation_input_tokens,
296
+ );
297
+ const longOutput = bounded(row.long_context_output_tokens, row.output_tokens);
298
+ const longReasoning = reasoningIncludedInOutput
299
+ ? 0
300
+ : bounded(row.long_context_reasoning_output_tokens, row.reasoning_output_tokens);
301
+ const longContextPremium = usesOpenAILongContextTier ? (
302
+ longInput * (pricing.input || 0) +
303
+ longCached * (pricing.cache_read || 0) +
304
+ longCacheWrite * (pricing.cache_write || 0) +
305
+ 0.5 * longOutput * (pricing.output || 0) +
306
+ 0.5 * longReasoning * (pricing.output || 0)
307
+ ) / 1_000_000 : 0;
308
+
309
+ if (!hasPriorityRates) return baseCost + longContextPremium;
310
+
311
+ // Astra Fast is a flat multiple of whichever context tier the request was on
312
+ // (short 10/1/12.5/50 -> 20/2/25/100; long 20/2/25/75 -> 40/4/50/150), so the
313
+ // tier multiplier and the long-context premium are orthogonal: a request that
314
+ // is both bills at the LONG rate times the multiplier, not standard times the
315
+ // multiplier. That needs the intersection, which is why the parser records
316
+ // priority_long_context_* alongside priority_*; without it (queue rows, which
317
+ // carry no context-length subset at all) the overlap is 0 and the premium
318
+ // falls back to the short-context multiple, matching the row's own base.
319
+ const priorityInput = bounded(row.priority_input_tokens, row.input_tokens);
320
+ const priorityCached = bounded(row.priority_cached_input_tokens, row.cached_input_tokens);
321
+ const priorityCacheWrite = bounded(
322
+ row.priority_cache_creation_input_tokens,
323
+ row.cache_creation_input_tokens,
324
+ );
325
+ const priorityOutput = bounded(row.priority_output_tokens, row.output_tokens);
326
+ const priorityReasoning = reasoningIncludedInOutput
327
+ ? 0
328
+ : bounded(row.priority_reasoning_output_tokens, row.reasoning_output_tokens);
329
+ const priorityBase = (
330
+ priorityInput * (pricing.input || 0) +
331
+ priorityCached * (pricing.cache_read || 0) +
332
+ priorityCacheWrite * (pricing.cache_write || 0) +
333
+ priorityOutput * (pricing.output || 0) +
334
+ priorityReasoning * (pricing.output || 0)
335
+ ) / 1_000_000;
336
+
337
+ const priorityLong = usesOpenAILongContextTier ? (
338
+ bounded(row.priority_long_context_input_tokens, Math.min(priorityInput, longInput)) *
339
+ (pricing.input || 0) +
340
+ bounded(row.priority_long_context_cached_input_tokens, Math.min(priorityCached, longCached)) *
341
+ (pricing.cache_read || 0) +
342
+ bounded(
343
+ row.priority_long_context_cache_creation_input_tokens,
344
+ Math.min(priorityCacheWrite, longCacheWrite),
345
+ ) * (pricing.cache_write || 0) +
346
+ 0.5 * bounded(row.priority_long_context_output_tokens, Math.min(priorityOutput, longOutput)) *
347
+ (pricing.output || 0) +
348
+ 0.5 * bounded(
349
+ row.priority_long_context_reasoning_output_tokens,
350
+ Math.min(priorityReasoning, longReasoning),
351
+ ) * (pricing.output || 0)
352
+ ) / 1_000_000 : 0;
353
+
354
+ const priorityPremium = (priorityMultiplier - 1) * (priorityBase + priorityLong);
355
+ return baseCost + longContextPremium + priorityPremium;
356
+ }
357
+
358
+ // Backwards-compatible MODEL_PRICING export. Test at
359
+ // test/model-breakdown.test.js:236 reads `localApi.MODEL_PRICING["kiro-agent"]`
360
+ // and expects { input, output, cache_read, cache_write } shape. We expose the
361
+ // CURATED.exact map (which contains the kiro entries by design); LiteLLM
362
+ // entries are NOT included here because they're keyed dynamically and the old
363
+ // table was authoritative for what is now CURATED.
364
+ const MODEL_PRICING = curatedOverrides.exact;
365
+
366
+ module.exports = {
367
+ ensurePricingLoaded,
368
+ getPricingRevision,
369
+ getModelPricing,
370
+ getModelPricingInfo,
371
+ getRowPricing,
372
+ computeRowCost,
373
+ resetPricingForTests,
374
+ MODEL_PRICING,
375
+ ZERO_PRICING,
376
+ OPENAI_LONG_CONTEXT_INPUT_THRESHOLD,
377
+ // Internal hooks for tests.
378
+ __getStateForTests: () => state,
379
+ };