/* C8 ignore file */ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent"; import type { AdaptiveRoutingMode, AdaptiveRoutingState, ProviderUsageState, RouteDecision, RouteFeedbackCategory, RouteThinkingLevel, } from "./types.js"; import { classifyPrompt } from "./classifier.js"; import { readAdaptiveRoutingConfig } from "./config.js"; import { inspectDelegatedSelection } from "./delegated-runtime.js"; import { decideRoute } from "./engine.js"; import { normalizeRouteCandidates } from "./normalize.js"; import { readAdaptiveRoutingState, writeAdaptiveRoutingState } from "./state.js"; import { appendTelemetryEvent, computeStats, createDecisionId, createFeedbackEvent, formatStats, hashPrompt, readTelemetryEvents, } from "./telemetry.js"; const STATUS_KEY = "adaptive-routing"; const STARTUP_STATE_REFRESH_DELAY_MS = 250; interface RuntimeState { state: AdaptiveRoutingState; usage?: ProviderUsageState; lastDecision?: RouteDecision; lastDecisionPromptHash?: string; lastDecisionTurnCount: number; lastDecisionOverridden: boolean; lastDecisionStartedAt?: number; applyingRoute: boolean; } export default function adaptiveRoutingExtension(pi: ExtensionAPI) { const runtime: RuntimeState = { applyingRoute: false, lastDecision: undefined, lastDecisionOverridden: false, lastDecisionPromptHash: undefined, lastDecisionStartedAt: undefined, lastDecisionTurnCount: 0, state: readAdaptiveRoutingState(), usage: undefined, }; function persistState(): void { writeAdaptiveRoutingState({ ...runtime.state, lastDecision: runtime.lastDecision, }); } function getEffectiveMode(): AdaptiveRoutingMode { const config = readAdaptiveRoutingConfig(); return runtime.state.mode ?? config.mode; } function currentRouteLabel(): string | undefined { const mode = getEffectiveMode(); if (mode === "off") { return undefined; } const lockLabel = runtime.state.lock ? ` 🔒 ${runtime.state.lock.model}:${runtime.state.lock.thinking}` : ""; const decision = runtime.lastDecision; return decision ? `${mode} → ${decision.selectedModel}:${decision.selectedThinking}${lockLabel}` : `${mode}${lockLabel}`; } function updateStatus(ctx: ExtensionContext): void { ctx.ui.setStatus(STATUS_KEY, currentRouteLabel()); } function refreshUsageSnapshot(): void { pi.events.emit("usage:query", undefined); } pi.events.on("usage:limits", (payload: unknown) => { const providerPayload = payload && typeof payload === "object" && "providers" in payload ? ((payload as { providers?: unknown }).providers as Record | undefined) : undefined; const providers: ProviderUsageState["providers"] = {}; if (providerPayload && typeof providerPayload === "object") { for (const [provider, value] of Object.entries(providerPayload)) { providers[provider] = { confidence: extractQuotaConfidence(value), remainingPct: extractRemainingPct(value), }; } } runtime.usage = { perModel: payload && typeof payload === "object" && typeof (payload as { perModel?: unknown }).perModel === "object" ? ((payload as { perModel: Record }).perModel ?? undefined) : undefined, perSource: payload && typeof payload === "object" && typeof (payload as { perSource?: unknown }).perSource === "object" ? ((payload as { perSource: Record }).perSource ?? undefined) : undefined, providers, rolling30dCost: payload && typeof payload === "object" && typeof (payload as { rolling30dCost?: unknown }).rolling30dCost === "number" ? ((payload as { rolling30dCost: number }).rolling30dCost ?? undefined) : undefined, sessionCost: payload && typeof payload === "object" && typeof (payload as { sessionCost?: unknown }).sessionCost === "number" ? ((payload as { sessionCost: number }).sessionCost ?? undefined) : undefined, updatedAt: Date.now(), }; }); let startupRefreshTimer: ReturnType | undefined; const cancelStartupRefresh = () => { if (!startupRefreshTimer) { return; } clearTimeout(startupRefreshTimer); startupRefreshTimer = undefined; }; const refreshRuntimeState = (ctx: ExtensionContext) => { cancelStartupRefresh(); runtime.state = readAdaptiveRoutingState(); refreshUsageSnapshot(); updateStatus(ctx); }; pi.on("session_start", async (_event, ctx) => { cancelStartupRefresh(); startupRefreshTimer = setTimeout(() => { startupRefreshTimer = undefined; refreshRuntimeState(ctx); }, STARTUP_STATE_REFRESH_DELAY_MS); startupRefreshTimer.unref?.(); }); pi.on("session_shutdown", async () => { cancelStartupRefresh(); }); pi.on("model_select", async (event, ctx) => { if (!runtime.applyingRoute && shouldRecordOverride(event, runtime.lastDecision)) { appendTelemetryEvent(readAdaptiveRoutingConfig().telemetry, { decisionId: runtime.lastDecision?.id, from: { model: runtime.lastDecision?.selectedModel ?? "unknown", thinking: runtime.lastDecision?.selectedThinking ?? "off", }, reason: "manual", timestamp: Date.now(), to: { model: `${event.model.provider}/${event.model.id}`, thinking: pi.getThinkingLevel() as RouteThinkingLevel, }, type: "route_override", }); runtime.lastDecisionOverridden = true; } updateStatus(ctx); }); pi.on("agent_end", async (_event, _ctx) => { if (!runtime.lastDecision?.id) { return; } const now = Date.now(); appendTelemetryEvent(readAdaptiveRoutingConfig().telemetry, { completed: true, decisionId: runtime.lastDecision.id, durationMs: typeof runtime.lastDecisionStartedAt === "number" ? Math.max(0, now - runtime.lastDecisionStartedAt) : undefined, selectedModel: runtime.lastDecision.selectedModel, timestamp: now, turnCount: runtime.lastDecisionTurnCount, type: "route_outcome", userOverrideOccurred: runtime.lastDecisionOverridden, }); runtime.lastDecisionStartedAt = undefined; }); pi.on("turn_end", async () => { runtime.lastDecisionTurnCount += 1; }); pi.on("before_agent_start", async (event, ctx) => { const config = readAdaptiveRoutingConfig(); runtime.state = readAdaptiveRoutingState(); const mode = runtime.state.mode ?? config.mode; if (mode === "off") { ctx.ui.setStatus(STATUS_KEY, undefined); return; } refreshUsageSnapshot(); const availableModels = ctx.modelRegistry.getAvailable(); const candidates = normalizeRouteCandidates(availableModels).filter( (candidate) => !config.models.excluded.some((entry) => entry === candidate.fullId || entry === candidate.modelId), ); if (candidates.length === 0) { ctx.ui.setStatus(STATUS_KEY, `${mode} → no eligible models`); return; } const classification = await classifyPrompt(event.prompt, config, ctx, candidates); const currentModel = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined; const currentThinking = pi.getThinkingLevel() as RouteThinkingLevel; const decision = decideRoute({ candidates, classification, config, currentModel, currentThinking, lock: runtime.state.lock, usage: runtime.usage, }); if (!decision) { ctx.ui.setStatus(STATUS_KEY, `${mode} → no route`); return; } decision.id = createDecisionId(); runtime.lastDecision = decision; runtime.lastDecisionPromptHash = hashPrompt(event.prompt); runtime.lastDecisionTurnCount = 0; runtime.lastDecisionOverridden = false; runtime.lastDecisionStartedAt = Date.now(); runtime.state.lastDecision = decision; persistState(); appendTelemetryEvent(config.telemetry, { candidates: decision.explanation.candidates, classifier: classification, decisionId: decision.id, explanationCodes: decision.explanation.codes, fallbacks: decision.fallbacks, mode, promptHash: runtime.lastDecisionPromptHash, quota: decision.explanation.quota, selected: { model: decision.selectedModel, thinking: decision.selectedThinking, }, timestamp: Date.now(), type: "route_decision", }); if (mode === "shadow") { if (currentModel && (currentModel !== decision.selectedModel || currentThinking !== decision.selectedThinking)) { appendTelemetryEvent(config.telemetry, { actual: { model: currentModel, thinking: currentThinking, }, decisionId: decision.id, promptHash: runtime.lastDecisionPromptHash, suggested: { model: decision.selectedModel, thinking: decision.selectedThinking, }, timestamp: Date.now(), type: "route_shadow_disagreement", }); } ctx.ui.notify(`Adaptive route suggestion: ${decision.selectedModel} · ${decision.selectedThinking}`, "info"); updateStatus(ctx); return; } await applyDecision(pi, ctx, decision, candidates, runtime); updateStatus(ctx); }); const routeCommand = { description: "Adaptive routing controls: /route [status|on|off|shadow|auto|explain|assignments|delegated|why|lock|unlock|refresh|feedback|stats] and /route: aliases", async handler(args: string, ctx: ExtensionCommandContext) { const command = args.trim(); const [head, ...rest] = command.split(/\s+/).filter(Boolean); const subcommand = (head ?? "status").toLowerCase(); runtime.state = readAdaptiveRoutingState(); switch (subcommand) { case "on": case "auto": { runtime.state.mode = "auto"; persistState(); updateStatus(ctx); ctx.ui.notify("Adaptive routing set to auto mode.", "info"); return; } case "off": { runtime.state.mode = "off"; persistState(); updateStatus(ctx); ctx.ui.notify("Adaptive routing disabled.", "warning"); return; } case "shadow": { runtime.state.mode = "shadow"; persistState(); updateStatus(ctx); ctx.ui.notify("Adaptive routing set to shadow mode.", "info"); return; } case "lock": { if (!ctx.model) { ctx.ui.notify("No active model to lock.", "warning"); return; } runtime.state.lock = { model: `${ctx.model.provider}/${ctx.model.id}`, setAt: Date.now(), thinking: pi.getThinkingLevel() as RouteThinkingLevel, }; persistState(); updateStatus(ctx); ctx.ui.notify( `Adaptive routing locked to ${runtime.state.lock.model}:${runtime.state.lock.thinking}.`, "info", ); return; } case "unlock": { runtime.state.lock = undefined; persistState(); updateStatus(ctx); ctx.ui.notify("Adaptive routing lock cleared.", "info"); return; } case "refresh": { refreshUsageSnapshot(); runtime.state = readAdaptiveRoutingState(); ctx.ui.notify("Adaptive routing config and usage refreshed.", "info"); updateStatus(ctx); return; } case "feedback": { const category = normalizeFeedbackCategory(rest[0]); if (!category) { ctx.ui.notify( "Usage: /route feedback ", "warning", ); return; } appendTelemetryEvent( readAdaptiveRoutingConfig().telemetry, createFeedbackEvent(runtime.lastDecision, category), ); ctx.ui.notify(`Recorded route feedback: ${category}.`, "info"); return; } case "stats": { await openOverlay(ctx, formatStats(computeStats(readTelemetryEvents()))); return; } case "assignments": case "delegated": { await openOverlay(ctx, buildDelegatedAssignmentLines(readAdaptiveRoutingConfig(), ctx, runtime.usage)); return; } case "why": { await openOverlay(ctx, buildDelegatedWhyLines(readAdaptiveRoutingConfig(), ctx, rest)); return; } case "explain": { await openOverlay(ctx, buildExplanationLines(runtime.lastDecision, runtime.usage)); return; } default: { ctx.ui.notify(buildStatusLine(runtime.state, runtime.lastDecision, getEffectiveMode()), "info"); } } }, }; pi.registerCommand("route", routeCommand); const routeAliases: { name: string; subcommand: string; description: string; }[] = [ { description: "Show the current adaptive routing status.", name: "route status", subcommand: "status", }, { description: "Enable adaptive routing auto mode.", name: "route on", subcommand: "on", }, { description: "Enable adaptive routing auto mode.", name: "route auto", subcommand: "auto", }, { description: "Disable adaptive routing.", name: "route off", subcommand: "off", }, { description: "Suggest route decisions without changing the active model.", name: "route shadow", subcommand: "shadow", }, { description: "Explain the latest adaptive route decision.", name: "route explain", subcommand: "explain", }, { description: "Show delegated routing assignments.", name: "route assignments", subcommand: "assignments", }, { description: "Show delegated routing assignments.", name: "route delegated", subcommand: "delegated", }, { description: "Inspect why a delegated model was chosen.", name: "route why", subcommand: "why", }, { description: "Lock routing to the current model and thinking level.", name: "route lock", subcommand: "lock", }, { description: "Clear the adaptive routing lock.", name: "route unlock", subcommand: "unlock", }, { description: "Refresh routing config and usage snapshots.", name: "route refresh", subcommand: "refresh", }, { description: "Record feedback for the last adaptive routing decision.", name: "route feedback", subcommand: "feedback", }, { description: "Show adaptive routing telemetry stats.", name: "route stats", subcommand: "stats", }, ]; for (const alias of routeAliases) { pi.registerCommand(alias.name, { description: alias.description, handler: (args: string, ctx: ExtensionCommandContext) => routeCommand.handler(args ? `${alias.subcommand} ${args}` : alias.subcommand, ctx), }); } } async function applyDecision( pi: ExtensionAPI, ctx: ExtensionContext, decision: RouteDecision, candidates: ReturnType, runtime: RuntimeState, ): Promise { const currentModel = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined; const currentThinking = pi.getThinkingLevel() as RouteThinkingLevel; if (currentModel === decision.selectedModel && currentThinking === decision.selectedThinking) { return; } const target = candidates.find((candidate) => candidate.fullId === decision.selectedModel); if (!target) { ctx.ui.notify(`Adaptive route target unavailable: ${decision.selectedModel}`, "warning"); return; } runtime.applyingRoute = true; try { if (currentModel !== decision.selectedModel) { const ok = await pi.setModel(target.model); if (!ok) { ctx.ui.notify(`Failed to switch to ${decision.selectedModel}.`, "error"); return; } } if (currentThinking !== decision.selectedThinking) { pi.setThinkingLevel(decision.selectedThinking); } ctx.ui.notify(`Adaptive route applied: ${decision.selectedModel} · ${decision.selectedThinking}`, "info"); } finally { runtime.applyingRoute = false; } } function shouldRecordOverride( event: { model?: { provider: string; id: string } }, lastDecision: RouteDecision | undefined, ): boolean { if (!(lastDecision && event.model)) { return false; } return `${event.model.provider}/${event.model.id}` !== lastDecision.selectedModel; } function extractQuotaConfidence(value: unknown): ProviderUsageState["providers"][string]["confidence"] { if (!value || typeof value !== "object") { return "unknown"; } const typedValue = value as { windows?: unknown[]; stale?: boolean }; if (Array.isArray(typedValue.windows) && typedValue.windows.length > 0) { return "authoritative"; } if (typedValue.stale) { return "estimated"; } return "unknown"; } function extractRemainingPct(value: unknown): number | undefined { if (!value || typeof value !== "object") { return undefined; } const typedValue = value as { windows?: unknown[] }; if (!Array.isArray(typedValue.windows)) { return undefined; } const percentages = typedValue.windows .map((window: unknown) => window && typeof window === "object" ? Number((window as { remainingPct?: unknown }).remainingPct) : Number.NaN, ) .filter((pct: number) => Number.isFinite(pct)); if (percentages.length === 0) { return undefined; } return Math.min(...percentages); } function normalizeFeedbackCategory(value: string | undefined): RouteFeedbackCategory | undefined { switch ((value ?? "").toLowerCase()) { case "good": case "bad": case "wrong-intent": case "overkill": case "underpowered": case "wrong-provider": case "wrong-thinking": { return value?.toLowerCase() as RouteFeedbackCategory; } default: { return undefined; } } } function buildStatusLine( state: AdaptiveRoutingState, decision: RouteDecision | undefined, mode: AdaptiveRoutingMode, ): string { const parts = [`mode=${mode}`]; if (state.lock) { parts.push(`lock=${state.lock.model}:${state.lock.thinking}`); } if (decision) { parts.push(`last=${decision.selectedModel}:${decision.selectedThinking}`); } return `adaptive routing · ${parts.join(" · ")}`; } function buildExplanationLines(decision: RouteDecision | undefined, usage: ProviderUsageState | undefined): string[] { if (!decision) { return ["Adaptive Routing", "No route decision recorded yet."]; } const lines = [ "Adaptive Routing", `Selected: ${decision.selectedModel}`, `Thinking: ${decision.selectedThinking}`, `Summary: ${decision.explanation.summary}`, `Codes: ${decision.explanation.codes.join(", ") || "none"}`, ]; if (decision.explanation.classification) { const c = decision.explanation.classification; lines.push(`Intent: ${c.intent} · complexity ${c.complexity} · tier ${c.recommendedTier}`); lines.push(`Thinking recommendation: ${c.recommendedThinking} · confidence ${Math.round(c.confidence * 100)}%`); lines.push(`Classifier: ${c.classifierMode}${c.classifierModel ? ` (${c.classifierModel})` : ""}`); lines.push(`Reason: ${c.reason}`); } if (decision.fallbacks.length > 0) { lines.push(`Fallbacks: ${decision.fallbacks.join(" → ")}`); } if (decision.explanation.candidates?.length) { lines.push("Top candidates:"); for (const candidate of decision.explanation.candidates) { lines.push(` - ${candidate.model} (${candidate.score.toFixed(1)}) [${candidate.reasons.join(", ")}]`); } } if (usage && Object.keys(usage.providers).length > 0) { lines.push("Quota snapshot:"); for (const [provider, state] of Object.entries(usage.providers)) { lines.push(` - ${provider}: ${state.remainingPct ?? "?"}% · ${state.confidence}`); } } lines.push("Press q, esc, space, or enter to close."); return lines; } function buildDelegatedAssignmentLines( config: ReturnType, ctx: ExtensionCommandContext, usage: ProviderUsageState | undefined, ): string[] { const lines = ["Delegated Routing Assignments"]; const delegated = config.delegatedRouting; if (!delegated.enabled) { lines.push("Delegated routing is disabled."); return lines; } const availableModels = ctx.modelRegistry.getAvailable().map((model) => ({ fullId: `${model.provider}/${model.id}`, id: model.id, name: model.name, provider: model.provider, })); const categoryEntries = Object.entries(delegated.categories); if (categoryEntries.length === 0) { lines.push("No delegated categories configured."); return lines; } const { disabledProviders } = config.delegatedModelSelection; const { disabledModels } = config.delegatedModelSelection; if (disabledProviders.length > 0) { lines.push(`Disabled providers: ${disabledProviders.join(", ")}`); } if (disabledModels.length > 0) { lines.push(`Disabled models: ${disabledModels.join(", ")}`); } for (const [category, policy] of categoryEntries) { const resolvedModel = resolveDelegatedAssignmentModel({ availableModels, category, config, policy, }); lines.push(`- ${category}`); if (policy.preferredProviders?.length) { lines.push(` providers: ${policy.preferredProviders.join(" → ")}`); } if (policy.fallbackGroup) { lines.push(` fallback group: ${policy.fallbackGroup}`); } if (policy.candidates?.length) { lines.push(` candidates: ${policy.candidates.join(" → ")}`); } if (policy.defaultThinking) { lines.push(` thinking: ${policy.defaultThinking}`); } if (policy.taskProfile) { lines.push(` task profile: ${policy.taskProfile}`); } lines.push(` resolved: ${resolvedModel ?? "(no matching installed model)"}`); if (usage) { for (const provider of policy.preferredProviders ?? []) { const providerUsage = usage.providers[provider]; if (providerUsage) { lines.push(` usage ${provider}: ${providerUsage.remainingPct ?? "?"}% · ${providerUsage.confidence}`); } } } } const roleOverrides = Object.entries(config.delegatedModelSelection.roleOverrides); if (roleOverrides.length > 0) { lines.push("Role overrides:"); for (const [role, override] of roleOverrides) { const resolvedModel = resolveDelegatedAssignmentModel({ availableModels, category: undefined, config, override, policy: { candidates: override.candidateModels, defaultThinking: undefined, fallbackGroup: undefined, preferredProviders: override.preferredProviders, }, }); lines.push(`- ${role}`); if (override.preferredModels?.length) { lines.push(` preferred models: ${override.preferredModels.join(" → ")}`); } if (override.preferredProviders?.length) { lines.push(` preferred providers: ${override.preferredProviders.join(" → ")}`); } if (override.blockedProviders?.length) { lines.push(` blocked providers: ${override.blockedProviders.join(", ")}`); } if (override.blockedModels?.length) { lines.push(` blocked models: ${override.blockedModels.join(", ")}`); } lines.push(` resolved: ${resolvedModel ?? "(no matching installed model)"}`); } } lines.push("Press q, esc, space, or enter to close."); return lines; } function buildDelegatedWhyLines( config: ReturnType, ctx: ExtensionCommandContext, args: string[], ): string[] { const lines = ["Delegated Routing Why"]; const target = args[0]; if (!config.delegatedRouting.enabled) { lines.push("Delegated routing is disabled."); return lines; } if (!target) { lines.push("Usage: /route why [task text]"); lines.push("Examples:"); lines.push(" /route why quick-discovery scan the repo and summarize hotspots"); return lines; } const availableModels = ctx.modelRegistry.getAvailable().map((model) => ({ contextWindow: model.contextWindow, cost: model.cost, fullId: `${model.provider}/${model.id}`, id: model.id, input: model.input, maxTokens: model.maxTokens, name: model.name, provider: model.provider, reasoning: model.reasoning, })); const taskText = args.slice(1).join(" ").trim() || undefined; const categoryPolicy = config.delegatedRouting.categories[target]; const roleOverride = config.delegatedModelSelection.roleOverrides[target]; if (!(categoryPolicy || roleOverride)) { lines.push(`Unknown delegated target: ${target}`); return lines; } const inspection = inspectDelegatedSelection({ availableModels, category: categoryPolicy ? target : undefined, config, defaults: { allowSmallContextForSmallTasks: categoryPolicy?.allowSmallContextForSmallTasks ?? roleOverride?.allowSmallContextForSmallTasks ?? config.delegatedModelSelection.allowSmallContextForSmallTasks, minContextWindow: categoryPolicy?.minContextWindow ?? roleOverride?.minContextWindow, preferFastModels: categoryPolicy?.preferFastModels ?? roleOverride?.preferFastModels ?? target === "quick-discovery", taskProfile: categoryPolicy?.taskProfile ?? roleOverride?.taskProfile ?? "all", }, roleKeys: roleOverride ? [target] : undefined, taskText, }); lines.push(`target: ${target}`); if (taskText) { lines.push(`task: ${taskText}`); } lines.push(`selected: ${inspection.selection?.selectedModel ?? "(no matching installed model)"}`); if (inspection.selection) { lines.push(`task profile: ${inspection.selection.taskProfile}`); lines.push(`task size: ${inspection.selection.taskSize}`); lines.push(`min context: ${inspection.selection.minimumContextWindow}`); } if (inspection.policy?.preferredModels?.length) { lines.push(`preferred models: ${inspection.policy.preferredModels.join(" → ")}`); } if (inspection.policy?.candidateModels?.length) { lines.push(`candidates: ${inspection.policy.candidateModels.join(" → ")}`); } if (inspection.policy?.preferredProviders?.length) { lines.push(`preferred providers: ${inspection.policy.preferredProviders.join(" → ")}`); } if (inspection.policy?.blockedProviders?.length) { lines.push(`blocked providers: ${inspection.policy.blockedProviders.join(", ")}`); } if (inspection.policy?.blockedModels?.length) { lines.push(`blocked models: ${inspection.policy.blockedModels.join(", ")}`); } if (inspection.selection?.ranked.length) { lines.push("ranked:"); for (const ranked of inspection.selection.ranked.slice(0, 5)) { lines.push(`- ${ranked.model}`); lines.push(` reasons: ${ranked.reasons.join(", ") || "(none)"}`); } } if (inspection.selection?.rejected.length) { lines.push("rejected:"); for (const rejected of inspection.selection.rejected.slice(0, 8)) { lines.push(`- ${rejected.model}: ${rejected.reason}`); } } lines.push("Press q, esc, space, or enter to close."); return lines; } export function resolveDelegatedAssignmentModel(params: { category?: string; policy: NonNullable["delegatedRouting"]["categories"][string]>; config: ReturnType; availableModels: { provider: string; id: string; fullId: string; name: string; }[]; override?: ReturnType["delegatedModelSelection"]["roleOverrides"][string]; }): string | undefined { const { category, policy, config, availableModels, override } = params; const blockedProviders = new Set([ ...config.delegatedModelSelection.disabledProviders, ...(override?.blockedProviders ?? []), ]); const blockedModels = new Set([...config.delegatedModelSelection.disabledModels, ...(override?.blockedModels ?? [])]); const unblockedModels = availableModels.filter( (model) => !blockedProviders.has(model.provider) && !blockedModels.has(model.fullId) && !blockedModels.has(model.id), ); for (const ref of override?.preferredModels ?? []) { const match = ref.endsWith("/") ? unblockedModels.find((model) => model.provider === ref.slice(0, ref.indexOf("/"))) : unblockedModels.find((model) => model.fullId === ref || model.id === ref); if (match) { return match.fullId; } } const refs = [ ...(policy.candidates ?? []), ...(policy.fallbackGroup ? (config.fallbackGroups[policy.fallbackGroup]?.candidates ?? []) : []), ...(override?.candidateModels ?? []), ]; for (const ref of refs) { const match = ref.endsWith("/") ? unblockedModels.find((model) => model.provider === ref.slice(0, ref.indexOf("/"))) : unblockedModels.find((model) => model.fullId === ref || model.id === ref); if (match) { return match.fullId; } } for (const provider of [...(override?.preferredProviders ?? []), ...(policy.preferredProviders ?? [])]) { const match = unblockedModels.find((model) => model.provider === provider); if (match) { return match.fullId; } } /* C8 ignore next 5 */ let cheapFallback: | { provider: string; id: string; fullId: string; name: string; } | undefined; if (category === "quick-discovery") { cheapFallback = unblockedModels.find((model) => model.provider === "groq"); } if (cheapFallback) { return cheapFallback.fullId; } return unblockedModels[0]?.fullId; } async function openOverlay(ctx: ExtensionCommandContext, lines: string[]): Promise { await ctx.ui.custom( (tui, _theme, _keybindings, done) => ({ dispose() { // No-op overlay cleanup. }, handleInput(data: string) { if (data === "q" || data === "\x1b" || data === " " || data === "\r") { done(undefined); return; } if (data === "r") { tui.requestRender(); } }, invalidate() { // No-op overlay invalidation. }, render(width: number) { return lines.map((line) => line.slice(0, width)); }, }), { overlay: true, overlayOptions: { anchor: "center", maxHeight: 28, width: 96 }, }, ); }