context-doctor 0.49.1 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +19 -17
  2. package/dist/apptools.d.ts +89 -0
  3. package/dist/apptools.js +203 -0
  4. package/dist/appwindow.d.ts +75 -0
  5. package/dist/appwindow.js +161 -0
  6. package/dist/budget.d.ts +20 -2
  7. package/dist/budget.js +43 -3
  8. package/dist/cachemisses.d.ts +70 -0
  9. package/dist/cachemisses.js +126 -0
  10. package/dist/ccost.js +8 -4
  11. package/dist/claudedir.d.ts +15 -0
  12. package/dist/claudedir.js +19 -1
  13. package/dist/cli.js +77 -29
  14. package/dist/clihelp.d.ts +5 -1
  15. package/dist/clihelp.js +9 -1
  16. package/dist/codexstatusline.d.ts +176 -0
  17. package/dist/codexstatusline.js +353 -0
  18. package/dist/compactwindow.d.ts +14 -2
  19. package/dist/compactwindow.js +30 -5
  20. package/dist/credits.d.ts +192 -0
  21. package/dist/credits.js +350 -0
  22. package/dist/doctor.d.ts +18 -0
  23. package/dist/doctor.js +62 -3
  24. package/dist/fanout.d.ts +2 -0
  25. package/dist/fanout.js +12 -2
  26. package/dist/fileparams.js +15 -3
  27. package/dist/fix.d.ts +48 -3
  28. package/dist/fix.js +112 -19
  29. package/dist/limits.d.ts +87 -2
  30. package/dist/limits.js +329 -29
  31. package/dist/mcp.d.ts +1 -0
  32. package/dist/mcp.js +106 -100
  33. package/dist/mod/api.d.ts +27 -1
  34. package/dist/mod/api.js +2 -1
  35. package/dist/mod/logic.d.ts +85 -1
  36. package/dist/mod/logic.js +118 -5
  37. package/dist/mod/register.d.ts +16 -2
  38. package/dist/mod/register.js +59 -5
  39. package/dist/modelids.d.ts +15 -0
  40. package/dist/modelids.js +35 -2
  41. package/dist/modmeasure.d.ts +7 -0
  42. package/dist/modmeasure.js +9 -0
  43. package/dist/orgrates.d.ts +4 -2
  44. package/dist/orgrates.js +21 -3
  45. package/dist/overhead.js +10 -3
  46. package/dist/pricing.js +7 -0
  47. package/dist/progresssummaries.d.ts +103 -1
  48. package/dist/progresssummaries.js +187 -11
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +9 -4
  51. package/dist/savings.js +3 -1
  52. package/dist/spend.d.ts +32 -3
  53. package/dist/spend.js +68 -6
  54. package/dist/starts.d.ts +34 -1
  55. package/dist/starts.js +88 -21
  56. package/dist/usagepane.js +1 -1
  57. package/package.json +1 -1
package/dist/limits.js CHANGED
@@ -153,17 +153,21 @@ export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath(
153
153
  });
154
154
  if (!due.length)
155
155
  return 0;
156
- if (existsSync(path) && statSync(path).size > LOG_ROTATE_AT) {
157
- const text = tail(path, LOG_KEEP_BYTES);
158
- writeFileSync(path, text.slice(text.indexOf("\n") + 1));
159
- }
160
- appendFileSync(path, due.map((l) => JSON.stringify(l)).join("\n") + "\n");
156
+ appendLog(path, due);
161
157
  return due.length;
162
158
  }
163
159
  catch {
164
160
  return 0;
165
161
  }
166
162
  }
