Skill: theshadowrose/task-complexity-router (version 1.0.0)

--- name: "AI Task Router — Auto-Route Prompts by Complexity (Local/Cloud)" description: "Regex-based routing sends simple tasks to local AI, medium to mid-tier, complex to premium — saving 60%+ on API costs." author: "@TheShadowRose" version: "1.0.0" tags: ["task-routing", "cost-optimization", "complexity-detection", "ollama", "auto-routing", "smart-dispatch"] license: "MIT" --- # AI Task Router — Auto-Route Prompts by Complexity (Local/Cloud) Regex-based routing sends simple tasks to local AI, medium to mid-tier, complex to premium — saving 60%+ on API costs. --- Automatically routes prompts to the cheapest model that can handle them. ## How It Works Pattern matching classifies tasks into tiers: | Task Type | Example | Routed To | Cost | |-----------|---------|-----------|------| | Simple | "hi", "thanks", "what time is it" | Local (Ollama) | $0 | | Moderate | "write an email", "analyze this" | Mid-tier (Sonnet) | $ | | Complex | "debug this codebase", "write a chapter" | Premium (Opus) | $$$ | ## Usage ```javascript const { TaskRouter } = require('./src/task-router'); const router = new TaskRouter({ defaultModel: 'local', escalationModel: 'sonnet', heavyModel: 'opus' }); const result = router.route('analyze the sales data from Q3'); // { model: 'sonnet', reason: 'Analysis task', confidence: 0.8 } ``` ## Custom Rules Add your own routing patterns: ```javascript router.addRule({ name: 'code-review', pattern: /\b(review|refactor|debug|optimize)\b.*\b(code|function|class)\b/i, model: 'opus', reason: 'Code review needs deep reasoning' }); ``` ## Cost Savings Typical usage pattern routes ~70% of tasks to free local models, ~25% to mid-tier, and ~5% to premium. With Opus at $15/M tokens vs Ollama at $0, this saves 60-80% on API costs. --- ## ⚠️ Disclaimer This software is provided "AS IS", without warranty of any kind, express or implied. **USE AT YOUR OWN RISK.** - The author(s) are NOT liable for any damages, losses, or consequences arising from the use or misuse of this software — including but not limited to financial loss, data loss, security breaches, business interruption, or any indirect/consequential damages. - This software does NOT constitute financial, legal, trading, or professional advice. - Users are solely responsible for evaluating whether this software is suitable for their use case, environment, and risk tolerance. - No guarantee is made regarding accuracy, reliability, completeness, or fitness for any particular purpose. - The author(s) are not responsible for how third parties use, modify, or distribute this software after purchase. By downloading, installing, or using this software, you acknowledge that you have read this disclaimer and agree to use the software entirely at your own risk. **DATA DISCLAIMER:** This software processes and stores data locally on your system. The author(s) are not responsible for data loss, corruption, or unauthorized access resulting from software bugs, system failures, or user error. Always maintain independent backups of important data. This software does not transmit data externally unless explicitly configured by the user. --- ## Support & Links | | | |---|---| | 🐛 **Bug Reports** | [REDACTED_SECRET] | | ☕ **Ko-fi** | [ko-fi.com/theshadowrose](https://ko-fi.com/theshadowrose) | | 🛒 **Gumroad** | [shadowyrose.gumroad.com](https://shadowyrose.gumroad.com) | | 🐦 **Twitter** | [@TheShadowyRose](https://twitter.com/TheShadowyRose) | | 🐙 **GitHub** | [github.com/TheShadowRose](https://github.com/TheShadowRose) | | 🧠 **PromptBase** | [promptbase.com/profile/shadowrose](https://promptbase.com/profile/shadowrose) | *Built with [OpenClaw](https://github.com/openclaw/openclaw) — thank you for making this possible.* --- 🛠️ **Need something custom?** Custom OpenClaw agents & skills starting at $500. If you can describe it, I can build it. → [Hire me on Fiverr](https://www.fiverr.com/s/jjmlZ0v)

path: LICENSE.md
content: MIT License

Copyright (c) 2026 Shadow Rose

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


path: README.md
content: # AI Task Router

Automatically routes prompts to the cheapest model that can handle them.

## How It Works

Pattern matching classifies tasks into tiers:

