maxpool 1.24.70 → 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.70",
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",
@@ -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,
@@ -328,7 +332,7 @@ const PERSISTED_QUOTA_FIELDS = [
328
332
  // drops until the next probe sweep re-learns it. The probe still rewrites it on
329
333
  // every successful sweep, so a plan change heals on the same cadence.
330
334
  'weeklyAbsent', 'capSpanSes', 'capSpanWk', 'providerSes', 'providerSesReset', 'providerWk', 'providerWkReset',
331
- 'providerQuotaSource', 'lastProbeOkAt',
335
+ 'providerQuotaSource', 'lastProbeOkAt', 'noPlan',
332
336
  ];
333
337
 
334
338
  const PROVIDER_429_MIN_BENCH_SEC = 60;
@@ -3798,7 +3802,20 @@ export class AccountManager {
3798
3802
  if (usage.source === 'console-only') q.providerQuotaSource = 'console-only';
3799
3803
  return;
3800
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
+ }
3801
3817
  q.providerQuotaSource = usage.source || 'zai';
3818
+ q.noPlan = false; // a real reading means the plan exists (renewed / re-bought)
3802
3819
  if (usage.ses) {
3803
3820
  if (usage.ses.utilization != null) q.providerSes = clamp01(usage.ses.utilization);
3804
3821
  if (usage.ses.resetAt != null) {
@@ -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/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
@@ -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
@@ -914,6 +918,28 @@ async function forwardRequest(
914
918
  upRes = await fetch(linkUrl, { method: req.method, headers: linkHeaders, body: ['GET', 'HEAD'].includes(req.method) ? undefined : body, duplex: 'half', signal: linkCtl.signal });
915
919
  } finally { clearTimeout(linkTtfb); }
916
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
+ }
917
943
  // Pinned cloud account refused (rate-limited / unavailable) before any byte
918
944
  // streamed: cool THIS mirror row and fail over through the normal path to the
919
945
  // next-best account, local or cloud — exactly like a local account's 429.
@@ -994,7 +1020,7 @@ async function forwardRequest(
994
1020
 
995
1021
  const upstreamUrl = `${account.upstream || upstream}${req.url}`;
996
1022
  const method = req.method;
997
- const upstreamBody = rewriteBodyForAccount(body, account);
1023
+ const upstreamBody = rewriteBodyForAccount(body, account, { identity: requestInfo.accountIdentity });
998
1024
 
999
1025
  // A threaded follow-up routed to an account that does not hold the thread cannot be
1000
1026
  // served by it: a different Anthropic account 404s, a provider rejects the truncated
@@ -1118,6 +1144,54 @@ async function forwardRequest(
1118
1144
  const errorBody = await readErrorBody(upstreamRes);
1119
1145
  const retryAfter = parseRetryAfter(upstreamRes.headers.get('retry-after'))
1120
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
+
1121
1195
  const rateLimit = classifyRateLimit(account, rateLimitHeaders, errorBody, { model: requestInfo.model, retryAfter });
1122
1196
  if (rateLimit.scope === 'upstream') {
1123
1197
  const parsedError = parseJsonError(errorBody);
@@ -2349,7 +2423,7 @@ function isContextLengthError(errorBody) {
2349
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);
2350
2424
  }
2351
2425
 
2352
- 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 };
2353
2427
 
2354
2428
  async function readErrorBody(upstreamRes, limitBytes = 64 * 1024) {
2355
2429
  if (!upstreamRes.body) return '';
@@ -2380,9 +2454,13 @@ function parseProviderRetryAfter(body, provider) {
2380
2454
  const message = parsed?.message || '';
2381
2455
 
2382
2456
  if (provider === 'zai') {
2383
- const nextFlush = message.match(/reset at\s+`?([^`\n]+?)`?$/i)?.[1]
2384
- || message.match(/next_flush_time[:\s]+`?([^`\n]+?)`?$/i)?.[1];
2385
- 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 });
2386
2464
  if (resetSeconds) return resetSeconds;
2387
2465
 
2388
2466
  if (['1302', '1303', '1305'].includes(String(code))) return 60;
@@ -2414,6 +2492,34 @@ function parseJsonError(body) {
2414
2492
  }
2415
2493
  }
2416
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
+
2417
2523
  function classifyRateLimit(account, headers, body, opts = {}) {
2418
2524
  if (account.type === 'provider') return { scope: 'account', fingerprint: null };
2419
2525
 
@@ -2510,11 +2616,24 @@ function recordRequestIncident(requestInfo, fingerprint, accountIndex, retryAfte
2510
2616
  return incident;
2511
2617
  }
2512
2618
 
2513
- 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 } = {}) {
2514
2627
  if (!value) return null;
2515
2628
  const trimmed = String(value).trim();
2516
- const dateMs = Date.parse(trimmed);
2517
- 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;
2518
2637
  return Math.min(Math.max(Math.ceil((dateMs - Date.now()) / 1000), 1), 24 * 60 * 60);
2519
2638
  }
2520
2639
  const n = Number(trimmed);
@@ -3657,8 +3776,18 @@ function describeBodyShape(buf) {
3657
3776
  const threadOwners = new ThreadOwners();
3658
3777
  const THREAD_GATE_ENABLED = process.env.MAXPOOL_THREAD_GATE !== '0';
3659
3778
 
3660
- function rewriteBodyForAccount(body, account) {
3779
+ function rewriteBodyForAccount(body, account, { identity = false } = {}) {
3661
3780
  const needsProviderSanitize = account.type === 'provider';
3781
+ // Identity first, on the RAW string: splicing only the metadata.user_id value keeps
3782
+ // every other byte identical (a parse→serialize round-trip corrupts >2^53 integers
3783
+ // in tool results — red-team M1, 2026-11-07).
3784
+ if (identity && body.length && body.includes('"metadata"')) {
3785
+ const rewritten = rewriteMetadataUserIdRaw(body.toString(), account);
3786
+ if (rewritten != null && (!account.model && !account.modelMap && !needsProviderSanitize)) {
3787
+ return Buffer.from(rewritten);
3788
+ }
3789
+ if (rewritten != null) body = Buffer.from(rewritten);
3790
+ }
3662
3791
  if (!body.length || (!account.model && !account.modelMap && !needsProviderSanitize)) return body;
3663
3792
 
3664
3793
  try {
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);