@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
891 lines • 39.3 kB
JavaScript
/**
* Model resolution, scoping, and initial selection
*/
import { getCursorVariantAlias, modelsAreEqual, parseCursorVariantId, } from "@earendil-works/pi-ai";
import chalk from "chalk";
import { minimatch } from "minimatch";
import { isValidThinkingLevel } from "../cli/args.js";
import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./extensions/builtin/anthropic-subscription/account-management.js";
import { selectProviderDefault } from "./provider-default-selection.js";
import { ultrafastSelectionWarning } from "./ultrafast-lanes.js";
/** Default model IDs for each known provider */
export const defaultModelPerProvider = {
"alibaba-token-plan": "qwen3.7-max",
"amazon-bedrock": "us.anthropic.claude-opus-5-5",
"ant-ling": "Ring-2.6-1T",
"anthropic-subscription": "claude-opus-5-5",
anthropic: "claude-opus-5-5",
bai: "gpt-5.6-sol",
openai: "gpt-6.2-sol",
"azure-openai-responses": "gpt-5.4",
"chatgpt-subscription": "gpt-6.2-sol",
ollama: "qwen3.5:397b",
// Cursor ships no models until its chat protocol is ported; "auto" matches
// the Cursor agent's native model auto-selection once models exist.
cursor: "auto",
// Radius resolves its catalog after discovery; "balanced" is the selectable default.
radius: "balanced",
nvidia: "nvidia/nemotron-3-ultra-550b-a55b",
deepseek: "deepseek-v4-pro",
google: "gemini-3.1-pro-preview",
"google-vertex": "gemini-3.1-pro-preview",
"github-copilot": "gpt-5.4",
openrouter: "moonshotai/kimi-k2.6",
"vercel-ai-gateway": "zai/glm-5.1",
opengateway: "moonshotai/kimi-k3.1-pro",
xai: "grok-4.7",
groq: "openai/gpt-oss-120b",
cerebras: "gpt-oss-120b",
zai: "glm-5.3",
"zai-coding-cn": "glm-5.3",
mistral: "devstral-medium-latest",
minimax: "MiniMax-M2.7",
"minimax-cn": "MiniMax-M2.7",
moonshotai: "kimi-k3.1-pro",
"moonshotai-cn": "kimi-k3.1-pro",
huggingface: "moonshotai/Kimi-K2.6",
fireworks: "accounts/fireworks/models/kimi-k3",
together: "moonshotai/Kimi-K3",
venice: "z-ai-glm-5-3",
baseten: "zai-org/GLM-5.2",
opencode: "kimi-k2.6",
"opencode-go": "kimi-k3.1-pro",
"kimi-coding": "kimi-for-coding",
meta: "muse-spark-1.3",
"cloudflare-workers-ai": "@cf/moonshotai/kimi-k2.6",
"cloudflare-ai-gateway": "workers-ai/@cf/moonshotai/kimi-k2.6",
"qwen-token-plan": "qwen3.7-max",
"qwen-token-plan-cn": "qwen3.7-max",
"qwen-token-plan-individual": "qwen3.8-max",
xiaomi: "mimo-v2.6-pro",
"xiaomi-token-plan-cn": "mimo-v2.6-pro",
"xiaomi-token-plan-ams": "mimo-v2.6-pro",
"xiaomi-token-plan-sgp": "mimo-v2.6-pro",
};
export function getModelNarrowingPatterns(options) {
return options.cliPatterns ?? options.legacyEnabledPatterns ?? [];
}
/**
* Helper to check if a model ID looks like an alias (no date suffix)
* Dates are typically in format: -20241022 or -20250929
*/
function isAlias(id) {
// Check if ID ends with -latest
if (id.endsWith("-latest"))
return true;
// Check if ID ends with a date pattern (-YYYYMMDD)
const datePattern = /-\d{8}$/;
return !datePattern.test(id);
}
/**
* Find an exact model reference match.
* Supports either a bare model id or a canonical provider/modelId reference.
* When matching by bare id, ambiguous matches across providers are rejected.
*/
export function findExactModelReferenceMatch(modelReference, availableModels) {
const trimmedReference = modelReference.trim();
if (!trimmedReference) {
return undefined;
}
const normalizedReference = trimmedReference.toLowerCase();
const canonicalMatches = availableModels.filter((model) => `${model.provider}/${model.id}`.toLowerCase() === normalizedReference);
if (canonicalMatches.length === 1) {
return canonicalMatches[0];
}
if (canonicalMatches.length > 1) {
return undefined;
}
const slashIndex = trimmedReference.indexOf("/");
if (slashIndex !== -1) {
const provider = trimmedReference.substring(0, slashIndex).trim();
const modelId = trimmedReference.substring(slashIndex + 1).trim();
if (provider && modelId) {
const providerMatches = availableModels.filter((model) => model.provider.toLowerCase() === provider.toLowerCase() &&
model.id.toLowerCase() === modelId.toLowerCase());
if (providerMatches.length === 1) {
return providerMatches[0];
}
if (providerMatches.length > 1) {
return undefined;
}
}
}
const idMatches = availableModels.filter((model) => model.id.toLowerCase() === normalizedReference);
return idMatches.length === 1 ? idMatches[0] : undefined;
}
/**
* Try to match a pattern to a model from the available models list.
* Returns the matched model or undefined if no match found.
*/
const CURSOR_PROVIDER_IDS = new Set(["cursor", "cursor-cli-oauth"]);
const CURSOR_ALIAS_LEVEL_TOKENS = ["minimal", "low", "medium", "high", "extra-high", "xhigh", "max", "none"];
function legacySelection(legacyVariantId) {
const alias = getCursorVariantAlias(legacyVariantId);
if (!alias?.level)
return undefined;
return { level: alias.level, source: "legacy-variant", legacyVariantId };
}
function derivedCursorVariantIds(model) {
if ((model.provider !== "cursor" || model.api !== "cursor-agent") &&
(model.provider !== "cursor-cli-oauth" || model.api !== "cursor-cli-oauth"))
return undefined;
// The CLI provider registers its own API id but shares Cursor's catalog compat schema.
return model.compat?.cursorReasoning?.variantIds;
}
/**
* Reverse lookup through variant ids a runtime-derived Cursor group observed (senpi#2038).
* Case-insensitive like `findExactModelReferenceMatch`, which resolved these ids before grouping.
*/
function derivedCursorVariantMatch(model, reference) {
const variantIds = derivedCursorVariantIds(model);
if (variantIds === undefined)
return undefined;
const normalized = reference.toLowerCase();
for (const [level, id] of Object.entries(variantIds)) {
if (id?.toLowerCase() === normalized)
return { level: level, variantId: id };
}
return undefined;
}
function derivedResolution(model, match) {
return {
model,
thinkingLevel: match.level,
thinkingSelection: { level: match.level, source: "legacy-variant", legacyVariantId: match.variantId },
};
}
function cursorLegacySelection(model, variantId) {
const alias = legacySelection(variantId);
if (alias)
return alias;
const match = derivedCursorVariantMatch(model, variantId);
return match === undefined
? undefined
: { level: match.level, source: "legacy-variant", legacyVariantId: match.variantId };
}
function resolveLegacyCursorReference(modelReference, availableModels) {
const trimmed = modelReference.trim();
if (!trimmed)
return undefined;
const slashIndex = trimmed.indexOf("/");
const explicitProvider = slashIndex === -1 ? undefined : trimmed.slice(0, slashIndex);
const legacyVariantId = slashIndex === -1 ? trimmed : trimmed.slice(slashIndex + 1);
const alias = getCursorVariantAlias(legacyVariantId);
const providerMatches = (model) => CURSOR_PROVIDER_IDS.has(model.provider) &&
(!explicitProvider || model.provider.toLowerCase() === explicitProvider.toLowerCase());
if (alias) {
const candidates = availableModels.filter((model) => providerMatches(model) && model.id === alias.targetId);
if (candidates.length !== 1)
return undefined;
const thinkingSelection = legacySelection(legacyVariantId);
return {
model: candidates[0],
thinkingLevel: thinkingSelection?.level,
thinkingSelection,
};
}
// Unlike static aliases, derived aliases must not displace an exact raw model.
const exactCandidates = explicitProvider ? availableModels.filter(providerMatches) : availableModels;
if (findExactModelReferenceMatch(trimmed, [...exactCandidates]))
return undefined;
// Variant ids only the runtime derivation groups resolve through the observed ids (senpi#2038).
const derivedCandidates = availableModels.flatMap((model) => {
const match = providerMatches(model) ? derivedCursorVariantMatch(model, legacyVariantId) : undefined;
return match === undefined ? [] : [{ model, match }];
});
if (derivedCandidates.length !== 1)
return undefined;
return derivedResolution(derivedCandidates[0].model, derivedCandidates[0].match);
}
function cursorLegacyAliasesForModel(model) {
if (!CURSOR_PROVIDER_IDS.has(model.provider))
return [];
const targetId = model.id;
const baseId = targetId.endsWith("-thinking") ? targetId.slice(0, -9) : targetId;
const candidates = new Set([targetId, `${baseId}-thinking`, `${baseId}-fast`]);
for (const level of CURSOR_ALIAS_LEVEL_TOKENS) {
candidates.add(`${baseId}-${level}`);
candidates.add(`${baseId}-thinking-${level}`);
candidates.add(`${baseId}-${level}-thinking`);
candidates.add(`${targetId}-${level}`);
}
const aliases = [...candidates].filter((candidate) => getCursorVariantAlias(candidate)?.targetId === targetId);
for (const derivedId of Object.values(derivedCursorVariantIds(model) ?? {})) {
aliases.push(derivedId);
}
return aliases;
}
function resolveDerivedCursorVariant(provider, modelId, modelSource) {
const parsed = parseCursorVariantId(modelId);
if (parsed.fast || parsed.level === undefined || parsed.baseId === "")
return undefined;
const targetId = parsed.thinking === true ? `${parsed.baseId}-thinking` : parsed.baseId;
const model = modelSource.getModel(provider, targetId);
const match = model === undefined ? undefined : derivedCursorVariantMatch(model, modelId);
if (model === undefined || match === undefined)
return undefined;
return derivedResolution(model, match);
}
export function resolveStoredModelReference(provider, modelId, modelSource) {
if (CURSOR_PROVIDER_IDS.has(provider)) {
const alias = getCursorVariantAlias(modelId);
if (alias) {
const model = modelSource.getModel(provider, alias.targetId);
if (model) {
const thinkingSelection = legacySelection(modelId);
return { model, thinkingLevel: thinkingSelection?.level, thinkingSelection };
}
}
else {
const direct = modelSource.getModel(provider, modelId);
if (direct)
return { model: direct };
const derived = resolveDerivedCursorVariant(provider, modelId, modelSource);
if (derived)
return derived;
}
}
const direct = modelSource.getModel(provider, modelId);
return direct ? { model: direct } : undefined;
}
/**
* A saved selection, preferring a lane that can authenticate it. A Claude subscription moved from
* the direct `anthropic` provider to the Agent SDK lane (senpi#3259), so a saved `anthropic/<id>`
* follows it to `anthropic-subscription/<id>` when only that lane holds auth.
*/
function resolveStoredModelWithAuth(provider, modelId, modelRuntime) {
const resolved = resolveStoredModelReference(provider, modelId, modelRuntime);
if (resolved && modelRuntime.hasConfiguredAuth(resolved.model.provider))
return resolved;
if (provider === "anthropic") {
const lane = resolveStoredModelReference(ANTHROPIC_SUBSCRIPTION_PROVIDER_ID, modelId, modelRuntime);
if (lane && modelRuntime.hasConfiguredAuth(lane.model.provider))
return lane;
}
return resolved;
}
function tryMatchModel(modelPattern, availableModels) {
const exactMatch = findExactModelReferenceMatch(modelPattern, availableModels);
if (exactMatch) {
return exactMatch;
}
// No exact match - fall back to partial matching
const matches = availableModels.filter((m) => m.id.toLowerCase().includes(modelPattern.toLowerCase()) ||
m.name?.toLowerCase().includes(modelPattern.toLowerCase()));
if (matches.length === 0) {
return undefined;
}
// Separate into aliases and dated versions
const aliases = matches.filter((m) => isAlias(m.id));
const datedVersions = matches.filter((m) => !isAlias(m.id));
if (aliases.length > 0) {
// Prefer alias - if multiple aliases, pick the one that sorts highest
aliases.sort((a, b) => b.id.localeCompare(a.id));
return aliases[0];
}
else {
// No alias found, pick latest dated version
datedVersions.sort((a, b) => b.id.localeCompare(a.id));
return datedVersions[0];
}
}
function buildFallbackModel(provider, modelId, availableModels) {
const providerModels = availableModels.filter((m) => m.provider === provider);
if (providerModels.length === 0)
return undefined;
const defaultId = defaultModelPerProvider[provider];
const baseModel = defaultId
? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])
: providerModels[0];
return {
...baseModel,
id: modelId,
name: modelId,
};
}
const SERVICE_TIER_VALUES = ["auto", "flex", "priority", "ultrafast"];
function isServiceTier(value) {
return SERVICE_TIER_VALUES.includes(value);
}
/** Invalid-decorator warnings discard the decorators parsed with them. An Ultrafast advisory does not. */
function dropsParsedDecorators(warning) {
return warning?.startsWith("Invalid thinking level") ?? false;
}
function pushUltrafastAdvisory(diagnostics, pattern, model, serviceTier) {
const message = ultrafastSelectionWarning(model, serviceTier);
if (!message)
return;
diagnostics.push({ type: "warning", code: "ultrafast-undocumented", message, pattern });
}
/**
* Parse a pattern to extract model, thinking level, and service tier.
* Handles models with colons in their IDs (e.g., OpenRouter's :exacto suffix).
*
* Grammar: `<model-pattern>[:<auto|flex|priority>][:<thinking-level>]`
*
* Algorithm:
* 1. Try to match the FULL pattern as a model (mandatory first step: real model ids
* contain colons, and one may even end in a decorator-looking segment)
* 2. If found, return it with no decorators
* 3. If not found and the pattern has colons, split on the last colon and consume
* recognized decorators right-to-left:
* - valid thinking level -> use it and recurse on the prefix
* - valid service tier -> use it and recurse on the prefix
* - anything else -> warn and recurse on the prefix without decorators
*
* A decorator parsed further right never overrides one parsed further left, so the
* leftmost occurrence (the grammar's slot order) wins.
*
* @internal Exported for testing
*/
export function parseModelPattern(pattern, availableModels, options) {
const legacyMatch = resolveLegacyCursorReference(pattern, availableModels);
if (legacyMatch) {
return { ...legacyMatch, serviceTier: undefined, warning: undefined };
}
const fullMatch = tryMatchModel(pattern, availableModels);
if (fullMatch) {
return {
model: fullMatch,
thinkingLevel: undefined,
thinkingSelection: undefined,
serviceTier: undefined,
warning: undefined,
};
}
const lastColonIndex = pattern.lastIndexOf(":");
if (lastColonIndex === -1) {
return { model: undefined, thinkingLevel: undefined, serviceTier: undefined, warning: undefined };
}
const prefix = pattern.substring(0, lastColonIndex);
const suffix = pattern.substring(lastColonIndex + 1);
if (isValidThinkingLevel(suffix)) {
const result = parseModelPattern(prefix, availableModels, options);
if (result.model) {
const thinkingLevel = dropsParsedDecorators(result.warning) ? undefined : (result.thinkingLevel ?? suffix);
return {
model: result.model,
thinkingLevel,
thinkingSelection: thinkingLevel ? { level: thinkingLevel, source: "explicit" } : undefined,
serviceTier: result.serviceTier,
warning: result.warning,
};
}
return result;
}
else if (isServiceTier(suffix)) {
const result = parseModelPattern(prefix, availableModels, options);
if (result.model) {
const serviceTier = dropsParsedDecorators(result.warning) ? undefined : (result.serviceTier ?? suffix);
return {
model: result.model,
thinkingLevel: result.thinkingLevel,
thinkingSelection: result.thinkingSelection,
serviceTier,
warning: result.warning ?? ultrafastSelectionWarning(result.model, serviceTier),
};
}
return result;
}
else {
const allowFallback = options?.allowInvalidThinkingLevelFallback ?? true;
if (!allowFallback) {
return { model: undefined, thinkingLevel: undefined, serviceTier: undefined, warning: undefined };
}
const result = parseModelPattern(prefix, availableModels, options);
if (result.model) {
return {
model: result.model,
thinkingLevel: undefined,
thinkingSelection: undefined,
serviceTier: result.serviceTier,
warning: `Invalid thinking level "${suffix}" in pattern "${pattern}". Using default instead.`,
};
}
return result;
}
}
export function resolveModelScopeFromModels(patterns, models) {
const availableModels = [...models];
const scopedModels = [];
const diagnostics = [];
const patternResolutions = [];
const claimedIds = new Set();
const canonicalId = (model) => `${model.provider}/${model.id}`;
const addScoped = (entry) => {
const id = canonicalId(entry.model);
if (claimedIds.has(id))
return undefined;
claimedIds.add(id);
scopedModels.push(entry);
return id;
};
for (const pattern of patterns) {
const isGlob = pattern.includes("*") || pattern.includes("?") || pattern.includes("[");
if (isGlob) {
let globPattern = pattern;
let thinkingLevel;
let serviceTier;
for (;;) {
const colonIdx = globPattern.lastIndexOf(":");
if (colonIdx === -1)
break;
const suffix = globPattern.substring(colonIdx + 1);
if (thinkingLevel === undefined && isValidThinkingLevel(suffix))
thinkingLevel = suffix;
else if (serviceTier === undefined && isServiceTier(suffix))
serviceTier = suffix;
else
break;
globPattern = globPattern.substring(0, colonIdx);
}
const exactMatch = findExactModelReferenceMatch(globPattern, availableModels);
if (exactMatch) {
const thinkingSelection = thinkingLevel ? { level: thinkingLevel, source: "explicit" } : undefined;
const owned = addScoped({ model: exactMatch, thinkingLevel, thinkingSelection, serviceTier });
pushUltrafastAdvisory(diagnostics, pattern, exactMatch, serviceTier);
patternResolutions.push({
pattern,
ownedIds: owned ? [owned] : [],
thinkingLevel,
serviceTier,
unresolved: false,
isGlob: true,
});
continue;
}
const canonicalPattern = globPattern.includes("/");
const matches = (provider, id) => minimatch(`${provider}/${id}`, globPattern, { nocase: true }) ||
(!canonicalPattern && minimatch(id, globPattern, { nocase: true }));
const projections = new Map();
for (const model of availableModels) {
const id = canonicalId(model);
if (matches(model.provider, model.id)) {
projections.set(id, { model, aliases: [] });
}
for (const aliasId of cursorLegacyAliasesForModel(model)) {
if (!matches(model.provider, aliasId))
continue;
const projection = projections.get(id) ?? { model, aliases: [] };
projection.aliases.push({ id: aliasId, selection: cursorLegacySelection(model, aliasId) });
projections.set(id, projection);
}
}
if (projections.size === 0) {
diagnostics.push({
type: "warning",
code: "no-match",
message: `No models match pattern "${pattern}"`,
pattern,
});
patternResolutions.push({
pattern,
ownedIds: [],
thinkingLevel,
serviceTier,
unresolved: true,
isGlob: true,
});
continue;
}
const ownedIds = [];
for (const { model, aliases } of projections.values()) {
let thinkingSelection;
let projectedLevel = thinkingLevel;
if (thinkingLevel !== undefined) {
thinkingSelection = { level: thinkingLevel, source: "explicit" };
}
else {
const selections = aliases.flatMap((alias) => (alias.selection ? [alias.selection] : []));
const levels = new Set(selections.map((selection) => selection.level));
if (levels.size === 1 && selections.length > 0) {
thinkingSelection = [...selections].sort((a, b) => (a.legacyVariantId ?? "").localeCompare(b.legacyVariantId ?? ""))[0];
projectedLevel = thinkingSelection.level;
}
}
const owned = addScoped({ model, thinkingLevel: projectedLevel, thinkingSelection, serviceTier });
pushUltrafastAdvisory(diagnostics, pattern, model, serviceTier);
if (owned)
ownedIds.push(owned);
}
patternResolutions.push({
pattern,
ownedIds,
thinkingLevel,
serviceTier,
unresolved: false,
isGlob: true,
});
continue;
}
const { model, thinkingLevel, thinkingSelection, serviceTier, warning } = parseModelPattern(pattern, availableModels);
if (warning) {
diagnostics.push({
type: "warning",
code: model && warning === ultrafastSelectionWarning(model, serviceTier)
? "ultrafast-undocumented"
: "invalid-thinking-level",
message: warning,
pattern,
});
}
if (!model) {
diagnostics.push({
type: "warning",
code: "no-match",
message: `No models match pattern "${pattern}"`,
pattern,
});
patternResolutions.push({
pattern,
ownedIds: [],
thinkingLevel,
serviceTier,
unresolved: true,
isGlob: false,
});
continue;
}
const owned = addScoped({ model, thinkingLevel, thinkingSelection, serviceTier });
patternResolutions.push({
pattern,
ownedIds: owned ? [owned] : [],
thinkingLevel,
serviceTier,
unresolved: false,
isGlob: false,
});
}
return { scopedModels, diagnostics, patternResolutions };
}
export async function resolveModelScopeWithDiagnostics(patterns, modelRuntime, options) {
return resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options));
}
export async function resolveModelScope(patterns, modelRuntime, options) {
const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime, options);
for (const diagnostic of diagnostics) {
if (options?.onWarning) {
options.onWarning(diagnostic.message);
continue;
}
console.warn(chalk.yellow(`Warning: ${diagnostic.message}`));
}
return scopedModels;
}
/**
* Resolve a single model from CLI flags.
*
* Supports:
* - --provider <provider> --model <pattern>
* - --model <provider>/<pattern>
* - Fuzzy matching (same rules as model scoping: exact id, then partial id/name)
*
* Note: This does not apply the thinking level by itself, but it may *parse* and
* return a thinking level from "<pattern>:<thinking>" so the caller can apply it.
*/
export function resolveCliModel(options) {
const { cliProvider, cliModel, cliThinking, modelRuntime } = options;
if (!cliModel) {
return { model: undefined, warning: undefined, error: undefined };
}
// Important: use *all* models here, not just models with pre-configured auth.
// This allows "--api-key" to be used for first-time setup.
const availableModels = [...modelRuntime.getModels()];
if (availableModels.length === 0) {
return {
model: undefined,
warning: undefined,
error: "No models available. Check your installation or add models to models.json.",
};
}
// Build canonical provider lookup (case-insensitive)
const providerMap = new Map();
for (const m of availableModels) {
providerMap.set(m.provider.toLowerCase(), m.provider);
}
let provider = cliProvider ? providerMap.get(cliProvider.toLowerCase()) : undefined;
if (cliProvider && !provider) {
return {
model: undefined,
warning: undefined,
error: `Unknown provider "${cliProvider}". Use --list-models to see available providers/models.`,
};
}
// If no explicit --provider, try to interpret "provider/model" format first.
// When the prefix before the first slash matches a known provider, prefer that
// interpretation over matching models whose IDs literally contain slashes
// (e.g. "zai/glm-5" should resolve to provider=zai, model=glm-5, not to a
// vercel-ai-gateway model with id "zai/glm-5").
let pattern = cliModel;
let inferredProvider = false;
if (!provider) {
const slashIndex = cliModel.indexOf("/");
if (slashIndex !== -1) {
const maybeProvider = cliModel.substring(0, slashIndex);
const canonical = providerMap.get(maybeProvider.toLowerCase());
if (canonical) {
provider = canonical;
pattern = cliModel.substring(slashIndex + 1);
inferredProvider = true;
}
}
}
// If no provider was inferred from the slash, try exact matches without provider inference.
// This handles models whose IDs naturally contain slashes (e.g. OpenRouter-style IDs).
// Bare exact IDs can exist in multiple providers, so do not choose by catalog order.
// Prefer the sole authenticated provider when there is one; otherwise require an
// explicit provider to avoid silently selecting an unusable provider.
if (!provider) {
const lower = cliModel.toLowerCase();
const exactMatches = availableModels.filter((m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower);
if (exactMatches.length === 1) {
return { model: exactMatches[0], warning: undefined, thinkingLevel: undefined, error: undefined };
}
if (exactMatches.length > 1) {
const authenticatedExactMatches = exactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));
if (authenticatedExactMatches.length === 1) {
return {
model: authenticatedExactMatches[0],
warning: undefined,
thinkingLevel: undefined,
error: undefined,
};
}
const matches = exactMatches
.map((m) => `${m.provider}/${m.id}`)
.sort((a, b) => a.localeCompare(b))
.join(", ");
const authHint = authenticatedExactMatches.length === 0
? "No matching provider is authenticated."
: "More than one matching provider is authenticated.";
return {
model: undefined,
warning: undefined,
thinkingLevel: undefined,
error: `Model "${cliModel}" is ambiguous across providers: ${matches}. ${authHint} Use --provider or provider/model.`,
};
}
}
if (cliProvider && provider) {
// If both were provided, tolerate --model <provider>/<pattern> by stripping the provider prefix
const prefix = `${provider}/`;
if (cliModel.toLowerCase().startsWith(prefix.toLowerCase())) {
pattern = cliModel.substring(prefix.length);
}
}
const candidates = provider ? availableModels.filter((m) => m.provider === provider) : availableModels;
const { model, thinkingLevel, thinkingSelection, serviceTier, warning } = parseModelPattern(pattern, candidates, {
allowInvalidThinkingLevelFallback: false,
});
if (model) {
// If provider inference matched an unauthenticated provider/model pair, prefer
// one exact raw model-id match that is authenticated. This keeps
// "provider/model" syntax preferred when usable, but handles models whose
// literal id starts with a known provider name (for example
// commandcode model id "xiaomi/mimo-v2.5-pro").
if (inferredProvider) {
const rawExactMatches = availableModels.filter((m) => m.id.toLowerCase() === cliModel.toLowerCase() && !modelsAreEqual(m, model));
if (rawExactMatches.length > 0 && !modelRuntime.hasConfiguredAuth(model.provider)) {
const authenticatedRawMatches = rawExactMatches.filter((m) => modelRuntime.hasConfiguredAuth(m.provider));
if (authenticatedRawMatches.length === 1) {
return {
model: authenticatedRawMatches[0],
thinkingLevel: undefined,
serviceTier,
warning: undefined,
error: undefined,
};
}
}
}
return { model, thinkingLevel, thinkingSelection, serviceTier, warning, error: undefined };
}
if (inferredProvider) {
const lower = cliModel.toLowerCase();
const exact = availableModels.find((m) => m.id.toLowerCase() === lower || `${m.provider}/${m.id}`.toLowerCase() === lower);
if (exact) {
return { model: exact, warning: undefined, thinkingLevel: undefined, serviceTier, error: undefined };
}
const fallback = parseModelPattern(cliModel, availableModels, {
allowInvalidThinkingLevelFallback: false,
});
if (fallback.model) {
return {
model: fallback.model,
thinkingLevel: fallback.thinkingLevel,
serviceTier: fallback.serviceTier,
warning: fallback.warning,
error: undefined,
};
}
}
if (provider) {
// Parse thinking level suffix from the pattern before building the fallback model,
// but only when --thinking is not explicitly provided.
// e.g. "zai-org/GLM-5.1-FP8:high" → modelId="zai-org/GLM-5.1-FP8", fallbackThinking="high"
let fallbackPattern = pattern;
let fallbackThinking;
if (!cliThinking) {
const lastColon = pattern.lastIndexOf(":");
if (lastColon !== -1) {
const suffix = pattern.substring(lastColon + 1);
if (isValidThinkingLevel(suffix)) {
fallbackPattern = pattern.substring(0, lastColon);
fallbackThinking = suffix;
}
}
}
const fallbackModel = buildFallbackModel(provider, fallbackPattern, availableModels);
if (fallbackModel) {
const requestedThinking = cliThinking ?? fallbackThinking;
const model = requestedThinking && requestedThinking !== "off" ? { ...fallbackModel, reasoning: true } : fallbackModel;
const fallbackWarning = warning
? `${warning} Model "${fallbackPattern}" not found for provider "${provider}". Using custom model id.`
: `Model "${fallbackPattern}" not found for provider "${provider}". Using custom model id.`;
return {
model,
thinkingLevel: fallbackThinking,
serviceTier,
warning: fallbackWarning,
error: undefined,
};
}
}
const display = provider ? `${provider}/${pattern}` : cliModel;
return {
model: undefined,
thinkingLevel: undefined,
serviceTier,
warning,
error: `Model "${display}" not found. Use --list-models to see available models.`,
};
}
/**
* Find the initial model to use based on priority:
* 1. CLI args (provider + model)
* 2. First model from scoped models (if not continuing/resuming)
* 3. Restored from session (if continuing/resuming)
* 4. Saved default from settings
* 5. First available model with valid API key
*/
export async function findInitialModel(options) {
const { cliProvider, cliModel, scopedModels, isContinuing, defaultProvider, defaultModelId, modelRuntime } = options;
let model;
// 1. CLI args take priority
if (cliProvider && cliModel) {
const resolved = resolveCliModel({
cliProvider,
cliModel,
modelRuntime,
});
if (resolved.error) {
console.error(chalk.red(resolved.error));
process.exit(1);
}
if (resolved.model) {
return {
model: resolved.model,
thinkingLevel: resolved.thinkingLevel,
thinkingSelection: resolved.thinkingSelection,
fallbackMessage: undefined,
provenance: "cli",
};
}
}
// 2. Use first model from scoped models (skip if continuing/resuming)
if (scopedModels.length > 0 && !isContinuing) {
const scopedModel = scopedModels[0];
const perModel = options.modelThinkingLevels?.[`${scopedModel.model.provider}/${scopedModel.model.id}`];
return {
model: scopedModels[0].model,
thinkingLevel: perModel ?? scopedModels[0].thinkingLevel,
thinkingSelection: scopedModels[0].thinkingSelection,
fallbackMessage: undefined,
provenance: "scoped",
};
}
// 3. Try saved default from settings if auth is configured.
if (defaultProvider && defaultModelId) {
const resolved = resolveStoredModelWithAuth(defaultProvider, defaultModelId, modelRuntime);
if (resolved && modelRuntime.hasConfiguredAuth(resolved.model.provider)) {
model = resolved.model;
return {
model,
thinkingLevel: resolved.thinkingLevel,
thinkingSelection: resolved.thinkingSelection,
fallbackMessage: undefined,
provenance: "settings",
};
}
}
// 4. Try first available model with valid API key. Runtime callers use the settled
// snapshot; compatibility sources may still expose only the async availability API.
const availableModels = [
...(typeof modelRuntime.getAvailableSnapshot === "function"
? modelRuntime.getAvailableSnapshot()
: await modelRuntime.getAvailable()),
];
const selected = selectProviderDefault(availableModels, defaultModelPerProvider, modelRuntime);
if (selected) {
return {
model: selected.model,
thinkingLevel: undefined,
fallbackMessage: undefined,
provenance: selected.provenance,
};
}
// 5. No model found
return {
model: undefined,
thinkingLevel: undefined,
fallbackMessage: undefined,
provenance: "first-available",
};
}
/**
* Restore model from session, with fallback to available models
*/
export async function restoreModelFromSession(savedProvider, savedModelId, currentModel, shouldPrintMessages, modelRuntime) {
const restored = resolveStoredModelWithAuth(savedProvider, savedModelId, modelRuntime);
const restoredModel = restored?.model;
// A signed-out provider keeps its model; the first prompt asks for a login (senpi#4410).
if (restoredModel) {
if (shouldPrintMessages) {
console.log(chalk.dim(`Restored model: ${restoredModel.provider}/${restoredModel.id}`));
}
return { model: restoredModel, thinkingSelection: restored.thinkingSelection, fallbackMessage: undefined };
}
const reason = "model no longer exists";
if (shouldPrintMessages) {
console.error(chalk.yellow(`Warning: Could not restore model ${savedProvider}/${savedModelId} (${reason}).`));
}
// If we already have a model, use it as fallback
if (currentModel) {
if (shouldPrintMessages) {
console.log(chalk.dim(`Falling back to: ${currentModel.provider}/${currentModel.id}`));
}
return {
model: currentModel,
fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${currentModel.provider}/${currentModel.id}.`,
};
}
// Try to find any available model
const availableModels = [
...(typeof modelRuntime.getAvailableSnapshot === "function"
? modelRuntime.getAvailableSnapshot()
: await modelRuntime.getAvailable()),
];
const fallbackModel = selectProviderDefault(availableModels, defaultModelPerProvider, modelRuntime)?.model;
if (fallbackModel) {
if (shouldPrintMessages) {
console.log(chalk.dim(`Falling back to: ${fallbackModel.provider}/${fallbackModel.id}`));
}
return {
model: fallbackModel,
fallbackMessage: `Could not restore model ${savedProvider}/${savedModelId} (${reason}). Using ${fallbackModel.provider}/${fallbackModel.id}.`,
};
}
// No models available
return { model: undefined, fallbackMessage: undefined };
}
//# sourceMappingURL=model-resolver.js.map