claude-usage-limits 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,28 @@ const os = require('os');
21
21
  const path = require('path');
22
22
  const readline = require('readline');
23
23
 
24
+ const host = require('./host.js');
25
+ const codex = require('./codex.js');
26
+
27
+ // Which agent's meter to read. Resolved once from the command line or the
28
+ // environment, because a process that changed its mind halfway through would
29
+ // mix one host's percentages with the other's turns.
30
+ let activeHost = null;
31
+
32
+ function currentHost() {
33
+ if (!activeHost) activeHost = host.detect(process.argv.slice(2), process.env);
34
+ return activeHost;
35
+ }
36
+
37
+ function setHost(name) {
38
+ activeHost = host.normalise(name) || host.CLAUDE;
39
+ return activeHost;
40
+ }
41
+
42
+ function isCodex() {
43
+ return currentHost() === host.CODEX;
44
+ }
45
+
24
46
  const MINUTE = 60 * 1000;
25
47
  const HOUR = 60 * MINUTE;
26
48
  const DAY = 24 * HOUR;
@@ -206,7 +228,7 @@ function tokensOf(usage) {
206
228
  // The four token classes, kept apart because they are priced differently
207
229
  // and because knowing the split is what makes the totals reasonable about.
208
230
  function tokenParts(usage) {
209
- if (!usage) return { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 };
231
+ if (!usage) return { input: 0, cacheWrite: 0, cacheRead: 0, output: 0, reasoning: 0 };
210
232
  const creation = usage.cache_creation || {};
211
233
  const written =
212
234
  usage.cache_creation_input_tokens ||
@@ -216,6 +238,16 @@ function tokenParts(usage) {
216
238
  cacheWrite: written,
217
239
  cacheRead: usage.cache_read_input_tokens || 0,
218
240
  output: usage.output_tokens || 0,
241
+ // Reasoning is not a fifth class of token, it is a slice of the fourth.
242
+ // Measured over 1,565 turns of this account's transcripts, thinking never
243
+ // once exceeded output, so it is counted inside it and must not be added to
244
+ // any total: doing that would price every thinking turn twice.
245
+ //
246
+ // It is worth carrying separately all the same. Output is the dearest class
247
+ // there is, reasoning is about half of it, and it is the one part of the
248
+ // bill a setting can change. The skill has always said so; this is the
249
+ // number that says how much.
250
+ reasoning: (usage.output_tokens_details && usage.output_tokens_details.thinking_tokens) || 0,
219
251
  };
220
252
  }
221
253
 
@@ -233,6 +265,37 @@ function eventFrom(line, seen, project) {
233
265
  const at = Date.parse(entry.timestamp);
234
266
  if (!Number.isFinite(at)) return null;
235
267
 
268
+ // A request the limit refused is written like an assistant turn, with a
269
+ // synthetic model and a usage block of zeros. Two things follow.
270
+ //
271
+ // It is not a turn, and counting it as one dilutes the measured cost per turn
272
+ // with free ones, which makes the remaining headroom read longer than it is.
273
+ //
274
+ // And it is the only place the account says outright which window stopped the
275
+ // work and when that window comes back. The cached snapshot reports the
276
+ // 5-hour bucket as 0% with a null reset on this plan, so without reading
277
+ // these there is nothing at all to anchor that window to.
278
+ const quota = entry.quotaLimits;
279
+ if (entry.isApiErrorMessage && quota && typeof quota === 'object') {
280
+ const resetsAt = Number(quota.resetsAt);
281
+ return {
282
+ at,
283
+ model: '',
284
+ effort: null,
285
+ cost: 0,
286
+ tokens: 0,
287
+ parts: { input: 0, cacheWrite: 0, cacheRead: 0, output: 0, reasoning: 0 },
288
+ project: project || null,
289
+ sessionId: entry.sessionId || null,
290
+ rejected: {
291
+ status: typeof quota.status === 'string' ? quota.status : null,
292
+ key: typeof quota.rateLimitType === 'string' ? quota.rateLimitType : null,
293
+ // Seconds on the wire, milliseconds everywhere in here.
294
+ resetsAt: Number.isFinite(resetsAt) && resetsAt > 0 ? resetsAt * 1000 : null,
295
+ },
296
+ };
297
+ }
298
+
236
299
  // A resumed or forked session repeats earlier turns in a new file.
237
300
  const id = (entry.message.id || '') + '|' + (entry.requestId || '');
238
301
  if (id !== '|' && seen) {
@@ -253,6 +316,11 @@ function eventFrom(line, seen, project) {
253
316
  }
254
317
 
255
318
  async function readEvents(since) {
319
+ if (isCodex()) return codex.readEvents(since);
320
+ return readClaudeEvents(since);
321
+ }
322
+
323
+ async function readClaudeEvents(since) {
256
324
  const root = path.join(configDir(), 'projects');
257
325
  let dirs = [];
258
326
  try {
@@ -309,7 +377,7 @@ async function readEvents(since) {
309
377
  function totals(events) {
310
378
  let cost = 0;
311
379
  let tokens = 0;
312
- const parts = { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 };
380
+ const parts = { input: 0, cacheWrite: 0, cacheRead: 0, output: 0, reasoning: 0 };
313
381
  for (const event of events) {
314
382
  cost += event.cost;
315
383
  tokens += event.tokens;
@@ -318,6 +386,7 @@ function totals(events) {
318
386
  parts.cacheWrite += event.parts.cacheWrite;
319
387
  parts.cacheRead += event.parts.cacheRead;
320
388
  parts.output += event.parts.output;
389
+ parts.reasoning += event.parts.reasoning || 0;
321
390
  }
322
391
  }
323
392
  return { cost, tokens, turns: events.length, parts };
@@ -335,7 +404,7 @@ function byModel(events) {
335
404
  turns: 0,
336
405
  tokens: 0,
337
406
  cost: 0,
338
- parts: { input: 0, cacheWrite: 0, cacheRead: 0, output: 0 },
407
+ parts: { input: 0, cacheWrite: 0, cacheRead: 0, output: 0, reasoning: 0 },
339
408
  });
340
409
  }
341
410
  const row = rows.get(id);
@@ -347,6 +416,7 @@ function byModel(events) {
347
416
  row.parts.cacheWrite += event.parts.cacheWrite;
348
417
  row.parts.cacheRead += event.parts.cacheRead;
349
418
  row.parts.output += event.parts.output;
419
+ row.parts.reasoning += event.parts.reasoning || 0;
350
420
  }
351
421
  }
352
422
  const list = [...rows.values()].sort((a, b) => b.cost - a.cost);
@@ -382,7 +452,22 @@ function typicalTurnCost(recentEvents, windowEvents, allEvents, minSample) {
382
452
  .filter((cost) => Number.isFinite(cost) && cost > 0)
383
453
  .sort((a, b) => a - b);
384
454
  if (!costs.length) return null;
385
- return costs[Math.floor(costs.length / 2)];
455
+
456
+ // The middle turn resists a freak one, which is the point, but it is the
457
+ // wrong statistic for counting how many more turns fit. Turn costs are
458
+ // skewed: most are cheap, a few are far dearer, and they get dearer still as
459
+ // the context grows. The remaining budget is divided by the *average*, so
460
+ // taking the middle one systematically promises more turns than there are.
461
+ // Measured on the window that ran out on 2026-08-30: 182 turns promised, 110
462
+ // actually left.
463
+ //
464
+ // Trimming both ends and averaging what is left keeps the resistance to a
465
+ // single $7 turn while respecting the skew, and errs toward under-promising,
466
+ // which is the safe direction for a budget.
467
+ const cut = costs.length >= MIN_PACE_SAMPLE ? Math.max(1, Math.round(costs.length * 0.1)) : 0;
468
+ const kept = cut > 0 ? costs.slice(cut, costs.length - cut) : costs;
469
+ const middle = kept.length ? kept : costs;
470
+ return middle.reduce((sum, cost) => sum + cost, 0) / middle.length;
386
471
  }
387
472
 
388
473
  function dominantEffort(events) {
@@ -398,6 +483,36 @@ function dominantEffort(events) {
398
483
  return best ? best[0] : null;
399
484
  }
400
485
 
486
+ // What the thinking actually cost, rather than what it is generally said to
487
+ // cost. Reasoning is billed as output, so it is priced at the output rate of
488
+ // whichever models did the thinking, weighted by how much each of them did.
489
+ //
490
+ // This deliberately does not try to tell an `ultrathink` turn from a high
491
+ // effort setting from a model that simply chose to think. They are the same
492
+ // spend and the same lever, and the transcript does not reliably separate them
493
+ // anyway. What matters is how much of the bill is reasoning.
494
+ function reasoningSpend(models, tokens) {
495
+ const total = tokens && Number.isFinite(tokens.reasoning) ? tokens.reasoning : 0;
496
+ const output = tokens && Number.isFinite(tokens.output) ? tokens.output : 0;
497
+ if (total <= 0 || output <= 0) return null;
498
+
499
+ let cost = 0;
500
+ let priced = 0;
501
+ for (const row of models || []) {
502
+ const amount = row.parts && Number.isFinite(row.parts.reasoning) ? row.parts.reasoning : 0;
503
+ if (amount <= 0) continue;
504
+ cost += (amount * rateFor(row.model).output) / 1e6;
505
+ priced += amount;
506
+ }
507
+
508
+ return {
509
+ tokens: total,
510
+ shareOfOutput: total / output,
511
+ // Only claim a price when the models that did the thinking were priced.
512
+ cost: priced > 0 ? cost : null,
513
+ };
514
+ }
515
+
401
516
  // Which project directory the spend went to. Claude Code names these after
402
517
  // the working directory, so they are recognisable even though the mangling
403
518
  // is not reversible.
@@ -537,8 +652,12 @@ function shareOf(sessions, sessionId) {
537
652
  // whatever slice happens to be to hand. A thin baseline prices a point badly
538
653
  // and every correction built on it inherits the error: a 24 minute old
539
654
  // snapshot once turned a window truly at 70 per cent into a confident 82.
655
+ // Kept beside whichever agent it describes. The two hosts happen to use the
656
+ // same window keys, so a shared file would price a Codex point with what a
657
+ // Claude point costs and be wrong on both.
540
658
  function calibrationFile() {
541
- return path.join(configDir(), 'usage-limits-calibration.json');
659
+ const dir = isCodex() ? codex.homeDir() : configDir();
660
+ return path.join(dir, 'usage-limits-calibration.json');
542
661
  }
543
662
 
544
663
  function readCalibration() {
@@ -640,11 +759,18 @@ function buildWindow(spec, snapshot, events, now, options) {
640
759
  // was truly at 88% was reported at 49%. Calibrate on spend up to the reading
641
760
  // only, or the very spend being accounted for inflates the price per point
642
761
  // and shrinks its own correction.
762
+ // A reading with no reset time cannot be told apart from a current one by
763
+ // looking at it, so age is the only guide. Once the snapshot is older than
764
+ // the window itself, whatever it says describes a window that has since
765
+ // rolled over at least once, and quoting it as current is how a long gap
766
+ // ends up reported as a full budget.
767
+ window.snapshotOlderThanWindow =
768
+ Number.isFinite(extra.fetchedAt) && now - extra.fetchedAt >= spec.span;
769
+
643
770
  let percent = rawPercent;
644
771
  let sinceSnapshot = 0;
645
772
  if (
646
773
  rawPercent !== null &&
647
- rawPercent > 0 &&
648
774
  !window.stale &&
649
775
  Number.isFinite(extra.fetchedAt) &&
650
776
  extra.fetchedAt > start
@@ -656,13 +782,29 @@ function buildWindow(spec, snapshot, events, now, options) {
656
782
  // turns makes it far too cheap, and every dollar spent since then is then
657
783
  // divided by that, which is how a window truly at 55% got corrected all the
658
784
  // way to a confident 100.
659
- if (upTo.cost > 0 && after.cost > 0 && upTo.turns >= MIN_BASELINE_TURNS) {
660
- const mine = { usdPerPercent: upTo.cost / rawPercent, turns: upTo.turns, percent: rawPercent };
661
- const known = extra.knownCalibration;
662
- // Trust the better-sampled of the two, whichever that is.
663
- const chosen =
664
- known && Number.isFinite(known.turns) && known.turns > upTo.turns ? known : mine;
665
- window.calibration = mine;
785
+ //
786
+ // A reading of exactly 0 cannot price itself at all: there is no meter
787
+ // movement to divide the spend by. That used to end the correction here,
788
+ // which was the worst place to stop, because 0% is what a window reads
789
+ // right after a reset and therefore what a snapshot most often goes stale
790
+ // holding. The learned price covers it: what a point costs is a property
791
+ // of the plan, not of this reading.
792
+ const selfPriced =
793
+ rawPercent > 0 && upTo.cost > 0 && upTo.turns >= MIN_BASELINE_TURNS
794
+ ? { usdPerPercent: upTo.cost / rawPercent, turns: upTo.turns, percent: rawPercent }
795
+ : null;
796
+ if (selfPriced) window.calibration = selfPriced;
797
+
798
+ const known = extra.knownCalibration;
799
+ const usable =
800
+ known && Number.isFinite(known.usdPerPercent) && known.usdPerPercent > 0 ? known : null;
801
+ // Trust the better-sampled of the two, whichever that is.
802
+ const chosen =
803
+ selfPriced && usable
804
+ ? (usable.turns > selfPriced.turns ? usable : selfPriced)
805
+ : selfPriced || usable;
806
+
807
+ if (after.cost > 0 && chosen) {
666
808
  const pricePerPoint = chosen.usdPerPercent;
667
809
  sinceSnapshot = after.cost / pricePerPoint;
668
810
 
@@ -682,13 +824,27 @@ function buildWindow(spec, snapshot, events, now, options) {
682
824
  }
683
825
  }
684
826
 
685
- const derived = percent !== null && percent > 0 && spent.cost > 0 ? spent.cost / percent : null;
827
+ // Pricing a point off this window's own spend only works when this machine
828
+ // did most of that spending. It often has not: another device, a cloud task,
829
+ // or simply a window that opened before the local history did, and then a
830
+ // meter reading 61% divides by almost nothing and every remaining point looks
831
+ // free. The visible symptom is a window with plenty left reporting one turn
832
+ // of headroom, which is worse advice than reporting none.
833
+ // A couple of turns cannot account for a meter already well into the window,
834
+ // so when the two disagree that badly it is the local history that is
835
+ // incomplete, not the meter.
836
+ const thin = spent.turns < MIN_BASELINE_TURNS && percent >= UNEXPLAINED_PERCENT;
837
+ const measured = percent !== null && percent > 0 && spent.cost > 0 && !thin;
838
+ const derived = measured ? spent.cost / percent : null;
839
+ const known = extra.knownCalibration;
686
840
  const priced =
687
841
  derived !== null
688
842
  ? derived
689
843
  : Number.isFinite(extra.usdPerPercent) && extra.usdPerPercent > 0
690
844
  ? extra.usdPerPercent
691
- : null;
845
+ : known && Number.isFinite(known.usdPerPercent) && known.usdPerPercent > 0
846
+ ? known.usdPerPercent
847
+ : null;
692
848
 
693
849
  if (percent !== null && priced !== null) {
694
850
  window.usdPerPercent = priced;
@@ -730,6 +886,23 @@ function buildWindow(spec, snapshot, events, now, options) {
730
886
  return window;
731
887
  }
732
888
 
889
+ // The most recent time the account actually refused work, per window. This is
890
+ // ground truth: not an estimate of where the budget stands but a record of it
891
+ // having run out, with the window named and its reset time attached.
892
+ function lastRejections(events) {
893
+ const byKey = new Map();
894
+ for (const event of events || []) {
895
+ const rejected = event && event.rejected;
896
+ if (!rejected || rejected.status !== 'rejected') continue;
897
+ const key = rejected.key || 'unknown';
898
+ const seen = byKey.get(key);
899
+ if (!seen || event.at > seen.at) {
900
+ byKey.set(key, { key, at: event.at, resetsAt: rejected.resetsAt });
901
+ }
902
+ }
903
+ return byKey;
904
+ }
905
+
733
906
  // Which window binds is about what stops you soonest. It says nothing about
734
907
  // what stopping costs. Running out of a 5-hour window waits hours; running out
735
908
  // of the weekly one waits days. So a weekly window near the wall is worth
@@ -851,7 +1024,40 @@ function detectPlan(oauth) {
851
1024
  };
852
1025
  }
853
1026
 
1027
+ // The snapshot carries buckets this table has never heard of, and it gains more
1028
+ // over time: alongside five_hour and seven_day there are per-product and
1029
+ // codenamed limits that come and go. Dropping them silently means a limit that
1030
+ // is actually biting never gets mentioned, so anything carrying real spend is
1031
+ // reported even though there is no span to price it against.
1032
+ const KNOWN_KEYS = new Set(['five_hour', 'seven_day', 'seven_day_opus', 'seven_day_sonnet']);
1033
+ const NOT_A_WINDOW = new Set(['extra_usage', 'spend', 'limits', 'member_dashboard_available']);
1034
+
1035
+ function otherLimits(utilization, threshold) {
1036
+ if (!utilization) return [];
1037
+ const floor = Number.isFinite(threshold) ? threshold : 1;
1038
+ const rows = [];
1039
+ for (const key of Object.keys(utilization)) {
1040
+ if (KNOWN_KEYS.has(key) || NOT_A_WINDOW.has(key)) continue;
1041
+ const bucket = utilization[key];
1042
+ if (!bucket || typeof bucket.utilization !== 'number') continue;
1043
+ if (bucket.utilization < floor) continue;
1044
+ const resetsAt = bucket.resets_at ? Date.parse(bucket.resets_at) : null;
1045
+ rows.push({
1046
+ key,
1047
+ label: key.replace(/_/g, ' '),
1048
+ percentUsed: bucket.utilization,
1049
+ resetsAt: Number.isFinite(resetsAt) ? resetsAt : null,
1050
+ });
1051
+ }
1052
+ return rows.sort((a, b) => b.percentUsed - a.percentUsed);
1053
+ }
1054
+
854
1055
  function collect(now) {
1056
+ if (isCodex()) return codex.collect(now);
1057
+ return collectClaude(now);
1058
+ }
1059
+
1060
+ function collectClaude(now) {
855
1061
  const account = readJson(accountFile()) || {};
856
1062
  const settings = readJson(path.join(configDir(), 'settings.json')) || {};
857
1063
  const cache = account.cachedUsageUtilization || null;
@@ -861,6 +1067,8 @@ function collect(now) {
861
1067
 
862
1068
  return {
863
1069
  now,
1070
+ host: host.CLAUDE,
1071
+ money: true,
864
1072
  accountFile: accountFile(),
865
1073
  plan: plan.label,
866
1074
  planId: plan.id,
@@ -892,6 +1100,10 @@ const SATURATION_LIMIT = 105;
892
1100
  // Fewer turns than this before the snapshot and a point cannot be priced.
893
1101
  const MIN_BASELINE_TURNS = 5;
894
1102
 
1103
+ // Past this much of a window, a handful of local turns is not what spent it,
1104
+ // so their total is not a fair price for a point.
1105
+ const UNEXPLAINED_PERCENT = 20;
1106
+
895
1107
  function reconstructWindow(spec, snapshot, events, now) {
896
1108
  if (!snapshot || typeof snapshot.utilization !== 'number') return null;
897
1109
  if (snapshot.utilization <= 0) return null;
@@ -930,20 +1142,90 @@ function reconstructWindow(spec, snapshot, events, now) {
930
1142
  };
931
1143
  }
932
1144
 
1145
+ // The snapshot can be older than the window it describes without ever looking
1146
+ // stale, because a window with no reset time has nothing to compare against.
1147
+ // That is the ordinary case after a long gap: the 5-hour reading was taken
1148
+ // seven hours ago and says 0%, the window running now started two hours ago,
1149
+ // and the reading is about a window that no longer exists. Adding spend to it
1150
+ // is not the fix, because none of that spend is inside the window it describes.
1151
+ // Rebuilding is: the learned price per point turns this window's own spend
1152
+ // straight into a percentage.
1153
+ function reconstructUnanchored(spec, window, events, now, learned) {
1154
+ if (!window || window.stale) return null;
1155
+ if (!window.snapshotOlderThanWindow) return null;
1156
+ // Only worth doing when the reading is low enough to be the thing that is
1157
+ // wrong. A high reading that is old is already alarming and is left alone.
1158
+ if (window.percentUsed === null || window.percentUsed > 5) return null;
1159
+ if (!learned || !Number.isFinite(learned.usdPerPercent) || learned.usdPerPercent <= 0) {
1160
+ return null;
1161
+ }
1162
+
1163
+ const start = window.windowStart;
1164
+ const live = totals(events.filter((event) => event.at >= start && event.at <= now));
1165
+ if (live.cost <= 0) return null;
1166
+
1167
+ const raw = live.cost / learned.usdPerPercent;
1168
+ if (raw < 1) return null;
1169
+ // Same rule as every other rebuild: past this it is the calibration that is
1170
+ // full rather than the window, and claiming a spent budget is worse than
1171
+ // admitting the reading could not be rebuilt.
1172
+ if (raw > SATURATION_LIMIT) return null;
1173
+
1174
+ return buildWindow(
1175
+ spec,
1176
+ { utilization: Math.min(100, Math.round(raw)), resets_at: null },
1177
+ events,
1178
+ now,
1179
+ { estimated: true, windowStart: start, usdPerPercent: learned.usdPerPercent }
1180
+ );
1181
+ }
1182
+
933
1183
  // No snapshot at all means no windows, which is what tells the report to
934
1184
  // explain itself rather than print a table of dashes.
935
- function buildWindows(utilization, events, now, fetchedAt, learned) {
1185
+ function buildWindows(utilization, events, now, fetchedAt, learned, specs, rejections) {
936
1186
  if (!utilization) return [];
937
- return WINDOWS.map((spec) => {
1187
+ const refused = rejections || new Map();
1188
+ // Claude Code's windows are fixed and known. Codex reports the length of each
1189
+ // of its two windows in the payload, so it hands its own spans in rather than
1190
+ // having them assumed.
1191
+ const table = specs && specs.length ? specs : WINDOWS;
1192
+ return table.map((spec) => {
938
1193
  const snapshot = utilization[spec.key];
939
1194
  // The per-model weekly windows only exist on some plans.
940
1195
  if (spec.key !== 'five_hour' && spec.key !== 'seven_day' && !snapshot) return null;
941
1196
 
942
- const window = buildWindow(spec, snapshot, events, now, {
1197
+ const known = learned ? learned[spec.key] : null;
1198
+ const refusal = refused.get(spec.key);
1199
+
1200
+ // With no reset time the window has to be treated as rolling, which starts
1201
+ // it five hours ago and sweeps in whatever the window before it spent. When
1202
+ // the account has refused work on this window, its reset time is known
1203
+ // exactly: a refusal in the future is this window's own reset, and one in
1204
+ // the past is the moment the window running now began.
1205
+ let anchored = snapshot;
1206
+ let windowStart;
1207
+ if (snapshot && !snapshot.resets_at && refusal && Number.isFinite(refusal.resetsAt)) {
1208
+ if (refusal.resetsAt > now) {
1209
+ anchored = Object.assign({}, snapshot, {
1210
+ resets_at: new Date(refusal.resetsAt).toISOString(),
1211
+ });
1212
+ } else if (now - refusal.resetsAt < spec.span) {
1213
+ windowStart = refusal.resetsAt;
1214
+ }
1215
+ }
1216
+
1217
+ const window = buildWindow(spec, anchored, events, now, {
943
1218
  fetchedAt,
944
- knownCalibration: learned ? learned[spec.key] : null,
1219
+ knownCalibration: known,
1220
+ ...(windowStart === undefined ? {} : { windowStart }),
945
1221
  });
946
- if (!window.stale) return window;
1222
+ if (refusal) {
1223
+ window.refusedAt = refusal.at;
1224
+ window.refusedResetsAt = refusal.resetsAt;
1225
+ }
1226
+ if (!window.stale) {
1227
+ return reconstructUnanchored(spec, window, events, now, known) || window;
1228
+ }
947
1229
 
948
1230
  // Rolled over. Rebuild from local history rather than going blind on it.
949
1231
  const rebuilt = reconstructWindow(spec, snapshot, events, now);
@@ -976,31 +1258,62 @@ function sessionSpend(events, sessionId) {
976
1258
  }
977
1259
 
978
1260
  async function report(now, options) {
979
- const base = collect(now);
1261
+ let base = collect(now);
980
1262
  // A stale snapshot can put a window's start slightly further back than
981
1263
  // seven days, so give the scan a day of slack.
982
1264
  const earliest = now - 8 * DAY;
983
- const events = await readEvents(earliest);
1265
+ const all = await readEvents(earliest);
1266
+ // A refused request is a record of the limit, not a turn against it, so it is
1267
+ // kept apart from everything that measures spend or pace.
1268
+ const rejections = lastRejections(all);
1269
+ const events = all.filter((event) => !event.rejected);
1270
+
1271
+ // Codex carries the meter inside the same records as the turns, so the full
1272
+ // scan can find a newer reading than the quick one collect() does. Reuse it
1273
+ // rather than scanning twice or reporting the older of the two.
1274
+ if (isCodex()) {
1275
+ const live = options && options.codexMeter;
1276
+ const latest = live || codex.latestMeter(events);
1277
+ if (latest && (live || !base.snapshotFetchedAt || latest.at > base.snapshotFetchedAt)) {
1278
+ base = codex.collect(now, { meter: latest });
1279
+ }
1280
+ }
1281
+
1282
+ const onDisk = readCalibration();
1283
+ const learned = Object.assign({}, onDisk);
1284
+
1285
+ // Codex logs the meter next to every request, so the price of a point can be
1286
+ // measured outright instead of inferred. A measurement from this session
1287
+ // beats anything remembered from an earlier one.
1288
+ if (isCodex()) {
1289
+ for (const spec of base.windowSpecs || []) {
1290
+ const measured = codex.calibrate(events, spec.key, now);
1291
+ if (measured) learned[spec.key] = betterCalibration(learned[spec.key], measured);
1292
+ }
1293
+ }
984
1294
 
985
- const learned = readCalibration();
986
1295
  const windows = buildWindows(
987
1296
  base.utilization,
988
1297
  events,
989
1298
  now,
990
1299
  base.snapshotFetchedAt,
991
- learned
1300
+ learned,
1301
+ base.windowSpecs,
1302
+ rejections
992
1303
  );
993
1304
 
994
1305
  // Keep the best sample seen so far, so a thin baseline never has to guess.
995
1306
  const updated = Object.assign({}, learned);
996
- let changed = false;
997
1307
  for (const window of windows) {
998
1308
  if (!window.calibration) continue;
999
- const best = betterCalibration(learned[window.key], window.calibration);
1000
- if (best && best !== learned[window.key]) {
1001
- updated[window.key] = best;
1002
- changed = true;
1003
- }
1309
+ const best = betterCalibration(updated[window.key], window.calibration);
1310
+ if (best) updated[window.key] = best;
1311
+ }
1312
+ // Compared against what is actually on disk, so a measurement taken during
1313
+ // this run is saved too rather than only the ones inferred from a window.
1314
+ let changed = false;
1315
+ for (const key of Object.keys(updated)) {
1316
+ if (updated[key] !== onDisk[key]) changed = true;
1004
1317
  }
1005
1318
  if (changed) writeCalibration(updated);
1006
1319
 
@@ -1011,19 +1324,28 @@ async function report(now, options) {
1011
1324
  const scopeStart = binding ? binding.windowStart : now - 7 * DAY;
1012
1325
  const scoped = events.filter((event) => event.at >= scopeStart && event.at <= now);
1013
1326
  const scopedTotals = totals(scoped);
1327
+ // Worked out once and used twice: the table of models, and the price of the
1328
+ // reasoning inside it.
1329
+ const scopedModels = byModel(scoped);
1014
1330
 
1015
1331
  return Object.assign({}, base, {
1016
1332
  windows,
1017
1333
  binding,
1018
- credits: creditsFrom(base.utilization),
1334
+ otherLimits: otherLimits(base.utilization),
1335
+ // The last time the account actually refused work, so a report taken just
1336
+ // after a cutoff says so rather than describing the fresh window as though
1337
+ // nothing happened.
1338
+ lastRefusal: [...rejections.values()].sort((a, b) => b.at - a.at)[0] || null,
1339
+ credits: base.codexCredits || creditsFrom(base.utilization),
1019
1340
  sessions: activeSessions(events, now, CONCURRENT_WINDOW_MS),
1020
1341
  session: sessionSpend(events, options && options.sessionId),
1021
1342
  staleWindows: windows.filter((w) => w.stale).length,
1022
1343
  rates: costPercentiles(recentEvents.length >= 5 ? recentEvents : scoped),
1023
1344
  resumeAt: binding ? binding.resetsAt : null,
1024
- models: byModel(scoped),
1345
+ models: scopedModels,
1025
1346
  projects: byProject(scoped),
1026
1347
  tokens: scopedTotals.parts,
1348
+ reasoning: reasoningSpend(scopedModels, scopedTotals.parts),
1027
1349
  scopeLabel: binding ? binding.label : 'last 7 days',
1028
1350
  recent: {
1029
1351
  turns: recent.turns,
@@ -1087,7 +1409,9 @@ function statusLine(collected) {
1087
1409
 
1088
1410
  const now = collected.now || Date.now();
1089
1411
  const parts = [];
1090
- for (const spec of WINDOWS) {
1412
+ for (const spec of collected.windowSpecs && collected.windowSpecs.length
1413
+ ? collected.windowSpecs
1414
+ : WINDOWS) {
1091
1415
  const snapshot = utilization[spec.key];
1092
1416
  if (!snapshot || typeof snapshot.utilization !== 'number') continue;
1093
1417
  const resetsAt = snapshot.resets_at ? Date.parse(snapshot.resets_at) : null;
@@ -1097,11 +1421,16 @@ function statusLine(collected) {
1097
1421
  percent: snapshot.utilization,
1098
1422
  msToReset,
1099
1423
  stale: msToReset !== null && msToReset <= 0,
1424
+ // Zero with no reset time is not an empty window, it is a bucket that is
1425
+ // not reporting: a real window at 0% has just reset and says when it will
1426
+ // do so again. The status line cannot scan transcripts to find out which,
1427
+ // so it must not print the flattering reading as though it were measured.
1428
+ unreported: snapshot.utilization === 0 && !Number.isFinite(resetsAt),
1100
1429
  });
1101
1430
  }
1102
1431
  if (!parts.length) return '';
1103
1432
 
1104
- const trusted = parts.filter((part) => !part.stale);
1433
+ const trusted = parts.filter((part) => !part.stale && !part.unreported);
1105
1434
  const worst = trusted.length
1106
1435
  ? trusted.reduce((a, b) => (b.percent > a.percent ? b : a))
1107
1436
  : null;
@@ -1109,8 +1438,10 @@ function statusLine(collected) {
1109
1438
  .map((part) =>
1110
1439
  part.stale
1111
1440
  ? part.label + ' rolling'
1112
- : part.label + ' ' + part.percent + '%' +
1113
- (part.msToReset === null ? '' : ' ' + formatDuration(part.msToReset))
1441
+ : part.unreported
1442
+ ? part.label + ' ?'
1443
+ : part.label + ' ' + part.percent + '%' +
1444
+ (part.msToReset === null ? '' : ' ' + formatDuration(part.msToReset))
1114
1445
  )
1115
1446
  .join(' ');
1116
1447
 
@@ -1119,7 +1450,11 @@ function statusLine(collected) {
1119
1450
 
1120
1451
  function render(data) {
1121
1452
  const lines = [];
1122
- lines.push('Claude Code usage');
1453
+ // Codex meters an allowance and never quotes a price, so its report has no
1454
+ // honest money column. Everything else in the table means the same thing on
1455
+ // both hosts.
1456
+ const money = data.money !== false;
1457
+ lines.push((data.host === host.CODEX ? 'Codex usage' : 'Claude Code usage'));
1123
1458
  lines.push('');
1124
1459
  lines.push(' Plan ' + data.plan);
1125
1460
  lines.push(
@@ -1128,9 +1463,13 @@ function render(data) {
1128
1463
  );
1129
1464
  lines.push(' Settings model=' + data.settings.model + ' effort=' + data.settings.effortLevel);
1130
1465
  const credits = data.credits;
1131
- if (credits) {
1466
+ if (credits && credits.unlimited) {
1467
+ lines.push(' Credits unlimited');
1468
+ } else if (credits) {
1132
1469
  if (!credits.enabled) {
1133
1470
  lines.push(' Credits off, work stops when the plan allowance runs out');
1471
+ } else if (!money) {
1472
+ lines.push(' Credits on, balance ' + (credits.balance === null ? 'unknown' : credits.balance));
1134
1473
  } else {
1135
1474
  const amounts =
1136
1475
  credits.used === null
@@ -1147,14 +1486,31 @@ function render(data) {
1147
1486
  lines.push('');
1148
1487
 
1149
1488
  if (!data.windows.length) {
1489
+ // Two different situations, and telling them apart matters. Nothing to read
1490
+ // is a setup problem. Nothing to report is the correct answer on a plan
1491
+ // whose usage scales with credits rather than resetting on a clock.
1492
+ if (data.windowless) {
1493
+ lines.push(' This account reports no rolling usage window.');
1494
+ lines.push(' On flexible pricing there is no percentage to run down: usage scales');
1495
+ lines.push(' with credits, so the credit balance above is the budget to plan against.');
1496
+ if (data.planAdvice) {
1497
+ lines.push('');
1498
+ lines.push(data.planAdvice);
1499
+ }
1500
+ return lines.join('\n');
1501
+ }
1150
1502
  lines.push(' No usage snapshot in ' + (data.accountFile || '~/.claude.json') + '.');
1151
- lines.push(' Run /usage once inside Claude Code to populate it, then try again.');
1503
+ lines.push(
1504
+ data.host === host.CODEX
1505
+ ? ' Run a Codex turn once so it writes one, or --refresh to ask for it now.'
1506
+ : ' Run /usage once inside Claude Code to populate it, then try again.'
1507
+ );
1152
1508
  return lines.join('\n');
1153
1509
  }
1154
1510
 
1155
1511
  lines.push(
1156
1512
  ' ' + pad('Window', 15) + padLeft('Used', 6) + padLeft('Resets in', 12) +
1157
- padLeft('Left', 10) + padLeft('Turns left', 12)
1513
+ (money ? padLeft('Left', 10) : '') + padLeft('Turns left', 12)
1158
1514
  );
1159
1515
  for (const window of data.windows) {
1160
1516
  const marker = data.binding && window.key === data.binding.key ? ' <- binding' : '';
@@ -1169,13 +1525,30 @@ function render(data) {
1169
1525
  6
1170
1526
  ) +
1171
1527
  padLeft(formatDuration(window.msToReset), 12) +
1172
- padLeft(formatUSD(window.remainingUSD), 10) +
1528
+ (money ? padLeft(formatUSD(window.remainingUSD), 10) : '') +
1173
1529
  padLeft(window.turnsLeft === null ? '-' : '~' + formatCount(window.turnsLeft), 12) +
1174
1530
  marker
1175
1531
  );
1176
1532
  }
1177
1533
  lines.push('');
1178
1534
 
1535
+ // A bucket with no span cannot be priced or projected, but saying nothing
1536
+ // about one that is nearly full would be the worse failure.
1537
+ if (data.otherLimits && data.otherLimits.length) {
1538
+ lines.push(' Other limits reported by the account');
1539
+ for (const row of data.otherLimits) {
1540
+ lines.push(
1541
+ ' ' + pad(' ' + row.label, 24) + padLeft(row.percentUsed + '%', 6) +
1542
+ padLeft(
1543
+ Number.isFinite(row.resetsAt) ? formatDuration(row.resetsAt - data.now) : '-',
1544
+ 12
1545
+ )
1546
+ );
1547
+ }
1548
+ lines.push(' No window length is reported for these, so they are not projected.');
1549
+ lines.push('');
1550
+ }
1551
+
1179
1552
  if (data.models && data.models.length) {
1180
1553
  lines.push(' Models in the ' + (data.scopeLabel || 'window') + ' window');
1181
1554
  lines.push(
@@ -1184,14 +1557,15 @@ function render(data) {
1184
1557
  );
1185
1558
  for (const row of data.models) {
1186
1559
  lines.push(
1187
- ' ' + pad(' ' + row.model + (row.estimated ? ' *' : ''), 24) +
1560
+ ' ' + pad(' ' + row.model + (money && row.estimated ? ' *' : ''), 24) +
1188
1561
  padLeft(row.turns, 7) +
1189
1562
  padLeft(formatTokens(row.tokens), 10) +
1190
1563
  padLeft(formatTokens(row.parts.output), 9) +
1191
1564
  padLeft(Math.round(row.share * 100) + '%', 8)
1192
1565
  );
1193
1566
  }
1194
- if (data.models.some((row) => row.estimated)) {
1567
+ // The footnote is about the price table, which only the Claude reader uses.
1568
+ if (money && data.models.some((row) => row.estimated)) {
1195
1569
  lines.push(' * no published rate for this one yet, priced at the family average');
1196
1570
  }
1197
1571
  if (data.tokens) {
@@ -1201,6 +1575,19 @@ function render(data) {
1201
1575
  ', cache read ' + formatTokens(data.tokens.cacheRead) +
1202
1576
  ', output ' + formatTokens(data.tokens.output)
1203
1577
  );
1578
+ // Output is the dearest class and reasoning is usually about half of it,
1579
+ // which makes this the largest number on the report that a setting can
1580
+ // actually move. Saying so without measuring it was advice; this is the
1581
+ // measurement.
1582
+ const reasoning = data.reasoning;
1583
+ if (reasoning && reasoning.tokens > 0) {
1584
+ lines.push(
1585
+ ' Of that output, ' + formatTokens(reasoning.tokens) + ' was reasoning (' +
1586
+ Math.round(reasoning.shareOfOutput * 100) + '%' +
1587
+ (money && reasoning.cost !== null ? ', about ' + formatUSD(reasoning.cost) : '') +
1588
+ '), the part effort controls.'
1589
+ );
1590
+ }
1204
1591
  }
1205
1592
  lines.push('');
1206
1593
  }
@@ -1234,8 +1621,8 @@ function render(data) {
1234
1621
 
1235
1622
  if (data.recent.turns) {
1236
1623
  lines.push(
1237
- ' Recent pace ' + data.recent.turns + ' turns in the last hour, ' +
1238
- formatUSD(data.recent.usdPerTurn) + ' per turn' +
1624
+ ' Recent pace ' + data.recent.turns + ' turns in the last hour' +
1625
+ (money ? ', ' + formatUSD(data.recent.usdPerTurn) + ' per turn' : '') +
1239
1626
  (data.recent.effort ? ', effort ' + data.recent.effort : '')
1240
1627
  );
1241
1628
  } else {
@@ -1265,6 +1652,34 @@ function render(data) {
1265
1652
  lines.push(' Note the meter reads in whole percent, so a low reading is a wide bracket');
1266
1653
  }
1267
1654
 
1655
+ // A report taken shortly after a cutoff should say so. The percentages
1656
+ // describe the window running now and look perfectly healthy, which is
1657
+ // exactly why the fact that work was stopped an hour ago has to be stated
1658
+ // rather than left to be inferred from a number that no longer shows it.
1659
+ if (data.lastRefusal && Number.isFinite(data.lastRefusal.at) &&
1660
+ data.now - data.lastRefusal.at < 12 * HOUR) {
1661
+ const window = data.windows.find((one) => one.key === data.lastRefusal.key);
1662
+ lines.push(
1663
+ ' Cut off ' + formatDuration(data.now - data.lastRefusal.at) + ' ago the ' +
1664
+ ((window && window.label) || data.lastRefusal.key) + ' limit refused work' +
1665
+ (Number.isFinite(data.lastRefusal.resetsAt)
1666
+ ? ', and came back at ' + formatClock(data.lastRefusal.resetsAt)
1667
+ : '')
1668
+ );
1669
+ }
1670
+
1671
+ if (data.windows.some((window) => window.snapshotOlderThanWindow && !window.stale)) {
1672
+ lines.push(
1673
+ ' Note the snapshot is older than one of these windows, so its reading'
1674
+ );
1675
+ lines.push(
1676
+ ' describes a window that has since rolled over. ' +
1677
+ (data.host === host.CODEX
1678
+ ? 'Run --refresh for a live one.'
1679
+ : 'Run /usage for a fresh one.')
1680
+ );
1681
+ }
1682
+
1268
1683
  lines.push('');
1269
1684
  lines.push(verdictLine(data.binding));
1270
1685
  const binding = data.binding;
@@ -1341,9 +1756,11 @@ function renderForecast(data, turns) {
1341
1756
  }
1342
1757
  lines.push('');
1343
1758
  lines.push(
1344
- ' Priced from ' + data.rates.sample + ' recent turns: ' +
1345
- formatUSD(data.rates.median) + ' typical, ' + formatUSD(data.rates.high) +
1346
- ' at the expensive end.'
1759
+ data.money === false
1760
+ ? ' Priced from ' + data.rates.sample + ' recent turns, cheapest to dearest.'
1761
+ : ' Priced from ' + data.rates.sample + ' recent turns: ' +
1762
+ formatUSD(data.rates.median) + ' typical, ' + formatUSD(data.rates.high) +
1763
+ ' at the expensive end.'
1347
1764
  );
1348
1765
 
1349
1766
  const blocked = rows.filter((row) => !row.fits);
@@ -1359,6 +1776,15 @@ function renderForecast(data, turns) {
1359
1776
  ' It fits, but only if nothing goes wrong. Order the work so the valuable ' +
1360
1777
  'part lands first.'
1361
1778
  );
1779
+ } else if (data.sessions && data.sessions.length > 1) {
1780
+ // The percentages say it fits, and they would be right if this were the
1781
+ // only thing spending. It is not: the budget drains while these turns run,
1782
+ // so a verdict of "room for this" on its own is the one that gets someone
1783
+ // cut off mid-job.
1784
+ lines.push(
1785
+ ' It fits on its own, but ' + data.sessions.length + ' sessions are spending this ' +
1786
+ 'budget at once, so it will be gone sooner than these figures alone suggest.'
1787
+ );
1362
1788
  } else {
1363
1789
  lines.push(' There is room for this. No need to work around the limit.');
1364
1790
  }
@@ -1371,14 +1797,37 @@ function renderForecast(data, turns) {
1371
1797
  }
1372
1798
 
1373
1799
  async function main(argv) {
1800
+ // Settle the host before anything reads a file, so one run never mixes one
1801
+ // agent's percentages with the other's turns.
1802
+ setHost(host.detect(argv, process.env));
1803
+
1374
1804
  // The status line runs on every redraw, so it must not scan transcripts.
1375
1805
  if (argv.indexOf('--status') !== -1) {
1376
1806
  process.stdout.write(statusLine(collect(Date.now())) + '\n');
1377
1807
  return 0;
1378
1808
  }
1379
1809
 
1810
+ // Codex writes its meter into the session rollouts, so the cached reading is
1811
+ // only as fresh as the last request it made. Asking Codex itself is a second
1812
+ // and a child process, which is why it is opt-in rather than the default.
1813
+ let codexMeter = null;
1814
+ if (argv.indexOf('--refresh') !== -1) {
1815
+ if (!isCodex()) {
1816
+ process.stderr.write('usage: --refresh applies to Codex. Run /usage in Claude Code.\n');
1817
+ return 2;
1818
+ }
1819
+ try {
1820
+ codexMeter = await codex.refresh();
1821
+ } catch (err) {
1822
+ process.stderr.write(
1823
+ 'usage: could not read a live figure from Codex (' +
1824
+ ((err && err.code) || 'unknown') + '). Falling back to the newest one on disk.\n'
1825
+ );
1826
+ }
1827
+ }
1828
+
1380
1829
  const wantsJson = argv.indexOf('--json') !== -1;
1381
- const data = await report(Date.now());
1830
+ const data = await report(Date.now(), { codexMeter });
1382
1831
 
1383
1832
  const forecastAt = argv.indexOf('--forecast');
1384
1833
  if (forecastAt !== -1) {
@@ -1410,6 +1859,12 @@ if (require.main === module) {
1410
1859
 
1411
1860
  module.exports = {
1412
1861
  main,
1862
+ setHost,
1863
+ currentHost,
1864
+ isCodex,
1865
+ otherLimits,
1866
+ collectClaude,
1867
+ readClaudeEvents,
1413
1868
  RATES,
1414
1869
  WINDOWS,
1415
1870
  rateFor,
@@ -1425,6 +1880,7 @@ module.exports = {
1425
1880
  SATURATION_LIMIT,
1426
1881
  MIN_BASELINE_TURNS,
1427
1882
  buildWindows,
1883
+ lastRejections,
1428
1884
  bindingWindow,
1429
1885
  criticalOthers,
1430
1886
  betterCalibration,
@@ -1446,6 +1902,7 @@ module.exports = {
1446
1902
  collect,
1447
1903
  detectPlan,
1448
1904
  costPercentiles,
1905
+ reasoningSpend,
1449
1906
  forecastWindow,
1450
1907
  renderForecast,
1451
1908
  creditsFrom,