maxpool 1.24.71 → 1.24.72

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.71",
3
+ "version": "1.24.72",
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",
@@ -332,7 +332,7 @@ const PERSISTED_QUOTA_FIELDS = [
332
332
  // drops until the next probe sweep re-learns it. The probe still rewrites it on
333
333
  // every successful sweep, so a plan change heals on the same cadence.
334
334
  'weeklyAbsent', 'capSpanSes', 'capSpanWk', 'providerSes', 'providerSesReset', 'providerWk', 'providerWkReset',
335
- 'providerQuotaSource', 'lastProbeOkAt',
335
+ 'providerQuotaSource', 'lastProbeOkAt', 'noPlan',
336
336
  ];
337
337
 
338
338
  const PROVIDER_429_MIN_BENCH_SEC = 60;
@@ -3802,7 +3802,20 @@ export class AccountManager {
3802
3802
  if (usage.source === 'console-only') q.providerQuotaSource = 'console-only';
3803
3803
  return;
3804
3804
  }
3805
+ if (usage.noPlan) {
3806
+ // The key authenticates but the account HAS no plan (z.ai code 500 "no coding
3807
+ // plan", e.g. cancelled/expired — measured 2026-11-08). That is a stable
3808
+ // terminal state for the quota probe: show it in the row instead of "probing"
3809
+ // forever, and stop treating the row as a quota unknown.
3810
+ q.providerQuotaSource = 'zai';
3811
+ q.noPlan = true;
3812
+ q.providerSes = null; q.providerSesReset = null;
3813
+ q.providerWk = null; q.providerWkReset = null;
3814
+ q.lastProbeOkAt = Date.now();
3815
+ return;
3816
+ }
3805
3817
  q.providerQuotaSource = usage.source || 'zai';
