[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77V4FN2SYWCASNDSC2TFD6M":3,"skill-same:01M77V4FN2SYWCASNDSC2TFD6M":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":57,"ownerHtmlUrl":58,"ownerBlogUrl":6,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M77V4FN2SYWCASNDSC2TFD6M","smart-router",null,"Expertise-aware model router with semantic domain scoring, context-overflow protection, and security redaction. Automatically selects the optimal AI model using weighted expertise scoring (Feb 2026 benchmarks). Supports Claude, GPT, Gemini, Grok with automatic fallback chains, HITL gates, and cost optimization.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fs\u002Fsmart-router\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: smart-router\ndescription: >\n  Expertise-aware model router with semantic domain scoring, context-overflow protection,\n  and security redaction. Automatically selects the optimal AI model using weighted\n  expertise scoring (Feb 2026 benchmarks). Supports Claude, GPT, Gemini, Grok with\n  automatic fallback chains, HITL gates, and cost optimization.\nauthor: c0nSpIc0uS7uRk3r\nversion: 2.1.0\nlicense: MIT\nmetadata:\n  openclaw:\n    requires:\n      bins: [\"python3\"]\n      env: [\"ANTHROPIC_API_KEY\"]\n    optional_env: [\"GOOGLE_API_KEY\", \"OPENAI_API_KEY\", \"XAI_API_KEY\"]\n  features:\n    - Semantic domain detection\n    - Expertise-weighted scoring (0-100)\n    - Risk-based mandatory routing\n    - Context overflow protection (>150K → Gemini)\n    - Security credential redaction\n    - Circuit breaker with persistent state\n    - HITL gate for low-confidence routing\n  benchmarks:\n    source: \"Feb 2026 MLOC Analysis\"\n    models:\n      - \"Claude Opus 4.5: SWE-bench 80.9%\"\n      - \"GPT-5.2: AIME 100%, Control Flow 22 errors\u002FMLOC\"\n      - \"Gemini 3 Pro: Concurrency 69 issues\u002FMLOC\"\n---\n\n# A.I. Smart-Router\n\nIntelligently route requests to the optimal AI model using tiered classification with automatic fallback handling and cost optimization.\n\n## How It Works (Silent by Default)\n\nThe router operates transparently—users send messages normally and get responses from the best model for their task. No special commands needed.\n\n**Optional visibility**: Include `[show routing]` in any message to see the routing decision.\n\n## Tiered Classification System\n\nThe router uses a three-tier decision process:\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                    TIER 1: INTENT DETECTION                      │\n│  Classify the primary purpose of the request                     │\n├─────────────────────────────────────────────────────────────────┤\n│  CODE        │ ANALYSIS    │ CREATIVE   │ REALTIME  │ GENERAL   │\n│  write\u002Fdebug │ research    │ writing    │ news\u002Flive │ Q&A\u002Fchat  │\n│  refactor    │ explain     │ stories    │ X\u002FTwitter │ translate │\n│  review      │ compare     │ brainstorm │ prices    │ summarize │\n└──────┬───────┴──────┬──────┴─────┬──────┴─────┬─────┴─────┬─────┘\n       │              │            │            │           │\n       ▼              ▼            ▼            ▼           ▼\n┌─────────────────────────────────────────────────────────────────┐\n│                  TIER 2: COMPLEXITY ESTIMATION                   │\n├─────────────────────────────────────────────────────────────────┤\n│  SIMPLE (Tier $)        │ MEDIUM (Tier $$)    │ COMPLEX (Tier $$$)│\n│  • One-step task        │ • Multi-step task   │ • Deep reasoning  │\n│  • Short response OK    │ • Some nuance       │ • Extensive output│\n│  • Factual lookup       │ • Moderate context  │ • Critical task   │\n│  → Haiku\u002FFlash          │ → Sonnet\u002FGrok\u002FGPT   │ → Opus\u002FGPT-5      │\n└──────────────────────────┴─────────────────────┴───────────────────┘\n                                    │\n                                    ▼\n┌─────────────────────────────────────────────────────────────────┐\n│                TIER 3: SPECIAL CASE OVERRIDES                    │\n├─────────────────────────────────────────────────────────────────┤\n│  CONDITION                           │ OVERRIDE TO              │\n│  ─────────────────────────────────────┼─────────────────────────│\n│  Context >100K tokens                │ → Gemini Pro (1M ctx)    │\n│  Context >500K tokens                │ → Gemini Pro ONLY        │\n│  Needs real-time data                │ → Grok (regardless)      │\n│  Image\u002Fvision input                  │ → Opus or Gemini Pro     │\n│  User explicit override              │ → Requested model        │\n└──────────────────────────────────────┴──────────────────────────┘\n```\n\n## Intent Detection Patterns\n\n### CODE Intent\n- Keywords: write, code, debug, fix, refactor, implement, function, class, script, API, bug, error, compile, test, PR, commit\n- File extensions mentioned: .py, .js, .ts, .go, .rs, .java, etc.\n- Code blocks in input\n\n### ANALYSIS Intent  \n- Keywords: analyze, explain, compare, research, understand, why, how does, evaluate, assess, review, investigate, examine\n- Long-form questions\n- \"Help me understand...\"\n\n### CREATIVE Intent\n- Keywords: write (story\u002Fpoem\u002Fessay), create, brainstorm, imagine, design, draft, compose\n- Fiction\u002Fnarrative requests\n- Marketing\u002Fcopy requests\n\n### REALTIME Intent\n- Keywords: now, today, current, latest, trending, news, happening, live, price, score, weather\n- X\u002FTwitter mentions\n- Stock\u002Fcrypto tickers\n- Sports scores\n\n### GENERAL Intent (Default)\n- Simple Q&A\n- Translations\n- Summaries\n- Conversational\n\n### MIXED Intent (Multiple Intents Detected)\nWhen a request contains multiple clear intents (e.g., \"Write code to analyze this data and explain it creatively\"):\n\n1. **Identify primary intent** — What's the main deliverable?\n2. **Route to highest-capability model** — Mixed tasks need versatility\n3. **Default to COMPLEX complexity** — Multi-intent = multi-step\n\n**Examples:**\n- \"Write code AND explain how it works\" → CODE (primary) + ANALYSIS → Route to Opus\n- \"Summarize this AND what's the latest news on it\" → REALTIME takes precedence → Grok\n- \"Creative story using real current events\" → REALTIME + CREATIVE → Grok (real-time wins)\n\n## Language Handling\n\n**Non-English requests** are handled normally — all supported models have multilingual capabilities:\n\n| Model | Non-English Support |\n|-------|---------------------|\n| Opus\u002FSonnet\u002FHaiku | Excellent (100+ languages) |\n| GPT-5 | Excellent (100+ languages) |\n| Gemini Pro\u002FFlash | Excellent (100+ languages) |\n| Grok | Good (major languages) |\n\n**Intent detection still works** because:\n- Keyword patterns include common non-English equivalents\n- Code intent detected by file extensions, code blocks (language-agnostic)\n- Complexity estimated by query length (works across languages)\n\n**Edge case:** If intent unclear due to language, default to GENERAL intent with MEDIUM complexity.\n\n## Complexity Signals\n\n### Simple Complexity ($)\n- Short query (\u003C50 words)\n- Single question mark\n- \"Quick question\", \"Just tell me\", \"Briefly\"\n- Yes\u002Fno format\n- Unit conversions, definitions\n\n### Medium Complexity ($$)\n- Moderate query (50-200 words)\n- Multiple aspects to address\n- \"Explain\", \"Describe\", \"Compare\"\n- Some context provided\n\n### Complex Complexity ($$$)\n- Long query (>200 words) or complex task\n- \"Step by step\", \"Thoroughly\", \"In detail\"\n- Multi-part questions\n- Critical\u002Fimportant qualifier\n- Research, analysis, or creative work\n\n## Routing Matrix\n\n| Intent | Simple | Medium | Complex |\n|--------|--------|--------|---------|\n| **CODE** | Sonnet | Opus | Opus |\n| **ANALYSIS** | Flash | GPT-5 | Opus |\n| **CREATIVE** | Sonnet | Opus | Opus |\n| **REALTIME** | Grok | Grok | Grok-3 |\n| **GENERAL** | Flash | Sonnet | Opus |\n\n## Token Exhaustion & Automatic Model Switching\n\nWhen a model becomes unavailable mid-session (token quota exhausted, rate limit hit, API error), the router automatically switches to the next best available model and **notifies the user**.\n\n### Notification Format\n\nWhen a model switch occurs due to exhaustion, the user receives a notification:\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│  ⚠️ MODEL SWITCH NOTICE                                         │\n│                                                                  │\n│  Your request could not be completed on claude-opus-4-5         │\n│  (reason: token quota exhausted).                               │\n│                                                                  │\n│  ✅ Request completed using: anthropic\u002Fclaude-sonnet-4-5        │\n│                                                                  │\n│  The response below was generated by the fallback model.        │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Switch Reasons\n\n| Reason | Description |\n|--------|-------------|\n| `token quota exhausted` | Daily\u002Fmonthly token limit reached |\n| `rate limit exceeded` | Too many requests per minute |\n| `context window exceeded` | Input too large for model |\n| `API timeout` | Model took too long to respond |\n| `API error` | Provider returned an error |\n| `model unavailable` | Model temporarily offline |\n\n### Implementation\n\n```python\ndef execute_with_fallback(primary_model: str, fallback_chain: list[str], request: str) -> Response:\n    \"\"\"\n    Execute request with automatic fallback and user notification.\n    \"\"\"\n    attempted_models = []\n    switch_reason = None\n    \n    # Try primary model first\n    models_to_try = [primary_model] + fallback_chain\n    \n    for model in models_to_try:\n        try:\n            response = call_model(model, request)\n            \n            # If we switched models, prepend notification\n            if attempted_models:\n                notification = build_switch_notification(\n                    failed_model=attempted_models[0],\n                    reason=switch_reason,\n                    success_model=model\n                )\n                return Response(\n                    content=notification + \"\\n\\n---\\n\\n\" + response.content,\n                    model_used=model,\n                    switched=True\n                )\n            \n            return Response(content=response.content, model_used=model, switched=False)\n            \n        except TokenQuotaExhausted:\n            attempted_models.append(model)\n            switch_reason = \"token quota exhausted\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except RateLimitExceeded:\n            attempted_models.append(model)\n            switch_reason = \"rate limit exceeded\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except ContextWindowExceeded:\n            attempted_models.append(model)\n            switch_reason = \"context window exceeded\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except APITimeout:\n            attempted_models.append(model)\n            switch_reason = \"API timeout\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except APIError as e:\n            attempted_models.append(model)\n            switch_reason = f\"API error: {e.code}\"\n            log_fallback(model, switch_reason)\n            continue\n    \n    # All models exhausted\n    return build_exhaustion_error(attempted_models)\n\n\ndef build_switch_notification(failed_model: str, reason: str, success_model: str) -> str:\n    \"\"\"Build user-facing notification when model switch occurs.\"\"\"\n    return f\"\"\"⚠️ **MODEL SWITCH NOTICE**\n\nYour request could not be completed on `{failed_model}` (reason: {reason}).\n\n✅ **Request completed using:** `{success_model}`\n\nThe response below was generated by the fallback model.\"\"\"\n\n\ndef build_exhaustion_error(attempted_models: list[str]) -> Response:\n    \"\"\"Build error when all models are exhausted.\"\"\"\n    models_tried = \", \".join(attempted_models)\n    return Response(\n        content=f\"\"\"❌ **REQUEST FAILED**\n\nUnable to complete your request. All available models have been exhausted.\n\n**Models attempted:** {models_tried}\n\n**What you can do:**\n1. **Wait** — Token quotas typically reset hourly or daily\n2. **Simplify** — Try a shorter or simpler request\n3. **Check status** — Run `\u002Frouter status` to see model availability\n\nIf this persists, your human may need to check API quotas or add additional providers.\"\"\",\n        model_used=None,\n        switched=False,\n        failed=True\n    )\n```\n\n### Fallback Priority for Token Exhaustion\n\nWhen a model is exhausted, the router selects the next best model for the **same task type**:\n\n| Original Model | Fallback Priority (same capability) |\n|----------------|-------------------------------------|\n| Opus | Sonnet → GPT-5 → Grok-3 → Gemini Pro |\n| Sonnet | GPT-5 → Grok-3 → Opus → Haiku |\n| GPT-5 | Sonnet → Opus → Grok-3 → Gemini Pro |\n| Gemini Pro | Flash → GPT-5 → Opus → Sonnet |\n| Grok-2\u002F3 | (warn: no real-time fallback available) |\n\n### User Acknowledgment\n\nAfter a model switch, the agent should note in the response that:\n1. The original model was unavailable\n2. Which model actually completed the request\n3. The response quality may differ from the original model's typical output\n\nThis ensures transparency and sets appropriate expectations.\n\n### Streaming Responses with Fallback\n\nWhen using streaming responses, fallback handling requires special consideration:\n\n```python\nasync def execute_with_streaming_fallback(primary_model: str, fallback_chain: list[str], request: str):\n    \"\"\"\n    Handle streaming responses with mid-stream fallback.\n    \n    If a model fails DURING streaming (not before), the partial response is lost.\n    Strategy: Don't start streaming until first chunk received successfully.\n    \"\"\"\n    models_to_try = [primary_model] + fallback_chain\n    \n    for model in models_to_try:\n        try:\n            # Test with non-streaming ping first (optional, adds latency)\n            # await test_model_availability(model)\n            \n            # Start streaming\n            stream = await call_model_streaming(model, request)\n            first_chunk = await stream.get_first_chunk(timeout=10_000)  # 10s timeout for first chunk\n            \n            # If we got here, model is responding — continue streaming\n            yield first_chunk\n            async for chunk in stream:\n                yield chunk\n            return  # Success\n            \n        except (FirstChunkTimeout, StreamError) as e:\n            log_fallback(model, str(e))\n            continue  # Try next model\n    \n    # All models failed\n    yield build_exhaustion_error(models_to_try)\n```\n\n**Key insight:** Wait for the first chunk before committing to a model. If the first chunk times out, fall back before any partial response is shown to the user.\n\n### Retry Timing Configuration\n\n```python\nRETRY_CONFIG = {\n    \"initial_timeout_ms\": 30_000,     # 30s for first attempt\n    \"fallback_timeout_ms\": 20_000,    # 20s for fallback attempts (faster fail)\n    \"max_retries_per_model\": 1,       # Don't retry same model\n    \"backoff_multiplier\": 1.5,        # Not used (no same-model retry)\n    \"circuit_breaker_threshold\": 3,   # Failures before skipping model entirely\n    \"circuit_breaker_reset_ms\": 300_000  # 5 min before trying failed model again\n}\n```\n\n**Circuit breaker:** If a model fails 3 times in 5 minutes, skip it entirely for the next 5 minutes. This prevents repeatedly hitting a down service.\n\n## Fallback Chains\n\nWhen the preferred model fails (rate limit, API down, error), cascade to the next option:\n\n### Code Tasks\n```\nOpus → Sonnet → GPT-5 → Gemini Pro\n```\n\n### Analysis Tasks\n```\nOpus → GPT-5 → Gemini Pro → Sonnet\n```\n\n### Creative Tasks\n```\nOpus → GPT-5 → Sonnet → Gemini Pro\n```\n\n### Real-time Tasks\n```\nGrok-2 → Grok-3 → (warn: no real-time fallback)\n```\n\n### General Tasks\n```\nFlash → Haiku → Sonnet → GPT-5\n```\n\n### Long Context (Tiered by Size)\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                  LONG CONTEXT FALLBACK CHAIN                     │\n├─────────────────────────────────────────────────────────────────┤\n│  TOKEN COUNT        │ FALLBACK CHAIN                            │\n│  ───────────────────┼───────────────────────────────────────────│\n│  128K - 200K        │ Opus (200K) → Sonnet (200K) → Gemini Pro  │\n│  200K - 1M          │ Gemini Pro → Flash (1M) → ERROR_MESSAGE   │\n│  > 1M               │ ERROR_MESSAGE (no model supports this)    │\n└─────────────────────┴───────────────────────────────────────────┘\n```\n\n**Implementation:**\n\n```python\ndef handle_long_context(token_count: int, available_models: dict) -> str | ErrorMessage:\n    \"\"\"Route long-context requests with graceful degradation.\"\"\"\n    \n    # Tier 1: 128K - 200K tokens (Opus\u002FSonnet can handle)\n    if token_count \u003C= 200_000:\n        for model in [\"opus\", \"sonnet\", \"haiku\", \"gemini-pro\", \"flash\"]:\n            if model in available_models and get_context_limit(model) >= token_count:\n                return model\n    \n    # Tier 2: 200K - 1M tokens (only Gemini)\n    elif token_count \u003C= 1_000_000:\n        for model in [\"gemini-pro\", \"flash\"]:\n            if model in available_models:\n                return model\n    \n    # Tier 3: > 1M tokens (nothing available)\n    # Fall through to error\n    \n    # No suitable model found — return helpful error\n    return build_context_error(token_count, available_models)\n\n\ndef build_context_error(token_count: int, available_models: dict) -> ErrorMessage:\n    \"\"\"Build a helpful error message when no model can handle the input.\"\"\"\n    \n    # Find the largest available context window\n    max_available = max(\n        (get_context_limit(m) for m in available_models),\n        default=0\n    )\n    \n    # Determine what's missing\n    missing_models = []\n    if \"gemini-pro\" not in available_models and \"flash\" not in available_models:\n        missing_models.append(\"Gemini Pro\u002FFlash (1M context)\")\n    if token_count \u003C= 200_000 and \"opus\" not in available_models:\n        missing_models.append(\"Opus (200K context)\")\n    \n    # Format token count for readability\n    if token_count >= 1_000_000:\n        token_display = f\"{token_count \u002F 1_000_000:.1f}M\"\n    else:\n        token_display = f\"{token_count \u002F\u002F 1000}K\"\n    \n    return ErrorMessage(\n        title=\"Context Window Exceeded\",\n        message=f\"\"\"Your input is approximately **{token_display} tokens**, which exceeds the context window of all currently available models.\n\n**Required:** Gemini Pro (1M context) {\"— currently unavailable\" if \"gemini-pro\" not in available_models else \"\"}\n**Your max available:** {max_available \u002F\u002F 1000}K tokens\n\n**Options:**\n1. **Wait and retry** — Gemini may be temporarily down\n2. **Reduce input size** — Remove unnecessary content to fit within {max_available \u002F\u002F 1000}K tokens\n3. **Split into chunks** — I can process your input sequentially in smaller pieces\n\nWould you like me to help split this into manageable chunks?\"\"\",\n        \n        recoverable=True,\n        suggested_action=\"split_chunks\"\n    )\n```\n\n**Example Error Output:**\n\n```\n⚠️ Context Window Exceeded\n\nYour input is approximately **340K tokens**, which exceeds the context \nwindow of all currently available models.\n\nRequired: Gemini Pro (1M context) — currently unavailable\nYour max available: 200K tokens\n\nOptions:\n1. Wait and retry — Gemini may be temporarily down\n2. Reduce input size — Remove unnecessary content to fit within 200K tokens\n3. Split into chunks — I can process your input sequentially in smaller pieces\n\nWould you like me to help split this into manageable chunks?\n```\n\n## Dynamic Model Discovery\n\nThe router auto-detects available providers at runtime:\n\n```\n1. Check configured auth profiles\n2. Build available model list from authenticated providers\n3. Construct routing table using ONLY available models\n4. If preferred model unavailable, use best available alternative\n```\n\n**Example**: If only Anthropic and Google are configured:\n- Code tasks → Opus (Anthropic available ✓)\n- Real-time tasks → ⚠️ No Grok → Fall back to Opus + warn user\n- Long docs → Gemini Pro (Google available ✓)\n\n## Cost Optimization\n\nThe router considers cost when complexity is LOW:\n\n| Model | Cost Tier | Use When |\n|-------|-----------|----------|\n| Gemini Flash | $ | Simple tasks, high volume |\n| Claude Haiku | $ | Simple tasks, quick responses |\n| Claude Sonnet | $$ | Medium complexity |\n| Grok 2 | $$ | Real-time needs only |\n| GPT-5 | $$ | General fallback |\n| Gemini Pro | $$$ | Long context needs |\n| Claude Opus | $$$$ | Complex\u002Fcritical tasks |\n\n**Rule**: Never use Opus ($$$) for tasks that Flash ($) can handle.\n\n## User Controls\n\n### Show Routing Decision\nAdd `[show routing]` to any message:\n```\n[show routing] What's the weather in NYC?\n```\nOutput includes:\n```\n[Routed → xai\u002Fgrok-2-latest | Reason: REALTIME intent detected | Fallback: none available]\n```\n\n### Force Specific Model\nExplicit overrides:\n- \"use grok: ...\" → Forces Grok\n- \"use claude: ...\" → Forces Opus\n- \"use gemini: ...\" → Forces Gemini Pro\n- \"use flash: ...\" → Forces Gemini Flash\n- \"use gpt: ...\" → Forces GPT-5\n\n### Check Router Status\nAsk: \"router status\" or \"\u002Frouter\" to see:\n- Available providers\n- Configured models\n- Current routing table\n- Recent routing decisions\n\n## Implementation Notes\n\n### For Agent Implementation\n\nWhen processing a request:\n\n```\n1. DETECT available models (check auth profiles)\n2. CLASSIFY intent (code\u002Fanalysis\u002Fcreative\u002Frealtime\u002Fgeneral)\n3. ESTIMATE complexity (simple\u002Fmedium\u002Fcomplex)\n4. CHECK special cases (context size, vision, explicit override)\n5. FILTER by cost tier based on complexity ← BEFORE model selection\n6. SELECT model from filtered pool using routing matrix\n7. VERIFY model available, else use fallback chain (also cost-filtered)\n8. EXECUTE request with selected model\n9. IF failure, try next in fallback chain\n10. LOG routing decision (for debugging)\n```\n\n### Cost-Aware Routing Flow (Critical Order)\n\n```python\ndef route_with_fallback(request):\n    \"\"\"\n    Main routing function with CORRECT execution order.\n    Cost filtering MUST happen BEFORE routing table lookup.\n    \"\"\"\n    \n    # Step 1: Discover available models\n    available_models = discover_providers()\n    \n    # Step 2: Classify intent\n    intent = classify_intent(request)\n    \n    # Step 3: Estimate complexity\n    complexity = estimate_complexity(request)\n    \n    # Step 4: Check special-case overrides (these bypass cost filtering)\n    if user_override := get_user_model_override(request):\n        return execute_with_fallback(user_override, [])  # No cost filter for explicit override\n    \n    if token_count > 128_000:\n        return handle_long_context(token_count, available_models)  # Special handling\n    \n    if needs_realtime(request):\n        return execute_with_fallback(\"grok-2\", [\"grok-3\"])  # Realtime bypasses cost\n    \n    # ┌─────────────────────────────────────────────────────────────┐\n    # │  STEP 5: FILTER BY COST TIER — THIS MUST COME FIRST!       │\n    # │                                                             │\n    # │  Cost filtering happens BEFORE the routing table lookup,   │\n    # │  NOT after. This ensures \"what's 2+2?\" never considers     │\n    # │  Opus even momentarily.                                    │\n    # └─────────────────────────────────────────────────────────────┘\n    \n    allowed_tiers = get_allowed_tiers(complexity)\n    # SIMPLE  → [\"$\"]\n    # MEDIUM  → [\"$\", \"$$\"]\n    # COMPLEX → [\"$\", \"$$\", \"$$$\"]\n    \n    cost_filtered_models = {\n        model: meta for model, meta in available_models.items()\n        if COST_TIERS.get(model) in allowed_tiers\n    }\n    \n    # Step 6: NOW select from cost-filtered pool using routing preferences\n    preferences = ROUTING_PREFERENCES.get((intent, complexity), [])\n    \n    for model in preferences:\n        if model in cost_filtered_models:  # Only consider cost-appropriate models\n            selected_model = model\n            break\n    else:\n        # No preferred model in cost-filtered pool — use cheapest available\n        selected_model = select_cheapest(cost_filtered_models)\n    \n    # Step 7: Build cost-filtered fallback chain\n    task_type = get_task_type(intent, complexity)\n    full_chain = MASTER_FALLBACK_CHAINS.get(task_type, [])\n    filtered_chain = [m for m in full_chain if m in cost_filtered_models and m != selected_model]\n    \n    # Step 8-10: Execute with fallback + logging\n    return execute_with_fallback(selected_model, filtered_chain)\n\n\ndef get_allowed_tiers(complexity: str) -> list[str]:\n    \"\"\"Return allowed cost tiers for a given complexity level.\"\"\"\n    return {\n        \"SIMPLE\":  [\"$\"],                      # Budget only — no exceptions\n        \"MEDIUM\":  [\"$\", \"$$\"],                # Budget + standard\n        \"COMPLEX\": [\"$\", \"$$\", \"$$$\", \"$$$$\"], # All tiers — complex tasks deserve the best\n    }.get(complexity, [\"$\", \"$$\"])\n\n\n# Example flow for \"what's 2+2?\":\n#\n# 1. available_models = {opus, sonnet, haiku, flash, grok-2, ...}\n# 2. intent = GENERAL\n# 3. complexity = SIMPLE\n# 4. (no special cases)\n# 5. allowed_tiers = [\"$\"]  ← SIMPLE means $ only\n#    cost_filtered_models = {haiku, flash, grok-2}  ← Opus\u002FSonnet EXCLUDED\n# 6. preferences for (GENERAL, SIMPLE) = [flash, haiku, grok-2, sonnet]\n#    first match in cost_filtered = flash ✓\n# 7. fallback_chain = [haiku, grok-2]  ← Also cost-filtered\n# 8. execute with flash\n#\n# Result: Opus is NEVER considered, not even momentarily.\n```\n\n### Cost Optimization: Two Approaches\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│           COST OPTIMIZATION IMPLEMENTATION OPTIONS               │\n├─────────────────────────────────────────────────────────────────┤\n│                                                                  │\n│  APPROACH 1: Explicit filter_by_cost() (shown above)            │\n│  ─────────────────────────────────────────────────────────────  │\n│  • Calls get_allowed_tiers(complexity) explicitly               │\n│  • Filters available_models BEFORE routing table lookup         │\n│  • Most defensive — impossible to route wrong tier              │\n│  • Recommended for security-critical deployments                │\n│                                                                  │\n│  APPROACH 2: Preference ordering (implicit)                     │\n│  ─────────────────────────────────────────────────────────────  │\n│  • ROUTING_PREFERENCES lists cheapest capable models first      │\n│  • For SIMPLE tasks: [flash, haiku, grok-2, sonnet]            │\n│  • First available match wins → naturally picks cheapest        │\n│  • Simpler code, relies on correct preference ordering          │\n│                                                                  │\n│  This implementation uses BOTH for defense-in-depth:            │\n│  • Preference ordering provides first line of cost awareness    │\n│  • Explicit filter_by_cost() guarantees tier enforcement        │\n│                                                                  │\n│  For alternative implementations that rely solely on            │\n│  preference ordering, see references\u002Fmodels.md for the          │\n│  filter_by_cost() function if explicit enforcement is needed.   │\n│                                                                  │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Spawning with Different Models\n\nUse sessions_spawn for model routing:\n```\nsessions_spawn(\n  task: \"user's request\",\n  model: \"selected\u002Fmodel-id\",\n  label: \"task-type-query\"\n)\n```\n\n## Security\n\n- Never send sensitive data to untrusted models\n- API keys handled via environment\u002Fauth profiles only\n- See `references\u002Fsecurity.md` for full security guidance\n\n## Model Details\n\nSee `references\u002Fmodels.md` for detailed capabilities and pricing.\n","# A.I. Smart-Router\n\nIntelligently route requests to the optimal AI model using tiered classification with automatic fallback handling and cost optimization.\n\n## How It Works (Silent by Default)\n\nThe router operates transparently—users send messages normally and get responses from the best model for their task. No special commands needed.\n\n**Optional visibility**: Include `[show routing]` in any message to see the routing decision.\n\n## Tiered Classification System\n\nThe router uses a three-tier decision process:\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                    TIER 1: INTENT DETECTION                      │\n│  Classify the primary purpose of the request                     │\n├─────────────────────────────────────────────────────────────────┤\n│  CODE        │ ANALYSIS    │ CREATIVE   │ REALTIME  │ GENERAL   │\n│  write\u002Fdebug │ research    │ writing    │ news\u002Flive │ Q&A\u002Fchat  │\n│  refactor    │ explain     │ stories    │ X\u002FTwitter │ translate │\n│  review      │ compare     │ brainstorm │ prices    │ summarize │\n└──────┬───────┴──────┬──────┴─────┬──────┴─────┬─────┴─────┬─────┘\n       │              │            │            │           │\n       ▼              ▼            ▼            ▼           ▼\n┌─────────────────────────────────────────────────────────────────┐\n│                  TIER 2: COMPLEXITY ESTIMATION                   │\n├─────────────────────────────────────────────────────────────────┤\n│  SIMPLE (Tier $)        │ MEDIUM (Tier $$)    │ COMPLEX (Tier $$$)│\n│  • One-step task        │ • Multi-step task   │ • Deep reasoning  │\n│  • Short response OK    │ • Some nuance       │ • Extensive output│\n│  • Factual lookup       │ • Moderate context  │ • Critical task   │\n│  → Haiku\u002FFlash          │ → Sonnet\u002FGrok\u002FGPT   │ → Opus\u002FGPT-5      │\n└──────────────────────────┴─────────────────────┴───────────────────┘\n                                    │\n                                    ▼\n┌─────────────────────────────────────────────────────────────────┐\n│                TIER 3: SPECIAL CASE OVERRIDES                    │\n├─────────────────────────────────────────────────────────────────┤\n│  CONDITION                           │ OVERRIDE TO              │\n│  ─────────────────────────────────────┼─────────────────────────│\n│  Context >100K tokens                │ → Gemini Pro (1M ctx)    │\n│  Context >500K tokens                │ → Gemini Pro ONLY        │\n│  Needs real-time data                │ → Grok (regardless)      │\n│  Image\u002Fvision input                  │ → Opus or Gemini Pro     │\n│  User explicit override              │ → Requested model        │\n└──────────────────────────────────────┴──────────────────────────┘\n```\n\n## Intent Detection Patterns\n\n### CODE Intent\n- Keywords: write, code, debug, fix, refactor, implement, function, class, script, API, bug, error, compile, test, PR, commit\n- File extensions mentioned: .py, .js, .ts, .go, .rs, .java, etc.\n- Code blocks in input\n\n### ANALYSIS Intent  \n- Keywords: analyze, explain, compare, research, understand, why, how does, evaluate, assess, review, investigate, examine\n- Long-form questions\n- \"Help me understand...\"\n\n### CREATIVE Intent\n- Keywords: write (story\u002Fpoem\u002Fessay), create, brainstorm, imagine, design, draft, compose\n- Fiction\u002Fnarrative requests\n- Marketing\u002Fcopy requests\n\n### REALTIME Intent\n- Keywords: now, today, current, latest, trending, news, happening, live, price, score, weather\n- X\u002FTwitter mentions\n- Stock\u002Fcrypto tickers\n- Sports scores\n\n### GENERAL Intent (Default)\n- Simple Q&A\n- Translations\n- Summaries\n- Conversational\n\n### MIXED Intent (Multiple Intents Detected)\nWhen a request contains multiple clear intents (e.g., \"Write code to analyze this data and explain it creatively\"):\n\n1. **Identify primary intent** — What's the main deliverable?\n2. **Route to highest-capability model** — Mixed tasks need versatility\n3. **Default to COMPLEX complexity** — Multi-intent = multi-step\n\n**Examples:**\n- \"Write code AND explain how it works\" → CODE (primary) + ANALYSIS → Route to Opus\n- \"Summarize this AND what's the latest news on it\" → REALTIME takes precedence → Grok\n- \"Creative story using real current events\" → REALTIME + CREATIVE → Grok (real-time wins)\n\n## Language Handling\n\n**Non-English requests** are handled normally — all supported models have multilingual capabilities:\n\n| Model | Non-English Support |\n|-------|---------------------|\n| Opus\u002FSonnet\u002FHaiku | Excellent (100+ languages) |\n| GPT-5 | Excellent (100+ languages) |\n| Gemini Pro\u002FFlash | Excellent (100+ languages) |\n| Grok | Good (major languages) |\n\n**Intent detection still works** because:\n- Keyword patterns include common non-English equivalents\n- Code intent detected by file extensions, code blocks (language-agnostic)\n- Complexity estimated by query length (works across languages)\n\n**Edge case:** If intent unclear due to language, default to GENERAL intent with MEDIUM complexity.\n\n## Complexity Signals\n\n### Simple Complexity ($)\n- Short query (\u003C50 words)\n- Single question mark\n- \"Quick question\", \"Just tell me\", \"Briefly\"\n- Yes\u002Fno format\n- Unit conversions, definitions\n\n### Medium Complexity ($$)\n- Moderate query (50-200 words)\n- Multiple aspects to address\n- \"Explain\", \"Describe\", \"Compare\"\n- Some context provided\n\n### Complex Complexity ($$$)\n- Long query (>200 words) or complex task\n- \"Step by step\", \"Thoroughly\", \"In detail\"\n- Multi-part questions\n- Critical\u002Fimportant qualifier\n- Research, analysis, or creative work\n\n## Routing Matrix\n\n| Intent | Simple | Medium | Complex |\n|--------|--------|--------|---------|\n| **CODE** | Sonnet | Opus | Opus |\n| **ANALYSIS** | Flash | GPT-5 | Opus |\n| **CREATIVE** | Sonnet | Opus | Opus |\n| **REALTIME** | Grok | Grok | Grok-3 |\n| **GENERAL** | Flash | Sonnet | Opus |\n\n## Token Exhaustion & Automatic Model Switching\n\nWhen a model becomes unavailable mid-session (token quota exhausted, rate limit hit, API error), the router automatically switches to the next best available model and **notifies the user**.\n\n### Notification Format\n\nWhen a model switch occurs due to exhaustion, the user receives a notification:\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│  ⚠️ MODEL SWITCH NOTICE                                         │\n│                                                                  │\n│  Your request could not be completed on claude-opus-4-5         │\n│  (reason: token quota exhausted).                               │\n│                                                                  │\n│  ✅ Request completed using: anthropic\u002Fclaude-sonnet-4-5        │\n│                                                                  │\n│  The response below was generated by the fallback model.        │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Switch Reasons\n\n| Reason | Description |\n|--------|-------------|\n| `token quota exhausted` | Daily\u002Fmonthly token limit reached |\n| `rate limit exceeded` | Too many requests per minute |\n| `context window exceeded` | Input too large for model |\n| `API timeout` | Model took too long to respond |\n| `API error` | Provider returned an error |\n| `model unavailable` | Model temporarily offline |\n\n### Implementation\n\n```python\ndef execute_with_fallback(primary_model: str, fallback_chain: list[str], request: str) -> Response:\n    \"\"\"\n    Execute request with automatic fallback and user notification.\n    \"\"\"\n    attempted_models = []\n    switch_reason = None\n    \n    # Try primary model first\n    models_to_try = [primary_model] + fallback_chain\n    \n    for model in models_to_try:\n        try:\n            response = call_model(model, request)\n            \n            # If we switched models, prepend notification\n            if attempted_models:\n                notification = build_switch_notification(\n                    failed_model=attempted_models[0],\n                    reason=switch_reason,\n                    success_model=model\n                )\n                return Response(\n                    content=notification + \"\\n\\n---\\n\\n\" + response.content,\n                    model_used=model,\n                    switched=True\n                )\n            \n            return Response(content=response.content, model_used=model, switched=False)\n            \n        except TokenQuotaExhausted:\n            attempted_models.append(model)\n            switch_reason = \"token quota exhausted\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except RateLimitExceeded:\n            attempted_models.append(model)\n            switch_reason = \"rate limit exceeded\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except ContextWindowExceeded:\n            attempted_models.append(model)\n            switch_reason = \"context window exceeded\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except APITimeout:\n            attempted_models.append(model)\n            switch_reason = \"API timeout\"\n            log_fallback(model, switch_reason)\n            continue\n            \n        except APIError as e:\n            attempted_models.append(model)\n            switch_reason = f\"API error: {e.code}\"\n            log_fallback(model, switch_reason)\n            continue\n    \n    # All models exhausted\n    return build_exhaustion_error(attempted_models)\n\n\ndef build_switch_notification(failed_model: str, reason: str, success_model: str) -> str:\n    \"\"\"Build user-facing notification when model switch occurs.\"\"\"\n    return f\"\"\"⚠️ **MODEL SWITCH NOTICE**\n\nYour request could not be completed on `{failed_model}` (reason: {reason}).\n\n✅ **Request completed using:** `{success_model}`\n\nThe response below was generated by the fallback model.\"\"\"\n\n\ndef build_exhaustion_error(attempted_models: list[str]) -> Response:\n    \"\"\"Build error when all models are exhausted.\"\"\"\n    models_tried = \", \".join(attempted_models)\n    return Response(\n        content=f\"\"\"❌ **REQUEST FAILED**\n\nUnable to complete your request. All available models have been exhausted.\n\n**Models attempted:** {models_tried}\n\n**What you can do:**\n1. **Wait** — Token quotas typically reset hourly or daily\n2. **Simplify** — Try a shorter or simpler request\n3. **Check status** — Run `\u002Frouter status` to see model availability\n\nIf this persists, your human may need to check API quotas or add additional providers.\"\"\",\n        model_used=None,\n        switched=False,\n        failed=True\n    )\n```\n\n### Fallback Priority for Token Exhaustion\n\nWhen a model is exhausted, the router selects the next best model for the **same task type**:\n\n| Original Model | Fallback Priority (same capability) |\n|----------------|-------------------------------------|\n| Opus | Sonnet → GPT-5 → Grok-3 → Gemini Pro |\n| Sonnet | GPT-5 → Grok-3 → Opus → Haiku |\n| GPT-5 | Sonnet → Opus → Grok-3 → Gemini Pro |\n| Gemini Pro | Flash → GPT-5 → Opus → Sonnet |\n| Grok-2\u002F3 | (warn: no real-time fallback available) |\n\n### User Acknowledgment\n\nAfter a model switch, the agent should note in the response that:\n1. The original model was unavailable\n2. Which model actually completed the request\n3. The response quality may differ from the original model's typical output\n\nThis ensures transparency and sets appropriate expectations.\n\n### Streaming Responses with Fallback\n\nWhen using streaming responses, fallback handling requires special consideration:\n\n```python\nasync def execute_with_streaming_fallback(primary_model: str, fallback_chain: list[str], request: str):\n    \"\"\"\n    Handle streaming responses with mid-stream fallback.\n    \n    If a model fails DURING streaming (not before), the partial response is lost.\n    Strategy: Don't start streaming until first chunk received successfully.\n    \"\"\"\n    models_to_try = [primary_model] + fallback_chain\n    \n    for model in models_to_try:\n        try:\n            # Test with non-streaming ping first (optional, adds latency)\n            # await test_model_availability(model)\n            \n            # Start streaming\n            stream = await call_model_streaming(model, request)\n            first_chunk = await stream.get_first_chunk(timeout=10_000)  # 10s timeout for first chunk\n            \n            # If we got here, model is responding — continue streaming\n            yield first_chunk\n            async for chunk in stream:\n                yield chunk\n            return  # Success\n            \n        except (FirstChunkTimeout, StreamError) as e:\n            log_fallback(model, str(e))\n            continue  # Try next model\n    \n    # All models failed\n    yield build_exhaustion_error(models_to_try)\n```\n\n**Key insight:** Wait for the first chunk before committing to a model. If the first chunk times out, fall back before any partial response is shown to the user.\n\n### Retry Timing Configuration\n\n```python\nRETRY_CONFIG = {\n    \"initial_timeout_ms\": 30_000,     # 30s for first attempt\n    \"fallback_timeout_ms\": 20_000,    # 20s for fallback attempts (faster fail)\n    \"max_retries_per_model\": 1,       # Don't retry same model\n    \"backoff_multiplier\": 1.5,        # Not used (no same-model retry)\n    \"circuit_breaker_threshold\": 3,   # Failures before skipping model entirely\n    \"circuit_breaker_reset_ms\": 300_000  # 5 min before trying failed model again\n}\n```\n\n**Circuit breaker:** If a model fails 3 times in 5 minutes, skip it entirely for the next 5 minutes. This prevents repeatedly hitting a down service.\n\n## Fallback Chains\n\nWhen the preferred model fails (rate limit, API down, error), cascade to the next option:\n\n### Code Tasks\n```\nOpus → Sonnet → GPT-5 → Gemini Pro\n```\n\n### Analysis Tasks\n```\nOpus → GPT-5 → Gemini Pro → Sonnet\n```\n\n### Creative Tasks\n```\nOpus → GPT-5 → Sonnet → Gemini Pro\n```\n\n### Real-time Tasks\n```\nGrok-2 → Grok-3 → (warn: no real-time fallback)\n```\n\n### General Tasks\n```\nFlash → Haiku → Sonnet → GPT-5\n```\n\n### Long Context (Tiered by Size)\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                  LONG CONTEXT FALLBACK CHAIN                     │\n├─────────────────────────────────────────────────────────────────┤\n│  TOKEN COUNT        │ FALLBACK CHAIN                            │\n│  ───────────────────┼───────────────────────────────────────────│\n│  128K - 200K        │ Opus (200K) → Sonnet (200K) → Gemini Pro  │\n│  200K - 1M          │ Gemini Pro → Flash (1M) → ERROR_MESSAGE   │\n│  > 1M               │ ERROR_MESSAGE (no model supports this)    │\n└─────────────────────┴───────────────────────────────────────────┘\n```\n\n**Implementation:**\n\n```python\ndef handle_long_context(token_count: int, available_models: dict) -> str | ErrorMessage:\n    \"\"\"Route long-context requests with graceful degradation.\"\"\"\n    \n    # Tier 1: 128K - 200K tokens (Opus\u002FSonnet can handle)\n    if token_count \u003C= 200_000:\n        for model in [\"opus\", \"sonnet\", \"haiku\", \"gemini-pro\", \"flash\"]:\n            if model in available_models and get_context_limit(model) >= token_count:\n                return model\n    \n    # Tier 2: 200K - 1M tokens (only Gemini)\n    elif token_count \u003C= 1_000_000:\n        for model in [\"gemini-pro\", \"flash\"]:\n            if model in available_models:\n                return model\n    \n    # Tier 3: > 1M tokens (nothing available)\n    # Fall through to error\n    \n    # No suitable model found — return helpful error\n    return build_context_error(token_count, available_models)\n\n\ndef build_context_error(token_count: int, available_models: dict) -> ErrorMessage:\n    \"\"\"Build a helpful error message when no model can handle the input.\"\"\"\n    \n    # Find the largest available context window\n    max_available = max(\n        (get_context_limit(m) for m in available_models),\n        default=0\n    )\n    \n    # Determine what's missing\n    missing_models = []\n    if \"gemini-pro\" not in available_models and \"flash\" not in available_models:\n        missing_models.append(\"Gemini Pro\u002FFlash (1M context)\")\n    if token_count \u003C= 200_000 and \"opus\" not in available_models:\n        missing_models.append(\"Opus (200K context)\")\n    \n    # Format token count for readability\n    if token_count >= 1_000_000:\n        token_display = f\"{token_count \u002F 1_000_000:.1f}M\"\n    else:\n        token_display = f\"{token_count \u002F\u002F 1000}K\"\n    \n    return ErrorMessage(\n        title=\"Context Window Exceeded\",\n        message=f\"\"\"Your input is approximately **{token_display} tokens**, which exceeds the context window of all currently available models.\n\n**Required:** Gemini Pro (1M context) {\"— currently unavailable\" if \"gemini-pro\" not in available_models else \"\"}\n**Your max available:** {max_available \u002F\u002F 1000}K tokens\n\n**Options:**\n1. **Wait and retry** — Gemini may be temporarily down\n2. **Reduce input size** — Remove unnecessary content to fit within {max_available \u002F\u002F 1000}K tokens\n3. **Split into chunks** — I can process your input sequentially in smaller pieces\n\nWould you like me to help split this into manageable chunks?\"\"\",\n        \n        recoverable=True,\n        suggested_action=\"split_chunks\"\n    )\n```\n\n**Example Error Output:**\n\n```\n⚠️ Context Window Exceeded\n\nYour input is approximately **340K tokens**, which exceeds the context \nwindow of all currently available models.\n\nRequired: Gemini Pro (1M context) — currently unavailable\nYour max available: 200K tokens\n\nOptions:\n1. Wait and retry — Gemini may be temporarily down\n2. Reduce input size — Remove unnecessary content to fit within 200K tokens\n3. Split into chunks — I can process your input sequentially in smaller pieces\n\nWould you like me to help split this into manageable chunks?\n```\n\n## Dynamic Model Discovery\n\nThe router auto-detects available providers at runtime:\n\n```\n1. Check configured auth profiles\n2. Build available model list from authenticated providers\n3. Construct routing table using ONLY available models\n4. If preferred model unavailable, use best available alternative\n```\n\n**Example**: If only Anthropic and Google are configured:\n- Code tasks → Opus (Anthropic available ✓)\n- Real-time tasks → ⚠️ No Grok → Fall back to Opus + warn user\n- Long docs → Gemini Pro (Google available ✓)\n\n## Cost Optimization\n\nThe router considers cost when complexity is LOW:\n\n| Model | Cost Tier | Use When |\n|-------|-----------|----------|\n| Gemini Flash | $ | Simple tasks, high volume |\n| Claude Haiku | $ | Simple tasks, quick responses |\n| Claude Sonnet | $$ | Medium complexity |\n| Grok 2 | $$ | Real-time needs only |\n| GPT-5 | $$ | General fallback |\n| Gemini Pro | $$$ | Long context needs |\n| Claude Opus | $$$$ | Complex\u002Fcritical tasks |\n\n**Rule**: Never use Opus ($$$) for tasks that Flash ($) can handle.\n\n## User Controls\n\n### Show Routing Decision\nAdd `[show routing]` to any message:\n```\n[show routing] What's the weather in NYC?\n```\nOutput includes:\n```\n[Routed → xai\u002Fgrok-2-latest | Reason: REALTIME intent detected | Fallback: none available]\n```\n\n### Force Specific Model\nExplicit overrides:\n- \"use grok: ...\" → Forces Grok\n- \"use claude: ...\" → Forces Opus\n- \"use gemini: ...\" → Forces Gemini Pro\n- \"use flash: ...\" → Forces Gemini Flash\n- \"use gpt: ...\" → Forces GPT-5\n\n### Check Router Status\nAsk: \"router status\" or \"\u002Frouter\" to see:\n- Available providers\n- Configured models\n- Current routing table\n- Recent routing decisions\n\n## Implementation Notes\n\n### For Agent Implementation\n\nWhen processing a request:\n\n```\n1. DETECT available models (check auth profiles)\n2. CLASSIFY intent (code\u002Fanalysis\u002Fcreative\u002Frealtime\u002Fgeneral)\n3. ESTIMATE complexity (simple\u002Fmedium\u002Fcomplex)\n4. CHECK special cases (context size, vision, explicit override)\n5. FILTER by cost tier based on complexity ← BEFORE model selection\n6. SELECT model from filtered pool using routing matrix\n7. VERIFY model available, else use fallback chain (also cost-filtered)\n8. EXECUTE request with selected model\n9. IF failure, try next in fallback chain\n10. LOG routing decision (for debugging)\n```\n\n### Cost-Aware Routing Flow (Critical Order)\n\n```python\ndef route_with_fallback(request):\n    \"\"\"\n    Main routing function with CORRECT execution order.\n    Cost filtering MUST happen BEFORE routing table lookup.\n    \"\"\"\n    \n    # Step 1: Discover available models\n    available_models = discover_providers()\n    \n    # Step 2: Classify intent\n    intent = classify_intent(request)\n    \n    # Step 3: Estimate complexity\n    complexity = estimate_complexity(request)\n    \n    # Step 4: Check special-case overrides (these bypass cost filtering)\n    if user_override := get_user_model_override(request):\n        return execute_with_fallback(user_override, [])  # No cost filter for explicit override\n    \n    if token_count > 128_000:\n        return handle_long_context(token_count, available_models)  # Special handling\n    \n    if needs_realtime(request):\n        return execute_with_fallback(\"grok-2\", [\"grok-3\"])  # Realtime bypasses cost\n    \n    # ┌─────────────────────────────────────────────────────────────┐\n    # │  STEP 5: FILTER BY COST TIER — THIS MUST COME FIRST!       │\n    # │                                                             │\n    # │  Cost filtering happens BEFORE the routing table lookup,   │\n    # │  NOT after. This ensures \"what's 2+2?\" never considers     │\n    # │  Opus even momentarily.                                    │\n    # └─────────────────────────────────────────────────────────────┘\n    \n    allowed_tiers = get_allowed_tiers(complexity)\n    # SIMPLE  → [\"$\"]\n    # MEDIUM  → [\"$\", \"$$\"]\n    # COMPLEX → [\"$\", \"$$\", \"$$$\"]\n    \n    cost_filtered_models = {\n        model: meta for model, meta in available_models.items()\n        if COST_TIERS.get(model) in allowed_tiers\n    }\n    \n    # Step 6: NOW select from cost-filtered pool using routing preferences\n    preferences = ROUTING_PREFERENCES.get((intent, complexity), [])\n    \n    for model in preferences:\n        if model in cost_filtered_models:  # Only consider cost-appropriate models\n            selected_model = model\n            break\n    else:\n        # No preferred model in cost-filtered pool — use cheapest available\n        selected_model = select_cheapest(cost_filtered_models)\n    \n    # Step 7: Build cost-filtered fallback chain\n    task_type = get_task_type(intent, complexity)\n    full_chain = MASTER_FALLBACK_CHAINS.get(task_type, [])\n    filtered_chain = [m for m in full_chain if m in cost_filtered_models and m != selected_model]\n    \n    # Step 8-10: Execute with fallback + logging\n    return execute_with_fallback(selected_model, filtered_chain)\n\n\ndef get_allowed_tiers(complexity: str) -> list[str]:\n    \"\"\"Return allowed cost tiers for a given complexity level.\"\"\"\n    return {\n        \"SIMPLE\":  [\"$\"],                      # Budget only — no exceptions\n        \"MEDIUM\":  [\"$\", \"$$\"],                # Budget + standard\n        \"COMPLEX\": [\"$\", \"$$\", \"$$$\", \"$$$$\"], # All tiers — complex tasks deserve the best\n    }.get(complexity, [\"$\", \"$$\"])\n\n\n# Example flow for \"what's 2+2?\":\n#\n# 1. available_models = {opus, sonnet, haiku, flash, grok-2, ...}\n# 2. intent = GENERAL\n# 3. complexity = SIMPLE\n# 4. (no special cases)\n# 5. allowed_tiers = [\"$\"]  ← SIMPLE means $ only\n#    cost_filtered_models = {haiku, flash, grok-2}  ← Opus\u002FSonnet EXCLUDED\n# 6. preferences for (GENERAL, SIMPLE) = [flash, haiku, grok-2, sonnet]\n#    first match in cost_filtered = flash ✓\n# 7. fallback_chain = [haiku, grok-2]  ← Also cost-filtered\n# 8. execute with flash\n#\n# Result: Opus is NEVER considered, not even momentarily.\n```\n\n### Cost Optimization: Two Approaches\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│           COST OPTIMIZATION IMPLEMENTATION OPTIONS               │\n├─────────────────────────────────────────────────────────────────┤\n│                                                                  │\n│  APPROACH 1: Explicit filter_by_cost() (shown above)            │\n│  ─────────────────────────────────────────────────────────────  │\n│  • Calls get_allowed_tiers(complexity) explicitly               │\n│  • Filters available_models BEFORE routing table lookup         │\n│  • Most defensive — impossible to route wrong tier              │\n│  • Recommended for security-critical deployments                │\n│                                                                  │\n│  APPROACH 2: Preference ordering (implicit)                     │\n│  ─────────────────────────────────────────────────────────────  │\n│  • ROUTING_PREFERENCES lists cheapest capable models first      │\n│  • For SIMPLE tasks: [flash, haiku, grok-2, sonnet]            │\n│  • First available match wins → naturally picks cheapest        │\n│  • Simpler code, relies on correct preference ordering          │\n│                                                                  │\n│  This implementation uses BOTH for defense-in-depth:            │\n│  • Preference ordering provides first line of cost awareness    │\n│  • Explicit filter_by_cost() guarantees tier enforcement        │\n│                                                                  │\n│  For alternative implementations that rely solely on            │\n│  preference ordering, see references\u002Fmodels.md for the          │\n│  filter_by_cost() function if explicit enforcement is needed.   │\n│                                                                  │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Spawning with Different Models\n\nUse sessions_spawn for model routing:\n```\nsessions_spawn(\n  task: \"user's request\",\n  model: \"selected\u002Fmodel-id\",\n  label: \"task-type-query\"\n)\n```\n\n## Security\n\n- Never send sensitive data to untrusted models\n- API keys handled via environment\u002Fauth profiles only\n- See `references\u002Fsecurity.md` for full security guidance\n\n## Model Details\n\nSee `references\u002Fmodels.md` for detailed capabilities and pricing.\n",{"name":5,"author":24,"license":15,"version":25,"metadata":26,"description":51},"c0nSpIc0uS7uRk3r","2.1.0",{"features":27,"openclaw":35,"benchmarks":45},[28,29,30,31,32,33,34],"Semantic domain detection","Expertise-weighted scoring (0-100)","Risk-based mandatory routing","Context overflow protection (>150K → Gemini)","Security credential redaction","Circuit breaker with persistent state","HITL gate for low-confidence routing",{"requires":36,"optional_env":41},{"env":37,"bins":39},[38],"ANTHROPIC_API_KEY",[40],"python3",[42,43,44],"GOOGLE_API_KEY","OPENAI_API_KEY","XAI_API_KEY",{"models":46,"source":50},[47,48,49],"Claude Opus 4.5: SWE-bench 80.9%","GPT-5.2: AIME 100%, Control Flow 22 errors\u002FMLOC","Gemini 3 Pro: Concurrency 69 issues\u002FMLOC","Feb 2026 MLOC Analysis","Expertise-aware model router with semantic domain scoring, context-overflow protection, and security redaction. Automatically selects the optimal AI model using weighted expertise scoring (Feb 2026 benchmarks). Supports Claude, GPT, Gemini, Grok with automatic fallback chains, HITL gates, and cost optimization.\n","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fs\u002Fsmart-router",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill smart-router",{"tool":67,"command":68},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill smart-router",{"tool":70,"command":71},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill smart-router","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fs\u002Fsmart-router\u002FSKILL.md",true,[],[76,83,90,97,104,111],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]