@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
251 lines • 11.9 kB
JavaScript
import { isValidThinkingLevel } from "../../cli/args.js";
import { findExactModelReferenceMatch, parseModelPattern } from "../model-resolver.js";
import { MAX_PROVIDERS_PER_FAMILY, parseBareSelector, rankFamilyModels } from "./expansion.js";
function availableModels(lookup) {
return "getAll" in lookup ? lookup.getAll() : [...lookup];
}
/**
* Auth tier is optional so array lookups and older callers keep working; without
* it every provider lands in the non-OAuth tier and the precedence table decides.
*/
function authTiers(lookup) {
if (Array.isArray(lookup))
return { isUsingOAuth: () => false };
const registry = lookup;
return {
isUsingOAuth: (model) => registry.isUsingOAuth?.(model) === true,
hasConfiguredAuth: typeof registry.hasConfiguredAuth === "function"
? (model) => registry.hasConfiguredAuth?.(model) === true
: undefined,
isFallbackEligible: typeof registry.isFallbackEligible === "function" ? memoizedEligibility(registry) : undefined,
};
}
/**
* Eligibility is a provider's switch (`fallbackEligible`), read from settings on disk; one
* canonicalization pass used to ask it once per catalog model, a 150-450 ms stall on the first
* fallback check of a session. Settings cannot change within one synchronous pass, so each
* provider is asked once per pass.
*/
function memoizedEligibility(registry) {
const known = new Map();
return (model) => {
const cached = known.get(model.provider);
if (cached !== undefined)
return cached;
const eligible = registry.isFallbackEligible?.(model) !== false;
known.set(model.provider, eligible);
return eligible;
};
}
/** An empty entry list is the documented opt-out; it survives as a tombstone. */
export function isChainTombstone(entries) {
return Array.isArray(entries) && entries.length === 0;
}
function selectorReference(raw) {
const trimmed = raw.trim();
if (!trimmed.includes("/") || trimmed.includes("*"))
return undefined;
const lastColon = trimmed.lastIndexOf(":");
if (lastColon === -1)
return { reference: trimmed };
const prefix = trimmed.slice(0, lastColon);
const suffix = trimmed.slice(lastColon + 1).toLowerCase();
if (!isValidThinkingLevel(suffix))
return { reference: trimmed };
return { reference: prefix, thinkingLevel: suffix };
}
/**
* Resolves only complete provider/model selectors. The full input is resolved first
* so colons belonging to a model id remain part of that id; aliases then resolve
* against the model-id portion while retaining the explicitly selected provider.
*/
export function parseFallbackSelector(raw, lookup) {
const models = availableModels(lookup);
const trimmed = raw.trim();
const parsedReference = selectorReference(trimmed);
if (!parsedReference)
return undefined;
const fullMatch = findExactModelReferenceMatch(trimmed, models);
if (fullMatch) {
return { raw: trimmed, provider: fullMatch.provider, id: fullMatch.id };
}
const slashIndex = parsedReference.reference.indexOf("/");
const provider = parsedReference.reference.slice(0, slashIndex).trim();
const modelPattern = parsedReference.reference.slice(slashIndex + 1).trim();
if (!provider || !modelPattern)
return undefined;
// The provider is explicit, so resolve the id pattern inside that provider only.
// A global lookup lets foreign ids containing the pattern (e.g. Bedrock's
// "us.anthropic.claude-opus-5") win over the requested provider's exact id.
const providerModels = models.filter((model) => model.provider.toLowerCase() === provider.toLowerCase());
const parsed = parseModelPattern(parsedReference.thinkingLevel ? `${modelPattern}:${parsedReference.thinkingLevel}` : modelPattern, providerModels, { allowInvalidThinkingLevelFallback: false });
if (!parsed.model || parsed.warning)
return undefined;
if (parsedReference.thinkingLevel && !parsed.thinkingLevel)
return undefined;
return {
raw: trimmed,
provider: parsed.model.provider,
id: parsed.model.id,
thinkingLevel: parsed.thinkingLevel,
};
}
export function formatSelector(model, thinkingLevel) {
const base = `${model.provider}/${model.id}`;
return thinkingLevel ? `${base}:${thinkingLevel}` : base;
}
export function baseSelector(selector) {
return `${selector.provider}/${selector.id}`;
}
/**
* A rung's identity: the model plus the thinking level it runs at. An entry
* without an explicit level inherits the running level, so it names the rung in
* flight rather than a second rung of that model.
*/
export function rungSelector(selector) {
const base = baseSelector(selector);
return selector.thinkingLevel ? `${base}:${selector.thinkingLevel}` : base;
}
/**
* Converts validated configuration to canonical selector strings for runtime lookup.
*
* A bare key or entry (no provider prefix) is a model-family policy: it expands
* only to that model vendor's first-party providers (see `FIRST_PARTY_PROVIDERS`),
* so a chain shipped for `claude-fable-5` applies on both Anthropic lanes and
* never lands a rung on a reseller the user did not name.
* Provider-qualified keys and entries keep exact semantics, and an explicit key
* always overrides the expansion it collides with.
*/
/**
* Chain key matched when no exact or base key resolves for the current model.
* Exists so a model without its own configured chain still has an escape lane:
* without it, a hard-failing upstream wedges the session terminal even though
* healthy fallback targets exist (desktop thread 487d7c29, 2026-08-28: nine
* consecutive upstream 500s, zero fallback attempts, terminal error).
* Users disable it with the `"*": []` tombstone.
*/
export function canonicalizeFallbackChains(chains, lookup) {
const models = availableModels(lookup);
const tiers = authTiers(lookup);
const canonical = {};
const explicitKeys = new Set();
const tombstones = new Set();
// Two entries can name one rung (`k3` and `kimi-k3` both reach Kimi Code's `k3`); the first keeps its place.
const expandEntries = (entries, keySelector, sessionProvider) => [
...new Set(expandEach(entries, keySelector, sessionProvider)),
];
const expandEach = (entries, keySelector, sessionProvider) => entries.flatMap((entry) => {
const bare = parseBareSelector(entry);
if (bare) {
return rankFamilyModels(models, bare.family, tiers, { limit: MAX_PROVIDERS_PER_FAMILY, sessionProvider })
.map((model) => bare.thinkingLevel ? `${formatSelector(model)}:${bare.thinkingLevel}` : formatSelector(model))
.filter((selector) => normalizedBase(selector) !== normalizedBase(keySelector));
}
const parsedEntry = parseFallbackSelector(entry, models);
return parsedEntry ? [formatParsedSelector(parsedEntry)] : [];
});
// Bare keys expand first so a same-named explicit key can overwrite them.
for (const [key, entries] of Object.entries(chains)) {
const bareKey = parseBareSelector(key);
if (!bareKey || !Array.isArray(entries))
continue;
if (isChainTombstone(entries)) {
for (const model of rankFamilyModels(models, bareKey.family, tiers)) {
tombstones.add(formatSelector(model).toLowerCase());
}
continue;
}
for (const model of rankFamilyModels(models, bareKey.family, tiers)) {
const keySelector = bareKey.thinkingLevel
? `${formatSelector(model)}:${bareKey.thinkingLevel}`
: formatSelector(model);
const canonicalEntries = expandEntries(entries, keySelector, model.provider);
if (canonicalEntries.length > 0)
canonical[keySelector] = canonicalEntries;
}
}
for (const [key, entries] of Object.entries(chains)) {
if (parseBareSelector(key))
continue;
const parsedKey = parseFallbackSelector(key, models);
if (!parsedKey || !Array.isArray(entries))
continue;
const keySelector = formatParsedSelector(parsedKey);
if (isChainTombstone(entries)) {
tombstones.add(normalizedBase(keySelector));
continue;
}
explicitKeys.add(keySelector.toLowerCase());
const canonicalEntries = expandEntries(entries, keySelector, parsedKey.provider);
if (canonicalEntries.length > 0)
canonical[keySelector] = canonicalEntries;
}
for (const key of Object.keys(canonical)) {
if (explicitKeys.has(key.toLowerCase()))
continue;
if (tombstones.has(normalizedBase(key)))
delete canonical[key];
}
return canonical;
}
export function resolveChainKey(currentModel, currentThinking, chains, options) {
return (ownChainKey(currentModel, currentThinking, chains) ??
siblingChainKey(currentModel, currentThinking, chains, options?.fastSibling));
}
function ownChainKey(model, thinking, chains) {
const base = formatSelector(model);
const exact = thinking ? `${base}:${thinking}` : base;
if (Object.hasOwn(chains, exact))
return exact;
if (Object.hasOwn(chains, base))
return base;
return undefined;
}
// A session started on a `-fast` alias runs on its base model (service-tier swaps them), so a chain
// keyed by that alias still governs it (omo#12063). Only the catalog-paired same-provider sibling counts.
function siblingChainKey(model, thinking, chains, sibling) {
if (!sibling || sibling.provider !== model.provider)
return undefined;
return ownChainKey(sibling, thinking, chains);
}
function formatParsedSelector(selector) {
return rungSelector(selector);
}
/** The explicit `:level` suffix of a selector string, when it has one. */
function explicitThinkingLevel(selector) {
const normalized = selector.trim().toLowerCase();
const lastColon = normalized.lastIndexOf(":");
if (lastColon === -1)
return undefined;
const suffix = normalized.slice(lastColon + 1);
return isValidThinkingLevel(suffix) ? suffix : undefined;
}
function normalizedBase(selector) {
if (typeof selector !== "string")
return baseSelector(selector).toLowerCase();
const normalized = selector.trim().toLowerCase();
const level = explicitThinkingLevel(normalized);
return level === undefined ? normalized : normalized.slice(0, normalized.lastIndexOf(":"));
}
function normalizedExact(selector) {
return typeof selector === "string" ? selector.trim().toLowerCase() : formatParsedSelector(selector).toLowerCase();
}
/**
* Returns entries after the current fallback. A primary or unknown selector starts
* from the beginning, which also makes re-entry after stale runtime state safe.
*/
export function candidatesAfter(chainEntries, currentSelector) {
const exact = normalizedExact(currentSelector);
const exactIndex = chainEntries.findIndex((entry) => entry.toLowerCase() === exact);
if (exactIndex !== -1)
return chainEntries.slice(exactIndex + 1);
const base = normalizedBase(currentSelector);
// Only a same-base entry WITHOUT a level is the position: it inherits the
// running level, so it is the rung in flight. A same-base entry at another
// explicit level is a rung of its own - with `["X:off", "Y"]` and the session
// on X:high, matching on the base alone consumed X:off as the position and the
// chain skipped straight past it to Y.
const baseIndex = chainEntries.findIndex((entry) => normalizedBase(entry) === base && explicitThinkingLevel(entry) === undefined);
return baseIndex === -1 ? chainEntries : chainEntries.slice(baseIndex + 1);
}
//# sourceMappingURL=chains.js.map