maxpool 1.24.55 → 1.24.57

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maxpool",
3
- "version": "1.24.55",
3
+ "version": "1.24.57",
4
4
  "description": "Multi-account Claude Code proxy with adaptive, rate-aware load balancing across Claude accounts",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -3437,12 +3437,23 @@ export class AccountManager {
3437
3437
  if (account.type === 'provider') {
3438
3438
  const sesUsed = q.providerSes != null ? clamp01(q.providerSes) : null;
3439
3439
  const wkUsed = q.providerWk != null ? clamp01(q.providerWk) : null;
3440
- const used = Math.max(sesUsed ?? 0, wkUsed ?? 0);
3440
+ // The WEEKLY ladder tiers on the weekly window ALONE when the plan HAS one
3441
+ // (owner 2026-10-30: GLM serves to 100% of the session window; the old
3442
+ // Math.max(ses, wk) demoted a 97%-session / 20%-weekly key to 'critical' —
3443
+ // last-resort behind every Claude account with four-fifths of its weekly
3444
+ // window empty — council review 2026-10-31). A weeklyAbsent plan (providerWk
3445
+ // null: z.ai unlimited-weekly) keeps its historical ses-driven tiering — the
3446
+ // session window is its ONLY quota signal. Session availability otherwise
3447
+ // belongs to _isSessionQuotaUnavailable + PROVIDER_SES_WALL.
3448
+ const used = wkUsed != null ? wkUsed : (sesUsed ?? 0);
3441
3449
  // USAGE CAP — checked FIRST, before every tier: a reservation is owner intent
3442
3450
  // and outranks both the tier ladder and the upstream verdict. There is no
3443
3451
  // upstreamAllows carve-out for providers anyway, but the ordering documents
3444
- // that a cap can never be talked out of by the vendor's "allowed".
3445
- if (this._capped(account, used, 'wk', now)) return 'capped';
3452
+ // that a cap can never be talked out of by the vendor's "allowed". The cap
3453
+ // reads the WORST window (max of ses/wk): a z.ai cap bounds total spend, and
3454
+ // the 5h reading is real consumption against it.
3455
+ const capUsed = Math.max(sesUsed ?? 0, wkUsed ?? 0);
3456
+ if (this._capped(account, capUsed, 'wk', now)) return 'capped';
3446
3457
  if (used >= this.scheduler.weeklyExhaustedThreshold) return 'exhausted';
3447
3458
  if (used >= this.scheduler.weeklyCriticalThreshold) return 'critical';
3448
3459
  if (used >= this.scheduler.weeklyReserveThreshold) return 'reserve';
@@ -3695,6 +3706,25 @@ export class AccountManager {
3695
3706
 
3696
3707
  /** Store the latest reset-card listing for an account (prober piggyback).
3697
3708
  * Read by redeem policy AND by _scoreAccount's reset-aware preference. */
3709
+ /** Monthly-normalized price for the Capacity page's $/1M column (display-only;
3710
+ * never touches routing). Claude accounts read config.scheduler.monthlyPriceUSD
3711
+ * (name → USD/mo; no per-account price API exists), providers get theirs from
3712
+ * the z.ai subscription API via the prober. */
3713
+ applyMonthlyPrice(accountIndex, usd) {
3714
+ const a = this.accounts[accountIndex];
3715
+ if (a) a.monthlyPriceUSD = usd;
3716
+ }
3717
+
3718
+ monthlyPriceFor(account) {
3719
+ if (account?.type === 'provider') return account.monthlyPriceUSD ?? null;
3720
+ const tbl = this.scheduler?.monthlyPriceUSD;
3721
+ if (tbl && typeof tbl === 'object') {
3722
+ const hit = tbl[account?.name] ?? tbl['*'];
3723
+ if (Number.isFinite(hit)) return hit;
3724
+ }
3725
+ return null;
3726
+ }
3727
+
3698
3728
  applyResetCards(accountIndex, cards) {
3699
3729
  const account = this.accounts[accountIndex];
3700
3730
  if (!account || !cards) return;
package/src/prober.js CHANGED
@@ -9,6 +9,7 @@
9
9
 
10
10
  import { fetchUsage, fetchProviderUsage } from './oauth.js';
11
11
  import { listResetCards, redeemResetCard, fetchZaiModelUsage } from './zai-reset-cards.js';
12
+ import { listSubscriptions, monthlyPriceUSD } from './zai-subs.js';
12
13
  import { listResetGrants, claimResetGrant } from './claude-reset-grants.js';
13
14
  import { decideZai, decideClaude } from './reset-policy.js';
14
15
  import { zaiHourlyCalls, compareOutsideUsage, isUsableZaiUsage, OUTSIDE_CHECK_MS } from './outside-usage.js';
@@ -205,6 +206,16 @@ export class Prober {
205
206
  // A duplicate-guard-benched copy never redeems: the team pool owns that key now,
206
207
  // and two pools redeeming one key would burn two cards for one reset.
207
208
  if (account.enabled !== false && account.credential && !account.poolBenchedBy) {
209
+ // Subscription (price-per-token column): same cadence, same key, best-effort.
210
+ if (account.provider === 'zai' && this.am.applyMonthlyPrice) {
211
+ try {
212
+ if (!account._subsCheckedAt || Date.now() - account._subsCheckedAt > 24 * 3600_000) {
213
+ const subs = await this._withTimeout(listSubscriptions(account.credential));
214
+ account._subsCheckedAt = Date.now();
215
+ if (subs && !subs.error) this.am.applyMonthlyPrice(account.index, monthlyPriceUSD(subs.subscriptions));
216
+ }
217
+ } catch { /* price is display-only */ }
218
+ }
208
219
  if (account.provider === 'zai' && this.am.applyResetCards) {
209
220
  try {
210
221
  const cards = await this._withTimeout(this.cardsFn(account.credential));
package/src/server.js CHANGED
@@ -358,10 +358,17 @@ export function createProxyServer(accountManager, config, hooks = {}) {
358
358
  });
359
359
  // Keep the in-memory config mirror in step so a later TUI saveConfig
360
360
  // can't clobber the fresh tokens with stale ones.
361
- const mem = config.accounts.find(a => a.accountUuid === acct.accountUuid);
361
+ const mem = (config.accounts || []).find(a => a.accountUuid === acct.accountUuid);
362
362
  if (mem) Object.assign(mem, tokenFields);
363
363
  } catch (err) {
364
+ // A single-use credential write is only "ok" when it is DURABLE: the browser
365
+ // login may have invalidated the previous refresh token, so memory-only means
366
+ // a restart bricks the account while both sides recorded success (council
367
+ // review 2026-10-31). Tell the caller to retry instead of claiming Done.
364
368
  console.error(`[Maxpool] Remote inject persisted to memory but NOT disk for uuid ${acct.accountUuid.slice(0, 8)}: ${err?.message || err}`);
369
+ res.writeHead(507, { 'Content-Type': 'application/json' });
370
+ res.end(JSON.stringify({ ok: false, error: 'not_persisted', message: 'Saved in memory only — the pool could not write it to disk. Log in again.' }));
371
+ return;
365
372
  }
366
373
  res.writeHead(200, { 'Content-Type': 'application/json' });
367
374
  res.end(JSON.stringify({ ok: true, result: amAcct ? 'reauthed' : 'added', name: amAcct ? amAcct.name : (acct.name || acct.accountUuid.slice(0, 8)) }));
@@ -477,6 +484,12 @@ export function createProxyServer(accountManager, config, hooks = {}) {
477
484
  // caller can't steer routing. Applied by selection as an exclusive filter.
478
485
  const pin = headerValue(req.headers, 'x-maxpool-pin-account');
479
486
  if (pin && req.callerName && req.callerName !== 'legacy-key') requestInfo.pinAccount = String(pin);
487
+ else if (pin) {
488
+ // A pin from a legacy-key link is silently dropped — the local pool has
489
+ // already made mirror-specific decisions on it. Name the misconfiguration
490
+ // once instead (council review 2026-10-31: no warning fired anywhere).
491
+ console.error('[Maxpool] x-maxpool-pin-account dropped: the link authenticated with the remote\'s legacy apiKey — mint a named client key (proxy.clients) so pins and per-person attribution work');
492
+ }
480
493
  requestInfo.sessionKey = headerValue(req.headers, 'x-maxpool-session');
481
494
  requestInfo.caller = req._caller || null;
482
495
  // The CLIENT tells us how long it will wait — the only source that is actually
package/src/tui.js CHANGED
@@ -2703,11 +2703,11 @@ export class TUI {
2703
2703
  // Current is the live window (estimate while it runs; frozen into the columns at
2704
2704
  // close). Prev/Avg/N are the completed-cycle history. The no-weekly account's
2705
2705
  // weekly view approximates capacity as avg session tank × 33.6 (7×24/5h windows).
2706
- const ALL_COLS = ['Current', 'Prev', 'Avg', 'N'];
2706
+ const ALL_COLS = ['Current', 'Prev', 'Avg', 'N', '$/1M'];
2707
2707
  const CW = 11;
2708
2708
  const nameW = 12;
2709
2709
  let COLS = ALL_COLS;
2710
- while (COLS.length > 1 && (nameW + PROVIDER_W + 2 + COLS.length * CW + 14) > W) {
2710
+ while (COLS.length > 1 && (nameW + PROVIDER_W + 2 + COLS.length * CW + 22) > W) {
2711
2711
  COLS = COLS.slice(0, -1);
2712
2712
  }
2713
2713
  const header = ' ' + 'Account'.padEnd(nameW) + ' ' + 'Provider'.padEnd(PROVIDER_W) + ' '
@@ -2730,6 +2730,11 @@ export class TUI {
2730
2730
  const approx = sesTank && sesTank.n > 0
2731
2731
  ? formatTokens(Math.round(sesTank.avg * (7 * 24) / 5)) : '--';
2732
2732
  const cellsByName = { Current: cyan(approx), Prev: '--', Avg: '--', N: sesTank?.n ? String(sesTank.n) : '--' };
2733
+ // Same price cell as the main path: this account's weekly capacity IS the
2734
+ // derived tank (avg 5h × 33.6) — the price column must not go blank here.
2735
+ const p2 = this.am.monthlyPriceFor?.(a);
2736
+ cellsByName['$/1M'] = gray((sesTank?.avg && p2)
2737
+ ? ('$' + (p2 / (Math.round(sesTank.avg * (7 * 24) / 5) / 1e6)).toFixed(2)).padStart(CW) : '--'.padStart(CW));
2733
2738
  out.push(' ' + name + ' ' + prov + ' '
2734
2739
  + COLS.map(c => cellsByName[c].padStart(CW)).join('')
2735
2740
  + dim(' no weekly limit · avg 5h × 33.6'));
@@ -2761,6 +2766,19 @@ export class TUI {
2761
2766
  Avg: (tank?.source === 'cycles' ? formatTokens(tank.avg) : '--'),
2762
2767
  N: (tank?.source === 'cycles' ? String(tank.n) : '--'),
2763
2768
  };
2769
+ // $/1M (owner 2026-10-31 "price per token, not per subscription"): the measured
2770
+ // weekly tank divided by the plan's monthly-normalized price. Weekly in BOTH
2771
+ // views — a 5h tank refills ~33.6x per week, so the weekly figure is what a
2772
+ // month of subscription actually buys. '--' until a tank reading AND a price exist.
2773
+ const sesTankObj = this.am.capacityTank?.(i, 'ses');
2774
+ const wkTank = (a.quota?.weeklyAbsent && a.type === 'provider')
2775
+ ? (sesTankObj?.avg ? Math.round(sesTankObj.avg * (7 * 24) / 5) : null)
2776
+ : (this.am.capacityTank?.(i, 'wk')?.avg ?? null);
2777
+ const price = this.am.monthlyPriceFor?.(a);
2778
+ const priceCell = (wkTank && price)
2779
+ ? '$' + (price / (wkTank / 1e6)).toFixed(2)
2780
+ : '--';
2781
+ cellsByName['$/1M'] = gray(priceCell.padStart(CW));
2764
2782
  const row = ' ' + name + ' ' + prov + ' '
2765
2783
  + COLS.map(c => cellsByName[c].padStart(CW)).join('');
2766
2784
  out.push(row + (curPct ? ' ' + curPct : ''));
@@ -2769,6 +2787,7 @@ export class TUI {
2769
2787
  out.push('');
2770
2788
  out.push(' ' + dim('Capacity = tokens ÷ how full the provider said the window was, at close.'));
2771
2789
  out.push(' ' + dim('Current @% = live window, % full now · no-weekly weekly = avg 5h × 33.6.'));
2790
+ out.push(' ' + dim('$/1M = plan price ÷ measured weekly tank (monthly-normalized). -- = no price or tank yet.'));
2772
2791
  return out;
2773
2792
  }
2774
2793
 
@@ -0,0 +1,43 @@
1
+ /** z.ai subscription list — the FACT source for a GLM plan's billing cycle and
2
+ * price (same API the finops forecast uses; 2026-10-31). Used for the
3
+ * price-per-token column on the Capacity page: tank tokens ÷ normalized monthly
4
+ * price. Values are cached per account; a failed read degrades the column to
5
+ * '--' and never touches routing. */
6
+ const SUBS_URL = 'https://api.z.ai/api/biz/subscription/list';
7
+ const CYCLE_MONTHS = { monthly: 1, quarterly: 3, annually: 12 };
8
+
9
+ export async function listSubscriptions(token, { signal, fetchImpl = fetch } = {}) {
10
+ try {
11
+ const res = await fetchImpl(SUBS_URL, {
12
+ headers: { Authorization: `Bearer ${token}` },
13
+ signal: signal ?? AbortSignal.timeout(20_000),
14
+ });
15
+ if (!res.ok) return { error: `HTTP ${res.status}` };
16
+ const env = await res.json();
17
+ const rows = env?.data;
18
+ if (!Array.isArray(rows)) return { error: 'bad_payload' };
19
+ return { subscriptions: rows.map(s => ({
20
+ id: s.id,
21
+ product: s.productName || null,
22
+ billingCycle: s.billingCycle || null,
23
+ price: Number(s.renewPrice ?? s.actualPrice ?? 0) || null,
24
+ autoRenew: Number(s.autoRenew ?? 0) === 1,
25
+ status: s.status || null,
26
+ })) };
27
+ } catch (err) {
28
+ return { error: err?.name === 'AbortError' ? 'timeout' : (err?.message || 'error') };
29
+ }
30
+ }
31
+
32
+ /** Monthly-normalized price in USD, or null. An annually-billed plan's per-month
33
+ * cost is price/12 — the token tank it buys is the same every month. */
34
+ export function monthlyPriceUSD(subscriptions) {
35
+ if (!subscriptions?.length) return null;
36
+ // Prefer the VALID auto-renewing plan; fall back to the first row.
37
+ const s = subscriptions.find(x => x.status === 'VALID' && x.autoRenew)
38
+ || subscriptions.find(x => x.status === 'VALID')
39
+ || subscriptions[0];
40
+ const months = CYCLE_MONTHS[s?.billingCycle] || 0;
41
+ if (!months || !s?.price) return null;
42
+ return s.price / months;
43
+ }