@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
183 lines • 10.3 kB
JavaScript
import { createHash } from "node:crypto";
import { activeModelBlockUntil, pruneModelBlocks } from "../../../credential-pool/model-scope.js";
import { roundRobinState } from "../../../credential-pool/round-robin-state.js";
import { orderAccounts, preferHeadroom } from "../../../credential-pool/selection-order.js";
import { subscriptionLimits } from "../../../subscription-limits/limit-store.js";
import { usageShowsCapacity } from "../../../subscription-limits/usage-capacity.js";
export const DEFAULT_AFFINITY_KEY = "claude-sdk-oauth-default";
function describeAccountState(state) {
const until = state.until === undefined ? "re-login" : new Date(state.until).toISOString();
const login = state.reason === "auth_error" ? ` (run /login anthropic-subscription for ${state.name})` : "";
return `${state.name}: ${state.reason} until ${until}${login}`;
}
export class AllAccountsBlockedError extends Error {
constructor(soonestUnblockAt, blockReason, limitedModel, unavailableAccount, accounts = [], rateLimitedUntil) {
const until = soonestUnblockAt === undefined ? undefined : new Date(soonestUnblockAt).toISOString();
const summary = limitedModel !== undefined && until !== undefined
? `All Anthropic Subscription accounts have hit the usage limit for model ${limitedModel} until ${until}.`
: until === undefined
? "All Anthropic Subscription accounts are blocked until re-login."
: `All Anthropic Subscription accounts are blocked until ${until}.`;
super(accounts.length === 0 ? summary : `${summary} Accounts: ${accounts.map(describeAccountState).join("; ")}.`);
this.accounts = accounts;
this.limitedModel = limitedModel;
this.name = "AllAccountsBlockedError";
this.soonestUnblockAt = soonestUnblockAt;
this.blockReason = blockReason;
this.unavailableAccount = unavailableAccount;
this.rateLimitedUntil = rateLimitedUntil;
}
}
export function getAffinityKey(options) {
return options.affinityKey ?? options.sessionId ?? DEFAULT_AFFINITY_KEY;
}
function score(key, accountName) {
return createHash("sha256").update(`${key}\0${accountName}`).digest().readBigUInt64BE(0);
}
/**
* Session-stable HRW ordering preserves Claude prompt-cache locality while moving
* only the sessions that rendezvous with a newly added or removed account.
*/
export function rendezvousOrder(key, accounts) {
return [...accounts]
.map((account) => ({ account, score: score(key, account.name) }))
.sort((left, right) => (right.score > left.score ? 1 : right.score < left.score ? -1 : 0))
.map(({ account }) => account);
}
/** Account-level block for selection; an auth block with no deadline or a passed one is re-probed (senpi#3264). */
export function isAccountBlocked(account, now) {
return account.blockedUntil !== undefined && account.blockedUntil > now;
}
/** Whether the account can serve `model` now: no account-level block and no live block on that model. */
export function isBlockedFor(account, now, model) {
return isAccountBlocked(account, now) || activeModelBlockUntil(account.modelBlocks, model, now) !== undefined;
}
/**
* A usage-limit block the account's own usage, read after the block was stored, contradicts: the provider lifted
* the limit before the reset it stated (senpi#6536). Auth, billing and organization blocks need the user, so only
* a rate-limit block lifts this way.
*/
export function isLimitLiftedEarly(account, now) {
if (account.blockReason !== "rate_limit" || account.blockedAt === undefined)
return false;
if (account.blockedUntil === undefined || account.blockedUntil <= now)
return false;
const limits = subscriptionLimits
.snapshot()
.find((entry) => entry.provider === "anthropic-subscription" && entry.account === account.name);
return limits !== undefined && usageShowsCapacity(limits, account.blockedAt, now);
}
/**
* Removes elapsed blocks, auth blocks included: an auth block lasts until its
* re-probe time (senpi#3264), and one persisted before re-probe times existed
* has no expiry and clears at once, so the next request probes the account.
* A limit block newer usage contradicts is removed too (senpi#6536).
*/
export function clearExpiredBlocks(accounts, now = Date.now()) {
return accounts.map((account) => {
let available = account;
if ((account.blockReason !== undefined && (account.blockedUntil === undefined || account.blockedUntil <= now)) ||
isLimitLiftedEarly(account, now)) {
const { blockedUntil: _blockedUntil, blockReason: _blockReason, blockedAt: _blockedAt, authVerdict: _authVerdict, ...rest } = account;
available = rest;
}
if (available.modelBlocks === undefined)
return available;
const { modelBlocks, ...rest } = available;
const live = pruneModelBlocks(modelBlocks, now);
return live === undefined ? rest : { ...rest, modelBlocks: live };
});
}
function selectUnblocked(accounts, options, now, roundRobinOffset = 0) {
const pinned = options.pinnedAccount === undefined
? undefined
: accounts.find((account) => account.name === options.pinnedAccount);
if (pinned && !isBlockedFor(pinned, now, options.model))
return pinned;
const preferred = options.preferredAccount === undefined
? undefined
: accounts.find((account) => account.name === options.preferredAccount);
const usable = orderAccounts(accounts, rendezvousOrder(getAffinityKey(options), accounts), options.accountOrder, options.accountStrategy, roundRobinOffset).filter((account) => !isBlockedFor(account, now, options.model));
return preferHeadroom(usable, "anthropic-subscription", subscriptionLimits.snapshot(), now, preferred?.name)[0];
}
function unblockAt(account, now, model) {
const accountUntil = account.blockedUntil !== undefined && account.blockedUntil > now ? account.blockedUntil : undefined;
const modelUntil = activeModelBlockUntil(account.modelBlocks, model, now);
if (accountUntil === undefined)
return modelUntil;
return modelUntil === undefined ? accountUntil : Math.max(accountUntil, modelUntil);
}
function soonestUnblockAt(accounts, now, model) {
const candidates = accounts
.map((account) => unblockAt(account, now, model))
.filter((value) => value !== undefined);
return candidates.length === 0 ? undefined : Math.min(...candidates);
}
/** Account blocks that need the user (top-up, organization access, a new login), not a wait. */
const OUT_OF_POOL_REASONS = new Set(["billing", "org_not_allowed", "auth_error"]);
function poolRateLimitedUntil(accounts, now, model) {
const waiting = accounts.filter((account) => !(isAccountBlocked(account, now) && OUT_OF_POOL_REASONS.has(account.blockReason ?? "")));
const resets = [];
for (const account of waiting) {
const rateLimited = isAccountBlocked(account, now)
? account.blockReason === "rate_limit"
: activeModelBlockUntil(account.modelBlocks, model, now) !== undefined;
const until = unblockAt(account, now, model);
if (!rateLimited || until === undefined)
return undefined;
resets.push(until);
}
return resets.length === 0 ? undefined : Math.min(...resets);
}
function limitedModel(accounts, now, model) {
const modelOnly = accounts.some((account) => !isAccountBlocked(account, now) && activeModelBlockUntil(account.modelBlocks, model, now) !== undefined);
return modelOnly ? model : undefined;
}
/** Selects a pinned, resident, or strategy-ranked account; only round-robin holds a distribution cursor. */
export function selectAccount(accounts, requestedOptions = {}) {
const roundRobin = requestedOptions.accountStrategy === "round-robin"
? roundRobinState.session("anthropic-subscription", getAffinityKey(requestedOptions))
: undefined;
const options = roundRobin?.account !== undefined && requestedOptions.preferredAccount === undefined
? { ...requestedOptions, preferredAccount: roundRobin.account }
: requestedOptions;
const now = options.now ?? Date.now();
let candidates = accounts;
let unavailableAccount;
if (options.accountFallback === false) {
const name = options.pinnedAccount ??
options.preferredAccount ??
orderAccounts(accounts, rendezvousOrder(getAffinityKey(options), accounts), options.accountOrder, options.accountStrategy, roundRobin?.offset)[0]?.name;
candidates = accounts.filter((account) => account.name === name);
const pinnedBy = options.pinnedAccount !== undefined ? options.pinSource : undefined;
if (name !== undefined)
unavailableAccount = {
name,
configured: candidates.length > 0,
...(pinnedBy === undefined ? {} : { pinnedBy }),
};
}
const selected = selectUnblocked(candidates, options, now, roundRobin?.offset);
if (selected) {
if (roundRobin !== undefined)
roundRobin.account = selected.name;
return selected;
}
// A stale persisted rate-limit entry must not dead-end the pool. Retry once
// against the cleared view before reporting the earliest available account.
const cleared = clearExpiredBlocks(candidates, now);
const afterClear = selectUnblocked(cleared, options, now, roundRobin?.offset);
if (afterClear) {
if (roundRobin !== undefined)
roundRobin.account = afterClear.name;
return afterClear;
}
throw new AllAccountsBlockedError(soonestUnblockAt(candidates, now, options.model), candidates.length > 0 && candidates.every((account) => account.blockReason === "auth_error")
? "auth_error"
: undefined, limitedModel(candidates, now, options.model), unavailableAccount, candidates.map((account) => ({
name: account.name,
reason: account.blockReason ?? (isAccountBlocked(account, now) ? "blocked" : "model_limit"),
until: unblockAt(account, now, options.model),
})), poolRateLimitedUntil(candidates, now, options.model));
}
//# sourceMappingURL=affinity.js.map