UNPKG

@code-yeongyu/senpi

Version:

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

182 lines • 8.43 kB
import { isValidThinkingLevel } from "../../cli/args.js"; /** * The only providers a bare selector reaches: each model vendor's own lanes, * keyed by the vendor's model-id prefix. A bare id is a vendor policy, so a * reseller, gateway, cloud re-host or user-added provider that also publishes * the model is reached only through a selector that names it (`provider/id`). * Every provider id here exists in the builtin catalog or is registered by a * builtin extension (`anthropic-subscription`). */ export const FIRST_PARTY_PROVIDERS = [ { family: /^claude-/, providers: ["anthropic-subscription", "anthropic"] }, { family: /^(?:gpt-|o\d)/, providers: ["chatgpt-subscription", "openai"] }, { family: /^gemini-/, providers: ["google", "google-vertex"] }, { family: /^(?:kimi-|k\d)/, providers: ["kimi-coding", "moonshotai", "moonshotai-cn"] }, { family: /^glm-/, providers: ["zai", "zai-coding-cn"] }, { family: /^grok-/, providers: ["xai"] }, { family: /^deepseek-/, providers: ["deepseek"] }, { family: /^(?:mistral|codestral|devstral|magistral|ministral|pixtral)/, providers: ["mistral"] }, { family: /^minimax-/, providers: ["minimax", "minimax-cn"] }, { family: /^mimo-/, providers: ["xiaomi", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp", "xiaomi-token-plan-ams"], }, { family: /^qwen/, providers: ["qwen-token-plan", "qwen-token-plan-individual", "qwen-token-plan-cn", "alibaba-token-plan"], }, ]; /** * Whether a bare selector for `family` may resolve on `provider`. * * A rung (`sessionProvider` set) runs on the provider the chain key already runs * on: `resolveChainKey` only selects a key matching the running model's * `provider/id`, so that provider is the one the user chose. A fallback never * moves the turn to another account or billing lane of the same vendor (a * Claude subscription never falls onto the Anthropic API key, senpi#5518), and * `rankFamilyModels` keeps only the session's provider whenever it serves the * family. Another vendor's model named in the chain (a bare `k3` rung on a * Claude session) still reaches that vendor's first-party providers; anything * else takes an explicit `provider/id` entry. * * Bare keys pass no session provider: a key never routes a request, so a known * vendor's bare key attaches to its first-party sessions and an unknown * vendor's to every provider serving it. */ function inBareScope(provider, family, sessionProvider) { const normalized = provider.toLowerCase(); const vendor = FIRST_PARTY_PROVIDERS.find((entry) => entry.family.test(family)); if (sessionProvider === undefined) return vendor === undefined || vendor.providers.includes(normalized); const session = sessionProvider.toLowerCase(); if (normalized === session) return true; if (vendor === undefined || vendor.providers.includes(session)) return false; return vendor.providers.includes(normalized); } /** * Deterministic tie-break inside one auth tier. Earlier wins. Providers absent * from the table sort after every listed one, alphabetically. */ const PROVIDER_PRECEDENCE = ["anthropic-subscription", "anthropic", "kimi-coding"]; function authTier(model, tiers) { if (tiers.isUsingOAuth(model)) return 0; if (tiers.hasConfiguredAuth?.(model) === true) return 1; return 2; } /** * How many providers one bare selector may fan out to. A shipped default must * stay a short, readable chain: senpi's builtin catalog publishes popular models * under a dozen providers, and expanding to all of them turned `/fallback` into * an unreadable wall and the policy into "try every gateway that resells this". * Two keeps the useful property - a second account for the same model - without * the noise. */ const MAX_PROVIDERS_PER_FAMILY = 2; /** A selector is bare when it carries no provider prefix and no wildcard. */ export function parseBareSelector(raw) { const trimmed = raw.trim(); if (!trimmed || trimmed.includes("/") || trimmed.includes("*")) return undefined; const lastColon = trimmed.lastIndexOf(":"); if (lastColon === -1) return { family: trimmed.toLowerCase() }; const suffix = trimmed.slice(lastColon + 1).toLowerCase(); if (!isValidThinkingLevel(suffix)) return { family: trimmed.toLowerCase() }; const family = trimmed.slice(0, lastColon).trim().toLowerCase(); return family ? { family, thinkingLevel: suffix } : undefined; } /** * Strips a provider-side namespace so Bedrock's `global.anthropic.claude-opus-5` * and a gateway's `anthropic/claude-opus-5` both reduce to `claude-opus-5`. */ function withoutNamespace(modelId) { const cut = Math.max(modelId.lastIndexOf("."), modelId.lastIndexOf("/")); return cut === -1 ? modelId : modelId.slice(cut + 1); } /** * The ids a model answers to as a family. Kimi Code serves the Moonshot models under bare * ids (`k3.1-pro` is Moonshot's `kimi-k3.1-pro`), so a `kimi-` family reaches it too. */ function familyIds(model) { const id = model.id.toLowerCase(); const ids = [id, withoutNamespace(id)]; return /^k\d/.test(id) ? [...ids, `kimi-${id}`] : ids; } /** A model's own id outranks the Kimi Code alias, which outranks a dash-suffixed variant. */ function exactness(model, family) { const id = model.id.toLowerCase(); if (id === family || withoutNamespace(id) === family) return 2; return familyIds(model).includes(family) ? 1 : 0; } /** * Conservative family match. A bare id matches its exact model and dash-suffixed * variants (`k3` -> `k3-256k`) but never an arbitrary substring, so `claude-fable-5` * cannot capture `not-claude-fable-5`. */ export function matchesFamily(model, family) { return familyIds(model).some((id) => id === family || id.startsWith(`${family}-`)); } /** Exact id wins, then the shortest variant, then alphabetical. */ function pickVariant(models, family) { const ranked = [...models].sort((left, right) => { const exact = exactness(right, family) - exactness(left, family); if (exact !== 0) return exact; if (left.id.length !== right.id.length) return left.id.length - right.id.length; return left.id.localeCompare(right.id); }); return ranked[0]; } function precedenceIndex(provider) { const index = PROVIDER_PRECEDENCE.indexOf(provider.toLowerCase()); return index === -1 ? PROVIDER_PRECEDENCE.length : index; } /** * Ranks one model per in-scope, eligible provider: OAuth-credential providers first (a * logged-in subscription is the account the user actually wants used), then the * fixed precedence table, then alphabetically. */ export function rankFamilyModels(models, family, tiers, options = {}) { const byProvider = new Map(); for (const model of models) { if (!inBareScope(model.provider, family, options.sessionProvider)) continue; // Family first: eligibility reads provider settings from disk, and only family members need it. if (!matchesFamily(model, family)) continue; if (tiers.isFallbackEligible?.(model) === false) continue; const bucket = byProvider.get(model.provider); if (bucket) bucket.push(model); else byProvider.set(model.provider, [model]); } // The session's own provider serves the family: the rung stays there and never reaches another lane. const session = options.sessionProvider?.toLowerCase(); const own = [...byProvider.entries()].find(([provider]) => provider.toLowerCase() === session)?.[1]; const picked = (own === undefined ? [...byProvider.values()] : [own]).flatMap((variants) => { const variant = pickVariant(variants, family); return variant ? [variant] : []; }); const ranked = picked.sort((left, right) => { const tier = authTier(left, tiers) - authTier(right, tiers); if (tier !== 0) return tier; const precedence = precedenceIndex(left.provider) - precedenceIndex(right.provider); if (precedence !== 0) return precedence; return left.provider.localeCompare(right.provider); }); const limit = options.limit ?? ranked.length; return ranked.slice(0, limit); } export { MAX_PROVIDERS_PER_FAMILY }; //# sourceMappingURL=expansion.js.map