maxpool 1.5.47 → 1.5.48

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.5.47",
3
+ "version": "1.5.48",
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",
@@ -1881,6 +1881,18 @@ export class AccountManager {
1881
1881
  this.sessionPolicies.set(sessionKey, { ...existing, thinkingContaminated: true });
1882
1882
  }
1883
1883
 
1884
+ /** Release a session pinned provider-only by an earlier turn. The incompatible latch is
1885
+ * deliberately sticky (it never downgrades), which is right while the transcript really
1886
+ * is unrepairable — but a repaired body IS replayable on Claude, so the pin must lift
1887
+ * or every previously-broken session stays exiled forever. */
1888
+ clearSessionIncompatible(sessionKey) {
1889
+ if (!sessionKey) return;
1890
+ const existing = this.sessionPolicies.get(sessionKey);
1891
+ if (!existing?.anthropicIncompatible) return;
1892
+ this.sessionPolicies.set(sessionKey, { ...existing, anthropicIncompatible: false });
1893
+ console.log(`[Maxpool] Session "${sessionKey}" repaired — Claude routes re-enabled`);
1894
+ }
1895
+
1884
1896
  isSessionThinkingContaminated(sessionKey) {
1885
1897
  if (!sessionKey) return false;
1886
1898
  return Boolean(this.sessionPolicies.get(sessionKey)?.thinkingContaminated);
package/src/index.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  runReloadBaton,
18
18
  RELOAD_SWAPPED, RELOAD_ROLLED_BACK,
19
19
  MSG_LISTEN, MSG_RELEASE, MSG_TAKEOVER, MSG_PROBE_READY,
20
- MSG_RELOAD_REQUEST, MSG_READY, MSG_FAILED, MSG_RELEASED, MSG_PRIMARY,
20
+ MSG_RELOAD_REQUEST, MSG_READY, MSG_FAILED, MSG_RELEASED, MSG_PRIMARY, MSG_ROLLED_BACK,
21
21
  } from './reload-protocol.js';
22
22
 
23
23
  const args = process.argv.slice(2);
