maxpool 1.24.94 → 1.24.95

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/README.md CHANGED
@@ -133,7 +133,7 @@ maxpool server
133
133
  ```
134
134
 
135
135
  When running from a TTY, shows an interactive TUI with:
136
- - Account table with session/weekly quota progress bars and reset countdowns
136
+ - Account table with session, Fable weekly and weekly quota progress bars and reset countdowns
137
137
  - Real-time activity log with request tracking
138
138
  - Keyboard shortcuts (see below)
139
139
 
@@ -297,6 +297,7 @@ TEAMCLAUDE_CONFIG=./my-config.json maxpool server
297
297
  "name": "user@example.com",
298
298
  "type": "oauth",
299
299
  "accountUuid": "...",
300
+ "organizationUuid": "...",
300
301
  "accessToken": "sk-ant-oat01-...",
301
302
  "refreshToken": "sk-ant-ort01-...",
302
303
  "expiresAt": 1774384968427
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maxpool",
3
- "version": "1.24.94",
3
+ "version": "1.24.95",
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",
@@ -1,4 +1,4 @@
1
- import { refreshAccessToken, isTokenExpiringSoon, modelFamily, tokenFingerprint } from './oauth.js';
1
+ import { refreshAccessToken, isTokenExpiringSoon, modelFamily, tokenFingerprint, sameUser, sameAccountIdentity } from './oauth.js';
2
2
  import { computeDuplicates, credentialFp, accountIdentity, remoteAccountIdentity } from './pool-link.js';
3
3
  import { appendEventLog } from './event-log.js';
4
4
  import { hourFloor } from './outside-usage.js';
@@ -625,6 +625,7 @@ export class AccountManager {
625
625
  type: acct.type,
626
626
  provider: acct.provider || (acct.type === 'provider' ? 'provider' : 'anthropic'),
627
627
  accountUuid: acct.accountUuid || null,
628
+ organizationUuid: acct.organizationUuid || null,
628
629
  credential: acct.accessToken || acct.authToken || acct.apiKey,
629
630
  upstream: acct.upstream || null,
630
631
  authHeader: acct.authHeader || null,
@@ -3488,13 +3489,16 @@ export class AccountManager {
3488
3489
  * Returns a plain integer (the minimum over self's profiles); the POLICY decides
3489
3490
  * sufficiency (holdMinPeers × holders). */
3490
3491
  countPeersWithRoom(self, now = Date.now()) {
3491
- const selfId = this.capacityIdentity(self);
3492
+ // Peers are deduped by capacity GROUP, not identity string: an org-less twin
3493
+ // of the same subscription (uuid:U vs uuid:U:org) groups with self and must
3494
+ // never count as a second roomy member of the pool.
3495
+ const selfGroup = new Set(this.capacityGroupOf(self));
3492
3496
  const selfProfiles = self?.profiles || ['claude', 'all'];
3493
3497
  const roomLeft = (util, ceiling, room) => Number.isFinite(util) && util <= ceiling - room;
3494
3498
  const roomy = [];
3495
3499
  for (const p of this.accounts) {
3496
3500
  const id = this.capacityIdentity(p);
3497
- if (id == null || id === selfId) continue;
3501
+ if (id == null || selfGroup.has(p)) continue;
3498
3502
  if (p.type !== 'oauth' || p.enabled === false) continue;
3499
3503
  if (p.remote || p.poolBenchedBy) continue;
3500
3504
  if (p.refreshDead || p.subscriptionGone) continue;
@@ -4964,7 +4968,7 @@ export class AccountManager {
4964
4968
  * fingerprint (same key shape). null = unresolvable (never merged by name). */
4965
4969
  capacityIdentity(a) {
4966
4970
  if (!a) return null;
4967
- if (a.remote) return remoteAccountIdentity({ type: a.type, provider: a.provider, accountUuid: a.remoteUuid, keyFingerprint: a.remoteKeyFp });
4971
+ if (a.remote) return remoteAccountIdentity({ type: a.type, provider: a.provider, accountUuid: a.remoteUuid, organizationUuid: a.remoteOrganizationUuid, keyFingerprint: a.remoteKeyFp });
4968
4972
  return accountIdentity(a);
4969
4973
  }
4970
4974
 
@@ -4972,7 +4976,19 @@ export class AccountManager {
4972
4976
  capacityGroupOf(a) {
4973
4977
  const id = this.capacityIdentity(a);
4974
4978
  if (!id) return [a];
4975
- return this.accounts.filter(x => this.capacityIdentity(x) === id);
4979
+ const same = this.accounts.filter(x => this.capacityIdentity(x) === id);
4980
+ // `uuid:<user>[:<org>]`: a row whose organization is unknown (saved before orgs
4981
+ // were recorded, or mirrored from an older pool) is still the same login as the
4982
+ // user's org-bearing row while that user has ONE known organization here. Two
4983
+ // known organizations are two subscriptions: then only exact ids group.
4984
+ if (!id.startsWith('uuid:')) return same;
4985
+ const user = id.split(':')[1];
4986
+ const rows = this.accounts.filter(x => {
4987
+ const xid = this.capacityIdentity(x);
4988
+ return xid && xid.startsWith('uuid:') && xid.split(':')[1] === user;
4989
+ });
4990
+ const orgs = new Set(rows.map(x => this.capacityIdentity(x).split(':')[2]).filter(Boolean));
4991
+ return orgs.size > 1 ? same : rows;
4976
4992
  }
4977
4993
 
4978
4994
  /** Merged closed-cycle history of an account's whole identity: this pool's ledger
@@ -5532,6 +5548,7 @@ export class AccountManager {
5532
5548
  type: acctData.type,
5533
5549
  provider: acctData.provider || (acctData.type === 'provider' ? 'provider' : 'anthropic'),
5534
5550
  accountUuid: acctData.accountUuid || null,
5551
+ organizationUuid: acctData.organizationUuid || null,
5535
5552
  credential: acctData.accessToken || acctData.authToken || acctData.apiKey,
5536
5553
  upstream: acctData.upstream || null,
5537
5554
  authHeader: acctData.authHeader || null,
@@ -5793,11 +5810,17 @@ export class AccountManager {
5793
5810
  return true;
5794
5811
  }
5795
5812
 
5796
- // Match a saved state entry to a live account by stable identity: prefer the
5797
- // account UUID when both have one, otherwise fall back to the name.
5813
+ /**
5814
+ * Match a saved state entry to a live account by stable identity: the account
5815
+ * UUID + organization UUID when both have a UUID, otherwise the name. A saved
5816
+ * entry without an organization (written before organizations were recorded)
5817
+ * also matches the same user under the same name, so quota survives the first
5818
+ * restart after an account learns its organization.
5819
+ */
5798
5820
  _sameIdentity(saved, account) {
5799
- if (saved.accountUuid && account.accountUuid) return saved.accountUuid === account.accountUuid;
5800
- return saved.name === account.name;
5821
+ if (!saved.accountUuid || !account.accountUuid) return saved.name === account.name;
5822
+ return sameAccountIdentity(saved, account)
5823
+ || (!saved.organizationUuid && sameUser(saved, account) && saved.name === account.name);
5801
5824
  }
5802
5825
 
5803
5826
  /**
@@ -5808,7 +5831,7 @@ export class AccountManager {
5808
5831
  return this.accounts.filter(a => !a.remote).map(a => {
5809
5832
  const quota = {};
5810
5833
  for (const f of PERSISTED_QUOTA_FIELDS) quota[f] = a.quota[f];
5811
- const out = { accountUuid: a.accountUuid, name: a.name, quota };
5834
+ const out = { accountUuid: a.accountUuid, organizationUuid: a.organizationUuid, name: a.name, quota };
5812
5835
  // OUTSIDE-USAGE flag survives restart (red-team R1.2): a restart is exactly
5813
5836
  // when a leak's cards are most at risk — remediation rotates keys and
5814
5837
  // restarts the pool, and the in-memory flag would vanish mid-remediation.
@@ -6018,6 +6041,7 @@ export class AccountManager {
6018
6041
  // persistence, re-auth, disk sync) can never resolve to a mirror row.
6019
6042
  a.accountUuid = null;
6020
6043
  a.remoteUuid = ra.accountUuid || null;
6044
+ a.remoteOrganizationUuid = ra.organizationUuid || null;
6021
6045
  a.provider = ra.provider || a.provider;
6022
6046
  a.quota = { ...emptyQuota(), ...(ra.quota || {}) };
6023
6047
  a.status = ra.status || 'active';
@@ -6332,6 +6356,7 @@ export class AccountManager {
6332
6356
  // fingerprint. Without these a linked pool can't see a duplicate Claude login
6333
6357
  // (live-rehearsal 2026-10-29: status omitted accountUuid → no bench).
6334
6358
  accountUuid: a.type === 'oauth' ? (a.accountUuid || null) : null,
6359
+ organizationUuid: a.type === 'oauth' ? (a.organizationUuid || null) : null,
6335
6360
  keyFingerprint: (a.type === 'provider' && a.credential) ? credentialFp(a.credential) : null,
6336
6361
  // Plan config (display-only) + this pool's closed cycles per window so a linked
6337
6362
  // pool can UNION history instead of picking one ledger (bounded: 12 weekly /
@@ -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
@@ -42,7 +42,7 @@ net.setDefaultAutoSelectFamilyAttemptTimeout(
42
42
  );
43
43
  import { Prober } from './prober.js';
44
44
  import { CapacityLedger } from './capacity-ledger.js';
45
- import { loginOAuth, fetchProfile, refreshAccessToken, isTokenExpiringSoon, tokenFingerprint, isLoginCancelled } from './oauth.js';
45
+ import { loginOAuth, fetchProfile, refreshAccessToken, isTokenExpiringSoon, tokenFingerprint, isLoginCancelled, sameAccountIdentity, organizationUnknownMatch, resolveOrganizations, suggestAccountName, knownDifferentOrg } from './oauth.js';
46
46
  import { TUI, writeTerminalSync, reclaimRawModeLogged, whenTerminalCaughtUp } from './tui.js';
47
47
  import { createTerminalModeSwitcher } from './terminal-mode.js';
48
48
  import { RestartController } from './restart-controller.js';
@@ -939,8 +939,7 @@ async function serverWorkerCommand() {
939
939
  // Pick up any new accounts from disk so index matching stays correct
940
940
  // (only add, don't refresh credentials — we're about to write the authoritative tokens)
941
941
  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);
942
+ const known = config.accounts.some(a => sameAccountIdentity(a, diskAcct) || nameMatches(a, diskAcct));
944
943
  if (!known) {
945
944
  config.accounts.push(diskAcct);
946
945
  accountManager.addAccount(diskAcct);
@@ -1423,7 +1422,7 @@ async function serverWorkerCommand() {
1423
1422
  // Use live tokens from AccountManager (not the stale config.accounts copy).
1424
1423
  diskConfig.accounts = config.accounts.map(a => {
1425
1424
  const am = accountManager.accounts.find(candidate =>
1426
- (a.accountUuid && candidate.accountUuid === a.accountUuid) || candidate.name === a.name
1425
+ sameAccountIdentity(candidate, a) || nameMatches(candidate, a)
1427
1426
  );
1428
1427
  const live = am ? {
1429
1428
  ...a,
@@ -1432,7 +1431,7 @@ async function serverWorkerCommand() {
1432
1431
  expiresAt: am.expiresAt,
1433
1432
  } : a;
1434
1433
  const diskAcct = diskConfig.accounts.find(
1435
- d => (a.accountUuid && d.accountUuid === a.accountUuid) || d.name === a.name
1434
+ d => sameAccountIdentity(d, a) || nameMatches(d, a)
1436
1435
  );
1437
1436
  return diskAcct ? { ...diskAcct, ...live } : live;
1438
1437
  });
@@ -1990,7 +1989,8 @@ async function loginOAuthCommand() {
1990
1989
  // Cloud-aware: a linked team pool with a usable key may receive the login instead.
1991
1990
  // Profile FIRST (once): a local match must win over the cloud default.
1992
1991
  const profile = await fetchProfile(creds.accessToken);
1993
- const localMatch = (profile?.accountUuid && config.accounts.find(a => a.type === 'oauth' && a.accountUuid === profile.accountUuid))
1992
+ const localMatch = (profile?.accountUuid && config.accounts.find(a => a.type === 'oauth' && sameAccountIdentity(a, profile)))
1993
+ || (profile?.accountUuid && organizationUnknownMatch(config.accounts, profile))
1994
1994
  || (profile?.email && config.accounts.find(a => a.type === 'oauth' && a.name === profile.email))
1995
1995
  || null;
1996
1996
  const { usable, unresolved, error } = await resolveUsablePools(config.pools, async (names) => {
@@ -2304,23 +2304,28 @@ async function accountsCommand() {
2304
2304
  )
2305
2305
  );
2306
2306
 
2307
- // Deduplicate by accountUuid — keep the last (most recently added) entry
2307
+ // Deduplicate by user + organization — keep the last (most recently added) entry
2308
2308
  const seen = new Map();
2309
2309
  let removed = 0;
2310
2310
  for (let i = config.accounts.length - 1; i >= 0; i--) {
2311
2311
  const a = config.accounts[i];
2312
2312
  const uuid = profiles[i]?.accountUuid || a.accountUuid;
2313
- if (uuid) {
2314
- if (seen.has(uuid)) {
2313
+ const org = profiles[i]?.organizationUuid || a.organizationUuid || '';
2314
+ const identity = uuid ? `${uuid}/${org}` : null;
2315
+ if (identity) {
2316
+ if (seen.has(identity)) {
2315
2317
  config.accounts.splice(i, 1);
2316
2318
  profiles.splice(i, 1);
2317
2319
  removed++;
2318
2320
  } else {
2319
- seen.set(uuid, i);
2320
- // Update stored UUID and name from profile
2321
+ seen.set(identity, i);
2322
+ // Update stored UUIDs and name from profile. Two organizations of one user
2323
+ // share the email, so the name is only taken when no other account has it.
2321
2324
  if (profiles[i] && !profiles[i].error) {
2322
2325
  a.accountUuid = profiles[i].accountUuid;
2323
- if (profiles[i].email) a.name = profiles[i].email;
2326
+ a.organizationUuid = profiles[i].organizationUuid;
2327
+ const email = profiles[i].email;
2328
+ if (email && !config.accounts.some((other, j) => j !== i && other.name === email)) a.name = email;
2324
2329
  }
2325
2330
  }
2326
2331
  }
@@ -2526,30 +2531,31 @@ async function upsertOAuthAccount(config, name, creds, source = 'unknown', prefe
2526
2531
  if (!profileOk) {
2527
2532
  console.error(`Warning: could not fetch account profile — ${profile?.error || 'no token'}`);
2528
2533
  }
2534
+ if (profileOk) await resolveOrganizations(config.accounts.filter(a => a.type === 'oauth'), profile.accountUuid);
2535
+ const uncertain = profileOk && !name ? organizationUnknownMatch(config.accounts, profile) : null;
2536
+ if (uncertain) {
2537
+ name = uncertain.name;
2538
+ 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>.`);
2539
+ }
2529
2540
  if (!name && profile?.email) {
2530
- name = profile.email;
2531
2541
  const tier = profile.hasClaudeMax ? 'Max' : profile.hasClaudePro ? 'Pro' : null;
2532
2542
  if (tier) console.log(`Detected Claude ${tier} account: ${profile.email}`);
2533
2543
  }
