maxpool 1.24.67 → 1.24.69

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.
@@ -26,7 +26,33 @@
26
26
  // The OAuth reset-stamp jitter (see AccountManager.noteCapacityWindowAdvance) shredded
27
27
  // real windows into slivers and recorded future-dated weekly cycles, so a v1 payload's
28
28
  // averages are wrong for weeks. Starting empty costs one window; keeping it costs trust.
29
- const SCHEMA_VERSION = 3;
29
+ //
30
+ // v4 (2026-11-06): open and closed cycles carry per-reading SAMPLES ({t, tokens, util})
31
+ // so a cycle's capacity is a MEDIAN OF SEGMENT SLOPES (Δtokens/Δutil) instead of one
32
+ // tokens/util division at close; plus recorded-not-used model-family and cache
33
+ // counters. v3 payloads restore unchanged (their cycles simply have no samples).
34
+ //
35
+ // v5 (2026-11-06): TOKEN AXIS CHANGE. Capacity tokens = input + cache_read + cache_creation
36
+ // + output — every token the provider processed — for Anthropic AND z.ai, so the two sit
37
+ // on one axis. Everything recorded before v5 counted input+output only (axis 'io') and
38
+ // is NOT comparable: it is never blended into a median. On restore from <v5, closed
39
+ // rows are tagged axis 'io' (kept, excluded from the tank) and each in-flight cycle is
40
+ // closed as a legacy row; the next accrual opens a fresh axis-'all' cycle. A row with no
41
+ // `axis` field (an older linked pool's export) is legacy by definition.
42
+ export const SCHEMA_VERSION = 5;
43
+ const READABLE_SCHEMAS = new Set([3, 4, 5]);
44
+ export const AXIS_ALL = 'all';
45
+
46
+ // Samples kept per cycle. Beyond the cap the series is thinned to evenly spaced points.
47
+ const MAX_SAMPLES_PER_CYCLE = 64;
48
+ // A slope is only taken across a utilization move at least this wide (vendors report
49
+ // whole percents; 1pp over 5pp is already 20% noise, over 1pp it is 100%).
50
+ const MIN_SEGMENT_DUTIL = 0.05;
51
+ // Close-time tokens/util is a lone-sample fallback; trusted only when the window was
52
+ // nearly full (1pp of rounding is then <=2%).
53
+ const CLOSE_FALLBACK_MIN_UTIL = 0.5;
54
+ // Samples exported per cycle to a linked pool (bounded payload).
55
+ const EXPORT_SAMPLES = 16;
30
56
 
31
57
  // Two closes this far apart are the SAME boundary observed twice (a clock-close and a
32
58
  // stamp-advance racing across the boundary second), not two windows.
@@ -65,6 +91,182 @@ function demote(c) {
65
91
  return { ...c, complete: false, partialReason: 'pre-v3-unverified' };
66
92
  }
67
93
 
