UNPKG

@code-yeongyu/senpi

Version:

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

483 lines • 24 kB
import { AUTH_BLOCK_REPROBE_MS } from "../../../credential-pool/auth-reprobe.js"; import { activeModelBlockUntil, mergeModelBlocks, modelBlockKey, pruneModelBlocks, withModelBlock, } from "../../../credential-pool/model-scope.js"; import { usageLimitResetMs } from "../../../credential-pool/reset-time.js"; import { logAccountBlocked } from "./account-block-log.js"; import { AllAccountsBlockedError, clearExpiredBlocks } from "./affinity.js"; import { recheckSelection, unverifiedLimitBlock } from "./limit-recheck.js"; import { isConfirmedAccountUsageLimit, usageLimitBlockMs } from "./usage-limit-block.js"; export const MAX_RATE_LIMIT_BLOCK_MS = 48 * 60 * 60 * 1_000; export const DEFAULT_RATE_LIMIT_BLOCK_MS = 60_000; /** Same-account retries per turn for a transient failure (overload, network, server error); it never rotates. */ export const TRANSIENT_RETRIES_PER_TURN = 2; export const TRANSIENT_RETRY_DELAY_MS = 1_000; export const TURN_RETRY_SUPPRESSION_PREFIX = "senpi:no-turn-retry:"; /** * Blocks that bind only the session that hit them, in memory for the process: a plain rate limit and a * one-model limit. Another session on the same account keeps using it and finds out on its own request. */ const sessionBlocks = new Map(); /** * Only a verdict that the account itself cannot serve anyone is shared through the credential store: a * confirmed account-level usage limit, a billing or organization refusal, or a rejected token. Moving * every session off the account is right then, since leaving them would retry a dead account. A plain * rate limit, an overload or a one-model limit is not that verdict, so it never moves other sessions * (senpi#3466). */ function isSharedVerdict(classification, error) { if (classification.kind === "auth_error" || classification.kind === "billing" || classification.kind === "org_not_allowed") return true; return (classification.kind === "rate_limit" && classification.modelFamily === undefined && isConfirmedAccountUsageLimit(errorText(error))); } function rememberSessionBlock(sessionKey, account) { if (sessionKey === undefined) return; const blocks = sessionBlocks.get(sessionKey) ?? new Map(); blocks.set(account.name, { blockedUntil: account.blockedUntil, blockReason: account.blockReason, blockedAt: account.blockedAt, modelBlocks: account.modelBlocks, }); sessionBlocks.set(sessionKey, blocks); } /** Drops elapsed session blocks for every session, so sessions that ended leave nothing behind. */ function pruneSessionBlocks(now) { for (const [sessionKey, blocks] of sessionBlocks) { for (const [name, block] of blocks) { if ((block.blockedUntil ?? 0) <= now && pruneModelBlocks(block.modelBlocks, now) === undefined) blocks.delete(name); } if (blocks.size === 0) sessionBlocks.delete(sessionKey); } } function withSessionBlocks(accounts, sessionKey, now) { pruneSessionBlocks(now); const blocks = sessionKey === undefined ? undefined : sessionBlocks.get(sessionKey); if (blocks === undefined) return [...accounts]; return accounts.map((account) => { const own = blocks.get(account.name); if (own === undefined) return account; const later = (own.blockedUntil ?? 0) > (account.blockedUntil ?? 0); return { ...account, ...(later ? { blockedUntil: own.blockedUntil, blockReason: own.blockReason, blockedAt: own.blockedAt } : {}), modelBlocks: mergeModelBlocks(account.modelBlocks, own.modelBlocks, 0), }; }); } function forgetSessionBlock(sessionKey, name) { if (sessionKey === undefined) return; const blocks = sessionBlocks.get(sessionKey); if (!blocks?.delete(name)) return; if (blocks.size === 0) sessionBlocks.delete(sessionKey); } /** `/claude-account unblock` lifts the account's session-scoped blocks in every session too. Returns whether one was lifted. */ export function forgetSessionBlocksFor(name) { let lifted = false; for (const [sessionKey, blocks] of [...sessionBlocks]) { if (!blocks.has(name)) continue; lifted = true; forgetSessionBlock(sessionKey, name); } return lifted; } export class ClassifiedSdkError extends Error { constructor(classification, original, suppressTurnRetry, poolState) { const detail = original instanceof Error ? original.message : String(original); super(`${suppressTurnRetry ? TURN_RETRY_SUPPRESSION_PREFIX : ""}${detail}`, poolState === undefined ? undefined : { cause: poolState }); this.name = "ClassifiedSdkError"; this.classification = classification; this.original = original; this.suppressTurnRetry = suppressTurnRetry; this.poolState = poolState; } } function record(value) { return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined; } function defaultErrorFromEvent(event) { const value = record(event); return value?.type === "error" ? value.error : undefined; } function defaultIsVisibleDelta(event) { const value = record(event); if (typeof value?.type !== "string") return false; return /^(?:text|thinking|toolcall)_(?:start|delta|end)$/.test(value.type); } function errorText(error) { if (typeof error === "string") return error; if (error instanceof Error) return error.message; const value = record(error); return typeof value?.message === "string" ? value.message : String(error); } function retryAfterMs(error) { const value = record(error); const explicit = value?.retryAfterMs; if (typeof explicit === "number" && Number.isFinite(explicit) && explicit > 0) return Math.ceil(explicit); const text = errorText(error); const milliseconds = text.match(/\bretry[-_ ]?after[-_ ]?ms\s*[:=]\s*(\d+(?:\.\d+)?)/i); if (milliseconds) return Math.ceil(Number(milliseconds[1])); const seconds = text.match(/\bretry[-_ ]?after\s*[:=]\s*(\d+(?:\.\d+)?)/i); return seconds ? Math.ceil(Number(seconds[1]) * 1_000) : undefined; } function blockedAccount(account, classification, now, attempt, baseBlockMs, error, model) { if (classification.kind === "auth_error") { const blocked = { ...account, blockedUntil: now + AUTH_BLOCK_REPROBE_MS, blockReason: "auth_error", blockedAt: now, // Only a claude CLI login can be marked for a new sign-in; an env token account has no login to expire (senpi#5350). ...(classification.signInRequired !== undefined && account.store === "claude-cli" ? { signInRequired: classification.signInRequired } : {}), }; // The verdict names the sign-in it is about, so a block another engine writes is told apart (senpi#5623). return blocked.store === "claude-cli" ? { ...blocked, authVerdict: { dirId: blocked.dirId, at: now } } : blocked; } const fallback = Math.min(MAX_RATE_LIMIT_BLOCK_MS, baseBlockMs * 2 ** attempt); if (classification.modelFamily !== undefined && model !== undefined) { // A model-scoped limit lasts until its own reset, which Claude Code states in // the text ("resets 8pm"); the account itself keeps serving other models. const resetMs = retryAfterMs(error) ?? usageLimitResetMs(errorText(error), now); const duration = Math.min(MAX_RATE_LIMIT_BLOCK_MS, resetMs !== undefined && resetMs > 0 ? resetMs : fallback); const key = modelBlockKey(classification.modelFamily, model); return { ...account, modelBlocks: withModelBlock(account.modelBlocks, key, now + duration, now) }; } // A spent account is out until its limit resets, capped at the limit's own window; a fixed // short block sent a pinned account back to the same limit every minute (senpi#3462). const hinted = retryAfterMs(error) ?? usageLimitBlockMs(errorText(error), account.name, now); const duration = Math.min(MAX_RATE_LIMIT_BLOCK_MS, hinted ?? fallback); return { ...account, blockedUntil: now + duration, blockReason: classification.kind, blockedAt: now }; } /** * An account that just served a turn is not spent: a limit block stored before the turn started (a * misread reset, a stale failure) is cleared so it cannot hold a working account out. A block stored * after the turn started is newer evidence than this success and stays. Auth blocks keep their re-probe. */ async function clearBlockAfterSuccess(store, providerId, name, startedAt) { const clearable = (slot) => slot?.blockedUntil !== undefined && slot.blockReason !== "auth_error" && (slot.blockedAt ?? 0) <= startedAt; const stored = await store.read(providerId); if (stored?.type !== "oauth") return; const read = stored; const slot = read.accounts?.find((account) => account.name === name) ?? read.slotState?.[name]; if (!clearable(slot)) return; await store.modify(providerId, async (current) => { if (current?.type !== "oauth") return current; const credential = current; const state = credential.slotState?.[name]; const slotState = state === undefined || !clearable(state) ? credential.slotState : { ...credential.slotState, [name]: { ...(state.modelBlocks ? { modelBlocks: state.modelBlocks } : {}) } }; return { ...credential, ...(slotState === undefined ? {} : { slotState }), accounts: (credential.accounts ?? []).map((account) => { if (account.name !== name || !clearable(account)) return account; const { blockedUntil: _blockedUntil, blockReason: _blockReason, blockedAt: _blockedAt, ...rest } = account; return rest; }), }; }); } function isTransient(classification) { return classification.kind === "overloaded" || classification.kind === "other"; } function abortableSleep(ms, signal) { return new Promise((resolve, reject) => { if (signal?.aborted) { reject(signal.reason); return; } const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(timer); reject(signal?.reason); }; signal?.addEventListener("abort", onAbort, { once: true }); }); } function replaceAccount(accounts, replacement) { return accounts.map((account) => (account.name === replacement.name ? replacement : account)); } /** * Persists a block onto the stored slot. An `auth_error` is a verdict on the * sign-in that failed, so it is written only while the stored slot still names * that sign-in's account dir. When a re-login replaced it meanwhile, nothing is * written and the stored slot is returned: locking it "until re-login" would * strand a valid sign-in. */ async function persistBlock(store, providerId, account, now) { const signInMaterial = (slot) => slot.dirId; let superseded; await store.modify(providerId, async (current) => { if (current?.type !== "oauth") return current; const credential = current; if (account.source === "env") { return { ...credential, slotState: { ...credential.slotState, [account.name]: { blockedUntil: account.blockedUntil, blockReason: account.blockReason, ...(account.blockedAt === undefined ? {} : { blockedAt: account.blockedAt }), // Union with what a concurrent request stored meanwhile, later expiry winning. modelBlocks: mergeModelBlocks(credential.slotState?.[account.name]?.modelBlocks, account.modelBlocks, now), }, }, }; } const stored = (credential.accounts ?? []).find((existing) => existing.name === account.name); if (account.blockReason === "auth_error" && stored !== undefined && signInMaterial(stored) !== signInMaterial(account)) { superseded = stored; return current; } const accounts = (credential.accounts ?? []).map((existing) => existing.name === account.name ? { ...existing, blockedUntil: account.blockedUntil, blockReason: account.blockReason, ...(account.blockedAt === undefined ? {} : { blockedAt: account.blockedAt }), ...(account.store === "claude-cli" && account.signInRequired !== undefined ? { signInRequired: account.signInRequired } : {}), // Only this write's own auth verdict stays with the block (senpi#5623). authVerdict: existing.store === "claude-cli" ? account.authVerdict : undefined, modelBlocks: mergeModelBlocks(existing.modelBlocks, account.modelBlocks, now), } : existing); return { ...credential, accounts }; }); return superseded; } function usable(account, now, model) { return (account.blockReason === undefined && (account.blockedUntil === undefined || account.blockedUntil <= now) && activeModelBlockUntil(account.modelBlocks, model, now) === undefined); } /** * Runs one attempt per account for account-level failures (a limit, billing, auth), plus at most * TRANSIENT_RETRIES_PER_TURN same-account retries for a transient failure, after which the turn fails on * that account instead of rotating (and one retry on newer stored credentials). A retry is transparent only * before a text, thinking, or tool-call event reaches the caller; post-delta failures are marked so * AgentSession never replays the partial turn. */ export async function* runFailover(options) { const now = options.now ?? Date.now; const baseBlockMs = options.baseBlockMs ?? DEFAULT_RATE_LIMIT_BLOCK_MS; let accounts = clearExpiredBlocks(withSessionBlocks(options.accounts, options.sessionKey, now()), now()); const select = () => { try { return options.selectFn(accounts); } catch (error) { if (!(error instanceof AllAccountsBlockedError) || options.recheckedAccounts === undefined) throw error; return options.selectFn(recheckSelection(accounts, options.recheckedAccounts, now())); } }; const attemptLimit = options.accountFallback === false ? Math.min(accounts.length, 1) : accounts.length; let lastError; const retriedOnStoredMaterial = new Set(); let transientRetriesUsed = 0; let longContextRetried = false; let retryAccountName; for (let attempt = 0; attempt < attemptLimit; attempt++) { // Each attempt gets its own copy: an attempt may record a profile on its slot, and a concurrent // attempt holding the same stored object must still report the account it actually ran on. const retrySlot = retryAccountName === undefined ? undefined : accounts.find((slot) => slot.name === retryAccountName); retryAccountName = undefined; const account = { ...(retrySlot ?? select()) }; const held = accounts.find((slot) => slot.name === account.name); const rechecking = held !== undefined && unverifiedLimitBlock(held, now()) && retrySlot === undefined; options.recheckedAccounts?.add(account.name); let visibleDeltaEmitted = false; let completed = false; const startedAt = now(); try { const attemptStream = await options.runAttempt(account); for await (const event of attemptStream) { const failure = (options.errorFromEvent ?? defaultErrorFromEvent)(event); if (failure !== undefined) throw failure; visibleDeltaEmitted ||= (options.isVisibleDelta ?? defaultIsVisibleDelta)(event); yield event; } completed = true; } catch (error) { const classification = options.classify(error); const classified = new ClassifiedSdkError(classification, error, visibleDeltaEmitted); lastError = classified; if (!classification.retryable) throw classified; // An inconclusive half-open check retains the old block. It must not multiply into same-account retries. if (rechecking && (isTransient(classification) || classification.kind === "long_context_unavailable")) throw classified; // A refused 1M window is the account's entitlement, not a limit: never block or rotate it. // Retry once on the same account at the standard window (senpi#3408). if (classification.kind === "long_context_unavailable") { if (visibleDeltaEmitted || longContextRetried) throw classified; longContextRetried = true; options.onLongContextRefused?.(error); retryAccountName = account.name; attempt--; continue; } // A transient failure says nothing about the account: it is retried in place a bounded // number of times, then the turn fails on this account and the session's own retry and // model fallback take over. It never blocks or rotates the account: moving to another // account writes the whole conversation to a cold prompt cache, and a persisted block would // move every other session off a healthy account too (senpi#2891, senpi#3466). if (isTransient(classification)) { if (visibleDeltaEmitted || transientRetriesUsed >= TRANSIENT_RETRIES_PER_TURN) throw classified; const delayMs = TRANSIENT_RETRY_DELAY_MS * 2 ** transientRetriesUsed; transientRetriesUsed += 1; try { await (options.sleep ?? abortableSleep)(delayMs, options.signal); } catch { throw classified; } retryAccountName = account.name; attempt--; continue; } // A login this process could not read (senpi#5630) moves this turn to another account and is stored nowhere: // other sessions may read it fine, and an unlocked keychain must work on the very next turn. if (classification.kind === "login_unreadable") { if (visibleDeltaEmitted || attempt + 1 >= attemptLimit) throw classified; const unreadable = { ...account, blockedUntil: now() + AUTH_BLOCK_REPROBE_MS, blockReason: "login_unreadable", blockedAt: now(), }; accounts = replaceAccount(accounts, unreadable); let nextAccount; try { nextAccount = select(); } catch (selectError) { if (selectError instanceof AllAccountsBlockedError) throw classified; throw selectError; } await options.onFailover?.({ account: unreadable, classification, attempt: attempt + 1, visibleDeltaEmitted, nextAccount, }); continue; } const blocked = blockedAccount(account, classification, now(), attempt, baseBlockMs, error, options.model); // With no session to hold it, a block is shared as before: dropping it would re-send every // sessionless request to the spent account until its window resets. const persists = options.persistBlocks !== false; const shared = isSharedVerdict(classification, error) || options.sessionKey === undefined; if (persists && !shared) rememberSessionBlock(options.sessionKey, blocked); const superseded = persists && shared ? await persistBlock(options.store, options.providerId, blocked, now()) : undefined; if (superseded && !rechecking && !visibleDeltaEmitted && usable(superseded, now(), options.model) && !retriedOnStoredMaterial.has(account.name)) { // The rejected token was already replaced in the store: retry this // account once on the stored material instead of failing over. retriedOnStoredMaterial.add(account.name); accounts = replaceAccount(accounts, superseded); attempt--; continue; } logAccountBlocked({ account: blocked.name, reason: blocked.blockReason ?? "model_limit", until: blocked.blockedUntil ?? activeModelBlockUntil(blocked.modelBlocks, options.model, now()), shared, detail: errorText(error), }); accounts = replaceAccount(accounts, blocked); const event = { account: blocked, classification, attempt: attempt + 1, visibleDeltaEmitted, }; let poolState; try { if (!visibleDeltaEmitted && attempt + 1 < attemptLimit) { event.nextAccount = select(); } } catch (selectError) { if (!(selectError instanceof AllAccountsBlockedError)) throw selectError; poolState = selectError; } finally { await options.onFailover?.(event); } if (poolState !== undefined) throw new ClassifiedSdkError(classification, error, visibleDeltaEmitted, poolState); if (visibleDeltaEmitted) throw classified; } if (completed) { if (options.persistBlocks === false) return; forgetSessionBlock(options.sessionKey, account.name); // Outside the attempt's try: clearing is best-effort hygiene after a finished turn, so a store // failure is logged and the block stays for the next success; it never fails or replays the turn. await clearBlockAfterSuccess(options.store, options.providerId, account.name, startedAt).catch((error) => { process.stderr.write(`senpi anthropic-subscription: could not clear a stored block on ${account.name}: ${error instanceof Error ? error.message : String(error)}\n`); }); return; } } // The last account's own text speaks for that account only: when another account is out for this // model alone, the pool's refusal (a model-scoped limit) is what the fallback chain must read (senpi#5007). if (lastError !== undefined && lastError.classification.modelFamily === undefined && options.model !== undefined) { try { select(); } catch (refusal) { if (refusal instanceof AllAccountsBlockedError && refusal.limitedModel !== undefined) throw refusal; } } throw lastError ?? new Error("Anthropic Subscription failover exhausted without an attempt"); } //# sourceMappingURL=failover.js.map