2534
- if (!name) {
2535
- const n = config.accounts.filter(a => a.name.startsWith('account-')).length + 1;
2536
- name = `account-${n}`;
2537
- }
2544
+ if (!name) name = suggestAccountName(config.accounts, profile);
2538
2545
 
2539
2546
  const account = {
2540
2547
  name,
2541
2548
  type: 'oauth',
2542
2549
  source,
2543
2550
  accountUuid: profile?.accountUuid || null,
2551
+ organizationUuid: profile?.organizationUuid || null,
2544
2552
  accessToken: creds.accessToken,
2545
2553
  refreshToken: creds.refreshToken,
2546
2554
  expiresAt: creds.expiresAt,
2547
2555
  };
2548
2556
 
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;
2557
+ // Deduplicate: match by user + organization first, then by name
2558
+ let idx = config.accounts.findIndex(a => sameAccountIdentity(a, account));
2553
2559
  if (idx < 0) idx = config.accounts.findIndex(a => a.name === name);
2554
2560
 
2555
2561
  if (idx >= 0) {
@@ -2567,13 +2573,17 @@ async function upsertOAuthAccount(config, name, creds, source = 'unknown', prefe
2567
2573
  // ── config sync helpers ─────────────────────────────────────
2568
2574
 
2569
2575
  /**
2570
- * Find a config account entry matching an in-memory account (by UUID, then name).
2576
+ * Find a config account entry matching an in-memory account (by user + organization,
2577
+ * then name).
2571
2578
  */
2579
+ // Name fallback must never cross organizations: a same-user row with a KNOWN,
2580
+ // DIFFERENT organization owns its name and its tokens.
2581
+ function nameMatches(a, diskAcct) {
2582
+ return a.name === diskAcct.name && !knownDifferentOrg(a, diskAcct);
2583
+ }
2572
2584
  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
- }
2585
+ const idx = diskConfig.accounts.findIndex(a => sameAccountIdentity(a, account));
2586
+ if (idx >= 0) return idx;
2577
2587
  return diskConfig.accounts.findIndex(a => a.name === account.name);
2578
2588
  }
