UNPKG

@code-yeongyu/senpi

Version:

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

471 lines • 24.3 kB
import { clampThinkingLevel } from "@earendil-works/pi-ai"; import { fastSiblingOption } from "../fast-model-pair.js"; import { firstUsableCandidate } from "./candidates.js"; import { baseSelector, canonicalizeFallbackChains, formatSelector, parseFallbackSelector, resolveChainKey, rungSelector, } from "./chains.js"; import { subscribeProviderAccountEvents } from "../extensions/builtin/anthropic-subscription/account-events.js"; import { CircuitProbes } from "./circuit-probes.js"; import { releaseOnCredentialChange, releaseOnLimitReset } from "./credential-recovery.js"; import { pinAfterSwitch } from "./pin.js"; import { isPureNetworkTransient } from "./transient-network.js"; import { UnusableEntries } from "./unusable.js"; import { usageLimitScope } from "./usage-limit.js"; export class RetryFallbackController { constructor(deps) { this.triedSelectors = new Set(); // A fallback forced by a network blip serves out its turn; only the next turn boundary reverts it. this.heldForNetworkBlip = false; // Entries this session itself saw fail out of a chain: only these (or an entry spent for everyone) // may move the session off its model at a turn boundary (senpi#3467). this.ownFailures = new Set(); // Conservatively skip the refused provider for this turn: this synchronous scan cannot resolve // asynchronously prepared request credentials, including per-model endpoints or keys (senpi#2491). this.refusedProviders = new Set(); // Rungs the switch refused during this turn's walks, so exhaustion can say why (senpi#3447). this.refusals = []; this.deps = deps; this.probes = new CircuitProbes(deps.circuits); this.unusable = new UnusableEntries(deps.cooldowns); } get activeState() { return this.state; } get exhaustedChainKey() { return this.lastExhaustedChainKey; } /** The weekly-limit family hold on `model`, while it lasts (senpi#5596). */ heldFamily(model) { return this.unusable.heldFamily(model); } /** The families a no-family limit was confirmed on before it held the whole provider (senpi#5596). */ widenedFamiliesOf(provider) { return this.unusable.widenedFamiliesOf(provider); } get turnRefusals() { return [...this.refusals]; } isProviderSpent(provider) { return this.unusable.isProviderSpent(provider); } accountError(provider) { return this.unusable.accountError(provider); } accountResetAt(provider) { return this.unusable.accountResetAt(provider); } releaseGuessedAccountHold(provider) { return this.unusable.releaseGuessedAccountHold(provider); } releaseAccountHold(provider) { return this.unusable.releaseAccountHold(provider); } releaseAccountHoldShownServable(provider, usage) { return this.unusable.releaseAccountHoldShownServable(provider, usage); } resetTurn() { this.triedSelectors.clear(); this.refusedProviders.clear(); this.refusals.length = 0; this.lastExhaustedChainKey = undefined; } clear() { this.state = undefined; this.heldForNetworkBlip = false; this.canonicalCache = undefined; this.resetTurn(); } canonicalChains() { const chains = this.deps.getSettings().chains; const key = JSON.stringify(chains); if (this.canonicalCache?.key === key) return this.canonicalCache.chains; const canonical = canonicalizeFallbackChains(chains, this.deps.registry); this.canonicalCache = { key, chains: canonical }; return canonical; } /** * `refusedProvider`: a provider the failure being decided rules out (a request-level refusal or * a spent account) before the walk records it. */ canTryFallback(refusedProvider) { return this.nextCandidate(false, false, refusedProvider) !== undefined; } /** * Whether a chain exists for the current model at all, regardless of whether * a candidate is usable right now. `canTryFallback()` answers the latter and * goes false on cooldown or exhaustion, so it cannot tell a UI "you never * configured a chain" apart from "the chain is spent". */ hasConfiguredChain() { const current = this.deps.getCurrentSelector(); if (!current) return false; const chains = this.canonicalChains(); return (resolveChainKey(current.model, current.thinkingLevel, chains, fastSiblingOption(this.deps.registry, current.model)) !== undefined); } /** * Revert to the chain's original model at a turn boundary. Fires for unpinned * state under the cooldown-expiry policy once the original selector is no longer * suppressed and is still usable; pinned state and the "never" policy hold the * fallback model. One exception outranks both the cooldown and the policy: a * fallback that is itself known unusable (billing or an account limit) while the * original is not is never where the session rests (senpi#2376). An original that is * itself still held (an account usage limit with the reset it named, which can outlast * the circuit's 30-minute ceiling) is not restored before that hold ends (senpi#3347). * At a turn boundary, a changed credential on the original's provider first releases * its billing pin and parks (senpi#4099). */ async maybeRestorePrimary(revertPolicy, boundary = "turn") { const heldForNetworkBlip = this.heldForNetworkBlip && boundary === "continuation"; if (boundary === "turn") this.heldForNetworkBlip = false; const state = this.state; const current = this.deps.getCurrentSelector(); if (!state || !current) return false; const selector = parseFallbackSelector(state.originalSelector, this.deps.registry); const model = selector && this.deps.registry.find(selector.provider, selector.id); if (!model) return false; if (boundary === "turn") await releaseOnCredentialChange(state, model, this.deps, this.unusable); releaseOnLimitReset(state, model, this.deps, this.unusable); if (state.pinned || !this.deps.isAuthAvailable(model.provider)) return false; const stranded = this.unusable.isUnusable(current.model) && !this.unusable.isUnusable(model); if (!stranded && (heldForNetworkBlip || this.unusable.isUnusable(model) || !this.originalRecovered(state, revertPolicy))) return false; // User override wins: only restore the original thinking level when the // current level still equals the level the fallback switch applied. A manual // setThinkingLevel clears lastAppliedThinkingLevel (see noteManualThinkingLevel). const thinking = current.thinkingLevel === state.lastAppliedThinkingLevel ? (state.originalThinkingLevel ?? current.thinkingLevel ?? "off") : (current.thinkingLevel ?? "off"); await this.switchOrRelease(model, thinking, "fallback-revert"); const from = formatSelector(current.model); this.state = undefined; const cause = stranded ? { cause: "fallback-unusable" } : {}; const trigger = stranded ? { trigger: "fallback-unusable" } : {}; this.deps.logger.info("fallback_reverted", { from, to: state.originalSelector, ...trigger }); this.deps.emit({ type: "retry_fallback_reverted", from, to: state.originalSelector, ...cause }); return true; } originalRecovered(state, revertPolicy) { if (revertPolicy !== "cooldown-expiry") return false; const originalSelector = state.originalSelector; // The original rung may be parked by its own hard error while the model as a whole is not. const original = parseFallbackSelector(originalSelector, this.deps.registry); if (original && state.originalThinkingLevel !== undefined && this.deps.cooldowns.isSuppressed(rungSelector({ ...original, thinkingLevel: state.originalThinkingLevel }))) return false; // An entry the breaker tracks recovers on the circuit's clock; the per-session // cooldown only governs entries the breaker never opened (hard errors, breaker off). const suppressed = this.probes.governs(originalSelector) ? this.probes.isOpen(originalSelector) : this.deps.cooldowns.isSuppressed(originalSelector); return !suppressed && this.probes.admit(originalSelector) !== "open"; } /** * A user-driven setThinkingLevel makes the current level a deliberate choice, * so the revert restore-rule must no longer treat it as fallback-applied. */ noteManualThinkingLevel() { if (this.state) this.state.lastAppliedThinkingLevel = undefined; } /** * A senpi-owned compaction successfully rewrote the conversation context, the * one safe moment to re-attempt a refusal-pinned fallback's original model: * the refusal assumption ("the same context refuses again") no longer holds. * Refusal contributions clear; billing contributions never release - retrying * the same account never recovers it. Returns true only when the overall pin * transitioned true -> false, i.e. the caller may now restore the primary via * the existing maybeRestorePrimary gate. */ notifyCompactionApplied() { const state = this.state; if (!state) return false; state.pinnedByRefusal = false; const wasPinned = state.pinned; state.pinned = state.pinnedByBilling; if (!wasPinned || state.pinned) return false; this.deps.logger.info("refusal_pin_released", { chainKey: state.chainKey, originalSelector: state.originalSelector, trigger: "compaction", }); return true; } /** A user-driven model change abandons the fallback window entirely. */ clearForManualModelChange(model) { if (this.state) { this.deps.logger.info("fallback_cleared_manual", { selector: formatSelector(model) }); } this.state = undefined; this.heldForNetworkBlip = false; this.ownFailures.delete(formatSelector(model)); this.deps.cooldowns.clearModel(formatSelector(model)); this.unusable.clear(model); this.probes.release(); this.deps.circuits?.close(formatSelector(model)); } /** * A login or an explicit block reset on `provider` makes the account and * model holds it earned stale, so the restore guard stops waiting out a reset that may no longer apply. */ noteProviderAccountsChanged(provider) { this.unusable.clearProvider(provider, this.deps.registry.getAll()); } /** A response this session got from `selector` succeeded: the entry serves it again (senpi#3467). */ noteServed(selector) { this.ownFailures.delete(selector); this.probes.accept(selector); const slash = selector.indexOf("/"); if (slash > 0) this.emitScopeProbe(this.unusable.noteServed({ provider: selector.slice(0, slash), id: selector.slice(slash + 1).split(":")[0] ?? "", })); } emitScopeProbe(probe) { if (probe === undefined) return; this.deps.logger.info("usage_limit_scope_probe", { ...probe }); this.deps.emit({ type: "usage_limit_scope_probe", ...probe }); } /** * Records a failure that makes the entry unusable for every session - billing * or quota exhaustion, or a transient failure that spent its budget or failed a * half-open probe - independent of whether a fallback candidate remains. */ noteHealthFailure(model, thinkingLevel, failure) { this.emitScopeProbe(this.unusable.note(model, failure)); if (!this.managedChainKey({ model, thinkingLevel })) return; // A pure network fault is the transport's, not the model's: it never opens the shared circuit (senpi#3306). if (isPureNetworkTransient(failure.errorMessage)) return; this.ownFailures.add(formatSelector(model)); this.probes.noteFailure(formatSelector(model), failure); } /** * Turn-boundary skip: when the current entry's circuit is open because this session * saw it fail (and has not been served by it since), or because its account is spent * for everyone, move to the next closed entry without spending a request on it. A * sibling's bare failure or Retry-After never moves this session (senpi#3467). With no * closed entry left the current one stays and probes, so the chain never refuses a * turn; a half-open current entry is claimed for this session. */ async rerouteAroundOpenCircuit() { const current = this.deps.getCurrentSelector(); if (!this.deps.circuits || !current) return false; const currentBase = formatSelector(current.model); // A half-open entry is still claimed as this session's single probe whoever opened it. if (this.probes.admit(currentBase) !== "open") return false; // Another session's bare failure says this entry was slow for that session, not that it is // down for this one: a session that never failed on it keeps its model and finds out itself. if (!this.ownFailures.has(currentBase) && !this.probes.isExhausted(currentBase)) return false; const candidate = this.nextCandidate(false, true); if (!candidate || candidate.circuitOpen) return false; this.deps.logger.info("circuit_open_skip", { selector: currentBase }); await this.applyCandidate(current, candidate, "transient"); return true; } async tryFallback(reason, failure, failureObserved = true) { if (failure.refusedProvider !== undefined) this.refusedProviders.add(failure.refusedProvider); const current = this.deps.getCurrentSelector(); const blip = reason === "transient" && isPureNetworkTransient(failure.errorMessage); this.blipModel = blip && current ? formatSelector(current.model) : undefined; try { return await this.walkFallback(reason, failure, failureObserved); } finally { this.blipModel = undefined; } } async walkFallback(reason, failure, failureObserved) { const current = this.deps.getCurrentSelector(); // A network blip that outlasted the same-model retries may fall back for this turn, but it // leaves no cooldown or open circuit on the primary, so the next turn boundary reverts (senpi#3306). const networkBlip = reason === "transient" && isPureNetworkTransient(failure.errorMessage); // Only a transient failure that spent its budget opens the shared circuit // here; billing/quota exhaustion is recorded at the failure itself (see // noteHealthFailure) so the final chain entry opens too. if (failureObserved && current && reason === "transient") this.noteHealthFailure(current.model, current.thinkingLevel, failure); if (failureObserved && current) this.emitScopeProbe(this.unusable.note(current.model, failure)); // A weekly limit that named no family held only the failing family (senpi#5596): report it as that model's // limit, so the switch never claims the account's other models were skipped. const scopeOfText = usageLimitScope(failure.errorMessage); const limit = scopeOfText === "account" && current && !this.unusable.isProviderSpent(current.model.provider) && this.unusable.heldFamily(current.model) ? "model" : scopeOfText; // A model-wide park (transient, billing) can rule out the current model's other rungs, so the // walk re-scans after noting it; the first scan logs only when no re-scan follows. const modelWidePark = !networkBlip && failureObserved && (reason === "transient" || reason === "billing"); let candidate = this.nextCandidate(false, !modelWidePark); if (!current || !candidate) { if (modelWidePark) this.nextCandidate(false, true); return false; } const currentBase = formatSelector(current.model); if (!networkBlip && failureObserved && (reason === "transient" || reason === "hard-error" || reason === "billing")) { // A hard error is charged to the rung that failed (a level the model rejects, or any // non-retryable failure there), so it parks only that rung and a // later rung of the same model stays reachable; a transient or billing failure parks the // whole model, which is unhealthy at every level (senpi#3311). A network blip parks // nothing (senpi#3306). const parked = reason === "hard-error" ? rungSelector({ provider: current.model.provider, id: current.model.id, thinkingLevel: current.thinkingLevel, }) : currentBase; this.deps.cooldowns.note(parked, failure); this.deps.logger.info("cooldown_noted", { selector: parked, errorMessage: failure.errorMessage }); } if (modelWidePark) candidate = this.nextCandidate(false, true); // A rung the switch itself refuses does not end the walk: the next rung may fit (senpi#2894). while (candidate) { try { await this.applyCandidate(current, candidate, reason, limit); this.heldForNetworkBlip ||= networkBlip; return true; } catch (error) { if (!this.deps.isCandidateRefusal?.(error)) throw error; this.triedSelectors.add(rungSelector(candidate.selector)); this.refusals.push({ model: formatSelector(candidate.model), detail: error instanceof Error ? error.message : String(error), }); this.skip(formatSelector(candidate.model), "refused"); } candidate = this.nextCandidate(false, true); } return false; } async applyCandidate(current, candidate, reason, limit) { const thinking = this.selectThinking(candidate.selector, candidate.model, current.thinkingLevel); this.probes.admit(baseSelector(candidate.selector)); await this.switchOrRelease(candidate.model, thinking, "fallback"); this.triedSelectors.add(rungSelector(candidate.selector)); const from = formatSelector(current.model); const to = formatSelector(candidate.model); const prior = this.state; const recoveryRevision = prior ? prior.recoveryRevision : await this.deps.recoveryRevision?.(current.model.provider); const pin = pinAfterSwitch(prior, { from, fromProvider: current.model.provider, reason, limit }); // A new billing pin from a usage limit lasts until the reset the limit stated, when it named one (senpi#4085). const pinnedUntil = pin.pinnedByBilling && prior?.pinnedByBilling !== true ? (this.deps.cooldowns.statedResetAt(from) ?? this.unusable.accountResetAt(current.model.provider)) : prior?.pinnedUntil; this.state = { ...(recoveryRevision === undefined ? {} : { recoveryRevision }), chainKey: candidate.chainKey, originalThinkingLevel: prior?.originalThinkingLevel ?? current.thinkingLevel, lastAppliedThinkingLevel: thinking, ...pin, ...(pinnedUntil === undefined ? {} : { pinnedUntil }), }; const scope = limit === undefined ? {} : { limit }; this.deps.logger.info("fallback_applied", { from, to, chainKey: candidate.chainKey, reason, ...scope }); this.deps.emit({ type: "retry_fallback_applied", from, to, chainKey: candidate.chainKey, reason, ...scope }); } /** * The chain governing `current`, when fallback is enabled. An active episode's chain wins over the * rung's own chain, so the walk continues down the chain it started on: Opus 5.5 -> Fable 5.2 -> Kimi * never detours through Fable's own chain, and a Fable session that reached Opus 5.5 never takes * Opus 5.5's chain off Anthropic (senpi#6699). Outside an episode the model's own chain governs. */ managedChainKey(current) { if (!this.deps.getSettings().modelFallback) return undefined; const chains = this.canonicalChains(); const active = this.state?.chainKey; if (active && chains[active]) return active; const own = resolveChainKey(current.model, current.thinkingLevel, chains, fastSiblingOption(this.deps.registry, current.model)); return own && chains[own] ? own : undefined; } nextCandidate(reserve = true, logDecision = reserve, refusedProvider) { const current = this.deps.getCurrentSelector(); if (!this.deps.getSettings().modelFallback || !current) return undefined; // Models without an explicitly configured chain do not enter an implicit fallback lane. const chainKey = this.managedChainKey(current); const entries = chainKey ? this.canonicalChains()[chainKey] : undefined; if (!chainKey || !entries) { if (logDecision) this.deps.logger.debug("no_chain", { selector: formatSelector(current.model) }); return undefined; } const candidate = firstUsableCandidate(entries, current, { registry: this.deps.registry, tried: this.triedSelectors, isSuppressed: (base) => this.deps.cooldowns.isSuppressed(base), isAuthAvailable: (provider) => this.deps.isAuthAvailable(provider), isCircuitOpen: (base) => this.deps.circuits?.isOpen(base) ?? false, isProviderSpent: (provider) => this.unusable.isProviderSpent(provider), isProviderRefused: (provider) => provider === refusedProvider || this.refusedProviders.has(provider), isModelSkipped: (base) => base === this.blipModel, skip: (raw, skipReason) => this.skip(raw, skipReason), }); if (candidate) { if (reserve) this.triedSelectors.add(rungSelector(candidate.selector)); return { chainKey, ...candidate }; } this.lastExhaustedChainKey = chainKey; if (logDecision) this.deps.logger.info("candidates_exhausted", { chainKey }); return undefined; } async switchOrRelease(model, thinking, reason) { try { await this.deps.switchModel(model, thinking, reason); } catch (error) { this.probes.release(); throw error; } } selectThinking(selector, model, inherited) { const requested = selector.thinkingLevel ?? inherited ?? "off"; // Canonical clamp walks to the NEAREST supported level. Picking the highest // supported level instead would escalate an "off" request to max reasoning on // always-on fallback models. return clampThinkingLevel(model, requested); } skip(candidate, skipReason) { this.deps.logger.debug("candidate_skipped", { candidate, skipReason }); } } /** Only explicit account remedies invalidate holds; health and listing notices do not. */ export function followProviderAccountChanges(controller) { return subscribeProviderAccountEvents((event) => { if (event.type === "accounts_changed" && event.remedy !== undefined) controller.noteProviderAccountsChanged(event.provider); }); } //# sourceMappingURL=controller.js.map