maxpool 1.24.93 → 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.93",
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,14 +1,14 @@
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';
5
5
  import { CapacityLedger, TANK_MIN_UTIL, mergeCycles, tankStatsFromCycles } from './capacity-ledger.js';
6
6
  // A1: the ONE shared grant-scope answer (display, routing, claim and lift all read it).
7
- import { appliesTo, forgetClaimOrg } from './claude-reset-grants.js';
8
- import { POLICY, CLAUDE_WALL_WEEKLY, probeSentAt } from './reset-policy.js';
7
+ import { appliesTo, clearsGeneralWeekly, forgetClaimOrg } from './claude-reset-grants.js';
8
+ import { POLICY, CLAUDE_WALL_WEEKLY, probeSentAt, wallClaimHeld, HOLD_POOL_HAS_ROOM } from './reset-policy.js';
9
9
  import {
10
10
  LISTING_FRESH_MS, LIFT_GRACE_MS, CLAIM_STALE_LISTING_MAX_MS, CLAIM_BACKOFF_STEPS_MS,
11
- CLAIM_BACKOFF_CAP_MS, REACTIVE_CLAIM_TIMEOUT_MS,
11
+ CLAIM_BACKOFF_CAP_MS, REACTIVE_CLAIM_TIMEOUT_MS, CLAIM_FRESH_MS,
12
12
  } from './reset-timing.js';
13
13
 
14
14
  // Review r2 A: consecutive request-scoped faults before they count against the account.
