maxpool 1.24.66 → 1.24.68

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/src/index.js CHANGED
@@ -16,6 +16,7 @@ import { spawn, spawnSync } from 'node:child_process';
16
16
  import { createInterface } from 'node:readline';
17
17
  import { loadOrCreateConfig, loadConfig, saveConfig, atomicConfigUpdate, getConfigPath, loadState, saveState, getStatePath, getLogPath, readGeneration, flushConfigWrites, flushStateWrites, saveStateUnbumped } from './config.js';
18
18
  import { setEventLogPath, installConsoleMirror, setConsoleStdoutSuppressed, appendEventLog } from './event-log.js';
19
+ import { sendLoginToPool, planCliLogin, resolveUsablePools } from './cloud-login.js';
19
20
  import { SleepGuard } from './sleep-guard.js';
20
21
  import { AccountManager } from './account-manager.js';
21
22
  import { createProxyServer, REQUEST_IDLE_MAX_MS } from './server.js';
@@ -1745,7 +1746,65 @@ async function loginOAuthCommand() {
1745
1746
  process.exit(1);
1746
1747
  }
1747
1748
 
1748
- await upsertOAuthAccount(config, name, creds, 'login');
1749
+ // Cloud-aware: a linked team pool with a usable key may receive the login instead.
1750
+ // Profile FIRST (once): a local match must win over the cloud default.
1751
+ const profile = await fetchProfile(creds.accessToken);
1752
+ const localMatch = (profile?.accountUuid && config.accounts.find(a => a.type === 'oauth' && a.accountUuid === profile.accountUuid))
1753
+ || (profile?.email && config.accounts.find(a => a.type === 'oauth' && a.name === profile.email))
1754
+ || null;
1755
+ const { usable, unresolved, error } = await resolveUsablePools(config.pools, async (names) => {
1756
+ const { resolveSecrets } = await import('./secret-resolver.js');
1757
+ return resolveSecrets(names);
1758
+ });
1759
+ const flags = { local: args.includes('--local'), cloud: args.includes('--cloud'), pool: argValue('--pool') };
1760
+ const isTTY = !!(process.stdin.isTTY && process.stdout.isTTY);
1761
+ const ask = async (q) => {
1762
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
1763
+ const a = await new Promise(resolve => rl.question(q, resolve));
1764
+ rl.close();
1765
+ return a;
1766
+ };
1767
+ const input = { usable, unresolved, error, localMatch, flags, isTTY };
1768
+ let plan = planCliLogin(input);
1769
+ if (plan.action === 'ask-fallback') {
1770
+ console.error(plan.message);
1771
+ input.fallbackAnswer = await ask('Save on this laptop instead? [y/N]: ');
1772
+ plan = planCliLogin(input);
1773
+ }
1774
+ if (plan.action === 'ask-pool') {
1775
+ usable.forEach((p, i) => console.error(` ${i + 1}. ${p.name}`));
1776
+ input.poolAnswer = await ask(`Which team pool? [1-${usable.length}, default 1]: `);
1777
+ plan = planCliLogin(input);
1778
+ }
1779
+ if (plan.action === 'ask-target') {
1780
+ input.answer = await ask(`Add/update this account in the team pool "${plan.pool.name}" (recommended) or this laptop only? [T/l]: `);
1781
+ plan = planCliLogin(input);
1782
+ }
1783
+ if (plan.action === 'fail') {
1784
+ console.error(plan.message);
1785
+ process.exit(1);
1786
+ }
1787
+ if (plan.action === 'local') {
1788
+ await upsertOAuthAccount(config, name, creds, 'login', profile);
1789
+ return;
1790
+ }
1791
+
1792
+ const pool = plan.pool;
1793
+ if (!profile?.accountUuid) {
1794
+ // Without the uuid the server cannot match a re-authorization and would ADD a
1795
+ // duplicate row — the exact bug class v1.24.67 fixed on the server side. Abort.
1796
+ console.error(`Could not fetch the account profile (${profile?.error || 'no token'}) — the team pool needs the account id to add or re-authorize safely. NOTHING was saved on this laptop. Try again, or use --local.`);
1797
+ process.exit(1);
1798
+ }
1799
+ if (!name) name = profile?.email || `account-${Date.now().toString(36)}`;
1800
+ console.log(`Sending "${name}" to the team pool "${pool.name}"...`);
1801
+ const r = await sendLoginToPool({ url: pool.url, key: pool.key, name, profile, creds });
1802
+ if (r.ok) {
1803
+ console.log(`Done: "${r.name || name}" ${r.result === 'added' ? 'added to' : 're-authenticated in'} the team pool "${pool.name}". Nothing was saved on this laptop.`);
1804
+ return;
1805
+ }
1806
+ console.error(`${r.error}. NOTHING was saved on this laptop — not retried locally. Try again, or use --local to save here only.`);
1807
+ process.exit(1);
1749
1808
  }
1750
1809
 
1751
1810
  // ── env ─────────────────────────────────────────────────────
@@ -2189,6 +2248,7 @@ Commands:
2189
2248
  server Start the proxy server (default)
