UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

62 lines • 3.05 kB
import { createHash } from "node:crypto"; import { applyAccountOrder, isSlotBlocked } from "@earendil-works/pi-ai/auth/pool/select"; export const DEFAULT_CURSOR_AFFINITY_KEY = "cursor-cli-oauth-default"; export class AllCursorAccountsBlockedError extends Error { constructor(soonestUnblockAt) { super(soonestUnblockAt === undefined ? "All Cursor CLI OAuth accounts are blocked until re-login." : `All Cursor CLI OAuth accounts are blocked until ${new Date(soonestUnblockAt).toISOString()}.`); this.name = "AllCursorAccountsBlockedError"; this.soonestUnblockAt = soonestUnblockAt; } } export function getAffinityKey(options) { return options.affinityKey ?? options.sessionId ?? DEFAULT_CURSOR_AFFINITY_KEY; } function score(key, accountName) { return createHash("sha256").update(`${key}\0${accountName}`).digest().readBigUInt64BE(0); } /** Orders accounts by descending highest-random-weight score for the session key. */ 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); } /** Clears elapsed temporary blocks while retaining auth failures until the account logs in again. */ export function clearExpiredBlocks(accounts, now = Date.now()) { return accounts.map((account) => { if (account.blockReason !== "auth_error" && account.blockedUntil !== undefined && account.blockedUntil <= now) { const { blockedUntil: _blockedUntil, blockReason: _blockReason, ...available } = account; return available; } return account; }); } function selectUnblocked(accounts, options, now) { const pinned = options.pinnedAccount === undefined ? undefined : accounts.find((account) => account.name === options.pinnedAccount); if (pinned && !isSlotBlocked(pinned, now)) return pinned; return applyAccountOrder(options.accountOrder, rendezvousOrder(getAffinityKey(options), accounts)).find((account) => !isSlotBlocked(account, now)); } function soonestUnblockAt(accounts, now) { const candidates = accounts .map((account) => account.blockedUntil) .filter((value) => value !== undefined && value > now); return candidates.length === 0 ? undefined : Math.min(...candidates); } /** Selects the pinned account or the first available account in session-stable HRW order. */ export function selectAccount(accounts, options = {}) { const now = options.now ?? Date.now(); const selected = selectUnblocked(accounts, options, now); if (selected) return selected; const cleared = clearExpiredBlocks(accounts, now); const afterClear = selectUnblocked(cleared, options, now); if (afterClear) return afterClear; throw new AllCursorAccountsBlockedError(soonestUnblockAt(accounts, now)); } //# sourceMappingURL=affinity.js.map