@@ -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,
@@ -3449,6 +3450,113 @@ export class AccountManager {
3449
3450
  * - ramp: ease a just-recovered account back in instead of slamming it
3450
3451
  * - failures: direct per-account backoff after errors
3451
3452
  */
3453
+ /** R7 (owner, 2026-11-13 — task-2026-11-13-maxpool-hold-resets-when-pool-has-room):
3454
+ * how many OTHER accounts in THIS pool have room to absorb the load while the
3455
+ * GENERAL weekly wall claim waits for the account's free weekly refill (< 24h
3456
+ * out). General only (red-team r3): model walls are never held, so there is no
3457
+ * per-model count. The number
3458
+ * feeds decideClaudeWithReason's hold gate (opts.peersWithRoom), so it must be
3459
+ * computed LIVE from current account state — the hold re-evaluates every sweep.
3460
+ * Conservative per peer: only a probe-FRESH (≤ CLAIM_FRESH_MS) reading counts,
3461
+ * every disqualifier means "cannot confirm room" (claim, never hold on a guess):
3462
+ * - serves the SAME traffic (red-team r3 #4, r4 #5): counted PER routing profile
3463
+ * self serves, by the router's own _matchesProfile, and the THINNEST profile
3464
+ * decides — every kind of traffic the walled account carries needs its own
3465
+ * roomy peers (a peer serving only 'all' takes none of its 'claude' requests).
3466
+ * A self that serves no profile has no confirmed room (0).
3467
+ * - routable NOW: enabled, not throttled/error/exhausted, not pool-benched
3468
+ * (another process owns it), not a remote mirror (routed by its holder pool),
3469
+ * not auth/subscription-dead.
3470
+ * - weekly util (unified7d) leaves ≥ POLICY.holdPeerWeeklyRoom to the peer's
3471
+ * weekly ceiling — its effective usage cap, else 1.0 (uncapped: below the 0.65
3472
+ * `soft` tier the router already spreads load at). Red-team #4: room is
3473
+ * measured to the CAP, so a 0.70 cap at 0.64 is not room.
3474
+ * - 5h util (unified5h) leaves ≥ POLICY.holdPeerSessionRoom to the peer's
3475
+ * session bench (_sessionBenchThreshold: its 5h cap, else the 0.90 switch
3476
+ * threshold) — a session-benched account absorbs nothing.
3477
+ * - a DIFFERENT identity (accountUuid/credential fingerprint) — not this same
3478
+ * account under a second name; peers sharing one capacityIdentity (two local
3479
+ * names for one subscription) count ONCE (red-team #6).
3480
+ * - every ACTIVE model bucket the peer reports also has ≥ holdPeerWeeklyRoom
3481
+ * left (red-team #1) — the walled account serves no model at all, so a peer
3482
+ * whose Fable is exhausted/full (or 429-marked, or unreadable) would leave
3483
+ * Fable with no route for up to a day. An inactive bucket binds nothing (the
3484
+ * router's _scopedExhausted rule).
3485
+ * - a RESOLVABLE identity (red-team r2 #4): a peer whose capacityIdentity is
3486
+ * null is unknown capacity and is not counted; one equal to self's is self
3487
+ * (or self under a second name). Self itself is excluded by the same check —
3488
+ * its identity is either null or its own.
3489
+ * Returns a plain integer (the minimum over self's profiles); the POLICY decides
3490
+ * sufficiency (holdMinPeers × holders). */
3491
+ countPeersWithRoom(self, now = Date.now()) {
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));
3496
+ const selfProfiles = self?.profiles || ['claude', 'all'];
3497
+ const roomLeft = (util, ceiling, room) => Number.isFinite(util) && util <= ceiling - room;
3498
+ const roomy = [];
3499
+ for (const p of this.accounts) {
3500
+ const id = this.capacityIdentity(p);
3501
+ if (id == null || selfGroup.has(p)) continue;
3502
+ if (p.type !== 'oauth' || p.enabled === false) continue;
3503
+ if (p.remote || p.poolBenchedBy) continue;
3504
+ if (p.refreshDead || p.subscriptionGone) continue;
3505
+ if (p.status === 'throttled' || p.status === 'error' || p.status === 'exhausted') continue;
3506
+ if (p.cooldownUntil && p.cooldownUntil > now) continue;
3507
+ const q = p.quota || {};
3508
+ // Probe-fresh only: a peer whose reading predates this sweep's decision is
3509
+ // unknown capacity, and unknown capacity must not hold a claim.
3510
+ const fresh = q.lastProbeOkAt != null && now - q.lastProbeOkAt <= CLAIM_FRESH_MS;
3511
+ if (!fresh) continue;
3512
+ const wkCeiling = this._effectiveCap(p, 'wk', now) ?? 1;
3513
+ if (!roomLeft(q.unified7d, wkCeiling, POLICY.holdPeerWeeklyRoom)) continue;
3514
+ if (!roomLeft(q.unified5h, this._sessionBenchThreshold(p, now), POLICY.holdPeerSessionRoom)) continue;
3515
+ const buckets = Object.values(q.scopedWeekly || {}).filter(e => e && e.isActive !== false);
3516
+ if (buckets.some(e => !roomLeft(e.utilization, 1, POLICY.holdPeerWeeklyRoom))) continue;
3517
+ roomy.push({ p, id });
3518
+ }
3519
+ if (!selfProfiles.length) return 0;
3520
+ return Math.min(...selfProfiles.map(pr =>
3521
+ new Set(roomy.filter(({ p }) => this._matchesProfile(p, pr)).map(({ id }) => id)).size));
3522
+ }
3523
+
3524
+ // ── R7 hold register (red-team r2 #1/#2) ──────────────────────────────────
3525
+ // account._wallHold = { at, refillAt } is stamped whenever either claim path HOLDS the
3526
+ // GENERAL weekly wall (the only wall R7 holds — red-team r3). It is live only
3527
+ // while the hold still describes reality — see isHoldingWall — so a general
3528
+ // claim, the refill or leaving the wall retires it without any clearing code.
3529
+
3530
+ /** Record that `account`'s general weekly wall claim was held, and WHICH refill
3531
+ * it waits for (red-team r4 #4). */
3532
+ noteWallHold(account, now = Date.now()) {
3533
+ if (account) account._wallHold = { at: now, refillAt: account.quota?.unified7dReset ?? null };
3534
+ }
3535
+
3536
+ /** Is `account` holding its general weekly wall RIGHT NOW? A stamped hold that no
3537
+ * claim CLEARING the general weekly has superseded (lastFullGeneralClaimAt before
3538
+ * the stamp — a Fable claim refills nothing the hold waits on, red-team r3 #3; a
3539
+ * give-back claim retires it only through the live reading below, r5 #1), on an
3540
+ * enabled, live (r5 #2), locally-owned account still at the wall with its refill
3541
+ * still ahead — and that refill is still the one it waited for (a later window is
3542
+ * a new wall, not this hold; holdRefillSlackMs absorbs the two sources' reading
3543
+ * precision). */
3544
+ isHoldingWall(account, now = Date.now()) {
3545
+ const h = account?._wallHold;
3546
+ if (!h || account.enabled === false || account.poolBenchedBy) return false;
3547
+ if (account.refreshDead || account.subscriptionGone) return false; // a dead account serves nothing to hold for
3548
+ if (account.lastFullGeneralClaimAt != null && account.lastFullGeneralClaimAt >= h.at) return false;
3549
+ const q = account.quota || {};
3550
+ if (!(q.unified7dReset <= h.refillAt + POLICY.holdRefillSlackMs)) return false;
3551
+ return Number.isFinite(q.unified7d) && q.unified7d >= CLAUDE_WALL_WEEKLY && q.unified7dReset > now;
3552
+ }
3553
+
3554
+ /** The walls a hold must budget for: every OTHER account holding now, plus
3555
+ * `self` (the wall being decided). Feeds wallClaimHeld's holdersInPool. */
3556
+ countHoldingWalls(self, now = Date.now()) {
3557
+ return 1 + this.accounts.filter(a => a !== self && this.isHoldingWall(a, now)).length;
3558
+ }
3559
+
3452
3560
  /**
3453
3561
  * Does this account hold a banked reset that can actually lift its BINDING limit?
3454
3562
  * Claude grants: usable, not paused, unexpired. z.ai cards: unexpired five-hour cards
@@ -4860,7 +4968,7 @@ export class AccountManager {
4860
4968
  * fingerprint (same key shape). null = unresolvable (never merged by name). */