| Task Type | Example | Routed To | Cost |
|-----------|---------|-----------|------|
| Simple | "hi", "thanks", "what time is it" | Local (Ollama) | $0 |
| Moderate | "write an email", "analyze this" | Mid-tier (Sonnet) | $ |
| Complex | "debug this codebase", "write a chapter" | Premium (Opus) | $$$ |

## Usage

```javascript
const { TaskRouter } = require('./src/task-router');

const router = new TaskRouter({
  defaultModel: 'local',
  escalationModel: 'sonnet',
  heavyModel: 'opus'
});

const result = router.route('analyze the sales data from Q3');
// { model: 'sonnet', reason: 'Analysis task', confidence: 0.8 }
```

## Custom Rules

Add your own routing patterns:

```javascript
router.addRule({
  name: 'code-review',
  pattern: /\b(review|refactor|debug|optimize)\b.*\b(code|function|class)\b/i,
  model: 'opus',
  reason: 'Code review needs deep reasoning'
});
```

## Cost Savings

Typical usage pattern routes ~70% of tasks to free local models, ~25% to mid-tier, and ~5% to premium. With Opus at $15/M tokens vs Ollama at $0, this saves 60-80% on API costs.
---

## ⚠️ Disclaimer

This software is provided "AS IS", without warranty of any kind, express or implied.

**USE AT YOUR OWN RISK.**

- The author(s) are NOT liable for any damages, losses, or consequences arising from 
  the use or misuse of this software — including but not limited to financial loss, 
  data loss, security breaches, business interruption, or any indirect/consequential damages.
- This software does NOT constitute financial, legal, trading, or professional advice.
- Users are solely responsible for evaluating whether this software is suitable for 
  their use case, environment, and risk tolerance.
- No guarantee is made regarding accuracy, reliability, completeness, or fitness 
  for any particular purpose.
- The author(s) are not responsible for how third parties use, modify, or distribute 
  this software after purchase.

By downloading, installing, or using this software, you acknowledge that you have read 
this disclaimer and agree to use the software entirely at your own risk.


**DATA DISCLAIMER:** This software processes and stores data locally on your system. 
The author(s) are not responsible for data loss, corruption, or unauthorized access 
resulting from software bugs, system failures, or user error. Always maintain 
independent backups of important data. This software does not transmit data externally 
unless explicitly configured by the user.

---

## Support & Links