@@ -626,7 +626,9 @@ async function serverWorkerCommand() {
626
626
  // before (or without) the npm update check. The cold worker's update check below
627
627
  // fills in latest/hasUpdate.
628
628
  getCurrentVersion()
629
- .then(v => { accountManager.versionInfo ||= { current: v, latest: null, hasUpdate: false, checkedAt: null }; })
629
+ .then(v => {
630
+ accountManager.versionInfo ||= { current: v, latest: null, hasUpdate: false, checkedAt: null };
631
+ })
630
632
  .catch(() => {});
631
633
 
632
634
  // Persist refreshed tokens back to config. Defense-in-depth: the updater reads
@@ -727,6 +729,10 @@ async function serverWorkerCommand() {
727
729
  // Self-heal timer for a seamless reload that rolls back (new worker fails to boot,
728
730
  // we're never released). Cleared on MSG_RELEASE; fires cancelRestart otherwise.
729
731
  let reloadWatchdog = null;
732
+ // One cold-restart fallback per reload request — see the rollback watchdog below.
733
+ let coldFallbackUsed = false;
734
+ let reloadIsForUpdate = false;
735
+ let lastRollbackReason = null;
730
736
 
731
737
  // Best-effort terminal restore on ANY abnormal exit path (uncaughtException,
732
738
  // a bare process.exit, a crash) so the user's shell is never left in raw mode
@@ -857,6 +863,8 @@ async function serverWorkerCommand() {
857
863
  || process.env.MAXPOOL_TUI_COLD_RESTART === '1';
858
864
  if (!forceCold && reloadStrategy({ supervised }) === 'seamless') {
859
865
  try {
866
+ coldFallbackUsed = false; // fresh reload → fresh cold-fallback budget
867
+ lastRollbackReason = null;
860
868
  process.send({ type: MSG_RELOAD_REQUEST });
861
869
  // Arm the rollback self-heal: restartController already latched
862
870
  // pending/restarting + paused admission (in _restart, before we got here).
@@ -868,7 +876,29 @@ async function serverWorkerCommand() {
868
876
  reloadWatchdog = null;
869
877
  if (draining) return; // MSG_RELEASE already arrived → a real reload, not a rollback
870
878
  if (restartController?.cancelRestart()) {
871
- console.log('[Maxpool] Reload rolled back (new worker never took over) — resumed serving.');
879
+ console.log('[Maxpool] Reload rolled back (new worker never took over).');
880
+ }
881
+ // FALL BACK TO A COLD RESTART — but ONLY when a newer build is actually on disk
882
+ // waiting to be picked up. Resuming the old worker is what made "press u → c"
883
+ // look like nothing happened: the graceful swap failed under machine load and
884
+ // the update was abandoned, forever. Gating on a real pending update preserves
885
+ // the safety property that a plain failed reload leaves a HEALTHY worker serving
886
+ // (never kill a working process for nothing), while an update still lands.
887
+ // One attempt per reload request, so a build that cannot boot can't crash-loop.
888
+ // Cold-restart ONLY when the new build was merely SLOW to signal ready (a
889
+ // loaded machine — the reported case). If it reported failure or died before
890
+ // ready, the build cannot boot: restarting into it would leave the user with no
891
+ // working proxy at all, strictly worse than the bug being fixed. Absent reason
892
+ // (older supervisor) is treated as unsafe.
893
+ const swapWasSlowNotBroken = lastRollbackReason === 'timeout';
894
+ if (reloadIsForUpdate && swapWasSlowNotBroken && !coldFallbackUsed) {
895
+ coldFallbackUsed = true;
896
+ console.log('[Maxpool] Applying the update with a full restart instead — one moment.');
897
+ restartWorkerNow();
898
+ } else if (reloadIsForUpdate && !swapWasSlowNotBroken) {
899
+ console.log('[Maxpool] The new version failed to start — resumed serving on the current version. Update NOT applied.');
900
+ } else {
901
+ console.log('[Maxpool] Rollback complete — resumed serving on the current version.');
872
902
  }
873
903
  }, RELOAD_ROLLBACK_SELFHEAL_MS);
874
904
  reloadWatchdog.unref?.();
@@ -1060,6 +1090,11 @@ async function serverWorkerCommand() {
1060
1090
  if (r?.applicable && config?.autoApply && restartController) {
1061
1091
  markApplied(r.installedVersion);
1062
1092
  notifyUpdate('Applying update — seamless reload…');
1093
+ // Mark this reload as UPDATE-driven: if the seamless swap rolls back (machine
1094
+ // under load), the watchdog cold-restarts so the update actually lands instead of
1095
+ // silently resuming the old build. A plain 'r' restart never does that — there a
1096
+ // rollback should leave the healthy worker serving.
1097
+ reloadIsForUpdate = true;
1063
1098
  restartController.requestRestart();
1064
1099
  }
1065
1100
  };
@@ -1071,6 +1106,11 @@ async function serverWorkerCommand() {
1071
1106
  if (r?.applicable && restartController) {
1072
1107
  markApplied(r.installedVersion);
1073
1108
  notifyUpdate('Applying update — seamless reload…');
1109
+ // Mark this reload as UPDATE-driven: if the seamless swap rolls back (machine
1110
+ // under load), the watchdog cold-restarts so the update actually lands instead of
1111
+ // silently resuming the old build. A plain 'r' restart never does that — there a
1112
+ // rollback should leave the healthy worker serving.
1113
+ reloadIsForUpdate = true;
1074
1114
  restartController.requestRestart();
1075
1115
  }
1076
1116
  };
@@ -1284,6 +1324,9 @@ async function serverWorkerCommand() {
1284
1324
  // sends MSG_PRIMARY (the baton waits on it).
1285
1325
  await listenOnHandle(handle);
1286
1326
  await becomePrimary({ viaTakeover: true });
1327
+ } else if (msg?.type === MSG_ROLLED_BACK) {
1328
+ // Why the swap failed decides whether a cold restart is safe (see the watchdog).
1329
+ lastRollbackReason = msg.reason || null;
1287
1330
  } else if (msg?.type === MSG_RELEASE) {
1288
1331
  // Baton release: stop accepting NEW (keep in-flight), retire keep-alive
1289
1332
  // sockets with Connection: close, stop writing, flush once, drop TUI.
@@ -14,6 +14,11 @@
14
14
 
15
15
  // Supervisor → worker
16
16
  export const MSG_LISTEN = 'listen'; // (with handle) accept on this socket + take TUI/lease
17
+ // Tells the surviving old worker WHY a reload rolled back. 'timeout' = the new worker
18
+ // was merely slow to signal ready (a loaded machine) — safe to retry with a cold
19
+ // restart. 'failed' = it reported failure or died before ready — a cold restart there
20
+ // would commit to a build that cannot boot and leave NO working proxy.
21
+ export const MSG_ROLLED_BACK = 'rolled-back';
17
22
  export const MSG_RELEASE = 'release'; // stop accepting, stop writing, flush, give up TUI
18
23
  export const MSG_TAKEOVER = 'takeover'; // (with handle) start accepting + acquire writer lease + TUI
19
24
  export const MSG_PROBE_READY = 'probe-ready'; // ask a headless worker to confirm it booted OK
@@ -70,11 +75,13 @@ export async function runReloadBaton({
70
75
  ready = await newWorker.waitFor([MSG_READY, MSG_FAILED], readyTimeoutMs);
71
76
  } catch (err) {
72
77
  log(`reload: readiness wait failed (${err.message}); rolling back`);
78
+ try { oldWorker.send({ type: MSG_ROLLED_BACK, reason: 'timeout' }); } catch { /* old worker gone */ }
73
79
  return RELOAD_ROLLED_BACK;
74
80
  }
75
81
  // (b) New worker did not come up cleanly → roll back fully, old stays primary.
76
82
  if (!ready || ready.type === MSG_FAILED) {
77
83
  log(`reload: new worker reported failed (${ready?.reason || 'no ready'}); rolling back`);
84
+ try { oldWorker.send({ type: MSG_ROLLED_BACK, reason: 'failed' }); } catch { /* old worker gone */ }
78
85
  return RELOAD_ROLLED_BACK;
79
86
  }
80
87
 
package/src/server.js CHANGED
@@ -357,12 +357,28 @@ async function forwardRequest(
357
357
  // PRE-STRIP a session already known to carry provider-authored thinking. The client
358
358
  // resends the whole poisoned history every turn, so without this each turn pays another
359
359
  // rejected round-trip before the reactive repair kicks in. Latched by the first repair.
360
+ // ALSO repairs a transcript maxpool predicts Anthropic will reject (a provider web
361
+ // search). That prediction happens BEFORE any request is sent and bars every Claude
362
+ // account, so the reactive repair in the 4xx handler could never be reached for it —
363
+ // the session stayed exiled to GLM/Kimi, or got NO ROUTE AT ALL when they're disabled
364
+ // (8 healthy Claude accounts idle while the user is told nothing is available).
365
+ // Repairing here, ahead of routing, is what makes that case recoverable.
360
366
  if (retryCount === 0 && !requestInfo.thinkingStripped
361
- && accountManager.isSessionThinkingContaminated?.(requestInfo.sessionKey)) {
367
+ && (requestInfo.anthropicIncompatible
368
+ || accountManager.isSessionThinkingContaminated?.(requestInfo.sessionKey))) {
362
369
  const pre = stripForeignThinkingBlocks(body);
363
370
  if (pre.body) {
364
371
  body = pre.body;
365
372
  requestInfo = { ...requestInfo, thinkingStripped: true };
373
+ if (pre.converted) {
374
+ // The body now replays cleanly on Claude, so drop the predictive verdict —
375
+ // otherwise routing still exiles it and _noteRequestPolicy latches it sticky.
376
+ requestInfo = { ...requestInfo, anthropicIncompatible: false };
377
+ // And un-latch a session pinned by an EARLIER turn: the sticky policy is ORed in
378
+ // and never downgrades, so without this the user's already-broken sessions stay
379
+ // pinned forever even though we can now repair them.
380
+ accountManager.clearSessionIncompatible?.(requestInfo.sessionKey);
381
+ }
366
382
  }
367
383
  }
368
384
 
@@ -915,7 +931,11 @@ async function forwardRequest(
915
931
  // fixes it. Still deterministic — never the fuzzy isAnthropicIncompatBody heuristic.
916
932
  const isSignatureRejection = account.type !== 'provider'
917
933
  && (/invalid `signature` in `thinking`/i.test(errorBody)
918
- || /content\.\d+\.thinking\.signature/i.test(errorBody));
934
+ || /content\.\d+\.thinking\.signature/i.test(errorBody)
935
+ // A provider web search: `server_tool_use.id: String should match pattern
936
+ // '^srvtoolu_…'`. Repairable by converting the pair to text (verified 200 OK) —
937
+ // it used to fall through to a PERMANENT provider pin.
938
+ || /server_tool_use\.id: String should match pattern/i.test(errorBody));
919
939
  const errorType = errorBody.includes('Invalid `signature` in `thinking` block')
920
940
  ? 'invalid_thinking_signature'
921
941
  : anthropicIncompat ? 'anthropic_incompatible_transcript'
@@ -959,12 +979,12 @@ async function forwardRequest(
959
979
  // still fails, the provider pin below is the fallback.
960
980
  if (isSignatureRejection && !requestInfo.thinkingStripped
961
981
  && canRetryBufferedBody && retryCount + 1 < maxAttempts && !res.headersSent) {
962
- const { body: cleanBody, removed } = stripForeignThinkingBlocks(body);
982
+ const { body: cleanBody, removed, converted } = stripForeignThinkingBlocks(body);
963
983
  if (cleanBody) {
964
984
  // Latch it so EVERY later turn is stripped up front instead of re-paying this
965
985
  // rejected round-trip (the client resends the full poisoned history each turn).
966
986
  accountManager.markSessionThinkingContaminated?.(requestInfo.sessionKey);
967
- console.log(`[Maxpool] Recovering session on Claude: stripped ${removed} provider-authored thinking block(s) Anthropic rejected`);
987
+ console.log(`[Maxpool] Recovering session on Claude: stripped ${removed} provider thinking block(s), converted ${converted} provider search block(s) to text`);
968
988
  return forwardRequest(
969
989
  req, res, cleanBody, accountManager, upstream, retryCount + 1, hooks, reqId, ctx, logDir,
970
990
  retryConfig, queueConfig, { ...requestInfo, thinkingStripped: true },
@@ -1030,8 +1050,8 @@ async function forwardRequest(
1030
1050
  // ran; without it we found nothing provider-shaped, so claiming we stripped —
1031
1051
  // or blaming GLM/Kimi — would misdirect the user.
1032
1052
  const what = requestInfo.thinkingStripped
1033
- ? 'This session ran on GLM/Kimi earlier and Anthropic rejects the thinking blocks they wrote. Maxpool removed them and retried on Claude, but Anthropic still rejected the history.'
1034
- : "Anthropic rejected a thinking block in this session's history, and maxpool could not identify it as provider-authored, so it could not be repaired automatically.";
1053
+ ? 'This session ran on GLM/Kimi earlier, and Anthropic will not accept parts of what they wrote. Maxpool repaired what it could and retried on Claude, but Anthropic still rejected the history.'
1054
+ : "Anthropic rejected part of this session's history that maxpool could not repair automatically.";
1035
1055
  const hint = provs.length === 0
1036
1056
  ? ''
1037
1057
  : provs.every(a => a.enabled === false)
@@ -1556,22 +1576,96 @@ function isStrippableThinkingBlock(block) {
1556
1576
  *
1557
1577
  * Returns { body, removed } — `body` is null when nothing needed stripping.
1558
1578
  */
1579
+ // A provider's web search leaves a `server_tool_use` id Anthropic rejects (it demands
1580
+ // ^srvtoolu_). Verified 2026-07-26 against the live API: renaming the id is NOT enough —
1581
+ // a second gate rejects the result's `encrypted_content`, which only Anthropic can mint.
1582
+ // But converting the pair into plain TEXT is accepted (200 OK) and keeps what the search
1583
+ // actually found, so the session survives with its information intact. This is what made
1584
+ // the web-search case look permanently unrepairable.
1585
+ /** Collect foreign server-tool ids across the WHOLE transcript first — a call sits on the
1586
+ * assistant turn but its result is often carried on the FOLLOWING user turn, so a
1587
+ * per-message scan would leave that result behind (and it alone still 400s). */
1588
+ function collectForeignServerToolIds(messages) {
1589
+ const ids = new Set();
1590
+ const clientIds = new Set();
1591
+ const walk = (blocks) => {
1592
+ if (!Array.isArray(blocks)) return;
1593
+ for (const b of blocks) {
1594
+ if (b?.type === 'tool_use' && b.id) clientIds.add(b.id);
1595
+ if (b?.type === 'server_tool_use' && !ANTHROPIC_TOOL_ID.test(String(b.id || ''))) ids.add(b.id);
1596
+ if (Array.isArray(b?.content)) walk(b.content); // nested, mirrors detectTranscriptOrigin
1597
+ }
1598
+ };
1599
+ for (const msg of messages) walk(msg?.content);
1600
+ // NEVER treat an id that a real client tool_use also owns as foreign: converting its
1601
+ // tool_result would orphan that tool_use and Anthropic 400s ("tool_use ids without
1602
+ // tool_result"), which the sticky pre-strip would then re-inflict every turn — a
1603
+ // permanent loop. Providers with per-turn counters (call_0, call_1) make the collision
1604
+ // likely, not theoretical.
1605
+ for (const id of clientIds) ids.delete(id);
1606
+ return ids;
1607
+ }
1608
+
1609
+ function convertForeignServerTools(content, foreignIds) {
1610
+ if (!foreignIds || foreignIds.size === 0) return { content, converted: 0 };
1611
+ let converted = 0;
1612
+ const out = [];
1613
+ for (const b of content) {
1614
+ if (b?.type === 'server_tool_use' && foreignIds.has(b.id)) {
1615
+ const q = b.input?.query;
1616
+ out.push({ type: 'text', text: q ? `[searched the web for: ${q}]` : `[used ${b.name || 'a tool'}]` });
1617
+ converted++;
1618
+ continue;
1619
+ }
1620
+ // Any result block referring to a foreign call — web_search_tool_result and friends.
1621
+ if (b?.tool_use_id && foreignIds.has(b.tool_use_id)) {
1622
+ const rows = Array.isArray(b.content) ? b.content : [];
1623
+ // Fall back through the shapes a PROVIDER may use — the point of converting rather
1624
+ // than dropping is to keep what the search found; assuming Anthropic's {title,url}
1625
+ // would silently discard a GLM row that carries text instead.
1626
+ const found = rows
1627
+ .map(r => [r?.title, r?.url].filter(Boolean).join(' — ')
1628
+ || (typeof r === 'string' ? r : (r?.text ?? r?.content ?? r?.snippet ?? '')))
1629
+ .map(t => (typeof t === 'string' ? t.slice(0, 300) : ''))
1630
+ .filter(Boolean).slice(0, 10);
1631
+ out.push({ type: 'text', text: found.length ? `[search results: ${found.join(' | ')}]` : '[search returned no usable results]' });
1632
+ converted++;
1633
+ continue;
1634
+ }
1635
+ out.push(b);
1636
+ }
1637
+ return { content: out, converted };
1638
+ }
1639
+
1559
1640
  function stripForeignThinkingBlocks(body) {
1560
1641
  try {
1561
1642
  const json = JSON.parse(Buffer.isBuffer(body) ? body.toString('utf8') : String(body));
1562
1643
  if (!Array.isArray(json?.messages)) return { body: null, removed: 0 };
1563
1644
  let removed = 0;
1645
+ let converted = 0;
1646
+ const foreignToolIds = collectForeignServerToolIds(json.messages);
1564
1647
  const messages = [];
1565
1648
  for (const msg of json.messages) {
1566
- if (msg?.role !== 'assistant' || !Array.isArray(msg.content)) { messages.push(msg); continue; }
1649
+ if (!Array.isArray(msg?.content)) { messages.push(msg); continue; }
1650
+ // Foreign server-tool pairs are converted on EVERY role: the call sits on the
1651
+ // assistant turn but its result can be carried on the following user turn.
1652
+ const tools = convertForeignServerTools(msg.content, foreignToolIds);
1653
+ converted += tools.converted;
1654
+ if (msg.role !== 'assistant') {
1655
+ messages.push(tools.converted ? { ...msg, content: tools.content } : msg);
1656
+ continue;
1657
+ }
1567
1658
  let localRemoved = 0;
1568
- const kept = msg.content.filter(block => {
1659
+ const kept = tools.content.filter(block => {
1569
1660
  if (!isStrippableThinkingBlock(block)) return true;
1570
1661
  localRemoved++;
1571
1662
  return false;
1572
1663
  });
1573
1664
  removed += localRemoved;
1574
- if (!localRemoved) { messages.push(msg); continue; }
1665
+ if (!localRemoved) {
1666
+ messages.push(tools.converted ? { ...msg, content: tools.content } : msg);
1667
+ continue;
1668
+ }
1575
1669
  // A turn that stripping empties is DROPPED, not left with its poisoned block:
1576
1670
  // leaving it would resend the exact body that just 400'd while reporting success
1577
1671
  // and burning the single recovery attempt. Verified against the live API — the
@@ -1579,11 +1673,11 @@ function stripForeignThinkingBlocks(body) {
1579
1673
  if (kept.length === 0) continue;
1580
1674
  messages.push({ ...msg, content: kept });
1581
1675
  }
1582
- if (!removed) return { body: null, removed: 0 };
1676
+ if (!removed && !converted) return { body: null, removed: 0, converted: 0 };
1583
1677
  json.messages = messages;
1584
- return { body: Buffer.from(JSON.stringify(json)), removed };
1678
+ return { body: Buffer.from(JSON.stringify(json)), removed, converted };
1585
1679
  } catch {
1586
- return { body: null, removed: 0 }; // non-JSON / unparseable → no rewrite
1680
+ return { body: null, removed: 0, converted: 0 }; // non-JSON / unparseable → no rewrite
1587
1681
  }
1588
1682
  }
1589
1683