4861
4969
  capacityIdentity(a) {
4862
4970
  if (!a) return null;
4863
- 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 });
4864
4972
  return accountIdentity(a);
4865
4973
  }
4866
4974
 
@@ -4868,7 +4976,19 @@ export class AccountManager {
4868
4976
  capacityGroupOf(a) {
4869
4977
  const id = this.capacityIdentity(a);
4870
4978
  if (!id) return [a];
4871
- 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;
4872
4992
  }
4873
4993
 
4874
4994
  /** Merged closed-cycle history of an account's whole identity: this pool's ledger
@@ -5428,6 +5548,7 @@ export class AccountManager {
5428
5548
  type: acctData.type,
5429
5549
  provider: acctData.provider || (acctData.type === 'provider' ? 'provider' : 'anthropic'),
5430
5550
  accountUuid: acctData.accountUuid || null,
5551
+ organizationUuid: acctData.organizationUuid || null,
5431
5552
  credential: acctData.accessToken || acctData.authToken || acctData.apiKey,
5432
5553
  upstream: acctData.upstream || null,
5433
5554
  authHeader: acctData.authHeader || null,
@@ -5689,11 +5810,17 @@ export class AccountManager {
5689
5810
  return true;
5690
5811
  }
5691
5812
 
5692
- // Match a saved state entry to a live account by stable identity: prefer the
5693
- // 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
+ */
5694
5820
  _sameIdentity(saved, account) {
5695
- if (saved.accountUuid && account.accountUuid) return saved.accountUuid === account.accountUuid;
5696
- 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);
5697
5824
  }
5698
5825
 
