@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
248 lines • 12.5 kB
JavaScript
import { slotsOfOwnKind } from "@earendil-works/pi-ai/auth/pool/kinds";
import { ConfigReferenceError } from "@earendil-works/pi-ai/utils/config-reference";
import { getConfigValueEnvVarNames, resolveConfigValue } from "../resolve-config-value.js";
import { discoverEnvSlots } from "./env-slots.js";
import { STORE_BUSY, writeHealthUnlessStoreBusy } from "./health-write.js";
import { activeModelBlockUntil } from "./model-scope.js";
import { acquireHalfOpenLease, applicableStoredState, } from "./state-store.js";
/** Hands a half-open probe lease back, if the slot still holds that exact lease. */
export async function releaseProbeLease(repository, providerId, lane, slotName, leaseId) {
await writeHealthUnlessStoreBusy(`lease release on ${slotName}`, () => repository.mutateSlotState(providerId, lane, slotName, (current) => {
if (current?.lease?.id !== leaseId)
return current;
const { lease: _released, ...rest } = current;
return rest;
}));
}
/**
* A model block found after taking the half-open probe lease hands the lease
* back: this request cannot run the probe, but a request for another model can.
*/
async function releaseLeaseIfModelBlocked(repository, providerId, lane, slotName, leaseId, until) {
if (until === undefined)
return;
await releaseProbeLease(repository, providerId, lane, slotName, leaseId);
}
/**
* A slot whose half-open probe another request is running. It stays listed, blocked until that
* probe's lease expires, so a refusal can name when to retry instead of reporting no slot at all
* (senpi#4094). Its reason is not `rate_limit`, so the all-cooling probe never sends a second
* request to it while the first is in flight.
*/
async function probeInFlight(repository, providerId, lane, slot, isApplicable, now) {
const state = (await repository.listSlots(providerId, lane))[slot.name];
const lease = isApplicable(state) ? state?.lease : undefined;
if (lease === undefined || lease.expiresAt <= now)
return undefined;
return { ...slot, blockedUntil: lease.expiresAt, blockReason: PROBE_IN_FLIGHT };
}
const PROBE_IN_FLIGHT = "probe_in_flight";
/**
* The half-open probe lease for a slot whose cooldown elapsed. When the state
* file stays locked, the slot is probed without a lease rather than dropped:
* the lease only spreads probes across callers, and a store that cannot be
* written must not turn an expired cooldown into "no account available".
*/
function probeLease(repository, providerId, lane, slotName, now) {
return writeHealthUnlessStoreBusy(`probe lease on ${slotName}`, () => acquireHalfOpenLease(repository, providerId, lane, slotName, { now }));
}
function overlayState(slot, state) {
if (!state)
return slot;
return {
...slot,
...(state.blockedUntil === undefined ? {} : { blockedUntil: state.blockedUntil }),
...(state.blockReason === undefined ? {} : { blockReason: state.blockReason }),
...(state.failureCount === undefined ? {} : { failureCount: state.failureCount }),
...(state.lease === undefined ? {} : { lease: state.lease }),
};
}
/**
* The slot as the requested model sees it: a live block on that model makes the
* slot unavailable to THIS request only, until the block's own expiry (senpi#2555).
*/
function overlayModelBlock(slot, until) {
if (until === undefined || (slot.blockedUntil !== undefined && slot.blockedUntil >= until))
return slot;
return {
...slot,
blockedUntil: until,
blockReason: slot.blockReason ?? "rate_limit",
};
}
/** Skipped-slot notices already printed in this process (field + reason; never a value). */
const warnedSlotReferences = new Set();
/**
* Lists the provider's rotation slots with sidecar health overlaid. Stored
* credentials own the lane when present; env slots participate only when
* nothing is stored, preserving today's resolution precedence. An env slot's
* persisted health applies only while its HMAC revision still matches the
* current env value, so rotating a key in place clears its own stale block.
*/
export async function listRotationSlots(sources, options = {}) {
const acquireLeases = options.acquireLeases !== false;
const modelId = options.modelId;
const now = sources.now ?? Date.now;
const { providerId, credential, env, repository } = sources;
const policySlots = [];
let referenceError;
for (const [name, ref] of Object.entries(sources.policy?.slots ?? {})) {
const envVarName = ref.env ?? `models.json:${name}`;
let key;
try {
key =
ref.env !== undefined
? env(ref.env)
: ref.value !== undefined
? await resolveConfigValue(ref.value, typeof ref.value === "string"
? {}
: Object.fromEntries(getConfigValueEnvVarNames(ref.value).flatMap((variable) => {
const value = env(variable);
return value === undefined ? [] : [[variable, value]];
})))
: undefined;
}
catch (error) {
if (!(error instanceof ConfigReferenceError))
throw error;
const notice = `${error.field}: configuration reference ${error.reason}; skipping credential slot`;
// Slots are listed on every request; a broken unused slot warns once per process, not once per turn.
if (!warnedSlotReferences.has(notice)) {
warnedSlotReferences.add(notice);
console.warn(notice);
}
referenceError ??= error;
continue;
}
if (!key)
continue;
policySlots.push({ name, envVarName, key, source: "env" });
}
if (credential) {
const state = await repository.listSlots(providerId, "stored");
const slots = [];
// A slot of the other kind cannot project, so a session must never be handed it (senpi#3486).
for (const slot of slotsOfOwnKind(credential)) {
if (slot.signedOut === true)
continue;
const persisted = state[slot.name];
const revisions = await repository.storedSlotRevisions(providerId, slot.name, {
key: slot.key,
access: slot.access,
refresh: slot.refresh,
});
const storedRevision = revisions.account;
const materialRevision = revisions.material;
// A verdict on the account survives a token refresh; a rejected token retires with its material (senpi#4093).
const applicable = applicableStoredState(persisted, revisions);
const modelUntil = activeModelBlockUntil(applicable?.modelBlocks, modelId, now());
// A slot still blocked for this model never takes the half-open probe lease:
// it cannot run, and holding the lease would starve other models' requests.
let lease;
if (acquireLeases &&
modelUntil === undefined &&
applicable?.blockedUntil !== undefined &&
applicable.blockedUntil <= now()) {
lease = await probeLease(repository, providerId, "stored", slot.name, now());
if (lease === undefined) {
const inFlight = await probeInFlight(repository, providerId, "stored", {
name: slot.name,
lane: "stored",
pinned: credential.pinned === slot.name,
storedRevision,
// A 401 on this slot after the lease ends is a verdict on this token (senpi#5097).
materialRevision,
}, (state) => applicableStoredState(state, revisions) !== undefined, now());
if (inFlight !== undefined)
slots.push(inFlight);
continue;
}
}
if (lease !== undefined && lease !== STORE_BUSY) {
const leased = await repository.listSlots(providerId, "stored");
const leasedState = leased[slot.name];
const leasedApplicable = applicableStoredState(leasedState, revisions);
// Re-read after the awaits: a concurrent request may have blocked this model meanwhile.
const leasedModelUntil = activeModelBlockUntil(leasedApplicable?.modelBlocks, modelId, now());
await releaseLeaseIfModelBlocked(repository, providerId, "stored", slot.name, lease.leaseId, leasedModelUntil);
slots.push(overlayModelBlock(overlayState({
name: slot.name,
lane: "stored",
pinned: credential.pinned === slot.name,
storedRevision,
materialRevision,
...(leasedModelUntil === undefined ? { heldLeaseId: lease.leaseId } : {}),
}, leasedApplicable), leasedModelUntil));
continue;
}
slots.push(overlayModelBlock(overlayState({
name: slot.name,
lane: "stored",
pinned: credential.pinned === slot.name,
storedRevision,
materialRevision,
}, applicable), modelUntil));
}
if (policySlots.length === 0) {
if (slots.length === 0 && referenceError !== undefined)
throw referenceError;
return slots;
}
const namedSources = {
...sources,
credential: undefined,
policy: { ...sources.policy, slots: {} },
};
const namedSlots = await listEnvRotationSlots(namedSources, policySlots, acquireLeases, modelId);
return [...slots, ...namedSlots];
}
const envSlots = [...discoverEnvSlots(providerId, env), ...policySlots];
if (envSlots.length === 0 && referenceError !== undefined)
throw referenceError;
return listEnvRotationSlots(sources, envSlots, acquireLeases, modelId);
}
async function listEnvRotationSlots(sources, envSlots, acquireLeases, modelId) {
if (envSlots.length === 0)
return [];
const { providerId, repository } = sources;
const now = sources.now ?? Date.now;
const state = await repository.listSlots(providerId, "env");
const slots = [];
for (const slot of envSlots) {
const persisted = state[slot.name];
const revision = await repository.envCredentialRevision(slot.envVarName, slot.key);
let applicable = persisted?.credentialRevision === revision ? persisted : undefined;
let modelUntil = activeModelBlockUntil(applicable?.modelBlocks, modelId, now());
let heldLeaseId;
if (acquireLeases &&
modelUntil === undefined &&
applicable?.blockedUntil !== undefined &&
applicable.blockedUntil <= now()) {
const lease = await probeLease(repository, providerId, "env", slot.name, now());
if (lease === undefined) {
const inFlight = await probeInFlight(repository, providerId, "env", { name: slot.name, lane: "env", envKey: slot.key, envVarName: slot.envVarName }, (state) => state?.credentialRevision === revision, now());
if (inFlight !== undefined)
slots.push(inFlight);
continue;
}
if (lease !== STORE_BUSY) {
const leased = await repository.listSlots(providerId, "env");
const leasedState = leased[slot.name];
applicable = leasedState?.credentialRevision === revision ? leasedState : undefined;
modelUntil = activeModelBlockUntil(applicable?.modelBlocks, modelId, now());
await releaseLeaseIfModelBlocked(repository, providerId, "env", slot.name, lease.leaseId, modelUntil);
if (modelUntil === undefined)
heldLeaseId = lease.leaseId;
}
}
slots.push(overlayModelBlock(overlayState({
name: slot.name,
lane: "env",
envKey: slot.key,
envVarName: slot.envVarName,
...(heldLeaseId === undefined ? {} : { heldLeaseId }),
}, applicable), modelUntil));
}
return slots;
}
//# sourceMappingURL=rotation-slots.js.map