add health checks and generic fallback to PromptRegistry (#5879)

* fix: Harden PromptRegistry with health checks and generic fallback

- Perform registry health check after loading (validate GENERIC, log counts/warnings)
- Always try GENERIC when family-specific variant is missing
- Enhance error diagnostics with available variants and registry state
- Ensure GENERIC variant exists; create minimal fallback if loading fails
- Minor test style cleanup and variants index update to support reliability

* simpilfy

* variants

* Fix import

* type safe

* remove lazy loading

* load and set variants

* fix import location
This commit is contained in:
Bee authored and GitHub committed 2025-08-28 16:39:56 -07:00
1 parent 31161f894b
commit 8c1093cfdc
7 files changed
+104 -34

No files matched your search

@@ -63,7 +63,9 @@ ${differences}
// Helper to compare two strings and return differences
const compareStrings = (expected: string, actual: string): string | null => {
if (expected === actual) return null
if (expected === actual) {
return null
}
const expectedLines = expected.split("\n")
const actualLines = actual.split("\n")
@@ -3,6 +3,8 @@ import { getModelFamily } from ".."
import { getSystemPromptComponents } from "../components"
import { registerClineToolSets } from "../tools"
import type { ComponentFunction, ComponentRegistry, PromptVariant, SystemPromptContext } from "../types"
import { loadAllVariantConfigs } from "../variants"
import { config as genericConfig } from "../variants/generic/config"
import { PromptBuilder } from "./PromptBuilder"
export class PromptRegistry {
@@ -32,9 +34,37 @@ export class PromptRegistry {
await Promise.all([this.loadVariants(), this.loadComponents()])
// Perform health check to ensure critical variants are available
this.performHealthCheck()
this.loaded = true
}
/**
* Perform health check to ensure registry is in a valid state
*/
private performHealthCheck(): void {
const criticalVariants = [ModelFamily.GENERIC]
const missingVariants = criticalVariants.filter((variant) => !this.variants.has(variant))
if (missingVariants.length > 0) {
console.error(`Registry health check failed: Missing critical variants: ${missingVariants.join(", ")}`)
console.error(`Available variants: ${Array.from(this.variants.keys()).join(", ")}`)
}
if (this.variants.size === 0) {
console.error("Registry health check failed: No variants loaded at all")
}
if (Object.keys(this.components).length === 0) {
console.warn("Registry health check warning: No components loaded")
}
console.log(
`Registry health check: ${this.variants.size} variants, ${Object.keys(this.components).length} components loaded`,
)
}
/**
* Get prompt by model ID with fallback to generic
*/
@@ -43,11 +73,31 @@ export class PromptRegistry {
// Try model family fallback (e.g., "claude-4" -> "claude")
const modelFamily = getModelFamily(context.providerInfo)
const variant = this.variants.get(modelFamily ?? ModelFamily.GENERIC)
let variant = this.variants.get(modelFamily ?? ModelFamily.GENERIC)
// If no variant found for the detected family, explicitly try generic
if (!variant && modelFamily !== ModelFamily.GENERIC) {
variant = this.variants.get(ModelFamily.GENERIC)
}
if (!variant) {
// Enhanced error with debugging information
const availableVariants = Array.from(this.variants.keys())
const errorDetails = {
requestedModel: context.providerInfo.model.id,
detectedFamily: modelFamily,
availableVariants,
variantsCount: this.variants.size,
componentsCount: Object.keys(this.components).length,
isLoaded: this.loaded,
}
console.error("Prompt variant lookup failed:", errorDetails)
throw new Error(
`No prompt variant found for model '${context.providerInfo.model.id}' and no generic fallback available`,
`No prompt variant found for model '${context.providerInfo.model.id}' (family: ${modelFamily}) and no generic fallback available. ` +
`Available variants: [${availableVariants.join(", ")}]. ` +
`Registry state: loaded=${this.loaded}, variants=${this.variants.size}, components=${Object.keys(this.components).length}`,
)
}
@@ -184,30 +234,44 @@ export class PromptRegistry {
/**
* Load all variants from the variants directory
*/
private async loadVariants(): Promise<void> {
private loadVariants(): void {
try {
const { VARIANT_CONFIGS } = await import("../variants")
this.variants = new Map<string, PromptVariant>()
// Load each variant configuration
const loadPromises = Object.entries(VARIANT_CONFIGS).map(async ([variantId, configLoader]) => {
try {
const config = await configLoader()
await this.loadVariantFromConfig(variantId, config)
} catch (error) {
console.warn(`Warning: Could not load variant '${variantId}':`, error)
}
})
for (const [id, config] of Object.entries(loadAllVariantConfigs())) {
this.variants.set(id, { ...config, id })
}
await Promise.all(loadPromises)
// Ensure generic variant is always available as a safety fallback
this.ensureGenericFallback()
} catch (error) {
console.warn("Warning: Could not load variants:", error)
// Even if variant loading fails completely, create a minimal generic fallback
this.createMinimalGenericFallback()
}
}
/**
* Ensure generic variant is available, create minimal one if missing
*/
private ensureGenericFallback(): void {
if (!this.variants.has(ModelFamily.GENERIC)) {
console.warn("Generic variant not found, creating minimal fallback")
this.createMinimalGenericFallback()
}
}
/**
* Create a minimal generic variant as absolute fallback
*/
private createMinimalGenericFallback(): void {
this.loadVariantFromConfig(ModelFamily.GENERIC, genericConfig)
}
/**
* Load a single variant from its TypeScript config
*/
private async loadVariantFromConfig(variantId: string, config: Omit<PromptVariant, "id">): Promise<void> {
private loadVariantFromConfig(variantId: string, config: Omit<PromptVariant, "id">): void {
try {
const variant: PromptVariant = {
...config,
@@ -1,4 +1,4 @@
import { SystemPromptSection } from "../.."
import { SystemPromptSection } from "../../templates/placeholders"
export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}}
@@ -1,4 +1,4 @@
import { SystemPromptSection } from "../.."
import { SystemPromptSection } from "../../templates/placeholders"
export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}}
@@ -7,34 +7,39 @@
*/
export { config as genericConfig, type GenericVariantConfig } from "./generic/config"
export { config as gpt5Config, type GPT5VariantConfig } from "./gpt-5/config"
export { config as nextGenConfig, type NextGenVariantConfig } from "./next-gen/config"
export { config as xsConfig, type XsVariantConfig } from "./xs/config"
import { config as genericConfig } from "./generic/config"
import { config as gpt5Config } from "./gpt-5/config"
import { config as nextGenConfig } from "./next-gen/config"
import { config as xsConfig } from "./xs/config"
/**
* Variant Registry for dynamic loading
*
* This registry allows for lazy loading of variant configurations,
* which is useful for reducing initial bundle size and enabling
* runtime variant selection.
* This registry allows for loading variant configurations.
*/
export const VARIANT_CONFIGS = {
/**
* Generic variant - Fallback for all model types
* Optimized for broad compatibility and stable performance
*/
generic: () => import("./generic/config").then((m) => m.config),
generic: genericConfig,
/**
* Next-gen variant - Advanced models with enhanced capabilities
* Includes additional features like feedback loops and web fetching
*/
"next-gen": () => import("./next-gen/config").then((m) => m.config),
"next-gen": nextGenConfig,
gpt5: gpt5Config,
/**
* XS variant - Compact models with limited context windows
* Streamlined for efficiency with essential tools only
*/
xs: () => import("./xs/config").then((m) => m.config),
xs: xsConfig,
} as const
/**
@@ -60,18 +65,16 @@ export function isValidVariantId(id: string): id is VariantId {
/**
* Load a variant configuration dynamically
* @param variantId - The ID of the variant to load
* @returns Promise that resolves to the variant configuration
* @returns Variant configuration
*/
export async function loadVariantConfig(variantId: VariantId) {
const loader = VARIANT_CONFIGS[variantId]
return await loader()
export function loadVariantConfig(variantId: VariantId) {
return VARIANT_CONFIGS[variantId]
}
/**
* Load all variant configurations
* @returns Promise that resolves to a map of all variant configurations
* @returns A map of all variant configurations
*/
export async function loadAllVariantConfigs() {
const entries = await Promise.all(Object.entries(VARIANT_CONFIGS).map(async ([id, loader]) => [id, await loader()] as const))
return Object.fromEntries(entries) as Record<VariantId, Awaited<ReturnType<(typeof VARIANT_CONFIGS)[VariantId]>>>
export function loadAllVariantConfigs() {
return VARIANT_CONFIGS
}
@@ -1,4 +1,4 @@
import { SystemPromptSection } from "../.."
import { SystemPromptSection } from "../../templates/placeholders"
export const baseTemplate = `{{${SystemPromptSection.AGENT_ROLE}}}
@@ -1,4 +1,5 @@
import { PromptVariant, SystemPromptSection } from "../.."
import { SystemPromptSection } from "../../templates/placeholders"
import { PromptVariant } from "../../types"
const XS_EDITING_FILES = `FILE EDITING RULES
- Default: replace_in_file; write_to_file for new files or full rewrites.