| | |
|---|---|
| 🐛 **Bug Reports** | [REDACTED_SECRET] |
| ☕ **Ko-fi** | [ko-fi.com/theshadowrose](https://ko-fi.com/theshadowrose) |
| 🛒 **Gumroad** | [shadowyrose.gumroad.com](https://shadowyrose.gumroad.com) |
| 🐦 **Twitter** | [@TheShadowyRose](https://twitter.com/TheShadowyRose) |
| 🐙 **GitHub** | [github.com/TheShadowRose](https://github.com/TheShadowRose) |
| 🧠 **PromptBase** | [promptbase.com/profile/shadowrose](https://promptbase.com/profile/shadowrose) |

*Built with [OpenClaw](https://github.com/openclaw/openclaw) — thank you for making this possible.*

---

🛠️ **Need something custom?** Custom OpenClaw agents & skills starting at $500. If you can describe it, I can build it. → [Hire me on Fiverr](https://www.fiverr.com/s/jjmlZ0v)


path: src/task-router.js
content: /**
 * Task Router — Public version
 * Detects task complexity and routes to appropriate model
 * Basic scaffolding — no self-learning (that's private)
 */

class TaskRouter {
  constructor(config = {}) {
    this.config = {
      defaultModel: config.defaultModel || 'local',
      escalationModel: config.escalationModel || 'sonnet',
      heavyModel: config.heavyModel || 'opus',
      ...config
    };

    // Complexity patterns — users can add their own
    this.rules = [
      // Simple — stays local
      { 
        name: 'greeting',
        pattern: /^(hi|hey|hello|mhmm|yeah|ok|thanks|good|nice)\.?$/i,
        model: 'local',
        reason: 'Simple acknowledgment'
      },
      { 
        name: 'short_question',
        pattern: /^(what|where|when|who|how)\b.{0,30}\?$/i,
        model: 'local',
        reason: 'Short question'
      },
      {
        name: 'status_check',
        pattern: /\b(status|check|list|show|count|time)\b/i,
        model: 'local',
        reason: 'Status or listing request'
      },

      // Moderate — escalate to mid-tier
      {
        name: 'analysis',
        pattern: /\b(analyze|compare|research|investigate|evaluate|review)\b/i,
        model: 'sonnet',
        reason: 'Analysis task'
      },
      {
        name: 'creation',
        pattern: /\b(create|build|generate|design|write|draft)\b/i,
        model: 'sonnet',
        reason: 'Creation task'
      },
      {
        name: 'explanation',
        pattern: /\b(explain|describe|summarize|break down|walk me through)\b/i,
        model: 'sonnet',
        reason: 'Explanation request'
      },

      // Complex — escalate to heavy model
      {
        name: 'architecture',
        pattern: /\b(architect|system design|framework|infrastructure|refactor)\b/i,
        model: 'opus',
        reason: 'Architecture task'
      },
      {
        name: 'long_writing',
        pattern: /\b(write.{0,20}(book|chapter|article|guide|report))\b/i,
        model: 'opus',
        reason: 'Long-form writing'
      },
      {
        name: 'financial',
        pattern: /\b(trade|trading|invest|financial|budget|revenue|profit)\b/i,
        model: 'opus',
        reason: 'Financial decision'
      },
      {
        name: 'security',
        pattern: /\b(security|vulnerability|encrypt|auth|permission|delete|destroy)\b/i,
        model: 'opus',
        reason: 'Security-sensitive task'
      }
    ];

    // User-defined custom rules (loaded from config)
    if (config.customRules) {
      for (const rule of config.customRules) {
        this.addRule(rule.name, new RegExp(rule.pattern, rule.flags || 'i'), rule.model, rule.reason);
      }
    }
  }

  /**
   * Route a message to the appropriate model
   * @param {string} message - User message
   * @param {object} context - Optional context (e.g., current conversation topic)
   * @returns {object} Routing decision
   */
  route(message, context = {}) {
    const matched = [];

    // Check all rules
    for (const rule of this.rules) {
      if (rule.pattern.test(message)) {
        matched.push(rule);
      }
    }

    // No rules matched — use default
    if (matched.length === 0) {
      // Fallback: short messages go local, long messages escalate
      if (message.split(/\s+/).length <= 5) {
        return {
          model: this.config.defaultModel,
          reason: 'Short message, default model',
          confidence: 0.5,
          matched: []
        };
      } else {
        return {
          model: this.config.escalationModel,
          reason: 'Longer message, escalated to mid-tier',
          confidence: 0.4,
          matched: []
        };
      }
    }

    // Multiple rules matched — use highest tier
    const modelPriority = { 'opus': 3, 'sonnet': 2, 'local': 1 };
    const bestMatch = matched.reduce((best, current) => {
      const currentPriority = modelPriority[current.model] || 0;
      const bestPriority = modelPriority[best.model] || 0;
      return currentPriority > bestPriority ? current : best;
    });

    // Context overrides
    if (context.forceModel) {
      return {
        model: context.forceModel,
        reason: `User override: ${context.forceModel}`,
        confidence: 1.0,
        matched: matched.map(m => m.name)
      };
    }

    return {
      model: bestMatch.model,
      reason: bestMatch.reason,
      confidence: Math.min(0.9, 0.5 + (matched.length * 0.1)),
      matched: matched.map(m => m.name)
    };
  }

  /**
   * Add a custom routing rule
   */
  addRule(name, pattern, model, reason) {
    this.rules.push({ name, pattern, model, reason });
  }

  /**
   * Remove a routing rule by name
   */
  removeRule(name) {
    this.rules = this.rules.filter(r => r.name !== name);
  }

  /**
   * Get all current rules (for UI display)
   */
  getRules() {
    return this.rules.map(r => ({
      name: r.name,
      pattern: r.pattern.source,
      model: r.model,
      reason: r.reason
    }));
  }

  /**
   * Export rules to JSON (for saving config)
   */
  exportRules() {
    return this.rules.map(r => ({
      name: r.name,
      pattern: r.pattern.source,
      flags: r.pattern.flags,
      model: r.model,
      reason: r.reason
    }));
  }
}

module.exports = { TaskRouter };


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)