maxpool 1.24.43 → 1.24.45

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.43",
3
+ "version": "1.24.45",
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",
@@ -470,6 +470,14 @@ export class AccountManager {
470
470
  // Named-caller request attribution (team pools): callerName → requests served.
471
471
  // Server-side (not TUI-side) so headless pools feed the web screen too.
472
472
  this.callerCounts = new Map();
473
+ // Per-person usage analytics (owner 2026-10-29; red-team verdict: persisted
474
+ // buckets, requests AND tokens, never the rotating event log). caller -> {
475
+ // hours: { 'YYYY-MM-DDTHH' UTC: {req, tok} } (rolling 48)
476
+ // days: { 'YYYY-MM-DD' UTC: {req, tok} } (rolling 35)
477
+ // total: {req, tok}
478
+ // }. A request ROUTED TO A LINKED POOL is not counted here (SC22: no double
479
+ // counting — the serving pool owns it), enforced by countRequest's caller.
480
+ this.callerStats = new Map();
473
481
  // Team-pool links (owner D8): remote pools as accounts + duplicate benching.
474
482
  this.poolLinks = [];
475
483
  this._remoteIdentities = new Map();
@@ -821,7 +829,7 @@ export class AccountManager {
821
829
  if (!account) return null;
822
830
 
823
831
  const weight = Math.max(1, Number(requestInfo.weight) || 1);
824
- const upstreamThrottleProbe = account.type !== 'provider' && this._claimUpstreamThrottleProbe();
832
+ const upstreamThrottleProbe = account.type !== 'provider' && !account.remote && this._claimUpstreamThrottleProbe();
825
833
  if (requestInfo.sessionKey) {
826
834
  // Same clock the selection above used, so the peak-failover guard can never
827
835
  // disagree with the peak tier that caused the move (defaults to real time).
@@ -851,9 +859,97 @@ export class AccountManager {
851
859
 
852
860
  // Named-caller attribution: one bump per CLIENT request (server calls this
853
861
  // right after auth, so retries/reroutes never double-count).
854
- countRequest(callerName) {
855
- if (!callerName) return;
862
+ countRequest(callerName, { forwarded = false } = {}) {
863
+ if (!callerName || forwarded) return;
856
864
  this.callerCounts.set(callerName, (this.callerCounts.get(callerName) || 0) + 1);
865
+ this._bumpCaller(callerName, 1, 0);
866
+ }
867
+
868
+ /** Attribute response TOKENS to the caller (SC22: tokens + requests). */
869
+ countCallerTokens(callerName, tokens) {
870
+ if (!callerName || !tokens) return;
871
+ this._bumpCaller(callerName, 0, tokens);
872
+ }
873
+
874
+ _bumpCaller(callerName, req, tok) {
875
+ const now = new Date();
876
+ const hourKey = now.toISOString().slice(0, 13); // 'YYYY-MM-DDTHH' UTC
877
+ const dayKey = now.toISOString().slice(0, 10); // 'YYYY-MM-DD' UTC
878
+ let st = this.callerStats.get(callerName);
879
+ if (!st) { st = { hours: {}, days: {}, total: { req: 0, tok: 0 } }; this.callerStats.set(callerName, st); }
880
+ for (const [bucket, key] of [[st.hours, hourKey], [st.days, dayKey]]) {
881
+ bucket[key] = bucket[key] || { req: 0, tok: 0 };
882
+ bucket[key].req += req; bucket[key].tok += tok;
883
+ }
884
+ st.total.req += req; st.total.tok += tok;
885
+ this._pruneCallerBuckets(st);
886
+ }
887
+
888
+ /** SC22: reverse one request bucket entry (a forwarded request re-counted at auth). */
889
+ _unbumpCaller(callerName) {
890
+ const st = this.callerStats.get(callerName);
891
+ if (!st) return;
892
+ const now = new Date();
893
+ for (const [k, src] of [[now.toISOString().slice(0, 13), st.hours], [now.toISOString().slice(0, 10), st.days]]) {
894
+ if (src[k]) { src[k].req = Math.max(0, src[k].req - 1); }
895
+ }
896
+ st.total.req = Math.max(0, st.total.req - 1);
897
+ }
898
+
899
+ _pruneCallerBuckets(st) {
900
+ const now = Date.now();
901
+ for (const k of Object.keys(st.hours)) if (now - Date.parse(k + ':00:00Z') > 48 * 3600_000) delete st.hours[k];
902
+ for (const k of Object.keys(st.days)) if (now - Date.parse(k + 'T00:00:00Z') > 35 * 24 * 3600_000) delete st.days[k];
903
+ }
904
+
905
+ /** Restore persisted caller stats (restart survival). */
906
+ restoreCallerStats(saved) {
907
+ if (!saved || typeof saved !== 'object') return;
908
+ for (const [name, st] of Object.entries(saved)) {
909
+ if (st && st.hours && st.days && st.total) {
910
+ this._pruneCallerBuckets(st);
911
+ this.callerStats.set(name, st);
912
+ }
913
+ }
914
+ }
915
+
916
+ exportCallerStats() {
917
+ return Object.fromEntries([...this.callerStats.entries()].map(([n, st]) => [n, {
918
+ hours: st.hours, days: st.days, total: st.total,
919
+ }]));
920
+ }
921
+
922
+ /** SC22 windows: rolling 24h (from hourly buckets), 7d/30d + prior (daily). */
923
+ callerWindowStats() {
924
+ const now = Date.now();
925
+ const out = new Map();
926
+ const win = (st, ms, hourly) => {
927
+ let req = 0, tok = 0;
928
+ const src = hourly ? st.hours : st.days;
929
+ for (const [k, v] of Object.entries(src)) {
930
+ const t = Date.parse(hourly ? k + ':00:00Z' : k + 'T00:00:00Z');
931
+ if (t <= now && now - t < ms) { req += v.req; tok += v.tok; }
932
+ }
933
+ return { req, tok };
934
+ };
935
+ const winPrior = (st, fromMs, toMs) => {
936
+ let req = 0, tok = 0;
937
+ for (const [k, v] of Object.entries(st.days)) {
938
+ const t = Date.parse(k + 'T00:00:00Z');
939
+ const age = now - t;
940
+ if (t <= now && age >= fromMs && age < toMs) { req += v.req; tok += v.tok; }
941
+ }
942
+ return { req, tok };
943
+ };
944
+ for (const [name, st] of this.callerStats) {
945
+ out.set(name, {
946
+ h24: win(st, 24 * 3600_000, true), h24p: winPrior(st, 24 * 3600_000, 48 * 3600_000),
947
+ d7: win(st, 7 * 24 * 3600_000, false), d7p: winPrior(st, 7 * 24 * 3600_000, 14 * 24 * 3600_000),
948
+ d30: win(st, 30 * 24 * 3600_000, false), d30p: winPrior(st, 30 * 24 * 3600_000, 60 * 24 * 3600_000),
949
+ total: { ...st.total },
950
+ });
951
+ }
952
+ return out;
857
953
  }
858
954
 
859
955
  releaseAccount(lease, outcome = {}) {
@@ -972,6 +1068,14 @@ export class AccountManager {
972
1068
  // Subscription latched gone (org-disabled 403): benched until re-subscribed. The
973
1069
  // clear path is a successful re-auth (updateAccountTokens) after re-purchasing.
974
1070
  if (account.subscriptionGone) return false;
1071
+ // Remote mirror: available while its link is live and the cloud row itself is
1072
+ // usable (not needs-login, not error). Quota benches are handled by scoring /
1073
+ // the caller's weekly gates, mirroring local accounts.
1074
+ if (account.remote) {
1075
+ const l = account.remote.link;
1076
+ if (!l || l.lastError || l.lastOkAt == null) return false;
1077
+ if (account.refreshDead || account.status === 'error') return false;
1078
+ }
975
1079
  // Pool link: available only while its last poll succeeded AND the remote has a
976
1080
  // usable account — a down/empty team pool must not swallow requests that local
977
1081
  // accounts could serve.
@@ -1044,7 +1148,7 @@ export class AccountManager {
1044
1148
  }
1045
1149
 
1046
1150
  getGlobalInFlight() {
1047
- return this.accounts.reduce((sum, account) => sum + account.inFlight, 0);
1151
+ return this.accounts.filter(a => !a.remote).reduce((sum, account) => sum + account.inFlight, 0);
1048
1152
  }
1049
1153
 
1050
1154
  setAdmissionPaused(paused) {
@@ -2363,11 +2467,30 @@ export class AccountManager {
2363
2467
 
2364
2468
  _matchesRequest(account, profile, requestInfo = {}) {
2365
2469
  if (this.admissionPaused) return false;
2470
+ // A pinned request (from a linked pool) may ONLY run on the named account, and
2471
+ // never on a mirror row (no chained forwarding between pools).
2472
+ if (requestInfo.pinAccount != null) {
2473
+ if (account.remote || account.name !== requestInfo.pinAccount) return false;
2474
+ // P1: the pin bypasses this pool's balancer, so keep its anti-dogpile floor
2475
+ // here — refuse past 2x the soft per-account target; the caller fails over.
2476
+ if ((account.inFlight || 0) >= 2 * this.scheduler.perAccountConcurrencyTarget) {
2477
+ requestInfo.pinRefusedBusy = true;
2478
+ return false;
2479
+ }
2480
+ // P3: a pinned request isn't competing in this pool's queue — it skips the
2481
+ // queue-fairness gate (that alone 503'd every pinned Claude request). The
2482
+ // upstream throttle STAYS: it describes this pool's real egress to Anthropic.
2483
+ if (!this._isRequestCompatible(account, profile, requestInfo)) return false;
2484
+ if (account.type !== 'provider' && this._isUpstreamThrottleBlocking()) return false;
2485
+ return true;
2486
+ }
2366
2487
  // Duplicate guard: a local account whose identity also lives in a team pool
2367
2488
  // never serves — the cloud copy is the single writer.
2368
2489
  if (account.poolBenchedBy) return false;
2369
2490
  if (!this._isRequestCompatible(account, profile, requestInfo)) return false;
2370
- const providerLike = account.type === 'provider' || account.type === 'pool';
2491
+ // Cloud mirrors egress from the cloud's own IP — this machine's upstream throttle
2492
+ // and local queue fairness don't describe them.
2493
+ const providerLike = account.type === 'provider' || account.type === 'pool' || Boolean(account.remote);
2371
2494
  if (
2372
2495
  !providerLike
2373
2496
  && this.queueState.waiting.length
@@ -2865,7 +2988,10 @@ export class AccountManager {
2865
2988
  // pool will respect the accounts within it... included in the balancing act").
2866
2989
  // The link row's inFlight is mirrored from the remote status poll, so the
2867
2990
  // concurrency term already treats one link request as N remote requests.
2868
- const inflight = account.activeWeight + reqWeight;
2991
+ // A cloud mirror's depth includes OTHER teammates' live load on that same cloud
2992
+ // account (mirrored from the link poll), so every routing term below — the
2993
+ // unchanged balancing logic — sees it as busy as it really is.
2994
+ const inflight = account.activeWeight + reqWeight + (account._remoteOtherLoad || 0);
2869
2995
  const refillMult = this._fastRefillMultiplier(account);
2870
2996
  if (account.type === 'pool' && account._link) {
2871
2997
  // Utilization = the cloud's own reported fraction of usable accounts spent
@@ -4119,6 +4245,7 @@ export class AccountManager {
4119
4245
  if (
4120
4246
  !account.enabled
4121
4247
  || account.type === 'provider'
4248
+ || account.remote // H4: cloud rows egress from the cloud, not this machine
4122
4249
  || !this._isRequestCompatible(account, requestInfo.profile || 'claude', requestInfo)
4123
4250
  ) {
4124
4251
  continue;
@@ -4464,7 +4591,7 @@ export class AccountManager {
4464
4591
  // being iterated makes the loop skip the element after each removal — so
4465
4592
  // dropping 2 of 3 config providers left one phantom behind.
4466
4593
  for (const a of [...this.accounts]) {
4467
- if (a.configSourced && !wantedNames.has(a.name)) {
4594
+ if (a.configSourced && !a.remote && !wantedNames.has(a.name)) {
4468
4595
  const idx = this.accounts.indexOf(a);
4469
4596
  if (idx >= 0 && this.accounts[idx].inFlight === 0) this.removeAccount(idx);
4470
4597
  }
@@ -4568,7 +4695,7 @@ export class AccountManager {
4568
4695
  * by account identity so it can be matched back after a restart.
4569
4696
  */
4570
4697
  exportQuotaState() {
4571
- return this.accounts.map(a => {
4698
+ return this.accounts.filter(a => !a.remote).map(a => {
4572
4699
  const quota = {};
4573
4700
  for (const f of PERSISTED_QUOTA_FIELDS) quota[f] = a.quota[f];
4574
4701
  const out = { accountUuid: a.accountUuid, name: a.name, quota };
@@ -4639,7 +4766,8 @@ export class AccountManager {
4639
4766
  for (const l of this.poolLinks) {
4640
4767
  if (l.identities) for (const [k, v] of l.identities) ids.set(k, v);
4641
4768
  }
4642
- const dups = computeDuplicates(this.accounts, ids);
4769
+ for (const l of this.poolLinks) this.syncRemoteMirrors(l);
4770
+ const dups = computeDuplicates(this.accounts.filter(a => !a.remote), ids);
4643
4771
  const benchedIdx = new Set(dups.map(d => d.index));
4644
4772
  for (const a of this.accounts) {
4645
4773
  const wasBenched = Boolean(a.poolBenchedBy);
@@ -4688,6 +4816,67 @@ export class AccountManager {
4688
4816
  return null;
4689
4817
  }
4690
4818
 
4819
+ /** MIRROR the linked pool's accounts as individual routable rows (owner
4820
+ * 2026-10-29: "every cloud account listed the same way the local ones are ...
4821
+ * pulled together without any aggregation"). Each mirror row carries the remote's
4822
+ * live quota/status and NO credential — prober, token refresh, card redemption and
4823
+ * persistence all skip credential-less rows by construction. A request routed to a
4824
+ * mirror row is forwarded to its pool PINNED to that remote account. */
4825
+ syncRemoteMirrors(link) {
4826
+ if (!link) return;
4827
+ const rows = link.lastError || link.lastOkAt == null ? [] : (link.status?.accounts || []);
4828
+ const seen = new Set();
4829
+ for (const ra of rows) {
4830
+ if (ra.remote) continue; // never mirror a mirror (no chained hops)
4831
+ if (ra.enabled === false) continue; // benched on the cloud = not offered
4832
+ const name = `${ra.name} ☁`;
4833
+ seen.add(name);
4834
+ let a = this.accounts.find(x => x.remote && x.name === name);
4835
+ if (!a) {
4836
+ this.addAccount({
4837
+ name, type: ra.type === 'oauth' ? 'oauth' : (ra.type === 'provider' ? 'provider' : ra.type),
4838
+ provider: ra.provider, profiles: ra.type === 'provider' ? ['all'] : ['claude', 'all'],
4839
+ configSourced: true, runtime: false,
4840
+ });
4841
+ a = this.accounts[this.accounts.length - 1];
4842
+ }
4843
+ a.remote = { linkName: link.name, remoteName: ra.name, url: link.url, key: link.key, link };
4844
+ a.credential = null; a.refreshToken = null;
4845
+ // M2: keep the cloud's uuid OFF accountUuid so uuid-first matchers (config
4846
+ // persistence, re-auth, disk sync) can never resolve to a mirror row.
4847
+ a.accountUuid = null;
4848
+ a.remoteUuid = ra.accountUuid || null;
4849
+ a.provider = ra.provider || a.provider;
4850
+ a.quota = { ...emptyQuota(), ...(ra.quota || {}) };
4851
+ a.status = ra.status || 'active';
4852
+ a.refreshDead = Boolean(ra.refreshDead);
4853
+ a.lastError = ra.lastError || null;
4854
+ a.rateLimitedUntil = ra.rateLimitedUntil ? Date.parse(ra.rateLimitedUntil) : null;
4855
+ a.capUtilization = ra.capUtilization ?? null;
4856
+ a.capMode = ra.capMode ?? a.capMode;
4857
+ a.capCeiling = ra.capCeiling ?? a.capCeiling;
4858
+ a.capRampStart = ra.capRampStart ?? a.capRampStart;
4859
+ a.addedAt = null; // H3: mirrors never count as "warming"
4860
+ a.resetCards = ra.resetCards || null;
4861
+ a.resetGrants = ra.resetGrants || null;
4862
+ // Other teammates' live load on this cloud account (remote inFlight minus our
4863
+ // own leases) — so the balancer sees the account as busy as it really is.
4864
+ a._remoteOtherLoad = Math.max(0, (ra.inFlight || 0) - (a.inFlight || 0));
4865
+ a._remoteLoad = ra.load || null;
4866
+ a.probing = false;
4867
+ a.enabled = true;
4868
+ }
4869
+ // A cloud account that left the cloud (or a down link): drop the mirror so
4870
+ // routing never targets it. Rows with in-flight leases drain first.
4871
+ // Never REMOVE at runtime (red-team P5): removal reindexes every account while
4872
+ // refreshes/exclusions hold numeric indexes. A gone or unreachable cloud account
4873
+ // is disabled in place (out of routing, hidden from the list) and revived when
4874
+ // it reappears.
4875
+ for (const a of this.accounts) {
4876
+ if (a.remote && a.remote.linkName === link.name && !seen.has(a.name)) a.enabled = false;
4877
+ }
4878
+ }
4879
+
4691
4880
  /** True when account is benched by the duplicate guard. */
4692
4881
  isPoolBenched(account) {
4693
4882
  return Boolean(account && account.poolBenchedBy);
@@ -4718,6 +4907,11 @@ export class AccountManager {
4718
4907
  provider: a.provider,
4719
4908
  enabled: a.enabled,
4720
4909
  poolBenchedBy: a.poolBenchedBy || null,
4910
+ remote: Boolean(a.remote),
4911
+ // Reset cards / grants (display + cross-pool routing preference). Card ids,
4912
+ // counts and expiry only — no credentials; the redeem stays with the holder.
4913
+ resetCards: a.resetCards ? { fiveHour: a.resetCards.fiveHour, weekly: a.resetCards.weekly, checkedAt: a.resetCards.checkedAt } : null,
4914
+ resetGrants: a.resetGrants ? { grants: a.resetGrants.grants, cooldownUntil: a.resetGrants.cooldownUntil, checkedAt: a.resetGrants.checkedAt } : null,
4721
4915
  // Identity for duplicate matching by linked pools (D12). The Claude account
4722
4916
  // UUID is an identifier, not a credential; provider keys export only a
4723
4917
  // fingerprint. Without these a linked pool can't see a duplicate Claude login
@@ -4812,6 +5006,11 @@ export class AccountManager {
4812
5006
  : 0,
4813
5007
  },
4814
5008
  callers: Object.fromEntries([...this.callerCounts.entries()].map(([n, c]) => [n, { requests: c }])),
5009
+ // SC22: per-person analytics for linked pools (day buckets + windows + tokens).
5010
+ callerStats: Object.fromEntries([...this.callerStats.entries()].map(([n, st]) => [n, {
5011
+ days: st.days, total: { ...st.total },
5012
+ }])),
5013
+ callerWindows: Object.fromEntries([...this.callerWindowStats().entries()].map(([n, w]) => [n, w])),
4815
5014
  pools: this.poolLinks.map(l => ({
4816
5015
  name: l.name,
4817
5016
  url: l.url,
package/src/index.js CHANGED
@@ -647,6 +647,7 @@ async function serverWorkerCommand() {
647
647
  // self-healing window as an abrupt SIGKILL. A cold restart reads the clean-shutdown
648
648
  // final flush and restores fully (the reported zero-request case).
649
649
  if (savedState?.runtimeProviders) accountManager.restoreRuntimeProviders(savedState.runtimeProviders);
650
+ if (savedState?.callerStats) accountManager.restoreCallerStats?.(savedState.callerStats);
650
651
 
651
652
  // ── config-sourced providers (GCP Secret Manager) ──────────────────────────
652
653
  // Provider keys (GLM, Kimi) defined in the config's `providers` section, each
@@ -698,7 +699,9 @@ async function serverWorkerCommand() {
698
699
  ...p,
699
700
  key: p.keySecret ? (resolved[p.keySecret] || null) : (p.key || null),
700
701
  }));
701
- for (const l of links) accountManager.upsertPoolAccount(l);
702
+ // Owner 2026-10-29: no single "team" account — each cloud account is mirrored
703
+ // as its own row (syncRemoteMirrors on every link poll) and balanced with the
704
+ // local accounts by the unchanged routing logic.
702
705
  accountManager.setPoolLinks(links);
703
706
  const armed = links.filter(l => l.key).length;
704
707
  console.log(`[Maxpool] Team pools: ${armed} linked${links.length - armed ? `, ${links.length - armed} unresolved key` : ''}`);
@@ -741,6 +744,9 @@ async function serverWorkerCommand() {
741
744
  // OPEN cycle must persist or a mid-cycle restart records a near-empty cycle as
742
745
  // a real capacity observation and poisons the averages forever (B1).
743
746
  capacity: accountManager.capacity?.serialize?.() || null,
747
+ // SC22 per-person analytics — same generation-guarded payload, survives
748
+ // restarts and seamless reloads.
749
+ callerStats: accountManager.exportCallerStats?.() || {},
744
750
  },
745
751
  { expectedGeneration },
746
752
  )
package/src/server.js CHANGED
@@ -288,7 +288,11 @@ export function createProxyServer(accountManager, config, hooks = {}) {
288
288
  // In strict mode the legacy single key is still accepted; label it so its
289
289
  // traffic is attributed and logged rather than anonymous.
290
290
  req.callerName = caller.name || (strictClients ? 'legacy-key' : null);
291
+ // SC22: count ONLY when this pool serves the request upstream. A request
292
+ // later routed to a linked pool is UN-counted at release time (the serving
293
+ // pool owns it) — see the pool-forward path's countRequest(name,{forwarded:true}).
291
294
  accountManager.countRequest?.(req.callerName);
295
+ req._caller = req.callerName;
292
296
 
293
297
  // Let client token refresh requests pass through to upstream untouched.
294
298
  // The proxy manages its own tokens via ensureTokenFresh(); intercepting
@@ -381,7 +385,13 @@ export function createProxyServer(accountManager, config, hooks = {}) {
381
385
  requestInfo.queueBlockedReason = `request body ${body.length} bytes exceeds queue.maxQueuedBodyBytes ${maxQueuedBodyBytes}`;
382
386
  }
383
387
  requestInfo.profile = getMaxpoolProfile(req.headers);
388
+ // PIN (owner D8 per-account shape): a linked pool chose a specific account
389
+ // here. Honored only for an authenticated NAMED client — an anonymous/legacy
390
+ // caller can't steer routing. Applied by selection as an exclusive filter.
391
+ const pin = headerValue(req.headers, 'x-maxpool-pin-account');
392
+ if (pin && req.callerName && req.callerName !== 'legacy-key') requestInfo.pinAccount = String(pin);
384
393
  requestInfo.sessionKey = headerValue(req.headers, 'x-maxpool-session');
394
+ requestInfo.caller = req._caller || null;
385
395
  // The CLIENT tells us how long it will wait — the only source that is actually
386
396
  // true. A `cc` session exports CLAUDE_STREAM_IDLE_TIMEOUT_MS=3h and forwards it
387
397
  // here; a bare `claude` sends nothing and keeps the conservative 240s default,
@@ -587,6 +597,16 @@ async function forwardRequest(
587
597
  );
588
598
  if (queued) return;
589
599
 
600
+ if (requestInfo.pinAccount != null) {
601
+ ctx.status = 503;
602
+ const busy = Boolean(requestInfo.pinRefusedBusy);
603
+ ctx.account = `(pinned ${requestInfo.pinAccount} ${busy ? 'busy' : 'unavailable'})`;
604
+ try { res.setHeader('retry-after', busy ? '2' : '30'); } catch { /* headers sent */ }
605
+ sendErrorResponse(res, requestInfo, 503, { type: 'error', error: {
606
+ type: busy ? 'pinned_account_busy' : 'pinned_account_unavailable',
607
+ message: `Account "${requestInfo.pinAccount}" is ${busy ? 'busy' : 'not available'} right now` } });
608
+ return;
609
+ }
590
610
  ctx.status = 429;
591
611
  ctx.account = '(none available)';
592
612
  const retryPlan = accountManager.nextRetryForRequest?.(requestInfo, new Set()) || {};
@@ -729,7 +749,7 @@ async function forwardRequest(
729
749
  // request to it with the person's key, a stepped hop header, and the client's
730
750
  // session header preserved — the remote pool does its own account selection,
731
751
  // so no body rewriting, no credential substitution.
732
- if (account.type === 'pool') {
752
+ if (account.type === 'pool' || account.remote) {
733
753
  const hop = nextHopCount(headerValue(req.headers, HOP_HEADER));
734
754
  if (hop == null) {
735
755
  accountManager.releaseAccount(lease, { neutral: true });
@@ -746,12 +766,16 @@ async function forwardRequest(
746
766
  // cloud pool turned them into runtime accounts — a key the owner had disabled
747
767
  // locally went live remotely). The remote pool owns its own accounts.
748
768
  if (/^x-maxpool-(zai|kimi)-/.test(lk)) continue;
769
+ if (lk === 'x-maxpool-pin-account') continue; // M4: only this pool sets a pin
749
770
  linkHeaders[k] = v;
750
771
  }
751
772
  linkHeaders[HOP_HEADER] = String(hop);
752
- linkHeaders['x-api-key'] = account.credential; // person's pool key
773
+ // person's pool key: the link row holds it; a mirror row carries its link's key
774
+ linkHeaders['x-api-key'] = account.remote ? account.remote.key : account.credential;
753
775
  delete linkHeaders.authorization;
754
- const linkUrl = `${account.upstream}${req.url}`;
776
+ if (account.remote) linkHeaders['x-maxpool-pin-account'] = account.remote.remoteName;
777
+ const linkBase = account.remote ? String(account.remote.url).replace(/\/+$/, '') : account.upstream;
778
+ const linkUrl = `${linkBase}${req.url}`;
755
779
  ctx.account = account.name;
756
780
  // The client-gone listener from the pre-response window would release the
757
781
  // lease a SECOND time when the stream closes normally — remove just the
@@ -763,8 +787,30 @@ async function forwardRequest(
763
787
  accountManager.releaseAccount(lease, outcome);
764
788
  };
765
789
  try {
766
- const upRes = await fetch(linkUrl, { method: req.method, headers: linkHeaders, body: ['GET', 'HEAD'].includes(req.method) ? undefined : body, duplex: 'half' });
790
+ // P4a: a blackholed link must not hang the request (and hold a lease) for
791
+ // minutes — bound time-to-headers like the direct path's TTFB guard.
792
+ const linkCtl = new AbortController();
793
+ const linkTtfb = setTimeout(() => linkCtl.abort(), 15_000);
794
+ res.once('close', () => linkCtl.abort());
795
+ let upRes;
796
+ try {
797
+ upRes = await fetch(linkUrl, { method: req.method, headers: linkHeaders, body: ['GET', 'HEAD'].includes(req.method) ? undefined : body, duplex: 'half', signal: linkCtl.signal });
798
+ } finally { clearTimeout(linkTtfb); }
767
799
  ctx.status = upRes.status;
800
+ // Pinned cloud account refused (rate-limited / unavailable) before any byte
801
+ // streamed: cool THIS mirror row and fail over through the normal path to the
802
+ // next-best account, local or cloud — exactly like a local account's 429.
803
+ if (account.remote && (upRes.status === 429 || upRes.status === 503) && retryCount + 1 < maxAttempts && !res.headersSent) {
804
+ try { await upRes.body?.cancel(); } catch { /* drained */ }
805
+ const ra = Number(upRes.headers.get('retry-after'));
806
+ // P3: "busy" is a 2s back-off on this row only; "unavailable"/429 cools longer.
807
+ account.cooldownUntil = Date.now() + (Number.isFinite(ra) && ra > 0 ? Math.min(ra, 300) * 1000 : 30_000);
808
+ finishLink({ status: upRes.status, error: 'remote_pinned_unavailable' });
809
+ excludedIndexes.add(account.index);
810
+ if (hasEligibleRoute(accountManager, requestInfo, excludedIndexes)) {
811
+ return forwardRequest(req, res, body, accountManager, upstream, retryCount + 1, hooks, reqId, ctx, logDir, retryConfig, queueConfig, requestInfo, canRetryBufferedBody, canQueueBufferedBody, excludedIndexes);
812
+ }
813
+ }
768
814
  const outHeaders = {};
769
815
  upRes.headers.forEach((v, k) => { if (!HOP_BY_HOP_HEADERS.has(k) && k !== 'content-length' && k !== 'transfer-encoding') outHeaders[k] = v; });
770
816
  res.writeHead(upRes.status, outHeaders);
@@ -781,9 +827,16 @@ async function forwardRequest(
781
827
  }
782
828
  res.end();
783
829
  finishLink({ success: ctx.status < 500, status: ctx.status });
830
+ // SC22 no-double-count: this request was counted at auth; the serving pool
831
+ // counted it too. Undo the local one.
832
+ if (req.callerName && ctx.status < 500) {
833
+ accountManager.callerCounts?.set(req.callerName, Math.max(0, (accountManager.callerCounts.get(req.callerName) || 1) - 1));
834
+ accountManager._unbumpCaller?.(req.callerName);
835
+ }
784
836
  hooks.onRequestRouted?.(reqId, { account: account.name });
785
837
  } catch (err) {
786
838
  finishLink({ status: 502, error: 'pool_link_unreachable' });
839
+ excludedIndexes.add(account.index); // P4b: never re-pick a row that just failed
787
840
  const retried = retryCount + 1 < maxAttempts && hasEligibleRoute(accountManager, requestInfo, excludedIndexes)
788
841
  ? await forwardRequest(req, res, body, accountManager, upstream, retryCount + 1, hooks, reqId, ctx, logDir, retryConfig, queueConfig, requestInfo, canRetryBufferedBody, canQueueBufferedBody, excludedIndexes)
789
842
  : null;
@@ -2769,6 +2822,10 @@ async function queueAndRetry(
2769
2822
  // a real outage doesn't spin. A non-streaming network failure (no keepalive) still
2770
2823
  // fails fast — it would die on the client's own timeout anyway.
2771
2824
  if (cause === 'proxy') return false;
2825
+ // A PINNED request (a linked pool chose one specific account here) never holds:
2826
+ // the caller owns failover across its whole pool, so answer fast and let it pick
2827
+ // the next-best account instead of parking the request on one busy account.
2828
+ if (requestInfo.pinAccount != null) return false;
2772
2829
  if (cause === 'network' && !canQueueBufferedBody) return false;
2773
2830
  // NETWORK SOAK, hard-bounded. A brief connectivity blip should not throw away a turn —
2774
2831
  // but an unbounded soak is worse than a fast error (it presents as a hang, which is the
@@ -3800,9 +3857,11 @@ function parseSSEEvent(event, accountIndex, accountManager, requestInfo = {}) {
3800
3857
  if (!requestInfo.isCountTokens) {
3801
3858
  if (data.type === 'message_start' && data.message?.usage) {
3802
3859
  accountManager.updateUsage(accountIndex, data.message.usage.input_tokens, 0);
3860
+ accountManager.countCallerTokens?.(requestInfo.caller, data.message.usage.input_tokens);
3803
3861
  requestInfo._capacityInput = Math.max(requestInfo._capacityInput || 0, data.message.usage.input_tokens || 0);
3804
3862
  } else if (data.type === 'message_delta' && data.usage) {
3805
3863
  accountManager.updateUsage(accountIndex, 0, data.usage.output_tokens);
3864
+ accountManager.countCallerTokens?.(requestInfo.caller, data.usage.output_tokens);
3806
3865
  requestInfo._capacityOutput = Math.max(requestInfo._capacityOutput || 0, data.usage.output_tokens || 0);
3807
3866
  }
3808
3867
  }
@@ -3856,6 +3915,7 @@ function extractUsageFromBody(buffer, accountIndex, accountManager, requestInfo
3856
3915
  const json = JSON.parse(buffer.toString());
3857
3916
  if (json.usage) {
3858
3917
  accountManager.updateUsage(accountIndex, json.usage.input_tokens, json.usage.output_tokens);
3918
+ accountManager.countCallerTokens?.(requestInfo.caller, (json.usage.input_tokens || 0) + (json.usage.output_tokens || 0));
3859
3919
  // CAPACITY LEDGER — M4: a /count_tokens response is a prompt-size echo with ZERO
3860
3920
  // work delivered. Claude Code calls it constantly; counting it would inflate every
3861
3921
  // cycle by whole prompt sizes.
package/src/tui.js CHANGED
@@ -30,6 +30,7 @@ const vw = s => strip(s).length;
30
30
  // Status/Quota start offsets (4/25/35/49) are pure functions of these widths + the
31
31
  // 4-col row prefix, independent of the quota-bar width.
32
32
  const NAME_W = 20; // a.name.slice(0, NAME_W).padEnd(NAME_W) — fits a full email like 2solarmax@gmail.com (19)
33
+ const WHERE_W = 5; // 'Local' / 'Cloud' — where the account is provisioned
33
34
  const PROVIDER_W = 9; // providerLabel(a).padEnd(PROVIDER_W) — fits "Anthropic"
34
35
  const STATUS_W = 13; // rpad(status, STATUS_W) — fits "throttled 59s"
35
36
  const RESETS_W = 6; // 'Rst' column — FIXED width (fits '2~21d'); a variable
@@ -43,8 +44,14 @@ const ROW_PREFIX = ' '; // ' ' + sel(1) + cur(1) + ' ' — 4 cols before the
43
44
  // Titlecase default so a future provider (Codex/Grok) renders sanely; truncated to
44
45
  // the column width so a long name can never misalign the row.
45
46
  const PROVIDER_LABELS = { anthropic: 'Anthropic', zai: 'z.ai', kimi: 'Moonshot', openai: 'OpenAI', codex: 'Codex', grok: 'Grok', xai: 'Grok' };
47
+ /** 'Cloud' for an account mirrored from a linked team pool, 'Local' otherwise. */
48
+ function whereCell(a) {
49
+ return a?.remote ? cyan('Cloud'.padEnd(WHERE_W)) : dim('Local'.padEnd(WHERE_W));
50
+ }
51
+
46
52
  function providerLabel(a) {
47
53
  if (a.type === 'pool') return 'Team pool';
54
+
48
55
  if (a._cloud) return (PROVIDER_LABELS[a.provider] || a.provider || 'Cloud').slice(0, PROVIDER_W - 1) + '☁';
49
56
  const key = a.provider || (a.type === 'provider' ? 'provider' : 'anthropic');
50
57
  const label = PROVIDER_LABELS[key] || (key.charAt(0).toUpperCase() + key.slice(1));
@@ -62,12 +69,19 @@ function acctHeader(W) {
62
69
  const quota = W >= 88 ? 'Quota (used% · resets-in)' : 'Quota';
63
70
  return ROW_PREFIX
64
71
  + 'Account'.padEnd(NAME_W) + ' '
72
+ + 'Where'.padEnd(WHERE_W) + ' '
65
73
  + 'Provider'.padEnd(PROVIDER_W) + ' '
66
74
  + 'Status'.padEnd(STATUS_W) + ' '
67
75
  + 'Rst'.padEnd(RESETS_W) + ' '
68
76
  + quota;
69
77
  }
70
78
 
79
+ /** padStart by VISIBLE width (ANSI color codes take no columns). */
80
+ function lpadVis(s, w) {
81
+ const gap = w - vw(s);
82
+ return gap > 0 ? ' '.repeat(gap) + s : s;
83
+ }
84
+
71
85
  function rpad(s, w) {
72
86
  const gap = w - vw(s);
73
87
  return gap > 0 ? s + ' '.repeat(gap) : s;
@@ -612,6 +626,7 @@ export class TUI {
612
626
  case 'routing': this._keyRouting(k); break;
613
627
  case 'updates': this._keyUpdates(k); break;
614
628
  case 'capacity': this._keyCapacity(k); break;
629
+ case 'people': this._keyPeople(k); break;
615
630
  case 'addtype': this._keyAddType(k); break;
616
631
  case 'select': this._keySelect(k); break;
617
632
  case 'input': this._keyInput(k); break;
@@ -657,6 +672,8 @@ export class TUI {
657
672
  this.mode = 'updates';
658
673
  } else if (k === 'y') {
659
674
  this.mode = 'capacity';
675
+ } else if (k === 'p') {
676
+ this.mode = 'people';
660
677
  } else if (k === 'h') {
661
678
  this.hideDisabled = !this.hideDisabled;
662
679
  this._addLog(this.hideDisabled ? 'Hiding disabled accounts' : 'Showing all accounts');
@@ -1983,6 +2000,14 @@ export class TUI {
1983
2000
  this._writeScreen(lines, W, H);
1984
2001
  return;
1985
2002
  }
2003
+ if (this.mode === 'people') {
2004
+ lines.push(...this._renderPeoplePage(W));
2005
+ while (lines.length < H - 2) lines.push('');
2006
+ lines.push(' ' + dim('─'.repeat(W - 2)));
2007
+ lines.push(this._renderFooter());
2008
+ this._writeScreen(lines, W, H);
2009
+ return;
2010
+ }
1986
2011
 
1987
2012
  // ── Accounts
1988
2013
  if (this.am.accounts.length === 0) {
@@ -2011,6 +2036,8 @@ export class TUI {
2011
2036
  let hidden = 0;
2012
2037
  for (const i of this._displayOrder()) {
2013
2038
  if (this.hideDisabled && this.am.accounts[i]?.enabled === false) { hidden++; continue; }
2039
+ // The legacy single team-pool row is superseded by per-account cloud rows.
2040
+ if (this.am.accounts[i]?.type === 'pool') continue;
2014
2041
  lines.push(this._renderAcct(i, bw, showBoth));
2015
2042
  }
2016
2043
  if (hidden > 0) {
@@ -2114,11 +2141,7 @@ export class TUI {
2114
2141
  // A row benched by the duplicate guard renders the CLOUD's live copy (status,
2115
2142
  // bars, in-flight, request counts) — never the stale local snapshot. Identity
2116
2143
  // and name stay local so the row doesn't move.
2117
- const remote = this.am.remoteRowFor?.(a);
2118
- if (remote) {
2119
- a = { ...a, ...remote.row, name: a.name, index: a.index, poolBenchedBy: a.poolBenchedBy,
2120
- _cloud: true, _cloudOk: remote.linkOk, enabled: true };
2121
- }
2144
+
2122
2145
  // Highlight the ACTIVE account(s) — drives BOTH the ► marker and the green
2123
2146
  // "active" status color. In manual mode that's the single pinned account (all
2124
2147
  // traffic goes there). In automatic load-balancing there is no single "current"
@@ -2136,7 +2159,9 @@ export class TUI {
2136
2159
  const cur = isCur ? green('►') : ' ';
2137
2160
 
2138
2161
  // Name (bold if selected)
2139
- const rawName = a.name.slice(0, NAME_W).padEnd(NAME_W);
2162
+ // A cloud row is named exactly like the account (the Where column says Cloud);
2163
+ // its internal name carries a suffix only to stay unique next to a local copy.
2164
+ const rawName = (a.remote ? a.remote.remoteName : a.name).slice(0, NAME_W).padEnd(NAME_W);
2140
2165
  // A disabled account reads as "off" — dim the whole name. Applied as a SINGLE SGR
2141
2166
  // (never dim(bold(...)) — bold()'s trailing RESET would cancel the dim mid-string),
2142
2167
  // so a disabled row is never also bold-selected.
@@ -2208,7 +2233,7 @@ export class TUI {
2208
2233
  case 'waiting': status = yellow('waiting'); break;
2209
2234
  case 'paused': status = yellow('paused'); break;
2210
2235
  case 'disabled': status = red('✕ disabled'); break;
2211
- case 'pool-benched': status = gray('⟐ team pool'); break;
2236
+ case 'pool-benched': status = gray('in cloud'); break;
2212
2237
  case 'cloud-down': status = red('⟐ cloud ✕'); break;
2213
2238
  // Disabled AND needs re-login — both facts matter, and DISABLED LEADS.
2214
2239
  // The owner's question that drove this (2026-09-30): "when I disable the account
@@ -2305,7 +2330,7 @@ export class TUI {
2305
2330
  t2 = t1;
2306
2331
  }
2307
2332
 
2308
- let line = ` ${sel}${cur} ${name} ${type} ${status} ${resetsCell} ${l1} ${bar(r1, bw, t1)}`;
2333
+ let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${resetsCell} ${l1} ${bar(r1, bw, t1)}`;
2309
2334
  if (showBoth) {
2310
2335
  // "no weekly cap on this plan" is a DIFFERENT state from "not read yet", and
2311
2336
  // both render as an empty bar. Say which, so a healthy uncapped account
@@ -2463,7 +2488,7 @@ export class TUI {
2463
2488
  // setting whenever the probe is quiet is how a shipped feature reads as absent.
2464
2489
  for (const tag of settingsTags(this.am, a)) note += ` ${tag}`;
2465
2490
 
2466
- let line = ` ${sel}${cur} ${name} ${type} ${status} Ses ${sesCell}`;
2491
+ let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} Ses ${sesCell}`;
2467
2492
  if (showBoth) line += ` Wk ${wkCell}`;
2468
2493
  line += note;
2469
2494
  // Same recent-load columns as OAuth (providers track inFlight + load events),
@@ -2502,11 +2527,74 @@ export class TUI {
2502
2527
  };
2503
2528
  }
2504
2529
 
2530
+ /** PEOPLE page (SC22) — usage by teammate. Rolling windows (24h/7d/30d, priors
2531
+ * as DELTAS) + cumulative, requests AND tokens; merges this pool's served traffic
2532
+ * with linked pools' callerWindows — each request counted once, at the pool that
2533
+ * served it (red-team verdict 2026-10-29: delta = % on base>=50, raw otherwise;
2534
+ * honesty footer for coverage + link sync; nobody-yet state, not zeros). */
2535
+ _renderPeoplePage(W = 80) {
2536
+ const out = [];
2537
+ out.push('');
2538
+ out.push(` ${bold('Usage by person')} ${dim('— requests · ~7d = tokens · rolling windows · no double counting')}`);
2539
+ out.push('');
2540
+
2541
+ const merged = new Map();
2542
+ const addWin = (name, w) => {
2543
+ const cur = merged.get(name) || { h24: 0, h24p: 0, d7: 0, d7p: 0, d30: 0, d30p: 0, total: 0, tok7: 0 };
2544
+ for (const k of ['h24', 'h24p', 'd7', 'd7p', 'd30', 'd30p', 'total']) cur[k] += (w[k]?.req ?? 0);
2545
+ cur.tok7 += (w.d7?.tok ?? 0);
2546
+ merged.set(name, cur);
2547
+ };
2548
+ for (const [n, w] of this.am.callerWindowStats?.() || []) addWin(n, w);
2549
+ for (const l of this.am.poolLinks || []) {
2550
+ const cw = l.status?.callerWindows || {};
2551
+ for (const [n, w] of Object.entries(cw)) addWin(n, w);
2552
+ }
2553
+ merged.delete('legacy-key');
2554
+ if (!merged.size) {
2555
+ out.push(dim(' Nobody has made a named request yet. Rows appear once requests'));
2556
+ out.push(dim(' carry personal pool keys.'));
2557
+ return out;
2558
+ }
2559
+
2560
+ const fmt = n => n >= 1000 ? (n / 1000).toFixed(n >= 10000 ? 0 : 1) + 'k' : String(n);
2561
+ const fmtTok = t => t >= 1e6 ? (t / 1e6).toFixed(1) + 'M' : t >= 1000 ? Math.round(t / 1000) + 'k' : String(t);
2562
+ const delta = (cur, prior) => {
2563
+ if (!prior) return dim('--');
2564
+ const d = prior >= 50 ? `${cur > prior ? '+' : ''}${Math.round(((cur - prior) / prior) * 100)}%` : `${cur - prior >= 0 ? '+' : ''}${cur - prior}`;
2565
+ return d.startsWith('+') ? green(d) : d.startsWith('-') ? yellow(d) : dim(d);
2566
+ };
2567
+ const CW = 9;
2568
+ const header = ' ' + 'person'.padEnd(10)
2569
+ + ['24h', 'Δ24h', '7d', 'Δ7d', '30d', 'Δ30d', 'total', '~7d tok'].map(c => c.padStart(CW)).join('');
2570
+ out.push(dimUnderline(fitLine(header, W)));
2571
+
2572
+ const rows = [...merged.entries()].sort((a, b) => b[1].d7 - a[1].d7);
2573
+ const tot = { h24: 0, h24p: 0, d7: 0, d7p: 0, d30: 0, d30p: 0, total: 0, tok7: 0 };
2574
+ for (const [name, w] of rows) {
2575
+ for (const k of Object.keys(tot)) tot[k] += w[k];
2576
+ out.push(' ' + name.slice(0, 10).padEnd(10)
2577
+ + [fmt(w.h24), delta(w.h24, w.h24p), fmt(w.d7), delta(w.d7, w.d7p), fmt(w.d30), delta(w.d30, w.d30p), fmt(w.total), fmtTok(w.tok7)]
2578
+ .map(c => lpadVis(String(c), CW)).join(''));
2579
+ }
2580
+ out.push(dim(' ' + 'total'.padEnd(10)
2581
+ + [fmt(tot.h24), delta(tot.h24, tot.h24p), fmt(tot.d7), delta(tot.d7, tot.d7p), fmt(tot.d30), delta(tot.d30, tot.d30p), fmt(tot.total), fmtTok(tot.tok7)]
2582
+ .map(c => lpadVis(String(c), CW)).join('')));
2583
+
2584
+ const link = (this.am.poolLinks || []).find(l => l.lastOkAt);
2585
+ out.push(dim(` data since boot${link ? ` · team pool synced ${new Date(link.lastOkAt).toLocaleTimeString()}` : ''}`));
2586
+ return out;
2587
+ }
2588
+
2505
2589
  _keyCapacity(k) {
2506
2590
  if (k === 'w') { this.capacityWindow = this.capacityWindow === 'wk' ? 'ses' : 'wk'; }
2507
2591
  else if (k === 'esc' || k === 'q') { this.mode = 'normal'; }
2508
2592
  }
2509
2593
 
2594
+ _keyPeople(k) {
2595
+ if (k === 'esc' || k === 'q') { this.mode = 'normal'; }
2596
+ }
2597
+
2510
2598
  /**
2511
2599
  * Capacity page — how much an account ACTUALLY delivers before it runs out.
2512
2600
  *
@@ -2638,11 +2726,13 @@ export class TUI {
2638
2726
  _renderFooter() {
2639
2727
  switch (this.mode) {
2640
2728
  case 'normal':
2641
- return ` ${bold('a')} Accounts ${bold('m')} Routing ${bold('y')} Capacity ${bold('h')} Hide disabled ${dim('│')} ${bold('u')} Updates ${bold('r')} Restart ${bold('q')} Stop server`;
2729
+ return ` ${bold('a')} Accounts ${bold('m')} Routing ${bold('y')} Capacity ${bold('p')} People ${bold('h')} Hide disabled ${dim('│')} ${bold('u')} Updates ${bold('r')} Restart ${bold('q')} Stop server`;
2642
2730
  case 'capacity': {
2643
2731
  const other = this.capacityWindow === 'wk' ? '5h session' : 'weekly (7d)';
2644
2732
  return ` ${bold('w')} Show ${cyan(other)} ${bold('Esc')} Back`;
2645
2733
  }
2734
+ case 'people':
2735
+ return ` ${bold('Esc')} Back`;
2646
2736
  case 'updates': {
2647
2737
  const state = this._autoUpdateOn() ? green('on') : dim('off');
2648
2738
  return ` ${bold('c')} Check & apply now ${bold('t')} Automatic updates: ${state} ↻ ${bold('Esc')} Back`;