2190
2249
  login OAuth login via browser (adds the account you're signed into at claude.ai)
2191
2250
  login --api Add an API key account
2251
+ login --cloud|--local [--pool <name>] Send the login to the linked team pool (default when one is configured) or keep it on this laptop
2192
2252
  env [--with-key] Print env vars to use with Claude
2193
2253
  pool shared <host> <key> Point this machine at a shared team pool
2194
2254
  pool local Point this machine back at its own local pool
@@ -2217,9 +2277,9 @@ Config: ${getConfigPath()}
2217
2277
 
2218
2278
  // ── shared account upsert ────────────────────────────────────
2219
2279
 
2220
- async function upsertOAuthAccount(config, name, creds, source = 'unknown') {
2221
- // Fetch profile to auto-name and deduplicate by account UUID
2222
- const profile = await fetchProfile(creds.accessToken);
2280
+ async function upsertOAuthAccount(config, name, creds, source = 'unknown', prefetchedProfile = null) {
2281
+ // Fetch profile to auto-name and deduplicate by account UUID (reuse one already fetched)
2282
+ const profile = prefetchedProfile || await fetchProfile(creds.accessToken);
2223
2283
  const profileOk = profile && !profile.error;
2224
2284
 
2225
2285
  if (!profileOk) {
package/src/pool-link.js CHANGED
@@ -44,6 +44,14 @@ export function accountIdentity(account) {
44
44
  return null;
45
45
  }
46
46
 
47
+ /** Identity of a REMOTE status row (same key shape as accountIdentity). */
48
+ export function remoteAccountIdentity(a) {
49
+ if (!a) return null;
50
+ if (a.type === 'oauth') return a.accountUuid ? `uuid:${a.accountUuid}` : null;
51
+ if (a.type === 'provider' && a.provider && a.keyFingerprint) return `key:${a.provider}:${a.keyFingerprint}`;
52
+ return null;
53
+ }
54
+
47
55
  /** Identity map from a REMOTE pool's status JSON (key-gated /maxpool/status):
48
56
  * { accounts: [{name,type,provider,accountUuid,enabled,...}], callers, ... }.
49
57
  * Provider rows don't carry credentials — the remote pool exports a
package/src/server.js CHANGED
@@ -358,8 +358,11 @@ export function createProxyServer(accountManager, config, hooks = {}) {
358
358
  });
359
359
  // Keep the in-memory config mirror in step so a later TUI saveConfig
360
360
  // can't clobber the fresh tokens with stale ones.
361
+ // A NEW row must enter the mirror too: the disk sync adds any disk row whose
362
+ // uuid the mirror lacks, so a missing entry became a second live row.
361
363
  const mem = (config.accounts || []).find(a => a.accountUuid === acct.accountUuid);
362
364
  if (mem) Object.assign(mem, tokenFields);
365
+ else if (Array.isArray(config.accounts)) config.accounts.push({ name: acct.name || acct.accountUuid.slice(0, 8), type: 'oauth', accountUuid: acct.accountUuid, enabled: true, ...tokenFields });
363
366
  } catch (err) {
364
367
  // A single-use credential write is only "ok" when it is DURABLE: the browser
365
368
  // login may have invalidated the previous refresh token, so memory-only means
@@ -672,6 +675,7 @@ async function forwardRequest(
672
675
  || accountManager.isSessionThinkingContaminated?.(requestInfo.sessionKey))) {
673
676
  const pre = stripForeignThinkingBlocks(body);
674
677
  if (pre.body) {
678
+ if (pre.converted) console.log(`[Maxpool] Up-front repair: stripped ${pre.removed} provider thinking block(s), converted ${pre.converted} provider tool block(s) before routing [sess ${requestInfo.sessionKey || '?'}]`);
675
679
  body = pre.body;
676
680
  requestInfo = { ...requestInfo, thinkingStripped: true };
677
681
  if (pre.converted) {
@@ -1686,7 +1690,38 @@ async function forwardRequest(
1686
1690
  // is buffered, so latch the session Anthropic-incompatible (sticky → once per
1687
1691
  // session) and retry PROVIDER-only, rather than surfacing the 400. Only worth
1688
1692
  // it when a provider can actually serve it (profile=all with a GLM/Kimi token).
1693
+ //
1694
+ // REPAIR FIRST (2026-11-06, "customer fups"): the broad strip + coordinate repair
1695
+ // above may both have found nothing while the transcript is still curable — the
1696
+ // measured case is a GLM-authored `mcp_tool_use`/`mcp_tool_result` pair, which
1697
+ // both repairs predate. Try the conversion once here; if it changes the body,
1698
+ // retry THAT on Claude instead of pinning. Pin only when the conversion finds
1699
+ // nothing (a genuinely unrepairable transcript). This kills the pin loop: pin →
1700
+ // provider exhausts → "can only run on GLM" with ~59h Retry — while a text-
1701
+ // converted body replays 200 (verified live, count_tokens, 2026-11-06).
1689
1702
  const providerAvailable = accountManager.accounts?.some(a => a.type === 'provider' && a.enabled !== false);
1703
+ // Exact-shape gate (red-team M2): the loose isAnthropicIncompatBody matcher also
1704
+ // fires on unrelated unknown-tag 400s (its expected-tags list mentions
1705
+ // server_tool_use); a rewrite must key on the two MCP wordings or the
1706
+ // deterministic server-tool-id wording, never the fuzzy predicate.
1707
+ const incompatRepairable = /server_tool_use\.id: String should match pattern/i.test(errorBody)
1708
+ || /mcp_tool_(use|result)/.test(errorBody)
1709
+ && /(does not match any of the expected tags|without a corresponding)/i.test(errorBody);
1710
+ if (anthropicIncompat && incompatRepairable && !requestInfo.incompatRepairTried && canRepairBody) {
1711
+ const repaired = stripForeignThinkingBlocks(body);
1712
+ if (repaired.body) {
1713
+ // Latch the pre-strip sticky so the NEXT turn repairs up front instead of
1714
+ // re-paying this rejected round-trip every turn (the client resends the whole
1715
+ // poisoned history each turn — same cache-churn the audit is about).
1716
+ accountManager.markSessionThinkingContaminated?.(requestInfo.sessionKey);
1717
+ console.log(`[Maxpool] Recovering session on Claude: incompatibility repair removed ${repaired.removed} thinking block(s), converted ${repaired.converted} provider tool block(s) — retrying on Claude before pinning`);
1718
+ return forwardRequest(
1719
+ req, res, repaired.body, accountManager, upstream, retryCount + 1, hooks, reqId, ctx, logDir,
1720
+ retryConfig, queueConfig, { ...requestInfo, incompatRepairTried: true, anthropicIncompatible: false, repairCount: repairCount + 1 },
1721
+ repaired.body.length <= retryConfig.maxRetryBufferBytes, canQueueBufferedBody, excludedIndexes,
1722
+ );
1723
+ }
1724
+ }
1690
1725
  if (anthropicIncompat && requestInfo.sessionKey && providerAvailable
1691
1726
  && canRetryBufferedBody && retryCount + 1 < maxAttempts && !clientHasRealBytes(res, requestInfo)) {
1692
1727
  accountManager.markSessionIncompatible?.(requestInfo.sessionKey, requestInfo.homeProvider);
@@ -1844,6 +1879,9 @@ async function forwardRequest(
1844
1879
  accountManager.accrueCapacity?.(account.index, {
1845
1880
  input: requestInfo._capacityInput || 0,
1846
1881
  output: requestInfo._capacityOutput || 0,
1882
+ cacheRead: requestInfo._capacityCacheRead || 0,
1883
+ cacheCreation: requestInfo._capacityCacheCreation || 0,
1884
+ model: requestInfo.model,
1847
1885
  });
1848
1886
  }
1849
1887
  accountManager.releaseAccount(lease, { success: true, status: upstreamRes.status });
@@ -2753,7 +2791,12 @@ function repairEffort(body, mode, errorBody = '') {
2753
2791
 
2754
2792
  /** Collect foreign server-tool ids across the WHOLE transcript first — a call sits on the
2755
2793
  * assistant turn but its result is often carried on the FOLLOWING user turn, so a
2756
- * per-message scan would leave that result behind (and it alone still 400s). */
2794
+ * per-message scan would leave that result behind (and it alone still 400s).
2795
+ * `mcp_tool_use` is collected the same way: GLM emits provider-authored MCP calls
2796
+ * (webReader etc. with `call_…` ids), and Anthropic rejects them BOTH ways — the plain
2797
+ * Messages API lists no `mcp_tool_use` tag at all, and the mcp beta rejects the pair
2798
+ * because the provider puts the `mcp_tool_result` on the assistant turn (measured live
2799
+ * 2026-11-06, "customer fups" session). Conversion to text is accepted either way. */
2757
2800
  function collectForeignServerToolIds(messages) {
2758
2801
  const ids = new Set();
2759
2802
  const clientIds = new Set();
@@ -2761,7 +2804,8 @@ function collectForeignServerToolIds(messages) {
2761
2804
  if (!Array.isArray(blocks)) return;
2762
2805
  for (const b of blocks) {
2763
2806
  if (b?.type === 'tool_use' && b.id) clientIds.add(b.id);
2764
- if (b?.type === 'server_tool_use' && !ANTHROPIC_TOOL_ID.test(String(b.id || ''))) ids.add(b.id);
2807
+ if ((b?.type === 'server_tool_use' || b?.type === 'mcp_tool_use')
2808
+ && !ANTHROPIC_TOOL_ID.test(String(b.id || ''))) ids.add(b.id);
2765
2809
  if (Array.isArray(b?.content)) walk(b.content); // nested, mirrors detectTranscriptOrigin
2766
2810
  }
2767
2811
  };
@@ -2786,17 +2830,34 @@ function convertForeignServerTools(content, foreignIds) {
2786
2830
  converted++;
2787
2831
  continue;
2788
2832
  }
2789
- // Any result block referring to a foreign call — web_search_tool_result and friends.
2833
+ if (b?.type === 'mcp_tool_use' && foreignIds.has(b.id)) {
2834
+ const inp = JSON.stringify(b.input ?? {});
2835
+ // Truncate by CODE POINTS: a raw .slice can split a surrogate pair (an emoji at
2836
+ // char 299), and a lone surrogate makes the body invalid JSON-UTF8 Anthropic 400s
2837
+ // with no repair path — killing the session the conversion is saving (red-team M1).
2838
+ out.push({ type: 'text', text: `[called ${b.name || 'a tool'}${b.server_name ? ` (${b.server_name})` : ''} on ${Array.from(inp).slice(0, 300).join('')}]` });
2839
+ converted++;
2840
+ continue;
2841
+ }
2842
+ // Any result block referring to a foreign call — web_search_tool_result, mcp_tool_result and friends.
2790
2843
  if (b?.tool_use_id && foreignIds.has(b.tool_use_id)) {
2791
2844
  const rows = Array.isArray(b.content) ? b.content : [];
2792
2845
  // Fall back through the shapes a PROVIDER may use — the point of converting rather
2793
2846
  // than dropping is to keep what the search found; assuming Anthropic's {title,url}
2794
2847
  // would silently discard a GLM row that carries text instead.
2848
+ if (typeof b.content === 'string' && b.content) rows.push(b.content); // a plain-string result (e.g. an error row) — keep it (red-team M6)
2795
2849
  const found = rows
2796
2850
  .map(r => [r?.title, r?.url].filter(Boolean).join(' — ')
2797
2851
  || (typeof r === 'string' ? r : (r?.text ?? r?.content ?? r?.snippet ?? '')))
2798
- .map(t => (typeof t === 'string' ? t.slice(0, 300) : ''))
2852
+ .map(t => (typeof t === 'string' ? Array.from(t).slice(0, 300).join('') : ''))
2799
2853
  .filter(Boolean).slice(0, 10);
2854
+ if (b?.type === 'mcp_tool_result') {
2855
+ // An MCP result carries {type:'text'} rows, not {title,url} — label it as the
2856
+ // tool's answer rather than "[search results]" so the transcript stays honest.
2857
+ out.push({ type: 'text', text: found.length ? `[${b.name || 'mcp tool'} result: ${found.join(' | ')}]` : '[mcp tool returned no usable results]' });
2858
+ converted++;
2859
+ continue;
2860
+ }
2800
2861
  out.push({ type: 'text', text: found.length ? `[search results: ${found.join(' | ')}]` : '[search returned no usable results]' });
2801
2862
  converted++;
2802
2863
  continue;
@@ -3329,8 +3390,12 @@ const ANTHROPIC_TOOL_ID = /^(toolu|srvtoolu)_/;
3329
3390
  // from the tool-use id shapes in its `messages`. Returns { anthropicIncompatible,
3330
3391
  // homeProvider }.
3331
3392
  // anthropicIncompatible = the transcript has a `server_tool_use` id NOT matching
3332
- // ^srvtoolu_ — the ONE DETERMINISTIC incompatibility (Anthropic 400s on replay,
3333
- // the reported bug). Anthropic validates a client `tool_use.id` LOOSELY
3393
+ // ^srvtoolu_, OR a foreign `mcp_tool_use` id (2026-11-06: GLM emits provider-authored
3394
+ // MCP calls with `call_…` ids; Anthropic rejects the block type on the plain API and
3395
+ // the mis-roled result pair under the mcp beta — both measured live). Either means
3396
+ // Anthropic 400s on replay, but BOTH are repairable by the pre-strip conversion, so
3397
+ // a `true` here routes into the up-front repair rather than a permanent exile.
3398
+ // Anthropic validates a client `tool_use.id` LOOSELY
3334
3399
  // (^[a-zA-Z0-9_-]+$), so GLM `call_…` / Kimi `tool_…` client ids PASS and a
3335
3400
  // Kimi/GLM session without server-tools is FINE on Claude — we do NOT predict
3336
3401
  // those (a rejected thinking signature, if it ever happens, self-heals via the
@@ -3350,7 +3415,12 @@ function detectTranscriptOrigin(json) {
3350
3415
  if (Array.isArray(value)) { for (const v of value) { visit(v); if (incompatible) return; } return; }
3351
3416
  if (!value || typeof value !== 'object') return;
3352
3417
  const t = value.type;
3353
- if (t === 'server_tool_use' && typeof value.id === 'string' && !ANTHROPIC_TOOL_ID.test(value.id)) {
3418
+ // Incompatible only when the CONVERTER can also cure it (red-team M4): flagging a
3419
+ // nested or id-colliding block the converter skips would exile the session to GLM
3420
+ // before Claude is ever tried — the incident's dead-session outcome. The id set is
3421
+ // computed by the converter's own collector (nested-walking, collision-guarded).
3422
+ const convertibleIds = collectForeignServerToolIds(json?.messages || []);
3423
+ if ((t === 'server_tool_use' || t === 'mcp_tool_use') && typeof value.id === 'string' && convertibleIds.has(value.id)) {
3354
3424
  incompatible = true; noteForeign(value.id); return;
3355
3425
  }
3356
3426
  if (t === 'tool_use' && typeof value.id === 'string' && !ANTHROPIC_TOOL_ID.test(value.id)) noteForeign(value.id);
@@ -3369,13 +3439,19 @@ function detectTranscriptOrigin(json) {
3369
3439
  // self-heal onto a provider instead of surfacing the 400.
3370
3440
  function isAnthropicIncompatBody(body) {
3371
3441
  if (!body) return false;
3372
- // The deterministic server-tool-id 400, the known invalid-signature error, or a
3442
+ // The deterministic server-tool-id 400, the known invalid-signature error, a
3373
3443
  // thinking-block signature VALIDATION error (missing/invalid) — the last gated on
3374
3444
  // a validation verb so a user message merely echoing "thinking"/"signature" can't
3375
- // false-latch the session provider-pinned for life.
3445
+ // false-latch the session provider-pinned for life — and the two MCP shapes
3446
+ // (2026-11-06, verbatim, measured live): the plain API's unknown-tag rejection and
3447
+ // the mcp beta's mis-roled-pair rejection. NB the plain-API text lists
3448
+ // 'server_tool_use' among its expected tags, which USED to be the only reason an
3449
+ // mcp-only transcript tripped this predicate — an accident of wording, now pinned.
3376
3450
  return /srvtoolu_|server_tool_use/.test(body)
3377
3451
  || /invalid `signature` in `thinking`/i.test(body)
3378
- || (/thinking/.test(body) && /signature/.test(body) && /(should match|required|invalid|expected|must )/i.test(body));
3452
+ || (/thinking/.test(body) && /signature/.test(body) && /(should match|required|invalid|expected|must )/i.test(body))
3453
+ || (/mcp_tool_(use|result)/.test(body)
3454
+ && /(does not match any of the expected tags|without a corresponding)/i.test(body));
3379
3455
  }
3380
3456
 
3381
3457
  function containsThinkingBlock(value) {
@@ -3989,6 +4065,14 @@ async function streamResponse(webStream, res, status, responseHeaders, accountIn
3989
4065
  }
3990
4066
  }
3991
4067
 
4068
+ /** Running-max the cache counters of one usage object into the request's capacity book.
4069
+ * Capacity tokens = input + cache_read + cache_creation + output (every token the
4070
+ * provider processed), the same definition for Anthropic and z.ai. */
4071
+ function noteCapacityCache(requestInfo, usage) {
4072
+ requestInfo._capacityCacheRead = Math.max(requestInfo._capacityCacheRead || 0, usage?.cache_read_input_tokens || 0);
4073
+ requestInfo._capacityCacheCreation = Math.max(requestInfo._capacityCacheCreation || 0, usage?.cache_creation_input_tokens || 0);
4074
+ }
4075
+
3992
4076
  function parseSSEEvent(event, accountIndex, accountManager, requestInfo = {}) {
3993
4077
  const dataLine = event.split('\n').find(l => l.startsWith('data: '));
3994
4078
  if (!dataLine) return;
@@ -4004,10 +4088,17 @@ function parseSSEEvent(event, accountIndex, accountManager, requestInfo = {}) {
4004
4088
  accountManager.updateUsage(accountIndex, data.message.usage.input_tokens, 0);
4005
4089
  accountManager.countCallerTokens?.(requestInfo.caller, data.message.usage.input_tokens);
4006
4090
  requestInfo._capacityInput = Math.max(requestInfo._capacityInput || 0, data.message.usage.input_tokens || 0);
4091
+ noteCapacityCache(requestInfo, data.message.usage);
4007
4092
  } else if (data.type === 'message_delta' && data.usage) {
4008
4093
  accountManager.updateUsage(accountIndex, 0, data.usage.output_tokens);
4009
4094
  accountManager.countCallerTokens?.(requestInfo.caller, data.usage.output_tokens);
4010
4095
  requestInfo._capacityOutput = Math.max(requestInfo._capacityOutput || 0, data.usage.output_tokens || 0);
4096
+ // Providers differ in WHICH event carries the cache/input counters (z.ai: all of
4097
+ // them on message_delta, message_start is zeros — captured 2026-11-06, pinned by
4098
+ // test/capacity-seam.test.js + test/fixtures/zai-sse-usage.txt), so every field is
4099
+ // a running max over BOTH events.
4100
+ requestInfo._capacityInput = Math.max(requestInfo._capacityInput || 0, data.usage.input_tokens || 0);
4101
+ noteCapacityCache(requestInfo, data.usage);
4011
4102
  }
4012
4103
  }
4013
4104
  if (sseEventContainsThinking(data)) {
@@ -4068,6 +4159,9 @@ function extractUsageFromBody(buffer, accountIndex, accountManager, requestInfo
4068
4159
  accountManager.accrueCapacity?.(accountIndex, {
4069
4160
  input: json.usage.input_tokens || 0,
4070
4161
  output: json.usage.output_tokens || 0,
4162
+ cacheRead: json.usage.cache_read_input_tokens || 0,
4163
+ cacheCreation: json.usage.cache_creation_input_tokens || 0,
4164
+ model: requestInfo.model,
4071
4165
  });
4072
4166
  }
4073
4167
  }
package/src/tui.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  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
+ import { sendLoginToPool } from './cloud-login.js';
6
7
 
7
8
  // ── ANSI helpers ─────────────────────────────────────────────
8
9
 
@@ -454,6 +455,28 @@ function timestamp() {
454
455
 
455
456
  // ── TUI class ────────────────────────────────────────────────
456
457
 
458
+ /** Compact plan cell: "Max Q $134/mo". '--' when no plan is configured (no guessing). */
459
+ function planLabel(plan) {
460
+ if (!plan) return '--';
461
+ const cad = { monthly: 'M', quarterly: 'Q', annual: 'A', annually: 'A', yearly: 'A' }[plan.cadence] || '';
462
+ const tier = (plan.tier || '').replace(/^(claude|glm coding)\s+/i, '');
463
+ const monthly = plan.priceUsd != null && plan.billingMonths ? plan.priceUsd / plan.billingMonths : null;
464
+ return [tier, cad, monthly != null ? `$${Math.round(monthly)}/mo` : ''].filter(Boolean).join(' ') || '--';
465
+ }
466
+
467
+ /** Where a finished browser login goes. mirror → that team pool; a brand-new
468
+ * account (no mirror, not already local) with a keyed linked pool → ask (first
469
+ * keyed link); else local. */
470
+ export function decideLoginTarget({ mirror, links, existing, accountUuid }) {
471
+ if (mirror) return { kind: 'mirror', mirror };
472
+ if (existing) return { kind: 'local' };
473
+ const link = (Array.isArray(links) ? links : []).find(l => l && l.url && l.key);
474
+ if (!link) return { kind: 'local' };
475
+ // The team pool dedupes by account id; without it a re-login would ADD a duplicate.
476
+ if (!accountUuid) return { kind: 'no-uuid' };
477
+ return { kind: 'ask-team', link };
478
+ }
479
+
457
480
  export class TUI {
458
481
  constructor({ accountManager, config, saveConfig, syncAccounts, onQuit, onRestart }) {
459
482
  this.am = accountManager;
@@ -1452,35 +1475,7 @@ export class TUI {
1452
1475
  // there — never persisted locally (single writer: one account, one home).
1453
1476
  // Same keystroke as a local re-auth; the routing is by where the account
1454
1477
  // lives, so nothing is selected and no menu appears.
1455
- const mirror = this._findRemoteMirrorFor(profile);
1456
- if (mirror) {
1457
- setConsoleStdoutSuppressed(false);
1458
- await this._sendLoginToRemote(mirror, creds, profile);
1459
- return;
1460
- }
1461
- const existing = this._findExistingOAuthAccount(profile);
1462
- let name;
1463
- if (existing) {
1464
- process.stdout.write(`\nThis Claude account is already added as "${existing.name}" — re-authenticating it in place (no duplicate).\n`);
1465
- name = existing.name;
1466
- } else {
1467
- const suggested = profile?.email
1468
- || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1469
- const rl = createInterface({ input: process.stdin, output: process.stdout });
1470
- const answer = await new Promise(resolve => rl.question(`Name this NEW account [${suggested}]: `, resolve));
1471
- rl.close();
1472
- name = String(answer || '').trim() || suggested;
1473
- }
1474
- // Lift the mute BEFORE the upsert so its persist-confirmation (a console.log,
1475
- // deliberately visible during the stopped-TUI login) reaches the user.
1476
- setConsoleStdoutSuppressed(false);
1477
- // Message honors the ACTUAL result: if a manually-typed name collided with a
1478
- // different existing account, upsert updates in place → "Re-authenticated", never
1479
- // a false "Added new account".
1480
- const { updated } = await this._upsertOAuthAccount({ creds, profile, name, source: 'login' });
1481
- process.stdout.write(updated
1482
- ? `\nRe-authenticated "${name}". Returning to maxpool…\n`
1483
- : `\nAdded new account "${name}". Returning to maxpool…\n`);
1478
+ await this._routeLogin(creds, profile);
1484
1479
  } catch (e) {
1485
1480
  if (isLoginCancelled(e)) {
1486
1481
  process.stdout.write('\nLogin cancelled.\n');
@@ -1493,6 +1488,69 @@ export class TUI {
1493
1488
  }
1494
1489
  }
1495
1490
 
1491
+ // Where a finished browser login goes. Pure decision (see decideLoginTarget):
1492
+ // a mirror match → that team pool; a brand-new account with a linked team pool →
1493
+ // ask once (default team pool); otherwise the local save path.
1494
+ async _routeLogin(creds, profile) {
1495
+ const decision = decideLoginTarget({
1496
+ mirror: this._findRemoteMirrorFor(profile),
1497
+ links: this.am.poolLinks,
1498
+ existing: this._findExistingOAuthAccount(profile),
1499
+ accountUuid: profile?.accountUuid,
1500
+ });
1501
+ if (decision.kind === 'no-uuid') {
1502
+ setConsoleStdoutSuppressed(false);
1503
+ process.stdout.write("\nCould not read this account's id — the team pool needs it. Nothing was saved; try again.\n");
1504
+ return;
1505
+ }
1506
+ if (decision.kind === 'mirror') {
1507
+ setConsoleStdoutSuppressed(false);
1508
+ await this._sendLoginToRemote(decision.mirror, creds, profile);
1509
+ return;
1510
+ }
1511
+ const existing = this._findExistingOAuthAccount(profile);
1512
+ let name;
1513
+ if (existing) {
1514
+ process.stdout.write(`\nThis Claude account is already added as "${existing.name}" — re-authenticating it in place (no duplicate).\n`);
1515
+ name = existing.name;
1516
+ } else {
1517
+ const suggested = profile?.email
1518
+ || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1519
+ let toTeam = false;
1520
+ if (decision.kind === 'ask-team') {
1521
+ const where = String(await this._ask(`\nThis is a new account. Add it to the team pool "${decision.link.name}" (recommended) or this laptop only? [T/l]: `) || '').trim().toLowerCase();
1522
+ toTeam = where !== 'l';
1523
+ }
1524
+ const answer = await this._ask(`Name this NEW account [${suggested}]: `);
1525
+ name = String(answer || '').trim() || suggested;
1526
+ if (toTeam) {
1527
+ setConsoleStdoutSuppressed(false);
1528
+ await this._sendLoginToTarget(
1529
+ { url: decision.link.url, key: decision.link.key, linkName: decision.link.name },
1530
+ name, creds, profile, { newAccount: true });
1531
+ return;
1532
+ }
1533
+ }
1534
+ // Lift the mute BEFORE the upsert so its persist-confirmation (a console.log,
1535
+ // deliberately visible during the stopped-TUI login) reaches the user.
1536
+ setConsoleStdoutSuppressed(false);
1537
+ // Message honors the ACTUAL result: if a manually-typed name collided with a
1538
+ // different existing account, upsert updates in place → "Re-authenticated", never
1539
+ // a false "Added new account".
1540
+ const { updated } = await this._upsertOAuthAccount({ creds, profile, name, source: 'login' });
1541
+ process.stdout.write(updated
1542
+ ? `\nRe-authenticated "${name}". Returning to maxpool…\n`
1543
+ : `\nAdded new account "${name}". Returning to maxpool…\n`);
1544
+ }
1545
+
1546
+ // One readline question → answer string.
1547
+ async _ask(question) {
1548
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1549
+ const answer = await new Promise(resolve => rl.question(question, resolve));
1550
+ rl.close();
1551
+ return answer;
1552
+ }
1553
+
1496
1554
  // The browser login belongs to a linked team pool iff a mirror row carries the
1497
1555
  // same account uuid (M2: mirrors hold remoteUuid, never accountUuid, so a
1498
1556
  // uuid-first matcher cannot alias onto a local account).
@@ -1507,36 +1565,23 @@ export class TUI {
1507
1565
  async _sendLoginToRemote(mirror, creds, profile) {
1508
1566
  const remote = mirror.remote;
1509
1567
  const name = remote.remoteName || mirror.name;
1510
- process.stdout.write(`\n"${name}" lives in the team pool (${remote.linkName}) — sending the fresh login there…\n`);
1511
- const ctl = new AbortController();
1512
- const t = setTimeout(() => ctl.abort(), 20_000);
1513
- try {
1514
- const res = await fetch(`${String(remote.url).replace(/\/+$/, '')}/maxpool/accounts`, {
1515
- method: 'POST',
1516
- headers: { 'Content-Type': 'application/json', 'x-api-key': remote.key || '' },
1517
- body: JSON.stringify({
1518
- account: {
1519
- name, type: 'oauth',
1520
- accountUuid: profile?.accountUuid,
1521
- accessToken: creds.accessToken,
1522
- refreshToken: creds.refreshToken,
1523
- expiresAt: creds.expiresAt,
1524
- source: 'remote-login',
1525
- },
1526
- }),
1527
- signal: ctl.signal,
1528
- });
1529
- const json = await res.json().catch(() => ({}));
1530
- if (res.ok && json.ok) {
1531
- process.stdout.write(`\nDone: "${name}" ${json.result === 'added' ? 'added to' : 're-authenticated in'} the team pool. Nothing was saved on this laptop.\n`);
1532
- this._addLog(`Remote login: "${name}" → team pool ${remote.linkName} (${json.result})`);
1533
- } else {
1534
- process.stdout.write(`\nTeam pool rejected the login (HTTP ${res.status}: ${json?.message || json?.error || 'unknown error'}). NOTHING was saved on this laptop — not retried locally.\n`);
1535
- }
1536
- } catch (e) {
1537
- process.stdout.write(`\nCould not reach the team pool (${e?.name === 'AbortError' ? 'timed out' : e?.message}). NOTHING was saved on this laptop — try again in a moment.\n`);
1538
- } finally {
1539
- clearTimeout(t);
1568
+ return this._sendLoginToTarget(remote, name, creds, profile, { newAccount: false });
1569
+ }
1570
+
1571
+ // Shared sender. target = {url, key, linkName}. Same single-writer rule for a
1572
+ // NEW account: a failure never falls back to a local save.
1573
+ async _sendLoginToTarget(remote, name, creds, profile, { newAccount }) {
1574
+ process.stdout.write(newAccount
1575
+ ? `\nSending new account "${name}" to the team pool (${remote.linkName})…\n`
1576
+ : `\n"${name}" lives in the team pool (${remote.linkName}) — sending the fresh login there…\n`);
1577
+ const r = await sendLoginToPool({ url: remote.url, key: remote.key, name, profile, creds });
1578
+ if (r.ok) {
1579
+ process.stdout.write(`\nDone: "${name}" ${r.result === 'added' ? 'added to' : 're-authenticated in'} the team pool${newAccount ? ` (${remote.linkName})` : ''}. Nothing was saved on this laptop.\n`);
1580
+ this._addLog(`Remote login: "${name}" → team pool ${remote.linkName} (${r.result})`);
1581
+ } else if (r.kind === 'unreachable') {
1582
+ process.stdout.write(`\n${r.error}. NOTHING was saved on this laptop — try again in a moment.\n`);
1583
+ } else {
1584
+ process.stdout.write(`\n${r.error}. NOTHING was saved on this laptop — not retried locally.\n`);
1540
1585
  }
1541
1586
  }
1542
1587
 
@@ -2707,27 +2752,44 @@ export class TUI {
2707
2752
  if (!ledger) { out.push(yellow(' Capacity ledger unavailable on this worker.')); return out; }
2708
2753
 
2709
2754
  // Owner-specified table (2026-08-26): the same shape for BOTH views —
2710
- // Current cycle (tokens + % used) · Prev cycle · Avg across all cycles · N cycles.
2755
+ // Current cycle (tokens + % used) · Prev cycle · Med (median) across all cycles · N cycles.
2711
2756
  // Current is the live window (estimate while it runs; frozen into the columns at
2712
2757
  // close). Prev/Avg/N are the completed-cycle history. The no-weekly account's
2713
2758
  // weekly view approximates capacity as avg session tank × 33.6 (7×24/5h windows).
2714
- const ALL_COLS = ['Current', 'Prev', 'Avg', 'N', '$/1M'];
2759
+ // Plan/Where are the leftmost extras and drop first when the terminal is narrow
2760
+ // (the numeric columns are the point of the page). Where = which pool's ledger holds
2761
+ // this account's cycles (cloud / laptop / both) — ONE row per account identity.
2762
+ const ALL_COLS = ['Current', 'Prev', 'Med-3', 'Med-all', 'N', '$/1M'];
2763
+ // Narrow terminals drop from the right, but Med-3 goes before Med-all.
2764
+ const DROP_ORDER = ['$/1M', 'N', 'Med-3', 'Med-all', 'Prev', 'Current'];
2715
2765
  const CW = 11;
2716
2766
  const nameW = 12;
2767
+ const WHERE_W = 7, PLAN_W = 16;
2717
2768
  let COLS = ALL_COLS;
2718
2769
  while (COLS.length > 1 && (nameW + PROVIDER_W + 2 + COLS.length * CW + 22) > W) {
2719
- COLS = COLS.slice(0, -1);
2770
+ const drop = DROP_ORDER.find(c => COLS.includes(c));
2771
+ COLS = COLS.filter(c => c !== drop);
2720
2772
  }
2773
+ const showWhere = (nameW + PROVIDER_W + 2 + COLS.length * CW + WHERE_W + 1 + 22) <= W;
2774
+ const showPlan = showWhere && (nameW + PROVIDER_W + 2 + COLS.length * CW + WHERE_W + PLAN_W + 2 + 22) <= W;
2721
2775
  const header = ' ' + 'Account'.padEnd(nameW) + ' ' + 'Provider'.padEnd(PROVIDER_W) + ' '
2776
+ + (showWhere ? 'Where'.padEnd(WHERE_W) : '')
2777
+ + (showPlan ? 'Plan'.padEnd(PLAN_W) + ' ' : '')
2722
2778
  + COLS.map(c => c.padStart(CW)).join('');
2723
2779
  out.push(dimUnderline(fitLine(header, W)));
2724
2780
 
2725
- for (const i of this._displayOrder()) {
2781
+ const capRows = this.am.capacityRows
2782
+ ? this.am.capacityRows(this._displayOrder(), { hideDisabled: this.hideDisabled })
2783
+ : this._displayOrder().map(i => ({ index: i, group: [i], unresolved: false, displayName: this.am.accounts[i]?.name, where: null, priceAccount: this.am.accounts[i], plan: null, cache: null }));
2784
+ for (const cr of capRows) {
2785
+ const i = cr.index;
2726
2786
  const a = this.am.accounts[i];
2727
2787
  if (!a) continue;
2728
- if (this.hideDisabled && a.enabled === false) continue;
2729
- const name = truncate(a.name, nameW).padEnd(nameW);
2788
+ const name = truncate(cr.displayName + (cr.unresolved ? '?' : ''), nameW).padEnd(nameW);
2730
2789
  const prov = gray(providerLabel(a).padEnd(PROVIDER_W));
2790
+ const whereCell = showWhere ? gray((cr.where || '--').padEnd(WHERE_W)) : '';
2791
+ const planCell = showPlan ? gray(planLabel(cr.plan, cr.priceAccount, this.am).padEnd(PLAN_W) + ' ') : '';
2792
+ const lead = name + ' ' + prov + ' ' + whereCell + planCell;
2731
2793
 
2732
2794
  // The no-weekly plan has NO weekly window to complete — its weekly "capacity" is
2733
2795
  // derived: avg session tank × 33.6 (the number of 5h windows in 7 days). Shown
@@ -2737,13 +2799,13 @@ export class TUI {
2737
2799
  const sesTank = this.am.capacityTank?.(i, 'ses');
2738
2800
  const approx = sesTank && sesTank.n > 0
2739
2801
  ? formatTokens(Math.round(sesTank.avg * (7 * 24) / 5)) : '--';
2740
- const cellsByName = { Current: cyan(approx), Prev: '--', Avg: '--', N: sesTank?.n ? String(sesTank.n) : '--' };
2802
+ const cellsByName = { Current: cyan(approx), Prev: '--', 'Med-3': '--', 'Med-all': '--', N: sesTank?.n ? String(sesTank.n) : '--' };
2741
2803
  // Same price cell as the main path: this account's weekly capacity IS the
2742
2804
  // derived tank (avg 5h × 33.6) — the price column must not go blank here.
2743
- const p2 = this.am.monthlyPriceFor?.(a);
2805
+ const p2 = this.am.monthlyPriceFor?.(cr.priceAccount);
2744
2806
  cellsByName['$/1M'] = gray((sesTank?.avg && p2)
2745
2807
  ? ('$' + (p2 / (Math.round(sesTank.avg * (7 * 24) / 5) / 1e6)).toFixed(2)).padStart(CW) : '--'.padStart(CW));
2746
- out.push(' ' + name + ' ' + prov + ' '
2808
+ out.push(' ' + lead
2747
2809
  + COLS.map(c => cellsByName[c].padStart(CW)).join('')
2748
2810
  + dim(' no weekly limit · avg 5h × 33.6'));
2749
2811
  continue;
@@ -2771,8 +2833,11 @@ export class TUI {
2771
2833
  const cellsByName = {
2772
2834
  Current: cur.padStart(CW - (curPct ? curPct.length + 1 : 0)),
2773
2835
  Prev: (tank?.source === 'cycles' && tank.prev != null ? formatTokens(tank.prev) : '--'),
2774
- Avg: (tank?.source === 'cycles' ? formatTokens(tank.avg) : '--'),
2775
- N: (tank?.source === 'cycles' ? String(tank.n) : '--'),
2836
+ 'Med-3': (tank?.source === 'cycles' && tank.recent != null ? formatTokens(tank.recent) : '--'),
2837
+ 'Med-all': (tank?.source === 'cycles' ? formatTokens(tank.avg) : '--'),
2838
+ // `n*` = at least one contributing cycle is a two-pool merge (no per-reading
2839
+ // samples survive a merge, so it is estimated from close-time tokens only).
2840
+ N: (tank?.source === 'cycles' ? String(tank.n) + (tank.mergedCount > 0 ? '*' : '') : '--'),
2776
2841
  };
2777
2842
  // $/1M (owner 2026-10-31 "price per token, not per subscription"): the measured
2778
2843
  // weekly tank divided by the plan's monthly-normalized price. Weekly in BOTH
@@ -2789,18 +2854,21 @@ export class TUI {
2789
2854
  ? (sesTankObj?.avg ? Math.round(sesTankObj.avg * (7 * 24) / 5) : null)
2790
2855
  : (this.am.capacityTank?.(i, 'wk')?.avg
2791
2856
  ?? (a.type === 'provider' && sesTankObj?.avg ? Math.round(sesTankObj.avg * WK_PER_SES) : null));
2792
- const price = this.am.monthlyPriceFor?.(a);
2857
+ const price = this.am.monthlyPriceFor?.(cr.priceAccount);
2793
2858
  const priceCell = (wkTank && price)
2794
2859
  ? '$' + (price / (wkTank / 1e6)).toFixed(2)
2795
2860
  : '--';
2796
2861
  cellsByName['$/1M'] = gray(priceCell.padStart(CW));
2797
- const row = ' ' + name + ' ' + prov + ' '
2862
+ const row = ' ' + lead
2798
2863
  + COLS.map(c => cellsByName[c].padStart(CW)).join('');
2799
2864
  out.push(row + (curPct ? ' ' + curPct : ''));
2800
2865
  }
2801
2866
 
2802
2867
  out.push('');
2803
- out.push(' ' + dim('Capacity = tokens ÷ how full the provider said the window was, at close.'));
2868
+ out.push(' ' + dim('Capacity = median of tokens ÷ % full across readings in each cycle. Med-3 = median of last 3 cycles, Med-all = every cycle.'));
2869
+ out.push(' ' + dim('One row per account. Where = which side holds its history: cloud, laptop or both. ? = identity unknown.'));
2870
+ out.push(' ' + dim('Tokens = everything the provider processed (input + cached + output), same for Claude and GLM.'));
2871
+ out.push(' ' + dim('N = cycles in Med-all (Med-3 uses the newest 3). N* = includes a cycle both pools saw (merged) — estimated from close-time tokens, less precise.'));
2804
2872
  out.push(' ' + dim('Current @% = live window, % full now · no-weekly weekly = avg 5h × 33.6.'));
2805
2873
  out.push(' ' + dim('$/1M = plan price ÷ measured weekly tank (monthly-normalized). -- = no price or tank yet.'));
2806
2874
  return out;