94
+
95
+ // Concurrent-cycle tolerance for merging two pools' histories of the SAME account window.
96
+ const MERGE_TOLERANCE_MS = 10 * 60_000;
97
+
98
+ /** Model family tag for the recorded (not yet used) per-model accrual breakdown. */
99
+ export function capacityModelFamily(model) {
100
+ const s = String(model || '').toLowerCase();
101
+ if (s.includes('opus')) return 'opus';
102
+ if (s.includes('sonnet')) return 'sonnet';
103
+ if (s.includes('haiku')) return 'haiku';
104
+ if (s.includes('glm')) return 'glm';
105
+ return 'other';
106
+ }
107
+
108
+ function median(arr) {
109
+ if (!arr.length) return null;
110
+ const a = arr.slice().sort((x, y) => x - y);
111
+ const m = a.length >> 1;
112
+ return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
113
+ }
114
+
115
+ /** Keep `max` evenly spaced samples (first and last always survive). */
116
+ function thin(samples, max = MAX_SAMPLES_PER_CYCLE) {
117
+ if (samples.length <= max) return samples;
118
+ const out = [];
119
+ for (let i = 0; i < max; i++) out.push(samples[Math.round(i * (samples.length - 1) / (max - 1))]);
120
+ return out;
121
+ }
122
+
123
+ /** Segment slopes Δtokens/Δutil over a cycle's samples. Greedy non-overlapping
124
+ * segments: anchor at a sample, close the segment at the first later sample whose
125
+ * utilization is >= MIN_SEGMENT_DUTIL higher, then anchor there. Pairs with a
126
+ * narrower move are skipped (whole-percent rounding turns them into noise); pairs
127
+ * with no token flow carry no information and are skipped too. */
128
+ export function segmentSlopes(samples) {
129
+ const out = [];
130
+ if (!Array.isArray(samples)) return out;
131
+ let anchor = null;
132
+ for (const s of samples) {
133
+ if (!Number.isFinite(s?.util) || !Number.isFinite(s?.tokens)) continue;
134
+ if (!anchor) { anchor = s; continue; }
135
+ if (s.util < anchor.util) { anchor = s; continue; } // refill inside the cycle
136
+ const du = s.util - anchor.util;
137
+ if (du >= MIN_SEGMENT_DUTIL - 1e-9 && s.util >= TANK_MIN_UTIL) {
138
+ const dt = s.tokens - anchor.tokens;
139
+ if (dt > 0) out.push(dt / du);
140
+ anchor = s;
141
+ }
142
+ }
143
+ return out;
144
+ }
145
+
146
+ /** ONE cycle's capacity estimate (no cross-cycle clamp — the old "physical floor"
147
+ * turned one big cycle into a floor under every other cycle):
148
+ * 1. median of segment slopes (the owner's "many measurements per cycle")
149
+ * 2. an exported estimate (`est`) from a pool whose samples we do not hold
150
+ * 3. close-time tokens/util, ONLY when the window ended nearly full (>= 0.5)
151
+ * else null = too little data (never shown as a bogus number). */
152
+ export function cycleEstimate(c) {
153
+ const slopes = segmentSlopes(c.samples);
154
+ if (slopes.length) return { tokens: median(slopes), method: 'slopes', segments: slopes.length };
155
+ if (Number.isFinite(c.est) && c.est > 0 && !c.merged) return { tokens: c.est, method: 'exported', segments: 0 };
156
+ if (Number.isFinite(c.finalUtilization) && c.finalUtilization >= CLOSE_FALLBACK_MIN_UTIL && c.tokens > 0) {
157
+ return { tokens: c.tokens / c.finalUtilization, method: 'close', segments: 0 };
158
+ }
159
+ return null;
160
+ }
161
+
162
+ const RECENT_CYCLES = 3;
163
+
164
+ /** Tank stats from a list of closed cycles (local ledger rows, remote exports, or a
165
+ * merge of both). Per cycle: cycleEstimate. Across cycles: MEDIAN (not mean).
166
+ * `n` = contributing cycles; `tooLittleData` = admitted cycles that yielded nothing. */
167
+ export function tankStatsFromCycles(cycles, window, { readFloor = null, ignoreCeiling = false } = {}) {
168
+ const floor = (readFloor ?? READ_FLOOR_MS)[window] ?? 0;
169
+ // AXIS GATE: only all-token cycles are capacity observations. Legacy input+output rows
170
+ // (axis 'io', or no axis from an older linked pool) are a different unit and are never
171
+ // blended into the median — they stay in the ledger as history only.
172
+ const admitted = (cycles || []).filter(c =>
173
+ c.axis === AXIS_ALL
174
+ && !c.disabledDuring
175
+ && c.partialReason !== 'pre-v3-unverified'
176
+ && c.partialReason !== 'no-weekly-plan'
177
+ && !c.spansRefill
178
+ && (ignoreCeiling || (c.endedAt - c.startedAt) <= WINDOW_MS[window] * WINDOW_CEIL_FACTOR));
179
+ const ests = [];
180
+ let tooLittle = 0;
181
+ for (const c of admitted) {
182
+ const est = cycleEstimate(c);
183
+ const span = c.endedAt - c.startedAt;
184
+ // Read floor: a cycle shorter than 80% of its window is junk UNLESS it is a real
185
+ // observation — it ended nearly full AND holds >= 2 qualifying samples (reports@
186
+ // joined mid-week: a 4.3-day weekly tail at util 1.0 is a true reading, and the
187
+ // slope method does not care that we joined late).
188
+ const short = span < floor - 1_000;
189
+ const realShort = est?.method === 'slopes' && c.finalUtilization >= CLOSE_FALLBACK_MIN_UTIL;
190
+ if (!est || (short && !realShort)) { tooLittle++; continue; }
191
+ ests.push({ c, est });
192
+ }
193
+ if (!ests.length) return null;
194
+ let exact = 0, bounded = 0;
195
+ for (const { c, est } of ests) {
196
+ const fromStart = c.startedAt != null && c.windowStartedAt != null
197
+ && c.startedAt <= c.windowStartedAt + 60_000 && c.complete;
198
+ // A slope is invariant to when we started counting, so it is never a late-join lower bound.
199
+ if (est.method === 'slopes' || est.method === 'exported' || fromStart) exact++; else bounded++;
200
+ }
201
+ const vals = ests.map(e => e.est.tokens);
202
+ const last = ests[ests.length - 1], prev = ests[ests.length - 2];
203
+ // `recent` = median over the LAST 3 qualifying cycles (fewer if fewer exist). `ests`
204
+ // keeps the input order, which closedCycles delivers oldest-first.
205
+ const recentVals = vals.slice(-RECENT_CYCLES);
206
+ return {
207
+ avg: Math.round(median(vals)), // field name kept for consumers: it IS the median over ALL cycles
208
+ recent: recentVals.length ? Math.round(median(recentVals)) : null,
209
+ recentN: recentVals.length,
210
+ exact, bounded, n: ests.length, tooLittleData: tooLittle,
211
+ // contributing cycles that are two-pool merges (samples dropped → close-time precision)
212
+ mergedCount: ests.filter(e => e.c.merged).length,
213
+ last: Math.round(last.est.tokens),
214
+ prev: prev ? Math.round(prev.est.tokens) : null,
215
+ lowerBound: bounded > 0 && exact === 0,
216
+ };
217
+ }
218
+
219
+ const cycleKey = (c) => c.resetAt ?? c.endedAt;
220
+
221
+ /** Union two pools' closed-cycle histories for ONE account. A window both pools saw
222
+ * (resetAt within ±10 min) is ONE vendor window that each pool measured from its OWN
223
+ * traffic only: tokens SUM, utilization is the vendor's global reading (MAX, never
224
+ * summed). Measured: mk@gomokka wk reset 11-04 — Mac 9.04M + cloud 1.34M at util 1.0
225
+ * is a 10.38M cycle; deduping would drop the cloud's 1.3M.
226
+ * Sample alignment across pools is impractical (different clocks, polling cadence,
227
+ * each series counts only its own pool's tokens), so a merged cycle drops its samples
228
+ * and is estimated as summed tokens / max util at close (needs util >= 0.5, as for any
229
+ * close-time reading). Disjoint cycles pass through untouched, samples included. */
230
+ export function mergeCycles(localCycles, remoteCycles) {
231
+ const local = (localCycles || []).map(c => ({ ...c }));
232
+ const used = new Set();
233
+ const out = [];
234
+ const remotes = (remoteCycles || []).slice().sort((a, b) => cycleKey(a) - cycleKey(b));
235
+ const matched = new Map(); // local idx -> merged cycle
236
+ for (const r of remotes) {
237
+ let best = -1, bestD = Infinity;
238
+ for (let i = 0; i < local.length; i++) {
239
+ if (used.has(i)) continue;
240
+ if ((local[i].axis ?? 'io') !== (r.axis ?? 'io')) continue; // never sum across token axes
241
+ const d = Math.abs(cycleKey(local[i]) - cycleKey(r));
242
+ if (d <= MERGE_TOLERANCE_MS && d < bestD) { best = i; bestD = d; }
243
+ }
244
+ if (best < 0) { out.push({ ...r }); continue; }
245
+ used.add(best);
246
+ const l = local[best];
247
+ const utils = [l.finalUtilization, r.finalUtilization].filter(Number.isFinite);
248
+ const starts = [l.windowStartedAt, r.windowStartedAt].filter(v => v != null);
249
+ const merged = {
250
+ startedAt: Math.min(l.startedAt, r.startedAt),
251
+ endedAt: Math.max(l.endedAt, r.endedAt),
252
+ tokens: (l.tokens || 0) + (r.tokens || 0),
253
+ complete: Boolean(l.complete || r.complete),
254
+ disabledDuring: Boolean(l.disabledDuring || r.disabledDuring),
255
+ spansRefill: Boolean(l.spansRefill || r.spansRefill),
256
+ resetAt: l.resetAt ?? r.resetAt,
257
+ merged: true, sources: 2, axis: l.axis ?? r.axis,
258
+ ...(utils.length ? { finalUtilization: Math.max(...utils) } : {}),
259
+ ...(starts.length ? { windowStartedAt: Math.min(...starts) } : {}),
260
+ ...((l.partialReason || r.partialReason) ? { partialReason: l.partialReason || r.partialReason } : {}),
261
+ };
262
+ // pre-v3-unverified on EITHER side must keep the merged row out (never-trust reason)
263
+ if (l.partialReason === 'pre-v3-unverified' || r.partialReason === 'pre-v3-unverified') merged.partialReason = 'pre-v3-unverified';
264
+ matched.set(best, merged);
265
+ }
266
+ local.forEach((l, i) => out.push(matched.get(i) || l));
267
+ return out.sort((a, b) => cycleKey(a) - cycleKey(b));
268
+ }
269
+
68
270
  export class CapacityLedger {
69
271
  constructor({ now = () => Date.now() } = {}) {
70
272
  this._now = now;
@@ -98,7 +300,7 @@ export class CapacityLedger {
98
300
  }
99
301
  return CapacityLedger.fromSerialized(migrated, { now });
100
302
  }
101
- if (!payload || payload.schemaVersion !== SCHEMA_VERSION) {
303
+ if (!payload || !READABLE_SCHEMAS.has(payload.schemaVersion)) {
102
304
  // No history to continue: whatever window each account is in RIGHT NOW is
103
305
  // already in progress, so the next cycle we close saw only its tail. Flag it so
104
306
  // it is shown but never averaged (live 2026-08-23: the first GLM cycle after the
@@ -111,7 +313,7 @@ export class CapacityLedger {
111
313
  for (const [name, rec] of Object.entries(payload.accounts || {})) {
112
314
  const a = { ses: { open: null, closed: [] }, wk: { open: null, closed: [] }, days: {} };
113
315
  for (const w of ['ses', 'wk']) {
114
- if (rec[w]?.open) a[w].open = { ...rec[w].open };
316
+ if (rec[w]?.open) a[w].open = JSON.parse(JSON.stringify(rec[w].open));
115
317
  if (Array.isArray(rec[w]?.closed)) {
116
318
  // LOAD-TIME REPAIR, applied at EVERY version — not inside the v2→v3 branch,
117
319
  // which is where it was first (wrongly) placed: a future-dated row can be
@@ -120,10 +322,27 @@ export class CapacityLedger {
120
322
  // 2026-08-23: a row ending 19:54 survived the v3 migration untouched because
121
323
  // the state was already v3. A cycle cannot end after now; such a row is
122
324
  // corrupt, so demote it and clamp it rather than let it re-alert until evicted.
123
- a[w].closed = rec[w].closed.slice(-MAX_CYCLES_PER_WINDOW).map(c =>
325
+ a[w].closed.push(...rec[w].closed.slice(-MAX_CYCLES_PER_WINDOW).map(c => ({ ...c, axis: c.axis === AXIS_ALL ? AXIS_ALL : 'io' })).map(c =>
124
326
  (c.endedAt > Date.now() + 60_000)
125
327
  ? { ...c, endedAt: c.startedAt, complete: false, partialReason: 'repaired-future-endedAt' }
126
- : c);
328
+ : c));
329
+ }
330
+ // AXIS: an in-flight cycle counted input+output only. It cannot continue on the
331
+ // all-tokens axis (half its tokens would be on the old definition), so it is
332
+ // closed as a LEGACY row and the next accrual opens a fresh axis-'all' cycle.
333
+ if (a[w].open && a[w].open.axis !== AXIS_ALL) {
334
+ const o = a[w].open;
335
+ if (o.tokensSoFar > 0) {
336
+ a[w].closed.push({
337
+ startedAt: o.startedAt, endedAt: Math.min(o.lastAccrualAt || o.startedAt, Date.now()),
338
+ tokens: o.tokensSoFar, complete: false, disabledDuring: Boolean(o.disabledDuring),
339
+ partialReason: 'legacy-axis', axis: 'io',
340
+ ...(Number.isFinite(o.peakUtilization) ? { finalUtilization: o.peakUtilization } : {}),
341
+ ...(o.windowStartedAt != null ? { windowStartedAt: o.windowStartedAt } : {}),
342
+ resetAt: null,
343
+ });
344
+ }
345
+ a[w].open = null;
127
346
  }
128
347
  }
129
348
  if (rec.days && typeof rec.days === 'object') {
@@ -139,8 +358,8 @@ export class CapacityLedger {
139
358
  const accounts = {};
140
359
  for (const [name, rec] of this._accounts) {
141
360
  accounts[name] = {
142
- ses: { open: rec.ses.open ? { ...rec.ses.open } : null, closed: rec.ses.closed.slice() },
143
- wk: { open: rec.wk.open ? { ...rec.wk.open } : null, closed: rec.wk.closed.slice() },
361
+ ses: { open: rec.ses.open ? JSON.parse(JSON.stringify(rec.ses.open)) : null, closed: rec.ses.closed.slice() },
362
+ wk: { open: rec.wk.open ? JSON.parse(JSON.stringify(rec.wk.open)) : null, closed: rec.wk.closed.slice() },
144
363
  days: Object.fromEntries(Object.entries(rec.days).map(([d, v]) => [d, { ...v }])),
145
364
  };
146
365
  }
@@ -163,8 +382,15 @@ export class CapacityLedger {
163
382
  * M3 in the pre-mortem — Anthropic interim deltas are CUMULATIVE, so the SSE seam
164
383
  * passes the running max, and this adds it exactly once per request).
165
384
  * count_tokens requests are the CALLER's job to skip (M4) — they never reach here. */
166
- accrue(name, { input, output }, at = this._now(), windows = ['ses', 'wk']) {
167
- if (!(input > 0) && !(output > 0)) return;
385
+ accrue(name, { input, output, cacheRead = 0, cacheCreation = 0, model = null }, at = this._now(), windows = ['ses', 'wk']) {
386
+ // TOKEN DEFINITION (v5, owner 2026-11-06): every token the provider processed =
387
+ // input + cache_read + cache_creation + output, identical for Anthropic and z.ai so
388
+ // both sit on one axis. (The cache counters are also kept separately per cycle.)
389
+ const cr = cacheRead > 0 ? cacheRead : 0, cc = cacheCreation > 0 ? cacheCreation : 0;
390
+ const total = (input > 0 ? input : 0) + (output > 0 ? output : 0) + cr + cc;
391
+ if (!(total > 0)) return;
392
+ // `model` is recorded as a per-family token breakdown (open.models), never used by the tank.
393
+ const fam = capacityModelFamily(model);
168
394
  const rec = this._rec(name);
169
395
  for (const w of windows) {
170
396
  // Open the window lazily if nothing is open (a mid-cycle boot or a window whose
@@ -174,16 +400,21 @@ export class CapacityLedger {
174
400
  const joined = this._joinedMidWindow && rec[w].closed.length === 0;
175
401
  rec[w].open = {
176
402
  startedAt: at, tokensSoFar: 0, lastAccrualAt: at,
177
- complete: !joined, disabledDuring: false,
403
+ complete: !joined, disabledDuring: false, axis: AXIS_ALL,
178
404
  ...(joined ? { partialReason: 'joined-mid-window' } : {}),
179
405
  };
180
406
  }
181
- rec[w].open.tokensSoFar += input + output;
182
- rec[w].open.lastAccrualAt = at;
407
+ const o = rec[w].open;
408
+ o.tokensSoFar += total;
409
+ o.cacheRead = (o.cacheRead || 0) + cr;
410
+ o.cacheCreation = (o.cacheCreation || 0) + cc;
411
+ o.models = o.models || {};
412
+ o.models[fam] = (o.models[fam] || 0) + total;
413
+ o.lastAccrualAt = at;
183
414
  }
184
415
  const day = new Date(at).toISOString().slice(0, 10);
185
416
  rec.days[day] = rec.days[day] || { tokens: 0, partial: false };
186
- rec.days[day].tokens += input + output;
417
+ rec.days[day].tokens += total;
187
418
  this._evictDays(rec);
188
419
  }
189
420
 
@@ -281,6 +512,10 @@ export class CapacityLedger {
281
512
  // percentage counts everything). Dropping it here made every tank read "bounded".
282
513
  ...(open.windowStartedAt != null ? { windowStartedAt: open.windowStartedAt } : {}),
283
514
  ...(open.peakReset ? { spansRefill: true } : {}),
515
+ ...(open.samples?.length ? { samples: thin(open.samples) } : {}),
516
+ axis: open.axis || 'io',
517
+ ...(open.cacheRead !== undefined ? { cacheRead: open.cacheRead, cacheCreation: open.cacheCreation || 0 } : {}),
518
+ ...(open.models ? { models: open.models } : {}),
284
519
  resetAt,
285
520
  });
286
521
  if (rec[window].closed.length > MAX_CYCLES_PER_WINDOW) rec[window].closed.shift();
@@ -372,9 +607,23 @@ export class CapacityLedger {
372
607
  if (Number.isFinite(open.peakUtilization) && open.peakUtilization - m.utilization >= 0.10) {
373
608
  open.peakUtilization = m.utilization;
374
609
  open.peakReset = true;
610
+ open.samples = []; // pre-refill readings describe a different tank
375
611
  } else if (!Number.isFinite(open.peakUtilization) || m.utilization > open.peakUtilization) {
376
612
  open.peakUtilization = m.utilization;
377
613
  }
614
+ // SAMPLE: {t, tokens (cumulative in-window), util, + cumulative cache/model counters}.
615
+ // Only a CHANGED utilization is a new measurement: the first reading at a level is
616
+ // the closest bracket of when that level was crossed; repeats add nothing.
617
+ open.samples = open.samples || [];
618
+ const lastS = open.samples[open.samples.length - 1];
619
+ if (!lastS || lastS.util !== m.utilization) {
620
+ open.samples.push({
621
+ t: at, tokens: open.tokensSoFar, util: m.utilization,
622
+ cr: open.cacheRead || 0, cc: open.cacheCreation || 0,
623
+ ...(open.models ? { m: { ...open.models } } : {}),
624
+ });
625
+ if (open.samples.length > MAX_SAMPLES_PER_CYCLE * 2) open.samples = thin(open.samples);
626
+ }
378
627
  const key = `${m.name}:${m.window}`;
379
628
  const prev = this._utilMarks.get(key);
380
629
  // Keep the OLDEST usable mark within this cycle: a wider span means a larger
@@ -447,74 +696,38 @@ export class CapacityLedger {
447
696
  * into the average as fake precision.
448
697
  * Returns { avg, exact, n, bounded, last } or null when no usable readings. */
449
698
  tankStats(name, window) {
450
- const rec = this._accounts.get(name);
451
- const floor = (this._readFloorOverride ?? READ_FLOOR_MS)[window] ?? 0;
452
- // TANK READING SET (2026-10-13): partial cycles COUNT here. The strict
453
- // `complete` gate was written for demand stats and quietly deleted every
454
- // weekly observation — a 7d window outlives every maxpool restart/sleep, so
455
- // restoreCapacityState's >60s downtime check marked nearly all of them
456
- // partial and the Weekly (7d) page read "--" everywhere (owner report
457
- // 2026-10-13). For TANK math a gap is already handled: tokens ÷ vendor % is
458
- // a lower bound whenever spend was unseen, and exact/bounded/lowerBound
459
- // exist to say so. Still excluded, hard: disabledDuring (operator benched
460
- // the account — not a capacity observation) and `pre-v3-unverified` (the
461
- // ONE reason that means "never trust this row").
462
- const closed = (rec?.[window]?.closed || []).filter(c =>
463
- !c.disabledDuring
464
- && c.partialReason !== 'pre-v3-unverified'
465
- && c.partialReason !== 'no-weekly-plan'
466
- && !c.spansRefill
467
- && (c.endedAt - c.startedAt) >= floor - 1_000
468
- // CEILING: a cycle far longer than its window swallowed a rollover it never
469
- // saw — two tanks' tokens over one tank's percentage (see WINDOW_CEIL_FACTOR).
470
- && (this._readFloorOverride != null
471
- || (c.endedAt - c.startedAt) <= WINDOW_MS[window] * WINDOW_CEIL_FACTOR));
472
- // PHYSICAL FLOOR: a tank can never be smaller than the most tokens ever
473
- // delivered in one complete window — every token we count is a vendor token
474
- // (C ≤ V ≤ tank), so maxDelivered ≤ tank is an invariant, not a heuristic.
475
- // A reading implying a smaller tank is contaminated: the vendor % counted
476
- // spend maxpool never saw (usage outside the proxy — an account also used
477
- // directly), or the reading was stale. Measured live 2026-08-26: a window
478
- // that delivered 497k at a reported "95% full" implied a 523k tank while an
479
- // earlier window of the SAME account had delivered 1.53M — impossible, and
480
- // the understated reading silently dragged the average down 3.6x.
481
- // CLAMP, never discard: the contaminated reading is still a real lower bound
482
- // (the tank is at least the tokens we saw), so it joins the average AT the
483
- // floor rather than being thrown away — discarding left an account whose
484
- // every reading was contaminated with NOTHING to show. After a plan
485
- // downgrade the floor over-states until old cycles age out — conservative.
486
- // The floor is taken over EVERY admitted cycle, partial ones included: a
487
- // partial cycle's token count is still tokens the vendor really delivered,
488
- // so it is still a hard lower bound on the tank. Restricting it to complete
489
- // cycles left it inert on weekly history, where nearly every cycle is partial
490
- // (red-team 2026-10-13, finding 4).
491
- const maxDelivered = closed.reduce((m, c) => Math.max(m, c.tokens), 0);
492
- const usable = closed.filter(c =>
493
- Number.isFinite(c.finalUtilization) && c.finalUtilization >= TANK_MIN_UTIL);
494
- if (!usable.length) return null;
495
- let sum = 0, exact = 0, bounded = 0;
496
- for (const c of usable) {
497
- const observedFromStart = c.startedAt != null && c.windowStartedAt != null
498
- && c.startedAt <= c.windowStartedAt + 60_000 && c.complete;
499
- sum += Math.max(c.tokens / c.finalUtilization, maxDelivered);
500
- if (observedFromStart) exact++; else bounded++;
501
- }
502
- const last = usable[usable.length - 1];
503
- const prevCycle = usable[usable.length - 2];
504
- return {
505
- avg: Math.round(sum / usable.length),
506
- exact, bounded,
507
- n: usable.length,
508
- last: Math.round(Math.max(last.tokens / last.finalUtilization, maxDelivered)),
509
- // PREV in TANK units (tokens ÷ that cycle's own reading) — the page's
510
- // Prev column used to come from windowStats (delivered tokens), mixing
511
- // units across one row (2026-10-13 owner report). Same physical floor as
512
- // the average: a reading implying less than a past delivery is impossible.
513
- prev: prevCycle != null
514
- ? Math.round(Math.max(prevCycle.tokens / prevCycle.finalUtilization, maxDelivered))
515
- : null,
516
- lowerBound: bounded > 0 && exact === 0,
517
- };
699
+ return tankStatsFromCycles(this.closedCycles(name, window), window,
700
+ { readFloor: this._readFloorOverride, ignoreCeiling: this._readFloorOverride != null });
701
+ }
702
+
703
+ /** Closed cycles of one account window (shallow copies). The tank reading set:
704
+ * partial cycles COUNT (a 7d window outlives every restart, so a complete-only gate
705
+ * deleted all weekly history — owner report 2026-10-13); disabledDuring and
706
+ * pre-v3-unverified are excluded in tankStatsFromCycles. */
707
+ closedCycles(name, window) {
708
+ return (this._accounts.get(name)?.[window]?.closed || []).map(c => ({ ...c }));
709
+ }
710
+
711
+ /** Bounded export for a linked pool (B1): closed cycles of one window, newest last,
712
+ * samples thinned. `est` carries this pool's own per-cycle estimate so a consumer
713
+ * that cannot re-derive it still has the slope-based number. */
714
+ exportCycles(name, window, limit) {
715
+ const closed = (this._accounts.get(name)?.[window]?.closed || []).slice(-limit);
716
+ return closed.map(c => {
717
+ const e = cycleEstimate(c);
718
+ const o = {
719
+ startedAt: c.startedAt, endedAt: c.endedAt, resetAt: c.resetAt ?? null,
720
+ axis: c.axis ?? 'io',
721
+ tokens: c.tokens, complete: c.complete, disabledDuring: Boolean(c.disabledDuring),
722
+ ...(c.partialReason ? { partialReason: c.partialReason } : {}),
723
+ ...(c.spansRefill ? { spansRefill: true } : {}),
724
+ ...(Number.isFinite(c.finalUtilization) ? { finalUtilization: c.finalUtilization } : {}),
725
+ ...(c.windowStartedAt != null ? { windowStartedAt: c.windowStartedAt } : {}),
726
+ ...(e && e.method === 'slopes' ? { est: Math.round(e.tokens) } : {}),
727
+ };
728
+ if (c.samples?.length) o.samples = thin(c.samples, EXPORT_SAMPLES).map(({ t, tokens, util }) => ({ t, tokens, util }));
729
+ return o;
730
+ });
518
731
  }
519
732
 
520
733
  rollingThroughput(name, days = 7) {
@@ -0,0 +1,126 @@
1
+ // CLI `maxpool login` → linked cloud team pool. Pure helpers (no top-level side
2
+ // effects) so tests can import them without running the CLI in index.js.
3
+ // Mirrors src/tui.js _sendLoginToTarget: same request shape, 20s timeout, and the
4
+ // single-writer rule — a cloud failure NEVER falls back to a local save.
5
+
6
+ const TIMEOUT_MS = 20_000;
7
+
8
+ /**
9
+ * POST a fresh OAuth login to the team pool. Never throws.
10
+ * @returns {Promise<{ok:boolean, result?:string, name?:string, error?:string}>}
11
+ */
12
+ export async function sendLoginToPool({ url, key, name, profile, creds, fetchImpl = fetch, timeoutMs = TIMEOUT_MS }) {
13
+ // No uuid → the server cannot dedupe a re-authorization and would ADD a duplicate
14
+ // row (the v1.24.67 bug class). Refuse rather than risk it.
15
+ if (!profile?.accountUuid) return { ok: false, kind: 'no-uuid', error: 'Account profile unavailable — no account id to add or re-authorize safely' };
16
+ const ctl = new AbortController();
17
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
18
+ try {
19
+ const res = await fetchImpl(`${String(url).replace(/\/+$/, '')}/maxpool/accounts`, {
20
+ method: 'POST',
21
+ headers: { 'Content-Type': 'application/json', 'x-api-key': key || '' },
22
+ body: JSON.stringify({
23
+ account: {
24
+ name, type: 'oauth',
25
+ accountUuid: profile?.accountUuid,
26
+ accessToken: creds.accessToken,
27
+ refreshToken: creds.refreshToken,
28
+ expiresAt: creds.expiresAt,
29
+ source: 'remote-login',
30
+ },
31
+ }),
32
+ signal: ctl.signal,
33
+ });
34
+ const json = await res.json().catch(() => ({}));
35
+ if (res.ok && json.ok) return { ok: true, result: json.result, name: json.name || name };
36
+ return { ok: false, kind: 'rejected', error: `Team pool rejected the login (HTTP ${res.status}: ${json?.message || json?.error || 'unknown error'})` };
37
+ } catch (e) {
38
+ return { ok: false, kind: 'unreachable', error: `Could not reach the team pool (${e?.name === 'AbortError' ? 'timed out' : e?.message})` };
39
+ } finally {
40
+ clearTimeout(t);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Decide where a CLI login goes. `pools` = pools WITH a usable key (caller resolves).
46
+ * `answer` = the T/l reply when a TTY prompt was shown (undefined/'' = Enter).
47
+ * @returns {'local'|'cloud'|'ask'} 'ask' = TTY, no flag, pool present: caller must
48
+ * prompt, then call again with `answer`.
49
+ */
50
+ export function chooseLoginTarget({ pools, flags = {}, isTTY, answer }) {
51
+ const hasPool = Array.isArray(pools) && pools.length > 0;
52
+ if (flags.local) return 'local';
53
+ if (!hasPool) return 'local';
54
+ if (flags.cloud) return 'cloud';
55
+ if (!isTTY) return 'cloud';
56
+ if (answer === undefined) return 'ask';
57
+ return String(answer).trim().toLowerCase() === 'l' ? 'local' : 'cloud';
58
+ }
59
+
60
+ /**
61
+ * Split configured pools into usable (have a key) and unresolved (configured but
62
+ * the key could not be loaded). The caller needs the difference: "no pool
63
+ * configured" and "pool configured, key missing" must never look the same.
64
+ * @returns {Promise<{usable:Array, unresolved:string[], error?:string}>}
65
+ */
66
+ export async function resolveUsablePools(configPools, resolve) {
67
+ const defs = (Array.isArray(configPools) ? configPools : []).filter(p => p && p.name && p.url);
68
+ const names = defs.map(p => p.keySecret).filter(Boolean);
69
+ let resolved = {};
70
+ let error;
71
+ if (names.length) {
72
+ try { resolved = (await resolve(names)) || {}; } catch (e) { resolved = {}; error = e?.message || String(e); }
73
+ }
74
+ const all = defs.map(p => ({ name: p.name, url: p.url, key: p.keySecret ? (resolved[p.keySecret] || null) : (p.key || null) }));
75
+ const out = { usable: all.filter(p => p.key), unresolved: all.filter(p => !p.key).map(p => p.name) };
76
+ if (error) out.error = error;
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * Full CLI decision (pure). Inputs: usable/unresolved from resolveUsablePools,
82
+ * localMatch (account already in config.accounts), flags {local,cloud,pool},
83
+ * isTTY, and prompt replies (answer = T/l, poolAnswer = pool pick, fallbackAnswer = y/N).
84
+ * @returns {{action:'local'|'cloud'|'fail'|'ask-pool'|'ask-target'|'ask-fallback', pool?:object, message?:string}}
85
+ */
86
+ export function planCliLogin({ usable = [], unresolved = [], error, localMatch = null, flags = {}, isTTY, answer, poolAnswer, fallbackAnswer }) {
87
+ const unresolvedMsg = (n) => `Team pool '${n}' is configured but its key could not be loaded${error ? ` (${error})` : ''}.`;
88
+ if (flags.local && flags.cloud) return { action: 'fail', message: 'Use either --cloud or --local, not both.' };
89
+ if (flags.local) return { action: 'local' };
90
+ // An account lives in exactly ONE pool: a local match is re-authenticated locally.
91
+ if (localMatch) {
92
+ if (flags.cloud) return { action: 'fail', message: `This account is already on this laptop as "${localMatch.name}" — an account lives in one pool only. Re-run without --cloud to re-authenticate it here.` };
93
+ return { action: 'local' };
94
+ }
95
+ let pool = null;
96
+ if (flags.pool) {
97
+ pool = usable.find(p => p.name === flags.pool) || null;
98
+ if (!pool) {
99
+ return { action: 'fail', message: unresolved.includes(flags.pool)
100
+ ? unresolvedMsg(flags.pool)
101
+ : `No team pool named '${flags.pool}' is configured.` };
102
+ }
103
+ } else if (usable.length === 0) {
104
+ if (unresolved.length) {
105
+ const msg = unresolved.map(unresolvedMsg).join(' ');
106
+ if (flags.cloud || !isTTY) return { action: 'fail', message: `${msg} Nothing was saved.${flags.cloud ? '' : ' Use --local to save on this laptop.'}` };
107
+ if (fallbackAnswer === undefined) return { action: 'ask-fallback', message: msg };
108
+ return String(fallbackAnswer).trim().toLowerCase() === 'y'
109
+ ? { action: 'local' }
110
+ : { action: 'fail', message: 'Nothing was saved.' };
111
+ }
112
+ if (flags.cloud) return { action: 'fail', message: '--cloud: no team pool is configured (config.pools). Nothing was saved.' };
113
+ return { action: 'local' };
114
+ } else if (usable.length === 1) {
115
+ pool = usable[0];
116
+ } else {
117
+ if (!isTTY) return { action: 'fail', message: `${usable.length} team pools are linked (${usable.map(p => p.name).join(', ')}) — pass --pool <name> to choose one, or --local. Nothing was saved.` };
118
+ if (poolAnswer === undefined) return { action: 'ask-pool' };
119
+ const a = String(poolAnswer).trim();
120
+ pool = a === '' ? usable[0] : (usable[Number(a) - 1] || usable.find(p => p.name === a) || null);
121
+ if (!pool) return { action: 'fail', message: `'${a}' is not one of the linked pools. Nothing was saved.` };
122
+ }
123
+ const t = chooseLoginTarget({ pools: [pool], flags, isTTY, answer });
124
+ if (t === 'ask') return { action: 'ask-target', pool };
125
+ return t === 'local' ? { action: 'local' } : { action: 'cloud', pool };
126
+ }