maxpool 1.24.69 → 1.24.71

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.69",
3
+ "version": "1.24.71",
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",
@@ -108,6 +108,10 @@ function emptyQuota() {
108
108
  }
109
109
 
110
110
  const DEFAULT_SCHEDULER = {
111
+ // Kept high on purpose. A cap of 3 was tried 2026-11-07 (to look like one person)
112
+ // and measured against the owner's real traffic first: peaks of 79 simultaneous
113
+ // requests from his many sessions, with only ~4 accounts usable that day, would
114
+ // have queued and failed. Spreading load is the router's job, not a hard cap's.
111
115
  safetyMaxActivePerAccount: 50,
112
116
  safetyMaxGlobalActive: 150,
113
117
  cooldownMs: 30_000,
@@ -0,0 +1,107 @@
1
+ // One fixed client identity per upstream account (owner 2026-11-07, after two z.ai
2
+ // "usage risk" notices). Claude Code stamps every request with a per-INSTALL id
3
+ // (metadata.user_id → device_id) and its machine/runtime details (x-stainless-*,
4
+ // user-agent). Forwarded verbatim, one pooled account shows several installs on
5
+ // different machines alternating within seconds. Here every request leaving for an
6
+ // account carries that account's own stable device id and one machine profile, so
7
+ // each account presents as one laptop whoever sent the request. Sessions stay as
8
+ // sent (one person legitimately runs many sessions), and anything that is not a
9
+ // Claude Code request passes through untouched.
10
+ import { createHash } from 'node:crypto';
11
+
12
+ const FIXED_MACHINE = { 'x-stainless-os': 'MacOS', 'x-stainless-arch': 'arm64' };
13
+ const CC_UA = /^claude-cli\/\d+(?:\.\d+)*.*$/;
14
+
15
+ /** Stable per-account seed: the Claude account uuid, else the row name (NOT the
16
+ * provider key — z.ai key rotation would silently change the identity; the name
17
+ * survives rotation). Same account on two pools → same identity. */
18
+ function accountSeed(account) {
19
+ if (account.accountUuid) return `uuid:${account.accountUuid}`;
20
+ return `name:${account.name}`;
21
+ }
22
+
23
+ export function virtualDeviceId(account) {
24
+ return createHash('sha256').update(`maxpool-device-v1:${accountSeed(account)}`).digest('hex');
25
+ }
26
+
27
+ // The metadata.user_id string Claude Code sends today is a JSON object as a STRING
28
+ // inside the outer JSON body: metadata.user_id = '{"device_id":"…","account_uuid":"…","session_id":"…"}'.
29
+ // We operate on the RAW body string, splicing only that inner string. The rest of
30
+ // the body is never parsed or re-serialized: JSON.parse→stringify corrupts integers
31
+ // above 2^53 (snowflake ids in tool results) and reformats exponents — byte drift
32
+ // the transcript does not forgive (red-team M1, 2026-11-07).
33
+
34
+ /** Find the escaped-string value of metadata.user_id in a raw JSON body.
35
+ * Returns { start, end, text } — the value's source range WITHOUT quotes and its
36
+ * unescaped text — or null. Scanning, not regex: real bodies vary spacing, and the
37
+ * value itself contains escapes a naive [^"]* would cut short. */
38
+ function scanMetadataUserId(bodyStr) {
39
+ const key = bodyStr.indexOf('"user_id"');
40
+ if (key === -1) return null;
41
+ let i = bodyStr.indexOf(':', key + 9);
42
+ if (i === -1) return null;
43
+ i++;
44
+ while (i < bodyStr.length && /\s/.test(bodyStr[i])) i++;
45
+ if (bodyStr[i] === '{') {
46
+ // Not a string (someone sent an object) — not ours to touch.
47
+ return null;
48
+ }
49
+ if (bodyStr[i] !== '"') return null;
50
+ i++;
51
+ const start = i;
52
+ while (i < bodyStr.length) {
53
+ const c = bodyStr[i];
54
+ if (c === '\\') { i += 2; continue; }
55
+ if (c === '"') break;
56
+ i++;
57
+ }
58
+ if (i >= bodyStr.length) return null;
59
+ let text;
60
+ try { text = JSON.parse(`"${bodyStr.slice(start, i)}"`); } catch { return null; }
61
+ return { start, end: i, text };
62
+ }
63
+
64
+ /** Build the account's replacement for the inner user_id string. */
65
+ function replacementUserId(account, originalText) {
66
+ const device = virtualDeviceId(account);
67
+ const acctUuid = account.type === 'oauth' && account.accountUuid ? account.accountUuid : '';
68
+ let o = null;
69
+ try { o = JSON.parse(originalText); } catch { return null; }
70
+ if (!o || typeof o !== 'object' || !('device_id' in o) || !('session_id' in o)) return null;
71
+ o.device_id = device;
72
+ if ('account_uuid' in o) o.account_uuid = acctUuid;
73
+ const next = JSON.stringify(o);
74
+ return next === originalText ? null : next;
75
+ }
76
+
77
+ /** Rewrite metadata.user_id in a RAW request-body string. Returns the new body
78
+ * string, or null when nothing applies (not Claude Code's shape → untouched). */
79
+ export function rewriteMetadataUserIdRaw(bodyStr, account) {
80
+ if (typeof bodyStr !== 'string' || !bodyStr.includes('"metadata"')) return null;
81
+ const hit = scanMetadataUserId(bodyStr);
82
+ if (!hit) return null;
83
+ // Legacy flat form first: it is not JSON, so replacementUserId would reject it.
84
+ const legacy = /^user_[0-9a-f]+_account_[^_]*_session_(.+)$/.exec(hit.text);
85
+ const acctUuid = account.type === 'oauth' && account.accountUuid ? account.accountUuid : '';
86
+ let next = legacy
87
+ ? `user_${virtualDeviceId(account)}_account_${acctUuid}_session_${legacy[1]}`
88
+ : replacementUserId(account, hit.text);
89
+ if (next == null) return null;
90
+ return bodyStr.slice(0, hit.start) + JSON.stringify(next).slice(1, -1) + bodyStr.slice(hit.end);
91
+ }
92
+
93
+ /** Normalize outgoing headers in place: one machine profile for every account (the
94
+ * per-account device id is what tells them apart). Client versions are left as
95
+ * sent: pinning to the "newest seen" made every account's version regress after a
96
+ * restart (red-team M2) and mid-retry UA flips — and several versions is what a
97
+ * normal auto-updating fleet of installs looks like anyway. Only touches requests
98
+ * that identify as Claude Code (user-agent claude-cli/…). */
99
+ export function normalizeClientHeaders(headers) {
100
+ const uaKey = Object.keys(headers).find(k => k.toLowerCase() === 'user-agent');
101
+ if (!uaKey || !CC_UA.test(String(headers[uaKey]))) return false;
102
+ const lower = new Map(Object.keys(headers).map(k => [k.toLowerCase(), k]));
103
+ for (const [h, v] of Object.entries(FIXED_MACHINE)) {
104
+ if (lower.has(h)) headers[lower.get(h)] = v;
105
+ }
106
+ return true;
107
+ }
package/src/config.js CHANGED
@@ -77,6 +77,10 @@ export function createDefaultConfig() {
77
77
  // cache prefix. Claude-account responses are NEVER scrubbed. Default OFF until the
78
78
  // E2E package is owner-approved.
79
79
  providerThinkingScrub: false,
80
+ // Each upstream account presents ONE fixed Claude Code identity (device id +
81
+ // machine profile) regardless of who sent the request — pooled accounts stop
82
+ // showing several installs alternating within seconds. On by default; false = verbatim.
83
+ accountIdentity: true,
80
84
  routing: {
81
85
  mode: 'automatic',
82
86
  preferredAccount: null,
package/src/index.js CHANGED
@@ -18,6 +18,7 @@ import { loadOrCreateConfig, loadConfig, saveConfig, atomicConfigUpdate, getConf
18
18
  import { setEventLogPath, installConsoleMirror, setConsoleStdoutSuppressed, appendEventLog } from './event-log.js';
19
19
  import { sendLoginToPool, planCliLogin, resolveUsablePools } from './cloud-login.js';
20
20
  import { SleepGuard } from './sleep-guard.js';
21
+ import { controllingTerminalAlive } from './terminal-alive.js';
21
22
  import { AccountManager } from './account-manager.js';
22
23
  import { createProxyServer, REQUEST_IDLE_MAX_MS } from './server.js';
23
24
 
@@ -1638,7 +1639,18 @@ async function serverWorkerCommand() {
1638
1639
  // drain + exit cleanly so we never reload into a headless orphan that outlives
1639
1640
  // the terminal and squats the port. Headless/service mode keeps SIGHUP as the
1640
1641
  // conventional reload signal (baton under the supervisor, else exit-75).
1641
- process.on('SIGHUP', () => { if (isInteractiveTerminal()) shutdownGracefully('SIGHUP', { terminalClose: true }); else requestReload(); });
1642
+ // A SIGHUP while the terminal is still open came from another program (`kill
1643
+ // -HUP`), not a closed window — ignore it rather than kill every session using
1644
+ // the pool. Re-check shortly after, in case the signal raced the terminal revoke.
1645
+ const hangupShutdown = () => shutdownGracefully('SIGHUP', { terminalClose: true });
1646
+ process.on('SIGHUP', () => {
1647
+ if (!isInteractiveTerminal()) return requestReload();
1648
+ if (!controllingTerminalAlive()) return hangupShutdown();
1649
+ console.log('[Maxpool] Ignored SIGHUP: this terminal is still open, so another program sent it (not a closed window). Maxpool keeps running — press r to restart it.');
1650
+ for (const ms of [500, 2000]) {
1651
+ setTimeout(() => { if (!draining && !controllingTerminalAlive()) hangupShutdown(); }, ms).unref?.();
1652
+ }
1653
+ });
1642
1654
  }
1643
1655
 
1644
1656
  function logPlainServerStart({ host, port, accounts, threshold, config }) {
package/src/pool-link.js CHANGED
@@ -178,6 +178,17 @@ function sanitizeRemoteStatus(json) {
178
178
  * so a link that hasn't polled yet still benches what it benched last run.
179
179
  */
180
180
  const BOOT_IDS_TTL_MS = 14 * 24 * 3600 * 1000; // stale beyond this → trust a fresh boot instead
181
+ export const FAILS_BEFORE_DOWN = 2;
182
+
183
+ /** Plain-English cause of a link failure, for the one-line cloud banner. */
184
+ export function describeLinkError(err) {
185
+ const e = String(err || '');
186
+ if (e === 'key rejected') return "the cloud pool rejected this laptop's key";
187
+ if (/^HTTP 5\d\d$/.test(e)) return `the cloud pool answered with an error (${e})`;
188
+ if (/^HTTP /.test(e)) return `the cloud pool answered ${e}`;
189
+ // timeout, ECONNREFUSED/RESET, "fetch failed", DNS… — from here they look alike.
190
+ return `no connection — check your internet or the tunnel (${e || 'network error'})`;
191
+ }
181
192
 
182
193
  export class PoolLink {
183
194
  constructor(def, deps = {}) {
@@ -194,6 +205,8 @@ export class PoolLink {
194
205
  this.status = null; // raw remote status JSON when ok
195
206
  this.lastError = null;
196
207
  this.lastOkAt = null;
208
+ this.failStreak = 0; // consecutive failed checks
209
+ this.downSince = null; // when lastError was first set (the outage start)
197
210
  this.identities = new Map();
198
211
  this.summary = null;
199
212
  }
@@ -226,13 +239,23 @@ export class PoolLink {
226
239
  this.status = sanitizeRemoteStatus(r.json);
227
240
  this.lastOkAt = r.at;
228
241
  this.lastError = null;
242
+ this.failStreak = 0;
243
+ this.downSince = null;
229
244
  this.identities = remoteIdentities(r.json);
230
245
  this.summary = summarizeRemote(r.json);
231
246
  } else {
232
- // Keep the LAST good status for display, but mark the link degraded so
233
- // routing benches it and the UI names the error.
234
- this.lastError = r.error;
235
- this.summary = null;
247
+ // One missed check on a flaky network is not an outage: a single timeout
248
+ // used to flip every cloud row to ✕ while requests were still getting
249
+ // through. Mark the link down only after FAILS_BEFORE_DOWN checks in a row
250
+ // (a rejected key is never transient — down at once). Keep the LAST good
251
+ // status for display; down → routing benches it and the UI names the cause.
252
+ this.failStreak = (this.failStreak || 0) + 1;
253
+ this.lastPollError = r.error;
254
+ if (this.failStreak >= FAILS_BEFORE_DOWN || r.error === 'key rejected' || this.lastOkAt == null) {
255
+ if (!this.lastError) this.downSince = r.at;
256
+ this.lastError = r.error;
257
+ this.summary = null;
258
+ }
236
259
  }
237
260
  return r;
238
261
  } finally {
package/src/server.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import http from 'node:http';
2
+ import { normalizeClientHeaders, rewriteMetadataUserIdRaw } from './client-identity.js';
2
3
  import { appendEventLog } from './event-log.js';
3
4
  import { atomicConfigUpdate } from './config.js';
4
5
  import { HOP_HEADER, nextHopCount, safeText } from './pool-link.js';
@@ -499,6 +500,8 @@ export function createProxyServer(accountManager, config, hooks = {}) {
499
500
  // Read per request (not captured at boot) so a config flip + seamless reload
500
501
  // takes effect on the next request with no restart.
501
502
  requestInfo.providerThinkingScrub = Boolean(config.providerThinkingScrub);
503
+ // On unless switched off: each account presents as one fixed Claude Code install.
504
+ requestInfo.accountIdentity = config.accountIdentity !== false;
502
505
  // The CLIENT tells us how long it will wait — the only source that is actually
503
506
  // true. A `cc` session exports CLAUDE_STREAM_IDLE_TIMEOUT_MS=3h and forwards it
504
507
  // here; a bare `claude` sends nothing and keeps the conservative 240s default,
@@ -857,6 +860,7 @@ async function forwardRequest(
857
860
  headers['x-api-key'] = account.credential;
858
861
  delete headers['authorization'];
859
862
  }
863
+ if (requestInfo.accountIdentity && !account.remote) normalizeClientHeaders(headers);
860
864
 
861
865
  // POOL LINK (owner D8): this "account" is another maxpool. Forward the raw
862
866
  // request to it with the person's key, a stepped hop header, and the client's
@@ -994,7 +998,7 @@ async function forwardRequest(
994
998
 
995
999
  const upstreamUrl = `${account.upstream || upstream}${req.url}`;
996
1000
  const method = req.method;
997
- const upstreamBody = rewriteBodyForAccount(body, account);
1001
+ const upstreamBody = rewriteBodyForAccount(body, account, { identity: requestInfo.accountIdentity });
998
1002
 
999
1003
  // A threaded follow-up routed to an account that does not hold the thread cannot be
1000
1004
  // served by it: a different Anthropic account 404s, a provider rejects the truncated
@@ -3657,8 +3661,18 @@ function describeBodyShape(buf) {
3657
3661
  const threadOwners = new ThreadOwners();
3658
3662
  const THREAD_GATE_ENABLED = process.env.MAXPOOL_THREAD_GATE !== '0';
3659
3663
 
3660
- function rewriteBodyForAccount(body, account) {
3664
+ function rewriteBodyForAccount(body, account, { identity = false } = {}) {
3661
3665
  const needsProviderSanitize = account.type === 'provider';
3666
+ // Identity first, on the RAW string: splicing only the metadata.user_id value keeps
3667
+ // every other byte identical (a parse→serialize round-trip corrupts >2^53 integers
3668
+ // in tool results — red-team M1, 2026-11-07).
3669
+ if (identity && body.length && body.includes('"metadata"')) {
3670
+ const rewritten = rewriteMetadataUserIdRaw(body.toString(), account);
3671
+ if (rewritten != null && (!account.model && !account.modelMap && !needsProviderSanitize)) {
3672
+ return Buffer.from(rewritten);
3673
+ }
3674
+ if (rewritten != null) body = Buffer.from(rewritten);
3675
+ }
3662
3676
  if (!body.length || (!account.model && !account.modelMap && !needsProviderSanitize)) return body;
3663
3677
 
3664
3678
  try {
@@ -0,0 +1,24 @@
1
+ // Is the terminal running maxpool still open? A SIGHUP has two very different
2
+ // senders: the kernel, when the window closes (→ shut down, or we orphan onto a
3
+ // dead terminal), and another program running `kill -HUP` to "reload" (→ shutting
4
+ // down kills every session using the pool; happened 2026-11-07). When the window
5
+ // really closed, the controlling terminal is revoked: opening /dev/tty fails and
6
+ // writes to it fail. When it is still open, both succeed.
7
+ import { openSync, closeSync, writeSync } from 'node:fs';
8
+
9
+ export function controllingTerminalAlive({
10
+ isTTY = Boolean(process.stdout.isTTY),
11
+ fd = process.stdout.fd,
12
+ open = openSync, close = closeSync, write = writeSync,
13
+ } = {}) {
14
+ // Not a real terminal (a pipe, or the test suite's forced-terminal mode): no way
15
+ // to tell, so keep the long-standing answer — treat the SIGHUP as a hangup.
16
+ if (!isTTY) return false;
17
+ try {
18
+ close(open('/dev/tty', 'r+'));
19
+ write(fd, '');
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
package/src/tui.js CHANGED
@@ -4,6 +4,7 @@ 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
6
  import { sendLoginToPool } from './cloud-login.js';
7
+ import { describeLinkError } from './pool-link.js';
7
8
 
8
9
  // ── ANSI helpers ─────────────────────────────────────────────
9
10
 
@@ -815,6 +816,22 @@ export class TUI {
815
816
  return ` Routing ${cyan(routing)}${xpText}`;
816
817
  }
817
818
 
819
+ /** One line per unreachable team pool, so a lost connection reads as ONE cause
820
+ * instead of every cloud row turning red. '' lines are skipped by the caller. */
821
+ _cloudLinkLines(W = 80, now = Date.now()) {
822
+ const out = [];
823
+ for (const l of this.am.poolLinks || []) {
824
+ if (!l.lastError && l.lastOkAt != null) continue;
825
+ const since = l.downSince ?? l.lastOkAt;
826
+ const forTxt = since ? ` for ${formatAge(now - since)}` : '';
827
+ const synced = l.lastOkAt ? ` · last synced ${new Date(l.lastOkAt).toLocaleTimeString()}` : '';
828
+ const why = l.lastOkAt == null && !l.lastError ? 'connecting…' : describeLinkError(l.lastError);
829
+ const line = ` Cloud ${yellow(`⟐ ${l.name} unreachable${forTxt}`)} ${dim('—')} ${why}${dim(`. Cloud accounts paused; local accounts still serving${synced}.`)}`;
830
+ out.push(fitLine(line, W));
831
+ }
832
+ return out;
833
+ }
834
+
818
835
  _renderUpdatesDetail() {
819
836
  const v = this.am.versionInfo;
820
837
  const running = v?.current ? `v${v.current}` : 'unknown';
@@ -2076,6 +2093,7 @@ export class TUI {
2076
2093
  if (provReq > 0) xpText += ` ${dim('·')} ${yellow(`providers: ${provReq} req/15m`)}`;
2077
2094
  }
2078
2095
  lines.push(this._routingLine(routing, xpText));
2096
+ lines.push(...this._cloudLinkLines(W));
2079
2097
  const queuedCount = this.am.queueState?.waiting?.length || 0;
2080
2098
  // Throttle and WAITING are different things and used to share one line labelled
2081
2099
  // "Anthropic upstream throttled" — so a request parked purely because every account
@@ -2367,7 +2385,8 @@ export class TUI {
2367
2385
  case 'paused': status = yellow('paused'); break;
2368
2386
  case 'disabled': status = red('✕ disabled'); break;
2369
2387
  case 'pool-benched': status = gray('in cloud'); break;
2370
- case 'cloud-down': status = red('⟐ cloud ✕'); break;
2388
+ // The banner above names the cause once; each row just says it is out of reach.
2389
+ case 'cloud-down': status = yellow('⟐ offline'); break;
2371
2390
  // Disabled AND needs re-login — both facts matter, and DISABLED LEADS.
2372
2391
  // The owner's question that drove this (2026-09-30): "when I disable the account
2373
2392
  // and then the token expires, does it show disabled or reauth? It needs to