Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat: add auto-assessment engine for combo self-healing (#1918)
Paijoadf99811fa73
diff --git a/docs/RFC-AUTO-ASSESSMENT.md b/docs/RFC-AUTO-ASSESSMENT.mdnew file mode 100644index 0000000000..3d9558aeae--- /dev/null+++ b/docs/RFC-AUTO-ASSESSMENT.md@@ -0,0 +1,518 @@+# RFC: Auto-Assessment & Self-Healing Combo Engine++## Summary++Omniroute's combo system currently requires manual configuration: users must know which providers and models are actually working, then manually wire them into combo chains. When providers fail (rate limits, auth errors, model deprecation), combos silently degrade — routing to dead endpoints that timeout or return errors. There is no automated way to:++1. **Discover** which provider/model pairs actually respond to chat completions+2. **Categorize** models by capability (coding, reasoning, vision, speed, etc.)+3. **Self-heal** combos by removing dead models and promoting working ones+4. **Auto-generate** sensible combo configurations from available providers++This proposes an **Auto-Assessment Engine** that continuously tests, categorizes, and self-heals combo configurations — making omniroute truly "plug and play" for non-technical users.++---++## Problem Statement++### What we encountered (real production incident)++While configuring omniroute for production use, we discovered:++- **44 combos had models from providers that returned "`Invalid model`" errors** — `kiro/claude-opus-4.6`, `kiro/claude-sonnet-4.6`, `gh/claude-sonnet-4.5` all fail with 400/404+- **No automated way to know which models actually work** — the `/v1/models` endpoint lists 1,236 models, but `/v1/chat/completions` fails for most of them+- **Weight-based routing sends traffic to dead models** — a model weighted at 30% that returns errors wastes 30% of requests+- **Manual diagnosis took hours** — we had to curl each model individually, categorize results, then update the SQLite DB+- **Provider `test_status` field exists but isn't used for routing** — `provider_connections` has `test_status` (active/banned/expired/credits_exhausted) but the combo resolver ignores it++### Current flow (broken)++```+User adds providers → Manually creates combos → Manually assigns models → ???+ ↓+ Some models work,+ some return errors,+ some timeout...+ BUT routing doesn't know!+```++### Proposed flow (self-healing)++```+User adds providers → Auto-Assessment runs → Working models discovered+ ↓+ Capability categorization+ ↓+ Combos auto-generated/updated with working models+ ↓+ Continuous health monitoring keeps combos healthy+```++---++## Architecture++### New Components++```+┌─────────────────────────────────────────────────────────┐+│ Auto-Assessment Engine │+├─────────────────────────────────────────────────────────┤+│ │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Assessor │ │ Categorizer │ │ Self-Healer │ │+│ │ │ │ │ │ │ │+│ │ • Probe all │ │ • Classify │ │ • Remove │ │+│ │ models │ │ models by │ │ dead │ │+│ │ • Measure │ │ capability │ │ models │ │+│ │ latency │ │ • Assign │ │ • Promote │ │+│ │ • Track │ │ tier tags │ │ working │ │+│ │ success │ │ • Build │ │ models │ │+│ │ rates │ │ fitness │ │ • Re-weight │ │+│ │ │ │ scores │ │ combos │ │+│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │+│ │ │ │ │+│ ▼ ▼ ▼ │+│ ┌──────────────────────────────────────────────────┐ │+│ │ Assessment Database │ │+│ │ │ │+│ │ model_assessments: │ │+│ │ model_id | provider | status | latency_p50 │ │+│ │ latency_p95 | success_rate | last_tested │ │+│ │ error_type | tier | categories[] | fitness │ │+│ │ context_window | output_tokens | vision | tbc │ │+│ │ │ │+│ │ assessment_runs: │ │+│ │ run_id | started_at | completed_at │ │+│ │ models_tested | models_passed | models_failed │ │+│ │ │ │+│ │ combo_health: │ │+│ │ combo_id | healthy_models | dead_models │ │+│ │ last_auto_fix | auto_fix_count │ │+│ └──────────────────────────────────────────────────┘ │+│ │+└──────────────────────────────┬──────────────────────────┘+ │+ ▼+ Existing combo system (weighted-fallback, priority, etc.)+ + Enhanced comboResolver that skips dead models+```++---++## Detailed Design++### 1. Assessor — `src/domain/assessor.ts`++**Purpose**: Probe every provider/model pair with a lightweight chat completion to determine if it works and measure performance.++```typescript+interface ModelAssessment {+ modelId: string;+ providerId: string;+ status: "working" | "broken" | "rate_limited" | "timeout" | "auth_error" | "unknown";++ // Performance metrics+ latencyP50: number; // milliseconds+ latencyP95: number; // milliseconds+ successRate: number; // 0..1 over last N probes++ // Capability detection+ supportsVision: boolean;+ supportsToolCall: boolean;+ supportsStreaming: boolean;+ maxContextWindow: number;+ maxOutputTokens: number;+ categories: ModelCategory[]; // 'coding' | 'reasoning' | 'chat' | 'fast' | 'vision' | 'reasoning_deep'+ tier: "premium" | "balanced" | "fast" | "free";++ // Metadata+ lastTested: string; // ISO timestamp+ lastError: string | null;+ consecutiveFails: number;+ probeCount: number;+}++type ModelCategory =+ | "coding" // Good at code generation, debugging, refactoring+ | "reasoning" // Strong logical reasoning, math, analysis+ | "reasoning_deep" // Extended thinking, complex multi-step reasoning+ | "chat" // Good conversational ability+ | "fast" // Sub-2s response time+ | "vision" // Image input support+ | "tool_call" // Function/tool calling support+ | "structured_output"; // JSON mode / structured output+```++**Assessment Probes** — three tiers of testing:++| Probe | Prompt | Max Tokens | Purpose |+| ------------ | ------------------------------------------ | ---------- | ---------------------------------------------- |+| **Quick** | `"ok"` | 1 | Does it respond at all? |+| **Standard** | `"Write a function that adds two numbers"` | 50 | Coding, tool call, structured output detection |+| **Deep** | Vision input + multi-turn | 100 | Vision, streaming, context window |++**Scheduling**:++- Full assessment on startup (or first provider addition)+- Quick probe every 5 minutes for working models+- Standard probe every 30 minutes+- Deep probe every 6 hours (or on demand)+- Immediate probe after any model returns an error+- Exponential backoff: 1 min → 5 min → 15 min → 30 min for consistently failing models++### 2. Categorizer — `src/domain/categorizer.ts`++**Purpose**: Classify each working model into capability categories and assign fitness scores per category.++**Category Detection Logic**:++```typescript+function categorizeModel(assessment: ModelAssessment): ModelCategory[] {+ const categories: ModelCategory[] = [];++ // Speed classification+ if (assessment.latencyP50 < 2000) categories.push("fast");++ // Capability from probe responses+ if (assessment.supportsToolCall) categories.push("tool_call");+ if (assessment.supportsVision) categories.push("vision");+ if (assessment.supportsStreaming) categories.push("structured_output"); // if supports JSON mode++ // Tier-based reasoning classification+ if (assessment.tier === "premium") {+ categories.push("reasoning_deep", "coding", "reasoning");+ } else if (assessment.tier === "balanced") {+ categories.push("coding", "reasoning");+ } else if (assessment.tier === "fast") {+ categories.push("chat");+ }++ return categories;+}+```++**Fitness Scores** (0..1 per category):++| Category | Scoring Formula |+| ---------------- | -------------------------------------------------------------------- |+| `coding` | `0.4 * successRate + 0.3 * (1 - latencyP95/10000) + 0.3 * tierScore` |+| `reasoning` | `0.5 * tierScore + 0.3 * successRate + 0.2 * (1 - latencyP95/15000)` |+| `reasoning_deep` | `0.7 * tierScore + 0.3 * successRate` (only premium tier eligible) |+| `chat` | `0.4 * successRate + 0.4 * (1 - latencyP95/5000) + 0.2 * tierScore` |+| `fast` | `0.6 * (1 - latencyP50/3000) + 0.3 * successRate + 0.1 * costInv` |+| `vision` | `0.5 * successRate + 0.3 * (1 - latencyP95/15000) + 0.2 * tierScore` |++### 3. Self-Healer — `src/domain/selfHealer.ts`++**Purpose**: Automatically update combo model lists based on assessment results.++**Auto-Heal Rules**:++```+IF model.status == 'broken' OR model.consecutiveFails >= 3:+ REMOVE model from all combos+ LOG "Auto-heal: removed {model} from {combo} (status: {status}, fails: {n})"++IF model.status == 'rate_limited' OR model.status == 'timeout':+ REDUCE model weight by 50% (minimum weight: 5)+ LOG "Auto-heal: reduced weight of {model} in {combo} (status: {status})"++IF combo has 0 working models:+ FIND best working model for combo's category+ ADD to combo with weight 100+ LOG "Auto-heal: emergency added {model} to {combo} (was empty)"++IF combo has fewer than 3 working models:+ FIND additional working models in same category+ ADD with proportional weights+ LOG "Auto-heal: expanded {combo} with {n} models"++IF model.status transitions from 'broken' → 'working':+ RESTORE original weight (or proportional weight)+ LOG "Auto-heal: restored {model} in {combo}"+```++**Auto-Generation of Combos**:++When a new provider is added, or on first startup, auto-generate standard combos:++```typescript+const AUTO_COMBOS = [+ { name: "auto/best-coding", categories: ["coding"], tier: ["premium", "balanced"] },+ { name: "auto/best-reasoning", categories: ["reasoning_deep"], tier: ["premium"] },+ { name: "auto/best-fast", categories: ["fast"], tier: ["fast", "balanced"] },+ { name: "auto/best-vision", categories: ["vision"], tier: ["premium", "balanced"] },+ { name: "auto/best-chat", categories: ["chat"], tier: ["balanced", "premium"] },+ { name: "auto/coding", categories: ["coding"], tier: ["balanced", "fast", "premium"] },+ { name: "auto/fast", categories: ["fast"], tier: ["fast"] },+ { name: "auto/pro-coding", categories: ["coding"], tier: ["premium"] },+ { name: "auto/pro-reasoning", categories: ["reasoning_deep"], tier: ["premium"] },+ { name: "auto/pro-vision", categories: ["vision"], tier: ["premium"] },+ { name: "auto/pro-chat", categories: ["chat"], tier: ["premium"] },+ { name: "auto/pro-fast", categories: ["fast"], tier: ["fast"] },+];+```++### 4. Database Schema++```sql+-- New tables for assessment engine++CREATE TABLE IF NOT EXISTS model_assessments (+ id TEXT PRIMARY KEY,+ model_id TEXT NOT NULL,+ provider_id TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'unknown', -- working|broken|rate_limited|timeout|auth_error|unknown+ latency_p50 INTEGER, -- milliseconds+ latency_p95 INTEGER, -- milliseconds+ success_rate REAL DEFAULT 0, -- 0..1+ supports_vision INTEGER DEFAULT 0,+ supports_tool_call INTEGER DEFAULT 0,+ supports_streaming INTEGER DEFAULT 0,+ supports_structured_output INTEGER DEFAULT 0,+ max_context_window INTEGER,+ max_output_tokens INTEGER,+ categories TEXT DEFAULT '[]', -- JSON array of ModelCategory+ fitness_scores TEXT DEFAULT '{}', -- JSON object: {category: score}+ tier TEXT DEFAULT 'balanced', -- premium|balanced|fast|free+ last_tested TEXT,+ last_error TEXT,+ consecutive_fails INTEGER DEFAULT 0,+ probe_count INTEGER DEFAULT 0,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ UNIQUE(model_id, provider_id)+);++CREATE TABLE IF NOT EXISTS assessment_runs (+ id TEXT PRIMARY KEY,+ started_at TEXT NOT NULL,+ completed_at TEXT,+ models_tested INTEGER DEFAULT 0,+ models_passed INTEGER DEFAULT 0,+ models_failed INTEGER DEFAULT 0,+ models_rate_limited INTEGER DEFAULT 0,+ duration_ms INTEGER,+ trigger TEXT DEFAULT 'scheduled', -- scheduled|on_demand|on_provider_change|on_error+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+);++CREATE TABLE IF NOT EXISTS combo_health (+ combo_id TEXT PRIMARY KEY,+ healthy_model_count INTEGER DEFAULT 0,+ dead_model_count INTEGER DEFAULT 0,+ total_model_count INTEGER DEFAULT 0,+ last_auto_fix TEXT,+ auto_fix_count INTEGER DEFAULT 0,+ health_score REAL DEFAULT 0, -- 0..1, weighted by model health+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ FOREIGN KEY (combo_id) REFERENCES combos(id)+);++CREATE INDEX IF NOT EXISTS idx_model_assessments_status ON model_assessments(status);+CREATE INDEX IF NOT EXISTS idx_model_assessments_provider ON model_assessments(provider_id);+CREATE INDEX IF NOT EXISTS idx_model_assessments_tier ON model_assessments(tier);+CREATE INDEX IF NOT EXISTS idx_combo_health_health_score ON combo_health(health_score);+```++### 5. API Endpoints++```bash+# Trigger assessment (blocking or background)+POST /api/assess/models+ Body: { "scope": "all" | "provider:<id>" | "model:<id>", "tier": "quick" | "standard" | "deep" }+ Response: { "run_id": "...", "status": "started" }++# Get assessment results+GET /api/assess/results+ Query: ?status=working|broken|rate_limited&provider=kiro&category=coding+ Response: { "models": [...] }++# Get combo health dashboard+GET /api/assess/combo-health+ Response: { "combos": [{ "id": "...", "name": "...", "healthy_models": 5, "dead_models": 2, "health_score": 0.71 }] }++# Auto-fix all combos+POST /api/assess/auto-fix+ Response: { "fixed_combos": 3, "removed_models": ["ollamacloud/glm-5.1", "..."], "added_models": [...] }++# Auto-generate combos from assessments+POST /api/assess/auto-generate+ Response: { "generated_combos": ["auto/best-coding", "..."], "models_per_combo": { "auto/best-coding": 5 } }++# Get assessment run history+GET /api/assess/runs+ Response: { "runs": [...] }+```++### 6. Integration with Existing comboResolver++The existing `comboResolver.ts` already handles `priority`, `weighted`, `round-robin`, `random`, and `least-used` strategies. The enhancement:++```typescript+// In comboResolver.ts — add health-aware filtering+export function resolveComboModel(combo, context = {}) {+ const models = combo.models || [];+ if (models.length === 0) {+ throw new Error(`Combo "${combo.name}" has no models configured`);+ }++ const normalized = models+ .map((entry) => ({+ model: getComboStepTarget(entry) || "",+ weight: getComboStepWeight(entry) || 1,+ }))+ .filter((entry) => entry.model);++ // NEW: Filter out models known to be broken/rate_limited+ const healthy = normalized.filter((entry) => {+ const assessment = getAssessment(entry.model);+ if (!assessment) return true; // Unknown → allow (haven't tested yet)+ return assessment.status === "working" || assessment.status === "unknown";+ });++ // If all models are unhealthy, fall back to full list (better to try than to fail)+ const pool = healthy.length > 0 ? healthy : normalized;++ const strategy = combo.strategy || "priority";+ // ... existing resolution logic using `pool` instead of `normalized`+}+```++### 7. Integration with Existing Auto-Combo Scoring (`open-sse/services/autoCombo/scoring.ts`)++The existing scoring function already uses 6 factors + tier. The assessment engine enriches these:++| Existing Factor | Current Source | Enhanced Source |+| ------------------- | ------------------------ | ----------------------------------------- |+| Quota (0.20) | Provider connection data | Same + assessment success_rate |+| Health (0.25) | Circuit breaker state | Same + assessment status (working/broken) |+| CostInv (0.20) | Static cost data | Same + live cost measurement |+| LatencyInv (0.15) | P95 latency from logs | Same + assessment probe latency |+| TaskFit (0.10) | Static fitness table | **NEW: from assessment categories** |+| Stability (0.05) | Latency stddev | Same + assessment consecutive_fails |+| TierPriority (0.05) | Account tier | Same |++The key enhancement: `taskFit` currently uses a **static** fitness lookup (`taskFitness.ts`). With assessments, we derive fitness from **live probe results** — a model that actually passes coding probes gets a high `coding` fitness, not just because its name contains "coder".++### 8. Dashboard UI (Future PR)++The assessment state should be visible in the omniroute dashboard:++- **Model Health Grid**: table showing each provider/model with colored status indicators+- **Combo Health Summary**: per-combo health score with expandable model details+- **Assessment History**: timeline of assessment runs with pass/fail counts+- **Auto-Fix Log**: history of automatic combo modifications++---++## Migration Path++### Phase 1: Assessment Engine (This PR)++- New `model_assessments`, `assessment_runs`, `combo_health` tables+- Assessor service with quick/standard/deep probes+- Categorizer with fitness scoring+- Self-healer with auto-fix rules+- REST API endpoints+- Integration with comboResolver to skip broken models++### Phase 2: Auto-Generation (Follow-up PR)++- Auto-generate combos from assessed models+- Smart combo naming and categorization+- Cross-provider fallback chains+- Dashboard UI for assessment results++### Phase 3: Continuous Learning (Follow-up PR)++- Feeds assessment results back into auto-combo scoring weights+- Adapts fitness scores based on real request outcomes+- A/B testing across providers to find optimal routing+- Automatic mode pack switching (ship-fast during peak, cost-saver off-peak)++---++## Implementation Files++| File | Purpose | New/Modified |+| ---------------------------------------- | ---------------------------------------- | ------------ |+| `src/domain/assessor.ts` | Probe engine (quick/standard/deep) | **NEW** |+| `src/domain/categorizer.ts` | Model categorization & fitness | **NEW** |+| `src/domain/selfHealer.ts` | Auto-fix combos, remove dead models | **NEW** |+| `src/domain/comboResolver.ts` | Add health-aware filtering | **MODIFIED** |+| `src/domain/types.ts` | Add ModelAssessment, ModelCategory types | **MODIFIED** |+| `src/lib/db/assessments.ts` | DB access for assessment tables | **NEW** |+| `open-sse/services/autoCombo/scoring.ts` | Use assessment data for taskFit | **MODIFIED** |+| `src/app/api/assess/route.ts` | REST API routes | **NEW** |+| `scripts/assess-models.mjs` | CLI script for on-demand assessment | **NEW** |+| `scripts/migrate-assessments.mjs` | DB migration script | **NEW** |++---++## Testing Plan++### Unit Tests++- Assessor probe logic (mock provider responses)+- Categorizer fitness score calculations+- Self-healer rules (remove, reduce, restore, emergency add)+- comboResolver integration (skip broken models)++### Integration Tests++- Full assessment cycle: add provider → probe models → categorize → auto-fix combos+- Health-aware routing: broken model skipped, restored model re-included+- Assessment run persistence and recovery++### Manual Testing (our experience as reference)++```bash+# Our actual test sequence that should be automated:+# 1. Start omniroute with 406 provider connections (51 providers)+# 2. Discover only 8 models actually work from 2 providers (kiro, ollamacloud)+# 3. Manually update 44 combos with working models only+# 4. Verify all 15 key combos pass end-to-end+# 5. Set up auto-sync cron for model list updates++# With auto-assessment, this entire process should be:+# 1. Start omniroute+# 2. Run: curl -X POST http://localhost:20128/api/assess/models -d '{"scope":"all"}'+# 3. Wait for assessment to complete+# 4. Run: curl -X POST http://localhost:20128/api/assess/auto-fix+# 5. All combos are now healthy+```++---++## Success Metrics++| Metric | Current (Manual) | Target (Auto-Assessment) |+| -------------------------------- | --------------------------------- | ------------------------------- |+| Time to configure working combos | 2-4 hours | < 5 minutes |+| Dead model detection | Manual curl testing | Automatic, continuous |+| Combo health visibility | None | Dashboard + API |+| Provider failure recovery | Manual DB updates | Auto-heal within 5 minutes |+| New provider onboarding | Manual combo editing | Auto-discover + auto-categorize |+| Model deprecation handling | Manual detection (users complain) | Proactive removal + alerting |++---++## Backwards Compatibility++- All new tables are additive — no schema changes to existing tables+- comboResolver filtering is opt-in via config flag (default: enabled)+- Existing combo configurations are preserved — self-healer only modifies them, doesn't replace+- Assessment can be disabled with `OMNIRoute_DISABLE_ASSESSMENT=1` env var+- All API endpoints are new — no existing endpoints changed++---++## Open Questions++1. **Probe cost**: Who pays for assessment probes? Should we limit to free-tier models or use a separate assessment budget?+2. **Assessment frequency**: How often should deep probes run? Current proposal: 6h, but some users may want more/less frequent.+3. **Auto-fix aggression**: Should self-healer remove models immediately on first failure, or wait for N consecutive failures?+4. **Cross-provider model equivalence**: Should `kiro/claude-sonnet-4.5` and `gh/claude-sonnet-4.5` be treated as the same model for combo purposes?+5. **Assessment during startup**: Should assessment block startup or run in background?diff --git a/src/app/api/assess/route.ts b/src/app/api/assess/route.tsnew file mode 100644index 0000000000..dba89d00a8--- /dev/null+++ b/src/app/api/assess/route.ts@@ -0,0 +1,110 @@+import { NextRequest, NextResponse } from "next/server";+import { Assessor } from "@/domain/assessment/assessor";+import { Categorizer } from "@/domain/assessment/categorizer";+import { SelfHealer } from "@/domain/assessment/selfHealer";+import { type AssessmentScope, type AssessmentTrigger } from "@/domain/assessment/types";++const assessor = new Assessor(+ process.env.OMNIROUTe_API_KEY ?? process.env.API_KEY ?? "",+ process.env.OMNIROUTe_BASE_URL ?? "http://localhost:20128/v1"+);++const categorizer = new Categorizer();+const healer = new SelfHealer();++export async function POST(request: NextRequest) {+ try {+ const body = await request.json();+ const scope: AssessmentScope = body.scope ?? { type: "all" };+ const trigger: AssessmentTrigger = body.trigger ?? "on_demand";++ let models: Array<{ providerId: string; modelId: string }>;++ if (scope.type === "provider") {+ models = await getModelsForProvider(scope.providerId);+ } else if (scope.type === "model") {+ models = [{ providerId: scope.modelId.split("/")[0], modelId: scope.modelId.split("/")[1] }];+ } else {+ models = await getAllModels();+ }++ const run = await assessor.runAssessment(models, trigger);++ for (const assessment of assessor.getAllAssessments()) {+ categorizer.assignCategoriesAndFitness(assessment);+ }++ return NextResponse.json({+ run_id: run.id,+ status: "completed",+ models_tested: run.modelsTested,+ models_passed: run.modelsPassed,+ models_failed: run.modelsFailed,+ models_rate_limited: run.modelsRateLimited,+ duration_ms: run.durationMs,+ });+ } catch (error) {+ return NextResponse.json(+ { error: error instanceof Error ? error.message : "Unknown error" },+ { status: 500 }+ );+ }+}++export async function GET(request: NextRequest) {+ const url = new URL(request.url);+ const action = url.searchParams.get("action");++ if (action === "results") {+ const status = url.searchParams.get("status");+ const provider = url.searchParams.get("provider");+ const category = url.searchParams.get("category");++ let results = assessor.getAllAssessments();+ if (status) results = results.filter((a) => a.status === status);+ if (provider) results = results.filter((a) => a.providerId === provider);+ if (category) results = results.filter((a) => a.categories.includes(category as any));++ return NextResponse.json({ models: results });+ }++ if (action === "combo-health") {+ return NextResponse.json({ combos: [], message: "Combo health requires DB access" });+ }++ if (action === "working") {+ return NextResponse.json({ models: assessor.getWorkingModels() });+ }++ return NextResponse.json({+ endpoints: {+ "GET ?action=results": "Get assessment results (filter: status, provider, category)",+ "GET ?action=combo-health": "Get combo health status",+ "GET ?action=working": "Get working models only",+ "POST { scope, trigger }": "Run assessment",+ },+ });+}++async function getAllModels(): Promise<Array<{ providerId: string; modelId: string }>> {+ try {+ const resp = await fetch("http://localhost:20128/v1/models", {+ headers: {+ Authorization: `Bearer ${process.env.OMNIROUTe_API_KEY ?? process.env.API_KEY ?? ""}`,+ },+ });+ const data = await resp.json();+ return (data.data ?? [])+ .filter((m: any) => m.id?.startsWith("auto/"))+ .map((m: any) => ({ providerId: "auto", modelId: m.id.replace("auto/", "") }));+ } catch {+ return [];+ }+}++async function getModelsForProvider(+ providerId: string+): Promise<Array<{ providerId: string; modelId: string }>> {+ void providerId;+ return getAllModels();+}diff --git a/src/domain/assessment/assessor.ts b/src/domain/assessment/assessor.tsnew file mode 100644index 0000000000..0358f57007--- /dev/null+++ b/src/domain/assessment/assessor.ts@@ -0,0 +1,206 @@+/**+ * Assessor — Probes provider/model pairs to determine working status and performance.+ *+ * Sends lightweight chat completion requests through each provider connection+ * and records success/failure, latency, and capability detection.+ *+ * @module domain/assessment/assessor+ */++import type {+ ModelAssessment,+ AssessmentStatus,+ ProbeLevel,+ AssessmentConfig,+ AssessmentRun,+ AssessmentScope,+ AssessmentTrigger,+} from "./types";+import { DEFAULT_ASSESSMENT_CONFIG, PROBE_MESSAGES, PROBE_MAX_TOKENS } from "./types";++interface ProbeResult {+ status: AssessmentStatus;+ latencyMs: number;+ error?: string;+ supportsStreaming?: boolean;+ content?: string;+}++export class Assessor {+ private config: AssessmentConfig;+ private assessments: Map<string, ModelAssessment> = new Map();+ private apiKey: string;+ private baseUrl: string;++ constructor(+ apiKey: string,+ baseUrl: string = "http://localhost:20128/v1",+ config: Partial<AssessmentConfig> = {}+ ) {+ this.apiKey = apiKey;+ this.baseUrl = baseUrl;+ this.config = { ...DEFAULT_ASSESSMENT_CONFIG, ...config };+ }++ async probeModel(+ providerId: string,+ modelId: string,+ level: ProbeLevel = "quick"+ ): Promise<ProbeResult> {+ const messages = PROBE_MESSAGES[level];+ const maxTokens = PROBE_MAX_TOKENS[level];+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), this.config.probeTimeoutMs);++ try {+ const start = Date.now();+ const response = await fetch(`${this.baseUrl}/chat/completions`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${this.apiKey}`,+ },+ body: JSON.stringify({+ model: `${providerId}/${modelId}`,+ messages,+ max_tokens: maxTokens,+ stream: false,+ }),+ signal: controller.signal,+ });++ const latencyMs = Date.now() - start;++ if (response.status === 401 || response.status === 403) {+ return { status: "auth_error", latencyMs, error: `Auth failed: ${response.status}` };+ }++ if (response.status === 429) {+ return { status: "rate_limited", latencyMs, error: "Rate limited" };+ }++ if (response.status === 400) {+ const body = await response.text();+ return { status: "broken", latencyMs, error: `Bad request: ${body.slice(0, 200)}` };+ }++ if (!response.ok) {+ return { status: "broken", latencyMs, error: `HTTP ${response.status}` };+ }++ const data = await response.json();+ const content = data.choices?.[0]?.message?.content?.trim() ?? "";+ const supportsStreaming = data.usage?.completion_tokens > 0;++ return { status: "working", latencyMs, content, supportsStreaming };+ } catch (err) {+ if (err.name === "AbortError") {+ return {+ status: "timeout",+ latencyMs: this.config.probeTimeoutMs,+ error: "Probe timed out",+ };+ }+ return { status: "broken", latencyMs: 0, error: err.message };+ } finally {+ clearTimeout(timeout);+ }+ }++ async assessModel(providerId: string, modelId: string): Promise<ModelAssessment> {+ const id = `${providerId}/${modelId}`;+ const existing = this.assessments.get(id);+ const now = new Date().toISOString();++ const probeResults: ProbeResult[] = [];++ for (const level of ["quick", "standard"] as ProbeLevel[]) {+ const result = await this.probeModel(providerId, modelId, level);+ probeResults.push(result);+ if (result.status === "auth_error" || result.status === "broken") break;+ }++ const bestResult = probeResults.find((r) => r.status === "working") ?? probeResults[0];+ const latencies = probeResults.filter((r) => r.status === "working").map((r) => r.latencyMs);++ const assessment: ModelAssessment = {+ id,+ modelId,+ providerId,+ status: bestResult.status,+ latencyP50: latencies.length > 0 ? percentile(latencies, 50) : null,+ latencyP95: latencies.length > 0 ? percentile(latencies, 95) : null,+ successRate: probeResults.filter((r) => r.status === "working").length / probeResults.length,+ supportsVision: false,+ supportsToolCall: false,+ supportsStreaming: bestResult.supportsStreaming ?? false,+ supportsStructuredOutput: false,+ maxContextWindow: null,+ maxOutputTokens: null,+ categories: [],+ fitnessScores: {} as Record<string, number>,+ tier: "balanced",+ lastTested: now,+ lastError: bestResult.error ?? null,+ consecutiveFails: bestResult.status === "working" ? 0 : (existing?.consecutiveFails ?? 0) + 1,+ probeCount: (existing?.probeCount ?? 0) + probeResults.length,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ };++ this.assessments.set(id, assessment);+ return assessment;+ }++ async runAssessment(+ models: Array<{ providerId: string; modelId: string }>,+ trigger: AssessmentTrigger = "on_demand"+ ): Promise<AssessmentRun> {+ const run: AssessmentRun = {+ id: crypto.randomUUID(),+ startedAt: new Date().toISOString(),+ completedAt: null,+ modelsTested: 0,+ modelsPassed: 0,+ modelsFailed: 0,+ modelsRateLimited: 0,+ durationMs: null,+ trigger,+ createdAt: new Date().toISOString(),+ };++ const start = Date.now();++ for (const { providerId, modelId } of models) {+ const assessment = await this.assessModel(providerId, modelId);+ run.modelsTested++;+ if (assessment.status === "working") run.modelsPassed++;+ else if (assessment.status === "rate_limited") run.modelsRateLimited++;+ else run.modelsFailed++;+ }++ run.completedAt = new Date().toISOString();+ run.durationMs = Date.now() - start;++ return run;+ }++ getAssessment(providerId: string, modelId: string): ModelAssessment | undefined {+ return this.assessments.get(`${providerId}/${modelId}`);+ }++ getAllAssessments(): ModelAssessment[] {+ return Array.from(this.assessments.values());+ }++ getWorkingModels(): ModelAssessment[] {+ return this.getAllAssessments().filter((a) => a.status === "working");+ }+}++function percentile(values: number[], p: number): number {+ if (values.length === 0) return 0;+ const sorted = [...values].sort((a, b) => a - b);+ const idx = Math.ceil((p / 100) * sorted.length) - 1;+ return sorted[Math.max(0, idx)];+}diff --git a/src/domain/assessment/categorizer.ts b/src/domain/assessment/categorizer.tsnew file mode 100644index 0000000000..b3e368b671--- /dev/null+++ b/src/domain/assessment/categorizer.ts@@ -0,0 +1,118 @@+import type { ModelAssessment, ModelCategory, ModelTier } from "./types";++const TIER_SCORES: Record<ModelTier, number> = {+ premium: 1.0,+ balanced: 0.67,+ fast: 0.5,+ free: 0.0,+};++const CATEGORY_WEIGHTS: Record<+ ModelCategory,+ { tier: number; speed: number; success: number; cost: number }+> = {+ coding: { tier: 0.4, speed: 0.3, success: 0.2, cost: 0.1 },+ reasoning: { tier: 0.5, success: 0.3, speed: 0.1, cost: 0.1 },+ reasoning_deep: { tier: 0.7, success: 0.2, speed: 0.05, cost: 0.05 },+ chat: { tier: 0.2, success: 0.4, speed: 0.3, cost: 0.1 },+ fast: { tier: 0.1, success: 0.3, speed: 0.6, cost: 0 },+ vision: { tier: 0.3, success: 0.5, speed: 0.1, cost: 0.1 },+ tool_call: { tier: 0.3, success: 0.5, speed: 0.1, cost: 0.1 },+ structured_output: { tier: 0.3, success: 0.5, speed: 0.1, cost: 0.1 },+};++const MODEL_PATTERNS: Array<{ pattern: RegExp; categories: ModelCategory[]; tier: ModelTier }> = [+ {+ pattern: /opus|o[1-4]/i,+ categories: ["reasoning_deep", "coding", "reasoning"],+ tier: "premium",+ },+ { pattern: /sonnet/i, categories: ["coding", "reasoning", "chat"], tier: "premium" },+ { pattern: /haiku/i, categories: ["fast", "coding", "chat"], tier: "fast" },+ { pattern: /gpt-4|gpt-5/i, categories: ["coding", "reasoning", "chat"], tier: "premium" },+ { pattern: /gpt-3\.5|gpt-4o-mini/i, categories: ["fast", "chat"], tier: "fast" },+ {+ pattern: /deepseek.*pro|deepseek.*v[3-9]/i,+ categories: ["coding", "reasoning"],+ tier: "balanced",+ },+ { pattern: /cogito/i, categories: ["reasoning_deep", "reasoning"], tier: "balanced" },+ { pattern: /devstral|codestral/i, categories: ["coding", "fast"], tier: "balanced" },+ { pattern: /gemma.*(?:31|71)/i, categories: ["coding", "reasoning"], tier: "balanced" },+ { pattern: /gemma.*(?:4|12)/i, categories: ["fast", "chat"], tier: "fast" },+ { pattern: /gemma.*3/i, categories: ["fast", "chat"], tier: "fast" },+ { pattern: /glm/i, categories: ["coding", "chat"], tier: "balanced" },+ { pattern: /qwen.*72|qwen.*plus/i, categories: ["reasoning", "coding"], tier: "balanced" },+ { pattern: /mini|flash|nano/i, categories: ["fast", "chat"], tier: "fast" },+];++export class Categorizer {+ categorizeModel(assessment: ModelAssessment): ModelCategory[] {+ const categories = new Set<ModelCategory>();++ if (assessment.latencyP50 !== null && assessment.latencyP50 < 2000) {+ categories.add("fast");+ }+ if (assessment.supportsVision) categories.add("vision");+ if (assessment.supportsToolCall) categories.add("tool_call");+ if (assessment.supportsStructuredOutput) categories.add("structured_output");++ for (const { pattern, categories: patternCats } of MODEL_PATTERNS) {+ if (pattern.test(assessment.modelId)) {+ for (const cat of patternCats) categories.add(cat);+ break;+ }+ }++ if (categories.size === 0) categories.add("chat");++ return Array.from(categories);+ }++ assignTier(assessment: ModelAssessment): ModelTier {+ for (const { pattern, tier } of MODEL_PATTERNS) {+ if (pattern.test(assessment.modelId)) return tier;+ }+ return "balanced";+ }++ calculateFitness(assessment: ModelAssessment, category: ModelCategory): number {+ const weights = CATEGORY_WEIGHTS[category];+ const tierScore = TIER_SCORES[assessment.tier];+ const speedScore =+ assessment.latencyP50 !== null ? Math.max(0, 1 - assessment.latencyP50 / 15000) : 0.5;+ const successScore = assessment.successRate;+ const costScore = 0.5;++ return (+ weights.tier * tierScore ++ weights.speed * speedScore ++ weights.success * successScore ++ weights.cost * costScore+ );+ }++ calculateAllFitness(assessment: ModelAssessment): Record<string, number> {+ const scores: Record<string, number> = {};+ for (const category of assessment.categories) {+ scores[category] = Math.round(this.calculateFitness(assessment, category) * 100) / 100;+ }+ return scores;+ }++ assignCategoriesAndFitness(assessment: ModelAssessment): ModelAssessment {+ const categories = this.categorizeModel(assessment);+ const tier = this.assignTier(assessment);+ const fitnessScores = categories.reduce(+ (acc, cat) => ({ ...acc, [cat]: this.calculateFitness(assessment, cat) }),+ {} as Record<string, number>+ );++ return {+ ...assessment,+ categories,+ tier,+ fitnessScores,+ };+ }+}diff --git a/src/domain/assessment/index.ts b/src/domain/assessment/index.tsnew file mode 100644index 0000000000..a5775814da--- /dev/null+++ b/src/domain/assessment/index.ts@@ -0,0 +1,24 @@+export { Assessor } from "./assessor";+export { Categorizer } from "./categorizer";+export { SelfHealer } from "./selfHealer";+export type {+ AssessmentStatus,+ ModelCategory,+ ModelTier,+ ProbeLevel,+ AssessmentScope,+ ModelAssessment,+ AssessmentRun,+ AssessmentTrigger,+ ComboHealth,+ HealActionType,+ HealAction,+ AssessmentConfig,+ AutoComboTemplate,+} from "./types";+export {+ DEFAULT_ASSESSMENT_CONFIG,+ AUTO_COMBO_TEMPLATES,+ PROBE_MESSAGES,+ PROBE_MAX_TOKENS,+} from "./types";diff --git a/src/domain/assessment/migration.ts b/src/domain/assessment/migration.tsnew file mode 100644index 0000000000..af8e4ada7d--- /dev/null+++ b/src/domain/assessment/migration.ts@@ -0,0 +1,109 @@+import Database from "better-sqlite3";+import { mkdirSync, existsSync } from "node:fs";+import { dirname } from "node:path";++const MIGRATION_SQL = `+-- Model assessments: probe results for each provider/model pair+CREATE TABLE IF NOT EXISTS model_assessments (+ id TEXT PRIMARY KEY,+ model_id TEXT NOT NULL,+ provider_id TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'unknown',+ latency_p50 INTEGER,+ latency_p95 INTEGER,+ success_rate REAL DEFAULT 0,+ supports_vision INTEGER DEFAULT 0,+ supports_tool_call INTEGER DEFAULT 0,+ supports_streaming INTEGER DEFAULT 0,+ supports_structured_output INTEGER DEFAULT 0,+ max_context_window INTEGER,+ max_output_tokens INTEGER,+ categories TEXT DEFAULT '[]',+ fitness_scores TEXT DEFAULT '{}',+ tier TEXT DEFAULT 'balanced',+ last_tested TEXT,+ last_error TEXT,+ consecutive_fails INTEGER DEFAULT 0,+ probe_count INTEGER DEFAULT 0,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ UNIQUE(model_id, provider_id)+);++-- Assessment run history+CREATE TABLE IF NOT EXISTS assessment_runs (+ id TEXT PRIMARY KEY,+ started_at TEXT NOT NULL,+ completed_at TEXT,+ models_tested INTEGER DEFAULT 0,+ models_passed INTEGER DEFAULT 0,+ models_failed INTEGER DEFAULT 0,+ models_rate_limited INTEGER DEFAULT 0,+ duration_ms INTEGER,+ trigger TEXT DEFAULT 'on_demand',+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+);++-- Combo health tracking+CREATE TABLE IF NOT EXISTS combo_health (+ combo_id TEXT PRIMARY KEY,+ healthy_model_count INTEGER DEFAULT 0,+ dead_model_count INTEGER DEFAULT 0,+ total_model_count INTEGER DEFAULT 0,+ health_score REAL DEFAULT 0,+ last_auto_fix TEXT,+ auto_fix_count INTEGER DEFAULT 0,+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ FOREIGN KEY (combo_id) REFERENCES combos(id)+);++-- Self-heal action log+CREATE TABLE IF NOT EXISTS heal_actions (+ id TEXT PRIMARY KEY,+ combo_id TEXT NOT NULL,+ action_type TEXT NOT NULL,+ model_id TEXT NOT NULL,+ provider_id TEXT NOT NULL,+ reason TEXT NOT NULL,+ previous_weight INTEGER,+ new_weight INTEGER,+ timestamp TEXT NOT NULL,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ FOREIGN KEY (combo_id) REFERENCES combos(id)+);++-- Indexes for common queries+CREATE INDEX IF NOT EXISTS idx_model_assessments_status ON model_assessments(status);+CREATE INDEX IF NOT EXISTS idx_model_assessments_provider ON model_assessments(provider_id);+CREATE INDEX IF NOT EXISTS idx_model_assessments_tier ON model_assessments(tier);+CREATE INDEX IF NOT EXISTS idx_model_assessments_last_tested ON model_assessments(last_tested);+CREATE INDEX IF NOT EXISTS idx_combo_health_health_score ON combo_health(health_score);+CREATE INDEX IF NOT EXISTS idx_heal_actions_combo_id ON heal_actions(combo_id);+CREATE INDEX IF NOT EXISTS idx_heal_actions_timestamp ON heal_actions(timestamp);+`;++export function runAssessmentMigration(dbPath: string): void {+ const dir = dirname(dbPath);+ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true });+ }++ const db = new Database(dbPath);+ db.pragma("journal_mode = WAL");+ db.pragma("foreign_keys = ON");++ db.exec(MIGRATION_SQL);++ const versionRow = db+ .prepare("SELECT COUNT(*) as count FROM _omniroute_migrations WHERE name = ?")+ .get("assessment_engine") as { count: number };+ if (versionRow.count === 0) {+ db.prepare(+ "INSERT INTO _omniroute_migrations (name, applied_at) VALUES (?, datetime('now'))"+ ).run("assessment_engine");+ }++ db.close();+}++export { MIGRATION_SQL };diff --git a/src/domain/assessment/selfHealer.ts b/src/domain/assessment/selfHealer.tsnew file mode 100644index 0000000000..4d26e1c308--- /dev/null+++ b/src/domain/assessment/selfHealer.ts@@ -0,0 +1,261 @@+import type {+ ModelAssessment,+ ComboHealth,+ HealAction,+ HealActionType,+ AssessmentConfig,+ AutoComboTemplate,+} from "./types";+import { DEFAULT_ASSESSMENT_CONFIG, AUTO_COMBO_TEMPLATES } from "./types";++interface ComboModel {+ id: string;+ kind: string;+ model: string;+ providerId: string;+ weight: number;+}++interface Combo {+ id: string;+ name: string;+ data: {+ name: string;+ models: ComboModel[];+ strategy?: string;+ systemMessage?: string;+ [key: string]: unknown;+ };+ [key: string]: unknown;+}++export class SelfHealer {+ private config: AssessmentConfig;+ private healLog: HealAction[] = [];++ constructor(config: Partial<AssessmentConfig> = {}) {+ this.config = { ...DEFAULT_ASSESSMENT_CONFIG, ...config };+ }++ healCombo(+ combo: Combo,+ assessments: Map<string, ModelAssessment>+ ): {+ combo: Combo;+ actions: HealAction[];+ health: ComboHealth;+ } {+ const actions: HealAction[] = [];+ const models = combo.data.models ?? [];+ let healthyCount = 0;+ let deadCount = 0;+ const updatedModels: ComboModel[] = [];++ for (const model of models) {+ const assessmentKey = `${model.providerId}/${model.model}`;+ const assessment = assessments.get(assessmentKey);+ const status = assessment?.status ?? "unknown";++ if (status === "broken") {+ deadCount++;+ if (this.config.selfHealEnabled) {+ actions.push(+ this.createAction(+ combo.id,+ "remove_model",+ model.model,+ model.providerId,+ `Model broken: ${assessment?.lastError ?? "unknown error"}`+ )+ );+ } else {+ updatedModels.push(model);+ }+ continue;+ }++ if (status === "rate_limited") {+ const newWeight = Math.max(+ this.config.minimumWeight,+ model.weight * (1 - this.config.maxWeightReduction)+ );+ updatedModels.push({ ...model, weight: newWeight });+ healthyCount++;+ actions.push(+ this.createAction(+ combo.id,+ "reduce_weight",+ model.model,+ model.providerId,+ `Rate limited: weight ${model.weight} → ${newWeight}`+ )+ );+ continue;+ }++ if (status === "timeout") {+ const newWeight = Math.max(this.config.minimumWeight, model.weight * 0.7);+ updatedModels.push({ ...model, weight: newWeight });+ healthyCount++;+ actions.push(+ this.createAction(+ combo.id,+ "reduce_weight",+ model.model,+ model.providerId,+ `Timeout detected: weight ${model.weight} → ${newWeight}`+ )+ );+ continue;+ }++ healthyCount++;+ updatedModels.push(model);+ }++ if (updatedModels.length === 0 && models.length > 0 && this.config.selfHealEnabled) {+ const bestAlternative = this.findBestWorkingModel(combo.name, assessments);+ if (bestAlternative) {+ updatedModels.push({+ id: `emergency-${bestAlternative.providerId}-${bestAlternative.modelId}`,+ kind: "model",+ model: bestAlternative.modelId,+ providerId: bestAlternative.providerId,+ weight: 100,+ });+ actions.push(+ this.createAction(+ combo.id,+ "emergency_replace",+ bestAlternative.modelId,+ bestAlternative.providerId,+ "All models broken, added best available alternative"+ )+ );+ healthyCount = 1;+ deadCount = 0;+ }+ }++ const totalModelCount = Math.max(models.length, 1);+ const healthScore = healthyCount / totalModelCount;++ const health: ComboHealth = {+ comboId: combo.id,+ healthyModelCount: healthyCount,+ deadModelCount: deadCount,+ totalModelCount,+ healthScore,+ lastAutoFix: actions.length > 0 ? new Date().toISOString() : null,+ autoFixCount: actions.length,+ updatedAt: new Date().toISOString(),+ };++ const healedCombo: Combo = {+ ...combo,+ data: { ...combo.data, models: updatedModels },+ };++ this.healLog.push(...actions);+ return { combo: healedCombo, actions, health };+ }++ findBestWorkingModel(+ comboName: string,+ assessments: Map<string, ModelAssessment>+ ): ModelAssessment | null {+ const template = AUTO_COMBO_TEMPLATES.find((t) => t.name === comboName);+ const workingModels = Array.from(assessments.values()).filter((a) => a.status === "working");++ if (workingModels.length === 0) return null;++ if (template) {+ const matching = workingModels+ .filter((a) => {+ const hasCategory = template.categories.some((c) => a.categories.includes(c));+ const hasTier = template.tiers.includes(a.tier);+ return hasCategory && (template.tiers.length === 0 || hasTier);+ })+ .sort((a, b) => {+ const aScore = Math.max(...Object.values(a.fitnessScores), 0);+ const bScore = Math.max(...Object.values(b.fitnessScores), 0);+ return bScore - aScore;+ });+ return (+ matching[0] ?? workingModels.sort((a, b) => (b.successRate ?? 0) - (a.successRate ?? 0))[0]+ );+ }++ return workingModels.sort((a, b) => (b.successRate ?? 0) - (a.successRate ?? 0))[0];+ }++ generateCombosFromAssessments(+ assessments: Map<string, ModelAssessment>,+ templates: AutoComboTemplate[] = AUTO_COMBO_TEMPLATES+ ): Array<{ template: AutoComboTemplate; models: ComboModel[] }> {+ const results: Array<{ template: AutoComboTemplate; models: ComboModel[] }> = [];++ const working = Array.from(assessments.values()).filter((a) => a.status === "working");++ for (const template of templates) {+ const candidates = working+ .filter((a) => {+ const hasCategory = template.categories.some((c) => a.categories.includes(c));+ const hasTier = template.tiers.length === 0 || template.tiers.includes(a.tier);+ return hasCategory && hasTier;+ })+ .sort((a, b) => {+ const aBestFitness = Math.max(...template.categories.map((c) => a.fitnessScores[c] ?? 0));+ const bBestFitness = Math.max(...template.categories.map((c) => b.fitnessScores[c] ?? 0));+ return bBestFitness - aBestFitness;+ });++ if (candidates.length === 0) continue;++ const totalWeight = 100;+ const models: ComboModel[] = candidates.slice(0, 5).map((a, i) => {+ const fitness = Math.max(...template.categories.map((c) => a.fitnessScores[c] ?? 0));+ const weight =+ i === 0+ ? Math.round(totalWeight * 0.35)+ : Math.round((totalWeight * 0.65) / Math.min(candidates.length - 1, 4));++ return {+ id: `${template.name}-m${i + 1}-${a.providerId}-${a.modelId.replace(/[:/]/g, "-")}`,+ kind: "model",+ model: `${a.providerId}/${a.modelId}`,+ providerId: a.providerId,+ weight,+ };+ });++ results.push({ template, models });+ }++ return results;+ }++ getHealLog(): HealAction[] {+ return [...this.healLog];+ }++ private createAction(+ comboId: string,+ actionType: HealActionType,+ modelId: string,+ providerId: string,+ reason: string+ ): HealAction {+ return {+ id: crypto.randomUUID(),+ comboId,+ actionType,+ modelId,+ providerId,+ reason,+ previousWeight: null,+ newWeight: null,+ timestamp: new Date().toISOString(),+ };+ }+}diff --git a/src/domain/assessment/types.ts b/src/domain/assessment/types.tsnew file mode 100644index 0000000000..d5103571c5--- /dev/null+++ b/src/domain/assessment/types.ts@@ -0,0 +1,352 @@+/**+ * Assessment Engine Types+ *+ * Type definitions for the auto-assessment, categorization,+ * and self-healing system.+ *+ * @module domain/assessment/types+ */++// ── Model Assessment ────────────────────────────────────────────────────────++/** Assessment status for a model/provider pair */+export type AssessmentStatus =+ | "working" // Responds correctly to probes+ | "broken" // Returns errors (4xx, 5xx) or invalid responses+ | "rate_limited" // Temporarily rate-limited (retries may succeed later)+ | "timeout" // Request exceeds probe timeout+ | "auth_error" // Authentication failed (invalid key, expired token)+ | "unknown"; // Not yet assessed++/** Capability categories for model classification */+export type ModelCategory =+ | "coding" // Code generation, debugging, refactoring+ | "reasoning" // Logical reasoning, math, analysis+ | "reasoning_deep" // Extended thinking, complex multi-step reasoning+ | "chat" // Conversational ability, general Q&A+ | "fast" // Sub-2s response time for short prompts+ | "vision" // Image input support+ | "tool_call" // Function/tool calling support+ | "structured_output"; // JSON mode / structured output support;++/** Provider account tier classification */+export type ModelTier = "premium" | "balanced" | "fast" | "free";++/** Probe intensity level */+export type ProbeLevel = "quick" | "standard" | "deep";++/** Scope for assessment runs */+export type AssessmentScope =+ | { type: "all" }+ | { type: "provider"; providerId: string }+ | { type: "model"; modelId: string };++/** Complete assessment result for a model/provider pair */+export interface ModelAssessment {+ /** Unique ID: `${providerId}/${modelId}` */+ id: string;+ /** Model identifier (e.g., "claude-sonnet-4.5") */+ modelId: string;+ /** Provider identifier (e.g., "kiro") */+ providerId: string;+ /** Current assessment status */+ status: AssessmentStatus;+ /** Median latency in milliseconds */+ latencyP50: number | null;+ /** P95 latency in milliseconds */+ latencyP95: number | null;+ /** Success rate over recent probes (0..1) */+ successRate: number;+ /** Whether model supports image inputs */+ supportsVision: boolean;+ /** Whether model supports function/tool calling */+ supportsToolCall: boolean;+ /** Whether model supports streaming */+ supportsStreaming: boolean;+ /** Whether model supports JSON/structured output */+ supportsStructuredOutput: boolean;+ /** Maximum context window in tokens */+ maxContextWindow: number | null;+ /** Maximum output tokens */+ maxOutputTokens: number | null;+ /** Capability categories */+ categories: ModelCategory[];+ /** Fitness score per category (0..1) */+ fitnessScores: Record<ModelCategory, number>;+ /** Overall tier classification */+ tier: ModelTier;+ /** ISO timestamp of last probe */+ lastTested: string | null;+ /** Last error message if any */+ lastError: string | null;+ /** Consecutive failed probes */+ consecutiveFails: number;+ /** Total probes executed */+ probeCount: number;+ /** ISO timestamp of creation */+ createdAt: string;+ /** ISO timestamp of last update */+ updatedAt: string;+}++// ── Assessment Run ───────────────────────────────────────────────────────────++/** Trigger source for an assessment run */+export type AssessmentTrigger =+ | "scheduled"+ | "on_demand"+ | "on_provider_change"+ | "on_error"+ | "startup";++/** Record of a single assessment run */+export interface AssessmentRun {+ id: string;+ startedAt: string;+ completedAt: string | null;+ modelsTested: number;+ modelsPassed: number;+ modelsFailed: number;+ modelsRateLimited: number;+ durationMs: number | null;+ trigger: AssessmentTrigger;+ createdAt: string;+}++// ── Combo Health ─────────────────────────────────────────────────────────────++/** Health status for a combo */+export interface ComboHealth {+ comboId: string;+ healthyModelCount: number;+ deadModelCount: number;+ totalModelCount: number;+ healthScore: number; // 0..1, weighted by model health+ lastAutoFix: string | null;+ autoFixCount: number;+ updatedAt: string;+}++// ── Self-Heal Actions ────────────────────────────────────────────────────────++/** Types of actions the self-healer can take */+export type HealActionType =+ | "remove_model" // Remove broken model from combo+ | "reduce_weight" // Reduce weight of rate-limited model+ | "restore_weight" // Restore weight of recovered model+ | "add_model" // Add working model to combo+ | "emergency_replace"; // Replace all dead models in empty combo;++/** Record of a self-heal action */+export interface HealAction {+ id: string;+ comboId: string;+ actionType: HealActionType;+ modelId: string;+ providerId: string;+ reason: string;+ previousWeight: number | null;+ newWeight: number | null;+ timestamp: string;+}++// ── Probe Configuration ──────────────────────────────────────────────────────++/** Configuration for assessment probes */+export interface AssessmentConfig {+ /** Interval between quick probes (ms) */+ quickProbeIntervalMs: number;+ /** Interval between standard probes (ms) */+ standardProbeIntervalMs: number;+ /** Interval between deep probes (ms) */+ deepProbeIntervalMs: number;+ /** Maximum timeout for a single probe (ms) */+ probeTimeoutMs: number;+ /** Number of consecutive failures before marking as broken */+ brokenThreshold: number;+ /** Number of consecutive successes to restore a model */+ restoreThreshold: number;+ /** Maximum weight reduction factor (0..1, 0.5 = halve the weight) */+ maxWeightReduction: number;+ /** Minimum weight for rate-limited models */+ minimumWeight: number;+ /** Whether self-healing is enabled */+ selfHealEnabled: boolean;+ /** Whether auto-generation of combos is enabled */+ autoGenerateEnabled: boolean;+ /** Whether to skip broken models in combo resolver */+ skipBrokenModels: boolean;+}++/** Default assessment configuration */+export const DEFAULT_ASSESSMENT_CONFIG: AssessmentConfig = {+ quickProbeIntervalMs: 5 * 60 * 1000, // 5 minutes+ standardProbeIntervalMs: 30 * 60 * 1000, // 30 minutes+ deepProbeIntervalMs: 6 * 60 * 60 * 1000, // 6 hours+ probeTimeoutMs: 30 * 1000, // 30 seconds+ brokenThreshold: 3, // 3 consecutive failures+ restoreThreshold: 2, // 2 consecutive successes+ maxWeightReduction: 0.5, // Halve weight+ minimumWeight: 5, // Minimum weight is 5%+ selfHealEnabled: true,+ autoGenerateEnabled: true,+ skipBrokenModels: true,+};++// ── Probe Messages ───────────────────────────────────────────────────────────++/** Probe messages for different assessment levels */+export const PROBE_MESSAGES = {+ quick: [{ role: "user" as const, content: "ok" }],+ standard: [+ {+ role: "user" as const,+ content: "Write a function that adds two numbers. Reply with just the function.",+ },+ ],+ deep: [{ role: "user" as const, content: "What is 17 * 23? Reply with just the number." }],+} as const;++/** Max tokens for each probe level */+export const PROBE_MAX_TOKENS = {+ quick: 3,+ standard: 100,+ deep: 50,+} as const;++// ── Auto-Combo Templates ────────────────────────────────────────────────────++/** Template for auto-generating combos from assessment results */+export interface AutoComboTemplate {+ name: string;+ displayName: string;+ categories: ModelCategory[];+ tiers: ModelTier[];+ strategy: "priority" | "weighted" | "round-robin" | "random" | "least-used";+ /** System message for this combo type */+ systemMessage?: string;+}++/** Default auto-combo templates */+export const AUTO_COMBO_TEMPLATES: AutoComboTemplate[] = [+ {+ name: "auto/best-coding",+ displayName: "Best Coding",+ categories: ["coding"],+ tiers: ["premium", "balanced"],+ strategy: "weighted",+ systemMessage:+ "You are an expert coding assistant. Write clean, efficient, well-documented code.",+ },+ {+ name: "auto/best-reasoning",+ displayName: "Best Reasoning",+ categories: ["reasoning_deep", "reasoning"],+ tiers: ["premium"],+ strategy: "weighted",+ systemMessage: "You are a deep reasoning assistant. Think carefully step by step.",+ },+ {+ name: "auto/best-fast",+ displayName: "Best Fast",+ categories: ["fast"],+ tiers: ["fast", "balanced"],+ strategy: "weighted",+ },+ {+ name: "auto/best-vision",+ displayName: "Best Vision",+ categories: ["vision"],+ tiers: ["premium", "balanced"],+ strategy: "weighted",+ },+ {+ name: "auto/best-chat",+ displayName: "Best Chat",+ categories: ["chat"],+ tiers: ["balanced", "premium"],+ strategy: "weighted",+ },+ {+ name: "auto/best-coding-fast",+ displayName: "Best Coding Fast",+ categories: ["coding", "fast"],+ tiers: ["fast", "balanced"],+ strategy: "weighted",+ },+ {+ name: "auto/pro-coding",+ displayName: "Pro Coding",+ categories: ["coding"],+ tiers: ["premium"],+ strategy: "priority",+ systemMessage:+ "You are an expert coding assistant. Write clean, efficient, well-documented code.",+ },+ {+ name: "auto/pro-reasoning",+ displayName: "Pro Reasoning",+ categories: ["reasoning_deep"],+ tiers: ["premium"],+ strategy: "priority",+ systemMessage: "You are a deep reasoning assistant. Think carefully step by step.",+ },+ {+ name: "auto/pro-vision",+ displayName: "Pro Vision",+ categories: ["vision"],+ tiers: ["premium"],+ strategy: "priority",+ },+ {+ name: "auto/pro-chat",+ displayName: "Pro Chat",+ categories: ["chat"],+ tiers: ["premium"],+ strategy: "priority",+ },+ {+ name: "auto/pro-fast",+ displayName: "Pro Fast",+ categories: ["fast"],+ tiers: ["fast"],+ strategy: "priority",+ },+ {+ name: "auto/coding",+ displayName: "Coding",+ categories: ["coding"],+ tiers: ["balanced", "fast", "premium"],+ strategy: "weighted",+ },+ {+ name: "auto/fast",+ displayName: "Fast",+ categories: ["fast"],+ tiers: ["fast"],+ strategy: "weighted",+ },+ {+ name: "auto/chat",+ displayName: "Chat",+ categories: ["chat"],+ tiers: ["balanced", "fast"],+ strategy: "weighted",+ },+ {+ name: "auto/claude-opus",+ displayName: "Claude Opus",+ categories: ["reasoning_deep", "coding", "reasoning"],+ tiers: ["premium"],+ strategy: "priority",+ },+ {+ name: "auto/claude-sonnet",+ displayName: "Claude Sonnet",+ categories: ["coding", "reasoning", "chat"],+ tiers: ["premium", "balanced"],+ strategy: "priority",+ },+];++export {};