5699
5826
  /**
@@ -5704,7 +5831,7 @@ export class AccountManager {
5704
5831
  return this.accounts.filter(a => !a.remote).map(a => {
5705
5832
  const quota = {};
5706
5833
  for (const f of PERSISTED_QUOTA_FIELDS) quota[f] = a.quota[f];
5707
- const out = { accountUuid: a.accountUuid, name: a.name, quota };
5834
+ const out = { accountUuid: a.accountUuid, organizationUuid: a.organizationUuid, name: a.name, quota };
5708
5835
  // OUTSIDE-USAGE flag survives restart (red-team R1.2): a restart is exactly
5709
5836
  // when a leak's cards are most at risk — remediation rotates keys and
5710
5837
  // restarts the pool, and the in-memory flag would vanish mid-remediation.
@@ -5716,6 +5843,14 @@ export class AccountManager {
5716
5843
  // count instead of nothing; restoreQuotaState marks it stale.
5717
5844
  if (a.resetGrants) out.resetGrants = { ...a.resetGrants, grants: (a.resetGrants.grants || []).map(g => ({ ...g })) };
5718
5845
  if (a.resetCards) out.resetCards = { ...a.resetCards, fiveHour: (a.resetCards.fiveHour || []).map(c => ({ ...c })), weekly: (a.resetCards.weekly || []).map(c => ({ ...c })) };
5846
+ // R7 HOLD REGISTER survives restart (red-team r5 #3): the hold and the claim
5847
+ // stamps that retire it / guard one claim per wall. isHoldingWall re-checks the
5848
+ // restored hold against the live wall and refill, so a stale one self-retires.
5849
+ // Unset fields are undefined and drop out of the JSON state file; a hold is
5850
+ // only ever replaced whole (noteWallHold), so sharing the reference is safe.
5851
+ out.wallHold = a._wallHold;
5852
+ out.lastGeneralClaimAt = a.lastGeneralClaimAt;
5853
+ out.lastFullGeneralClaimAt = a.lastFullGeneralClaimAt;
5719
5854
  return out;
5720
5855
  });
5721
5856
  }
@@ -5762,6 +5897,11 @@ export class AccountManager {
5762
5897
  if (match.resetCards && !account.resetCards) {
5763
5898
  account.resetCards = { ...match.resetCards, stale: true };
5764
5899
  }
5900
+ // R7 hold register (r5 #3). Boot-time only (index.js), so nothing live is
5901
+ // overwritten; an absent field restores as undefined, i.e. never stamped.
5902
+ account._wallHold = match.wallHold;
5903
+ account.lastGeneralClaimAt = match.lastGeneralClaimAt;
5904
+ account.lastFullGeneralClaimAt = match.lastFullGeneralClaimAt;
5765
5905
  // OUTSIDE-USAGE restored: keep holding R7 and force the next sweep to
5766
5906
  // re-verify immediately (fresh poolHourly can only re-prove the leak).
5767
5907
  if (match.outsideUsage?.outside) {
@@ -5901,6 +6041,7 @@ export class AccountManager {
5901
6041
  // persistence, re-auth, disk sync) can never resolve to a mirror row.
5902
6042
  a.accountUuid = null;
5903
6043
  a.remoteUuid = ra.accountUuid || null;
6044
+ a.remoteOrganizationUuid = ra.organizationUuid || null;
5904
6045
  a.provider = ra.provider || a.provider;
5905
6046
  a.quota = { ...emptyQuota(), ...(ra.quota || {}) };
5906
6047
  a.status = ra.status || 'active';
@@ -6061,12 +6202,40 @@ export class AccountManager {
6061
6202
  if (!account.credential || account.type !== 'oauth') return false;
6062
6203
  // C6 (finding 1): ONE claim per wall — after a claim, only a probe SENT after
6063
6204
  // it may show the wall again. Repeated 429s on the same wall never re-claim.
6064
- const lastClaimAt = account.lastClaimAt ?? null;
6205
+ // The general wall counts only claims that cleared it (red-team r4 #2): after a
6206
+ // Fable claim under the hold, a dark probe can't move past the account-wide
6207
+ // stamp, and the rescue / weekly 429 must still reach the general reset.
6208
+ const lastClaimAt = (kind === 'weekly' ? account.lastGeneralClaimAt : account.lastClaimAt) ?? null;
6065
6209
  if (lastClaimAt != null && !((probeSentAt(account.quota) ?? -Infinity) > lastClaimAt)) return false;
6066
6210
  // No grant (or a scoped 429 without a probe-measured bucket) → the next sweep
6067
6211
  // decides on its own fresh reading.
6068
6212
  const grant = this._reactiveClaimGrant(account, kind, now);
6069
6213
  if (!grant) return false;
6214
+ // R7 (owner, 2026-11-13): a wall 429 claims a held reset only when the free
6215
+ // refill of the limit it clears ISN'T imminent-with-pool-room — the same
6216
+ // wallClaimHeld rule the sweep uses, so the fast path cannot spend a reset the
6217
+ // sweep deliberately holds. Evaluated DIRECTLY here, not via the sweep's full
6218
+ // decision (red-team #3): at the wall the account's own usage probe and listing
6219
+ // are routinely stale (the usage endpoint 429s), and the sweep's freshness skips
6220
+ // would read as "not held" and fall through to a claim. The hold needs no fresh
6221
+ // reading of THIS account: the refill stamp is kept current by every response's
6222
+ // rate-limit headers (updateQuota), the grant end comes from the stored listing,
6223
+ // and capacity comes from the PEERS' own fresh probes (countPeersWithRoom). A
6224
+ // grant dying before (or within 24h after) the refill never waits. The budget
6225
+ // counts every wall held in this pool right now (r2 #2) and the hold is
6226
+ // registered (r2 #1) so the sweep's rescue can find it again.
6227
+ // GENERAL ONLY (red-team r3): a model (Fable) 429 claims exactly as before R7.
6228
+ if (kind === 'weekly' && wallClaimHeld(account.quota?.unified7dReset, grant, now,
6229
+ { peersWithRoom: () => this.countPeersWithRoom(account, now),
6230
+ holdersInPool: () => this.countHoldingWalls(account, now),
6231
+ listingCheckedAt: account.resetGrants?.checkedAt })) {
6232
+ // Log once per hold EPISODE: the sweep's rescue re-evaluates a held wall every
6233
+ // failed tick, and a line per tick would bury the console.
6234
+ const already = this.isHoldingWall(account, now);
6235
+ this.noteWallHold(account, now);
6236
+ if (!already) console.log(`[reset-grant] ${account.name}: at wall, claim held (${HOLD_POOL_HAS_ROOM})`);
6237
+ return false;
6238
+ }
6070
6239
  // C6: shared backoff per (account, grantId).
6071
6240
  const key = `${account.name}:${grant.id}`;
6072
6241
  const until = this._claimRetryUntil?.get(key);
@@ -6084,6 +6253,12 @@ export class AccountManager {
6084
6253
  if (r?.ok) {
6085
6254
  this.noteClaimSuccess(account.name, grant.id);
6086
6255
  account.lastClaimAt = Date.now();
6256
+ // A spent grant that applies to the general weekly — whatever the 429 kind —
6257
+ // counts as the general wall's claim (r3 #3, r4 #3: one claim per wall). Only
6258
+ // one that CLEARS it retires the hold (r5 #1): a give-back returns just what
6259
+ // the model used, and the live reading retires the hold once a probe sees it.
6260
+ if (appliesTo(grant).includes('general')) account.lastGeneralClaimAt = account.lastClaimAt;
6261
+ if (clearsGeneralWeekly(grant)) account.lastFullGeneralClaimAt = account.lastClaimAt;
6087
6262
  this.noteGrantClaimed(account, grant.id);
6088
6263
  // Clear the wall this claim refills.
6089
6264
  if (kind !== 'weekly' && account.quota?.scopedWeekly?.[kind]) delete account.quota.scopedWeekly[kind];
@@ -6181,6 +6356,7 @@ export class AccountManager {
6181
6356
  // fingerprint. Without these a linked pool can't see a duplicate Claude login
6182
6357
  // (live-rehearsal 2026-10-29: status omitted accountUuid → no bench).
6183
6358
  accountUuid: a.type === 'oauth' ? (a.accountUuid || null) : null,
6359
+ organizationUuid: a.type === 'oauth' ? (a.organizationUuid || null) : null,
6184
6360
  keyFingerprint: (a.type === 'provider' && a.credential) ? credentialFp(a.credential) : null,
6185
6361
  // Plan config (display-only) + this pool's closed cycles per window so a linked
6186
6362
  // pool can UNION history instead of picking one ledger (bounded: 12 weekly /
@@ -80,6 +80,14 @@ export function appliesTo(grant) {
80
80
  return [...out];
81
81
  }
82
82
 
83
+ /** Does spending this grant REFILL the general weekly outright (clears seven_day)?
84
+ * A give-back-only grant also applies to 'general' (appliesTo), but it returns
85
+ * only what one model used — whether that leaves the general wall is known only
86
+ * once a probe measures the drop (red-team r5 #1). */
87
+ export function clearsGeneralWeekly(grant) {
88
+ return Array.isArray(grant?.clears) && grant.clears.includes('seven_day');
89
+ }
90
+
83
91
  // Process-wide: the first listing logs the raw grant KEY SET (keys only, never
84
92
  // values) once, so a schema drift is visible without per-sweep spam. Set by
85
93
  // listResetGrants on the first grants-bearing response.
@@ -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