maxpool 1.24.94 → 1.24.96

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.
@@ -23,6 +23,7 @@ export async function sendLoginToPool({ url, key, name, profile, creds, fetchImp
23
23
  account: {
24
24
  name, type: 'oauth',
25
25
  accountUuid: profile?.accountUuid,
26
+ organizationUuid: profile?.organizationUuid,
26
27
  accessToken: creds.accessToken,
27
28
  refreshToken: creds.refreshToken,
28
29
  expiresAt: creds.expiresAt,
package/src/index.js CHANGED
@@ -20,7 +20,8 @@ import { setEventLogPath, installConsoleMirror, setConsoleStdoutSuppressed, setC
20
20
  import { sendLoginToPool, planCliLogin, resolveUsablePools } from './cloud-login.js';
21
21
  import { SleepGuard } from './sleep-guard.js';
22
22
  import { controllingTerminalAlive } from './terminal-alive.js';
23
- import { AccountManager } from './account-manager.js';
23
+ import { AccountManager, combineEfficiency } from './account-manager.js';
24
+ import { cacheUsageLabel } from './usage-label.js';
24
25
  import { createProxyServer, REQUEST_IDLE_MAX_MS } from './server.js';
25
26
 
26
27
  // ── Happy Eyeballs: stop racing a dead IPv6 leg ────────────────────────────────
@@ -42,7 +43,7 @@ net.setDefaultAutoSelectFamilyAttemptTimeout(
42
43
  );
43
44
  import { Prober } from './prober.js';
44
45
  import { CapacityLedger } from './capacity-ledger.js';
45
- import { loginOAuth, fetchProfile, refreshAccessToken, isTokenExpiringSoon, tokenFingerprint, isLoginCancelled } from './oauth.js';
46
+ import { loginOAuth, fetchProfile, refreshAccessToken, isTokenExpiringSoon, tokenFingerprint, isLoginCancelled, sameAccountIdentity, organizationUnknownMatch, resolveOrganizations, suggestAccountName, knownDifferentOrg } from './oauth.js';
46
47
  import { TUI, writeTerminalSync, reclaimRawModeLogged, whenTerminalCaughtUp } from './tui.js';
47
48
  import { createTerminalModeSwitcher } from './terminal-mode.js';
48
49
  import { RestartController } from './restart-controller.js';
@@ -939,8 +940,7 @@ async function serverWorkerCommand() {
939
940
  // Pick up any new accounts from disk so index matching stays correct
940
941
  // (only add, don't refresh credentials — we're about to write the authoritative tokens)
941
942
  for (const diskAcct of diskConfig.accounts) {
942
- const known = (diskAcct.accountUuid && config.accounts.some(a => a.accountUuid === diskAcct.accountUuid))
943
- || config.accounts.some(a => a.name === diskAcct.name);
943
+ const known = config.accounts.some(a => sameAccountIdentity(a, diskAcct) || nameMatches(a, diskAcct));
944
944
  if (!known) {
945
945
  config.accounts.push(diskAcct);
946
946
  accountManager.addAccount(diskAcct);
@@ -1090,7 +1090,8 @@ async function serverWorkerCommand() {
1090
1090
  // Headless (service / shared VM) pools have no TUI log buffer, so named-caller
1091
1091
  // attribution would otherwise reach no log at all. Only named callers are
1092
1092
  // logged here — a solo headless pool stays as quiet as before.
1093
- appendEventLog(`[Maxpool] ${info.caller} · ${info.method} ${info.path} → ${info.account || '?'} (${info.status})${info.conversation ? ` [cv ${info.conversation.slice(0, 8)}]` : ''}`);
1093
+ const cache = cacheUsageLabel(info.cacheUsage);
1094
+ appendEventLog(`[Maxpool] ${info.caller} · ${info.method} ${info.path} → ${info.account || '?'} (${info.status})${info.conversation ? ` [cv ${info.conversation.slice(0, 8)}]` : ''}${cache ? ` ${cache}` : ''}`);
1094
1095
  }
1095
1096
  },
1096
1097
  };
@@ -1396,7 +1397,8 @@ async function serverWorkerCommand() {
1396
1397
  // in memory but silently reverts on the next config write / restart. Merge
1397
1398
  // onto the existing disk scheduler block so other scheduler keys survive.
1398
1399
  if (config.scheduler?.crossProviderFallbackPolicy || config.scheduler?.providers
1399
- || config.scheduler?.weeklyAwareScoring !== undefined) {
1400
+ || config.scheduler?.weeklyAwareScoring !== undefined
1401
+ || config.scheduler?.stickyBusyBudgetMs !== undefined) {
1400
1402
  diskConfig.scheduler = {
1401
1403
  ...diskConfig.scheduler,
1402
1404
  ...(config.scheduler.crossProviderFallbackPolicy
@@ -1409,6 +1411,9 @@ async function serverWorkerCommand() {
1409
1411
  // default on the next restart.
1410
1412
  ...(config.scheduler.weeklyAwareScoring !== undefined
1411
1413
  ? { weeklyAwareScoring: config.scheduler.weeklyAwareScoring } : {}),
1414
+ // Wait for busy account (TUI routing b) — same reason as above.
1415
+ ...(config.scheduler.stickyBusyBudgetMs !== undefined
1416
+ ? { stickyBusyBudgetMs: config.scheduler.stickyBusyBudgetMs } : {}),
1412
1417
  };
1413
1418
  }
1414
1419
  // Persist live-toggled automatic-update flags (the TUI 'u' Updates menu). Same
@@ -1423,7 +1428,7 @@ async function serverWorkerCommand() {
1423
1428
  // Use live tokens from AccountManager (not the stale config.accounts copy).
1424
1429
  diskConfig.accounts = config.accounts.map(a => {
1425
1430
  const am = accountManager.accounts.find(candidate =>
1426
- (a.accountUuid && candidate.accountUuid === a.accountUuid) || candidate.name === a.name
1431
+ sameAccountIdentity(candidate, a) || nameMatches(candidate, a)
1427
1432
  );
1428
1433
  const live = am ? {
1429
1434
  ...a,
@@ -1432,7 +1437,7 @@ async function serverWorkerCommand() {
1432
1437
  expiresAt: am.expiresAt,
1433
1438
  } : a;
1434
1439
  const diskAcct = diskConfig.accounts.find(
1435
- d => (a.accountUuid && d.accountUuid === a.accountUuid) || d.name === a.name
1440
+ d => sameAccountIdentity(d, a) || nameMatches(d, a)
1436
1441
  );
1437
1442
  return diskAcct ? { ...diskAcct, ...live } : live;
1438
1443
  });
@@ -1990,7 +1995,8 @@ async function loginOAuthCommand() {
1990
1995
  // Cloud-aware: a linked team pool with a usable key may receive the login instead.
1991
1996
  // Profile FIRST (once): a local match must win over the cloud default.
1992
1997
  const profile = await fetchProfile(creds.accessToken);
1993
- const localMatch = (profile?.accountUuid && config.accounts.find(a => a.type === 'oauth' && a.accountUuid === profile.accountUuid))
1998
+ const localMatch = (profile?.accountUuid && config.accounts.find(a => a.type === 'oauth' && sameAccountIdentity(a, profile)))
1999
+ || (profile?.accountUuid && organizationUnknownMatch(config.accounts, profile))
1994
2000
  || (profile?.email && config.accounts.find(a => a.type === 'oauth' && a.name === profile.email))
1995
2001
  || null;
1996
2002
  const { usable, unresolved, error } = await resolveUsablePools(config.pools, async (names) => {
@@ -2230,13 +2236,25 @@ async function statusCommand() {
2230
2236
  console.log(`Anthropic: temporarily throttled (${state}, queued ${queued}${oldest})\n`);
2231
2237
  }
2232
2238
 
2239
+ for (const line of efficiencyLines(data)) console.log(line);
2240
+
2233
2241
  for (const acct of data.accounts) {
2234
- const q = acct.quota;
2242
+ // A benched duplicate exports quota: null (its local numbers are stale by design —
2243
+ // the cloud owns the live ones). {} keeps every quota read below safe.
2244
+ const q = acct.quota || {};
2235
2245
  const current = acct.name === data.currentAccount ? ' *' : '';
2236
2246
 
2237
2247
  console.log(` ${acct.name} (${acct.type})${current}`);
2238
2248
  console.log(` Status: ${acct.enabled === false ? 'disabled' : acct.status}`);
2239
2249
  console.log(` Load: current ${acct.load?.current?.inFlight || 0}/${acct.load?.current?.activeWeight || 0} weight, 15m ${formatLoadWindow(acct.load?.last15m)}, 1h ${formatLoadWindow(acct.load?.last1h)}`);
2250
+ if (acct.quotaSource === 'cloud-mirror') {
2251
+ console.log(' Quota: from team pool (this local copy is benched)');
2252
+ }
2253
+ // Cloud rows merge server-side: cache + served from the serving pool's export
2254
+ // (team-wide on that account), bounced from this pool's own refusals on it.
2255
+ const eff = acct.load?.last1h?.efficiency;
2256
+ const team = acct.remote && acct.teamEfficiency?.last1h ? ' (team)' : '';
2257
+ if (eff && (eff.served || eff.bounced)) console.log(` Cache: ${pctOrDash(eff.hit)} over 1h${team}, ${eff.served || 0} served, ${eff.bounced || 0} bounced`);
2240
2258
 
2241
2259
  if (acct.type === 'provider') {
2242
2260
  const last = acct.lastStatus ? `${acct.lastStatus} in ${formatDurationMs(acct.lastResponseMs)}` : '-';
@@ -2304,23 +2322,28 @@ async function accountsCommand() {
2304
2322
  )
2305
2323
  );
2306
2324
 
2307
- // Deduplicate by accountUuid — keep the last (most recently added) entry
2325
+ // Deduplicate by user + organization — keep the last (most recently added) entry
2308
2326
  const seen = new Map();
2309
2327
  let removed = 0;
2310
2328
  for (let i = config.accounts.length - 1; i >= 0; i--) {
2311
2329
  const a = config.accounts[i];
2312
2330
  const uuid = profiles[i]?.accountUuid || a.accountUuid;
2313
- if (uuid) {
2314
- if (seen.has(uuid)) {
2331
+ const org = profiles[i]?.organizationUuid || a.organizationUuid || '';
2332
+ const identity = uuid ? `${uuid}/${org}` : null;
2333
+ if (identity) {
2334
+ if (seen.has(identity)) {
2315
2335
  config.accounts.splice(i, 1);
2316
2336
  profiles.splice(i, 1);
2317
2337
  removed++;
2318
2338
  } else {
2319
- seen.set(uuid, i);
2320
- // Update stored UUID and name from profile
2339
+ seen.set(identity, i);
2340
+ // Update stored UUIDs and name from profile. Two organizations of one user
2341
+ // share the email, so the name is only taken when no other account has it.
2321
2342
  if (profiles[i] && !profiles[i].error) {
2322
2343
  a.accountUuid = profiles[i].accountUuid;
2323
- if (profiles[i].email) a.name = profiles[i].email;
2344
+ a.organizationUuid = profiles[i].organizationUuid;
2345
+ const email = profiles[i].email;
2346
+ if (email && !config.accounts.some((other, j) => j !== i && other.name === email)) a.name = email;
2324
2347
  }
2325
2348
  }
2326
2349
  }
@@ -2526,30 +2549,31 @@ async function upsertOAuthAccount(config, name, creds, source = 'unknown', prefe
2526
2549
  if (!profileOk) {
2527
2550
  console.error(`Warning: could not fetch account profile — ${profile?.error || 'no token'}`);
2528
2551
  }
2552
+ if (profileOk) await resolveOrganizations(config.accounts.filter(a => a.type === 'oauth'), profile.accountUuid);
2553
+ const uncertain = profileOk && !name ? organizationUnknownMatch(config.accounts, profile) : null;
2554
+ if (uncertain) {
2555
+ name = uncertain.name;
2556
+ console.log(`Same Claude user as "${name}", and its organization could not be checked: re-authenticating it in place. To add this login as a second account, run again with --name <new name>.`);
2557
+ }
2529
2558
  if (!name && profile?.email) {
2530
- name = profile.email;
2531
2559
  const tier = profile.hasClaudeMax ? 'Max' : profile.hasClaudePro ? 'Pro' : null;
2532
2560
  if (tier) console.log(`Detected Claude ${tier} account: ${profile.email}`);
2533
2561
  }
2534
- if (!name) {
2535
- const n = config.accounts.filter(a => a.name.startsWith('account-')).length + 1;
2536
- name = `account-${n}`;
2537
- }
2562
+ if (!name) name = suggestAccountName(config.accounts, profile);
2538
2563
 
2539
2564
  const account = {
2540
2565
  name,
2541
2566
  type: 'oauth',
2542
2567
  source,
2543
2568
  accountUuid: profile?.accountUuid || null,
2569
+ organizationUuid: profile?.organizationUuid || null,
2544
2570
  accessToken: creds.accessToken,
2545
2571
  refreshToken: creds.refreshToken,
2546
2572
  expiresAt: creds.expiresAt,
2547
2573
  };
2548
2574
 
2549
- // Deduplicate: match by UUID first, then by name
2550
- let idx = profile?.accountUuid
2551
- ? config.accounts.findIndex(a => a.accountUuid === profile.accountUuid)
2552
- : -1;
2575
+ // Deduplicate: match by user + organization first, then by name
2576
+ let idx = config.accounts.findIndex(a => sameAccountIdentity(a, account));
2553
2577
  if (idx < 0) idx = config.accounts.findIndex(a => a.name === name);
2554
2578
 
2555
2579
  if (idx >= 0) {
@@ -2567,13 +2591,17 @@ async function upsertOAuthAccount(config, name, creds, source = 'unknown', prefe
2567
2591
  // ── config sync helpers ─────────────────────────────────────
2568
2592
 
2569
2593
  /**
2570
- * Find a config account entry matching an in-memory account (by UUID, then name).
2594
+ * Find a config account entry matching an in-memory account (by user + organization,
2595
+ * then name).
2571
2596
  */
2597
+ // Name fallback must never cross organizations: a same-user row with a KNOWN,
2598
+ // DIFFERENT organization owns its name and its tokens.
2599
+ function nameMatches(a, diskAcct) {
2600
+ return a.name === diskAcct.name && !knownDifferentOrg(a, diskAcct);
2601
+ }
2572
2602
  function findConfigAccount(diskConfig, account) {
2573
- if (account.accountUuid) {
2574
- const idx = diskConfig.accounts.findIndex(a => a.accountUuid === account.accountUuid);
2575
- if (idx >= 0) return idx;
2576
- }
2603
+ const idx = diskConfig.accounts.findIndex(a => sameAccountIdentity(a, account));
2604
+ if (idx >= 0) return idx;
2577
2605
  return diskConfig.accounts.findIndex(a => a.name === account.name);
2578
2606
  }
2579
2607
 
@@ -2585,9 +2613,7 @@ function findConfigAccount(diskConfig, account) {
2585
2613
  async function syncAccountsFromDisk(diskConfig, memConfig, accountManager) {
2586
2614
  let added = 0;
2587
2615
  for (const diskAcct of diskConfig.accounts) {
2588
- const matchByUuid = diskAcct.accountUuid
2589
- ? memConfig.accounts.findIndex(a => a.accountUuid === diskAcct.accountUuid)
2590
- : -1;
2616
+ const matchByUuid = memConfig.accounts.findIndex(a => sameAccountIdentity(a, diskAcct));
2591
2617
  const matchByName = memConfig.accounts.findIndex(a => a.name === diskAcct.name);
2592
2618
  const memIdx = (matchByUuid >= 0 ? matchByUuid : null) ?? (matchByName >= 0 ? matchByName : -1);
2593
2619
 
@@ -2614,9 +2640,10 @@ async function syncAccountsFromDisk(diskConfig, memConfig, accountManager) {
2614
2640
 
2615
2641
  // Find the corresponding AccountManager entry and update credentials
2616
2642
  const mgr = accountManager.accounts.find(a =>
2617
- (diskAcct.accountUuid && a.accountUuid === diskAcct.accountUuid) || a.name === diskAcct.name
2643
+ sameAccountIdentity(a, diskAcct) || nameMatches(a, diskAcct)
2618
2644
  );
2619
2645
  if (!mgr) continue;
2646
+ if (diskAcct.organizationUuid && !mgr.organizationUuid) mgr.organizationUuid = diskAcct.organizationUuid;
2620
2647
  const enabled = diskAcct.enabled !== false;
2621
2648
  if (mgr.enabled !== enabled) {
2622
2649
  accountManager.setAccountEnabled(mgr.index, enabled);
@@ -2730,6 +2757,7 @@ function handleServerListenError(err, host, port) {
2730
2757
  `[Maxpool] ${host}:${port} is already in use.`,
2731
2758
  'Another Maxpool proxy may already be running.',
2732
2759
  'Check the existing server with: maxpool status',
2760
+ 'Dashboard: maxpool (attaches to the running service)',
2733
2761
  `Find the listener with: lsof -nP -iTCP:${port} -sTCP:LISTEN`,
2734
2762
  ];
2735
2763
  } else if (err.code === 'EACCES') {
@@ -2754,6 +2782,40 @@ function formatDurationMs(ms) {
2754
2782
  return `${Math.floor(sec / 60)}m${String(Math.round(sec % 60)).padStart(2, '0')}s`;
2755
2783
  }
2756
2784
 
2785
+ // A function declaration, not a const: commands dispatch before later consts initialise.
2786
+ function pctOrDash(x) { return x == null ? '—' : `${Math.round(x * 100)}%`; }
2787
+
2788
+ /** `maxpool status` Efficiency block. The server merges every row once (mirror rows:
2789
+ * cache + served from the serving pool's export, bounces / waits / moves / latency from
2790
+ * this pool's own events) — the same figures the TUI Cache line shows. With nothing
2791
+ * served or bounced in the window, rates read '—', never a measured-looking 0. */
2792
+ function efficiencyLines(data, key = 'last15m') {
2793
+ const accts = data.accounts || [];
2794
+ const overall = data.efficiency?.[key];
2795
+ if (!overall) return [];
2796
+ const claude = overall.claude || combineEfficiency([], 'claude');
2797
+ const glm = overall.glm || combineEfficiency([], 'glm');
2798
+ const served = claude.served + glm.served;
2799
+ const sum = (f) => (claude[f] || 0) + (glm[f] || 0);
2800
+ const cause = (c) => (claude.movedByCause?.[c] || 0) + (glm.movedByCause?.[c] || 0);
2801
+ const anyData = served + sum('bounced') > 0;
2802
+ const n = (x) => (anyData ? String(x) : '—');
2803
+ const failed = accts.reduce((t, a) => t + (a.load?.[key]?.failed || 0), 0);
2804
+ const linkDrops = accts.reduce((t, a) => t + (a.load?.[key]?.linkFailed || 0), 0);
2805
+ const co = data.clientOutcomes?.[key];
2806
+ const s = (ms) => (ms == null ? '—' : `${(ms / 1000).toFixed(1)}s`);
2807
+ return [
2808
+ `Efficiency (${key === 'last1h' ? '1h' : '15m'}):`,
2809
+ ` Cache: Claude ${pctOrDash(claude.hit)} (miss ${(claude.missTokens / 1e6).toFixed(1)}M tok) · GLM ${pctOrDash(glm.hit)} (miss ${(glm.missTokens / 1e6).toFixed(1)}M tok)`,
2810
+ ` Moves: ${served ? `${Math.round(sum('moved') * 100 / served)}/100 served` : '—'} (busy ${n(cause('busy'))} · balance ${n(cause('balance'))} · wall ${n(cause('wall'))} · link ${n(cause('link'))} · other ${n(cause('other'))})`,
2811
+ ` Bounced: ${n(sum('bounced'))} (refused ${n(sum('refused'))}) · failed ${failed} · link drops ${linkDrops}`,
2812
+ ` Waited: ${n(sum('waited'))}${sum('waited') ? ` (avg ${s(sum('waitMs') / sum('waited'))})` : ''} · waited then moved ${n(sum('waitThenMoved'))}`,
2813
+ ` Client errors: ${co ? `${co.poolErrors + co.requestErrors} of ${co.total} (pool ${co.poolErrors} · request ${co.requestErrors})` : '—'}`,
2814
+ ` First byte: p50 ${s(overall.e2eP50)} · p95 ${s(overall.e2eP95)} (this pool's clients, waits included)`,
2815
+ '',
2816
+ ];
2817
+ }
2818
+
2757
2819
  function formatLoadWindow(load = {}) {
2758
2820
  const avg = load.avgMs != null ? ` avg ${formatDurationMs(load.avgMs)}` : '';
2759
2821
  const failed = load.failed ? `, ${load.failed} failed` : '';
package/src/oauth.js CHANGED
@@ -153,6 +153,7 @@ export async function fetchProfile(accessToken) {
153
153
  const data = await res.json();
154
154
  return {
155
155
  accountUuid: data.account?.uuid,
156
+ organizationUuid: data.organization?.uuid,
156
157
  email: data.account?.email,
157
158
  name: data.account?.display_name,
158
159
  orgName: data.organization?.name,
@@ -165,6 +166,84 @@ export async function fetchProfile(accessToken) {
165
166
  }
166
167
  }
167
168
 
169
+ /** True when both records belong to the same Claude user (account.uuid). */
170
+ export function sameUser(a, b) {
171
+ return Boolean(a?.accountUuid) && a.accountUuid === b?.accountUuid;
172
+ }
173
+
174
+ /**
175
+ * True when both records are the same Claude login: the same user in the same
176
+ * organization. One user can hold a personal Max org and a Team org under one
177
+ * email; each is its own account. Records saved before organizations were
178
+ * recorded have no organizationUuid and match each other on the user alone; an
179
+ * entry with an org never matches one without, so a rotated single-use refresh
180
+ * token can never be written to the wrong entry.
181
+ */
182
+ export function sameAccountIdentity(a, b) {
183
+ return sameUser(a, b) && (a.organizationUuid || null) === (b.organizationUuid || null);
184
+ }
185
+
186
+ /**
187
+ * True when both records are the same Claude user in two KNOWN, DIFFERENT
188
+ * organizations: two separate accounts that must never be matched by name.
189
+ */
190
+ export function knownDifferentOrg(a, b) {
191
+ return sameUser(a, b) && Boolean(a.organizationUuid) && Boolean(b?.organizationUuid)
192
+ && a.organizationUuid !== b.organizationUuid;
193
+ }
194
+
195
+ /**
196
+ * The one OAuth entry of the login's user whose organization is still unknown,
197
+ * when no entry matches the login exactly; null otherwise. The TUI then asks
198
+ * "re-authenticate or add?", the CLI re-authenticates it in place. One shared
199
+ * rule for both so they can never drift apart.
200
+ */
201
+ export function organizationUnknownMatch(accounts, profile) {
202
+ if (accounts.some(a => sameAccountIdentity(a, profile))) return null;
203
+ return accounts.find(a => a.type === 'oauth' && sameUser(a, profile) && !a.organizationUuid) || null;
204
+ }
205
+
206
+ /**
207
+ * Fill in organizationUuid on the accounts of one user that lack it, by reading
208
+ * each one's profile with its own current access token. Read only: an expired or
209
+ * missing token is skipped, never refreshed. `credentialsOf` supplies the live
210
+ * token of a running account; by default the stored one is used. Returns the
211
+ * accounts still without an organization.
212
+ */
213
+ export async function resolveOrganizations(accounts, accountUuid, credentialsOf = a => a) {
214
+ const missing = accounts.filter(a => sameUser(a, { accountUuid }) && !a.organizationUuid);
215
+ for (const account of missing) {
216
+ const organizationUuid = await readOrganization(credentialsOf(account));
217
+ if (organizationUuid) account.organizationUuid = organizationUuid;
218
+ }
219
+ return missing.filter(a => !a.organizationUuid);
220
+ }
221
+
222
+ /** The organization uuid behind an unexpired access token (read only), else null. */
223
+ async function readOrganization({ accessToken, expiresAt } = {}) {
224
+ if (!accessToken || isTokenExpiringSoon(expiresAt, 0)) return null;
225
+ const profile = await fetchProfile(accessToken);
226
+ return profile?.organizationUuid || null;
227
+ }
228
+
229
+ /**
230
+ * Default name for a new account: its email, or "<email> (<plan type>)" when
231
+ * another account already carries that email as its name (the same user in
232
+ * another organization), or a numbered fallback when the profile has no email.
233
+ */
234
+ export function suggestAccountName(accounts, profile) {
235
+ const email = profile?.email;
236
+ if (!email) return `account-${accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
237
+ if (!accounts.some(a => a.name === email)) return email;
238
+ const type = String(profile.orgType || '').replace(/^claude_/, '');
239
+ const base = `${email} (${type || '2'})`;
240
+ if (!accounts.some(a => a.name === base)) return base;
241
+ // A THIRD org of the same plan type must not reuse the second's name.
242
+ let n = 2;
243
+ while (accounts.some(a => a.name === `${email} (${type || '2'} ${n})`)) n++;
244
+ return `${email} (${type || '2'} ${n})`;
245
+ }
246
+
168
247
  const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage';
169
248
  const OAUTH_USAGE_BETA = 'oauth-2025-04-20';
170
249
 
package/src/pool-link.js CHANGED
@@ -31,12 +31,14 @@ export function credentialFp(credential) {
31
31
  }
32
32
 
33
33
  /** Stable identity of an account for duplicate matching. Claude OAuth →
34
- * accountUuid; provider key → provider + key fingerprint. null = no identity
35
- * (an unnamed apikey account can't be matched — it never benches anything). */
34
+ * accountUuid (+ organizationUuid when known); provider key → provider + key
35
+ * fingerprint. null = no identity (an unnamed apikey account can't be matched —
36
+ * it never benches anything). */
36
37
  export function accountIdentity(account) {
37
38
  if (!account) return null;
38
39
  if (account.type === 'oauth') {
39
- return account.accountUuid ? `uuid:${account.accountUuid}` : null;
40
+ if (!account.accountUuid) return null;
41
+ return account.organizationUuid ? `uuid:${account.accountUuid}:${account.organizationUuid}` : `uuid:${account.accountUuid}`;
40
42
  }
41
43
  if (account.type === 'provider' && account.provider && account.credential) {
42
44
  return `key:${account.provider}:${credentialFp(account.credential)}`;
@@ -44,10 +46,23 @@ export function accountIdentity(account) {
44
46
  return null;
45
47
  }
46
48
 
49
+ // Keys a LOCAL row looks up in a remote identity map. A row whose organization is
50
+ // known also accepts the remote's org-less wildcard `uuid:<uuid>:*` (the remote
51
+ // saved the login before organizations were recorded, or runs an older version);
52
+ // an org-less row looks up the bare `uuid:<uuid>`, which an org-bearing remote row
53
+ // also registers while that user has a single organization there. Two KNOWN and
54
+ // different organizations never match.
55
+ export function identitiesOf(account) {
56
+ const id = accountIdentity(account);
57
+ if (!id) return [];
58
+ if (account.type === 'oauth' && account.organizationUuid) return [id, `uuid:${account.accountUuid}:*`];
59
+ return [id];
60
+ }
61
+
47
62
  /** Identity of a REMOTE status row (same key shape as accountIdentity). */
48
63
  export function remoteAccountIdentity(a) {
49
64
  if (!a) return null;
50
- if (a.type === 'oauth') return a.accountUuid ? `uuid:${a.accountUuid}` : null;
65
+ if (a.type === 'oauth') return accountIdentity(a);
51
66
  if (a.type === 'provider' && a.provider && a.keyFingerprint) return `key:${a.provider}:${a.keyFingerprint}`;
52
67
  return null;
53
68
  }
@@ -59,12 +74,33 @@ export function remoteAccountIdentity(a) {
59
74
  export function remoteIdentities(status) {
60
75
  const out = new Map();
61
76
  if (!status || !Array.isArray(status.accounts)) return out;
77
+ const orgsByUser = new Map(); // uuid -> Set of known organizations
78
+ const exactBare = new Set(); // bare keys owned by an org-less remote row
62
79
  for (const a of status.accounts) {
63
80
  if (a.enabled === false) continue; // a benched remote row doesn't bench the local copy
64
- let id = null;
65
- if (a.type === 'oauth' && a.accountUuid) id = `uuid:${a.accountUuid}`;
66
- else if (a.type === 'provider' && a.keyFingerprint) id = `key:${a.provider}:${a.keyFingerprint}`;
67
- if (id) out.set(id, { name: a.name, provider: a.provider, type: a.type });
81
+ const row = { name: a.name, provider: a.provider, type: a.type };
82
+ if (a.type === 'oauth') {
83
+ if (!a.accountUuid) continue;
84
+ const bare = `uuid:${a.accountUuid}`;
85
+ if (a.organizationUuid) {
86
+ out.set(`${bare}:${a.organizationUuid}`, row);
87
+ if (!out.has(bare)) out.set(bare, row); // for an org-less local copy
88
+ const set = orgsByUser.get(a.accountUuid) || new Set();
89
+ set.add(a.organizationUuid); orgsByUser.set(a.accountUuid, set);
90
+ } else {
91
+ out.set(bare, row); exactBare.add(bare);
92
+ out.set(`${bare}:*`, row); // for an org-bearing local copy
93
+ }
94
+ } else if (a.type === 'provider' && a.keyFingerprint) {
95
+ out.set(`key:${a.provider}:${a.keyFingerprint}`, row);
96
+ }
97
+ }
98
+ // Two known organizations of one user make an org-less local copy ambiguous:
99
+ // drop the bare key rather than bench on a guess (unless an org-less remote row
100
+ // owns it exactly).
101
+ for (const [uuid, orgs] of orgsByUser) {
102
+ const bare = `uuid:${uuid}`;
103
+ if (orgs.size > 1 && !exactBare.has(bare)) out.delete(bare);
68
104
  }
69
105
  return out;
70
106
  }
@@ -74,10 +110,23 @@ export function remoteIdentities(status) {
74
110
  export function computeDuplicates(accounts, remoteIdentitiesMap) {
75
111
  const out = [];
76
112
  if (!remoteIdentitiesMap || remoteIdentitiesMap.size === 0) return out;
113
+ // The org-less wildcard `uuid:<user>:*` is resolved only while the user has at
114
+ // most ONE known organization locally. Two local orgs against one org-less
115
+ // remote row is ambiguous (the remote holds at most one of the two
116
+ // subscriptions), so then only an exact identity match benches — mirroring the
117
+ // remote-side ambiguity rule below.
118
+ const orgCount = new Map();
119
+ for (const a of accounts) {
120
+ if (a?.type === 'oauth' && a.accountUuid && a.organizationUuid) {
121
+ orgCount.set(a.accountUuid, (orgCount.get(a.accountUuid) || 0) + 1);
122
+ }
123
+ }
77
124
  for (const a of accounts) {
78
- const id = accountIdentity(a);
79
- const hit = id ? remoteIdentitiesMap.get(id) : null;
80
- if (hit) out.push({ index: a.index, identity: id, remoteName: hit.name, provider: hit.provider });
125
+ const ids = identitiesOf(a);
126
+ const wildcard = ids[1];
127
+ const usable = orgCount.get(a.accountUuid) > 1 && wildcard ? ids.slice(0, 1) : ids;
128
+ const hit = usable.map(id => remoteIdentitiesMap.get(id)).find(Boolean);
129
+ if (hit) out.push({ index: a.index, identity: ids[0], remoteName: hit.name, provider: hit.provider });
81
130
  }
82
131
  return out;
83
132
  }
package/src/prober.js CHANGED
@@ -109,9 +109,15 @@ export class Prober {
109
109
  // a user often disables an account precisely BECAUSE it's exhausted, and still
110
110
  // wants to see its quota recover — so keep refreshing its usage for visibility
111
111
  // even though routing skips it. Do NOT add an enabled gate here.
112
- // Skip only auth-dead accounts (dead refresh token): probing them just re-POSTs
112
+ // Skip auth-dead accounts (dead refresh token): probing them just re-POSTs
113
113
  // the rejected token every cycle — a 400 storm. They recover only on re-auth.
114
- const oauth = this.am.accounts.filter(a => a.type === 'oauth' && a.credential && !a.refreshDead);
114
+ // Also skip BENCHED rows (`poolBenchedBy`): a local duplicate of an account the
115
+ // cloud team pool owns is never token-refreshed (account-manager
116
+ // ensureTokenFresh returns early so the cloud keeps the single-use refresh
117
+ // token), so its access token is dead and every probe fails — each failure
118
+ // widens the shared inter-probe gap and slows the HEALTHY rows. Its quota is
119
+ // shown from the cloud mirror (am.remoteRowFor), not from a local probe.
120
+ const oauth = this.am.accounts.filter(a => a.type === 'oauth' && a.credential && !a.refreshDead && !a.poolBenchedBy);
115
121
  // Pool links are probed by their own PoolLink status poll, not here.
116
122
  const providers = this.am.accounts.filter(a => a.type === 'provider' && a.credential); // 'pool' rows are excluded by type
117
123
 
@@ -413,6 +419,9 @@ export class Prober {
413
419
  * than silently swallowed — a swallowed failing probe is what let a stale
414
420
  * weekly look fresh. Never throws. */
415
421
  async probeOne(account) {
422
+ // Benched duplicate: never refreshed locally (see the sweep filter in probeAll),
423
+ // so the token is dead — a probe can only fail. Quota comes from the cloud mirror.
424
+ if (account.poolBenchedBy) return { ok: false, status: null, skipped: 'benched' };
416
425
  // Subscription latched org-disabled (account-manager recordProbeError): the quota
417
426
  // endpoint 403s before answering anything, so probing is pure waste until the org
418
427
  // accepts OAuth again. Skipping also stops the every-60s hammer that ran 700+ times