3818
+ q.noPlan = false; // a real reading means the plan exists (renewed / re-bought)
3806
3819
  if (usage.ses) {
3807
3820
  if (usage.ses.utilization != null) q.providerSes = clamp01(usage.ses.utilization);
3808
3821
  if (usage.ses.resetAt != null) {
package/src/oauth.js CHANGED
@@ -417,6 +417,13 @@ export async function fetchProviderUsage(account) {
417
417
  if (!res.ok) return { error: `HTTP ${res.status}`, status: res.status };
418
418
  const data = await res.json();
419
419
  if (data?.code !== 200 || !data?.data) {
420
+ // HTTP 200 with a `success:false` body is a POSITIVE answer, not a transient
421
+ // probe failure: "当前用户不存在coding plan" (code 500 — the account has NO
422
+ // coding plan, measured 2026-11-08 on a cancelled plan) or an empty envelope.
423
+ // Returning it as `error` kept the TUI bars on "probing" forever while the
424
+ // row's real state — no plan to read — went unnamed.
425
+ const noPlan = data?.code === 500 && /coding plan/i.test(String(data?.msg || ''));
426
+ if (noPlan) return { noPlan: true, source: 'zai' };
420
427
  return { error: `bad_envelope${data?.code != null ? ' code=' + data.code : ''}` };
421
428
  }
422
429
  const now = Date.now();
package/src/server.js CHANGED
@@ -918,6 +918,28 @@ async function forwardRequest(
918
918
  upRes = await fetch(linkUrl, { method: req.method, headers: linkHeaders, body: ['GET', 'HEAD'].includes(req.method) ? undefined : body, duplex: 'half', signal: linkCtl.signal });
919
919
  } finally { clearTimeout(linkTtfb); }
920
920
  ctx.status = upRes.status;
921
+ // The linked pool refused the request's SHAPE (not Claude Code). The cloud
922
+ // subscription accounts are healthy — exclude them (this mirror + every local
923
+ // oauth row) and fail over to routes that CAN serve the shape (apikey/provider);
924
+ // pass the refusal through only when none remains. (Red-team r2: answering
925
+ // outright starved the request of local routes when a mirror was picked first.)
926
+ if (account.remote && upRes.status === 429 && upRes.headers.get(REQUEST_SHAPE_REFUSAL_HEADER) && !clientHasRealBytes(res, requestInfo)) {
927
+ const errorText = await readErrorBody(upRes);
928
+ finishLink({ status: 429, error: 'request_shape_refused', neutral: true });
929
+ excludedIndexes.add(account.index);
930
+ for (const a of accountManager.accounts) {
931
+ if (a.type === 'oauth') excludedIndexes.add(a.index);
932
+ }
933
+ if (
934
+ retryCount + 1 < maxAttempts
935
+ && !res.headersSent
936
+ && hasEligibleRoute(accountManager, requestInfo, excludedIndexes)
937
+ ) {
938
+ return forwardRequest(req, res, body, accountManager, upstream, retryCount + 1, hooks, reqId, ctx, logDir, retryConfig, queueConfig, requestInfo, canRetryBufferedBody, canQueueBufferedBody, excludedIndexes);
939
+ }
940
+ sendErrorBody(res, requestInfo, 429, errorText, upRes.headers);
941
+ return;
942
+ }
921
943
  // Pinned cloud account refused (rate-limited / unavailable) before any byte
922
944
  // streamed: cool THIS mirror row and fail over through the normal path to the
923
945
  // next-best account, local or cloud — exactly like a local account's 429.
@@ -1122,6 +1144,54 @@ async function forwardRequest(
1122
1144
  const errorBody = await readErrorBody(upstreamRes);
1123
1145
  const retryAfter = parseRetryAfter(upstreamRes.headers.get('retry-after'))
1124
1146
  || parseProviderRetryAfter(errorBody, account.provider);
1147
+ // REQUEST-SHAPE refusal (2026-11-08): on a subscription login Anthropic serves
1148
+ // Opus/Sonnet only to Claude-Code-shaped requests; anything else gets a bare 429
1149
+ // ("Error", no quota headers) while Haiku on the same account is served —
1150
+ // bisected live, the identity system line alone flips 429 → 200. The ACCOUNT is
1151
+ // healthy, so benching it (60s) blocked every real session on it, and failing
1152
+ // over just collected the same refusal from every other account. Answer THIS
1153
+ // request and leave the account untouched.
1154
+ if (account.type === 'oauth' && !/haiku/.test(String(requestInfo.model || '')) && isRequestShapeRefusal(rateLimitHeaders, errorBody, body)) {
1155
+ // Anthropic answered, but a bare headerless "Error" 429 is also what a REAL
1156
+ // fleet throttle looks like to this shape — evidence neither way. Hand the
1157
+ // recovery probe back UNUSED: no deferral, no clearing; the very next request
1158
+ // (often the apikey failover in this same chain) claims it (red-team r2).
1159
+ accountManager.relinquishUpstreamProbe(lease);
1160
+ accountManager.releaseAccount(lease, { status: 429, error: 'request_shape_refused', neutral: true });
1161
+ console.log(`[Maxpool] 429 on "${account.name}" is a request-shape refusal (not Claude Code) — subscription accounts left active`);
1162
+ if (logDir) {
1163
+ logSections.push(`=== RESPONSE 429 — "${account.name}" refused request shape (subscription accounts untouched) ===\n${formatHeaders(upstreamRes.headers)}`);
1164
+ if (errorBody) logSections.push(`=== ERROR BODY ===\n${errorBody}`);
1165
+ }
1166
+ // Only SUBSCRIPTION logins refuse this shape. API-key and provider rows can
1167
+ // still serve it — exclude every subscription-shaped account (local oauth rows
1168
+ // and their cloud mirrors) and fail over if such a route remains (red-team
1169
+ // 2026-11-08: answering outright starved a request GLM would have served).
1170
+ excludedIndexes.add(account.index);
1171
+ for (const a of accountManager.accounts) {
1172
+ if (a.type === 'oauth') excludedIndexes.add(a.index); // local logins AND their cloud mirrors
1173
+ }
1174
+ if (
1175
+ canRetryBufferedBody
1176
+ && retryCount + 1 < maxAttempts
1177
+ && !res.headersSent
1178
+ && hasEligibleRoute(accountManager, requestInfo, excludedIndexes)
1179
+ ) {
1180
+ if (logDir) writeRequestLog(logDir, reqId, logSections);
1181
+ return forwardRequest(
1182
+ req, res, body, accountManager, upstream, retryCount + 1, hooks, reqId, ctx, logDir,
1183
+ retryConfig, queueConfig, requestInfo, canRetryBufferedBody, canQueueBufferedBody, excludedIndexes,
1184
+ );
1185
+ }
1186
+ if (logDir) writeRequestLog(logDir, reqId, logSections);
1187
+ ctx.status = 429;
1188
+ sendErrorResponse(res, requestInfo, 429, {
1189
+ type: 'error',
1190
+ error: { type: 'rate_limit_error', message: REQUEST_SHAPE_REFUSAL_MESSAGE },
1191
+ }, { [REQUEST_SHAPE_REFUSAL_HEADER]: '1' });
1192
+ return;
1193
+ }
1194
+
1125
1195
  const rateLimit = classifyRateLimit(account, rateLimitHeaders, errorBody, { model: requestInfo.model, retryAfter });
1126
1196
  if (rateLimit.scope === 'upstream') {
1127
1197
  const parsedError = parseJsonError(errorBody);
@@ -2353,7 +2423,7 @@ function isContextLengthError(errorBody) {
2353
2423
  return /exceeded model token limit|maximum context length|context length exceeded|context window (?:size )?(?:exceeded|too)|prompt is too long|input is too long|reduce the length of|too many (?:input )?tokens|request too large/i.test(errorBody);
2354
2424
  }
2355
2425
 
2356
- export const __serverTest = { directiveOnlySystemMessages, rewriteBodyForAccount, sanitizeBlocksForProvider, reanchorOrphanedSystemMessages, unavailableMessage, computeQueueWindowMs, waitForAvailableRoute, isRetriableUpstreamStatus, classifyEffortRejection, repairEffort, isCapacitySignalStatus, isStrippableThinkingBlock, stripForeignThinkingBlocks, parseRejectedBlockPath, stripRejectedBlockClass, peekRejectedBlockType, describeRejectedBlock, headerValue, getMaxpoolProfile, ensureQueueHeartbeat, clearQueueHeartbeat, commitStreamGraceHeartbeat, describeRequest, classifyRateLimit, detectTranscriptOrigin, isAnthropicIncompatBody, isContextLengthError, isProviderParamRejection, describeBodyShape, streamResponse, startIdleRequestReaper, normalizeModelEcho, classifyHeldStreamPrefix };
2426
+ export const __serverTest = { directiveOnlySystemMessages, rewriteBodyForAccount, sanitizeBlocksForProvider, reanchorOrphanedSystemMessages, unavailableMessage, computeQueueWindowMs, waitForAvailableRoute, isRetriableUpstreamStatus, classifyEffortRejection, repairEffort, isCapacitySignalStatus, isStrippableThinkingBlock, stripForeignThinkingBlocks, parseRejectedBlockPath, stripRejectedBlockClass, peekRejectedBlockType, describeRejectedBlock, headerValue, getMaxpoolProfile, ensureQueueHeartbeat, clearQueueHeartbeat, commitStreamGraceHeartbeat, describeRequest, classifyRateLimit, isRequestShapeRefusal, looksLikeClaudeCode, parseProviderRetryAfter, secondsUntilParsedTime, detectTranscriptOrigin, isAnthropicIncompatBody, isContextLengthError, isProviderParamRejection, describeBodyShape, streamResponse, startIdleRequestReaper, normalizeModelEcho, classifyHeldStreamPrefix };
2357
2427
 
2358
2428
  async function readErrorBody(upstreamRes, limitBytes = 64 * 1024) {
2359
2429
  if (!upstreamRes.body) return '';
@@ -2384,9 +2454,13 @@ function parseProviderRetryAfter(body, provider) {
2384
2454
  const message = parsed?.message || '';
2385
2455
 
2386
2456
  if (provider === 'zai') {
2387
- const nextFlush = message.match(/reset at\s+`?([^`\n]+?)`?$/i)?.[1]
2388
- || message.match(/next_flush_time[:\s]+`?([^`\n]+?)`?$/i)?.[1];
2389
- const resetSeconds = secondsUntilParsedTime(nextFlush);
2457
+ // z.ai embeds the reset as "...will reset at 2026-11-12 04:28:53][<request-id>]"
2458
+ // (measured 2026-11-08, code 1310): the bracketed request id trails the time, so
2459
+ // an anchor to end-of-string never matches and the parsed time became garbage.
2460
+ // Capture the time inside ITS bracket and hand only that to the time parser.
2461
+ const resetMatch = message.match(/reset at\s+`?(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)`?/i)
2462
+ || message.match(/next_flush_time[:\s]+`?([^`\]\n]+?)`?(?:\]|$)/i);
2463
+ const resetSeconds = secondsUntilParsedTime(resetMatch?.[1], { tzOffsetMs: ZAI_TZ_OFFSET_MS });
2390
2464
  if (resetSeconds) return resetSeconds;
2391
2465
 
2392
2466
  if (['1302', '1303', '1305'].includes(String(code))) return 60;
@@ -2418,6 +2492,34 @@ function parseJsonError(body) {
2418
2492
  }
2419
2493
  }
2420
2494
 
2495
+ const REQUEST_SHAPE_REFUSAL_HEADER = 'x-maxpool-request-shape-refused';
2496
+ const REQUEST_SHAPE_REFUSAL_MESSAGE = 'Anthropic serves this model on subscription accounts only to Claude Code requests. '
2497
+ + 'This request does not identify as Claude Code (its system prompt lacks the Claude Code identity line), '
2498
+ + 'so every pooled account refuses it the same way. Send it from Claude Code, or use a Haiku model.';
2499
+ const CLAUDE_CODE_IDENTITY = /^You are (Claude Code, Anthropic's official CLI for Claude|a Claude agent, built on Anthropic's Claude Agent SDK)/;
2500
+
2501
+ /** True when the request carries Claude Code's identity line as a leading system
2502
+ * block. Parse failure → true (unknown shape is never treated as a refusal). */
2503
+ function looksLikeClaudeCode(requestBody) {
2504
+ let parsed;
2505
+ try { parsed = JSON.parse(Buffer.isBuffer(requestBody) ? requestBody.toString() : String(requestBody)); } catch { return true; }
2506
+ const sys = parsed?.system;
2507
+ const blocks = typeof sys === 'string' ? [sys] : Array.isArray(sys) ? sys.map(b => b?.text) : [];
2508
+ return blocks.slice(0, 3).some(t => typeof t === 'string' && CLAUDE_CODE_IDENTITY.test(t.trimStart()));
2509
+ }
2510
+
2511
+ /** A 429 that refuses the request's SHAPE, not the account's quota: NO unified quota
2512
+ * headers at all, Anthropic's bare `rate_limit_error` "Error" body, and a request
2513
+ * that does not identify as Claude Code. All three must hold — a headerless 429 on a
2514
+ * real Claude Code request keeps the account-wide handling (red-team: a genuine cap
2515
+ * with stripped headers must still bench). */
2516
+ function isRequestShapeRefusal(headers, errorBody, requestBody) {
2517
+ if (Object.keys(headers).some(k => k.toLowerCase().startsWith('anthropic-ratelimit-unified'))) return false;
2518
+ const parsed = parseJsonError(errorBody);
2519
+ if (String(parsed?.type || '') !== 'rate_limit_error' || String(parsed?.message || '').trim() !== 'Error') return false;
2520
+ return !looksLikeClaudeCode(requestBody);
2521
+ }
2522
+
2421
2523
  function classifyRateLimit(account, headers, body, opts = {}) {
2422
2524
  if (account.type === 'provider') return { scope: 'account', fingerprint: null };
2423
2525
 
@@ -2514,11 +2616,24 @@ function recordRequestIncident(requestInfo, fingerprint, accountIndex, retryAfte
2514
2616
  return incident;
2515
2617
  }
2516
2618
 
2517
- function secondsUntilParsedTime(value) {
2619
+ // z.ai prints its reset timestamps in China time (UTC+8) with no zone marker —
2620
+ // measured 2026-11-08: the 1310 message said 04:28:53 while the account's own
2621
+ // quota API reported the same window as 20:28:53Z. Parsing it as UTC made every
2622
+ // reset 8h too late and once even landed in the past. Anthropic's own header
2623
+ // times are ISO-with-zone and never carry a raw offset.
2624
+ const ZAI_TZ_OFFSET_MS = 8 * 60 * 60 * 1000;
2625
+
2626
+ function secondsUntilParsedTime(value, { tzOffsetMs = 0 } = {}) {
2518
2627
  if (!value) return null;
2519
2628
  const trimmed = String(value).trim();
2520
- const dateMs = Date.parse(trimmed);
2521
- if (!Number.isNaN(dateMs)) {
2629
+ const naive = trimmed.match(/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)$/);
2630
+ const asUtcMs = naive
2631
+ ? Date.parse(`${naive[1]}T${naive[2]}Z`)
2632
+ : Date.parse(trimmed);
2633
+ if (!Number.isNaN(asUtcMs)) {
2634
+ // The offset applies ONLY to a zone-less "YYYY-MM-DD HH:MM:SS"; a time that
2635
+ // names its zone is already absolute.
2636
+ const dateMs = naive ? asUtcMs - tzOffsetMs : asUtcMs;
2522
2637
  return Math.min(Math.max(Math.ceil((dateMs - Date.now()) / 1000), 1), 24 * 60 * 60);
2523
2638
  }
2524
2639
  const n = Number(trimmed);
package/src/tui.js CHANGED
@@ -2631,6 +2631,12 @@ export class TUI {
2631
2631
  sesCell = emptyBar('n/a', bw);
2632
2632
  wkCell = emptyBar('n/a', bw);
2633
2633
  note = ` ${dim('console-only')}`;
2634
+ } else if (q.noPlan) {
2635
+ // z.ai answered: this key's account has no coding plan (cancelled/expired).
2636
+ // Name it — "probing" here read as a pool fault for days (owner, 2026-11-08).
2637
+ sesCell = emptyBar('no plan', bw);
2638
+ wkCell = emptyBar('no plan', bw);
2639
+ note = ` ${red('z.ai says no coding plan — check billing')}`;
2634
2640
  } else {
2635
2641
  sesCell = emptyBar('probing', bw);
2636
2642
  wkCell = emptyBar('probing', bw);