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.
package/src/tui.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { fetchProfile, loginOAuth, tokenFingerprint, isLoginCancelled } from './oauth.js';
5
5
  import { appendEventLog, setConsoleStdoutSuppressed } from './event-log.js';
6
+ import { sendLoginToPool } from './cloud-login.js';
6
7
 
7
8
  // ── ANSI helpers ─────────────────────────────────────────────
8
9
 
@@ -454,6 +455,28 @@ function timestamp() {
454
455
 
455
456
  // ── TUI class ────────────────────────────────────────────────
456
457
 
458
+ /** Compact plan cell: "Max Q $134/mo". '--' when no plan is configured (no guessing). */
459
+ function planLabel(plan) {
460
+ if (!plan) return '--';
461
+ const cad = { monthly: 'M', quarterly: 'Q', annual: 'A', annually: 'A', yearly: 'A' }[plan.cadence] || '';
462
+ const tier = (plan.tier || '').replace(/^(claude|glm coding)\s+/i, '');
463
+ const monthly = plan.priceUsd != null && plan.billingMonths ? plan.priceUsd / plan.billingMonths : null;
464
+ return [tier, cad, monthly != null ? `$${Math.round(monthly)}/mo` : ''].filter(Boolean).join(' ') || '--';
465
+ }
466
+
467
+ /** Where a finished browser login goes. mirror → that team pool; a brand-new
468
+ * account (no mirror, not already local) with a keyed linked pool → ask (first
469
+ * keyed link); else local. */
470
+ export function decideLoginTarget({ mirror, links, existing, accountUuid }) {
471
+ if (mirror) return { kind: 'mirror', mirror };
472
+ if (existing) return { kind: 'local' };
473
+ const link = (Array.isArray(links) ? links : []).find(l => l && l.url && l.key);
474
+ if (!link) return { kind: 'local' };
475
+ // The team pool dedupes by account id; without it a re-login would ADD a duplicate.
476
+ if (!accountUuid) return { kind: 'no-uuid' };
477
+ return { kind: 'ask-team', link };
478
+ }
479
+
457
480
  export class TUI {
458
481
  constructor({ accountManager, config, saveConfig, syncAccounts, onQuit, onRestart }) {
459
482
  this.am = accountManager;
@@ -1452,35 +1475,7 @@ export class TUI {
1452
1475
  // there — never persisted locally (single writer: one account, one home).
1453
1476
  // Same keystroke as a local re-auth; the routing is by where the account
1454
1477
  // lives, so nothing is selected and no menu appears.
1455
- const mirror = this._findRemoteMirrorFor(profile);
1456
- if (mirror) {
1457
- setConsoleStdoutSuppressed(false);
1458
- await this._sendLoginToRemote(mirror, creds, profile);
1459
- return;
1460
- }
1461
- const existing = this._findExistingOAuthAccount(profile);
1462
- let name;
1463
- if (existing) {
1464
- process.stdout.write(`\nThis Claude account is already added as "${existing.name}" — re-authenticating it in place (no duplicate).\n`);
1465
- name = existing.name;
1466
- } else {
1467
- const suggested = profile?.email
1468
- || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1469
- const rl = createInterface({ input: process.stdin, output: process.stdout });
1470
- const answer = await new Promise(resolve => rl.question(`Name this NEW account [${suggested}]: `, resolve));
1471
- rl.close();
1472
- name = String(answer || '').trim() || suggested;
1473
- }
1474
- // Lift the mute BEFORE the upsert so its persist-confirmation (a console.log,
1475
- // deliberately visible during the stopped-TUI login) reaches the user.
1476
- setConsoleStdoutSuppressed(false);
1477
- // Message honors the ACTUAL result: if a manually-typed name collided with a
1478
- // different existing account, upsert updates in place → "Re-authenticated", never
1479
- // a false "Added new account".
1480
- const { updated } = await this._upsertOAuthAccount({ creds, profile, name, source: 'login' });
1481
- process.stdout.write(updated
1482
- ? `\nRe-authenticated "${name}". Returning to maxpool…\n`
1483
- : `\nAdded new account "${name}". Returning to maxpool…\n`);
1478
+ await this._routeLogin(creds, profile);
1484
1479
  } catch (e) {
1485
1480
  if (isLoginCancelled(e)) {
1486
1481
  process.stdout.write('\nLogin cancelled.\n');
@@ -1493,6 +1488,69 @@ export class TUI {
1493
1488
  }
1494
1489
  }
1495
1490
 
1491
+ // Where a finished browser login goes. Pure decision (see decideLoginTarget):
1492
+ // a mirror match → that team pool; a brand-new account with a linked team pool →
1493
+ // ask once (default team pool); otherwise the local save path.
1494
+ async _routeLogin(creds, profile) {
1495
+ const decision = decideLoginTarget({
1496
+ mirror: this._findRemoteMirrorFor(profile),
1497
+ links: this.am.poolLinks,
1498
+ existing: this._findExistingOAuthAccount(profile),
1499
+ accountUuid: profile?.accountUuid,
1500
+ });
1501
+ if (decision.kind === 'no-uuid') {
1502
+ setConsoleStdoutSuppressed(false);
1503
+ process.stdout.write("\nCould not read this account's id — the team pool needs it. Nothing was saved; try again.\n");
1504
+ return;
1505
+ }
1506
+ if (decision.kind === 'mirror') {
1507
+ setConsoleStdoutSuppressed(false);
1508
+ await this._sendLoginToRemote(decision.mirror, creds, profile);
1509
+ return;
1510
+ }
1511
+ const existing = this._findExistingOAuthAccount(profile);
1512
+ let name;
1513
+ if (existing) {
1514
+ process.stdout.write(`\nThis Claude account is already added as "${existing.name}" — re-authenticating it in place (no duplicate).\n`);
1515
+ name = existing.name;
1516
+ } else {
1517
+ const suggested = profile?.email
1518
+ || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1519
+ let toTeam = false;
1520
+ if (decision.kind === 'ask-team') {
1521
+ const where = String(await this._ask(`\nThis is a new account. Add it to the team pool "${decision.link.name}" (recommended) or this laptop only? [T/l]: `) || '').trim().toLowerCase();
1522
+ toTeam = where !== 'l';
1523
+ }
1524
+ const answer = await this._ask(`Name this NEW account [${suggested}]: `);
1525
+ name = String(answer || '').trim() || suggested;
1526
+ if (toTeam) {
1527
+ setConsoleStdoutSuppressed(false);
1528
+ await this._sendLoginToTarget(
1529
+ { url: decision.link.url, key: decision.link.key, linkName: decision.link.name },
1530
+ name, creds, profile, { newAccount: true });
1531
+ return;
1532
+ }
1533
+ }
1534
+ // Lift the mute BEFORE the upsert so its persist-confirmation (a console.log,
1535
+ // deliberately visible during the stopped-TUI login) reaches the user.
1536
+ setConsoleStdoutSuppressed(false);
1537
+ // Message honors the ACTUAL result: if a manually-typed name collided with a
1538
+ // different existing account, upsert updates in place → "Re-authenticated", never
1539
+ // a false "Added new account".
1540
+ const { updated } = await this._upsertOAuthAccount({ creds, profile, name, source: 'login' });
1541
+ process.stdout.write(updated
1542
+ ? `\nRe-authenticated "${name}". Returning to maxpool…\n`
1543
+ : `\nAdded new account "${name}". Returning to maxpool…\n`);
1544
+ }
1545
+
1546
+ // One readline question → answer string.
1547
+ async _ask(question) {
1548
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1549
+ const answer = await new Promise(resolve => rl.question(question, resolve));
1550
+ rl.close();
1551
+ return answer;
1552
+ }
1553
+
1496
1554
  // The browser login belongs to a linked team pool iff a mirror row carries the
1497
1555
  // same account uuid (M2: mirrors hold remoteUuid, never accountUuid, so a
1498
1556
  // uuid-first matcher cannot alias onto a local account).
@@ -1507,36 +1565,23 @@ export class TUI {
1507
1565
  async _sendLoginToRemote(mirror, creds, profile) {
1508
1566
  const remote = mirror.remote;
1509
1567
  const name = remote.remoteName || mirror.name;
1510
- process.stdout.write(`\n"${name}" lives in the team pool (${remote.linkName}) — sending the fresh login there…\n`);
1511
- const ctl = new AbortController();
1512
- const t = setTimeout(() => ctl.abort(), 20_000);
1513
- try {
1514
- const res = await fetch(`${String(remote.url).replace(/\/+$/, '')}/maxpool/accounts`, {
1515
- method: 'POST',
1516
- headers: { 'Content-Type': 'application/json', 'x-api-key': remote.key || '' },
1517
- body: JSON.stringify({
1518
- account: {
1519
- name, type: 'oauth',
1520
- accountUuid: profile?.accountUuid,
1521
- accessToken: creds.accessToken,
1522
- refreshToken: creds.refreshToken,
1523
- expiresAt: creds.expiresAt,
1524
- source: 'remote-login',
1525
- },
1526
- }),
1527
- signal: ctl.signal,
1528
- });
1529
- const json = await res.json().catch(() => ({}));
1530
- if (res.ok && json.ok) {
1531
- process.stdout.write(`\nDone: "${name}" ${json.result === 'added' ? 'added to' : 're-authenticated in'} the team pool. Nothing was saved on this laptop.\n`);
1532
- this._addLog(`Remote login: "${name}" → team pool ${remote.linkName} (${json.result})`);
1533
- } else {
1534
- process.stdout.write(`\nTeam pool rejected the login (HTTP ${res.status}: ${json?.message || json?.error || 'unknown error'}). NOTHING was saved on this laptop — not retried locally.\n`);
1535
- }
1536
- } catch (e) {
1537
- process.stdout.write(`\nCould not reach the team pool (${e?.name === 'AbortError' ? 'timed out' : e?.message}). NOTHING was saved on this laptop — try again in a moment.\n`);
1538
- } finally {
1539
- clearTimeout(t);
1568
+ return this._sendLoginToTarget(remote, name, creds, profile, { newAccount: false });
1569
+ }
1570
+
1571
+ // Shared sender. target = {url, key, linkName}. Same single-writer rule for a
1572
+ // NEW account: a failure never falls back to a local save.
1573
+ async _sendLoginToTarget(remote, name, creds, profile, { newAccount }) {
1574
+ process.stdout.write(newAccount
1575
+ ? `\nSending new account "${name}" to the team pool (${remote.linkName})…\n`
1576
+ : `\n"${name}" lives in the team pool (${remote.linkName}) — sending the fresh login there…\n`);
1577
+ const r = await sendLoginToPool({ url: remote.url, key: remote.key, name, profile, creds });
1578
+ if (r.ok) {
1579
+ process.stdout.write(`\nDone: "${name}" ${r.result === 'added' ? 'added to' : 're-authenticated in'} the team pool${newAccount ? ` (${remote.linkName})` : ''}. Nothing was saved on this laptop.\n`);
1580
+ this._addLog(`Remote login: "${name}" → team pool ${remote.linkName} (${r.result})`);
1581
+ } else if (r.kind === 'unreachable') {
1582
+ process.stdout.write(`\n${r.error}. NOTHING was saved on this laptop — try again in a moment.\n`);
1583
+ } else {
1584
+ process.stdout.write(`\n${r.error}. NOTHING was saved on this laptop — not retried locally.\n`);
1540
1585
  }
1541
1586
  }
1542
1587
 
@@ -2707,27 +2752,44 @@ export class TUI {
2707
2752
  if (!ledger) { out.push(yellow(' Capacity ledger unavailable on this worker.')); return out; }
2708
2753
 
2709
2754
  // Owner-specified table (2026-08-26): the same shape for BOTH views —
2710
- // Current cycle (tokens + % used) · Prev cycle · Avg across all cycles · N cycles.
2755
+ // Current cycle (tokens + % used) · Prev cycle · Med (median) across all cycles · N cycles.
2711
2756
  // Current is the live window (estimate while it runs; frozen into the columns at
2712
2757
  // close). Prev/Avg/N are the completed-cycle history. The no-weekly account's
2713
2758
  // weekly view approximates capacity as avg session tank × 33.6 (7×24/5h windows).
2714
- const ALL_COLS = ['Current', 'Prev', 'Avg', 'N', '$/1M'];
2759
+ // Plan/Where are the leftmost extras and drop first when the terminal is narrow
2760
+ // (the numeric columns are the point of the page). Where = which pool's ledger holds
2761
+ // this account's cycles (cloud / laptop / both) — ONE row per account identity.
2762
+ const ALL_COLS = ['Current', 'Prev', 'Med-3', 'Med-all', 'N', '$/1M'];
2763
+ // Narrow terminals drop from the right, but Med-3 goes before Med-all.
2764
+ const DROP_ORDER = ['$/1M', 'N', 'Med-3', 'Med-all', 'Prev', 'Current'];
2715
2765
  const CW = 11;
2716
2766
  const nameW = 12;
2767
+ const WHERE_W = 7, PLAN_W = 16;
2717
2768
  let COLS = ALL_COLS;
2718
2769
  while (COLS.length > 1 && (nameW + PROVIDER_W + 2 + COLS.length * CW + 22) > W) {
2719
- COLS = COLS.slice(0, -1);
2770
+ const drop = DROP_ORDER.find(c => COLS.includes(c));
2771
+ COLS = COLS.filter(c => c !== drop);
2720
2772
  }
2773
+ const showWhere = (nameW + PROVIDER_W + 2 + COLS.length * CW + WHERE_W + 1 + 22) <= W;
2774
+ const showPlan = showWhere && (nameW + PROVIDER_W + 2 + COLS.length * CW + WHERE_W + PLAN_W + 2 + 22) <= W;
2721
2775
  const header = ' ' + 'Account'.padEnd(nameW) + ' ' + 'Provider'.padEnd(PROVIDER_W) + ' '
2776
+ + (showWhere ? 'Where'.padEnd(WHERE_W) : '')
2777
+ + (showPlan ? 'Plan'.padEnd(PLAN_W) + ' ' : '')
2722
2778
  + COLS.map(c => c.padStart(CW)).join('');
2723
2779
  out.push(dimUnderline(fitLine(header, W)));
2724
2780
 
2725
- for (const i of this._displayOrder()) {
2781
+ const capRows = this.am.capacityRows
2782
+ ? this.am.capacityRows(this._displayOrder(), { hideDisabled: this.hideDisabled })
2783
+ : this._displayOrder().map(i => ({ index: i, group: [i], unresolved: false, displayName: this.am.accounts[i]?.name, where: null, priceAccount: this.am.accounts[i], plan: null, cache: null }));
2784
+ for (const cr of capRows) {
2785
+ const i = cr.index;
2726
2786
  const a = this.am.accounts[i];
2727
2787
  if (!a) continue;
2728
- if (this.hideDisabled && a.enabled === false) continue;
2729
- const name = truncate(a.name, nameW).padEnd(nameW);
2788
+ const name = truncate(cr.displayName + (cr.unresolved ? '?' : ''), nameW).padEnd(nameW);
2730
2789
  const prov = gray(providerLabel(a).padEnd(PROVIDER_W));
2790
+ const whereCell = showWhere ? gray((cr.where || '--').padEnd(WHERE_W)) : '';
2791
+ const planCell = showPlan ? gray(planLabel(cr.plan, cr.priceAccount, this.am).padEnd(PLAN_W) + ' ') : '';
2792
+ const lead = name + ' ' + prov + ' ' + whereCell + planCell;
2731
2793
 
2732
2794
  // The no-weekly plan has NO weekly window to complete — its weekly "capacity" is
2733
2795
  // derived: avg session tank × 33.6 (the number of 5h windows in 7 days). Shown
@@ -2737,13 +2799,13 @@ export class TUI {
2737
2799
  const sesTank = this.am.capacityTank?.(i, 'ses');
2738
2800
  const approx = sesTank && sesTank.n > 0
2739
2801
  ? formatTokens(Math.round(sesTank.avg * (7 * 24) / 5)) : '--';
2740
- const cellsByName = { Current: cyan(approx), Prev: '--', Avg: '--', N: sesTank?.n ? String(sesTank.n) : '--' };
2802
+ const cellsByName = { Current: cyan(approx), Prev: '--', 'Med-3': '--', 'Med-all': '--', N: sesTank?.n ? String(sesTank.n) : '--' };
2741
2803
  // Same price cell as the main path: this account's weekly capacity IS the
2742
2804
  // derived tank (avg 5h × 33.6) — the price column must not go blank here.
2743
- const p2 = this.am.monthlyPriceFor?.(a);
2805
+ const p2 = this.am.monthlyPriceFor?.(cr.priceAccount);
2744
2806
  cellsByName['$/1M'] = gray((sesTank?.avg && p2)
2745
2807
  ? ('$' + (p2 / (Math.round(sesTank.avg * (7 * 24) / 5) / 1e6)).toFixed(2)).padStart(CW) : '--'.padStart(CW));
2746
- out.push(' ' + name + ' ' + prov + ' '
2808
+ out.push(' ' + lead
2747
2809
  + COLS.map(c => cellsByName[c].padStart(CW)).join('')
2748
2810
  + dim(' no weekly limit · avg 5h × 33.6'));
2749
2811
  continue;
@@ -2771,8 +2833,11 @@ export class TUI {
2771
2833
  const cellsByName = {
2772
2834
  Current: cur.padStart(CW - (curPct ? curPct.length + 1 : 0)),
2773
2835
  Prev: (tank?.source === 'cycles' && tank.prev != null ? formatTokens(tank.prev) : '--'),
2774
- Avg: (tank?.source === 'cycles' ? formatTokens(tank.avg) : '--'),
2775
- N: (tank?.source === 'cycles' ? String(tank.n) : '--'),
2836
+ 'Med-3': (tank?.source === 'cycles' && tank.recent != null ? formatTokens(tank.recent) : '--'),
2837
+ 'Med-all': (tank?.source === 'cycles' ? formatTokens(tank.avg) : '--'),
2838
+ // `n*` = at least one contributing cycle is a two-pool merge (no per-reading
2839
+ // samples survive a merge, so it is estimated from close-time tokens only).
2840
+ N: (tank?.source === 'cycles' ? String(tank.n) + (tank.mergedCount > 0 ? '*' : '') : '--'),
2776
2841
  };
2777
2842
  // $/1M (owner 2026-10-31 "price per token, not per subscription"): the measured
2778
2843
  // weekly tank divided by the plan's monthly-normalized price. Weekly in BOTH
@@ -2789,18 +2854,21 @@ export class TUI {
2789
2854
  ? (sesTankObj?.avg ? Math.round(sesTankObj.avg * (7 * 24) / 5) : null)
2790
2855
  : (this.am.capacityTank?.(i, 'wk')?.avg
2791
2856
  ?? (a.type === 'provider' && sesTankObj?.avg ? Math.round(sesTankObj.avg * WK_PER_SES) : null));
2792
- const price = this.am.monthlyPriceFor?.(a);
2857
+ const price = this.am.monthlyPriceFor?.(cr.priceAccount);
2793
2858
  const priceCell = (wkTank && price)
2794
2859
  ? '$' + (price / (wkTank / 1e6)).toFixed(2)
2795
2860
  : '--';
2796
2861
  cellsByName['$/1M'] = gray(priceCell.padStart(CW));
2797
- const row = ' ' + name + ' ' + prov + ' '
2862
+ const row = ' ' + lead
2798
2863
  + COLS.map(c => cellsByName[c].padStart(CW)).join('');
2799
2864
  out.push(row + (curPct ? ' ' + curPct : ''));
2800
2865
  }
2801
2866
 
2802
2867
  out.push('');
2803
- out.push(' ' + dim('Capacity = tokens ÷ how full the provider said the window was, at close.'));
2868
+ out.push(' ' + dim('Capacity = median of tokens ÷ % full across readings in each cycle. Med-3 = median of last 3 cycles, Med-all = every cycle.'));
2869
+ out.push(' ' + dim('One row per account. Where = which side holds its history: cloud, laptop or both. ? = identity unknown.'));
2870
+ out.push(' ' + dim('Tokens = everything the provider processed (input + cached + output), same for Claude and GLM.'));
2871
+ out.push(' ' + dim('N = cycles in Med-all (Med-3 uses the newest 3). N* = includes a cycle both pools saw (merged) — estimated from close-time tokens, less precise.'));
2804
2872
  out.push(' ' + dim('Current @% = live window, % full now · no-weekly weekly = avg 5h × 33.6.'));
2805
2873
  out.push(' ' + dim('$/1M = plan price ÷ measured weekly tank (monthly-normalized). -- = no price or tank yet.'));
2806
2874
  return out;