2579
2589
 
@@ -2585,9 +2595,7 @@ function findConfigAccount(diskConfig, account) {
2585
2595
  async function syncAccountsFromDisk(diskConfig, memConfig, accountManager) {
2586
2596
  let added = 0;
2587
2597
  for (const diskAcct of diskConfig.accounts) {
2588
- const matchByUuid = diskAcct.accountUuid
2589
- ? memConfig.accounts.findIndex(a => a.accountUuid === diskAcct.accountUuid)
2590
- : -1;
2598
+ const matchByUuid = memConfig.accounts.findIndex(a => sameAccountIdentity(a, diskAcct));
2591
2599
  const matchByName = memConfig.accounts.findIndex(a => a.name === diskAcct.name);
2592
2600
  const memIdx = (matchByUuid >= 0 ? matchByUuid : null) ?? (matchByName >= 0 ? matchByName : -1);
2593
2601
 
@@ -2614,9 +2622,10 @@ async function syncAccountsFromDisk(diskConfig, memConfig, accountManager) {
2614
2622
 
2615
2623
  // Find the corresponding AccountManager entry and update credentials
2616
2624
  const mgr = accountManager.accounts.find(a =>
2617
- (diskAcct.accountUuid && a.accountUuid === diskAcct.accountUuid) || a.name === diskAcct.name
2625
+ sameAccountIdentity(a, diskAcct) || nameMatches(a, diskAcct)
2618
2626
  );
2619
2627
  if (!mgr) continue;
2628
+ if (diskAcct.organizationUuid && !mgr.organizationUuid) mgr.organizationUuid = diskAcct.organizationUuid;
2620
2629
  const enabled = diskAcct.enabled !== false;
2621
2630
  if (mgr.enabled !== enabled) {
2622
2631
  accountManager.setAccountEnabled(mgr.index, enabled);
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/server.js CHANGED
@@ -9,7 +9,7 @@ import { ProviderThinkingScrubber, scrubProviderResponseBody, scrubEnabledFor, f
9
9
  import { writeFile, mkdir } from 'node:fs/promises';
10
10
  import { readFileSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
- import { modelFamily } from './oauth.js';
12
+ import { modelFamily, organizationUnknownMatch, sameAccountIdentity, sameUser } from './oauth.js';
13
13
 
14
14
 
15
15
  const HOP_BY_HOP_HEADERS = new Set([
@@ -460,6 +460,7 @@ export function createProxyServer(accountManager, config, hooks = {}) {
460
460
  try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { body = null; }
461
461
  const acct = body?.account;
462
462
  if (acct && typeof acct.name === 'string') acct.name = safeText(acct.name);
463
+ if (acct && typeof acct.organizationUuid !== 'string') delete acct.organizationUuid;
463
464
  if (!acct || acct.type !== 'oauth' || typeof acct.accountUuid !== 'string' || !acct.accountUuid ||
464
465
  typeof acct.refreshToken !== 'string' || !acct.refreshToken || typeof acct.accessToken !== 'string' || !acct.accessToken) {
465
466
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -467,7 +468,18 @@ export function createProxyServer(accountManager, config, hooks = {}) {
467
468
  return;
468
469
  }
469
470
  const who = caller.name || 'legacy-key';
470
- const amAcct = accountManager.accounts.find(a => a.accountUuid === acct.accountUuid);
471
+ // Exact match (user + org), else the ONE same-user row with no org yet: a
472
+ // login to a pool saved before organizations were recorded re-authenticates
473
+ // that row and stamps the organization onto it, exactly like the local path.
474
+ // Healing, BOTH directions: (a) an org-bearing login into a pool whose row
475
+ // predates orgs re-authenticates that row and stamps the org onto it; (b) an
476
+ // org-less login from an OLDER client re-authenticates the user's single row
477
+ // (any org) without touching its org. Two rows of the user → ambiguous: add.
478
+ const sameUserRows = accountManager.accounts.filter(a => sameUser(a, acct));
479
+ const amAcct = accountManager.accounts.find(a => sameAccountIdentity(a, acct))
480
+ || (acct.organizationUuid ? organizationUnknownMatch(accountManager.accounts, acct)
481
+ : (sameUserRows.length === 1 ? sameUserRows[0] : null));
482
+ if (amAcct && acct.organizationUuid) amAcct.organizationUuid = acct.organizationUuid;
471
483
  const tokenFields = {
472
484
  accessToken: acct.accessToken,
473
485
  refreshToken: acct.refreshToken,
@@ -485,26 +497,36 @@ export function createProxyServer(accountManager, config, hooks = {}) {
485
497
  if (amAcct.status === 'error') amAcct.status = 'active';
486
498
  appendEventLog(`[Maxpool] Remote re-auth: "${amAcct.name}" (uuid ${acct.accountUuid.slice(0, 8)}) by ${who}`);
487
499
  } else {
488
- const entry = { name: acct.name || acct.accountUuid.slice(0, 8), type: 'oauth', accountUuid: acct.accountUuid, enabled: true, ...tokenFields };
500
+ const entry = newInjectedEntry(acct, tokenFields, accountManager.accounts);
501
+ acct.name = entry.name; // the disk row and config mirror below take the same unique name
489
502
  accountManager.addAccount(entry);
490
503
  appendEventLog(`[Maxpool] Remote add: "${entry.name}" (uuid ${acct.accountUuid.slice(0, 8)}) by ${who}`);
491
504
  }
492
505
  try {
493
506
  await atomicConfigUpdate(diskConfig => {
494
- const onDisk = diskConfig.accounts.find(a => a.accountUuid === acct.accountUuid);
507
+ let onDisk = diskConfig.accounts.find(a => sameAccountIdentity(a, acct));
508
+ if (!onDisk && acct.organizationUuid) onDisk = organizationUnknownMatch(diskConfig.accounts, acct);
509
+ if (!onDisk && !acct.organizationUuid) onDisk = diskConfig.accounts.filter(a => sameUser(a, acct)).length === 1
510
+ ? diskConfig.accounts.find(a => sameUser(a, acct)) : null;
495
511
  if (onDisk) {
496
512
  Object.assign(onDisk, tokenFields);
513
+ if (acct.organizationUuid) onDisk.organizationUuid = acct.organizationUuid;
497
514
  } else {
498
- diskConfig.accounts.push({ name: acct.name || acct.accountUuid.slice(0, 8), type: 'oauth', accountUuid: acct.accountUuid, enabled: true, ...tokenFields });
515
+ diskConfig.accounts.push(newInjectedEntry(acct, tokenFields, diskConfig.accounts));
499
516
  }
500
517
  });
501
518
  // Keep the in-memory config mirror in step so a later TUI saveConfig
502
519
  // can't clobber the fresh tokens with stale ones.
503
520
  // A NEW row must enter the mirror too: the disk sync adds any disk row whose
504
521
  // uuid the mirror lacks, so a missing entry became a second live row.
505
- const mem = (config.accounts || []).find(a => a.accountUuid === acct.accountUuid);
506
- if (mem) Object.assign(mem, tokenFields);
507
- 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 });
522
+ let mem = (config.accounts || []).find(a => sameAccountIdentity(a, acct));
523
+ if (!mem && acct.organizationUuid) mem = organizationUnknownMatch(config.accounts || [], acct);
524
+ if (!mem && !acct.organizationUuid) mem = (config.accounts || []).filter(a => sameUser(a, acct)).length === 1
525
+ ? (config.accounts || []).find(a => sameUser(a, acct)) : null;
526
+ if (mem) {
527
+ Object.assign(mem, tokenFields);
528
+ if (acct.organizationUuid) mem.organizationUuid = acct.organizationUuid;
529
+ } else if (Array.isArray(config.accounts)) config.accounts.push(newInjectedEntry(acct, tokenFields, config.accounts));
508
530
  } catch (err) {
509
531
  // A single-use credential write is only "ok" when it is DURABLE: the browser
510
532
  // login may have invalidated the previous refresh token, so memory-only means
@@ -755,6 +777,23 @@ export function createProxyServer(accountManager, config, hooks = {}) {
755
777
  /**
756
778
  * Relay a request to upstream with no header rewriting — pure passthrough.
757
779
  */
780
+ /** The account a remote login adds: one Claude user in one organization, plus its tokens. */
781
+ function newInjectedEntry(acct, tokenFields, existing = []) {
782
+ // Two organizations of one user must never share a name: name-keyed lookups
783
+ // (disk sync, config writer) would write one org's tokens over the other's.
784
+ let name = acct.name || acct.accountUuid.slice(0, 8);
785
+ if (existing.some(a => !sameAccountIdentity(a, acct) && a.name === name)) {
786
+ const type = String(acct.orgType || '').replace(/^claude_/, '');
787
+ const suffix = type || '2';
788
+ let n = 2;
789
+ while (existing.some(a => a.name === `${name} (${suffix}${n > 2 ? ' ' + n : ''})`)) n++;
790
+ name = `${name} (${suffix}${n > 2 ? ' ' + n : ''})`;
791
+ }
792
+ const entry = { name, type: 'oauth', accountUuid: acct.accountUuid, enabled: true, ...tokenFields };
793
+ if (acct.organizationUuid) entry.organizationUuid = acct.organizationUuid;
794
+ return entry;
795
+ }
796
+
758
797
  async function relayRaw(req, res, upstream) {
759
798
  const bodyChunks = [];
760
799
  for await (const chunk of req) bodyChunks.push(chunk);
package/src/tui.js CHANGED
@@ -2,7 +2,7 @@ import { createInterface } from 'node:readline';
2
2
  import { readFileSync, writeSync } from 'node:fs';
3
3
  import { isatty } from 'node:tty';
4
4
  import { homedir } from 'node:os';
5
- import { fetchProfile, loginOAuth, tokenFingerprint, isLoginCancelled } from './oauth.js';
5
+ import { fetchProfile, loginOAuth, tokenFingerprint, isLoginCancelled, sameUser, sameAccountIdentity, organizationUnknownMatch, resolveOrganizations, suggestAccountName, knownDifferentOrg } from './oauth.js';
6
6
  import { appendEventLog, setConsoleStdoutSuppressed } from './event-log.js';
7
7
  import { sendLoginToPool } from './cloud-login.js';
8
8
  import { describeLinkError } from './pool-link.js';
@@ -140,8 +140,8 @@ const vw = s => strip(s).length;
140
140
  // ── Accounts-table columns ───────────────────────────────────
141
141
  // Fixed column widths shared by the header row (acctHeader) AND every data row, so
142
142
  // the header labels stay aligned with the columns they name. The Account/Provider/
143
- // Status/Quota start offsets (4/25/35/49) are pure functions of these widths + the
144
- // 4-col row prefix, independent of the quota-bar width.
143
+ // Status/Rst/Quota start offsets (4/25/35/49/56) are pure functions of these widths +
144
+ // the 4-col row prefix, independent of the quota-bar width.
145
145
  const NAME_W = 20; // a.name.slice(0, NAME_W).padEnd(NAME_W) — fits a full email like 2solarmax@gmail.com (19)
146
146
  const WHERE_W = 5; // 'Local' / 'Cloud' — where the account is provisioned
147
147
  const PROVIDER_W = 9; // providerLabel(a).padEnd(PROVIDER_W) — fits "Anthropic"
@@ -171,8 +171,8 @@ function providerLabel(a) {
171
171
 
172
172
  /**
173
173
  * Aligned column header for the accounts table. Names the three columns that carry
174
- * NO inline label (Account / Type / Status) plus a group label over the two quota
175
- * bars (Quota). The per-bar naming (Ses/Wk for OAuth, Tok/Req for API keys) and the
174
+ * NO inline label (Account / Type / Status) plus a group label over the quota bars
175
+ * (Quota). The per-bar naming (Ses/Fbl/Wk for OAuth, Tok/Fbl/Req for API keys) and the
176
176
  * load fields (Now/15m/1h) stay inline per row — they're row-type-dependent and
177
177
  * begin at a variable offset — so the header stops after the Quota group label.
178
178
  */
@@ -193,6 +193,45 @@ function lpadVis(s, w) {
193
193
  return gap > 0 ? ' '.repeat(gap) + s : s;
194
194
  }
195
195
 
196
+ /**
197
+ * Which quota bars fit a terminal W columns wide, and how wide each bar is. The
198
+ * space before the first bar comes from the column widths above, never from a
199
+ * hard-coded number (the old number went stale when the Rst column was added).
200
+ * Each extra bar costs its label gap (" Fbl " or " Wk ") plus one bar width.
201
+ * Under 70 columns only the session bar shows, 5 to 20 wide; from 70 the weekly
202
+ * bar joins it, both 5 to 20 wide. The Fable bar joins only once all three can be
203
+ * 9 wide (112 columns), the narrowest bar that still shows "100% 2d5h", and three
204
+ * bars stop growing at 11 wide, so the row never passes column 118 and the tags
205
+ * after the bars (cap, prefer, staleness) keep the room they have with two bars.
206
+ * Narrower terminals keep today's two bars plus the "Fable NN%" tag.
207
+ * When no account reports a session window, the session bar is left out: the
208
+ * weekly bar always shows and the Fable bar joins it from 97 columns.
209
+ */
210
+ const BAR_START = ROW_PREFIX.length + NAME_W + 1 + WHERE_W + 1 + PROVIDER_W + 1 + STATUS_W + 1 + RESETS_W + 1 + 'Ses '.length;
211
+ const BAR_GAP = ' Wk '.length;
212
+ const BAR_MIN_W = 5;
213
+ const BAR_MAX_W = 20;
214
+ const FABLE_BAR_MIN_W = 9;
215
+ const THREE_BAR_MAX_W = 11;
216
+ function barLayout(W, showSession = true) {
217
+ const showBoth = W >= 70 || !showSession;
218
+ const others = (showSession ? 1 : 0) + (showBoth ? 1 : 0);
219
+ const showFable = W >= BAR_START + (others + 1) * FABLE_BAR_MIN_W + others * BAR_GAP;
220
+ const bars = others + (showFable ? 1 : 0);
221
+ const free = W - BAR_START - (bars - 1) * BAR_GAP;
222
+ const fit = Math.floor(free / bars);
223
+ const maxW = bars === 3 ? THREE_BAR_MAX_W : BAR_MAX_W;
224
+ const bw = Math.max(BAR_MIN_W, Math.min(maxW, fit));
225
+ return { showSession, showBoth, showFable, bw };
226
+ }
227
+
228
+ /** True when the account's first bar (Ses, or Tok for an API key) has a reading. */
229
+ function hasSessionReading(a) {
230
+ const q = a?.quota || {};
231
+ if (a?.type === 'provider') return q.providerSes != null;
232
+ return q.unified5h != null || (q.tokensLimit != null && q.tokensRemaining != null);
233
+ }
234
+
196
235
  function rpad(s, w) {
197
236
  const gap = w - vw(s);
198
237
  return gap > 0 ? s + ' '.repeat(gap) : s;
@@ -541,6 +580,20 @@ function emptyBar(label, w = 10) {
541
580
  return `${ESC}100m${' '.repeat(lp)}${text}${' '.repeat(rp)}${RESET}`;
542
581
  }
543
582
 
583
+ /**
584
+ * The "Fbl" bar: one model family's weekly limit, which Anthropic counts separately
585
+ * from the account-wide weekly. Drawn with the same bar() as Ses and Wk, so it reads
586
+ * the same way (used% and time to reset). Shows the empty dash cell when there is
587
+ * nothing to show: a provider row, no probe result yet, or a limit Anthropic marks
588
+ * as inactive. Routing
589
+ * and the "Fable NN%" tag ignore an inactive limit too, so the bar stays quiet as well.
590
+ */
591
+ function scopedWeeklyBar(quota, family, w) {
592
+ const e = quota?.scopedWeekly?.[family];
593
+ if (!e || e.isActive === false || e.utilization == null) return emptyBar('—', w);
594
+ return bar(e.utilization, w, e.resetAt);
595
+ }
596
+
544
597
  /** Write a provider's enabled flag into the CONFIG entry `loadConfigProviders` reads.
545
598
  *
546
599
  * A config-sourced provider is re-created from config on every reload
@@ -562,7 +615,7 @@ export function applyProviderEnabledToConfig(config, name, enabled) {
562
615
  return { changed: true, previous };
563
616
  }
564
617
 
565
- export const __tuiTest = { applyProviderEnabledToConfig, formatReset, quotaLabel, bar, emptyBar, strip, loadText, countdown, acctHeader, fitLine, providerLabel, weeklyPolicyText, capText, capEffectivePct };
618
+ export const __tuiTest = { applyProviderEnabledToConfig, formatReset, quotaLabel, bar, emptyBar, scopedWeeklyBar, barLayout, strip, loadText, countdown, acctHeader, fitLine, providerLabel, weeklyPolicyText, capText, capEffectivePct };
566
619
 
567
620
  function timestamp() {
568
621
  return new Date().toLocaleTimeString('en-US', { hour12: false });
@@ -1160,7 +1213,7 @@ export class TUI {
1160
1213
  } else if (k === 'l') {
1161
1214
  this._confirm(
1162
1215
  'Log in / re-authenticate via browser?',
1163
- 'Opens a browser. Logging into an account that\'s already added RE-AUTHENTICATES it in place (revives a reauth/error account) — no duplicate. Otherwise a new account is added.',
1216
+ 'Opens a browser. Logging into an account that\'s already added (same user, same organization) RE-AUTHENTICATES it in place (revives a reauth/error account) — no duplicate. Another organization of the same user, or a new user, is added as a new account.',
1164
1217
  () => this._doLogin(),
1165
1218
  );
1166
1219
  } else if (k === 'n' && this.am.accounts.length > 0) {
@@ -1200,7 +1253,7 @@ export class TUI {
1200
1253
  this.mode = 'accounts';
1201
1254
  this._confirm(
1202
1255
  'Log in / re-authenticate via browser?',
1203
- 'Opens a browser. Logging into an account that is already added RE-AUTHENTICATES it in place — no duplicate.',
1256
+ 'Opens a browser. Logging into an account that is already added (same user, same organization) RE-AUTHENTICATES it in place — no duplicate. Another organization of the same user is added as a new account.',
1204
1257
  () => this._doLogin(),
1205
1258
  );
1206
1259
  return;
@@ -1731,7 +1784,7 @@ export class TUI {
1731
1784
  }
1732
1785
 
1733
1786
  // Browser OAuth login — the SAME flow re-authenticates an existing account (matched
1734
- // by accountUuid) or adds a new one. When the login is for an account already added,
1787
+ // by user + organization) or adds a new one. When the login is for an account already added,
1735
1788
  // we say so, keep its name, and skip the "name this account" prompt — so it's clear
1736
1789
  // it's a RE-AUTH in place (revives a dead-refresh/reauth account), not a duplicate.
1737
1790
  async _doLogin() {
@@ -1771,12 +1824,9 @@ export class TUI {
1771
1824
  // a mirror match → that team pool; a brand-new account with a linked team pool →
1772
1825
  // ask once (default team pool); otherwise the local save path.
1773
1826
  async _routeLogin(creds, profile) {
1774
- const decision = decideLoginTarget({
1775
- mirror: this._findRemoteMirrorFor(profile),
1776
- links: this.am.poolLinks,
1777
- existing: this._findExistingOAuthAccount(profile),
1778
- accountUuid: profile?.accountUuid,
1779
- });
1827
+ const mirror = this._findRemoteMirrorFor(profile);
1828
+ const existing = mirror ? null : await this._matchLogin(profile);
1829
+ const decision = decideLoginTarget({ mirror, links: this.am.poolLinks, existing, accountUuid: profile?.accountUuid });
1780
1830
  if (decision.kind === 'no-uuid') {
1781
1831
  setConsoleStdoutSuppressed(false);
1782
1832
  process.stdout.write("\nCould not read this account's id — the team pool needs it. Nothing was saved; try again.\n");
@@ -1787,14 +1837,14 @@ export class TUI {
1787
1837
  await this._sendLoginToRemote(decision.mirror, creds, profile);
1788
1838
  return;
1789
1839
  }
1790
- const existing = this._findExistingOAuthAccount(profile);
1791
1840
  let name;
1792
1841
  if (existing) {
1793
1842
  process.stdout.write(`\nThis Claude account is already added as "${existing.name}" — re-authenticating it in place (no duplicate).\n`);
1794
1843
  name = existing.name;
1795
1844
  } else {
1796
- const suggested = profile?.email
1797
- || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1845
+ const sibling = this._oauthAccounts().find(a => sameUser(a, profile));
1846
+ if (sibling) process.stdout.write(`\nSame Claude user as "${sibling.name}": adding a second account.\n`);
1847
+ const suggested = suggestAccountName(this.config.accounts, profile);
1798
1848
  let toTeam = false;
1799
1849
  if (decision.kind === 'ask-team') {
1800
1850
  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();
@@ -1835,7 +1885,14 @@ export class TUI {
1835
1885
  // uuid-first matcher cannot alias onto a local account).
1836
1886
  _findRemoteMirrorFor(profile) {
1837
1887
  if (!profile?.accountUuid) return null;
1838
- return this.am.accounts.find(a => a.remote && a.remoteUuid === profile.accountUuid) || null;
1888
+ // Exact match first (user + org). A mirror whose org is unknown (the cloud
1889
+ // pool saved the account before organizations were recorded) still owns the
1890
+ // login when it is the only same-user mirror: re-authenticate it rather than
1891
+ // add a second row. Two known orgs never alias.
1892
+ const mirrors = this.am.accounts.filter(a => a.remote && a.enabled !== false && sameUser({ accountUuid: a.remoteUuid }, profile));
1893
+ return mirrors.find(a => sameAccountIdentity({ accountUuid: a.remoteUuid, organizationUuid: a.remoteOrganizationUuid }, profile))
1894
+ || (profile.organizationUuid && mirrors.filter(a => !a.remoteOrganizationUuid).length === 1
1895
+ ? mirrors.find(a => !a.remoteOrganizationUuid) : null);
1839
1896
  }
1840
1897
 
1841
1898
  // Send a fresh browser login to the linked team pool that OWNS this account
@@ -1955,24 +2012,23 @@ export class TUI {
1955
2012
  }
1956
2013
 
1957
2014
  // Upsert an OAuth account into config + the running manager. Dedupes by
1958
- // accountUuid, then name. Shared by import and browser login.
2015
+ // user + organization, then name. Shared by import and browser login.
1959
2016
  async _upsertOAuthAccount({ creds, profile, name, source, verb = 'Added' }) {
1960
- if (!name) {
1961
- name = profile?.email
1962
- || `account-${this.config.accounts.filter(a => a.name.startsWith('account-')).length + 1}`;
1963
- }
2017
+ if (!name) name = suggestAccountName(this.config.accounts, profile);
1964
2018
  const entry = {
1965
2019
  name, type: 'oauth', source,
1966
2020
  accountUuid: profile?.accountUuid || null,
2021
+ organizationUuid: profile?.organizationUuid || null,
1967
2022
  accessToken: creds.accessToken,
1968
2023
  refreshToken: creds.refreshToken,
1969
2024
  expiresAt: creds.expiresAt,
1970
2025
  };
1971
2026
 
1972
- let idx = entry.accountUuid
1973
- ? this.config.accounts.findIndex(a => a.accountUuid === entry.accountUuid)
1974
- : -1;
1975
- if (idx < 0) idx = this.config.accounts.findIndex(a => a.name === name);
2027
+ // Identity first; the name only picks up rows that cannot carry an identity
2028
+ // (saved before uuids were stored). A row of the SAME USER with a KNOWN,
2029
+ // DIFFERENT organization never matches by name: its tokens are its own.
2030
+ let idx = this.config.accounts.findIndex(a => sameAccountIdentity(a, entry));
2031
+ if (idx < 0) idx = this.config.accounts.findIndex(a => a.name === name && !knownDifferentOrg(a, entry));
1976
2032
 
1977
2033
  if (idx >= 0) {
1978
2034
  const previous = this.config.accounts[idx];
@@ -1987,13 +2043,14 @@ export class TUI {
1987
2043
  // heal disk (persistTokenRefresh's generation guard skips a disk token that
1988
2044
  // != _refreshedFrom), so disk must be made correct right here.
1989
2045
  const amAcct = this.am.accounts.find(account =>
1990
- (entry.accountUuid && account.accountUuid === entry.accountUuid) || account.name === name
2046
+ sameAccountIdentity(account, entry) || (account.name === name && !knownDifferentOrg(account, entry))
1991
2047
  );
1992
2048
  if (amAcct) {
1993
2049
  amAcct.credential = creds.accessToken;
1994
2050
  amAcct.refreshToken = creds.refreshToken;
1995
2051
  amAcct.expiresAt = creds.expiresAt;
1996
2052
  amAcct.accountUuid = entry.accountUuid;
2053
+ amAcct.organizationUuid = entry.organizationUuid;
1997
2054
  amAcct.name = name;
1998
2055
  // Fresh tokens from re-auth revive a dead-refresh account. This in-place
1999
2056
  // update is the actual re-login path (the index.js reconcile sees no change
@@ -2035,15 +2092,84 @@ export class TUI {
2035
2092
  }
2036
2093
  }
2037
2094
 
2095
+ // Decide what a fresh browser-login profile is: an account already in the pool
2096
+ // (re-authenticate in place) or a new one. Same-user entries that do not know
2097
+ // their organization are read first; when one still cannot be read, the user decides.
2098
+ async _matchLogin(profile) {
2099
+ await this._resolveOrganizations(profile);
2100
+ const existing = this._findExistingOAuthAccount(profile);
2101
+ if (this._organizationUnknown(existing, profile)) return this._confirmReauth(existing);
2102
+ return existing;
2103
+ }
2104
+
2105
+ // Fill in the organization of same-user entries that lack one, reading each with
2106
+ // the running account's live token (read only, never refreshed), and mirror the
2107
+ // result to the manager. The upsert that follows persists it.
2108
+ async _resolveOrganizations(profile) {
2109
+ if (!profile?.accountUuid) return;
2110
+ await resolveOrganizations(this._oauthAccounts(), profile.accountUuid, entry => this._liveCredentials(entry));
2111
+ this._mirrorOrganizations(profile);
2112
+ }
2113
+
2114
+ _liveCredentials(entry) {
2115
+ const live = this._runningAccount(entry);
2116
+ return live ? { accessToken: live.credential, expiresAt: live.expiresAt } : entry;
2117
+ }
2118
+
2119
+ _mirrorOrganizations(profile) {
2120
+ const known = this._oauthAccounts().filter(a => sameUser(a, profile) && a.organizationUuid);
2121
+ for (const entry of known) this._mirrorOrganization(entry);
2122
+ }
2123
+
2124
+ _mirrorOrganization(entry) {
2125
+ const live = this._runningAccount(entry);
2126
+ if (live) live.organizationUuid = entry.organizationUuid;
2127
+ }
2128
+
2129
+ _runningAccount(entry) {
2130
+ return this.am.accounts.find(a => a.name === entry.name);
2131
+ }
2132
+
2133
+ _oauthAccounts() {
2134
+ return this.config.accounts.filter(a => a.type === 'oauth');
2135
+ }
2136
+
2038
2137
  // Find an already-configured OAuth account matching a fresh browser-login profile —
2039
- // by accountUuid (primary), then name===email — the SAME precedence _upsertOAuthAccount
2040
- // dedupes on, so the login flow can honestly say "re-authenticating" vs "adding new".
2138
+ // the same user in the same organization; else a same-user entry that does not know
2139
+ // its organization (the login then asks); else, for a profile without a uuid,
2140
+ // name===email; else an entry saved before uuids were stored. The SAME precedence
2141
+ // _upsertOAuthAccount dedupes on, so the login flow can honestly say
2142
+ // "re-authenticating" vs "adding new".
2041
2143
  _findExistingOAuthAccount(profile) {
2042
- const uuid = profile?.accountUuid || null;
2144
+ const accounts = this._oauthAccounts();
2043
2145
  const email = profile?.email || null;
2044
- let acct = uuid ? this.config.accounts.find(a => a.type === 'oauth' && a.accountUuid === uuid) : null;
2045
- if (!acct && email) acct = this.config.accounts.find(a => a.type === 'oauth' && a.name === email);
2046
- return acct || null;
2146
+ if (!profile?.accountUuid) return (email && accounts.find(a => a.name === email)) || null;
2147
+ return accounts.find(a => sameAccountIdentity(a, profile))
2148
+ || organizationUnknownMatch(accounts, profile)
2149
+ || accounts.find(a => !a.accountUuid && a.name === email)
2150
+ || null;
2151
+ }
2152
+
2153
+ // True when the match rests on the user alone: the entry's organization is unknown
2154
+ // while the login names one.
2155
+ _organizationUnknown(existing, profile) {
2156
+ return Boolean(existing?.accountUuid && profile?.organizationUuid && !existing.organizationUuid);
2157
+ }
2158
+
2159
+ // The user decides a same-user login whose organization could not be read: Enter
2160
+ // or r re-authenticates the entry, a adds a second account; anything else asks again.
2161
+ async _confirmReauth(existing) {
2162
+ const choice = await this._askReauthOrAdd(existing.name);
2163
+ if (choice === 'add') return null;
2164
+ if (choice === 'reauth') return existing;
2165
+ return this._confirmReauth(existing);
2166
+ }
2167
+
2168
+ async _askReauthOrAdd(name) {
2169
+ const raw = await this._ask(`Same Claude user as "${name}", organization unknown. Re-authenticate it (r) or add a second account (a)? [r] `);
2170
+ const answer = String(raw || '').trim().toLowerCase();
2171
+ if (['', 'r', 're-authenticate'].includes(answer)) return 'reauth';
2172
+ return ['a', 'add'].includes(answer) ? 'add' : null;
2047
2173
  }
2048
2174
 
2049
2175
  async _doAddKey(apiKey) {
@@ -2096,7 +2222,7 @@ export class TUI {
2096
2222
  _configAccountIndex(account) {
2097
2223
  if (!account) return -1;
2098
2224
  if (account.accountUuid) {
2099
- const byUuid = this.config.accounts.findIndex(candidate => candidate.accountUuid === account.accountUuid);
2225
+ const byUuid = this.config.accounts.findIndex(candidate => sameAccountIdentity(candidate, account));
2100
2226
  if (byUuid >= 0) return byUuid;
2101
2227
  }
2102
2228
  return this.config.accounts.findIndex(candidate => candidate.name === account.name);
@@ -2433,18 +2559,21 @@ export class TUI {
2433
2559
  } else {
2434
2560
  lines.push('');
2435
2561
  // Aligned column header (dim + underline so it reads as chrome, not data). It
2436
- // labels the fixed columns that have no inline label; the Ses/Wk/Tok/Req and
2562
+ // labels the fixed columns that have no inline label; the Ses/Fbl/Wk/Tok/Req and
2437
2563
  // Now/15m/1h labels stay inline per row. It sits DIRECTLY above the rows — the
2438
2564
  // abbreviation glossary is a FOOTER below the rows (a caption), never between
2439
2565
  // the header and the data (a left-aligned sentence there reads as a broken,
2440
2566
  // misaligned second header).
2441
2567
  lines.push(dimUnderline(acctHeader(W)));
2442
- const showBoth = W >= 70;
2443
- // 65/54 = the fixed pre-bar column span (prefix + Account + Provider + Status +
2444
- // gaps); grew by +4 with the wider 20-col Account column (was 61/50 at NAME_W 16).
2445
- const bw = showBoth
2446
- ? Math.max(5, Math.min(20, Math.floor((W - 65) / 2)))
2447
- : Math.max(5, Math.min(20, W - 54));
2568
+ // Sticky: once any account has reported a session window in this run, keep the
2569
+ // Ses column. A window that simply expires on an idle pool nulls its reading
2570
+ // until the next request or probe; dropping and re-adding the column then
2571
+ // would make every bar jump width. Pools that never report one keep it hidden.
2572
+ this._sessionColumnSeen = this._sessionColumnSeen || this.am.accounts.some(hasSessionReading);
2573
+ // Below 70 columns only ONE bar fits: Wk (real data) wins over a latched-but-
2574
+ // expired Ses, so the collapse logic still applies at narrow widths.
2575
+ const latch = W >= 70 ? this._sessionColumnSeen : this.am.accounts.some(hasSessionReading);
2576
+ const { showSession, showBoth, showFable, bw } = barLayout(W, latch);
2448
2577
 
2449
2578
  // Claude/OAuth accounts first, providers (GLM/Kimi fallback) last — a stable
2450
2579
  // display order over the canonical am.accounts array (which stays untouched so
@@ -2457,7 +2586,7 @@ export class TUI {
2457
2586
  // effectively off (owner 2026-10-29: "should it hide the local ones that are
2458
2587
  // in the cloud... they're effectively disabled as well"). No separate key.
2459
2588
  if (this.hideDisabled && this.am.accounts[i]?.poolBenchedBy) { hidden++; continue; }
2460
- lines.push(this._renderAcct(i, bw, showBoth));
2589
+ lines.push(this._renderAcct(i, bw, showBoth, showFable, showSession));
2461
2590
  }
2462
2591
  if (hidden > 0) {
2463
2592
  lines.push(` ${dim(`… ${hidden} disabled account${hidden === 1 ? '' : 's'} hidden — press h to show`)}`);
@@ -2573,7 +2702,7 @@ export class TUI {
2573
2702
  process.stdout.write(buf);
2574
2703
  }
2575
2704
 
2576
- _renderAcct(idx, bw, showBoth) {
2705
+ _renderAcct(idx, bw, showBoth, showFable = showBoth, showSession = true) {
2577
2706
  let a = this.am.accounts[idx];
2578
2707
  // A row benched by the duplicate guard renders the CLOUD's live copy (status,
2579
2708
  // bars, in-flight, request counts) — never the stale local snapshot. Identity
@@ -2842,7 +2971,7 @@ export class TUI {
2842
2971
  }
2843
2972
 
2844
2973
  if (a.type === 'provider') {
2845
- return this._renderProviderAcct(sel, cur, name, type, status + ' ' + resetsCell, a, bw, showBoth);
2974
+ return this._renderProviderAcct(sel, cur, name, type, status + ' ' + resetsCell, a, bw, showBoth, showFable, showSession);
2846
2975
  }
2847
2976
 
2848
2977
  // Quota ratios — prefer unified (Claude Max), fall back to standard (API key)
@@ -2865,15 +2994,20 @@ export class TUI {
2865
2994
  t2 = t1;
2866
2995
  }
2867
2996
 
2868
- let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${resetsCell} ${l1} ${bar(r1, bw, t1)}`;
2997
+ const bars = [];
2998
+ // The Fable bar comes first, before the session and weekly bars, on every row
2999
+ // type, so each bar starts at the same offset on OAuth, API-key and provider rows.
3000
+ if (showFable) bars.push(`Fbl ${scopedWeeklyBar(q, 'fable', bw)}`);
3001
+ if (showSession) bars.push(`${l1} ${bar(r1, bw, t1)}`);
2869
3002
  if (showBoth) {
2870
3003
  // "no weekly cap on this plan" is a DIFFERENT state from "not read yet", and
2871
3004
  // both render as an empty bar. Say which, so a healthy uncapped account
2872
3005
  // (privacy@gomokka.com, measured 2026-08-06) doesn't read as broken.
2873
- line += (r2 == null && q.weeklyAbsent)
2874
- ? ` ${l2} ${emptyBar('none', bw)}`
2875
- : ` ${l2} ${bar(r2, bw, t2)}`;
3006
+ bars.push((r2 == null && q.weeklyAbsent)
3007
+ ? `${l2} ${emptyBar('none', bw)}`
3008
+ : `${l2} ${bar(r2, bw, t2)}`);
2876
3009
  }
3010
+ let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${resetsCell} ${bars.join(' ')}`;
2877
3011
  const weekly = weeklyPolicyText(this.am, a);
2878
3012
  if (weekly) line += ` ${weekly}`;
2879
3013
  // Per-account SETTINGS (preferred pin, usage cap), whatever the account is
@@ -2906,7 +3040,7 @@ export class TUI {
2906
3040
  // headers don't carry them). If the probe has gone stale, say so — and name the
2907
3041
  // cause (e.g. rate-limited) when a probe failure is on record — rather than imply
2908
3042
  // the last-known value is current.
2909
- line += this._probeHealthNote(a);
3043
+ line += this._probeHealthNote(a, showFable);
2910
3044
  const act = loadText(this._accountLoad(a));
2911
3045
  if (act) line += ` ${dim(act)}`;
2912
3046
  return line;
@@ -2916,7 +3050,7 @@ export class TUI {
2916
3050
  * stale, names the cause from the last recorded probe failure (e.g. a 429 from
2917
3051
  * the usage endpoint) so a self-throttling probe reads as "rate-limited" rather
2918
3052
  * than an unexplained "stale". Leading spaces included so callers append raw. */
2919
- _probeHealthNote(a) {
3053
+ _probeHealthNote(a, showFable = false) {
2920
3054
  // A dead account (reauth / disabled) already surfaces its state in the status
2921
3055
  // column, and its quota reading is frozen and moot — the prober skips it, so a
2922
3056
  // "stale·probe 401" here is just the perpetual echo of the 401 that killed it.
@@ -2930,11 +3064,15 @@ export class TUI {
2930
3064
  // so a BUSY oauth account with a header-fresh reading and no probe-only scoped
2931
3065
  // cap is NOT stale, even if its background probe is 429-throttled. Provider bars
2932
3066
  // and per-model scoped caps ARE probe-only, so for those a stale probe genuinely
2933
- // means stale data → keep flagging.
3067
+ // means stale data → keep flagging. A scoped reading is DISPLAYED when its tag
3068
+ // shows (at or above the reserve floor) or, for Fable, whenever the Fbl bar is on
3069
+ // screen: the bar draws the reading at any level, so a stale low Fbl value must
3070
+ // carry the age marker too.
2934
3071
  const q = a.quota || {};
2935
3072
  const reserveFloor = this.am.scheduler?.weeklyReserveThreshold ?? 0.85; // mirrors _renderAcct's scoped-tag gate
2936
- const hasDisplayedScopedCap = Object.values(q.scopedWeekly || {}).some(
2937
- e => e && e.isActive !== false && e.utilization != null && e.utilization >= reserveFloor);
3073
+ const hasDisplayedScopedCap = Object.entries(q.scopedWeekly || {}).some(([family, e]) =>
3074
+ e && e.isActive !== false && e.utilization != null
3075
+ && (e.utilization >= reserveFloor || (showFable && family === 'fable')));
2938
3076
  if (a.type !== 'provider' && !hasDisplayedScopedCap) {
2939
3077
  const interval = this.am.quotaProbeIntervalMs; // > 0 here (else _quotaProbeStale returned false)
2940
3078
  const headerFresh = q.lastHeaderQuotaAt && (Date.now() - q.lastHeaderQuotaAt) <= Math.max(3 * interval, 180_000);
@@ -2971,7 +3109,7 @@ export class TUI {
2971
3109
  return interval > 0 ? `every ${formatAge(interval)}` : 'shortly';
2972
3110
  }
2973
3111
 
2974
- _renderProviderAcct(sel, cur, name, type, status, a, bw = 11, showBoth = true) {
3112
+ _renderProviderAcct(sel, cur, name, type, status, a, bw = 11, showBoth = true, showFable = showBoth, showSession = true) {
2975
3113
  const q = a.quota || {};
2976
3114
 
2977
3115
  // Ses/Wk bars in the SAME columns as OAuth rows (right after status) so the
@@ -3029,8 +3167,11 @@ export class TUI {
3029
3167
  // setting whenever the probe is quiet is how a shipped feature reads as absent.
3030
3168
  for (const tag of settingsTags(this.am, a)) note += ` ${tag}`;
3031
3169
 
3032
- let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} Ses ${sesCell}`;
3033
- if (showBoth) line += ` Wk ${wkCell}`;
3170
+ const bars = [];
3171
+ if (showFable) bars.push(`Fbl ${scopedWeeklyBar(q, 'fable', bw)}`);
3172
+ if (showSession) bars.push(`Ses ${sesCell}`);
3173
+ if (showBoth) bars.push(`Wk ${wkCell}`);
3174
+ let line = ` ${sel}${cur} ${name} ${whereCell(a)} ${type} ${status} ${bars.join(' ')}`;
3034
3175
  line += note;
3035
3176
  // Same recent-load columns as OAuth (providers track inFlight + load events),
3036
3177
  // plus a compact Last <status> <ms> — the one signal that matters for a