163
+ /** Append lines to the log, keeping its newest LOG_KEEP_BYTES once it passes LOG_ROTATE_AT. Throws on a write error (callers catch). */
164
+ function appendLog(path, lines) {
165
+ if (existsSync(path) && statSync(path).size > LOG_ROTATE_AT) {
166
+ const text = tail(path, LOG_KEEP_BYTES);
167
+ writeFileSync(path, text.slice(text.indexOf("\n") + 1));
168
+ }
169
+ appendFileSync(path, lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
170
+ }
167
171
  /** Every Claude reading in the log since `since`. */
168
172
  export function readClaudeReadings(since = 0, path = limitsLogPath()) {
169
173
  if (!existsSync(path))
@@ -206,6 +210,98 @@ export function rateLimitsFromHeaders(get) {
206
210
  }
207
211
  return Object.keys(out).length ? out : undefined;
208
212
  }
213
+ export function overageFromHeaders(get) {
214
+ const h = (n) => {
215
+ const v = get(`anthropic-ratelimit-unified-overage-${n}`);
216
+ return typeof v === "string" && v.trim() !== "" ? v.trim() : undefined;
217
+ };
218
+ const out = {};
219
+ const status = h("status");
220
+ if (status && /^[a-z_]{1,40}$/.test(status))
221
+ out.status = status;
222
+ const inUse = h("in-use");
223
+ if (inUse === "true" || inUse === "false")
224
+ out.inUse = inUse === "true";
225
+ const u = Number(h("utilization"));
226
+ if (h("utilization") !== undefined && Number.isFinite(u) && u >= 0 && u <= 10)
227
+ out.pct = Math.round(u * 1000) / 10;
228
+ const reset = Number(h("reset"));
229
+ if (h("reset") !== undefined && Number.isFinite(reset) && reset > 0)
230
+ out.reset = Math.round(reset);
231
+ return Object.keys(out).length ? out : undefined;
232
+ }
233
+ function parseOverageLine(line) {
234
+ let e;
235
+ try {
236
+ e = JSON.parse(line);
237
+ }
238
+ catch {
239
+ return undefined;
240
+ }
241
+ if (!e || typeof e !== "object" || e.w !== "overage" || typeof e.ts !== "number" || !Number.isFinite(e.ts))
242
+ return undefined;
243
+ return {
244
+ ts: e.ts, app: "claude", w: "overage",
245
+ ...(typeof e.status === "string" && /^[a-z_]{1,40}$/.test(e.status) ? { status: e.status } : {}),
246
+ ...(typeof e.inUse === "boolean" ? { inUse: e.inUse } : {}),
247
+ ...(typeof e.pct === "number" && Number.isFinite(e.pct) && e.pct >= 0 && e.pct <= 1000 ? { pct: e.pct } : {}),
248
+ ...(typeof e.reset === "number" && Number.isFinite(e.reset) && e.reset > 0 ? { reset: e.reset } : {}),
249
+ ...(typeof e.src === "string" && SOURCES.includes(e.src) ? { src: e.src } : {}),
250
+ };
251
+ }
252
+ /**
253
+ * Append what the credits headers say to the same log as the windows, as a
254
+ * line of its own (`"w": "overage"`, which older versions skip): at
255
+ * once when the status, whether credits are in use, or the reset changed;
256
+ * a moved utilization at most once a minute; an unchanged one every 15
257
+ * minutes. Never throws. Returns the lines written (0 or 1).
258
+ */
259
+ export function recordOverage(o, now = Date.now(), path = limitsLogPath(), source = "proxy") {
260
+ if (!o)
261
+ return 0;
262
+ const line = { ts: now, app: "claude", w: "overage", ...o, src: source };
263
+ try {
264
+ mkdirSync(dirname(path), { recursive: true });
265
+ let last;
266
+ if (existsSync(path)) {
267
+ for (const l of tail(path, 16 * 1024).split("\n"))
268
+ last = parseOverageLine(l) ?? last;
269
+ }
270
+ const sameReset = last && (last.reset !== undefined && line.reset !== undefined ? Math.abs(last.reset - line.reset) * 1000 <= SAME_RESET_MS : last.reset === line.reset);
271
+ const due = !last || now < last.ts || last.status !== line.status || last.inUse !== line.inUse || !sameReset
272
+ ? true
273
+ : last.pct === line.pct ? now - last.ts >= KEEPALIVE_MS : now - last.ts >= THROTTLE_MS;
274
+ if (!due)
275
+ return 0;
276
+ appendLog(path, [line]);
277
+ return 1;
278
+ }
279
+ catch {
280
+ return 0;
281
+ }
282
+ }
283
+ /** Every credits reading in the log since `since`, oldest first. */
284
+ export function readOverageReadings(since = 0, path = limitsLogPath()) {
285
+ if (!existsSync(path))
286
+ return [];
287
+ let text;
288
+ try {
289
+ text = readFileSync(path, "utf8");
290
+ }
291
+ catch {
292
+ return [];
293
+ }
294
+ const out = [];
295
+ for (const line of text.split("\n")) {
296
+ if (!line.includes('"overage"'))
297
+ continue;
298
+ const l = parseOverageLine(line);
299
+ if (!l || l.ts < since)
300
+ continue;
301
+ out.push({ ts: l.ts, ...(l.status ? { status: l.status } : {}), ...(l.inUse !== undefined ? { inUse: l.inUse } : {}), ...(l.pct !== undefined ? { pct: l.pct } : {}), ...(l.reset ? { resetsAt: l.reset * 1000 } : {}), ...(l.src ? { source: l.src } : {}) });
302
+ }
303
+ return out.sort((a, b) => a.ts - b.ts);
304
+ }
209
305
  // ---------------------------------------------------------------------------
210
306
  // Codex: readings and usage, both from its rollouts
211
307
  // ---------------------------------------------------------------------------
@@ -787,7 +883,15 @@ export function windowStatus(readings, now = Date.now()) {
787
883
  const period = readings.slice(first);
788
884
  const lookback = last.windowMs && last.windowMs <= 5 * HOUR ? HOUR : DAY;
789
885
  const recent = period.filter((r) => r.ts >= last.ts - lookback);
790
- const from = recent[0];
886
+ // A window that began within the lookback was at 0% when it began: the
887
+ // pace counts from there. From the period's first reading alone, a weekly
888
+ // window read for the first time hours after its reset (nothing used
889
+ // since) took ten minutes' burst for the day's pace and said a 2% week
890
+ // ran out in 8 hours.
891
+ const start = last.windowMs && last.resetsAt ? last.resetsAt - last.windowMs : undefined;
892
+ const from = start !== undefined && recent[0] && start >= last.ts - lookback && start < recent[0].ts
893
+ ? { ts: start, pct: 0 }
894
+ : recent[0];
791
895
  if (from && last.ts - from.ts >= 10 * MIN) {
792
896
  status.recentPerHour = Math.max(0, ((last.pct - from.pct) / (last.ts - from.ts)) * HOUR);
793
897
  }
@@ -1095,6 +1199,12 @@ const MIN_KEY_SHARE = 0.05;
1095
1199
  const MAX_KEY_REL_SE = 0.3;
1096
1200
  /** Windows this long or longer are fitted per reset (Claude's weekly; Codex's weekly and monthly). */
1097
1201
  const PER_RESET_MIN_MS = 7 * DAY - HOUR;
1202
+ /** A mix that moved less than this (half the summed share changes) held. */
1203
+ const MIX_HELD = 0.1;
1204
+ /** The mix's prediction must cover this share of each side's dollars with per-model rates. */
1205
+ const MIX_COVER = 0.9;
1206
+ /** A mix prediction within this factor of 1 is no mix move worth naming beside a limit move. */
1207
+ const MIX_NAMED = 1.2;
1098
1208
  /** Ratio of sums, sum(u) / sum(d), and its relative standard error (the ratio estimator's, across stretches). */
1099
1209
  function ratio(u, d) {
1100
1210
  const n = u.length;
@@ -1199,6 +1309,20 @@ function splitBy(segments, inSeg, keyOf, whole) {
1199
1309
  }
1200
1310
  return list;
1201
1311
  }
1312
+ /** The requests of each stretch: both lists are in time order. */
1313
+ function usageBySegment(segments, usage) {
1314
+ const inSeg = segments.map(() => []);
1315
+ let g = 0;
1316
+ for (const p of usage) {
1317
+ while (g < segments.length && segments[g].to < p.ts)
1318
+ g++;
1319
+ if (g >= segments.length)
1320
+ break;
1321
+ if (p.ts > segments[g].from)
1322
+ inSeg[g].push(p);
1323
+ }
1324
+ return inSeg;
1325
+ }
1202
1326
  /** One window's readings cut at each reset: the periods, oldest first. */
1203
1327
  function periodsOf(readings) {
1204
1328
  const clean = cleanReadings(readings);
@@ -1227,17 +1351,7 @@ export function resetWindowsOf(readings, usage, opts = {}) {
1227
1351
  const windowMs = last.windowMs ?? 7 * DAY;
1228
1352
  const resetsAt = last.resetsAt ?? first.ts + windowMs;
1229
1353
  const { segments, elsewherePct } = segmentsOf(period, usage, opts.stretchMs);
1230
- // The requests of each stretch: both lists are in time order.
1231
- const inSeg = segments.map(() => []);
1232
- let g = 0;
1233
- for (const p of usage) {
1234
- while (g < segments.length && segments[g].to < p.ts)
1235
- g++;
1236
- if (g >= segments.length)
1237
- break;
1238
- if (p.ts > segments[g].from)
1239
- inSeg[g].push(p);
1240
- }
1354
+ const inSeg = usageBySegment(segments, usage);
1241
1355
  const usd = segments.reduce((a, s) => a + s.usd, 0);
1242
1356
  const tokens = inSeg.reduce((a, pts) => a + pts.reduce((b, p) => b + tokensOf(p), 0), 0);
1243
1357
  const pctMatched = segments.reduce((a, s) => a + s.dpct, 0);
@@ -1310,15 +1424,158 @@ function sigmaOf(a, b, factor) {
1310
1424
  const se = Math.sqrt(a.relSe ** 2 + b.relSe ** 2);
1311
1425
  return se > 0 ? Math.abs(Math.log(factor)) / se : Infinity;
1312
1426
  }
1427
+ function mixRows(segs, usage, after) {
1428
+ const inSeg = usageBySegment(segs, usage);
1429
+ return segs.map((s, i) => {
1430
+ const byModel = new Map();
1431
+ for (const p of inSeg[i]) {
1432
+ const k = reportModel(p.model);
1433
+ byModel.set(k, (byModel.get(k) ?? 0) + p.usd);
1434
+ }
1435
+ return { dpct: s.dpct, byModel, after };
1436
+ });
1437
+ }
1438
+ function sharesOf(rows) {
1439
+ const t = new Map();
1440
+ let all = 0;
1441
+ for (const r of rows)
1442
+ for (const [k, v] of r.byModel) {
1443
+ t.set(k, (t.get(k) ?? 0) + v);
1444
+ all += v;
1445
+ }
1446
+ return all > 0 ? Object.fromEntries([...t].sort((a, b) => b[1] - a[1]).map(([k, v]) => [k, v / all])) : {};
1447
+ }
1448
+ /**
1449
+ * Per-model % of the limit per dollar, fitted on both sides' stretches at
1450
+ * once with one factor f for the after side (dpct = Σ β_m·usd_m, times f
1451
+ * after the move): f searched for, the rates least squares at each. β is
1452
+ * each model's rate before the move, and a move of the limit itself goes to
1453
+ * f instead of bending the rates. Fitting the rates over both sides with no
1454
+ * f would credit a model used mostly after a real move with that move. Undefined when the stretches cannot tell the
1455
+ * models apart (a rate at or below zero, or known worse than ±30%).
1456
+ */
1457
+ function jointRates(rows, keys) {
1458
+ if (keys.length < 2 || rows.length <= keys.length + 2)
1459
+ return undefined;
1460
+ const y = rows.map((r) => r.dpct);
1461
+ // For a given after-side factor the rates are plain least squares: search
1462
+ // the factor (on the log scale, 1/10x to 10x) for the least squared error.
1463
+ const at = (logF) => {
1464
+ const f = Math.exp(logF);
1465
+ const fit = olsSe(rows.map((r) => keys.map((k) => (r.byModel.get(k) ?? 0) * (r.after ? f : 1))), y);
1466
+ const sse = fit ? rows.reduce((a, r, i) => a + (y[i] - keys.reduce((b, k, j) => b + fit.coef[j] * (r.byModel.get(k) ?? 0) * (r.after ? f : 1), 0)) ** 2, 0) : Infinity;
1467
+ return { fit, sse };
1468
+ };
1469
+ let lo = -Math.log(10), hi = Math.log(10);
1470
+ const g = (Math.sqrt(5) - 1) / 2;
1471
+ let x1 = hi - g * (hi - lo), x2 = lo + g * (hi - lo);
1472
+ let f1 = at(x1).sse, f2 = at(x2).sse;
1473
+ for (let it = 0; it < 60 && hi - lo > 1e-5; it++) {
1474
+ if (f1 <= f2) {
1475
+ hi = x2;
1476
+ x2 = x1;
1477
+ f2 = f1;
1478
+ x1 = hi - g * (hi - lo);
1479
+ f1 = at(x1).sse;
1480
+ }
1481
+ else {
1482
+ lo = x1;
1483
+ x1 = x2;
1484
+ f1 = f2;
1485
+ x2 = lo + g * (hi - lo);
1486
+ f2 = at(x2).sse;
1487
+ }
1488
+ }
1489
+ const { fit } = at((lo + hi) / 2);
1490
+ if (!fit || fit.coef.some((b, j) => !(b > 0) || fit.se[j] / b > MAX_KEY_REL_SE))
1491
+ return undefined;
1492
+ return new Map(keys.map((k, j) => [k, fit.coef[j]]));
1493
+ }
1494
+ /** A window's own per-model rates (splitBy's), as % per dollar: none for the pooled "other". */
1495
+ function windowRates(w) {
1496
+ return new Map(w.byModel.filter((t) => t.usdPerPct !== undefined && t.usdPerPct > 0 && t.key !== "other").map((t) => [t.key, 1 / t.usdPerPct]));
1497
+ }
1498
+ /** Dollars per 1% a mix gives at per-model rates, over the dollars those rates cover; undefined under MIX_COVER. */
1499
+ function predicted(shares, rates) {
1500
+ let cover = 0, pctPerUsd = 0;
1501
+ for (const [k, s] of Object.entries(shares)) {
1502
+ const b = rates.get(k);
1503
+ if (b === undefined)
1504
+ continue;
1505
+ cover += s;
1506
+ pctPerUsd += s * b;
1507
+ }
1508
+ return cover >= MIX_COVER && pctPerUsd > 0 ? cover / pctPerUsd : undefined;
1509
+ }
1510
+ /**
1511
+ * The mix on each side of a move and what it alone predicts: rates from the
1512
+ * joint fit on the two sides' stretches, else the first of `fallback` (the
1513
+ * windows' own per-model figures, nearest first) that covers both sides.
1514
+ */
1515
+ function mixOf(before, after, fallback) {
1516
+ const sb = sharesOf(before), sa = sharesOf(after);
1517
+ const keys = [...new Set([...Object.keys(sb), ...Object.keys(sa)])];
1518
+ if (!keys.length || keys.every((k) => k === "unknown"))
1519
+ return undefined;
1520
+ const delta = keys.map((k) => [k, (sa[k] ?? 0) - (sb[k] ?? 0)]).sort((a, b) => b[1] - a[1]);
1521
+ const mix = {
1522
+ before: sb, after: sa, grew: delta[0][0],
1523
+ ...(delta.length > 1 && delta[delta.length - 1][1] < 0 ? { shrank: delta[delta.length - 1][0] } : {}),
1524
+ moved: delta.reduce((a, [, d]) => a + Math.abs(d), 0) / 2,
1525
+ };
1526
+ const named = keys.filter((k) => k !== "unknown" && k !== "other" && Math.max(sb[k] ?? 0, sa[k] ?? 0) >= MIN_KEY_SHARE);
1527
+ // The joint fit tells a model's own rate from a move only for a model used on both sides: one used on one side alone carries the move in its rate.
1528
+ const both = named.every((k) => (sb[k] ?? 0) >= MIN_KEY_SHARE && (sa[k] ?? 0) >= MIN_KEY_SHARE);
1529
+ const tries = [both ? jointRates([...before, ...after], named) : undefined, ...fallback].filter((r) => !!r && r.size > 0);
1530
+ for (const rates of tries) {
1531
+ const pb = predicted(sb, rates), pa = predicted(sa, rates);
1532
+ if (pb === undefined || pa === undefined)
1533
+ continue;
1534
+ mix.pctPerUsd = Object.fromEntries([...rates].filter(([k]) => k in sb || k in sa));
1535
+ mix.predictedBefore = pb;
1536
+ mix.predictedAfter = pa;
1537
+ return { mix, mixFactor: pa / pb };
1538
+ }
1539
+ return { mix };
1540
+ }
1541
+ /** Set a move's mix fields and its cause (SlopeChange.cause). `minSigma`: the bar the move itself had to clear. */
1542
+ function explainMove(c, before, after, fallback, se, minSigma) {
1543
+ const got = mixOf(before, after, fallback);
1544
+ if (!got)
1545
+ return;
1546
+ c.mix = got.mix;
1547
+ // A mix that held explains nothing, whatever the rates say.
1548
+ const mixFactor = got.mix.moved < MIX_HELD ? 1 : got.mixFactor;
1549
+ if (mixFactor === undefined) {
1550
+ c.cause = "unclear";
1551
+ return;
1552
+ }
1553
+ c.mixFactor = mixFactor;
1554
+ c.residual = c.factor / mixFactor;
1555
+ c.residualSigma = sigmaOf({ relSe: se.before }, { relSe: se.after }, c.residual);
1556
+ const limitMoved = Math.max(c.residual, 1 / c.residual) >= MIN_FACTOR && c.residualSigma >= minSigma;
1557
+ c.cause = !limitMoved ? "mix" : Math.max(mixFactor, 1 / mixFactor) >= MIX_NAMED ? "both" : "limit";
1558
+ }
1313
1559
  /**
1314
1560
  * Where what 1% costs moved: between consecutive windows that each have a
1315
1561
  * figure (dated at the reset), and inside a window at the one split of its
1316
1562
  * stretches that separates two rates best (dated at that stretch). Reported
1317
1563
  * from a 1.5x move either way, beyond 3 standard errors between windows and
1318
- * 4 inside one (the split is searched for).
1564
+ * 4 inside one (the split is searched for). Each move is checked against
1565
+ * the model mix on its two sides (explainMove; needs `readings` to find the
1566
+ * stretches): `cause` says whether the limit moved or the mix did.
1319
1567
  */
1320
1568
  export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1321
1569
  const out = [];
1570
+ const periods = readings.length ? periodsOf(readings) : [];
1571
+ const periodOf = (w) => periods.find((p) => p[0].ts === w.firstReading && p[p.length - 1].ts === w.lastReading);
1572
+ /**
1573
+ * The mix's fallback rates: `first`'s own per-model figures, then the other
1574
+ * windows', nearest to `around` first, never `skip`'s (a window that holds
1575
+ * a move inside it fits its rates across that move: a model used mostly
1576
+ * after it would carry the move as its own rate).
1577
+ */
1578
+ const ratesNear = (around, first, skip) => [...first, ...windows.filter((x) => !first.includes(x) && x !== skip && x.window === around.window).sort((x, y) => Math.abs(x.start - around.start) - Math.abs(y.start - around.start))].map(windowRates);
1322
1579
  const quoted = windows.filter((w) => w.usdPerPct !== undefined && w.relSe !== undefined && Number.isFinite(w.relSe) && !w.why);
1323
1580
  for (let i = 1; i < quoted.length; i++) {
1324
1581
  const a = quoted[i - 1], b = quoted[i];
@@ -1328,17 +1585,20 @@ export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1328
1585
  const sigma = sigmaOf({ relSe: a.relSe }, { relSe: b.relSe }, factor);
1329
1586
  if (Math.max(factor, 1 / factor) < MIN_FACTOR || sigma < RESET_SIGMA)
1330
1587
  continue;
1331
- out.push({
1588
+ const c = {
1332
1589
  window: b.window, label: b.label, kind: "reset", at: b.start, prevEnd: a.resetsAt,
1333
1590
  usdPerPctBefore: a.usdPerPct, usdPerPctAfter: b.usdPerPct, tokensPerPctBefore: a.tokensPerPct, tokensPerPctAfter: b.tokensPerPct,
1334
1591
  factor, sigma, versionsBefore: a.versions, versionsAfter: b.versions,
1335
- });
1592
+ };
1593
+ const pa = periodOf(a), pb = periodOf(b);
1594
+ if (pa && pb)
1595
+ explainMove(c, mixRows(segmentsOf(pa, usage, stretchMs).segments, usage, false), mixRows(segmentsOf(pb, usage, stretchMs).segments, usage, true), ratesNear(a, [a, b]), { before: a.relSe, after: b.relSe }, RESET_SIGMA);
1596
+ out.push(c);
1336
1597
  }
1337
1598
  // Inside a window: its own stretches again, split once where two rates fit best.
1338
- const periods = readings.length ? periodsOf(readings) : [];
1339
1599
  // Every window with a figure, loose ones too: a move inside a window is what makes its figure loose.
1340
1600
  for (const w of windows.filter((x) => x.usdPerPct !== undefined)) {
1341
- const period = periods.find((p) => p[0].ts === w.firstReading && p[p.length - 1].ts === w.lastReading);
1601
+ const period = periodOf(w);
1342
1602
  if (!period)
1343
1603
  continue;
1344
1604
  const segs = segmentsOf(period, usage, stretchMs).segments;
@@ -1370,11 +1630,13 @@ export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1370
1630
  return pct > 0 ? t / pct : undefined;
1371
1631
  };
1372
1632
  const vers = (from, to) => [...new Set(usage.filter((p) => p.ts > segs[from].from && p.ts <= segs[to - 1].to).map((p) => p.version).filter((v) => !!v))].sort(compareVersions);
1373
- out.push({
1633
+ const c = {
1374
1634
  window: w.window, label: w.label, kind: "within", at: segs[best.at].from,
1375
1635
  usdPerPctBefore: before.r, usdPerPctAfter: after.r, tokensPerPctBefore: tok(0, best.at), tokensPerPctAfter: tok(best.at, segs.length),
1376
1636
  factor, sigma, versionsBefore: vers(0, best.at), versionsAfter: vers(best.at, segs.length),
1377
- });
1637
+ };
1638
+ explainMove(c, mixRows(segs.slice(0, best.at), usage, false), mixRows(segs.slice(best.at), usage, true), ratesNear(w, [], w), { before: before.relSe, after: after.relSe }, WITHIN_SIGMA);
1639
+ out.push(c);
1378
1640
  }
1379
1641
  return out.sort((a, b) => a.at - b.at);
1380
1642
  }
@@ -1547,10 +1809,36 @@ function changeLine(c) {
1547
1809
  ? `between the reset of ${utcMinute(c.prevEnd)} and the window from ${utcMinute(c.at)}`
1548
1810
  : `at the reset of ${utcMinute(c.at)}`
1549
1811
  : `within the window, around ${utcMinute(c.at)}`;
1550
- const times = c.factor < 1 ? `${(1 / c.factor).toFixed(1)}x less use per 1%: the limit drains faster` : `${c.factor.toFixed(1)}x more use per 1%: the limit drains slower`;
1812
+ const move = (f) => (f < 1 ? `${(1 / f).toFixed(1)}x less use per 1%` : `${f.toFixed(1)}x more use per 1%`);
1813
+ const drains = (f) => (f < 1 ? "the limit drains faster" : "the limit drains slower");
1551
1814
  const tok = c.tokensPerPctBefore !== undefined && c.tokensPerPctAfter !== undefined ? `; tokens per 1% ${tokenCount(c.tokensPerPctBefore)} to ${tokenCount(c.tokensPerPctAfter)}` : "";
1552
1815
  const ver = versionSpan(c.versionsBefore) !== versionSpan(c.versionsAfter) ? `; Claude Code ${versionSpan(c.versionsBefore)} before, ${versionSpan(c.versionsAfter)} after` : "";
1553
- return `${c.label}, ${when}: 1% went from ${dollars(c.usdPerPctBefore)} to ${dollars(c.usdPerPctAfter)} of API-equivalent use (${times})${tok}${ver}.`;
1816
+ const head = `${c.label}, ${when}: 1% went from ${dollars(c.usdPerPctBefore)} to ${dollars(c.usdPerPctAfter)} of API-equivalent use`;
1817
+ if (!c.cause || c.cause === "limit" || !c.mix)
1818
+ return `${head} (${move(c.factor)}: ${drains(c.factor)})${tok}${ver}.`;
1819
+ const m = c.mix;
1820
+ const pct = (v) => `${Math.round((v ?? 0) * 100)}%`;
1821
+ const used = `you used ${modelLabel(m.grew)} for ${pct(m.after[m.grew])} of your dollars after it (${pct(m.before[m.grew])} before)`;
1822
+ const rate = m.pctPerUsd?.[m.grew], other = m.shrank ? m.pctPerUsd?.[m.shrank] : undefined;
1823
+ const ratio = rate !== undefined && other !== undefined && other > 0 ? rate / other : undefined;
1824
+ const per = ratio === undefined || (ratio < 1.1 && ratio > 1 / 1.1) ? ""
1825
+ : ratio > 1 ? `, which uses your limit ${ratio.toFixed(1)}x faster per dollar than ${modelLabel(m.shrank)}`
1826
+ : `, which uses your limit ${(1 / ratio).toFixed(1)}x slower per dollar than ${modelLabel(m.shrank)}`;
1827
+ const predicted = m.predictedBefore !== undefined && m.predictedAfter !== undefined ? `; the mix alone predicts ${dollars(m.predictedBefore)} to ${dollars(m.predictedAfter)}` : "";
1828
+ if (c.cause === "unclear") {
1829
+ return `${head} (${move(c.factor)}), and your model mix changed too: ${used}. Per-model figures are too thin yet to say how much of the move that explains${tok}${ver}.`;
1830
+ }
1831
+ const r = c.residual;
1832
+ if (c.cause === "mix") {
1833
+ const left = Math.max(r, 1 / r) < 1.15 ? "per model, 1% buys about the same" : `per model, 1% buys ${move(r).replace(" per 1%", "")}, under the 1.5x this report calls a move`;
1834
+ return `${head} (${move(c.factor)}). This comes from your model mix, not the limit: ${used}${per}${predicted}; ${left}${tok}${ver}.`;
1835
+ }
1836
+ return `${head} (${move(c.factor)}). Part of it is your model mix: ${used}${per}${predicted}. Beyond the mix, per model, 1% buys ${move(r).replace(" per 1%", "")}: ${drains(r)}${tok}${ver}.`;
1837
+ }
1838
+ /** "claude-fable-5-2" as "Fable 5.2"; any other id as it is. */
1839
+ export function modelLabel(key) {
1840
+ const m = /^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(key ?? "");
1841
+ return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : key ?? "another model";
1554
1842
  }
1555
1843
  /** Each key's own dollars per 1%, where the fit told them apart: "sdk-cli $13.90 ±9%, cli $25.00 ±7% (sdk-cli drains 1.8x per dollar)". */
1556
1844
  function splitLine(list) {
@@ -1562,7 +1850,14 @@ function splitLine(list) {
1562
1850
  const ratio = slow.usdPerPct / fast.usdPerPct;
1563
1851
  return `${sorted.map((t) => `${t.key} ${dollars(t.usdPerPct)}${plusMinus(t.relSe)}`).join(", ")} per 1%${ratio >= 1.1 ? ` (${fast.key} drains ${ratio.toFixed(1)}x per dollar against ${slow.key})` : ""}`;
1564
1852
  }
1565
- export function renderLimits(r) {
1853
+ /**
1854
+ * The full `limits` report. `pastLimit`: lines on requests paid from usage
1855
+ * credits past a limit (credits.ts creditsLines), placed under the windows;
1856
+ * none when nothing went past one. `ahead`: the line on what running out
1857
+ * before the weekly reset would cost on usage credits (credits.ts
1858
+ * creditsAheadLine), under the weekly window's run-out.
1859
+ */
1860
+ export function renderLimits(r, pastLimit = [], ahead) {
1566
1861
  const out = ["USAGE LIMITS", "═".repeat(60)];
1567
1862
  if (!r.windows.length && !r.resets.length) {
1568
1863
  out.push(`No limit readings yet. ${HOW_TO_RECORD}`, "", `Claude readings are kept in ${r.claudeLog.replace(homedir(), "~")}; Codex's are read from ~/.codex/sessions (none in the period).`);
@@ -1584,18 +1879,23 @@ export function renderLimits(r) {
1584
1879
  else if (s.recentPerHour === 0)
1585
1880
  out.push(" Pace: no rise over the recent readings.");
1586
1881
  else {
1587
- const avg = s.averagePerHour !== undefined ? `; ${pts(s.averagePerHour)} a hour on average this window` : "";
1588
- out.push(` Pace: ${pts(s.recentPerHour)} points an hour lately${avg}.`);
1882
+ const avg = s.averagePerHour !== undefined ? `; ${pts(s.averagePerHour)}% an hour on average this window` : "";
1883
+ out.push(` Pace: ${pts(s.recentPerHour)}% of the limit an hour lately${avg}.`);
1589
1884
  if (s.runsOutAt !== undefined) {
1590
1885
  out.push(s.beforeReset
1591
1886
  ? ` At that pace it runs out ${clock(s.runsOutAt, r.now)} (in ${hm(s.runsOutAt - r.now)}), before the reset.`
1592
1887
  : " At that pace it lasts until the reset.");
1888
+ if (ahead && s.beforeReset && s.app === "claude" && s.window === "seven_day")
1889
+ out.push(` ${ahead}`);
1593
1890
  }
1594
1891
  }
1595
1892
  }
1596
1893
  if (r.claudeWindows.length === 1 && r.claudeWindows[0] === "seven_day") {
1597
1894
  out.push("", "No 5-hour window in Claude's readings: a plan without one (Ultra), so the weekly window is the limit.");
1598
1895
  }
1896
+ if (pastLimit.length) {
1897
+ out.push("", "Past your plan's limit: usage credits", "─".repeat(60), ...pastLimit);
1898
+ }
1599
1899
  if (r.resets.length) {
1600
1900
  out.push("", "Each weekly (or longer) window, reset to reset: API-equivalent use per 1% (UTC dates)");
1601
1901
  out.push("─".repeat(60));
package/dist/mcp.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * save_handoff — store a handoff brief the next chat starts from (a chat's history cannot be cut)
19
19
  * recall — search this session's own transcript (compacted turns, cleared output); stdio only
20
20
  * Prompts: context_checkup, handoff, ask_file. Resources (stdio): handoff://latest, handoff://<id>.
21
+ * Codex only (stdio): the `statusline` tool and ui://context-doctor/statusline, its footer (codexstatusline.ts).
21
22
  *
22
23
  * Built on the MCP SDK's v2 packages: one server definition answers both
23
24
  * protocol eras, a 2025-era client's `initialize` (2024-10-07 to 2025-11-25)