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 +2 -1
- package/package.json +1 -1
- package/src/account-manager.js +188 -12
- package/src/claude-reset-grants.js +8 -0
- package/src/cloud-login.js +1 -0
- package/src/index.js +39 -30
- package/src/oauth.js +79 -0
- package/src/pool-link.js +60 -11
- package/src/prober.js +51 -9
- package/src/reset-policy.js +94 -9
- package/src/server.js +47 -8
- package/src/tui.js +199 -58
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
|
|
35
|
-
* (an unnamed apikey account can't be matched —
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
65
|
-
if (a.type === 'oauth'
|
|
66
|
-
|
|
67
|
-
|
|
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
|
|
79
|
-
const
|
|
80
|
-
|
|
125
|
+
const ids = identitiesOf(a);
|
|
126
|
+
const wildcard = ids[1];
|
|
127
|
+
const usable = orgCount.get(a.accountUuid) > 1 && wildcard ? ids.slice(0, 1) : ids;
|
|
128
|
+
const hit = usable.map(id => remoteIdentitiesMap.get(id)).find(Boolean);
|
|
129
|
+
if (hit) out.push({ index: a.index, identity: ids[0], remoteName: hit.name, provider: hit.provider });
|
|
81
130
|
}
|
|
82
131
|
return out;
|
|
83
132
|
}
|
package/src/prober.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { fetchUsage, fetchProviderUsage } from './oauth.js';
|
|
11
11
|
import { listResetCards, redeemResetCard, fetchZaiModelUsage } from './zai-reset-cards.js';
|
|
12
12
|
import { listSubscriptions, monthlyPriceUSD } from './zai-subs.js';
|
|
13
|
-
import { listResetGrants, claimResetGrant } from './claude-reset-grants.js';
|
|
13
|
+
import { listResetGrants, claimResetGrant, appliesTo, clearsGeneralWeekly } from './claude-reset-grants.js';
|
|
14
14
|
import { decideZai, decideClaudeWithReason, CLAUDE_WALL_WEEKLY } from './reset-policy.js';
|
|
15
15
|
import { zaiHourlyCalls, compareOutsideUsage, isUsableZaiUsage, OUTSIDE_CHECK_MS } from './outside-usage.js';
|
|
16
16
|
// Reset-machinery timing lives in ONE leaf module (re-exported for callers that
|
|
@@ -22,6 +22,10 @@ export { GRANTS_EVERY_MS, GRANTS_RETRY_MS, CLAIM_BACKOFF_STEPS_MS, CLAIM_BACKOFF
|
|
|
22
22
|
// token refresh per window — cheap, and bounded so a truly canceled plan isn't hammered).
|
|
23
23
|
export const SUB_RECHECK_MS = 30 * 60_000;
|
|
24
24
|
|
|
25
|
+
// The sweep-decision skips that mean "this tick's LISTING can't be trusted" — the
|
|
26
|
+
// only skips after a successful probe that hand a held wall to the rescue (r2 #1).
|
|
27
|
+
const STALE_LISTING_SKIPS = new Set(['listing stale', 'listing failed']);
|
|
28
|
+
|
|
25
29
|
export class Prober {
|
|
26
30
|
constructor(accountManager, { intervalMs = 0, probeFn = fetchUsage, providerProbeFn = fetchProviderUsage, grantsFn = listResetGrants, timeoutMs = 10_000, log = console.log, usageGapMs = null, zaiUsageFn = fetchZaiModelUsage, cardsFn = listResetCards, now = Date.now } = {}) {
|
|
27
31
|
this.am = accountManager;
|
|
@@ -360,6 +364,12 @@ export class Prober {
|
|
|
360
364
|
if (r?.ok) {
|
|
361
365
|
this.am.noteClaimSuccess?.(account.name, act.grant.id);
|
|
362
366
|
account.lastClaimAt = Date.now();
|
|
367
|
+
// A spent grant that applies to the general weekly — whatever scope it was
|
|
368
|
+
// claimed at — is the general wall's claim (r3 #3, r4 #3); only one that
|
|
369
|
+
// CLEARS it retires the hold (r5 #1, same rule as the 429 fast path). A
|
|
370
|
+
// Fable-only grant refills nothing the hold is waiting on.
|
|
371
|
+
if (appliesTo(act.grant).includes('general')) account.lastGeneralClaimAt = account.lastClaimAt;
|
|
372
|
+
if (clearsGeneralWeekly(act.grant)) account.lastFullGeneralClaimAt = account.lastClaimAt;
|
|
363
373
|
// Spend it in the STORED listing too: until the next listing (≤5 min) the
|
|
364
374
|
// held count, the lift and the reactive path must not see it as unspent.
|
|
365
375
|
this.am.noteGrantClaimed?.(account, act.grant.id);
|
|
@@ -481,13 +491,11 @@ export class Prober {
|
|
|
481
491
|
usage = await this._withTimeout(this.probeFn(account.credential));
|
|
482
492
|
}
|
|
483
493
|
}
|
|
484
|
-
if (usage == null) { // timed out
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
this.am.recordProbeError?.(account.index, usage.error, usage.status ?? null);
|
|
490
|
-
return { ok: false, status: usage.status ?? null };
|
|
494
|
+
if (usage == null || usage.error) { // timed out / HTTP error (e.g. 429) / fetch failure
|
|
495
|
+
const e = usage == null ? 'probe timed out' : usage.error;
|
|
496
|
+
this.am.recordProbeError?.(account.index, e, usage?.status ?? null);
|
|
497
|
+
await this._rescueHeldWall(account); // red-team r2 #1: a held wall must not strand
|
|
498
|
+
return { ok: false, status: usage?.status ?? null };
|
|
491
499
|
}
|
|
492
500
|
this.am.applyUsageData(account.index, usage, { sentAt: probeSentAt }); // clears the error + stamps freshness
|
|
493
501
|
// C1: decide the claim on the reading JUST stored (this sweep's probe), on
|
|
@@ -496,6 +504,7 @@ export class Prober {
|
|
|
496
504
|
return { ok: true, status: 200 };
|
|
497
505
|
} catch (e) { // best-effort; never let a probe throw
|
|
498
506
|
this.am.recordProbeError?.(account.index, e?.message || String(e), null);
|
|
507
|
+
await this._rescueHeldWall(account); // red-team r2 #1
|
|
499
508
|
return { ok: false, status: null };
|
|
500
509
|
} finally {
|
|
501
510
|
account._subRecheck = false;
|
|
@@ -509,12 +518,27 @@ export class Prober {
|
|
|
509
518
|
if (!this.am.applyResetGrants) return;
|
|
510
519
|
const listing = account.resetGrants;
|
|
511
520
|
if (!listing) return;
|
|
512
|
-
|
|
521
|
+
// R7 (2026-11-13): the GENERAL weekly wall claim (the only one R7 holds — red-team
|
|
522
|
+
// r3) waits for an imminent free refill only while
|
|
523
|
+
// other accounts in THIS pool have room. Counted LIVE per sweep, so the hold
|
|
524
|
+
// ends the moment capacity disappears; unknown capacity claims (never hold).
|
|
525
|
+
// holdersInPool budgets one hold per holdMinPeers roomy peers across the pool
|
|
526
|
+
// (r2 #2); a hold is registered so a later failed probe can still rescue it (r2 #1).
|
|
527
|
+
const peersWithRoom = this.am.countPeersWithRoom ? () => this.am.countPeersWithRoom(account) : null;
|
|
528
|
+
const holdersInPool = this.am.countHoldingWalls ? () => this.am.countHoldingWalls(account) : null;
|
|
529
|
+
const { action, reason, heldScope } = decideClaudeWithReason(account, listing, Date.now(), { peersWithRoom, holdersInPool });
|
|
530
|
+
// heldScope rides on every return once the general wall is held — a dying model
|
|
531
|
+
// grant claimed in the same decision included (r3 #2) — so the hold is always registered.
|
|
532
|
+
if (heldScope === 'general') this.am.noteWallHold?.(account);
|
|
513
533
|
if (action) {
|
|
514
534
|
account._claimSkipKey = null;
|
|
515
535
|
await this._claimClaudeGrant(account, action);
|
|
516
536
|
return;
|
|
517
537
|
}
|
|
538
|
+
// The probe answered but the stored LISTING is stale/failed (the grants call
|
|
539
|
+
// shares the rate-limited endpoint): the fresh decision can't run, so a held
|
|
540
|
+
// wall goes through the rescue exactly as on a failed probe (r2 #1).
|
|
541
|
+
if (STALE_LISTING_SKIPS.has(reason)) await this._rescueHeldWall(account);
|
|
518
542
|
// C5: at a reached limit with a held-but-unspent grant, say WHY once per
|
|
519
543
|
// (account, reason) change — the owner's live check reads exactly these lines.
|
|
520
544
|
// The reason is the POLICY's own rejection (stale listing, cooldown, already
|
|
@@ -537,6 +561,24 @@ export class Prober {
|
|
|
537
561
|
}
|
|
538
562
|
}
|
|
539
563
|
|
|
564
|
+
/** Red-team r2 #1 — the held-wall rescue. A wall this pool HELD (its stamp is
|
|
565
|
+
* still live) must not strand: while the account's own usage endpoint is dark
|
|
566
|
+
* (a 429'd probe, a timeout, a throw — every early return of probeOne), no fresh
|
|
567
|
+
* decision can be made, yet "capacity unknown" means CLAIM. Re-evaluate the hold
|
|
568
|
+
* directly (wallClaimHeld: header/probe refill stamp, stored listing ≤ 6h,
|
|
569
|
+
* peers' LIVE probe freshness) and claim through the reactive route — the same
|
|
570
|
+
* one the 429 fast path uses, whose pick tolerates a stale listing on purpose.
|
|
571
|
+
* A still-roomy pool keeps holding; a refill that moved past 24h (or a dying
|
|
572
|
+
* grant) makes wallClaimHeld itself release. Never claims a wall nobody held.
|
|
573
|
+
* General weekly wall only (red-team r3): no model wall is ever held. */
|
|
574
|
+
async _rescueHeldWall(account) {
|
|
575
|
+
if (!this.am.isHoldingWall?.(account)) return; // never a wall nobody held
|
|
576
|
+
// A listing-side cooldown is a server instruction the reactive route doesn't read.
|
|
577
|
+
const cd = account.resetGrants?.cooldownUntil;
|
|
578
|
+
if (cd != null && cd > Date.now()) return;
|
|
579
|
+
await this.am.tryReactiveClaim(account, { kind: 'weekly' });
|
|
580
|
+
}
|
|
581
|
+
|
|
540
582
|
_withTimeout(promise) {
|
|
541
583
|
return Promise.race([
|
|
542
584
|
promise,
|
package/src/reset-policy.js
CHANGED
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
* value cannot survive a wait.
|
|
44
44
|
*/
|
|
45
45
|
import { appliesTo as defaultAppliesTo } from './claude-reset-grants.js';
|
|
46
|
-
import { CLAIM_FRESH_MS } from './reset-timing.js';
|
|
46
|
+
import { CLAIM_FRESH_MS, CLAIM_STALE_LISTING_MAX_MS } from './reset-timing.js';
|
|
47
47
|
|
|
48
48
|
export const POLICY = {
|
|
49
49
|
wallWeekly: 0.90, // weekly at 90% = at the wall (z.ai cards; UNCHANGED — pre-mortem #22)
|
|
@@ -53,8 +53,29 @@ export const POLICY = {
|
|
|
53
53
|
dyingMinUtilSes: 0.50, // 5h refills are cheap capacity; demand more waste first
|
|
54
54
|
freeRefillWaitMs: 24 * 3600 * 1000, // R6: hold a wall redeem this close to the free refill
|
|
55
55
|
freeRefillImmediate: 0.98, // R6: ...unless this full — never block the owner
|
|
56
|
+
// R7 (owner, 2026-11-13): the Claude GENERAL weekly wall claim also waits for the
|
|
57
|
+
// free refill when OTHER accounts can absorb the load. Room per peer: probe-fresh
|
|
58
|
+
// (≤5 min) readings, weekly util with ≥ 35% headroom left, 5h util with ≥ 25%
|
|
59
|
+
// headroom to the 0.90 session bench, routable now.
|
|
60
|
+
holdPeerWeeklyRoom: 0.35,
|
|
61
|
+
holdPeerSessionRoom: 0.25,
|
|
62
|
+
holdMinPeers: 2,
|
|
63
|
+
// A hold is tied to the refill it waited for (red-team r4 #4). The same refill is
|
|
64
|
+
// read from two sources with different precision (rate-limit header: whole
|
|
65
|
+
// seconds; usage probe: fractional), so a reading up to this much later is still
|
|
66
|
+
// that refill; a rolled window moves it by days.
|
|
67
|
+
holdRefillSlackMs: 3600 * 1000,
|
|
68
|
+
// The 429 fast path and the rescue claim from the STORED listing, which they
|
|
69
|
+
// refuse past CLAIM_STALE_LISTING_MAX_MS (6h). A hold therefore lets go this long
|
|
70
|
+
// before that bound (red-team r4 #6), while the reset is still claimable — a dark
|
|
71
|
+
// listing is unknown state, and unknown means claim. The rescue runs every sweep.
|
|
72
|
+
holdListingMarginMs: 30 * 60 * 1000,
|
|
56
73
|
};
|
|
57
74
|
|
|
75
|
+
// The plain-words decision reason for an R7 hold — exported so status/log surfaces
|
|
76
|
+
// and tests share one string.
|
|
77
|
+
export const HOLD_POOL_HAS_ROOM = 'free refill <24h away, other accounts have room';
|
|
78
|
+
|
|
58
79
|
// Claude cedar_ember claims read their OWN wall (pre-mortem #22): 0.99, deliberately
|
|
59
80
|
// NOT POLICY.wallWeekly (0.90) which z.ai shares — moving the shared constant would
|
|
60
81
|
// redeem GLM cards at a different point. Claude benches at 0.999 (weeklyExhausted)
|
|
@@ -69,6 +90,34 @@ export { CLAIM_FRESH_MS };
|
|
|
69
90
|
|
|
70
91
|
function msLeft(t, now) { return t == null ? Infinity : t - now; }
|
|
71
92
|
|
|
93
|
+
/** R7 (owner, 2026-11-13): should a GENERAL weekly WALL claim of `grant` wait for the
|
|
94
|
+
* free refill at `refillAt`? GENERAL ONLY (red-team r3, orchestrator decision): a
|
|
95
|
+
* per-model (Fable) wall and a dying-value grant claim exactly as before R7. The ONE
|
|
96
|
+
* hold rule, shared by the sweep (decideClaudeWithReason) and the
|
|
97
|
+
* reactive 429 path (account-manager tryReactiveClaim) so neither can spend what the
|
|
98
|
+
* other holds. Reads only the refill stamp, the grant's end and a LIVE peer count —
|
|
99
|
+
* never the walled account's own usage reading, which is routinely stale at the wall.
|
|
100
|
+
* Conservative: an unknown / past / ≥24h-away refill, a grant that dies before (or
|
|
101
|
+
* within dyingWindowMs after) the refill — it would sit unspent at ~0% used — no
|
|
102
|
+
* counter, or a count that isn't an integer ≥ the pool-wide budget ⇒ false (claim).
|
|
103
|
+
* BUDGET (red-team r2 #2): roomy peers must cover EVERY wall currently held in this
|
|
104
|
+
* pool — holdMinPeers × holdersInPool(), where holdersInPool counts the walls
|
|
105
|
+
* holding now INCLUDING this one. Without a holders counter, this wall alone (1).
|
|
106
|
+
* LISTING AGE (red-team r4 #6): when the caller passes `listingCheckedAt`, a stored
|
|
107
|
+
* listing within holdListingMarginMs of the 6h claim bound — or of unknown age
|
|
108
|
+
* (null) — releases the hold: past that bound the reset could not be claimed at
|
|
109
|
+
* all while the listing stays dark. Both claim paths pass it. */
|
|
110
|
+
export function wallClaimHeld(refillAt, grant, now, { peersWithRoom, holdersInPool, listingCheckedAt } = {}) {
|
|
111
|
+
if (!(refillAt > now) || refillAt - now >= POLICY.freeRefillWaitMs) return false;
|
|
112
|
+
if (listingCheckedAt !== undefined
|
|
113
|
+
&& !(now - listingCheckedAt < CLAIM_STALE_LISTING_MAX_MS - POLICY.holdListingMarginMs)) return false;
|
|
114
|
+
if (grant?.endsAt != null && grant.endsAt - refillAt < POLICY.dyingWindowMs) return false;
|
|
115
|
+
const holders = holdersInPool ? holdersInPool() : 1;
|
|
116
|
+
if (!Number.isInteger(holders) || holders < 1) return false;
|
|
117
|
+
const count = peersWithRoom?.();
|
|
118
|
+
return Number.isInteger(count) && count >= POLICY.holdMinPeers * holders;
|
|
119
|
+
}
|
|
120
|
+
|
|
72
121
|
/** Decide the z.ai action. Returns {kind:'card', card, resetType} | null. */
|
|
73
122
|
export function decideZai(account, cards, now = Date.now()) {
|
|
74
123
|
if (account?.enabled === false) return null; // R0
|
|
@@ -128,8 +177,11 @@ export function probeSentAt(q) {
|
|
|
128
177
|
|
|
129
178
|
/** Decide the Claude action AND say why when there is none.
|
|
130
179
|
* Returns { action: {kind:'grant', grant, scope, giveBack?, reason} | null,
|
|
131
|
-
* reason: string | null } — `reason` names
|
|
132
|
-
* is null (C5: the skip log prints exactly this), or the
|
|
180
|
+
* reason: string | null, heldScope?: string | null } — `reason` names
|
|
181
|
+
* the rejection when action is null (C5: the skip log prints exactly this), or the
|
|
182
|
+
* claim reason; `heldScope` is 'general' whenever the R7 hold kept the general
|
|
183
|
+
* weekly wall unclaimed on this decision — on EVERY return after that point, a claim
|
|
184
|
+
* of a dying model grant included, so the caller always registers the hold (null: none).
|
|
133
185
|
*
|
|
134
186
|
* C1 (amended, 2026-11-10): the claim is decided per grant by appliesTo (D1),
|
|
135
187
|
* NEVER by the server's nextGrantId order alone (pre-mortem #8: a Fable 429 could
|
|
@@ -139,7 +191,20 @@ export function probeSentAt(q) {
|
|
|
139
191
|
* any claim we already made (no second claim for one wall).
|
|
140
192
|
* D4: a dying-value claim (not at the wall) waits when the free refill of the
|
|
141
193
|
* limit it clears is < 24h away; a wall claim never waits (limit effectively full).
|
|
142
|
-
* Session-only grants are NEVER claimed (owner 2026-10-30).
|
|
194
|
+
* Session-only grants are NEVER claimed (owner 2026-10-30).
|
|
195
|
+
* R7 (owner, 2026-11-13, task-2026-11-13-maxpool-hold-resets-when-pool-has-room):
|
|
196
|
+
* the GENERAL weekly WALL claim is HELD when its free refill is < 24h away
|
|
197
|
+
* (freeRefillWaitMs) AND opts.peersWithRoom() answers at least POLICY.holdMinPeers
|
|
198
|
+
* × opts.holdersInPool() — other accounts in THIS pool can absorb the load. Model
|
|
199
|
+
* (Fable) walls are never held (red-team r3) — but while the general wall is held the
|
|
200
|
+
* model WALL claim is skipped too: the account is benched by its general wall, so a
|
|
201
|
+
* Fable reset would buy nothing until the general refill lands — unless that grant
|
|
202
|
+
* would expire before (or within dyingWindowMs after) the refill: then it is claimed. The hold
|
|
203
|
+
* re-evaluates every decision tick (the caller supplies a live count), and fails
|
|
204
|
+
* CLAIM-side: capacity unknown (no counter, non-number answer) or a grant that
|
|
205
|
+
* would expire before the refill (or within a day after it — it would sit unspent
|
|
206
|
+
* at ~0% used) is claimed as today. Dying-value claims stay exempt: an expiring
|
|
207
|
+
* grant's value cannot survive any wait. */
|
|
143
208
|
export function decideClaudeWithReason(account, listing, now = Date.now(), opts = {}) {
|
|
144
209
|
const skip = reason => ({ action: null, reason });
|
|
145
210
|
if (account?.enabled === false) return skip('account disabled'); // R0
|
|
@@ -178,6 +243,14 @@ export function decideClaudeWithReason(account, listing, now = Date.now(), opts
|
|
|
178
243
|
const weeklyWall = wkUtil != null && wkUtil >= CLAUDE_WALL_WEEKLY;
|
|
179
244
|
// D4: the free refill of a limit < 24h away makes a not-at-the-wall spend redundant.
|
|
180
245
|
const refillSoon = resetAt => resetAt != null && msLeft(resetAt, now) < POLICY.freeRefillWaitMs;
|
|
246
|
+
// R7: hold the GENERAL wall claim for the imminent free refill while other accounts
|
|
247
|
+
// in this pool can absorb the load (wallClaimHeld). A hold NOTES its reason and
|
|
248
|
+
// moves on (red-team #2): the model-scoped loop below must still run, so a dying
|
|
249
|
+
// model grant is spent. `generalHeld` rides on every return after it (red-team r3
|
|
250
|
+
// #2) so the caller registers the hold even when this decision claims a dying model
|
|
251
|
+
// grant — it feeds the pool-wide budget and the held-wall rescue (r2 #1/#2).
|
|
252
|
+
let generalHeld = false;
|
|
253
|
+
const out = (action, why) => ({ action, reason: why, heldScope: generalHeld ? 'general' : null });
|
|
181
254
|
let reason = null;
|
|
182
255
|
const note = r => { if (reason == null) reason = r; };
|
|
183
256
|
|
|
@@ -188,16 +261,21 @@ export function decideClaudeWithReason(account, listing, now = Date.now(), opts
|
|
|
188
261
|
for (const g of general) {
|
|
189
262
|
const giveBack = g.givesBackWeekly === true && !(Array.isArray(g.clears) && g.clears.includes('seven_day'));
|
|
190
263
|
if (weeklyWall) {
|
|
264
|
+
// R7: the free refill is imminent and the pool has room — hold the claim.
|
|
265
|
+
if (wallClaimHeld(q.unified7dReset, g, now,
|
|
266
|
+
{ peersWithRoom: opts.peersWithRoom, holdersInPool: opts.holdersInPool, listingCheckedAt: listing.checkedAt })) {
|
|
267
|
+
generalHeld = true; note(HOLD_POOL_HAS_ROOM); continue;
|
|
268
|
+
}
|
|
191
269
|
// A give-back-only grant (no seven_day in clears) returns only what the model
|
|
192
270
|
// used — the claim snapshots unified7d so the next probe measures the drop.
|
|
193
|
-
return {
|
|
271
|
+
return out({ kind: 'grant', grant: g, scope: 'general', giveBack, reason: 'weekly at wall' }, 'weekly at wall');
|
|
194
272
|
}
|
|
195
273
|
const dying = msLeft(g.endsAt, now) < POLICY.dyingWindowMs
|
|
196
274
|
&& wkUtil != null && wkUtil >= POLICY.dyingMinUtilWeekly; // weekly window only (owner 2026-10-30)
|
|
197
275
|
if (!dying) continue;
|
|
198
276
|
if (g.requiresLimit) { note('requires limit'); continue; }
|
|
199
277
|
if (refillSoon(q.unified7dReset)) { note('free refill <24h away'); continue; }
|
|
200
|
-
return {
|
|
278
|
+
return out({ kind: 'grant', grant: g, scope: 'general', giveBack, reason: 'dying value' }, 'dying value');
|
|
201
279
|
}
|
|
202
280
|
if (weeklyWall && !general.length) note('general not held');
|
|
203
281
|
|
|
@@ -215,14 +293,21 @@ export function decideClaudeWithReason(account, listing, now = Date.now(), opts
|
|
|
215
293
|
const cand = grants.find(g => appliesTo(g).includes(fam));
|
|
216
294
|
if (!cand) continue;
|
|
217
295
|
if (e.utilization >= CLAUDE_WALL_WEEKLY) {
|
|
218
|
-
|
|
296
|
+
// Never held on its own (red-team r3) — but skipped while the GENERAL wall is
|
|
297
|
+
// held: the account is benched by its general wall, so a model reset buys
|
|
298
|
+
// nothing now; the hold re-evaluates every tick and, once the general refill
|
|
299
|
+
// lands (or the hold lets go), this wall claims as before R7. ONLY when the
|
|
300
|
+
// grant outlives the general refill by a day (red-team r4 #1) — one that
|
|
301
|
+
// would expire before then is claimed now, or it is lost.
|
|
302
|
+
if (generalHeld && (cand.endsAt == null || cand.endsAt - q.unified7dReset >= POLICY.dyingWindowMs)) continue;
|
|
303
|
+
return out({ kind: 'grant', grant: cand, scope: fam, reason: `${fam} weekly at wall` }, `${fam} weekly at wall`);
|
|
219
304
|
}
|
|
220
305
|
const dying = msLeft(cand.endsAt, now) < POLICY.dyingWindowMs
|
|
221
306
|
&& e.utilization >= POLICY.dyingMinUtilWeekly;
|
|
222
307
|
if (!dying) continue;
|
|
223
308
|
if (cand.requiresLimit) { note('requires limit'); continue; }
|
|
224
309
|
if (refillSoon(e.resetAt)) { note('free refill <24h away'); continue; }
|
|
225
|
-
return {
|
|
310
|
+
return out({ kind: 'grant', grant: cand, scope: fam, reason: 'dying value' }, 'dying value');
|
|
226
311
|
}
|
|
227
312
|
// A scoped bucket measured at the wall with no grant for it.
|
|
228
313
|
for (const [fam, e] of Object.entries(q.scopedWeekly || {})) {
|
|
@@ -231,5 +316,5 @@ export function decideClaudeWithReason(account, listing, now = Date.now(), opts
|
|
|
231
316
|
}
|
|
232
317
|
|
|
233
318
|
// Session-only grants: NEVER claimed (owner 2026-10-30) — falls through.
|
|
234
|
-
return
|
|
319
|
+
return out(null, reason ?? 'below wall');
|
|
235
320
|
}
|
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
|
-
|
|
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 =
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
506
|
-
if (mem)
|
|
507
|
-
|
|
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);
|