diff --git a/commands/delegate/README.md b/commands/delegate/README.md new file mode 100644 index 000000000..06e7da3fb --- /dev/null +++ b/commands/delegate/README.md @@ -0,0 +1,415 @@ +# AI Task Delegation System + +**Save 60-80% of Claude Code's context by delegating heavy tasks to specialized AI tools.** + +## Overview + +The Delegation System is a smart task router that allows Claude Code (Kai) to delegate context-heavy operations to external AI CLI tools like auggie, gemini, and aider. This dramatically reduces token usage while maintaining high-quality outputs. + +## Quick Start + +1. **Install tools** (optional - use what you have): + ```bash + npm install -g @augmentcode/cli # auggie + pip install aider-chat # aider + # gemini - see PAI reference docs + ``` + +2. **That's it!** The system works automatically when Kai detects large tasks. + +## How It Works + +**User Request:** +``` +"Analyze the ~/dev/myproject codebase" +``` + +**Kai's Response:** +``` +šŸ“Š Delegating to auggie (847 files detected)... +Estimated token savings: ~15,000 + +āœ… Analysis complete! +[Synthesized results] +``` + +## Architecture + +### Files + +1. **`delegate.md`** - Comprehensive documentation and configuration + - User guide and FAQ + - Tool configuration (YAML-style markdown) + - Status checker (run with `bun delegate.md`) + - Technical documentation + +2. **`delegate-router.md`** - Smart routing engine + - Task analysis (type, scope, complexity, token estimate) + - Decision logic (which tool to use) + - Execution engine (runs delegated tasks) + - Error handling (asks user on failure) + +### Delegation Flow + +``` +User Request + ↓ +Kai analyzes task (files, tokens, type) + ↓ +Should delegate? (>10 files OR >20K tokens) + ↓ +delegate-router.md selects optimal tool + ↓ +Tool executes task + ↓ +Kai synthesizes results for user +``` + +## Configuration + +Edit `delegate.md` or tell Kai: + +``` +"Don't use auggie anymore" +"Increase auggie timeout to 5 minutes" +"I installed a new tool called cursor-ai" +``` + +### Available Tools + +| Tool | Priority | Best For | Timeout | +|------|----------|----------|---------| +| **auggie** | 1 | Codebase analysis (>10 files) | 2 min | +| **gemini** | 2 | Fast text generation, summarization | 1 min | +| **aider** | 3 | Direct file editing, refactoring | 3 min | + +### Delegation Triggers + +**Kai delegates when:** +- Analyzing >10 files +- Processing >20,000 tokens +- Codebase-wide operations +- Large document summaries + +**Kai handles directly when:** +- Small tasks (<5K tokens) +- Interactive conversations +- Single file operations +- User wants Kai's perspective + +## Token Savings + +**Real-world examples:** + +| Scenario | Without Delegation | With Delegation | Savings | +|----------|-------------------|-----------------|---------| +| Codebase analysis (850 files) | ~40,000 tokens | ~7,000 tokens | **82%** | +| Large document summary (100KB) | ~25,000 tokens | ~5,000 tokens | **80%** | +| Multi-file refactoring (15 files) | ~30,000 tokens | ~3,000 tokens | **90%** | + +## Tool Capabilities + +### Auggie (Priority 1) + +**Best for:** +- Large codebases (>10 files) +- Understanding project architecture +- Finding patterns across files + +**How it works:** +- Indexes entire codebase with vector embeddings +- Semantic search across code +- Understands code relationships + +**Example tasks:** +- "Analyze the authentication system" +- "Find all API endpoints" +- "Explain the database schema" + +### Gemini (Priority 2) + +**Best for:** +- Fast text generation +- Document summarization (>5K tokens) +- Code generation from scratch +- Web research + +**How it works:** +- Large context window (1M+ tokens) +- Extremely fast inference +- Web search capability + +**Example tasks:** +- "Summarize this 50-page document" +- "Generate boilerplate for X" +- "Research current best practices" + +### Aider (Priority 3) + +**Best for:** +- Direct file editing +- Multi-file refactoring (1-20 files) +- Implementation tasks + +**How it works:** +- Reads files directly from disk +- Makes precise edits +- Creates git commits + +**Example tasks:** +- "Add docstrings to all functions" +- "Refactor class X to use pattern Y" +- "Update all imports to new path" + +## Usage Examples + +### Check Tool Status + +```bash +cd ~/dev/pai/commands/delegate +bun delegate.md +``` + +### Test Delegation Decision (Dry Run) + +```bash +bun delegate-router.md \ + --task "Analyze this TypeScript codebase" \ + --path ~/dev/myproject \ + --dry-run +``` + +### Force Specific Tool + +```bash +bun delegate-router.md \ + --task "Summarize this project" \ + --path ~/dev/myproject \ + --tool gemini +``` + +### JSON Output + +```bash +bun delegate-router.md \ + --task "Review security practices" \ + --path ~/dev/myproject \ + --json +``` + +## Configuration Format + +The system uses **YAML-style markdown** (PAI pattern) for configuration: + +```yaml +### auggie +enabled: true +command: auggie +priority: 1 +timeout: 120000 # 2 minutes + +bestFor: + - codebase-analysis (>10 files) + - architecture-review + +strengths: + - Codebase-aware indexing + - Full project context +``` + +## Natural Language Configuration + +Configure by talking to Kai: + +**Disable a tool:** +- "Don't use auggie anymore" + +**Adjust timeouts:** +- "Increase auggie timeout to 5 minutes" + +**Change priorities:** +- "Make gemini the first choice for analysis" + +**Add new tool:** +- "I installed a new tool called cursor-ai" + +Kai will update `delegate.md` and confirm changes. + +## Error Handling + +**When delegation fails**, Kai will ask: + +``` +Delegation to auggie failed: Connection timeout + +Would you like me to: + (a) Try another tool (gemini) + (b) Handle it directly + (c) Skip this task +``` + +**No auto-fallback** - you're always in control. + +## Extending the System + +To add a new AI tool: + +1. **Install the tool** and verify it works +2. **Add config section** to `delegate.md`: + ```yaml + ### my-tool + enabled: true + command: my-tool + priority: 4 + timeout: 60000 + + bestFor: + - custom-analysis + + strengths: + - What it does well + + usage: | + my-tool --flag "task" + ``` +3. **Tell Kai**: "I added my-tool, use it for X tasks" +4. **Test it**: Ask Kai to delegate a task to your new tool + +## Integration with PAI + +The delegation system follows PAI patterns: + +- āœ… **Markdown-first** - Config is readable markdown, not JSON +- āœ… **Natural language** - Configure by talking to Kai +- āœ… **Zero-setup** - Works if tools are installed +- āœ… **Consistent patterns** - Follows PAI conventions +- āœ… **Extensible** - Easy to add new tools + +## Troubleshooting + +### Tools not found + +```bash +cd ~/dev/pai/commands/delegate +bun delegate.md +``` + +This checks which tools are installed and where. + +### Delegation not triggering + +Check thresholds: +- Is your task >10 files? +- Is your task >20K tokens? + +Force delegation: +``` +"Use auggie to analyze this single file" +``` + +### Tool timeouts + +Increase timeout in `delegate.md` config: +```yaml +timeout: 300000 # 5 minutes instead of 2 +``` + +Or tell Kai: +``` +"Increase auggie timeout to 5 minutes" +``` + +### Wrong tool selected + +Force specific tool: +``` +"Use gemini instead of auggie for this" +``` + +Or adjust priorities in config. + +## Performance Tips + +1. **Use auggie for codebases** - Optimized for project analysis +2. **Use gemini for speed** - Fastest for text generation +3. **Use aider for editing** - Direct file manipulation +4. **Adjust timeouts** - Complex tasks need more time +5. **Enable only needed tools** - Reduces decision overhead + +## Security Considerations + +- Tools run with your user permissions +- Tools can read/write files in delegated paths +- Review tool output before accepting changes +- Aider can modify files directly (use git!) +- Gemini can make web requests + +## FAQ + +**Q: How does Kai know when to delegate?** + +A: Kai analyzes your request. If it involves >10 files or >20K tokens, delegation triggers automatically. + +**Q: Can I force a specific tool?** + +A: Yes! Just say "Use gemini to analyze this" and Kai will use that tool specifically. + +**Q: What if delegation fails?** + +A: Kai will ask you what to do - try another tool, have Kai handle it directly, or skip the task. + +**Q: Do I need all three tools?** + +A: No! Install what you want. Kai uses what's available and falls back gracefully. + +**Q: How do I disable delegation?** + +A: Change `enabled: true` to `enabled: false` in `delegate.md`, or tell Kai "Disable delegation system". + +**Q: Can I add my own tools?** + +A: Absolutely! Add a tool section to the config (copy the auggie format) and tell Kai about it. + +**Q: Will this work on my system?** + +A: If you have bun installed and any of the three tools (auggie, gemini, aider), yes! The system gracefully handles missing tools. + +## Related Links + +- **Auggie CLI**: https://docs.augmentcode.com +- **Gemini CLI**: https://github.com/gemini-cli +- **Aider**: https://aider.chat +- **PAI Documentation**: See PAI README + +## Version History + +### 1.0.0 (2025-10-11) - Initial Release + +Features: +- āœ… Three tools: auggie, gemini, aider +- āœ… Smart routing with priorities +- āœ… Natural language configuration +- āœ… Markdown-based config (PAI pattern) +- āœ… Ask-user-on-failure behavior +- āœ… Token usage logging +- āœ… Dry-run and JSON output modes +- āœ… Zero-setup operation + +## Contributing + +This is part of the Personal AI (PAI) ecosystem. Contributions welcome! + +1. Fork the PAI repo +2. Add your feature +3. Test thoroughly +4. Submit PR with clear description + +## License + +MIT License - See PAI repository for details + +--- + +**Built with ā¤ļø for the PAI ecosystem** + +*Saving tokens, one delegation at a time.* diff --git a/commands/delegate/delegate-router.md b/commands/delegate/delegate-router.md new file mode 100755 index 000000000..21c8dcd53 --- /dev/null +++ b/commands/delegate/delegate-router.md @@ -0,0 +1,520 @@ +#!/usr/bin/env bun +/** + * Delegation Router - Smart task routing to optimal AI tool + * Analyzes task requirements and routes to best available tool + * + * Usage: bun delegate-router.md --task "description" [options] + * echo "task description" | bun delegate-router.md + * + * Options: + * --task Task description + * --path File/directory path + * --pattern File pattern (e.g., "**\/*.ts") + * --tool Force specific tool (auggie|gemini|aider) + * --dry-run Show decision without executing + * --json Output JSON format + */ + +import { $ } from "bun"; +import { existsSync, statSync } from "fs"; +import { glob } from "glob"; + +interface TaskAnalysis { + type: + | "analyze" + | "summarize" + | "generate" + | "refactor" + | "research" + | "unknown"; + scope: "file" | "directory" | "codebase" | "document" | "web"; + inputSize: { + fileCount?: number; + estimatedTokens: number; + complexity: "low" | "medium" | "high"; + }; + requirements: string[]; +} + +interface DelegationDecision { + shouldDelegate: boolean; + tool: "auggie" | "gemini" | "aider" | "none"; + reason: string; + estimatedTokenSavings: number; + command: string; +} + +interface DelegationResult { + success: boolean; + tool: string; + output: string; + tokensSaved: number; + executionTime: number; + error?: string; +} + +interface DelegationOptions { + task: string; + path?: string; + pattern?: string; + tool?: string; + dryRun: boolean; + json: boolean; +} + +interface DelegationLogEntry { + tool: string; + task: string; + tokensSaved: number; + executionTime: number; + timestamp: string; +} + +interface DelegationLog { + delegations: DelegationLogEntry[]; +} + +async function analyzeTask( + taskDescription: string, + options: DelegationOptions +): Promise { + // Determine task type from keywords + const taskLower = taskDescription.toLowerCase(); + let type: TaskAnalysis["type"] = "unknown"; + + if ( + taskLower.includes("analyze") || + taskLower.includes("review") || + taskLower.includes("audit") + ) { + type = "analyze"; + } else if ( + taskLower.includes("summarize") || + taskLower.includes("summary") || + taskLower.includes("tldr") + ) { + type = "summarize"; + } else if ( + taskLower.includes("generate") || + taskLower.includes("create") || + taskLower.includes("write") + ) { + type = "generate"; + } else if ( + taskLower.includes("refactor") || + taskLower.includes("rewrite") || + taskLower.includes("migrate") + ) { + type = "refactor"; + } else if ( + taskLower.includes("research") || + taskLower.includes("find") || + taskLower.includes("search") + ) { + type = "research"; + } + + // Determine scope and input size + let scope: TaskAnalysis["scope"] = "document"; + let fileCount = 0; + let estimatedTokens = 1000; + + if (options.path && existsSync(options.path)) { + const stats = statSync(options.path); + + if (stats.isDirectory()) { + scope = "directory"; + // Count files matching pattern + const pattern = options.pattern || "**/*"; + const files = await glob(pattern, { cwd: options.path }); + fileCount = files.length; + estimatedTokens = fileCount * 500; // Rough estimate + + if (fileCount > 20) { + scope = "codebase"; + estimatedTokens = fileCount * 750; + } + } else { + scope = "file"; + fileCount = 1; + const size = stats.size; + estimatedTokens = Math.floor(size / 4); // ~4 bytes per token + } + } + + // Determine complexity + let complexity: TaskAnalysis["inputSize"]["complexity"] = "low"; + if (fileCount > 10 || estimatedTokens > 10000) complexity = "medium"; + if (fileCount > 30 || estimatedTokens > 30000) complexity = "high"; + + // Extract requirements + const requirements: string[] = []; + if (taskLower.includes("security")) requirements.push("security-aware"); + if (taskLower.includes("test")) requirements.push("test-generation"); + if (taskLower.includes("performance")) requirements.push("performance"); + if (scope === "codebase") requirements.push("codebase-context"); + + return { + type, + scope, + inputSize: { + fileCount, + estimatedTokens, + complexity, + }, + requirements, + }; +} + +async function makeDecision( + analysis: TaskAnalysis, + forcedTool?: string +): Promise { + // If tool is forced, validate and use it + if (forcedTool) { + const validTools = ["auggie", "gemini", "aider"] as const; + const tool = validTools.includes(forcedTool as any) + ? (forcedTool as "auggie" | "gemini" | "aider") + : "gemini"; // Default fallback if invalid tool specified + + return { + shouldDelegate: true, + tool, + reason: `User requested ${tool}`, + estimatedTokenSavings: analysis.inputSize.estimatedTokens * 0.7, + command: "", // Will be filled by executor + }; + } + + // Decision logic based on task analysis + const { type, scope, inputSize, requirements } = analysis; + + // Don't delegate small, simple tasks + if ( + inputSize.complexity === "low" && + inputSize.estimatedTokens < 5000 && + !requirements.includes("codebase-context") + ) { + return { + shouldDelegate: false, + tool: "none", + reason: "Task is small enough to handle directly", + estimatedTokenSavings: 0, + command: "", + }; + } + + // Codebase analysis → auggie (best for codebase context) + if ( + (type === "analyze" && scope === "codebase") || + requirements.includes("codebase-context") + ) { + return { + shouldDelegate: true, + tool: "auggie", + reason: "Codebase analysis benefits from auggie's indexing", + estimatedTokenSavings: inputSize.estimatedTokens * 0.8, + command: "", // Will be filled + }; + } + + // Large summarization → gemini (fast, large context) + if (type === "summarize" && inputSize.estimatedTokens > 10000) { + return { + shouldDelegate: true, + tool: "gemini", + reason: "Large summarization suited for gemini's speed", + estimatedTokenSavings: inputSize.estimatedTokens * 0.75, + command: "", + }; + } + + // Code generation → gemini (fast generation) + if (type === "generate") { + return { + shouldDelegate: true, + tool: "gemini", + reason: "Code generation benefits from gemini's speed", + estimatedTokenSavings: inputSize.estimatedTokens * 0.6, + command: "", + }; + } + + // Refactoring → aider (if available) or auggie + if (type === "refactor") { + // Check if aider is available + const aiderCheck = await $`which aider`.quiet().nothrow(); + const hasAider = aiderCheck.exitCode === 0; + + return { + shouldDelegate: true, + tool: hasAider ? "aider" : "auggie", + reason: hasAider + ? "Refactoring best handled by aider's direct editing" + : "Refactoring via auggie (aider not available)", + estimatedTokenSavings: inputSize.estimatedTokens * 0.7, + command: "", + }; + } + + // Research → gemini (web search capability) + if (type === "research") { + return { + shouldDelegate: true, + tool: "gemini", + reason: "Research benefits from gemini's web search", + estimatedTokenSavings: inputSize.estimatedTokens * 0.5, + command: "", + }; + } + + // Default: delegate medium/high complexity to gemini + if (inputSize.complexity !== "low") { + return { + shouldDelegate: true, + tool: "gemini", + reason: `${inputSize.complexity} complexity task, delegating for efficiency`, + estimatedTokenSavings: inputSize.estimatedTokens * 0.6, + command: "", + }; + } + + // Fallback: don't delegate + return { + shouldDelegate: false, + tool: "none", + reason: "Task suitable for direct handling", + estimatedTokenSavings: 0, + command: "", + }; +} + +async function executeDelegation( + decision: DelegationDecision, + task: string, + options: DelegationOptions +): Promise { + const startTime = Date.now(); + + try { + let output: string; + + switch (decision.tool) { + case "auggie": + output = await executeAuggie(task, options); + break; + case "gemini": + output = await executeGemini(task, options); + break; + case "aider": + output = await executeAider(task, options); + break; + default: + throw new Error(`Unknown tool: ${decision.tool}`); + } + + const executionTime = Date.now() - startTime; + + // Log delegation + await logDelegation({ + tool: decision.tool, + task, + tokensSaved: decision.estimatedTokenSavings, + executionTime, + timestamp: new Date().toISOString(), + }); + + return { + success: true, + tool: decision.tool, + output, + tokensSaved: decision.estimatedTokenSavings, + executionTime, + }; + } catch (error) { + // IMPORTANT: Don't auto-fallback to Kai - ask user what to do + // This returns a failure result which Kai will handle by asking the user + const errorMessage = error instanceof Error ? error.message : String(error); + + return { + success: false, + tool: decision.tool, + output: "", + tokensSaved: 0, + executionTime: Date.now() - startTime, + error: errorMessage, + }; + } +} + +async function executeAuggie(task: string, options: DelegationOptions): Promise { + const args = ["-p", "-q", task]; + + if (options.path) { + args.push(options.path); + } + + const result = await $`auggie ${args}`.quiet(); + return result.stdout.toString(); +} + +async function executeGemini(task: string, options: DelegationOptions): Promise { + const args = [task]; + + // Add file references if path provided + if (options.path && existsSync(options.path)) { + args.unshift(`@${options.path}`); + } + + const result = await $`gemini ${args}`.quiet(); + return result.stdout.toString(); +} + +async function executeAider(task: string, options: DelegationOptions): Promise { + const args = ["--yes", "--message", task]; + + if (options.path) { + args.push(options.path); + } + + const result = await $`aider ${args}`.quiet(); + return result.stdout.toString(); +} + +async function logDelegation(entry: DelegationLogEntry): Promise { + const logPath = "/tmp/delegation-log.json"; + let log: DelegationLog = { delegations: [] }; + + if (existsSync(logPath)) { + log = await Bun.file(logPath).json(); + } + + log.delegations.push(entry); + + // Keep last 100 delegations + if (log.delegations.length > 100) { + log.delegations = log.delegations.slice(-100); + } + + // Write log file with secure permissions (0600 = owner read/write only) + const logFile = Bun.file(logPath); + await Bun.write(logFile, JSON.stringify(log, null, 2)); + + // Set secure permissions on the log file + try { + await $`chmod 600 ${logPath}`.quiet(); + } catch { + // Permissions setting failed, but don't block operation + console.warn("Warning: Could not set secure permissions on log file"); + } +} + +async function main(): Promise { + const args = process.argv.slice(2); + + // Parse options + const options: DelegationOptions = { + task: "", + path: undefined, + pattern: undefined, + tool: undefined, + dryRun: false, + json: false, + }; + + for (let i = 0; i < args.length; i++) { + if (args[i] === "--task" && args[i + 1]) { + options.task = args[++i]; + } else if (args[i] === "--path" && args[i + 1]) { + options.path = args[++i]; + } else if (args[i] === "--pattern" && args[i + 1]) { + options.pattern = args[++i]; + } else if (args[i] === "--tool" && args[i + 1]) { + options.tool = args[++i]; + } else if (args[i] === "--dry-run") { + options.dryRun = true; + } else if (args[i] === "--json") { + options.json = true; + } + } + + // Read from stdin if no task provided + if (!options.task) { + const stdin = await Bun.stdin.text(); + if (stdin.trim()) { + options.task = stdin.trim(); + } + } + + if (!options.task) { + console.error("Error: No task provided"); + console.error("Usage: delegate-router --task 'description' [options]"); + process.exit(1); + } + + // Analyze task + const analysis = await analyzeTask(options.task, options); + + // Make decision + const decision = await makeDecision(analysis, options.tool); + + if (options.dryRun || options.json) { + const output = { + analysis, + decision, + wouldExecute: !options.dryRun && decision.shouldDelegate, + }; + + if (options.json) { + console.log(JSON.stringify(output, null, 2)); + } else { + console.log("šŸ“Š Task Analysis:"); + console.log(` Type: ${analysis.type}`); + console.log(` Scope: ${analysis.scope}`); + console.log(` Complexity: ${analysis.inputSize.complexity}`); + console.log( + ` Estimated Tokens: ${analysis.inputSize.estimatedTokens.toLocaleString()}` + ); + console.log(); + console.log("šŸŽÆ Delegation Decision:"); + console.log(` Should Delegate: ${decision.shouldDelegate}`); + console.log(` Tool: ${decision.tool}`); + console.log(` Reason: ${decision.reason}`); + console.log( + ` Token Savings: ${decision.estimatedTokenSavings.toLocaleString()}` + ); + } + + return; + } + + // Execute if should delegate + if (decision.shouldDelegate) { + console.log( + `šŸ”„ Delegating to ${decision.tool}... (saving ~${decision.estimatedTokenSavings} tokens)` + ); + + const result = await executeDelegation(decision, options.task, options); + + if (result.success) { + console.log(`āœ… Delegation complete (${result.executionTime}ms)`); + console.log(); + console.log(result.output); + } else { + // Don't auto-fallback - return error for Kai to ask user + console.error(`āŒ Delegation to ${result.tool} failed: ${result.error}`); + console.error( + `\nKai should ask user: "Delegation failed. Would you like me to:"` + ); + console.error(` (a) Try another tool`); + console.error(` (b) Handle it directly`); + console.error(` (c) Skip this task"`); + process.exit(1); + } + } else { + console.log(`ā„¹ļø ${decision.reason}`); + console.log("Task does not require delegation."); + } +} + +main().catch(console.error); diff --git a/commands/delegate/delegate.md b/commands/delegate/delegate.md new file mode 100755 index 000000000..7dbbe1b28 --- /dev/null +++ b/commands/delegate/delegate.md @@ -0,0 +1,633 @@ +#!/usr/bin/env bun +/** + * Delegation System - Comprehensive Documentation & Configuration + * + * This file contains: + * 1. User guide and quick start + * 2. Configuration (YAML-style markdown) + * 3. Tool status checking + * 4. Technical documentation + * + * For Kai: Read this file to understand delegation config and available tools + * For Users: Edit the config section or tell Kai to adjust settings + */ + +import { $ } from "bun"; + +// ============================================================================ +// QUICK START GUIDE +// ============================================================================ + +/** + * # Delegation System - Quick Start + * + * **TL;DR:** Kai automatically delegates heavy tasks to save context. No setup needed if you have the tools installed. + * + * ## 30-Second Start + * + * 1. **Install tools** (optional, use what you have): + * ```bash + * npm install -g @augmentcode/cli # auggie + * pip install aider-chat # aider + * # gemini - see gemini-cli-setup.md + * ``` + * + * 2. **That's it!** Kai will automatically delegate when appropriate. + * + * ## How It Works + * + * **You:** "Analyze the ~/dev/myproject codebase" + * + * **Kai:** + * ``` + * šŸ“Š Delegating to auggie (847 files detected)... + * Estimated token savings: ~15,000 + * + * āœ… Analysis complete! + * [Synthesized results from auggie] + * ``` + * + * ## Configuration + * + * Edit the CONFIG section below, or just tell Kai: + * - "Don't use auggie anymore" + * - "Increase delegation timeouts" + * - "I added a new tool called X" + * + * ## When Delegation Happens + * + * **Kai delegates:** + * - āœ… Analyzing >10 files + * - āœ… Processing >20K tokens + * - āœ… Codebase-wide operations + * - āœ… Large document summaries + * + * **Kai handles directly:** + * - āŒ Small tasks (<5K tokens) + * - āŒ Interactive conversations + * - āŒ When you want Kai's perspective + * + * ## Available Tools + * + * - **auggie** - Codebase analysis (best for projects) + * - **gemini** - Fast text processing (best for speed) + * - **aider** - Direct file editing (best for refactoring) + * + * Check status: Run this file directly (`bun delegate.md`) + * + * ## Benefits + * + * - šŸ’° Save 60-80% tokens on large tasks + * - ⚔ Faster parallel processing + * - šŸŽÆ Right tool for the job + * - šŸ¤ Better conversations (more context for chat) + * + * ## FAQ + * + * **Q: How does Kai know when to delegate?** + * + * A: Kai analyzes your request. If it involves >10 files or >20K tokens, delegation triggers automatically. + * + * **Q: Can I force a specific tool?** + * + * A: Yes! Just say "Use gemini to analyze this" and Kai will use that tool specifically. + * + * **Q: What if delegation fails?** + * + * A: Kai will ask you what to do - try another tool, have Kai handle it directly, or skip the task. + * + * **Q: Do I need all three tools?** + * + * A: No! Install what you want. Kai uses what's available and falls back gracefully. + * + * **Q: How do I disable delegation?** + * + * A: Change `enabled: true` to `enabled: false` in the config below, or tell Kai "Disable delegation system". + * + * **Q: Can I add my own tools?** + * + * A: Absolutely! Add a tool section to the config below (copy the auggie format) and tell Kai about it. + * + * ## That's It! + * + * No wizards, no complex setup. Just install tools and let Kai delegate intelligently. + */ + +// ============================================================================ +// CONFIGURATION +// ============================================================================ + +/** + * # Delegation System Configuration + * + * **Last Updated:** 2025-10-11 + * **Version:** 1.0.0 + * + * ## System Status + * + * ```yaml + * enabled: true + * autoDelegate: true + * announceDelegate: true + * askBeforeFallback: true # Ask user if delegation fails + * ``` + * + * ## Available Tools + * + * ### auggie + * ```yaml + * enabled: true + * command: auggie + * priority: 1 + * timeout: 120000 # 2 minutes + * + * bestFor: + * - codebase-analysis (>10 files) + * - architecture-review + * - project-understanding + * + * strengths: + * - Codebase-aware indexing + * - Full project context + * - Interactive and automated modes + * + * usage: | + * auggie -p -q "task description" /path/to/project + * ``` + * + * ### gemini + * ```yaml + * enabled: true + * command: gemini + * priority: 2 + * timeout: 60000 # 1 minute + * + * bestFor: + * - fast-text-generation + * - document-summarization (>5K tokens) + * - code-generation + * - web-research + * + * strengths: + * - Speed and efficiency + * - Large context window + * - Web search capability + * + * usage: | + * gemini "task description" + * # or with file: gemini "@file.txt task" + * ``` + * + * ### aider + * ```yaml + * enabled: true + * command: aider + * priority: 3 + * timeout: 180000 # 3 minutes + * + * bestFor: + * - direct-file-editing + * - code-refactoring (1-20 files) + * - implementation-tasks + * + * strengths: + * - Direct file manipulation + * - Git-aware changes + * - Multi-file refactoring + * + * usage: | + * aider --yes --message "task description" file.py + * ``` + * + * ## Delegation Rules + * + * ### When Kai Delegates + * + * **Always delegate:** + * - Analyzing >10 files → auggie + * - Processing >20,000 tokens → auggie or gemini + * - Document summarization >5,000 tokens → gemini + * - Batch code generation → gemini + * - Multi-file refactoring → aider + * + * **Never delegate:** + * - Single file operations (<3 files) + * - Small tasks (<5,000 tokens) + * - Interactive conversations + * - Tasks requiring Kai's perspective + * + * ### Tool Selection Logic + * + * ``` + * Task Type: analyze + Scope: codebase → auggie (fallback: gemini) + * Task Type: summarize + Size: large → gemini (fallback: auggie) + * Task Type: generate + Any size → gemini (fallback: auggie) + * Task Type: refactor + Multi-file → aider (fallback: auggie) + * Task Type: research + Web → gemini (no fallback) + * ``` + * + * ## Configuration Notes + * + * ### Adding Custom Tools + * + * To add a new tool, add a section like: + * + * ```yaml + * ### my-tool + * enabled: true + * command: my-tool + * priority: 4 + * timeout: 60000 + * + * bestFor: + * - custom-analysis + * + * strengths: + * - What it does well + * + * usage: | + * my-tool --flag "task" + * ``` + * + * Then tell Kai: "I added my-tool to delegation config, please use it for X tasks" + * + * ### Adjusting Settings + * + * Edit this file directly, then tell Kai: + * - "Kai, reload delegation config" + * - "I updated delegation timeouts" + * - "I disabled auggie delegation" + * + * Kai will re-read this file and adjust behavior. + * + * ### Disabling Tools + * + * Change `enabled: true` to `enabled: false`, or tell Kai: + * - "Don't use auggie for delegation anymore" + * - "Disable gemini delegation" + * + * ### Changing Priorities + * + * Lower number = higher priority. Adjust the `priority:` value. + */ + +// ============================================================================ +// TOOL STATUS CHECKER +// ============================================================================ + +async function checkToolStatus() { + const tools = [ + { + name: "auggie", + command: "auggie", + versionFlag: "--version", + description: "Augment Code CLI - Codebase-aware AI assistant" + }, + { + name: "gemini", + command: "gemini", + versionFlag: "--version", + description: "Gemini CLI - Fast text processing and generation" + }, + { + name: "aider", + command: "aider", + versionFlag: "--version", + description: "Aider - AI pair programming with direct file editing" + } + ]; + + console.log("šŸ” Delegation System - Tool Status\n"); + console.log("═".repeat(60)); + + for (const tool of tools) { + try { + // Check if tool exists + const whichResult = await $`which ${tool.command}`.text(); + const path = whichResult.trim(); + + if (!path) { + console.log(`\nāŒ ${tool.name}`); + console.log(` Status: Not installed`); + console.log(` Description: ${tool.description}`); + continue; + } + + // Get version + let version = "unknown"; + try { + const versionResult = await $`${tool.command} ${tool.versionFlag}`.text(); + version = versionResult.trim().split("\n")[0]; + } catch { + version = "installed (version unknown)"; + } + + console.log(`\nāœ… ${tool.name}`); + console.log(` Status: Available`); + console.log(` Path: ${path}`); + console.log(` Version: ${version}`); + console.log(` Description: ${tool.description}`); + } catch (error) { + console.log(`\nāŒ ${tool.name}`); + console.log(` Status: Not installed`); + console.log(` Description: ${tool.description}`); + } + } + + console.log("\n" + "═".repeat(60)); + console.log("\nšŸ“¦ Installation Commands:"); + console.log("\n auggie: npm install -g @augmentcode/cli"); + console.log(" gemini: See PAI reference docs for gemini-cli setup"); + console.log(" aider: pip install aider-chat"); + console.log(" or: brew install aider\n"); +} + +// ============================================================================ +// TECHNICAL DOCUMENTATION +// ============================================================================ + +/** + * # Delegation System - Technical Documentation + * + * ## Architecture + * + * The delegation system consists of two main components: + * + * 1. **delegate.md** (this file) - Configuration and documentation + * 2. **delegate-router.md** - Smart routing engine that executes delegations + * + * ## How It Works + * + * ### 1. Task Analysis + * + * When Kai receives a request, it analyzes: + * - **File count**: How many files are involved? + * - **Token estimate**: How large is the context? + * - **Task type**: Analysis, generation, refactoring, etc. + * - **Scope**: Single file, multi-file, or codebase-wide? + * + * ### 2. Delegation Decision + * + * Triggers delegation if: + * - File count > 10, OR + * - Estimated tokens > 20,000, OR + * - Explicit tool request (e.g., "use auggie to...") + * + * ### 3. Tool Selection + * + * The router: + * 1. Reads this config file + * 2. Filters enabled tools + * 3. Matches task type to tool capabilities + * 4. Selects by priority (lower number = higher priority) + * 5. Falls back to next tool if primary fails + * 6. **Asks user if all tools fail** (no auto-fallback to Kai) + * + * ### 4. Execution + * + * The router: + * 1. Constructs appropriate command + * 2. Executes with configured timeout + * 3. Captures stdout/stderr + * 4. Returns results to Kai + * + * ### 5. Synthesis + * + * Kai: + * 1. Receives raw tool output + * 2. Synthesizes into coherent response + * 3. Presents to user in structured format + * 4. Credits the tool used + * + * ## Token Savings + * + * Example scenarios: + * + * **Scenario 1: Codebase Analysis (850 files)** + * - Without delegation: ~40,000 tokens (reading all files) + * - With auggie delegation: ~7,000 tokens (auggie summary + synthesis) + * - **Savings: ~82%** + * + * **Scenario 2: Large Document Summary (100KB text)** + * - Without delegation: ~25,000 tokens (full document in context) + * - With gemini delegation: ~5,000 tokens (gemini summary + synthesis) + * - **Savings: ~80%** + * + * **Scenario 3: Multi-file Refactoring (15 files)** + * - Without delegation: ~30,000 tokens (all files + edits) + * - With aider delegation: ~3,000 tokens (aider handles edits) + * - **Savings: ~90%** + * + * ## Tool Capabilities + * + * ### Auggie (Priority 1) + * + * **Best for:** + * - Large codebases (>10 files) + * - Understanding project architecture + * - Finding patterns across files + * - Comprehensive analysis + * + * **How it works:** + * - Indexes entire codebase + * - Uses vector embeddings for semantic search + * - Understands code relationships + * - Can answer specific questions about code + * + * **Example tasks:** + * - "Analyze the authentication system" + * - "Find all API endpoints" + * - "Explain the database schema" + * - "Map out the component hierarchy" + * + * ### Gemini (Priority 2) + * + * **Best for:** + * - Fast text generation + * - Document summarization + * - Code generation from scratch + * - Web research + * + * **How it works:** + * - Large context window (1M+ tokens) + * - Extremely fast inference + * - Can search web for current info + * - Good at creative generation + * + * **Example tasks:** + * - "Summarize this 50-page document" + * - "Generate boilerplate for X" + * - "Research current best practices for Y" + * - "Create test data for Z" + * + * ### Aider (Priority 3) + * + * **Best for:** + * - Direct file editing + * - Multi-file refactoring + * - Implementation tasks + * - Git-aware changes + * + * **How it works:** + * - Reads files directly from disk + * - Makes precise edits + * - Creates git commits + * - Can work with multiple files + * + * **Example tasks:** + * - "Add docstrings to all functions" + * - "Refactor class X to use pattern Y" + * - "Update all imports to use new path" + * - "Add error handling to these 10 files" + * + * ## Configuration Format + * + * The config uses YAML-style markdown for readability. Kai parses this file by: + * + * 1. Reading the entire file as text + * 2. Extracting tool sections (### tool-name) + * 3. Parsing YAML-like key-value pairs + * 4. Building internal config object + * + * This is the PAI pattern: human-readable markdown that Kai can parse. + * + * ## Natural Language Configuration + * + * You can configure the system by talking to Kai: + * + * **Disable a tool:** + * - "Don't use auggie anymore" + * - "Disable aider delegation" + * + * **Adjust timeouts:** + * - "Increase auggie timeout to 5 minutes" + * - "Set gemini timeout to 30 seconds" + * + * **Change priorities:** + * - "Make gemini the first choice for analysis" + * - "Prefer aider over auggie for refactoring" + * + * **Add new tool:** + * - "I installed a new tool called 'cursor-ai'" + * - "Add cursor-ai to delegation with priority 4" + * + * Kai will update this file and confirm the changes. + * + * ## Extending the System + * + * To add a new AI tool: + * + * 1. **Install the tool** and verify it works + * 2. **Add config section** (copy existing tool format) + * 3. **Tell Kai** about it: "I added tool X, use it for Y tasks" + * 4. **Test it**: Ask Kai to delegate a task to your new tool + * + * Example: + * + * ```yaml + * ### cursor-ai + * enabled: true + * command: cursor-ai + * priority: 4 + * timeout: 90000 + * + * bestFor: + * - interactive-editing + * - ide-integration + * + * strengths: + * - Real-time suggestions + * - IDE integration + * + * usage: | + * cursor-ai analyze "task" --path /project + * ``` + * + * ## Troubleshooting + * + * ### Tools not found + * + * Run this file: `bun delegate.md` + * + * This checks which tools are installed and where they are. + * + * ### Delegation not triggering + * + * Check the thresholds: + * - Is your task >10 files? + * - Is your task >20K tokens? + * + * You can force delegation: "Use auggie to analyze this single file" + * + * ### Tool timeouts + * + * If tools are timing out, increase the timeout in config: + * - auggie: 120000 (2 min) → 300000 (5 min) + * - gemini: 60000 (1 min) → 120000 (2 min) + * - aider: 180000 (3 min) → 360000 (6 min) + * + * Or tell Kai: "Increase auggie timeout to 5 minutes" + * + * ### Wrong tool selected + * + * Adjust priorities or force specific tool: + * - "Use gemini instead of auggie for this" + * - "Always prefer aider for refactoring tasks" + * + * ## Security Considerations + * + * - Tools run with your user permissions + * - Tools can read/write files in delegated paths + * - Review tool output before accepting changes + * - Aider can modify files directly (use git!) + * - Gemini can make web requests + * + * ## Performance Tips + * + * 1. **Use auggie for codebases** - It's optimized for project analysis + * 2. **Use gemini for speed** - Fastest for text generation + * 3. **Use aider for editing** - Direct file manipulation is faster + * 4. **Adjust timeouts** - Complex tasks need more time + * 5. **Enable only needed tools** - Reduces decision overhead + * + * ## Integration with PAI + * + * The delegation system is designed for the Personal AI (PAI) ecosystem: + * + * - **Markdown-first**: Config is readable markdown, not JSON + * - **Natural language**: Configure by talking to Kai + * - **Zero-setup**: Works if tools are installed + * - **Consistent patterns**: Follows PAI conventions + * - **Extensible**: Easy to add new tools + * + * ## Related Documentation + * + * - **Auggie CLI**: https://docs.augmentcode.com + * - **Gemini CLI**: https://github.com/gemini-cli (see PAI reference docs for setup) + * - **Aider Docs**: https://aider.chat + * - **PAI Documentation**: See PAI README and reference docs + * + * ## Version History + * + * - **1.0.0** (2025-10-11) - Initial release + * - Three tools: auggie, gemini, aider + * - Smart routing with priorities + * - Natural language configuration + * - Markdown-based config + * - Ask-user-on-failure behavior + * + * --- + * + * **That's it!** This is the complete delegation system documentation and configuration. + */ + +// ============================================================================ +// MAIN - Tool Status Check +// ============================================================================ + +// When run directly, check tool status +if (import.meta.main) { + await checkToolStatus(); +} + +export { checkToolStatus };