diff --git a/docs/.obsidian/workspace.json b/docs/.obsidian/workspace.json index 855ce594..ffdaa675 100644 --- a/docs/.obsidian/workspace.json +++ b/docs/.obsidian/workspace.json @@ -13,12 +13,12 @@ "state": { "type": "markdown", "state": { - "file": "develop2/getting-started/quickstart.md", + "file": "developer/2_getting-started/concepts.md", "mode": "source", "source": false }, "icon": "lucide-file", - "title": "quickstart" + "title": "concepts" } } ] @@ -170,6 +170,13 @@ }, "active": "c883305ca140b86c", "lastOpenFiles": [ + "developer/structure.md", + "developer21/agents/3_advancagent.md", + "developer21/agents/agentIntroduction.md", + "developer21/agents/quickstart.md", + "developer/2_getting-started/quickstart.md", + "developer/2_getting-started/concepts.md", + "developer/1_index.md", "develop2/getting-started/installation.md", "develop2/getting-started/concepts.md", "develop2/getting-started/quickstart.md", @@ -178,7 +185,6 @@ "develop2/core/agents/overview.md", "develop2/core/agents/custom-agent.md", "develop2/index.md", - "developer/structure.md", "develop2/core/typescript-sdk/overview.md", "develop2/core/typescript-sdk", "develop2/core/cli/overview.md", @@ -199,12 +205,6 @@ "developer/structure-recommendations.md", "developer/overview.md", "developer/testing/main-index.md", - "developer/testing/index.md", - "developer/testing/agents-index.md", - "developer/2_core/1_index.md", - "developer/testing/tools-index.md", - "developer/testing/templates-index.md", - "developer/testing/sdk-index.md", - "developer/testing/getting-started-index.md" + "developer/testing/index.md" ] } \ No newline at end of file diff --git a/docs/developer/1_getting-started/1_introduction.md b/docs/developer/1_getting-started/1_introduction.md new file mode 100644 index 00000000..6762f70e --- /dev/null +++ b/docs/developer/1_getting-started/1_introduction.md @@ -0,0 +1,16 @@ +# Introduction + +Welcome to Codebolt AI Editor. + +![welcome](/img/custom-agent.png) + +## What is Codebolt + +Codebolt is an AI editor where you can create agents, build MCP tools, write code, customize features, and do much moreβ€”all in one place. + +## Quick Links + +[**Get Started**](installation) +[**Concept**](concept) +[**CLI**](cli.md) +[**Download**](download.md) diff --git a/docs/developer/1_getting-started/2_installation.md b/docs/developer/1_getting-started/2_installation.md new file mode 100644 index 00000000..8f5f52cf --- /dev/null +++ b/docs/developer/1_getting-started/2_installation.md @@ -0,0 +1,14 @@ +# Installation +Get codebolt installed on your computer in just a few minutes + +## Download codeobolt +Getting started is simple: +- Go to codebolt.ai and click β€œDownload” +- Run the installer once it downloads +- Open codebolt when installation finishes + +## First-time setup + +- process of First Time Setup + + diff --git a/docs/developer/1_getting-started/3_quickstart.md b/docs/developer/1_getting-started/3_quickstart.md new file mode 100644 index 00000000..e7da05ad --- /dev/null +++ b/docs/developer/1_getting-started/3_quickstart.md @@ -0,0 +1,10 @@ +# Quick Start + +This quickstart shows you how to use Codebolt’s main features: Agent, Inline Edit, and MCP Tools. + +# Open Codebolt + +- how to open project +- how to use Quick start empty project +- how to template like (React, Next, Express, etc) + diff --git a/docs/developer/1_getting-started/4_concepts.md b/docs/developer/1_getting-started/4_concepts.md new file mode 100644 index 00000000..5b96c196 --- /dev/null +++ b/docs/developer/1_getting-started/4_concepts.md @@ -0,0 +1,21 @@ +# Concepts +Learn the Key features that make codebolt more powarfull + + +### [Agent](../core/agents/overview.md) +Agents are AI-powered assistants that help automate tasks, answer questions, and provide coding suggestions within Codebolt. + +### [MCP Tools](../core/mcp-tools/overview.md) +MCP Tools are utilities that enhance productivity by allowing you to manage multiple tasks, files, or projects simultaneously. + +### [Context](../core/context/overview.md) +Context in Codebolt means you can use symbols like `@`, `#`, and `/` to reference files or Folders, Agent, MCP etc. + +### [Chats](1_introduction.md) +Chats let you interact with agents by asking questions or giving instructions and receiving responses. You can also manage your chat history, view file changes made during the conversation, and monitor background commands running as part of the chat session. + +### [Inline Edit (Ctrl + K)](../core/inline-edit/overview.md) +Inline Edit allows you to quickly edit code or text in place using the keyboard shortcut Ctrl + K, streamlining your workflow. + +Press Ctrl+K to describe changes and see them applied in place. + diff --git a/docs/developer/1_getting-started/_category_.json b/docs/developer/1_getting-started/_category_.json new file mode 100644 index 00000000..2f8ff56b --- /dev/null +++ b/docs/developer/1_getting-started/_category_.json @@ -0,0 +1,7 @@ +{ + "label": "Getting Started", + "position": 2, + "collapsible": false, + "collapsed": false, + "className": "red" + } \ No newline at end of file diff --git a/docs/developer/1_index.md b/docs/developer/1_index.md deleted file mode 100644 index 6e159527..00000000 --- a/docs/developer/1_index.md +++ /dev/null @@ -1,44 +0,0 @@ -# Welcome to Codebolt AI Editor - -Welcome to Codebolt AI Editor, the next-generation AI-powered code editor designed to accelerate your development workflow through intelligent automation and seamless AI integration. - -## What is Codebolt AI Editor? - -Codebolt AI Editor is a revolutionary development environment that combines the power of artificial intelligence with traditional coding tools to provide an unparalleled programming experience. Built for modern developers, it offers intelligent code generation, automated workflows, and context-aware assistance to help you build better software faster. - -## Key Features - -- **AI-Powered Agents**: Create custom agents that can understand your codebase and perform complex tasks autonomously -- **Multi-Agent Coordination**: Orchestrate multiple agents to work together on complex projects -- **Inline Edit (Ctrl+K)**: Make instant code modifications with AI assistance directly in your editor -- **Intelligent Chats**: Get coding help through natural language conversations with AI -- **Task Flow Automation**: Build and manage sophisticated workflows that integrate seamlessly with your development process -- **Context-Aware Intelligence**: Leverage deep project understanding for smarter suggestions and actions -- **Command Line Interface**: Powerful CLI tools for automation and scripting -- **TypeScript SDK**: Extend Codebolt with custom integrations and extensions - -## Quick Links - -### πŸš€ Getting Started -- [Installation Guide](getting-started/installation.md) - Set up Codebolt AI Editor on your system -- [Quickstart Tutorial](getting-started/quickstart.md) - Get up and running in minutes -- [Core Concepts](getting-started/concepts.md) - Understand the fundamental building blocks - -### πŸ”§ Core Features -- [Agents](core/agents/overview.md) - Learn about AI agents and how to create them -- [Multi-Agents](core/multi-agents/overview.md) - Coordinate multiple agents for complex tasks -- [Inline Edit](core/inline-edit/overview.md) - Master the Ctrl+K feature for quick edits -- [MCP Tools](core/mcp-tools/overview.md) - Extend functionality with Modular Component Plugins -- [Chats](core/chats/overview.md) - Leverage AI-assisted conversations -- [Task Flow](core/task-flow/overview.md) - Automate your development workflows - -### πŸ“š Learn More -- [End-to-End Tutorials](tutorials.md) - Complete project walkthroughs -- [API Reference](api-reference.md) - Detailed technical documentation -- [Troubleshooting](troubleshooting.md) - Common issues and solutions - -## Community & Support - -Join our growing community of developers who are revolutionizing how code is written with AI assistance. Whether you're building your first agent or orchestrating complex multi-agent workflows, we're here to help you succeed. - -Ready to transform your coding experience? Let's get started! diff --git a/docs/developer/2_getting-started/concepts.md b/docs/developer/2_getting-started/concepts.md deleted file mode 100644 index 0e45a4a3..00000000 --- a/docs/developer/2_getting-started/concepts.md +++ /dev/null @@ -1,162 +0,0 @@ -# Core Concepts - -Understanding these fundamental concepts will help you make the most of Codebolt AI Editor. Each concept builds upon the others to create a powerful, integrated development experience. - -## Agents - -**Agents** are AI-powered assistants that can understand your code and perform tasks autonomously. Think of them as specialized team members that work alongside you. - -Agents can analyze code, suggest improvements, generate documentation, run tests, and much more. They're triggered by events (like saving a file) or can be invoked manually. Each agent has a specific purpose and can be customized to match your workflow and coding standards. - -**Key Features:** -- Event-driven automation -- Context-aware analysis -- Customizable behavior -- Integration with your development tools - -[Learn more about Agents β†’](../core/agents/overview.md) - -## Multi-Agents - -**Multi-Agents** systems coordinate multiple agents to tackle complex tasks that require different specializations. Like a well-organized development team, each agent contributes their expertise to achieve a common goal. - -For example, you might have one agent analyze code quality, another handle testing, and a third generate documentation - all working together in a coordinated workflow to prepare your code for production. - -**Key Features:** -- Agent coordination and communication -- Complex workflow orchestration -- Parallel and sequential task execution -- Shared context and data flow - -[Learn more about Multi-Agents β†’](../core/multi-agents/overview.md) - -## MCP Tools - -**MCP (Modular Component Plugin) Tools** extend Codebolt's capabilities by adding new functionality through a standardized plugin system. These tools can integrate with external services, add new AI models, or provide specialized development utilities. - -MCP Tools make Codebolt infinitely extensible, allowing you to integrate with your favorite tools and services seamlessly. Whether you need database connectivity, API testing, or custom visualization, there's likely an MCP Tool for that. - -**Key Features:** -- Standardized plugin architecture -- Easy integration with external services -- Custom AI model support -- Community-driven ecosystem - -[Learn more about MCP Tools β†’](../core/mcp-tools/overview.md) - -## Inline Edit - -**Inline Edit** is Codebolt's signature feature, accessible via Ctrl+K (Cmd+K on macOS), that allows you to make AI-powered code modifications directly in your editor. Simply select code, press the shortcut, describe what you want, and watch your code transform. - -This feature bridges the gap between thinking about a change and implementing it, making code modification as natural as describing what you want in plain English. - -**Key Features:** -- Instant code transformation -- Natural language prompts -- Context-aware suggestions -- Undo/redo support - -[Learn more about Inline Edit β†’](../core/inline-edit/overview.md) - -## Chats - -**Chats** provide an AI-assisted conversational interface where you can ask questions, get coding help, and discuss implementation strategies. It's like having a knowledgeable senior developer available 24/7. - -The chat interface understands your project context, can reference your code, and provides detailed explanations with code examples. It's perfect for learning new concepts, debugging issues, or exploring different approaches to a problem. - -**Key Features:** -- Context-aware conversations -- Code-specific assistance -- Learning and exploration -- Integration with project files - -[Learn more about Chats β†’](../core/chats/overview.md) - -## Task Flow - -**Task Flow** is Codebolt's workflow automation system that helps you create, manage, and execute complex development processes. Think of it as your personal DevOps pipeline that can be customized for any workflow. - -Task Flow can automate everything from code generation and testing to deployment and monitoring. You can create flows that respond to events, run on schedules, or execute on-demand. - -**Key Features:** -- Visual workflow builder -- Event-driven automation -- Integration with agents and tools -- Conditional logic and branching - -[Learn more about Task Flow β†’](../core/task-flow/overview.md) - -## Context - -**Context** is how Codebolt understands your project structure, dependencies, coding patterns, and development preferences. The more context Codebolt has, the smarter and more helpful its suggestions become. - -Context includes your file structure, import relationships, coding style, project configuration, and even your team's conventions. This deep understanding enables Codebolt to provide relevant, accurate assistance that feels tailored to your specific project. - -**Key Features:** -- Project structure analysis -- Dependency mapping -- Code pattern recognition -- Team convention learning - -[Learn more about Context β†’](../core/context/overview.md) - -## CLI - -**CLI (Command Line Interface)** provides powerful command-line tools for automation, scripting, and integration with your existing development workflows. The CLI is perfect for CI/CD pipelines, batch operations, and advanced automation scenarios. - -Whether you're generating code, running agents, managing workflows, or analyzing projects, the CLI provides programmatic access to all of Codebolt's features. - -**Key Features:** -- Comprehensive command set -- Scriptable automation -- CI/CD integration -- Batch operations - -[Learn more about CLI β†’](../core/cli/overview.md) - -## TypeScript SDK - -**TypeScript SDK** enables developers to build custom extensions, integrations, and tools that extend Codebolt's functionality. With full TypeScript support, you get excellent developer experience with type safety and IntelliSense. - -The SDK provides APIs for creating custom agents, MCP tools, workflow steps, and integrations with external services. It's the foundation for building powerful, type-safe extensions. - -**Key Features:** -- Full TypeScript support -- Comprehensive API coverage -- Type-safe development -- Rich documentation and examples - -[Learn more about TypeScript SDK β†’](../core/typescript-sdk/overview.md) - -## How These Concepts Work Together - -These concepts are designed to work seamlessly together: - -1. **Agents** use **Context** to understand your project and make intelligent decisions -2. **Multi-Agents** coordinate multiple **Agents** through **Task Flow** workflows -3. **Inline Edit** leverages **Context** and can trigger **Agents** for complex transformations -4. **Chats** can invoke **Agents** and reference **Context** to provide better assistance -5. **MCP Tools** extend the capabilities of **Agents** and **Task Flow** -6. **CLI** provides programmatic access to all features for automation -7. **TypeScript SDK** enables custom development of all these components - -## Getting Started with Each Concept - -### For Beginners -Start with **Inline Edit** and **Chats** to get immediate value, then explore **Agents** for automation. - -### For Intermediate Users -Dive into **Task Flow** and **Multi-Agents** to create sophisticated workflows. - -### For Advanced Users -Explore **MCP Tools**, **CLI**, and **TypeScript SDK** to build custom solutions. - -## Next Steps - -Now that you understand the core concepts, you're ready to: - -1. **Explore specific features** by following the links to detailed guides -2. **Try the hands-on tutorials** in [tutorials.md](../tutorials.md) -3. **Build your first custom solution** using the [TypeScript SDK](../core/typescript-sdk/overview.md) - -Each concept has its own dedicated section in the [Core](../core/) documentation where you'll find detailed guides, examples, and best practices. Choose the concept that interests you most and dive in! diff --git a/docs/developer/2_getting-started/installation.md b/docs/developer/2_getting-started/installation.md deleted file mode 100644 index f0e7a509..00000000 --- a/docs/developer/2_getting-started/installation.md +++ /dev/null @@ -1,114 +0,0 @@ -# Installation Guide - -This guide will walk you through the step-by-step process of installing Codebolt AI Editor on your system. - -## Prerequisites - -Before installing Codebolt AI Editor, ensure your system meets the following requirements: - - -## Installation Steps - -### Windows Installation - -1. **Download the Installer** - ```powershell - # Download using PowerShell - Invoke-WebRequest -Uri "https://releases.codebolt.ai/windows/latest" -OutFile "CodeboltInstaller.exe" - ``` - -2. **Run the Installer** - - Double-click `CodeboltInstaller.exe` - - Follow the installation wizard - - Choose installation directory (default: `C:\Program Files\Codebolt`) - -3. **Verify Installation** - ```powershell - codebolt --version - ``` - -### macOS Installation - -1. **Using Homebrew (Recommended)** - ```bash - # Install Homebrew if not already installed - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - - # Install Codebolt - brew tap codebolt/tap - brew install codebolt-ai-editor - ``` - -2. **Manual Installation** - ```bash - # Download the .dmg file - curl -L "https://releases.codebolt.ai/macos/latest.dmg" -o "Codebolt.dmg" - - # Mount and install - hdiutil mount Codebolt.dmg - cp -R "/Volumes/Codebolt/Codebolt AI Editor.app" /Applications/ - hdiutil unmount "/Volumes/Codebolt" - ``` - -3. **Verify Installation** - ```bash - codebolt --version - `` -## Troubleshooting Common Issues - -### Issue: "Command not found: codebolt" -**Solution**: The installation path may not be in your system's PATH variable. - -**Windows:** -```powershell -# Add to PATH temporarily -$env:PATH += ";C:\Program Files\Codebolt\bin" - -# Add to PATH permanently -[Environment]::SetEnvironmentVariable("PATH", $env:PATH + ";C:\Program Files\Codebolt\bin", [EnvironmentVariableTarget]::User) -``` - -**macOS/Linux:** -```bash -# Add to your shell profile (.bashrc, .zshrc, etc.) -echo 'export PATH="/usr/local/bin/codebolt:$PATH"' >> ~/.bashrc -source ~/.bashrc -``` - -### Issue: "Node.js version incompatible" -**Solution**: Update Node.js to version 16.0 or higher. -```bash -# Using Node Version Manager (nvm) -nvm install 18 -nvm use 18 -``` - -### Issue: Permission denied during installation -**Solution**: -- **Windows**: Run installer as Administrator -- **macOS**: Use `sudo` for manual installation steps -- **Linux**: Ensure you have sudo privileges - -### Issue: Network connectivity problems -**Solution**: -1. Check your internet connection -2. Configure proxy settings if behind a corporate firewall: - ```bash - codebolt config set proxy.http "http://proxy.company.com:8080" - codebolt config set proxy.https "https://proxy.company.com:8080" - ``` - -## Next Steps - -Once installation is complete: - -1. **Take the Quickstart Tutorial**: [quickstart.md](quickstart.md) -2. **Learn Core Concepts**: [concepts.md](concepts.md) -3. **Create Your First Agent**: [../core/agents/custom-agent.md](../core/agents/custom-agent.md) - -## Getting Help - -If you encounter issues not covered in this guide: -- Check our [Troubleshooting Guide](../troubleshooting.md) -- Visit our [Community Forum](https://community.codebolt.ai) -- Contact support at [support@codebolt.ai](mailto:support@codebolt.ai) diff --git a/docs/developer/2_getting-started/quickstart.md b/docs/developer/2_getting-started/quickstart.md deleted file mode 100644 index 8326a9cd..00000000 --- a/docs/developer/2_getting-started/quickstart.md +++ /dev/null @@ -1,240 +0,0 @@ -# Quickstart Tutorial - -Welcome to Codebolt AI Editor! This hands-on tutorial will get you up and running in just 15 minutes. By the end, you'll have created your first agent, used Inline Edit, and executed a basic command. - -## What You'll Build - -In this tutorial, you'll: -1. Create a simple "Code Reviewer" agent -2. Use Inline Edit to improve code quality -3. Run basic CLI commands -4. Experience the power of AI-assisted development - -## Step 1: Launch Codebolt - -Open Codebolt AI Editor and create a new project: - -```bash -# Create a new project -codebolt create my-first-project -cd my-first-project - -# Open in Codebolt -codebolt open . -``` - -## Step 2: Create Your First Agent - -Let's create a simple agent that reviews code for best practices. - -### Using the UI (Recommended for beginners) - -1. **Open the Agent Panel**: Click the "Agents" tab in the sidebar -2. **Create New Agent**: Click the "+" button -3. **Configure the Agent**: - - **Name**: "Code Reviewer" - - **Description**: "Reviews code for best practices and suggests improvements" - - **Trigger**: "On file save" - - **Action**: "Analyze and suggest improvements" - -4. **Save the Agent**: Click "Create Agent" - -### Using Code (For developers who prefer configuration as code) - -Create a new file `agents/code-reviewer.json`: - -```json -{ - "name": "Code Reviewer", - "description": "Reviews code for best practices and suggests improvements", - "version": "1.0.0", - "triggers": [ - { - "type": "file_save", - "patterns": ["*.js", "*.ts", "*.py", "*.java"] - } - ], - "actions": [ - { - "type": "analyze_code", - "prompt": "Review this code for best practices, potential bugs, and suggest improvements. Focus on readability, performance, and maintainability.", - "output": "suggestions" - } - ], - "settings": { - "auto_apply": false, - "show_notifications": true - } -} -``` - -Register the agent: -```bash -codebolt agent register agents/code-reviewer.json -``` - -## Step 3: Test Your Agent - -Create a sample JavaScript file to test your agent: - -```javascript -// sample.js -function calculateTotal(items) { - var total = 0; - for (var i = 0; i < items.length; i++) { - total = total + items[i].price * items[i].quantity; - } - return total; -} - -var cart = [ - { price: 10, quantity: 2 }, - { price: 15, quantity: 1 }, - { price: 8, quantity: 3 } -]; - -console.log("Total: $" + calculateTotal(cart)); -``` - -Save the file and watch your Code Reviewer agent analyze it! - -## Step 4: Use Inline Edit (Ctrl+K) - -Now let's improve the code using Codebolt's powerful Inline Edit feature: - -1. **Select the `calculateTotal` function** -2. **Press `Ctrl+K`** (or `Cmd+K` on macOS) -3. **Enter your prompt**: "Convert this to modern JavaScript with arrow functions and const/let" -4. **Press Enter** and watch the magic happen! - -Expected result: -```javascript -const calculateTotal = (items) => { - return items.reduce((total, item) => total + (item.price * item.quantity), 0); -}; -``` - -### Try More Inline Edit Examples - -Select different parts of your code and try these prompts: - -- `"Add error handling for empty arrays"` -- `"Add JSDoc comments"` -- `"Convert to TypeScript with proper types"` -- `"Add input validation"` - -## Step 5: Explore CLI Commands - -Codebolt's CLI provides powerful automation capabilities: - -```bash -# List all available agents -codebolt agent list - -# Run an agent manually -codebolt agent run "Code Reviewer" --file sample.js - -# Generate code from a prompt -codebolt generate function "Create a function that validates email addresses" - -# Get project insights -codebolt analyze --type complexity - -# Run all agents on the project -codebolt workflow run review-and-improve -``` - -## Step 6: Create a Simple Workflow - -Let's create a workflow that combines multiple actions: - -```bash -# Create a new workflow -codebolt workflow create code-improvement -``` - -Configure the workflow in `workflows/code-improvement.json`: - -```json -{ - "name": "Code Improvement Workflow", - "description": "Analyzes, improves, and documents code", - "steps": [ - { - "name": "analyze", - "agent": "Code Reviewer", - "input": "all_files" - }, - { - "name": "improve", - "type": "inline_edit", - "prompt": "Apply the suggested improvements from the previous step" - }, - { - "name": "document", - "type": "generate", - "prompt": "Generate JSDoc comments for all functions" - } - ] -} -``` - -Run the workflow: -```bash -codebolt workflow run code-improvement -``` - -## Step 7: Explore the Chat Interface - -Open the Chat panel and try these example queries: - -1. **Code Help**: "How can I optimize this function for better performance?" -2. **Architecture Questions**: "What's the best way to structure a React component?" -3. **Debugging**: "Why might this function be returning undefined?" -4. **Learning**: "Explain the difference between map() and forEach()" - -## What You've Accomplished - -Congratulations! In just 15 minutes, you've: - -βœ… Created your first AI agent -βœ… Used Inline Edit to improve code -βœ… Executed CLI commands for automation -βœ… Built a simple workflow -βœ… Experienced AI-assisted development - -## Next Steps - -Now that you've got the basics down, here's what to explore next: - -### Immediate Next Steps -1. **Learn Core Concepts**: [concepts.md](concepts.md) - Understand the fundamentals -2. **Create Custom Agents**: [../core/agents/custom-agent.md](../core/agents/custom-agent.md) -3. **Explore Multi-Agent Workflows**: [../core/multi-agents/overview.md](../core/multi-agents/overview.md) - -### Advanced Features -1. **MCP Tools**: [../core/mcp-tools/overview.md](../core/mcp-tools/overview.md) - Extend Codebolt's capabilities -2. **Task Flow Automation**: [../core/task-flow/overview.md](../core/task-flow/overview.md) -3. **TypeScript SDK**: [../core/typescript-sdk/overview.md](../core/typescript-sdk/overview.md) - Build custom integrations - -### Real-World Projects -1. **End-to-End Tutorials**: [../tutorials.md](../tutorials.md) - Complete project walkthroughs - -## Pro Tips for Success - -1. **Start Small**: Begin with simple agents and gradually add complexity -2. **Use Descriptive Prompts**: The more specific your prompts, the better the results -3. **Iterate and Refine**: Agents improve with feedback and refinement -4. **Leverage Context**: Codebolt understands your project structure - use it! -5. **Join the Community**: Connect with other developers at [community.codebolt.ai](https://community.codebolt.ai) - -## Troubleshooting - -If something didn't work as expected: - -- **Agent not triggering**: Check the trigger patterns match your file types -- **Inline Edit not working**: Ensure you have selected text before pressing Ctrl+K -- **CLI commands failing**: Verify you're in a Codebolt project directory -- **Need more help**: Check our [Troubleshooting Guide](../troubleshooting.md) - -Ready to dive deeper? Let's explore the [Core Concepts](concepts.md) that power Codebolt AI Editor! diff --git a/docs/developer/core/_category_.json b/docs/developer/core/_category_.json new file mode 100644 index 00000000..02164e1b --- /dev/null +++ b/docs/developer/core/_category_.json @@ -0,0 +1,7 @@ +{ + "label": "Core", + "position": 2, + "collapsible": false, + "collapsed": false, + "className": "red" + } \ No newline at end of file diff --git a/docs/developer/core/agents/1_overview.md b/docs/developer/core/agents/1_overview.md new file mode 100644 index 00000000..5538cb8f --- /dev/null +++ b/docs/developer/core/agents/1_overview.md @@ -0,0 +1,112 @@ +# Overview + +Agents are intelligent assistants in Codebolt that can automate tasks, interact with your code, and enhance your development workflow. They use Codebolt's APIs to perform actions in your editor, making them much more powerful than simple prompt-based tools. + +## How Agents Work in Codebolt + +Agents operate by understanding your intent, planning tasks, and executing actions directly in your development environment. They can read, write, and refactor code, run tests, and even coordinate with other agents to handle complex workflows. + +## Agent Architecture + +```mermaid + +graph TB + subgraph "Codebolt Application" + A[Codebolt Editor] + B[Agent Orchestrator] + C[Service Manager] + + subgraph "Agent Services" + K[LLM Providers] + M[MCP Services] + E[File System] + end + end + + subgraph "Agent Runtime" + F[Custom Agent] + G[CodeboltJS Library] + H[Agent Logic] + I[System Prompts] + J[Task Instructions] + end + A --> B + A --> C + F --> G + G --> H + H --> I + H --> J + + G <--> C + + C <--> E + C --> K + C --> M + B --> F + +``` + + +## Agent Flow + +The following sequence diagram illustrates the complete flow of how a user request is processed through Codebolt and agents: + +```mermaid +sequenceDiagram + + + participant User + box Codebolt Editor + participant Codebolt as Editor UI + participant LLM as LLM Service + participant Tools as MCP Services + participant ServiceMgr as Service Manager + end + participant Agent as Custom Agent + + User->>Codebolt: Send request/message + Note over User,Codebolt: User types a request in chat + + Codebolt->>Agent: Start agent & forward message + Note over Codebolt,Agent: Agent Orchestrator routes to appropriate agent + + + Agent->>ServiceMgr: Send LLM request with context + Note over Agent,ServiceMgr: Agent calls LLM service via Service Manager + + ServiceMgr->>LLM: Route to LLM provider + Note over ServiceMgr,LLM: Service Manager handles LLM routing + + LLM->>ServiceMgr: Return response with tool calls + ServiceMgr->>Agent: Forward LLM response + Note over ServiceMgr,Agent: LLM suggests actions and tools to use + + loop Till LLM suggests to stop + Agent->>ServiceMgr: Request tool execution + Note over Agent,ServiceMgr: Agent calls specific tools via Service Manager + + ServiceMgr->>Tools: Execute tool/service + Note over ServiceMgr,Tools: File, code, MCP services, etc. + + Tools->>ServiceMgr: Return tool result + ServiceMgr->>Agent: Send tool result back + + + Agent->>ServiceMgr: Send tool results for next LLM call + Note over Agent,ServiceMgr: Agent reports tool execution results + + ServiceMgr->>LLM: Send results to LLM + LLM->>ServiceMgr: Return next steps or completion + ServiceMgr->>Agent: Forward LLM response + end + + Agent->>Codebolt: Task Completed, Send completion message + Codebolt->>User: Display final result + +``` + +## Creating Agents + +There are two main ways to create an agent in Codebolt: +- [Custom Agent](./2_custom-agent.md): Build an agent from scratch with your own logic and features. +- [Remix Agent](./3_remix-agent.md): Start from an existing agent and modify it to fit your needs. diff --git a/docs/developer/core/agents/2_custom-agent.md b/docs/developer/core/agents/2_custom-agent.md new file mode 100644 index 00000000..a7d44f78 --- /dev/null +++ b/docs/developer/core/agents/2_custom-agent.md @@ -0,0 +1,139 @@ +# Custom Agent + +Lets create Custom Agents + +- There are two way to create your agent + +## Sample Agent Flow Code + +Here's a complete example of how an agent handles a user request using the **CodeboltJS library**: + +```javascript +// Main agent entry point - handles incoming user messages +codebolt.onMessage((userMessage)=> { + try { + // 1. Extract context + const projectContext = await codebolt.project.getContext(); + + // 2. Get available tools for the agent + const tools = await codebolt.tools.listToolsFromToolBoxes(["codebolt", "filesystem"]); + + // 3. Prepare conversation with system context + const messages = [ + { + role: "system", + content: "You are a helpful coding assistant. Analyze the user request and use available tools to complete the task." + }, + { + role: "user", + content: `${userMessage}\n\nProject context: ${JSON.stringify(projectContext)}` + } + ]; + + // 4. Start conversation loop with LLM + let isTaskComplete = false; + let conversationHistory = [...messages]; + + while (!isTaskComplete) { + // Send request to LLM with available tools + const llmResponse = await codebolt.llm.chat(conversationHistory, tools); + + // 5. Process LLM response and execute tool calls + if (llmResponse.tool_calls && llmResponse.tool_calls.length > 0) { + // Execute each tool call requested by LLM + for (const toolCall of llmResponse.tool_calls) { + const toolResult = await codebolt.tools.executeToolCall(toolCall); + + // Add tool result to conversation + conversationHistory.push({ + role: "tool", + tool_call_id: toolCall.id, + content: JSON.stringify(toolResult) + }); + } + + // Get LLM's next response after tool execution + const followUpResponse = await codebolt.llm.chat(conversationHistory, tools); + + // Check if LLM indicates task is complete + if (followUpResponse.content.includes("task completed") || + !followUpResponse.tool_calls) { + isTaskComplete = true; + + // 6. Send final response to user + return followUpResponse.content; + } + } else { + // No tool calls needed, task is complete + isTaskComplete = true; + return llmResponse.content; + } + } + + } catch (error) { + console.error('Error in agent:', error); + } +}); +``` + + + +### Advance Using Prompt Builder classes + + +```js +const codebolt = require('@codebolt/codeboltjs').default; +const { + UserMessage, + SystemPrompt, + TaskInstruction, + Agent, + InitialPromptBuilder, + LLMOutputHandler, + FollowUpPromptBuilder +} = require("@codebolt/codeboltjs/utils"); + +codebolt.onMessage(async (userMessage) => { + try { + // Step 1: Build initial prompt with all context + const initialPromptBuilder = new InitialPromptBuilder(userMessage, codebolt); + let userPrompt = await initialPromptBuilder + .addMCPTools() // Add external tools + .addAgentTools() // Add sub-agents as tools + .addEnvironmentDetails() // Add system context + .addSystemPrompt('agent.yaml', 'test') // Load behavior instructions + .addTaskInstruction('task.yaml', 'main_task') // Load task definition + .buildInferenceParams(); // Assemble final prompt + + // Step 2: Get initial LLM response + let llmOutput = await codebolt.llm.inference(userPrompt); + let llmHandler = new LLMOutputHandler(llmOutput, codebolt); + + // Step 3: Continue conversation until completion + while (!llmHandler.isCompleted()) { + await llmHandler.sendMessageToUser(); // Send response to user + const toolResult = await llmHandler.runTools(); // Execute any tools + + // Step 4: Build follow-up prompt with context + const followUpPromptBuilder = new FollowUpPromptBuilder(); + userPrompt = await followUpPromptBuilder + .addPreviousConversation(userPrompt, llmOutput) + .addToolResult(toolResult) + .checkAndSummarizeConversationIfLong(30) + .build(); + + // Step 5: Continue the conversation + llmOutput = await codebolt.llm.inference(userPrompt); + llmHandler = new LLMOutputHandler(llmOutput, codebolt); + } + + console.log("βœ… Agent workflow completed successfully."); + } catch (error) { + console.error("❌ Agent error:", error); + codebolt.chat.sendMessage(error.message); + } +}); +``` + + +### How to run agent locally diff --git a/docs/developer/core/agents/3_remix-agent.md b/docs/developer/core/agents/3_remix-agent.md new file mode 100644 index 00000000..c04db596 --- /dev/null +++ b/docs/developer/core/agents/3_remix-agent.md @@ -0,0 +1,5 @@ +# Remixing Agents + +Remixing agents is the process of taking existing agents and modifying them to better fit your specific needs, coding standards, or workflow preferences. + +![Remix Agent](/img/custom-agent.png) diff --git a/docs/developer/core/agents/custom-agent.md b/docs/developer/core/agents/custom-agent.md deleted file mode 100644 index 4646cd7e..00000000 --- a/docs/developer/core/agents/custom-agent.md +++ /dev/null @@ -1,780 +0,0 @@ -# Creating Custom Agents - -This comprehensive guide will walk you through creating custom agents tailored to your specific development needs. Whether you want to automate code reviews, generate documentation, or implement custom workflows, this guide provides everything you need to build powerful, intelligent agents. - -## Introduction - -Custom agents are the key to unlocking Codebolt's full potential. While built-in agents handle common scenarios, custom agents can be tailored to your exact requirements, coding standards, and workflow preferences. - -By the end of this guide, you'll know how to: -- Design effective agent architectures -- Implement agents using multiple approaches -- Configure triggers and actions -- Handle complex workflows -- Debug and optimize agent performance - -## Agent Design Principles - -### 1. Single Responsibility -Each agent should have one clear purpose: -```javascript -// Good: Focused responsibility -const testGeneratorAgent = { - purpose: "Generate unit tests for JavaScript functions", - scope: "*.js files in src/ directory" -}; - -// Bad: Multiple responsibilities -const everythingAgent = { - purpose: "Review code, generate tests, update docs, deploy code" -}; -``` - -### 2. Configurable Behavior -Make your agents adaptable: -```json -{ - "name": "API Documentation Generator", - "settings": { - "docStyle": "jsdoc|swagger|openapi", - "includeExamples": true, - "autoUpdate": false, - "outputFormat": "markdown|html|json" - } -} -``` - -### 3. Graceful Error Handling -Agents should fail gracefully without breaking workflows: -```javascript -try { - const result = await performAnalysis(code); - return result; -} catch (error) { - logger.warn(`Analysis failed: ${error.message}`); - return { - success: false, - error: error.message, - fallback: "Manual review recommended" - }; -} -``` - -## Step-by-Step Agent Creation - -### Method 1: UI-Based Creation (Recommended for Beginners) - -#### Step 1: Access the Agent Builder -1. Open Codebolt AI Editor -2. Navigate to the "Agents" panel in the sidebar -3. Click "Create New Agent" -4. Select "Custom Agent" from the template options - -#### Step 2: Basic Configuration -``` -Agent Name: React Component Analyzer -Description: Analyzes React components for best practices and accessibility -Category: Code Quality -``` - -#### Step 3: Configure Triggers -``` -Trigger Type: File Save -File Patterns: - - src/components/**/*.jsx - - src/components/**/*.tsx -Exclude Patterns: - - **/*.test.js - - **/*.spec.js -``` - -#### Step 4: Define Actions -``` -Primary Action: Analyze Component -AI Model: GPT-4 -Prompt Template: | - Analyze this React component for: - 1. Best practices and patterns - 2. Accessibility issues - 3. Performance optimizations - 4. Code maintainability - - Component code: - {file_content} - - Provide specific, actionable suggestions. -``` - -#### Step 5: Configure Output -``` -Output Format: Suggestions List -Auto-apply: false -Show Notifications: true -Save Results: true -``` - -### Method 2: Configuration File Approach - -Create a comprehensive agent configuration file: - -```json -{ - "name": "React Component Analyzer", - "version": "1.0.0", - "description": "Analyzes React components for best practices and accessibility", - "author": "Your Team", - "category": "code-quality", - "icon": "react", - - "triggers": [ - { - "type": "file_save", - "patterns": [ - "src/components/**/*.{jsx,tsx}", - "src/pages/**/*.{jsx,tsx}" - ], - "exclude": [ - "**/*.test.{js,jsx,ts,tsx}", - "**/*.spec.{js,jsx,ts,tsx}", - "**/*.stories.{js,jsx,ts,tsx}" - ], - "debounce": 1000 - }, - { - "type": "manual", - "command": "analyze-component" - } - ], - - "workflow": [ - { - "name": "parse_component", - "type": "ast_analysis", - "config": { - "parser": "typescript", - "plugins": ["jsx", "decorators"] - } - }, - { - "name": "analyze_patterns", - "type": "ai_analysis", - "config": { - "model": "gpt-4", - "temperature": 0.2, - "max_tokens": 1000, - "prompt": "analyze_react_component.prompt" - } - }, - { - "name": "check_accessibility", - "type": "static_analysis", - "config": { - "rules": ["jsx-a11y/*"], - "severity": "warning" - } - }, - { - "name": "performance_check", - "type": "custom_analysis", - "config": { - "script": "./scripts/performance-analyzer.js" - } - } - ], - - "output": { - "format": "structured", - "template": "react_analysis.template", - "destinations": ["console", "file", "notification"], - "file_path": ".codebolt/analysis/{filename}.analysis.json" - }, - - "settings": { - "auto_apply_fixes": false, - "confidence_threshold": 0.8, - "max_suggestions": 10, - "learning_enabled": true, - "cache_results": true, - "cache_duration": "1h" - }, - - "dependencies": { - "ast-parser": "^2.0.0", - "eslint-plugin-jsx-a11y": "^6.7.0" - } -} -``` - -Register the agent: -```bash -codebolt agent register ./agents/react-component-analyzer.json -``` - -### Method 3: Programmatic Creation (TypeScript SDK) - -For maximum flexibility, create agents programmatically: - -```typescript -import { CodeboltAgent, TriggerType, ActionType } from '@codebolt/sdk'; - -class ReactComponentAnalyzer extends CodeboltAgent { - constructor() { - super({ - name: 'React Component Analyzer', - version: '1.0.0', - description: 'Analyzes React components for best practices' - }); - - this.addTrigger({ - type: TriggerType.FILE_SAVE, - patterns: ['src/components/**/*.{jsx,tsx}'], - debounce: 1000 - }); - - this.addAction({ - name: 'analyze_component', - type: ActionType.AI_ANALYSIS, - config: { - model: 'gpt-4', - prompt: this.getAnalysisPrompt() - } - }); - } - - private getAnalysisPrompt(): string { - return ` - Analyze this React component for: - - ## Code Quality - - Component structure and organization - - Props validation and TypeScript usage - - State management patterns - - Effect dependencies and cleanup - - ## Performance - - Unnecessary re-renders - - Expensive operations in render - - Missing memoization opportunities - - Bundle size implications - - ## Accessibility - - ARIA attributes and roles - - Keyboard navigation support - - Screen reader compatibility - - Color contrast and visual indicators - - ## Best Practices - - React hooks usage - - Component composition - - Error boundary implementation - - Testing considerations - - Provide specific, actionable recommendations with code examples where applicable. - `; - } - - async analyzeComponent(context: AnalysisContext): Promise { - try { - // Parse the component AST - const ast = await this.parseComponent(context.fileContent); - - // Extract component information - const componentInfo = this.extractComponentInfo(ast); - - // Run AI analysis - const aiAnalysis = await this.runAIAnalysis(context.fileContent); - - // Check accessibility - const a11yIssues = await this.checkAccessibility(ast); - - // Performance analysis - const perfIssues = await this.analyzePerformance(ast); - - return { - success: true, - suggestions: [ - ...aiAnalysis.suggestions, - ...a11yIssues.map(issue => ({ - type: 'accessibility', - severity: issue.severity, - message: issue.message, - line: issue.line, - fix: issue.suggestedFix - })), - ...perfIssues.map(issue => ({ - type: 'performance', - severity: issue.severity, - message: issue.message, - line: issue.line, - fix: issue.suggestedFix - })) - ], - metadata: { - componentName: componentInfo.name, - propsCount: componentInfo.props.length, - hooksUsed: componentInfo.hooks, - complexity: componentInfo.complexity - } - }; - } catch (error) { - return { - success: false, - error: error.message, - suggestions: [{ - type: 'error', - severity: 'info', - message: 'Automated analysis failed. Manual review recommended.' - }] - }; - } - } - - private async parseComponent(content: string) { - // Implementation for parsing React component - // Returns AST representation - } - - private extractComponentInfo(ast: any) { - // Extract component metadata from AST - // Returns component information object - } - - private async checkAccessibility(ast: any) { - // Run accessibility checks using eslint-plugin-jsx-a11y - // Returns array of accessibility issues - } - - private async analyzePerformance(ast: any) { - // Analyze for performance issues - // Returns array of performance suggestions - } -} - -// Register the agent -const agent = new ReactComponentAnalyzer(); -await agent.register(); -``` - -## Advanced Configuration Examples - -### Multi-Language Support Agent - -```json -{ - "name": "Polyglot Code Reviewer", - "triggers": [ - { - "type": "file_save", - "patterns": ["**/*.{js,ts,py,java,go,rs}"] - } - ], - "workflow": [ - { - "name": "detect_language", - "type": "language_detection", - "config": { - "fallback_to_extension": true - } - }, - { - "name": "language_specific_analysis", - "type": "conditional", - "branches": [ - { - "condition": "language === 'javascript' || language === 'typescript'", - "actions": ["eslint_check", "typescript_check", "security_scan"] - }, - { - "condition": "language === 'python'", - "actions": ["pylint_check", "black_format", "security_scan"] - }, - { - "condition": "language === 'java'", - "actions": ["checkstyle", "spotbugs", "pmd_analysis"] - }, - { - "condition": "language === 'go'", - "actions": ["go_fmt", "go_vet", "golint"] - }, - { - "condition": "language === 'rust'", - "actions": ["cargo_check", "clippy", "rustfmt"] - } - ] - } - ] -} -``` - -### Database Schema Agent - -```json -{ - "name": "Database Schema Guardian", - "triggers": [ - { - "type": "file_save", - "patterns": ["migrations/**/*.sql", "schema/**/*.sql"] - }, - { - "type": "git_commit", - "patterns": ["migrations/**", "schema/**"] - } - ], - "workflow": [ - { - "name": "parse_sql", - "type": "sql_parser", - "config": { - "dialect": "postgresql" - } - }, - { - "name": "validate_migration", - "type": "migration_validator", - "config": { - "check_breaking_changes": true, - "require_rollback": true, - "validate_indexes": true - } - }, - { - "name": "generate_documentation", - "type": "doc_generator", - "config": { - "format": "markdown", - "include_erd": true, - "output_path": "docs/database/" - } - }, - { - "name": "backup_check", - "type": "backup_validator", - "config": { - "require_backup_before_migration": true - } - } - ], - "integrations": { - "postgresql": { - "connection_string": "${DATABASE_URL}" - }, - "slack": { - "webhook": "${SLACK_WEBHOOK}", - "channel": "#database-changes" - } - } -} -``` - -### API Documentation Agent - -```typescript -class APIDocumentationAgent extends CodeboltAgent { - constructor() { - super({ - name: 'API Documentation Generator', - version: '2.0.0' - }); - - this.addTrigger({ - type: TriggerType.FILE_SAVE, - patterns: ['src/api/**/*.{js,ts}', 'src/routes/**/*.{js,ts}'] - }); - } - - async generateDocumentation(context: AnalysisContext): Promise { - const endpoints = await this.extractEndpoints(context.fileContent); - const openApiSpec = await this.generateOpenAPISpec(endpoints); - const examples = await this.generateExamples(endpoints); - - return { - openApiSpec, - examples, - postmanCollection: await this.generatePostmanCollection(endpoints), - readme: await this.generateReadme(endpoints) - }; - } - - private async extractEndpoints(content: string): Promise { - // Parse Express.js, Fastify, or other framework routes - // Extract method, path, parameters, responses - } - - private async generateOpenAPISpec(endpoints: APIEndpoint[]): Promise { - // Generate OpenAPI 3.0 specification - } - - private async generateExamples(endpoints: APIEndpoint[]): Promise { - // Generate realistic request/response examples - } -} -``` - -## Best Practices for Custom Agents - -### 1. Prompt Engineering - -**Effective Prompts:** -``` -Good: "Review this TypeScript function for type safety issues, performance problems, and suggest improvements with specific code examples." - -Bad: "Check this code." -``` - -**Use Context:** -```javascript -const prompt = ` -Review this ${fileExtension} file in a ${projectType} project. - -Project context: -- Framework: ${framework} -- Testing: ${testFramework} -- Linting: ${lintingRules} - -Code to review: -${fileContent} - -Focus on: -1. Framework-specific best practices -2. Project convention adherence -3. Integration with existing patterns -`; -``` - -### 2. Error Handling - -```typescript -class RobustAgent extends CodeboltAgent { - async execute(context: AgentContext): Promise { - try { - const result = await this.performAnalysis(context); - return this.formatSuccess(result); - } catch (error) { - if (error instanceof ValidationError) { - return this.formatValidationError(error); - } else if (error instanceof NetworkError) { - return this.formatNetworkError(error); - } else { - return this.formatUnknownError(error); - } - } - } - - private formatValidationError(error: ValidationError): AgentResult { - return { - success: false, - type: 'validation_error', - message: 'Input validation failed', - suggestions: [{ - type: 'fix', - message: error.message, - action: 'manual_review' - }] - }; - } -} -``` - -### 3. Performance Optimization - -```typescript -class OptimizedAgent extends CodeboltAgent { - private cache = new Map(); - - async analyze(context: AnalysisContext): Promise { - const cacheKey = this.generateCacheKey(context); - - if (this.cache.has(cacheKey)) { - return this.cache.get(cacheKey)!; - } - - const result = await this.performAnalysis(context); - this.cache.set(cacheKey, result); - - // Clean up old cache entries - if (this.cache.size > 100) { - this.cleanupCache(); - } - - return result; - } - - private generateCacheKey(context: AnalysisContext): string { - return `${context.filePath}:${context.fileHash}:${context.timestamp}`; - } -} -``` - -### 4. Testing Your Agent - -```typescript -describe('ReactComponentAnalyzer', () => { - let agent: ReactComponentAnalyzer; - - beforeEach(() => { - agent = new ReactComponentAnalyzer(); - }); - - test('should analyze functional component', async () => { - const mockComponent = ` - import React from 'react'; - - const Button = ({ onClick, children }) => { - return ; - }; - - export default Button; - `; - - const result = await agent.analyzeComponent({ - fileContent: mockComponent, - filePath: 'src/components/Button.jsx' - }); - - expect(result.success).toBe(true); - expect(result.suggestions).toContainEqual( - expect.objectContaining({ - type: 'accessibility', - message: expect.stringContaining('missing type attribute') - }) - ); - }); - - test('should handle malformed code gracefully', async () => { - const malformedCode = 'const Button = ('; - - const result = await agent.analyzeComponent({ - fileContent: malformedCode, - filePath: 'src/components/Broken.jsx' - }); - - expect(result.success).toBe(false); - expect(result.error).toBeDefined(); - }); -}); -``` - -## Debugging and Troubleshooting - -### Enable Debug Mode -```bash -# Debug specific agent -codebolt agent debug "React Component Analyzer" --verbose - -# Test agent with sample input -codebolt agent test "React Component Analyzer" \ - --file src/components/Button.jsx \ - --dry-run \ - --show-context -``` - -### Common Issues and Solutions - -**Agent Not Triggering** -```bash -# Check agent registration -codebolt agent list --detailed - -# Verify trigger patterns -codebolt agent inspect "React Component Analyzer" --triggers - -# Test pattern matching -codebolt agent test-pattern "src/components/**/*.jsx" --file "src/components/Button.jsx" -``` - -**Poor Analysis Quality** -1. Improve prompt specificity -2. Add more context to the analysis -3. Use examples in prompts -4. Implement feedback loops - -**Performance Issues** -1. Implement caching -2. Optimize trigger patterns -3. Use faster models for simple tasks -4. Implement result streaming - -### Monitoring Agent Performance - -```typescript -class MonitoredAgent extends CodeboltAgent { - private metrics = { - executions: 0, - totalTime: 0, - errors: 0, - successRate: 0 - }; - - async execute(context: AgentContext): Promise { - const startTime = Date.now(); - this.metrics.executions++; - - try { - const result = await super.execute(context); - this.updateSuccessMetrics(Date.now() - startTime); - return result; - } catch (error) { - this.updateErrorMetrics(Date.now() - startTime); - throw error; - } - } - - private updateSuccessMetrics(duration: number) { - this.metrics.totalTime += duration; - this.metrics.successRate = - (this.metrics.executions - this.metrics.errors) / this.metrics.executions; - } - - getMetrics() { - return { - ...this.metrics, - averageTime: this.metrics.totalTime / this.metrics.executions - }; - } -} -``` - -## Deployment and Distribution - -### Packaging Your Agent -```bash -# Create agent package -codebolt agent package ./agents/react-component-analyzer.json - -# Publish to agent registry -codebolt agent publish react-component-analyzer-1.0.0.cbag -``` - -### Sharing Agents -```json -{ - "name": "react-component-analyzer", - "version": "1.0.0", - "repository": "https://github.com/yourorg/codebolt-agents", - "license": "MIT", - "keywords": ["react", "components", "analysis", "accessibility"], - "codebolt": { - "minVersion": "1.0.0", - "categories": ["code-quality", "react"] - } -} -``` - -## Next Steps - -Now that you can create custom agents, explore: - -1. **[Remix Agents](remix-agent.md)** - Modify existing agents -2. **[Multi-Agent Systems](../multi-agents/overview.md)** - Coordinate multiple agents -3. **[Task Flow Integration](../task-flow/overview.md)** - Use agents in workflows -4. **[MCP Tools](../mcp-tools/overview.md)** - Extend agent capabilities - -## Community Resources - -- **Agent Templates**: [github.com/codebolt/agent-templates](https://github.com/codebolt/agent-templates) -- **Community Forum**: [community.codebolt.ai](https://community.codebolt.ai) -- **Agent Registry**: Browse and share agents with the community -- **Best Practices Guide**: Learn from experienced agent developers - -Start with simple agents and gradually add complexity as you become more comfortable with the concepts and tools. The key to successful agent development is iteration and continuous improvement based on real-world usage. diff --git a/docs/developer/core/agents/overview.md b/docs/developer/core/agents/overview.md deleted file mode 100644 index 685f904a..00000000 --- a/docs/developer/core/agents/overview.md +++ /dev/null @@ -1,345 +0,0 @@ -# Agents Overview - -Agents are the cornerstone of Codebolt AI Editor - intelligent, autonomous assistants that understand your code and can perform complex tasks on your behalf. Think of agents as specialized AI team members, each with their own expertise and responsibilities. - -## Introduction - -In traditional development environments, repetitive tasks like code reviews, testing, documentation generation, and refactoring consume significant time. Agents automate these tasks intelligently, learning from your codebase and adapting to your team's conventions. - -Unlike simple automation scripts, agents understand context, make decisions, and can handle complex, multi-step processes that would typically require human intervention. - -## How Agents Work - -### Step-by-Step Process - -1. **Trigger Detection**: Agents monitor for specific events (file saves, git commits, manual invocation) -2. **Context Analysis**: They analyze the current state of your code, project structure, and relevant history -3. **Decision Making**: Using AI models, agents determine the appropriate actions based on their configuration -4. **Action Execution**: Agents perform their designated tasks (code analysis, generation, modification, etc.) -5. **Result Communication**: They provide feedback, suggestions, or automatically apply changes -6. **Learning**: Agents learn from outcomes to improve future performance - -### Example Workflow -``` -File Saved (trigger) β†’ Agent Activated β†’ Code Analysis β†’ -Issue Detection β†’ Generate Fix β†’ Present Suggestion β†’ -User Approval β†’ Apply Changes β†’ Learn from Outcome -``` - -## Architecture - -### Core Components - -``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Trigger β”‚ β”‚ Agent Core β”‚ β”‚ Action β”‚ -β”‚ System │───▢│ (AI Brain) │───▢│ Executor β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ β”‚ β”‚ - β–Ό β–Ό β–Ό -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Event β”‚ β”‚ Context β”‚ β”‚ Result β”‚ -β”‚ Listeners β”‚ β”‚ Manager β”‚ β”‚ Handler β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -### Trigger System -- **File Events**: Save, create, delete, modify -- **Git Events**: Commit, push, pull, branch creation -- **Time-based**: Scheduled execution -- **Manual**: User-initiated commands -- **Custom**: API calls, webhooks, external integrations - -### AI Brain (Agent Core) -- **Language Models**: GPT-4, Claude, or custom models -- **Context Processing**: Understanding project structure and history -- **Decision Engine**: Determining appropriate actions -- **Memory System**: Learning from past interactions - -### Action Executor -- **Code Generation**: Creating new code based on specifications -- **Code Modification**: Editing existing code intelligently -- **Analysis**: Reviewing code for issues, patterns, or improvements -- **Integration**: Calling external APIs, tools, or services - -## Agent Lifecycle - -### 1. Initialization Phase -```javascript -// Agent registration and setup -const agent = new CodeboltAgent({ - name: "Code Reviewer", - version: "1.0.0", - triggers: ["file_save"], - capabilities: ["analyze", "suggest", "document"] -}); -``` - -### 2. Activation Phase -```javascript -// Triggered by event -agent.on('file_save', async (context) => { - const analysis = await agent.analyze(context.file); - return agent.generateSuggestions(analysis); -}); -``` - -### 3. Execution Phase -```javascript -// Processing and action execution -const result = await agent.execute({ - action: "review_code", - target: "src/components/Button.tsx", - context: projectContext -}); -``` - -### 4. Learning Phase -```javascript -// Feedback incorporation -agent.learn({ - action: "code_review", - feedback: "suggestion_accepted", - outcome: "bug_prevented" -}); -``` - -## Types of Agents - -### Built-in Agents - -#### Code Quality Agent -- **Purpose**: Maintains code standards and best practices -- **Triggers**: File save, pre-commit -- **Actions**: Linting, formatting, complexity analysis -- **Example Output**: "Consider extracting this function - it has high complexity" - -#### Security Agent -- **Purpose**: Identifies security vulnerabilities -- **Triggers**: File save, dependency changes -- **Actions**: Vulnerability scanning, secure coding suggestions -- **Example Output**: "Potential SQL injection vulnerability detected" - -#### Documentation Agent -- **Purpose**: Generates and maintains documentation -- **Triggers**: Function creation, API changes -- **Actions**: JSDoc generation, README updates, API documentation -- **Example Output**: Auto-generated comprehensive function documentation - -#### Test Agent -- **Purpose**: Creates and maintains test coverage -- **Triggers**: New function creation, code changes -- **Actions**: Unit test generation, test coverage analysis -- **Example Output**: Generated Jest test cases with edge case coverage - -### Custom Agents - -Custom agents are tailored to your specific needs and workflows: - -#### Database Migration Agent -```javascript -{ - "name": "DB Migration Helper", - "triggers": ["schema_change"], - "actions": [ - "generate_migration", - "validate_schema", - "backup_data" - ], - "integrations": ["postgresql", "mongodb"] -} -``` - -#### Deployment Agent -```javascript -{ - "name": "Auto Deployer", - "triggers": ["git_push_main"], - "actions": [ - "run_tests", - "build_application", - "deploy_staging", - "notify_team" - ], - "conditions": ["tests_pass", "build_success"] -} -``` - -## Agent Configuration - -### Basic Configuration -```json -{ - "name": "Code Reviewer", - "description": "Reviews code for best practices and potential issues", - "version": "1.0.0", - "author": "Your Team", - "triggers": [ - { - "type": "file_save", - "patterns": ["*.js", "*.ts", "*.jsx", "*.tsx"], - "exclude": ["node_modules/**", "dist/**"] - } - ], - "actions": [ - { - "type": "analyze_code", - "prompt": "Review this code for best practices, potential bugs, and suggest improvements", - "model": "gpt-4", - "max_suggestions": 5 - } - ], - "settings": { - "auto_apply": false, - "confidence_threshold": 0.8, - "learning_enabled": true - } -} -``` - -### Advanced Configuration -```json -{ - "name": "Full Stack Reviewer", - "triggers": [ - { - "type": "file_save", - "patterns": ["src/**/*.{js,ts,jsx,tsx}"] - }, - { - "type": "git_commit", - "branch_patterns": ["feature/*", "bugfix/*"] - } - ], - "workflow": [ - { - "step": "analyze_frontend", - "condition": "file_matches('src/components/**')", - "actions": ["review_react_patterns", "check_accessibility"] - }, - { - "step": "analyze_backend", - "condition": "file_matches('src/api/**')", - "actions": ["review_api_design", "check_security"] - }, - { - "step": "generate_tests", - "condition": "missing_tests()", - "actions": ["create_unit_tests", "create_integration_tests"] - } - ], - "integrations": { - "eslint": { "config": ".eslintrc.json" }, - "jest": { "config": "jest.config.js" }, - "sonarqube": { "project_key": "my-project" } - } -} -``` - -## Agent Communication - -Agents can communicate with each other to coordinate complex tasks: - -```javascript -// Agent A completes code review -const reviewResult = await codeReviewAgent.execute(context); - -// Agent A notifies Agent B -await testGeneratorAgent.notify('code_reviewed', { - file: context.file, - suggestions: reviewResult.suggestions, - complexity_score: reviewResult.complexity -}); - -// Agent B generates appropriate tests -const testResult = await testGeneratorAgent.execute({ - trigger: 'code_reviewed', - context: reviewResult -}); -``` - -## Best Practices - -### Agent Design -1. **Single Responsibility**: Each agent should have a clear, focused purpose -2. **Configurable Behavior**: Make agents adaptable to different projects and teams -3. **Graceful Degradation**: Handle failures without breaking the development workflow -4. **Performance Awareness**: Optimize for speed and resource usage - -### Trigger Configuration -1. **Specific Patterns**: Use precise file patterns to avoid unnecessary activations -2. **Exclude Directories**: Skip generated code, dependencies, and build artifacts -3. **Debouncing**: Prevent rapid-fire triggering during bulk operations -4. **Conditional Logic**: Add conditions to prevent inappropriate activations - -### Action Implementation -1. **Idempotent Operations**: Ensure actions can be safely repeated -2. **Clear Feedback**: Provide meaningful, actionable suggestions -3. **Context Preservation**: Maintain code style and project conventions -4. **Reversible Changes**: Allow users to undo agent modifications - -## Performance Considerations - -### Optimization Strategies -- **Lazy Loading**: Load agent components only when needed -- **Caching**: Store analysis results to avoid redundant processing -- **Parallel Execution**: Run independent agents simultaneously -- **Resource Limits**: Set boundaries on memory and CPU usage - -### Monitoring -```javascript -// Agent performance metrics -const metrics = await agent.getMetrics(); -console.log({ - executions: metrics.totalExecutions, - avgResponseTime: metrics.averageResponseTime, - successRate: metrics.successRate, - userSatisfaction: metrics.feedbackScore -}); -``` - -## Debugging Agents - -### Debug Mode -```bash -# Enable debug logging -codebolt agent debug --name "Code Reviewer" --verbose - -# Test agent with specific input -codebolt agent test "Code Reviewer" --file src/example.js --dry-run -``` - -### Common Issues and Solutions - -**Agent Not Triggering** -- Check trigger patterns and file paths -- Verify agent is enabled and properly registered -- Review exclusion patterns - -**Poor Suggestions** -- Improve prompt engineering -- Add more context to the agent configuration -- Increase training data or examples - -**Performance Issues** -- Optimize trigger patterns -- Implement caching strategies -- Reduce model complexity or switch to faster models - -## Next Steps - -Ready to create your own agents? Check out these guides: - -- [Creating Custom Agents](custom-agent.md) - Step-by-step agent development -- [Remixing Agents](remix-agent.md) - Modify existing agents for your needs -- [Multi-Agent Coordination](../multi-agents/overview.md) - Orchestrate multiple agents - -## Examples and Templates - -Visit our [GitHub repository](https://github.com/codebolt/agent-templates) for: -- Pre-built agent templates -- Real-world examples -- Community contributions -- Best practice implementations - -Agents are the foundation of an intelligent development workflow. Start with simple use cases and gradually build more sophisticated automation as you become comfortable with the concepts and tools. diff --git a/docs/developer/core/agents/remix-agent.md b/docs/developer/core/agents/remix-agent.md deleted file mode 100644 index 57a3776a..00000000 --- a/docs/developer/core/agents/remix-agent.md +++ /dev/null @@ -1,868 +0,0 @@ -# Remixing Agents - -Remixing agents is the process of taking existing agents and modifying them to better fit your specific needs, coding standards, or workflow preferences. Think of it as forking an open-source project - you start with a solid foundation and customize it to your requirements. - -## What is Agent Remixing? - -Agent remixing allows you to: -- **Customize existing agents** without building from scratch -- **Adapt agents to your team's conventions** and coding standards -- **Combine features** from multiple agents into one -- **Extend functionality** of built-in or community agents -- **Learn from existing implementations** while creating your own variants - -This approach is much faster than creating agents from scratch and helps you leverage the collective knowledge of the Codebolt community. - -## When to Remix vs. Create New - -### Remix When: -- βœ… An existing agent does 70%+ of what you need -- βœ… You want to modify behavior or add features to a working agent -- βœ… You need to adapt an agent to different languages or frameworks -- βœ… You want to learn how successful agents are structured -- βœ… You need to customize prompts or triggers for your workflow - -### Create New When: -- ❌ No existing agent addresses your use case -- ❌ Your requirements are completely different from existing agents -- ❌ You need a highly specialized, unique workflow -- ❌ The existing agent's architecture doesn't fit your needs - -## How to Remix Agents - -### Method 1: Using the Codebolt UI - -#### Step 1: Find an Agent to Remix -1. Open the **Agents** panel in Codebolt -2. Browse the **Community** or **Built-in** agent collections -3. Click on an agent that's close to your needs -4. Click **"Remix This Agent"** - -#### Step 2: Customize the Agent -The remix interface will open with the original agent's configuration: - -``` -Original Agent: "JavaScript Code Reviewer" -Your Remix: "TypeScript Enterprise Code Reviewer" - -Modifications: -βœ“ Change file patterns to include .ts and .tsx files -βœ“ Add enterprise-specific coding standards -βœ“ Include security scanning rules -βœ“ Add team notification integration -``` - -#### Step 3: Test and Deploy -1. **Preview Changes**: See what will be different -2. **Test with Sample Code**: Run the agent on test files -3. **Save Your Remix**: Give it a new name and description -4. **Deploy**: Activate the agent in your workspace - -### Method 2: Configuration File Remixing - -#### Step 1: Export the Original Agent -```bash -# Export an existing agent's configuration -codebolt agent export "JavaScript Code Reviewer" --output js-reviewer-original.json - -# View the configuration -cat js-reviewer-original.json -``` - -#### Step 2: Create Your Remix Configuration -```json -{ - "name": "TypeScript Enterprise Code Reviewer", - "version": "1.0.0", - "description": "Enterprise-grade TypeScript code review with security focus", - "basedOn": { - "agent": "JavaScript Code Reviewer", - "version": "2.1.0", - "modifications": "Added TypeScript support, enterprise rules, security scanning" - }, - - "triggers": [ - { - "type": "file_save", - "patterns": [ - "src/**/*.{ts,tsx}", - "lib/**/*.{ts,tsx}", - "apps/**/*.{ts,tsx}" - ], - "exclude": [ - "**/*.test.{ts,tsx}", - "**/*.spec.{ts,tsx}", - "node_modules/**", - "dist/**", - "build/**" - ], - "debounce": 2000 - }, - { - "type": "git_commit", - "branch_patterns": ["feature/*", "bugfix/*", "hotfix/*"] - } - ], - - "workflow": [ - { - "name": "typescript_check", - "type": "typescript_compiler", - "config": { - "strict": true, - "noImplicitAny": true, - "strictNullChecks": true - } - }, - { - "name": "enterprise_lint", - "type": "eslint", - "config": { - "extends": [ - "@company/eslint-config-enterprise", - "@typescript-eslint/recommended", - "@typescript-eslint/recommended-requiring-type-checking" - ], - "rules": { - "no-any": "error", - "explicit-function-return-type": "error", - "@typescript-eslint/no-unsafe-assignment": "error" - } - } - }, - { - "name": "security_scan", - "type": "security_analyzer", - "config": { - "rules": ["owasp-top-10", "enterprise-security"], - "severity_threshold": "medium" - } - }, - { - "name": "ai_review", - "type": "ai_analysis", - "config": { - "model": "gpt-4", - "temperature": 0.1, - "prompt": "enterprise_typescript_review.prompt" - } - } - ], - - "output": { - "format": "enterprise_report", - "destinations": ["console", "slack", "jira"], - "slack": { - "channel": "#code-reviews", - "webhook": "${SLACK_WEBHOOK_URL}" - }, - "jira": { - "project": "CR", - "issue_type": "Code Review" - } - }, - - "settings": { - "auto_apply_fixes": false, - "require_approval": true, - "confidence_threshold": 0.9, - "max_suggestions": 15, - "enterprise_mode": true - } -} -``` - -#### Step 3: Create Custom Prompt Template -``` -// enterprise_typescript_review.prompt -You are a senior TypeScript developer conducting a code review for an enterprise application. - -Review this TypeScript code for: - -## Type Safety & TypeScript Best Practices -- Proper type annotations and interfaces -- Avoidance of 'any' type -- Generic usage and constraints -- Strict null checks compliance -- Proper module declarations - -## Enterprise Code Standards -- SOLID principles adherence -- Design pattern implementation -- Error handling and logging -- Performance considerations -- Memory management - -## Security Considerations -- Input validation and sanitization -- SQL injection prevention -- XSS vulnerability assessment -- Authentication and authorization -- Data encryption requirements - -## Maintainability -- Code documentation and comments -- Test coverage recommendations -- Refactoring opportunities -- Technical debt identification - -## Team Conventions -- Naming conventions compliance -- File structure adherence -- Import/export patterns -- Configuration management - -Provide specific, actionable feedback with code examples where applicable. -Prioritize security and maintainability issues. -Include severity levels: Critical, High, Medium, Low. - -Code to review: -{file_content} - -Project context: -- Framework: {project_framework} -- TypeScript version: {typescript_version} -- Team size: {team_size} -``` - -#### Step 4: Register Your Remix -```bash -# Register the remixed agent -codebolt agent register typescript-enterprise-reviewer.json - -# Verify it's working -codebolt agent test "TypeScript Enterprise Code Reviewer" \ - --file src/components/UserProfile.tsx \ - --dry-run -``` - -### Method 3: Programmatic Remixing (TypeScript SDK) - -```typescript -import { CodeboltAgent, AgentRemixer } from '@codebolt/sdk'; - -class TypeScriptEnterpriseReviewer extends CodeboltAgent { - constructor() { - // Start with the base agent - const baseAgent = AgentRemixer.load('JavaScript Code Reviewer'); - - // Initialize with base configuration - super(baseAgent.getConfiguration()); - - // Apply customizations - this.customizeForTypeScript(); - this.addEnterpriseRules(); - this.addSecurityScanning(); - this.addTeamIntegrations(); - } - - private customizeForTypeScript() { - // Update file patterns - this.updateTriggers({ - patterns: ['src/**/*.{ts,tsx}', 'lib/**/*.{ts,tsx}'], - exclude: ['**/*.test.{ts,tsx}', '**/*.spec.{ts,tsx}'] - }); - - // Add TypeScript-specific workflow steps - this.addWorkflowStep({ - name: 'typescript_check', - type: 'typescript_compiler', - config: { - strict: true, - noImplicitAny: true, - strictNullChecks: true - } - }); - } - - private addEnterpriseRules() { - // Add enterprise linting rules - this.addWorkflowStep({ - name: 'enterprise_lint', - type: 'eslint', - config: { - extends: ['@company/eslint-config-enterprise'], - rules: { - 'no-any': 'error', - 'explicit-function-return-type': 'error' - } - } - }); - } - - private addSecurityScanning() { - this.addWorkflowStep({ - name: 'security_scan', - type: 'security_analyzer', - config: { - rules: ['owasp-top-10', 'enterprise-security'], - severity_threshold: 'medium' - } - }); - } - - private addTeamIntegrations() { - this.addOutputDestination({ - type: 'slack', - config: { - channel: '#code-reviews', - webhook: process.env.SLACK_WEBHOOK_URL - } - }); - - this.addOutputDestination({ - type: 'jira', - config: { - project: 'CR', - issue_type: 'Code Review' - } - }); - } - - // Override the analysis method to add enterprise-specific logic - async performAnalysis(context: AnalysisContext): Promise { - const baseResult = await super.performAnalysis(context); - - // Add enterprise-specific analysis - const enterpriseIssues = await this.runEnterpriseAnalysis(context); - const securityIssues = await this.runSecurityAnalysis(context); - - return { - ...baseResult, - suggestions: [ - ...baseResult.suggestions, - ...enterpriseIssues, - ...securityIssues - ], - metadata: { - ...baseResult.metadata, - enterpriseCompliance: this.checkEnterpriseCompliance(context), - securityScore: this.calculateSecurityScore(securityIssues) - } - }; - } - - private async runEnterpriseAnalysis(context: AnalysisContext): Promise { - // Implementation for enterprise-specific analysis - return []; - } - - private async runSecurityAnalysis(context: AnalysisContext): Promise { - // Implementation for security analysis - return []; - } -} - -// Register the remixed agent -const agent = new TypeScriptEnterpriseReviewer(); -await agent.register(); -``` - -## Practical Remix Examples - -### Example 1: Adapting a React Agent for Vue.js - -**Original Agent**: React Component Analyzer -**Remix Goal**: Analyze Vue.js components - -```json -{ - "name": "Vue Component Analyzer", - "basedOn": { - "agent": "React Component Analyzer", - "version": "1.5.0" - }, - - "triggers": [ - { - "type": "file_save", - "patterns": ["src/**/*.vue", "components/**/*.vue"] - } - ], - - "workflow": [ - { - "name": "parse_vue_component", - "type": "vue_parser", - "config": { - "parser": "vue-eslint-parser", - "parserOptions": { - "ecmaVersion": 2020, - "sourceType": "module" - } - } - }, - { - "name": "analyze_composition_api", - "type": "vue_analyzer", - "config": { - "checkCompositionAPI": true, - "checkReactivity": true, - "checkLifecycle": true - } - }, - { - "name": "ai_analysis", - "type": "ai_analysis", - "config": { - "prompt": "vue_component_analysis.prompt" - } - } - ] -} -``` - -### Example 2: Creating a Language-Specific Variant - -**Original Agent**: Generic Code Quality Checker -**Remix Goal**: Python-specific quality checker - -```typescript -class PythonQualityChecker extends CodeboltAgent { - constructor() { - const baseAgent = AgentRemixer.load('Generic Code Quality Checker'); - super(baseAgent.getConfiguration()); - - this.adaptForPython(); - } - - private adaptForPython() { - // Update file patterns - this.updateTriggers({ - patterns: ['**/*.py'], - exclude: ['**/__pycache__/**', '**/venv/**', '**/.pytest_cache/**'] - }); - - // Add Python-specific tools - this.addWorkflowStep({ - name: 'python_lint', - type: 'pylint', - config: { - rcfile: '.pylintrc', - disable: ['C0111', 'C0103'] - } - }); - - this.addWorkflowStep({ - name: 'python_format', - type: 'black', - config: { - line_length: 88, - target_version: ['py38', 'py39', 'py310'] - } - }); - - this.addWorkflowStep({ - name: 'python_security', - type: 'bandit', - config: { - severity: 'medium', - confidence: 'medium' - } - }); - - // Update AI prompt for Python-specific analysis - this.updateAIPrompt(` - You are reviewing Python code for: - 1. PEP 8 compliance and Python idioms - 2. Type hints usage (Python 3.5+) - 3. Exception handling best practices - 4. Performance optimizations - 5. Security vulnerabilities - 6. Testing recommendations - - Focus on Pythonic solutions and modern Python features. - `); - } -} -``` - -### Example 3: Team-Specific Customization - -**Original Agent**: API Documentation Generator -**Remix Goal**: Company-specific API documentation - -```json -{ - "name": "Acme Corp API Documentation Generator", - "basedOn": { - "agent": "API Documentation Generator", - "version": "2.0.0" - }, - - "settings": { - "company_standards": { - "api_version_format": "v{major}.{minor}", - "authentication_method": "JWT", - "response_format": "JSON:API", - "error_format": "RFC7807" - }, - - "documentation_template": { - "include_company_header": true, - "include_rate_limiting": true, - "include_sdk_examples": true, - "supported_languages": ["javascript", "python", "java", "csharp"] - }, - - "integrations": { - "confluence": { - "space_key": "API", - "parent_page": "API Documentation" - }, - "postman": { - "workspace_id": "${POSTMAN_WORKSPACE_ID}", - "collection_name": "Acme Corp APIs" - } - } - }, - - "workflow": [ - { - "name": "extract_endpoints", - "type": "api_extractor", - "config": { - "frameworks": ["express", "fastify", "koa"], - "include_middleware": true - } - }, - { - "name": "validate_company_standards", - "type": "company_validator", - "config": { - "check_naming_conventions": true, - "check_response_formats": true, - "check_error_handling": true - } - }, - { - "name": "generate_openapi", - "type": "openapi_generator", - "config": { - "version": "3.0.3", - "info": { - "title": "Acme Corp API", - "contact": { - "name": "API Team", - "email": "api-team@acmecorp.com" - }, - "license": { - "name": "Proprietary" - } - } - } - }, - { - "name": "generate_sdk_examples", - "type": "sdk_example_generator", - "config": { - "languages": ["javascript", "python", "java", "csharp"], - "include_authentication": true, - "include_error_handling": true - } - } - ] -} -``` - -## Advanced Remixing Techniques - -### Combining Multiple Agents - -```typescript -class FullStackReviewer extends CodeboltAgent { - constructor() { - super({ - name: 'Full Stack Code Reviewer', - version: '1.0.0' - }); - - // Combine features from multiple agents - this.combineAgents([ - 'React Component Analyzer', - 'Node.js API Reviewer', - 'Database Query Analyzer', - 'Security Scanner' - ]); - } - - private combineAgents(agentNames: string[]) { - agentNames.forEach(name => { - const agent = AgentRemixer.load(name); - - // Merge triggers - this.mergeTriggers(agent.getTriggers()); - - // Merge workflow steps - this.mergeWorkflowSteps(agent.getWorkflow()); - - // Merge settings - this.mergeSettings(agent.getSettings()); - }); - } - - async performAnalysis(context: AnalysisContext): Promise { - const results: AnalysisResult[] = []; - - // Run frontend analysis if it's a frontend file - if (this.isFrontendFile(context.filePath)) { - results.push(await this.runFrontendAnalysis(context)); - } - - // Run backend analysis if it's a backend file - if (this.isBackendFile(context.filePath)) { - results.push(await this.runBackendAnalysis(context)); - } - - // Run database analysis if it contains database queries - if (this.containsDatabaseQueries(context.fileContent)) { - results.push(await this.runDatabaseAnalysis(context)); - } - - // Always run security analysis - results.push(await this.runSecurityAnalysis(context)); - - return this.mergeResults(results); - } -} -``` - -### Creating Agent Variants - -```typescript -class AgentVariantFactory { - static createLanguageVariant(baseAgent: string, language: string): CodeboltAgent { - const config = AgentRemixer.load(baseAgent).getConfiguration(); - - const languageConfigs = { - typescript: { - patterns: ['**/*.{ts,tsx}'], - linter: 'typescript-eslint', - formatter: 'prettier' - }, - python: { - patterns: ['**/*.py'], - linter: 'pylint', - formatter: 'black' - }, - java: { - patterns: ['**/*.java'], - linter: 'checkstyle', - formatter: 'google-java-format' - }, - go: { - patterns: ['**/*.go'], - linter: 'golangci-lint', - formatter: 'gofmt' - } - }; - - const langConfig = languageConfigs[language]; - if (!langConfig) { - throw new Error(`Unsupported language: ${language}`); - } - - // Apply language-specific configuration - config.triggers = config.triggers.map(trigger => ({ - ...trigger, - patterns: langConfig.patterns - })); - - config.workflow = config.workflow.map(step => { - if (step.type === 'linter') { - return { ...step, config: { ...step.config, tool: langConfig.linter } }; - } - if (step.type === 'formatter') { - return { ...step, config: { ...step.config, tool: langConfig.formatter } }; - } - return step; - }); - - return new CodeboltAgent(config); - } - - static createFrameworkVariant(baseAgent: string, framework: string): CodeboltAgent { - // Similar implementation for framework-specific variants - } - - static createTeamVariant(baseAgent: string, teamConfig: TeamConfig): CodeboltAgent { - // Implementation for team-specific customizations - } -} - -// Usage -const tsReviewer = AgentVariantFactory.createLanguageVariant('Code Reviewer', 'typescript'); -const reactAnalyzer = AgentVariantFactory.createFrameworkVariant('Component Analyzer', 'react'); -``` - -## Best Practices for Remixing - -### 1. Document Your Changes -```json -{ - "name": "My Custom Agent", - "basedOn": { - "agent": "Original Agent", - "version": "1.0.0", - "modifications": [ - "Added TypeScript support", - "Integrated with company Slack", - "Added custom security rules", - "Modified prompt for enterprise context" - ] - }, - "changelog": [ - { - "version": "1.0.0", - "date": "2024-01-15", - "changes": ["Initial remix from Original Agent v1.0.0"] - }, - { - "version": "1.1.0", - "date": "2024-01-20", - "changes": ["Added security scanning", "Improved TypeScript support"] - } - ] -} -``` - -### 2. Test Thoroughly -```bash -# Test your remix with various file types -codebolt agent test "My Custom Agent" --file test-files/component.tsx -codebolt agent test "My Custom Agent" --file test-files/api.ts -codebolt agent test "My Custom Agent" --file test-files/utils.ts - -# Compare with original agent -codebolt agent compare "Original Agent" "My Custom Agent" --file test-files/sample.js -``` - -### 3. Maintain Compatibility -```typescript -class CompatibleRemix extends CodeboltAgent { - constructor() { - super({ - name: 'Compatible Remix', - compatibilityVersion: '1.0.0' - }); - } - - // Ensure backward compatibility - async execute(context: AgentContext): Promise { - try { - return await this.newImplementation(context); - } catch (error) { - // Fall back to original behavior - return await this.originalImplementation(context); - } - } -} -``` - -### 4. Version Your Remixes -```json -{ - "name": "Enterprise Code Reviewer", - "version": "2.1.0", - "basedOn": { - "agent": "Code Reviewer", - "version": "1.5.0" - }, - "compatibility": { - "codebolt_min_version": "1.0.0", - "node_min_version": "16.0.0" - } -} -``` - -## Sharing Your Remixes - -### Publishing to the Community -```bash -# Package your remix -codebolt agent package my-custom-agent.json - -# Publish to the community registry -codebolt agent publish my-custom-agent-1.0.0.cbag \ - --category "code-quality" \ - --tags "typescript,enterprise,security" \ - --description "Enterprise TypeScript code reviewer with security focus" -``` - -### Creating Agent Templates -```json -{ - "name": "Enterprise Agent Template", - "type": "template", - "description": "Template for creating enterprise-grade code review agents", - "parameters": [ - { - "name": "language", - "type": "select", - "options": ["typescript", "javascript", "python", "java"], - "required": true - }, - { - "name": "slack_webhook", - "type": "string", - "description": "Slack webhook URL for notifications" - }, - { - "name": "security_level", - "type": "select", - "options": ["basic", "enterprise", "government"], - "default": "enterprise" - } - ], - "template": "enterprise-agent-template.json" -} -``` - -## Troubleshooting Remix Issues - -### Common Problems and Solutions - -**Remix Not Working as Expected** -```bash -# Debug the remix process -codebolt agent debug-remix "Original Agent" "My Remix" --verbose - -# Check configuration differences -codebolt agent diff "Original Agent" "My Remix" -``` - -**Performance Issues** -```bash -# Profile agent performance -codebolt agent profile "My Remix" --duration 60s - -# Compare performance with original -codebolt agent benchmark "Original Agent" "My Remix" -``` - -**Trigger Pattern Issues** -```bash -# Test trigger patterns -codebolt agent test-triggers "My Remix" --directory src/ - -# Validate pattern syntax -codebolt agent validate-patterns "src/**/*.{ts,tsx}" -``` - -## Next Steps - -Now that you understand agent remixing: - -1. **Browse the Agent Registry** to find agents to remix -2. **Join the Community** to share your remixes and get feedback -3. **Explore Multi-Agent Systems** to coordinate your remixed agents -4. **Learn Advanced SDK Features** for more sophisticated remixing - -## Community Resources - -- **Agent Registry**: Browse remixable agents -- **Remix Gallery**: See examples of successful remixes -- **Community Forum**: Get help with remixing challenges -- **Template Library**: Use pre-built remix templates - -Remixing is a powerful way to quickly create agents that perfectly fit your needs. Start with small modifications and gradually build more sophisticated customizations as you become comfortable with the process. diff --git a/docs/developer/core/chats/overview.md b/docs/developer/core/chats/overview.md deleted file mode 100644 index 8d4f3df3..00000000 --- a/docs/developer/core/chats/overview.md +++ /dev/null @@ -1,610 +0,0 @@ -# Chats Overview - -Chats in Codebolt AI Editor provide an intelligent, context-aware conversational interface where you can get coding help, explore ideas, debug issues, and learn new concepts. Think of it as having a knowledgeable senior developer available 24/7 who understands your project, coding patterns, and development challenges. - -## Introduction - -The Chat interface goes beyond simple question-and-answer interactions. It's deeply integrated with your development environment, understanding your project structure, current files, recent changes, and development context. This enables highly relevant, actionable assistance that feels tailored to your specific situation. - -Whether you're stuck on a complex algorithm, need help with a framework you're learning, want to explore different implementation approaches, or need to debug a tricky issue, Chats provide intelligent assistance that adapts to your needs and expertise level. - -## How Chats Work - -### Context-Aware Intelligence - -The Chat system maintains rich context about your development environment: - -``` -Project Context: -β”œβ”€β”€ File Structure & Dependencies -β”œβ”€β”€ Current Code & Recent Changes -β”œβ”€β”€ Language & Framework Detection -β”œβ”€β”€ Coding Patterns & Conventions -β”œβ”€β”€ Error Messages & Stack Traces -└── Development History & Preferences -``` - -### Conversation Memory - -Chats remember the conversation flow and can reference: -- Previous questions and answers -- Code snippets you've shared -- Solutions you've tried -- Your preferences and skill level -- Related discussions across sessions - -### Multi-Modal Understanding - -The Chat interface can process and respond to: -- **Text queries** - Natural language questions and descriptions -- **Code snippets** - Analyze, debug, or improve code segments -- **Error messages** - Diagnose and provide solutions -- **Screenshots** - Understand UI issues or design questions -- **File references** - Discuss specific files or components - -## Usage Guide - -### Getting Started with Chats - -#### Opening Chat Interface -``` -Method 1: Click the Chat icon in the sidebar -Method 2: Use keyboard shortcut Ctrl+Shift+C (Cmd+Shift+C on macOS) -Method 3: Right-click in editor and select "Chat about this code" -``` - -#### Basic Interaction Patterns - -**Asking Questions:** -``` -You: How do I implement authentication in this React app? -AI: I can see you're using React with TypeScript. For authentication, I'd recommend... -``` - -**Code Analysis:** -``` -You: [Select code] Can you explain what this function does? -AI: This function implements a binary search algorithm. Let me break it down... -``` - -**Problem Solving:** -``` -You: I'm getting a "Cannot read property 'map' of undefined" error -AI: This error suggests you're trying to call map() on undefined. Let me help you debug... -``` - -### Effective Query Patterns - -#### Specific Technical Questions -``` -Good: "How do I implement JWT authentication in Express.js with refresh tokens?" -Better: "I need to add JWT auth to my Express API. I want access tokens with 15min expiry and refresh tokens. How should I structure this?" -``` - -#### Code Review and Improvement -``` -Good: "Can you review this code?" -Better: "Can you review this React component for performance issues and accessibility concerns?" -``` - -#### Learning and Exploration -``` -Good: "What's the difference between useEffect and useLayoutEffect?" -Better: "I'm building a custom hook that needs to measure DOM elements. Should I use useEffect or useLayoutEffect, and why?" -``` - -#### Debugging Help -``` -Good: "My code isn't working" -Better: "My API call is returning 401 unauthorized, but I'm passing the Bearer token in the Authorization header. Here's my fetch code: [code snippet]" -``` - -## Advanced Features - -### Code-Specific Conversations - -#### Contextual Code Discussion -When you select code and start a chat, the AI automatically understands: - -```typescript -// Selected code -const fetchUserData = async (userId: string) => { - const response = await fetch(`/api/users/${userId}`); - return response.json(); -}; - -// Your question: "How can I make this more robust?" -// AI Response: "I can see this function lacks error handling and type safety. Here are several improvements..." -``` - -#### Multi-File Context -``` -You: "This component isn't updating when the user data changes" -AI: "Looking at your UserProfile component and the useUser hook you're importing, I can see the issue. The hook isn't triggering re-renders because..." -``` - -### Project-Aware Assistance - -#### Framework-Specific Help -``` -// In a Next.js project -You: "How do I add server-side rendering to this page?" -AI: "Since you're using Next.js 13 with the app directory, you can use Server Components..." - -// In a React project -You: "How do I add server-side rendering to this page?" -AI: "For client-side React, you'll want to consider Next.js or implement SSR with a solution like..." -``` - -#### Dependency-Aware Suggestions -``` -You: "How do I add form validation?" -AI: "I see you're already using React Hook Form in your project. Here's how to add validation with your existing setup..." -``` - -### Learning and Exploration - -#### Interactive Learning -``` -You: "I want to learn about React hooks" -AI: "Great! Let's start with the basics and build up to advanced patterns. What's your current experience level with React?" - -You: "I know class components but hooks are new to me" -AI: "Perfect! Let's start by converting one of your existing class components to hooks. I can see you have a UserProfile class component - shall we use that as an example?" -``` - -#### Concept Exploration -``` -You: "What are the pros and cons of different state management solutions?" -AI: "For your React TypeScript project, here are the main options and how they'd fit your use case: - -**Redux Toolkit** - Good for complex state logic -- Pros: Predictable, great DevTools, scales well -- Cons: Boilerplate, learning curve -- Best for: Large apps with complex state interactions - -**Zustand** - Lightweight and flexible -- Pros: Simple API, TypeScript-friendly, small bundle -- Cons: Less opinionated, fewer patterns -- Best for: Medium apps that need flexibility - -Based on your project size and team experience, I'd recommend..." -``` - -### Debugging and Problem Solving - -#### Error Diagnosis -``` -You: "I'm getting this error: [paste stack trace]" -AI: "This error is occurring because of a race condition in your useEffect. Here's what's happening: - -1. Component mounts and starts API call -2. User navigates away quickly -3. Component unmounts but API call completes -4. setState is called on unmounted component - -Here are three ways to fix this..." -``` - -#### Performance Analysis -``` -You: "My app is running slowly, especially when scrolling through this list" -AI: "Looking at your component, I can identify several performance bottlenecks: - -1. **Expensive calculations in render** - You're calling `calculateStats()` on every render -2. **Missing memoization** - Child components re-render unnecessarily -3. **Large DOM nodes** - Rendering 1000+ items without virtualization - -Let's address these one by one..." -``` - -#### Architecture Guidance -``` -You: "How should I structure this feature?" -AI: "Based on your existing architecture, I'd suggest this structure: - -``` -src/features/user-management/ -β”œβ”€β”€ components/ -β”‚ β”œβ”€β”€ UserList.tsx -β”‚ β”œβ”€β”€ UserCard.tsx -β”‚ └── UserForm.tsx -β”œβ”€β”€ hooks/ -β”‚ β”œβ”€β”€ useUsers.ts -β”‚ └── useUserForm.ts -β”œβ”€β”€ services/ -β”‚ └── userService.ts -└── types/ - └── user.types.ts -``` - -This follows your established patterns and separates concerns clearly..." -``` - -## Customizing Chat Behavior - -### Conversation Settings - -```json -{ - "chat": { - "model": "gpt-4", - "temperature": 0.1, - "max_tokens": 2000, - "context_length": 8000, - - "personality": { - "style": "helpful_senior_developer", - "verbosity": "detailed_but_concise", - "code_examples": "always_include", - "explanations": "step_by_step" - }, - - "project_context": { - "include_file_structure": true, - "include_dependencies": true, - "include_recent_changes": true, - "max_context_files": 10 - }, - - "code_analysis": { - "auto_detect_language": true, - "include_best_practices": true, - "suggest_improvements": true, - "explain_complex_logic": true - } - } -} -``` - -### Custom Prompts and Templates - -```typescript -// Custom chat templates -const chatTemplates = { - codeReview: { - prompt: "Please review this code for:\n1. Best practices\n2. Performance issues\n3. Security concerns\n4. Maintainability\n\nCode:\n{code}", - context: "include_project_patterns" - }, - - debugging: { - prompt: "I'm experiencing this issue: {description}\n\nError: {error}\n\nCode: {code}\n\nPlease help me debug this step by step.", - context: "include_stack_trace" - }, - - learning: { - prompt: "I want to learn about {topic}. My current level is {experience_level}. Can you explain it with examples relevant to my {project_type} project?", - context: "include_project_context" - } -}; -``` - -### Team-Specific Customization - -```json -{ - "team_chat_config": { - "coding_standards": { - "style_guide": "company_style_guide.md", - "linting_rules": ".eslintrc.json", - "naming_conventions": "camelCase for variables, PascalCase for components" - }, - - "preferred_solutions": { - "state_management": "Redux Toolkit", - "testing": "Jest + React Testing Library", - "styling": "Styled Components", - "api_client": "Axios with custom interceptors" - }, - - "project_patterns": [ - "Always use TypeScript strict mode", - "Prefer functional components with hooks", - "Use custom hooks for business logic", - "Follow feature-based folder structure" - ] - } -} -``` - -## Integration with Development Workflow - -### IDE Integration - -#### Context Menu Integration -```typescript -// Right-click context menu options -const contextMenuItems = [ - { - label: "Explain this code", - action: (selectedCode) => openChat(`Explain this code:\n\n${selectedCode}`) - }, - { - label: "Find issues", - action: (selectedCode) => openChat(`Review this code for potential issues:\n\n${selectedCode}`) - }, - { - label: "Suggest improvements", - action: (selectedCode) => openChat(`How can I improve this code?\n\n${selectedCode}`) - }, - { - label: "Add error handling", - action: (selectedCode) => openChat(`Add comprehensive error handling to:\n\n${selectedCode}`) - } -]; -``` - -#### Inline Chat Suggestions -```typescript -// Intelligent suggestions based on context -const inlineSuggestions = { - onError: "Ask chat: 'How do I handle this error properly?'", - onComplexCode: "Ask chat: 'Can you help simplify this logic?'", - onPerformanceIssue: "Ask chat: 'How can I optimize this code?'", - onTestNeeded: "Ask chat: 'Help me write tests for this function'" -}; -``` - -### Agent Integration - -```typescript -class ChatIntegratedAgent extends CodeboltAgent { - async analyzeCode(code: string): Promise { - // Perform automated analysis - const issues = await this.staticAnalysis(code); - - if (issues.length > 0) { - // Start a chat conversation for complex issues - const chatResponse = await this.startChat(` - I found these issues in the code: - ${issues.map(i => `- ${i.message}`).join('\n')} - - Code: - ${code} - - Can you provide detailed solutions with examples? - `); - - return { - issues, - chatSuggestions: chatResponse.suggestions, - chatConversationId: chatResponse.conversationId - }; - } - - return { issues: [] }; - } -} -``` - -### Workflow Integration - -```yaml -# Task flow with chat integration -workflow: - - name: "code_review" - type: "agent" - agent: "code_reviewer" - - - name: "discuss_issues" - type: "chat" - condition: "issues_found" - prompt: "The code review found these issues: {issues}. Let's discuss solutions." - - - name: "implement_fixes" - type: "inline_edit" - depends_on: ["discuss_issues"] - prompt: "Implement the solutions we discussed in chat" -``` - -## Examples of Effective Queries - -### Code Understanding -``` -"Can you walk me through how this authentication middleware works?" - -"What's the purpose of this useCallback hook here?" - -"Why is this component re-rendering so much?" -``` - -### Problem Solving -``` -"I need to add real-time updates to this dashboard. What's the best approach?" - -"How do I handle race conditions in this async function?" - -"My tests are flaky - they pass sometimes and fail other times. How do I debug this?" -``` - -### Learning and Growth -``` -"I keep hearing about 'composition over inheritance' - can you show me examples in React?" - -"What are the security implications of storing JWT tokens in localStorage vs cookies?" - -"How do I migrate from class components to hooks without breaking existing functionality?" -``` - -### Architecture and Design -``` -"I'm building a feature that needs to work across multiple pages. How should I structure the state management?" - -"What's the best way to handle form validation in a multi-step wizard?" - -"How do I design an API that can handle both REST and GraphQL efficiently?" -``` - -## Best Practices - -### Writing Effective Queries - -#### Be Specific About Context -``` -Good: "How do I optimize this React component?" -Better: "This React component renders a list of 1000 items and scrolling is laggy. How do I optimize it?" -Best: "This UserList component renders 1000+ user cards and scrolling is laggy on mobile. I'm using map() to render each item. How do I implement virtualization or other optimizations?" -``` - -#### Include Relevant Code -``` -Good: "My API call isn't working" -Better: "My API call returns 500 error: [paste error]" -Best: "My API call returns 500 error. Here's my code: [code] and the error: [error]. I'm using Express.js with this middleware: [middleware code]" -``` - -#### Specify Your Goals -``` -Good: "How do I improve this code?" -Better: "How do I make this code more maintainable?" -Best: "This code will be maintained by junior developers. How do I make it more readable and self-documenting while maintaining performance?" -``` - -### Managing Conversations - -#### Use Follow-up Questions -``` -Initial: "How do I implement caching?" -Follow-up: "That's helpful! How do I handle cache invalidation when the user data changes?" -Follow-up: "What about handling cache misses gracefully?" -``` - -#### Reference Previous Context -``` -"Earlier you suggested using React Query. How does that integrate with the authentication pattern we discussed?" - -"Building on the error handling approach you showed, how do I add logging?" -``` - -#### Ask for Alternatives -``` -"You suggested using Redux. What would be a lighter-weight alternative?" - -"Are there any downsides to this approach? What are the trade-offs?" -``` - -## Troubleshooting - -### Common Issues - -#### Chat Not Understanding Context -**Problem**: Chat gives generic answers instead of project-specific advice -**Solutions**: -- Include more specific details about your project -- Reference specific files or frameworks you're using -- Provide code examples or error messages - -#### Conversations Losing Context -**Problem**: Chat forgets earlier parts of the conversation -**Solutions**: -- Summarize important points periodically -- Reference specific suggestions by summarizing them -- Start new conversations for distinctly different topics - -#### Getting Overly Complex Answers -**Problem**: Responses are too advanced or verbose -**Solutions**: -- Specify your experience level -- Ask for simpler explanations -- Request step-by-step breakdowns - -### Optimizing Chat Performance - -#### Reduce Response Time -```json -{ - "chat": { - "model": "gpt-3.5-turbo", // Faster than GPT-4 - "max_tokens": 1000, // Shorter responses - "temperature": 0.1 // More focused answers - } -} -``` - -#### Improve Context Relevance -```json -{ - "chat": { - "context": { - "include_recent_files": 5, - "include_error_logs": true, - "max_context_size": 4000 - } - } -} -``` - -## Advanced Chat Features - -### Multi-Turn Problem Solving - -``` -Turn 1: -You: "I need to build a user authentication system" -AI: "I'll help you design a secure authentication system. First, let me understand your requirements..." - -Turn 2: -You: "It's for a React app with a Node.js backend" -AI: "Great! For a React/Node.js setup, I recommend JWT tokens with refresh token rotation. Here's the architecture..." - -Turn 3: -You: "How do I handle token expiration gracefully?" -AI: "You'll want to implement automatic token refresh. Here's a React hook that handles this..." -``` - -### Collaborative Debugging - -``` -You: "My component isn't updating when props change" -AI: "Let me help debug this. Can you share the component code?" - -You: [shares component] -AI: "I see the issue - you're not including 'userData' in the useEffect dependency array. This means..." - -You: "I added it but now I get an infinite loop" -AI: "That's happening because userData is a new object on every render. Let's fix this with useMemo..." -``` - -### Code Generation Assistance - -``` -You: "I need a custom hook for managing form state with validation" -AI: "I'll create a useForm hook for you. What validation rules do you need?" - -You: "Required fields, email format, password strength" -AI: "Here's a complete useForm hook with those validations: - -```typescript -const useForm = (initialValues, validationRules) => { - // [Generated hook code with validation] -}; -``` - -Would you like me to show you how to use it in a component?" -``` - -## Next Steps - -Ready to make the most of Chats? Here's your learning path: - -1. **Start with Simple Questions**: Get comfortable with basic interactions -2. **Learn Effective Prompting**: Develop skills for getting better responses -3. **Integrate with Workflow**: Use chats as part of your development process -4. **Customize for Your Team**: Set up team-specific chat configurations -5. **Advanced Features**: Explore multi-turn conversations and complex problem solving - -## Related Features - -- [Inline Edit](../inline-edit/overview.md) - Use chat insights to guide code transformations -- [Agents](../agents/overview.md) - Create agents that can initiate chat conversations -- [Task Flow](../task-flow/overview.md) - Include chat interactions in automated workflows -- [Context](../context/overview.md) - Understand how context enhances chat responses - -## Community Resources - -- **Chat Templates**: Share effective prompt templates -- **Best Practices Guide**: Learn from experienced users -- **Use Case Examples**: See how others use chats effectively -- **Troubleshooting Forum**: Get help with chat-related issues - -Chats transform how you interact with your development environment. Instead of searching through documentation or Stack Overflow, you can have intelligent, context-aware conversations that provide immediate, relevant assistance tailored to your specific situation and project needs. diff --git a/docs/developer/core/cli/overview.md b/docs/developer/core/cli/overview.md index 0212d9cf..09309d8f 100644 --- a/docs/developer/core/cli/overview.md +++ b/docs/developer/core/cli/overview.md @@ -1,809 +1,29 @@ # CLI Overview -The Codebolt Command Line Interface (CLI) provides powerful command-line tools for automation, scripting, and integration with your existing development workflows. Whether you're building CI/CD pipelines, automating repetitive tasks, or managing large-scale operations, the CLI gives you programmatic access to all of Codebolt's features. - ## Introduction +The Codebolt CLI lets you work with Codebolt directly from your terminal. +With it, you can create agents, build MCP tools, publish agents, and manage your workspaceβ€”without opening the editor. -While Codebolt's visual interface is perfect for interactive development, many scenarios require command-line automation: -- **CI/CD Pipelines** - Integrate Codebolt into your build and deployment processes -- **Batch Operations** - Process multiple files or projects simultaneously -- **Scripting and Automation** - Create custom scripts for repetitive tasks -- **Remote Operations** - Manage Codebolt installations on servers -- **Integration Testing** - Validate agents and workflows programmatically -The CLI provides a comprehensive set of commands that mirror and extend the functionality available in the visual interface, designed for automation and scripting scenarios. ## Installation and Setup ### Installing the CLI +You can install the CLI globally: ```bash # Install globally via npm -npm install -g @codebolt/cli - -# Or install via Homebrew (macOS) -brew install codebolt/tap/codebolt-cli - -# Or download binary directly -curl -L https://releases.codebolt.ai/cli/latest/install.sh | bash -``` - -### Initial Configuration - -```bash -# Initialize Codebolt in your project -codebolt init - -# Authenticate with Codebolt Cloud (optional) -codebolt auth login - -# Configure default settings -codebolt config set editor.default_model gpt-4 -codebolt config set agents.auto_update true -codebolt config set workflows.parallel_execution true - -# Verify installation -codebolt --version -codebolt doctor # Check system health -``` - -## Core Commands - -### Project Management - -#### Project Initialization -```bash -# Initialize new Codebolt project -codebolt init [project-name] - --template react-typescript # Use project template - --agents basic # Include basic agents - --workflows ci-cd # Include CI/CD workflows - --config team # Use team configuration - -# Example: Create a new React project with full setup -codebolt init my-app \ - --template react-typescript \ - --agents "code-review,test-generator,security-scanner" \ - --workflows "ci-cd,code-quality" \ - --config ./team-config.json -``` - -#### Project Status and Information -```bash -# Show project status -codebolt status - --verbose # Detailed information - --json # JSON output format - -# Analyze project structure -codebolt analyze - --type complexity # Complexity analysis - --type dependencies # Dependency analysis - --type patterns # Pattern analysis - --output report.json # Save results - -# Get project insights -codebolt insights - --category performance # Performance insights - --category security # Security insights - --category maintainability # Maintainability insights -``` - -### Agent Management - -#### Agent Operations -```bash -# List available agents -codebolt agent list - --installed # Only installed agents - --category code-quality # Filter by category - --format table # Table format output - -# Install agents -codebolt agent install code-reviewer -codebolt agent install security-scanner@2.1.0 # Specific version -codebolt agent install ./custom-agent.json # Local agent - -# Run agents manually -codebolt agent run code-reviewer - --file src/components/Button.tsx # Target specific file - --config custom-config.json # Custom configuration - --output results.json # Save results - --dry-run # Preview without executing - -# Test agents -codebolt agent test code-reviewer - --input test-data.json - --expected expected-output.json - --timeout 30s - -# Agent development -codebolt agent create my-custom-agent - --template typescript # Use TypeScript template - --capabilities analyze,fix # Agent capabilities - --interactive # Interactive setup -``` - -#### Agent Configuration -```bash -# Configure agent settings -codebolt agent configure code-reviewer - --set confidence_threshold=0.8 - --set auto_apply=false - --set max_suggestions=10 - -# Export agent configuration -codebolt agent export code-reviewer --output code-reviewer-config.json - -# Import agent configuration -codebolt agent import code-reviewer-config.json - -# Update agents -codebolt agent update # Update all agents -codebolt agent update code-reviewer # Update specific agent -``` - -### Workflow Management - -#### Workflow Operations -```bash -# List workflows -codebolt workflow list - --status active # Filter by status - --category ci-cd # Filter by category - --format json # JSON output - -# Create new workflow -codebolt workflow create feature-development - --template full-stack # Use template - --interactive # Interactive setup - --from-file workflow.yaml # From configuration file - -# Execute workflows -codebolt workflow run ci-pipeline - --input '{"branch": "main", "environment": "staging"}' - --wait # Wait for completion - --follow # Follow execution logs - --timeout 30m # Set timeout - -# Schedule workflows -codebolt workflow schedule deploy-staging - --cron "0 2 * * 1-5" # Weekdays at 2 AM - --timezone UTC # Timezone - --enabled # Enable immediately -``` - -#### Workflow Monitoring -```bash -# Monitor workflow execution -codebolt workflow monitor ci-pipeline - --execution-id abc123 # Specific execution - --real-time # Real-time updates - --format json # JSON output - -# View workflow history -codebolt workflow history feature-development - --last 30d # Last 30 days - --status failed # Only failed executions - --export history.csv # Export to CSV - -# Analyze workflow performance -codebolt workflow analyze ci-pipeline - --metrics execution_time,success_rate - --period 7d - --output performance-report.json -``` - -### Code Operations +npm install -g codebolt-cli -#### Code Analysis -```bash -# Analyze code quality -codebolt analyze code - --path src/ # Target directory - --recursive # Include subdirectories - --exclude "**/*.test.js" # Exclude patterns - --rules eslint,security # Analysis rules - --format detailed # Output format - -# Generate code metrics -codebolt metrics - --type complexity # Complexity metrics - --type maintainability # Maintainability metrics - --threshold high # Only high-impact issues - --export metrics.json # Export results -``` - -#### Code Generation -```bash -# Generate code from prompts -codebolt generate component - --name UserProfile - --type react-typescript - --props "name:string,email:string,avatar?:string" - --output src/components/ - -# Generate tests -codebolt generate tests - --file src/utils/helpers.js - --framework jest - --coverage 100 - --output src/utils/helpers.test.js - -# Generate documentation -codebolt generate docs - --input src/api/ - --format markdown - --include-examples - --output docs/api/ -``` - -#### Code Transformation -```bash -# Batch code transformations -codebolt transform - --pattern "src/**/*.js" - --prompt "Convert to TypeScript with proper types" - --preview # Preview changes - --backup # Create backups - -# Refactor code -codebolt refactor - --file src/legacy/oldComponent.js - --target modern-react - --preserve-behavior - --add-tests - -# Format code -codebolt format - --path src/ - --style prettier - --fix # Fix formatting issues -``` - -## Advanced Usage - -### Batch Operations - -#### Processing Multiple Files -```bash -# Process all TypeScript files -codebolt batch process - --pattern "src/**/*.{ts,tsx}" - --agent code-reviewer - --parallel 4 # Process 4 files in parallel - --output-dir results/ - --continue-on-error # Don't stop on errors - -# Transform multiple projects -codebolt batch transform - --projects "projects/*/" - --prompt "Update to latest framework version" - --dry-run # Preview changes - --report transform-report.json -``` - -#### Bulk Agent Operations -```bash -# Run multiple agents on a project -codebolt batch agents - --agents "linter,security-scanner,test-generator" - --sequential # Run sequentially - --aggregate-results # Combine results - --output comprehensive-analysis.json -``` - -### CI/CD Integration - -#### GitHub Actions Integration -```yaml -# .github/workflows/codebolt.yml -name: Codebolt Analysis -on: [push, pull_request] - -jobs: - analyze: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Setup Codebolt CLI - run: | - npm install -g @codebolt/cli - codebolt auth login --token ${{ secrets.CODEBOLT_TOKEN }} - - - name: Run Code Analysis - run: | - codebolt workflow run code-analysis \ - --input '{"pr_number": "${{ github.event.pull_request.number }}"}' - --output analysis-results.json - - - name: Comment on PR - if: github.event_name == 'pull_request' - run: | - codebolt github comment-pr \ - --pr ${{ github.event.pull_request.number }} \ - --results analysis-results.json ``` -#### Jenkins Pipeline Integration -```groovy -pipeline { - agent any - - stages { - stage('Setup') { - steps { - sh 'npm install -g @codebolt/cli' - sh 'codebolt auth login --token $CODEBOLT_TOKEN' - } - } - - stage('Analysis') { - steps { - sh ''' - codebolt workflow run comprehensive-analysis \ - --input '{"branch": "'$BRANCH_NAME'", "build_number": "'$BUILD_NUMBER'"}' \ - --wait \ - --output analysis-results.json - ''' - } - } - - stage('Quality Gate') { - steps { - script { - def results = readJSON file: 'analysis-results.json' - if (results.quality_score < 8.0) { - error "Quality gate failed: score ${results.quality_score}" - } - } - } - } - } - - post { - always { - archiveArtifacts artifacts: 'analysis-results.json' - publishHTML([ - allowMissing: false, - alwaysLinkToLastBuild: true, - keepAll: true, - reportDir: 'reports', - reportFiles: 'codebolt-report.html', - reportName: 'Codebolt Analysis Report' - ]) - } - } -} -``` - -### Scripting and Automation - -#### Custom Scripts -```bash -#!/bin/bash -# deploy.sh - Automated deployment script - -set -e - -echo "Starting deployment process..." - -# Run pre-deployment checks -codebolt workflow run pre-deployment-checks \ - --input '{"environment": "production"}' \ - --wait - -if [ $? -ne 0 ]; then - echo "Pre-deployment checks failed" - exit 1 -fi - -# Build and test -codebolt workflow run build-and-test \ - --input '{"target": "production", "run_e2e": true}' \ - --wait - -# Deploy if tests pass -if [ $? -eq 0 ]; then - codebolt workflow run deploy-to-production \ - --input '{"version": "'$1'", "rollback_on_failure": true}' \ - --wait - - echo "Deployment completed successfully" -else - echo "Build or tests failed, deployment aborted" - exit 1 -fi -``` - -#### PowerShell Scripts (Windows) -```powershell -# analyze-and-report.ps1 -param( - [string]$ProjectPath = ".", - [string]$OutputDir = "./reports", - [string]$EmailRecipients = "" -) - -# Ensure output directory exists -New-Item -ItemType Directory -Force -Path $OutputDir - -# Run comprehensive analysis -Write-Host "Running comprehensive analysis..." -codebolt analyze comprehensive ` - --path $ProjectPath ` - --output "$OutputDir/analysis.json" ` - --format detailed - -# Generate reports -Write-Host "Generating reports..." -codebolt report generate ` - --input "$OutputDir/analysis.json" ` - --template comprehensive ` - --output "$OutputDir/report.html" - -# Send email if recipients specified -if ($EmailRecipients) { - codebolt notify email ` - --recipients $EmailRecipients ` - --subject "Code Analysis Report" ` - --body "Please find the attached analysis report." ` - --attachment "$OutputDir/report.html" -} - -Write-Host "Analysis complete. Reports saved to $OutputDir" -``` - -## Configuration Management - -### Configuration Files - -#### Global Configuration -```json -{ - "version": "1.0.0", - "defaults": { - "model": "gpt-4", - "temperature": 0.1, - "max_tokens": 2000, - "timeout": 300 - }, - "agents": { - "auto_update": true, - "parallel_execution": true, - "max_concurrent": 4, - "retry_attempts": 3 - }, - "workflows": { - "default_timeout": "30m", - "auto_retry": true, - "notification_channels": ["slack", "email"] - }, - "cli": { - "output_format": "table", - "verbose": false, - "color": true, - "progress_bars": true - } -} -``` - -#### Project Configuration -```yaml -# codebolt.yml -project: - name: "My Application" - type: "web" - language: "typescript" - framework: "react" - -agents: - enabled: - - code-reviewer - - security-scanner - - test-generator - - configurations: - code-reviewer: - confidence_threshold: 0.8 - auto_apply: false - focus_areas: ["performance", "security", "maintainability"] - - security-scanner: - severity_threshold: "medium" - include_dependencies: true - -workflows: - ci-pipeline: - triggers: - - push: ["main", "develop"] - - pull_request: ["main"] - - steps: - - name: "quality-check" - agents: ["code-reviewer", "security-scanner"] - - name: "test-generation" - agent: "test-generator" - condition: "quality_check.passed" - -cli: - aliases: - review: "agent run code-reviewer" - test: "workflow run test-suite" - deploy: "workflow run deployment" -``` - -### Environment Management - -```bash -# Manage multiple environments -codebolt env create staging -codebolt env create production - -# Switch environments -codebolt env use staging - -# Configure environment-specific settings -codebolt env config staging --set api_url=https://staging-api.company.com -codebolt env config production --set api_url=https://api.company.com - -# List environments -codebolt env list - -# Export environment configuration -codebolt env export staging --output staging-config.json -``` - -## Output Formats and Integration - -### Output Formats - -```bash -# JSON output for programmatic processing -codebolt analyze --format json | jq '.issues[] | select(.severity == "high")' - -# Table format for human readability -codebolt agent list --format table - -# CSV format for spreadsheet import -codebolt metrics --format csv --output metrics.csv - -# XML format for legacy systems -codebolt report generate --format xml --output report.xml - -# Custom format with templates -codebolt report generate --template custom-template.mustache --output custom-report.html -``` - -### Integration with External Tools - -#### Slack Integration -```bash -# Send results to Slack -codebolt analyze --format json | codebolt notify slack \ - --channel "#dev-team" \ - --template analysis-summary - -# Configure Slack webhook -codebolt config set integrations.slack.webhook_url $SLACK_WEBHOOK_URL -``` - -#### JIRA Integration -```bash -# Create JIRA issues from analysis results -codebolt analyze --format json | codebolt jira create-issues \ - --project DEV \ - --issue-type Bug \ - --assignee-field component_owner - -# Update existing JIRA issues -codebolt jira update-issue DEV-123 \ - --field status=Resolved \ - --comment "Fixed by automated analysis" -``` - -#### Database Integration -```bash -# Store results in database -codebolt analyze --format json | codebolt db store \ - --connection postgresql://user:pass@localhost/codebolt \ - --table analysis_results - -# Query historical data -codebolt db query \ - --connection postgresql://user:pass@localhost/codebolt \ - --query "SELECT * FROM analysis_results WHERE created_at > NOW() - INTERVAL '7 days'" -``` - -## Performance and Optimization - -### Parallel Processing - -```bash -# Process multiple files in parallel -codebolt batch process \ - --pattern "src/**/*.ts" \ - --parallel 8 \ - --chunk-size 10 - -# Parallel workflow execution -codebolt workflow run-parallel \ - --workflows "test-suite,security-scan,performance-test" \ - --max-concurrent 3 -``` - -### Caching and Incremental Processing - -```bash -# Enable caching for faster subsequent runs -codebolt config set cache.enabled true -codebolt config set cache.ttl 3600 # 1 hour - -# Incremental analysis (only changed files) -codebolt analyze --incremental \ - --since HEAD~1 # Since last commit - -# Clear cache when needed -codebolt cache clear -codebolt cache clear --pattern "analysis_*" -``` - -### Resource Management - -```bash -# Limit resource usage -codebolt config set limits.max_memory 2GB -codebolt config set limits.max_cpu_percent 50 -codebolt config set limits.timeout 600 # 10 minutes - -# Monitor resource usage -codebolt monitor resources --real-time -``` - -## Troubleshooting and Debugging - -### Debug Mode - -```bash -# Enable debug logging -codebolt --debug analyze code - -# Verbose output -codebolt --verbose workflow run ci-pipeline - -# Trace execution -codebolt --trace agent run code-reviewer -``` - -### Health Checks - -```bash -# System health check -codebolt doctor - --check-dependencies - --check-permissions - --check-connectivity - -# Agent health check -codebolt agent doctor code-reviewer - --test-configuration - --test-connectivity - --validate-permissions - -# Workflow validation -codebolt workflow validate ci-pipeline - --check-syntax - --check-dependencies - --dry-run -``` - -### Log Management - -```bash -# View logs -codebolt logs - --level error # Filter by level - --since 1h # Last hour - --follow # Follow new logs - --agent code-reviewer # Specific agent - -# Export logs -codebolt logs export - --format json - --output logs.json - --compress - -# Clear logs -codebolt logs clear --older-than 30d -``` - -## Best Practices - -### Script Organization - -```bash -# Use configuration files -codebolt --config ./configs/production.json analyze - -# Environment-specific configurations -codebolt --env production workflow run deploy - -# Modular scripts -#!/bin/bash -source ./scripts/common.sh -source ./scripts/codebolt-helpers.sh - -run_quality_checks() { - codebolt workflow run quality-checks --wait -} - -deploy_if_quality_passes() { - if run_quality_checks; then - codebolt workflow run deploy --env $1 - else - echo "Quality checks failed, deployment aborted" - exit 1 - fi -} -``` - -### Error Handling - -```bash -#!/bin/bash -set -e # Exit on any error - -# Function to handle errors -handle_error() { - echo "Error occurred in line $1" - codebolt notify slack --channel "#alerts" --message "Build failed at line $1" - exit 1 -} - -trap 'handle_error $LINENO' ERR - -# Your Codebolt operations here -codebolt workflow run ci-pipeline --wait -``` - -### Performance Optimization - -```bash -# Use parallel processing for independent operations -codebolt batch process \ - --pattern "src/**/*.ts" \ - --parallel $(nproc) \ - --chunk-size 5 - -# Cache results for repeated operations -codebolt config set cache.enabled true - -# Use incremental processing -codebolt analyze --incremental --since HEAD~1 -``` - -## Next Steps - -Ready to master the Codebolt CLI? Here's your learning path: - -1. **Start with Basic Commands**: Get familiar with core operations -2. **Learn Scripting**: Create automation scripts for your workflows -3. **Integrate with CI/CD**: Add Codebolt to your build pipelines -4. **Optimize Performance**: Use parallel processing and caching -5. **Advanced Integration**: Connect with external tools and services - -## Related Documentation - -- [Task Flow](../task-flow/overview.md) - Create workflows that can be executed via CLI -- [Agents](../agents/overview.md) - Manage and run agents from the command line -- [API Reference](../../api-reference.md) - Complete CLI command reference - -## Community Resources - -- **CLI Examples**: Real-world CLI usage examples -- **Script Library**: Community-contributed automation scripts -- **Integration Guides**: Step-by-step integration tutorials -- **Best Practices**: Learn from experienced CLI users +| Command | Description | +| -------------------------- | ------------------------------------- | +| `codebolt-cli login` | Log in to your Codebolt account | +| `codebolt-cli logout` | Log out from your account | +| `codebolt-cli version` | Check the installed CLI version | +| `codebolt-cli createagent` | Create a new agent | +| `codebolt-cli createtools` | Create a new MCP tool | +| `codebolt-cli publish` | Publish an agent | +| `codebolt-cli pull` | Pull agent or tool data from Codebolt | -The Codebolt CLI transforms how you integrate AI-powered development tools into your existing workflows. From simple automation scripts to complex CI/CD pipelines, the CLI provides the flexibility and power you need to scale Codebolt across your entire development process. diff --git a/docs/developer/core/context/overview.md b/docs/developer/core/context/overview.md deleted file mode 100644 index c8fa3415..00000000 --- a/docs/developer/core/context/overview.md +++ /dev/null @@ -1,915 +0,0 @@ -# Context Overview - -Context is the intelligence engine that powers Codebolt AI Editor's ability to provide smart, relevant assistance. It continuously analyzes and understands your project structure, coding patterns, dependencies, and development preferences to ensure that every AI interaction - whether through agents, chats, or inline edits - is informed by deep knowledge of your specific codebase and development context. - -## Introduction - -Traditional AI coding assistants provide generic suggestions that often don't fit your project's specific patterns, conventions, or architecture. Codebolt's Context system solves this by building and maintaining a comprehensive understanding of your development environment. - -Context enables Codebolt to: -- **Understand your project architecture** and suggest appropriate patterns -- **Respect your coding conventions** and maintain consistency -- **Leverage your existing dependencies** rather than suggesting new ones -- **Provide framework-specific guidance** based on your tech stack -- **Learn from your preferences** and adapt suggestions over time - -## How Context Works - -### Context Collection and Analysis - -``` -Project Files β†’ Parser β†’ AST Analysis β†’ Pattern Recognition β†’ Context Database - ↓ ↓ ↓ ↓ ↓ -Configuration β†’ Schema β†’ Dependencies β†’ Conventions β†’ Smart Suggestions -``` - -#### File System Analysis -```typescript -interface ProjectStructure { - rootPath: string; - fileTree: FileNode[]; - packageManagers: PackageManager[]; - configFiles: ConfigFile[]; - buildSystems: BuildSystem[]; - testFrameworks: TestFramework[]; -} - -class FileSystemAnalyzer { - async analyzeProject(rootPath: string): Promise { - const files = await this.scanDirectory(rootPath); - - return { - rootPath, - fileTree: await this.buildFileTree(files), - packageManagers: await this.detectPackageManagers(files), - configFiles: await this.findConfigFiles(files), - buildSystems: await this.detectBuildSystems(files), - testFrameworks: await this.detectTestFrameworks(files) - }; - } -} -``` - -#### Code Pattern Recognition -```typescript -interface CodingPatterns { - namingConventions: NamingConvention[]; - architecturalPatterns: ArchitecturalPattern[]; - designPatterns: DesignPattern[]; - errorHandlingPatterns: ErrorHandlingPattern[]; - testingPatterns: TestingPattern[]; -} - -class PatternAnalyzer { - async analyzeCodePatterns(files: SourceFile[]): Promise { - const patterns: CodingPatterns = { - namingConventions: [], - architecturalPatterns: [], - designPatterns: [], - errorHandlingPatterns: [], - testingPatterns: [] - }; - - for (const file of files) { - const ast = await this.parseFile(file); - - // Analyze naming patterns - patterns.namingConventions.push(...this.extractNamingConventions(ast)); - - // Identify architectural patterns - patterns.architecturalPatterns.push(...this.identifyArchitecturalPatterns(ast)); - - // Detect design patterns - patterns.designPatterns.push(...this.detectDesignPatterns(ast)); - - // Analyze error handling - patterns.errorHandlingPatterns.push(...this.analyzeErrorHandling(ast)); - - // Examine testing patterns - if (this.isTestFile(file)) { - patterns.testingPatterns.push(...this.analyzeTestPatterns(ast)); - } - } - - return this.consolidatePatterns(patterns); - } -} -``` - -#### Dependency Analysis -```typescript -interface DependencyGraph { - packages: PackageInfo[]; - internalDependencies: InternalDependency[]; - externalDependencies: ExternalDependency[]; - dependencyTree: DependencyNode[]; - unusedDependencies: string[]; - outdatedDependencies: OutdatedDependency[]; -} - -class DependencyAnalyzer { - async analyzeDependencies(projectPath: string): Promise { - const packageJson = await this.loadPackageJson(projectPath); - const lockFile = await this.loadLockFile(projectPath); - const sourceFiles = await this.loadSourceFiles(projectPath); - - const packages = await this.getPackageInfo(packageJson, lockFile); - const internalDeps = await this.analyzeInternalDependencies(sourceFiles); - const externalDeps = await this.analyzeExternalDependencies(sourceFiles, packages); - - return { - packages, - internalDependencies: internalDeps, - externalDependencies: externalDeps, - dependencyTree: await this.buildDependencyTree(internalDeps, externalDeps), - unusedDependencies: await this.findUnusedDependencies(packages, externalDeps), - outdatedDependencies: await this.checkOutdatedDependencies(packages) - }; - } -} -``` - -### Context Database Schema - -```typescript -interface ContextDatabase { - project: ProjectContext; - files: FileContext[]; - patterns: PatternContext; - dependencies: DependencyContext; - conventions: ConventionContext; - preferences: UserPreferences; - history: ContextHistory[]; -} - -interface ProjectContext { - id: string; - name: string; - type: 'web' | 'mobile' | 'desktop' | 'library' | 'cli'; - languages: Language[]; - frameworks: Framework[]; - architecture: ArchitecturalStyle; - teamSize: number; - complexity: ComplexityMetrics; -} - -interface FileContext { - path: string; - type: FileType; - language: string; - framework?: string; - purpose: FilePurpose; - complexity: number; - dependencies: string[]; - exports: ExportInfo[]; - patterns: PatternUsage[]; - lastModified: Date; -} -``` - -## Managing Project Context - -### Automatic Context Discovery - -Codebolt automatically analyzes your project to understand: - -#### Framework Detection -```typescript -class FrameworkDetector { - async detectFrameworks(projectPath: string): Promise { - const frameworks: Framework[] = []; - - // React detection - if (await this.hasPackage('react')) { - frameworks.push({ - name: 'React', - version: await this.getPackageVersion('react'), - features: await this.detectReactFeatures() - }); - } - - // Next.js detection - if (await this.hasPackage('next')) { - frameworks.push({ - name: 'Next.js', - version: await this.getPackageVersion('next'), - features: await this.detectNextFeatures() - }); - } - - // Express detection - if (await this.hasPackage('express')) { - frameworks.push({ - name: 'Express', - version: await this.getPackageVersion('express'), - features: await this.detectExpressFeatures() - }); - } - - return frameworks; - } - - private async detectReactFeatures(): Promise { - const features = []; - - if (await this.hasPackage('@types/react')) features.push('TypeScript'); - if (await this.hasPackage('react-router')) features.push('React Router'); - if (await this.hasPackage('redux')) features.push('Redux'); - if (await this.hasPackage('styled-components')) features.push('Styled Components'); - if (await this.findFilePattern('**/*.test.{js,jsx,ts,tsx}')) features.push('Testing'); - - return features; - } -} -``` - -#### Coding Convention Analysis -```typescript -class ConventionAnalyzer { - async analyzeConventions(sourceFiles: SourceFile[]): Promise { - const conventions: ConventionContext = { - naming: await this.analyzeNamingConventions(sourceFiles), - formatting: await this.analyzeFormattingConventions(sourceFiles), - structure: await this.analyzeStructureConventions(sourceFiles), - documentation: await this.analyzeDocumentationConventions(sourceFiles), - testing: await this.analyzeTestingConventions(sourceFiles) - }; - - return conventions; - } - - private async analyzeNamingConventions(files: SourceFile[]): Promise { - const samples = { - variables: [], - functions: [], - classes: [], - files: [], - directories: [] - }; - - for (const file of files) { - const ast = await this.parseFile(file); - samples.variables.push(...this.extractVariableNames(ast)); - samples.functions.push(...this.extractFunctionNames(ast)); - samples.classes.push(...this.extractClassNames(ast)); - samples.files.push(this.extractFileName(file)); - } - - return { - variables: this.detectNamingPattern(samples.variables), // camelCase, snake_case, etc. - functions: this.detectNamingPattern(samples.functions), - classes: this.detectNamingPattern(samples.classes), // PascalCase, etc. - files: this.detectNamingPattern(samples.files), // kebab-case, PascalCase, etc. - consistency: this.calculateConsistency(samples) - }; - } -} -``` - -### Context-Aware Features - -#### Smart Code Suggestions -```typescript -class ContextAwareCodeSuggestion { - async generateSuggestions(code: string, context: ProjectContext): Promise { - const suggestions: CodeSuggestion[] = []; - - // Framework-specific suggestions - if (context.frameworks.includes('React')) { - suggestions.push(...await this.getReactSuggestions(code, context)); - } - - if (context.frameworks.includes('Express')) { - suggestions.push(...await this.getExpressSuggestions(code, context)); - } - - // Pattern-based suggestions - const patterns = context.patterns.designPatterns; - if (patterns.includes('Repository Pattern')) { - suggestions.push(...await this.getRepositoryPatternSuggestions(code)); - } - - // Convention-based suggestions - suggestions.push(...await this.getConventionSuggestions(code, context.conventions)); - - return this.rankSuggestions(suggestions, context); - } - - private async getReactSuggestions(code: string, context: ProjectContext): Promise { - const suggestions = []; - - // Suggest hooks usage if functional components are preferred - if (context.conventions.componentStyle === 'functional') { - if (this.hasClassComponent(code)) { - suggestions.push({ - type: 'refactor', - message: 'Consider converting to functional component with hooks', - confidence: 0.8, - example: await this.generateFunctionalComponentExample(code) - }); - } - } - - // Suggest TypeScript if project uses TypeScript - if (context.languages.includes('TypeScript')) { - if (this.hasMissingTypes(code)) { - suggestions.push({ - type: 'enhancement', - message: 'Add TypeScript type annotations', - confidence: 0.9, - example: await this.addTypeAnnotations(code, context) - }); - } - } - - return suggestions; - } -} -``` - -#### Intelligent Import Suggestions -```typescript -class ImportSuggestionEngine { - async suggestImports(code: string, context: ProjectContext): Promise { - const missingImports = await this.findMissingImports(code); - const suggestions: ImportSuggestion[] = []; - - for (const missing of missingImports) { - // Check if it's available in project dependencies - const dependency = context.dependencies.find(dep => - dep.exports.includes(missing.identifier) - ); - - if (dependency) { - suggestions.push({ - identifier: missing.identifier, - source: dependency.name, - importType: this.determineImportType(dependency, missing.identifier), - confidence: 0.9 - }); - } else { - // Check internal modules - const internalModule = await this.findInternalModule(missing.identifier, context); - if (internalModule) { - suggestions.push({ - identifier: missing.identifier, - source: this.getRelativePath(code, internalModule.path), - importType: 'named', - confidence: 0.8 - }); - } - } - } - - return suggestions; - } -} -``` - -## Advanced Context Features - -### Context Sharing Across Agents - -```typescript -class SharedContextManager { - private contextStore: Map = new Map(); - - async shareContext(agentId: string, contextKey: string, data: ContextData): Promise { - const existingData = this.contextStore.get(contextKey); - - if (existingData) { - // Merge context data intelligently - const mergedData = await this.mergeContextData(existingData, data); - this.contextStore.set(contextKey, mergedData); - } else { - this.contextStore.set(contextKey, data); - } - - // Notify other agents of context update - await this.notifyAgents(contextKey, data, agentId); - } - - async getSharedContext(contextKey: string): Promise { - return this.contextStore.get(contextKey); - } - - private async mergeContextData(existing: ContextData, new_data: ContextData): Promise { - return { - ...existing, - ...new_data, - metadata: { - ...existing.metadata, - ...new_data.metadata, - lastUpdated: new Date(), - mergeCount: (existing.metadata?.mergeCount || 0) + 1 - } - }; - } -} -``` - -### Context-Driven Agent Behavior - -```typescript -class ContextAwareAgent extends CodeboltAgent { - async execute(input: AgentInput): Promise { - // Get project context - const projectContext = await this.getProjectContext(); - - // Adapt behavior based on context - if (projectContext.type === 'enterprise') { - return await this.executeEnterpriseMode(input, projectContext); - } else if (projectContext.type === 'startup') { - return await this.executeStartupMode(input, projectContext); - } - - return await this.executeDefaultMode(input, projectContext); - } - - private async executeEnterpriseMode(input: AgentInput, context: ProjectContext): Promise { - // Enterprise-specific behavior - const result = await this.performAnalysis(input); - - // Add enterprise-specific validations - result.validations.push(...await this.runComplianceChecks(input, context)); - result.validations.push(...await this.runSecurityChecks(input, context)); - result.validations.push(...await this.runScalabilityChecks(input, context)); - - return result; - } - - private async executeStartupMode(input: AgentInput, context: ProjectContext): Promise { - // Startup-specific behavior - focus on speed and simplicity - const result = await this.performAnalysis(input); - - // Prioritize quick wins and MVP features - result.suggestions = result.suggestions.filter(s => s.effort === 'low'); - result.suggestions.push(...await this.getMVPSuggestions(input, context)); - - return result; - } -} -``` - -### Dynamic Context Updates - -```typescript -class ContextUpdateEngine { - async updateContextFromChanges(changes: FileChange[]): Promise { - for (const change of changes) { - switch (change.type) { - case 'file_added': - await this.processNewFile(change.file); - break; - case 'file_modified': - await this.processModifiedFile(change.file, change.diff); - break; - case 'file_deleted': - await this.processDeletedFile(change.file); - break; - case 'dependency_added': - await this.processDependencyChange(change.dependency, 'added'); - break; - case 'dependency_removed': - await this.processDependencyChange(change.dependency, 'removed'); - break; - } - } - - // Recompute derived context - await this.recomputePatterns(); - await this.updateConventions(); - await this.refreshDependencyGraph(); - } - - private async processNewFile(file: SourceFile): Promise { - const fileContext = await this.analyzeFile(file); - - // Update project structure - await this.updateProjectStructure(fileContext); - - // Update patterns if this file introduces new ones - const newPatterns = await this.extractPatterns(file); - if (newPatterns.length > 0) { - await this.updatePatternDatabase(newPatterns); - } - - // Update dependency graph - const dependencies = await this.extractDependencies(file); - await this.updateDependencyGraph(dependencies); - } -} -``` - -## Context Configuration - -### Project-Level Configuration - -```json -{ - "context": { - "project": { - "type": "web_application", - "scale": "enterprise", - "team_size": "large", - "development_stage": "production" - }, - - "analysis": { - "include_patterns": [ - "src/**/*.{js,ts,jsx,tsx}", - "lib/**/*.{js,ts}", - "components/**/*.{jsx,tsx}" - ], - "exclude_patterns": [ - "node_modules/**", - "dist/**", - "build/**", - "coverage/**" - ], - "max_file_size": "1MB", - "deep_analysis": true - }, - - "conventions": { - "enforce_consistency": true, - "naming_conventions": { - "variables": "camelCase", - "functions": "camelCase", - "classes": "PascalCase", - "files": "kebab-case", - "directories": "kebab-case" - }, - "code_style": { - "indent_size": 2, - "quote_style": "single", - "semicolons": true, - "trailing_commas": true - } - }, - - "frameworks": { - "frontend": { - "primary": "React", - "version": "18.x", - "patterns": ["hooks", "functional_components"], - "state_management": "Redux Toolkit" - }, - "backend": { - "primary": "Express", - "version": "4.x", - "patterns": ["middleware", "router"], - "database": "PostgreSQL" - }, - "testing": { - "unit": "Jest", - "integration": "Supertest", - "e2e": "Cypress" - } - }, - - "preferences": { - "suggestion_verbosity": "detailed", - "auto_import": true, - "format_on_save": true, - "lint_on_save": true - } - } -} -``` - -### Team Context Sharing - -```json -{ - "team_context": { - "shared_conventions": { - "repository": "git@github.com:company/coding-standards.git", - "branch": "main", - "sync_interval": "daily" - }, - - "project_templates": { - "component_template": "templates/component.template.tsx", - "service_template": "templates/service.template.ts", - "test_template": "templates/test.template.ts" - }, - - "shared_patterns": { - "error_handling": "custom_error_classes", - "api_client": "axios_with_interceptors", - "state_management": "redux_toolkit_query", - "routing": "react_router_v6" - }, - - "team_preferences": { - "code_review_focus": ["security", "performance", "maintainability"], - "documentation_level": "comprehensive", - "test_coverage_minimum": 80 - } - } -} -``` - -### Context Synchronization - -```typescript -class TeamContextSync { - async syncWithTeam(teamConfig: TeamContextConfig): Promise { - // Pull latest team conventions - const teamConventions = await this.fetchTeamConventions(teamConfig.repository); - - // Merge with local context - const mergedContext = await this.mergeContexts( - await this.getLocalContext(), - teamConventions - ); - - // Update local context - await this.updateLocalContext(mergedContext); - - // Notify agents of context changes - await this.notifyAgentsOfContextUpdate(mergedContext); - } - - async shareContextWithTeam(contextUpdates: ContextUpdate[]): Promise { - // Filter updates that should be shared - const shareableUpdates = contextUpdates.filter(update => - update.scope === 'team' && update.approved - ); - - // Push to team repository - await this.pushContextUpdates(shareableUpdates); - - // Notify team members - await this.notifyTeamOfUpdates(shareableUpdates); - } -} -``` - -## Context Analytics and Insights - -### Project Health Metrics - -```typescript -class ContextAnalytics { - async generateProjectInsights(context: ProjectContext): Promise { - return { - codeQuality: await this.analyzeCodeQuality(context), - architecturalHealth: await this.analyzeArchitecture(context), - dependencyHealth: await this.analyzeDependencies(context), - teamConsistency: await this.analyzeConsistency(context), - technicalDebt: await this.analyzeTechnicalDebt(context), - recommendations: await this.generateRecommendations(context) - }; - } - - private async analyzeCodeQuality(context: ProjectContext): Promise { - return { - complexity: await this.calculateComplexity(context.files), - maintainability: await this.calculateMaintainability(context.files), - testCoverage: await this.calculateTestCoverage(context), - documentation: await this.calculateDocumentationCoverage(context), - codeSmells: await this.identifyCodeSmells(context.files) - }; - } - - private async analyzeArchitecture(context: ProjectContext): Promise { - return { - layerSeparation: await this.analyzeLayerSeparation(context), - dependencyCoupling: await this.analyzeCoupling(context.dependencies), - cohesion: await this.analyzeCohesion(context.files), - designPatternUsage: await this.analyzeDesignPatterns(context.patterns), - scalabilityIndicators: await this.analyzeScalability(context) - }; - } -} -``` - -### Context-Based Recommendations - -```typescript -class ContextRecommendationEngine { - async generateRecommendations(context: ProjectContext): Promise { - const recommendations: Recommendation[] = []; - - // Architecture recommendations - if (context.complexity.overall > 0.8) { - recommendations.push({ - type: 'architecture', - priority: 'high', - title: 'Consider breaking down complex modules', - description: 'Several modules have high complexity scores. Consider refactoring into smaller, more focused components.', - impact: 'maintainability', - effort: 'medium', - examples: await this.getComplexModuleExamples(context) - }); - } - - // Dependency recommendations - const outdatedDeps = context.dependencies.outdatedDependencies; - if (outdatedDeps.length > 0) { - recommendations.push({ - type: 'dependencies', - priority: 'medium', - title: 'Update outdated dependencies', - description: `${outdatedDeps.length} dependencies are outdated and may have security vulnerabilities.`, - impact: 'security', - effort: 'low', - examples: outdatedDeps.slice(0, 5).map(dep => ({ - name: dep.name, - current: dep.currentVersion, - latest: dep.latestVersion - })) - }); - } - - // Pattern recommendations - if (!context.patterns.includes('Error Handling')) { - recommendations.push({ - type: 'patterns', - priority: 'high', - title: 'Implement consistent error handling', - description: 'The project lacks consistent error handling patterns. Consider implementing a standardized approach.', - impact: 'reliability', - effort: 'medium', - examples: await this.getErrorHandlingExamples(context) - }); - } - - return recommendations; - } -} -``` - -## Context CLI Commands - -```bash -# Analyze project context -codebolt context analyze --depth deep --output report.json - -# View context summary -codebolt context summary --format table - -# Update context manually -codebolt context update --force-refresh - -# Export context for sharing -codebolt context export --include patterns,conventions --output team-context.json - -# Import team context -codebolt context import team-context.json --merge - -# Validate context consistency -codebolt context validate --check-conventions --check-patterns - -# Context-based recommendations -codebolt context recommendations --priority high --category architecture - -# Monitor context changes -codebolt context watch --real-time --notify-changes -``` - -## Best Practices - -### Maintaining Context Quality - -#### 1. Regular Context Updates -```typescript -// Automated context refresh -class ContextMaintenance { - async scheduleRegularUpdates(): Promise { - // Daily light refresh - schedule.scheduleJob('0 9 * * *', async () => { - await this.performLightContextUpdate(); - }); - - // Weekly deep analysis - schedule.scheduleJob('0 2 * * 0', async () => { - await this.performDeepContextAnalysis(); - }); - - // Monthly context cleanup - schedule.scheduleJob('0 1 1 * *', async () => { - await this.cleanupStaleContext(); - }); - } -} -``` - -#### 2. Context Validation -```typescript -class ContextValidator { - async validateContext(context: ProjectContext): Promise { - const issues: ValidationIssue[] = []; - - // Check for inconsistencies - if (context.conventions.naming.consistency < 0.8) { - issues.push({ - type: 'consistency', - severity: 'warning', - message: 'Naming conventions are inconsistent across the project' - }); - } - - // Validate dependencies - const circularDeps = await this.findCircularDependencies(context.dependencies); - if (circularDeps.length > 0) { - issues.push({ - type: 'architecture', - severity: 'error', - message: `Found ${circularDeps.length} circular dependencies` - }); - } - - return { - valid: issues.filter(i => i.severity === 'error').length === 0, - issues - }; - } -} -``` - -#### 3. Performance Optimization -```typescript -class ContextOptimization { - async optimizeContext(context: ProjectContext): Promise { - // Remove stale data - const cleanedContext = await this.removeStaleData(context); - - // Compress patterns - cleanedContext.patterns = await this.compressPatterns(cleanedContext.patterns); - - // Index for fast lookups - await this.createSearchIndexes(cleanedContext); - - return cleanedContext; - } -} -``` - -## Troubleshooting Context Issues - -### Common Problems - -#### Context Not Updating -```bash -# Force context refresh -codebolt context refresh --force - -# Clear context cache -codebolt context clear-cache - -# Rebuild context from scratch -codebolt context rebuild --full-analysis -``` - -#### Inconsistent Suggestions -```bash -# Validate context consistency -codebolt context validate --verbose - -# Check for conflicting patterns -codebolt context check-conflicts - -# Merge conflicting conventions -codebolt context resolve-conflicts --interactive -``` - -#### Performance Issues -```bash -# Optimize context database -codebolt context optimize - -# Reduce context scope -codebolt context configure --exclude "test/**" --exclude "docs/**" - -# Enable incremental updates -codebolt context configure --incremental-updates true -``` - -## Next Steps - -Ready to leverage Context for smarter AI assistance? Here's your path: - -1. **Understand Your Context**: Run context analysis to see what Codebolt knows about your project -2. **Configure Preferences**: Set up project-specific context configuration -3. **Monitor Context Quality**: Regularly validate and maintain context accuracy -4. **Share with Team**: Set up team context sharing for consistency -5. **Optimize Performance**: Fine-tune context settings for your project size - -## Related Features - -- [Agents](../agents/overview.md) - Agents use context for intelligent decision-making -- [Chats](../chats/overview.md) - Context powers relevant, project-aware conversations -- [Inline Edit](../inline-edit/overview.md) - Context ensures code transformations fit your patterns -- [Task Flow](../task-flow/overview.md) - Workflows adapt based on project context - -## Community Resources - -- **Context Patterns**: Share effective context configurations -- **Best Practices Guide**: Learn from experienced teams -- **Troubleshooting Forum**: Get help with context-related issues -- **Performance Tips**: Optimize context for large projects - -Context is the foundation that makes Codebolt truly intelligent. The better your context, the more relevant and helpful every AI interaction becomes. Start with basic context analysis and gradually refine your configuration as you learn what works best for your project and team. diff --git a/docs/developer/core/cotext.md b/docs/developer/core/cotext.md new file mode 100644 index 00000000..87609ee0 --- /dev/null +++ b/docs/developer/core/cotext.md @@ -0,0 +1,20 @@ +# Context + +Chat understands your codebase by analyzing: + +1. **Open files**: What you're currently viewing +2. **@ Symbol**: Use @ to select specific files, folders, and docs you want to reference +3. **# Symbol**: Used to select a specific agent from the agent marketplace + + +![@-symbol](/application/@-symbol.png) + +### Using @ to Select Content + +The @ symbol lets you precisely choose what Chat should focus on: + +- **@filename.js** - Select a specific file +- **@foldername/** - Include an entire folder +- **@docs/** - Reference documentation files + +![@-file](/application/@-file.png) diff --git a/docs/developer/core/inline-edit/overview.md b/docs/developer/core/inline-edit/overview.md deleted file mode 100644 index 8547b927..00000000 --- a/docs/developer/core/inline-edit/overview.md +++ /dev/null @@ -1,639 +0,0 @@ -# Inline Edit Overview - -Inline Edit is Codebolt AI Editor's signature feature that revolutionizes how you modify code. With a simple Ctrl+K (Cmd+K on macOS), you can transform any selected code using natural language descriptions, making code modification as intuitive as describing what you want in plain English. - -## Introduction - -Traditional code editing requires you to manually implement every change - typing, deleting, restructuring, and debugging. Inline Edit bridges the gap between intention and implementation, allowing you to describe what you want and letting AI handle the technical details. - -Whether you're refactoring a function, adding error handling, converting between programming paradigms, or implementing complex algorithms, Inline Edit understands your intent and generates the appropriate code while preserving your project's context and conventions. - -## How Inline Edit Works - -### The Basic Flow - -1. **Select Code**: Highlight the code you want to modify -2. **Activate Inline Edit**: Press Ctrl+K (Cmd+K on macOS) -3. **Describe Your Intent**: Type what you want to achieve -4. **Review Changes**: See the proposed modifications -5. **Accept or Iterate**: Apply changes or refine your request - -### Behind the Scenes - -``` -User Selection β†’ Context Analysis β†’ Intent Processing β†’ Code Generation β†’ Validation β†’ Presentation -``` - -#### Context Analysis -Inline Edit analyzes: -- Selected code structure and patterns -- Surrounding code context -- Project dependencies and imports -- Language-specific conventions -- Team coding standards - -#### Intent Processing -The AI model processes your natural language description: -- Identifies the transformation type -- Understands constraints and requirements -- Considers edge cases and error handling -- Plans the implementation approach - -#### Code Generation -Generates code that: -- Maintains existing functionality -- Follows project conventions -- Handles edge cases appropriately -- Integrates seamlessly with surrounding code - -## Detailed Examples - -### Example 1: Function Refactoring - -**Before:** -```javascript -function calculateTotal(items) { - var total = 0; - for (var i = 0; i < items.length; i++) { - total = total + items[i].price * items[i].quantity; - } - return total; -} -``` - -**Prompt:** "Convert to modern JavaScript with arrow functions and array methods" - -**After:** -```javascript -const calculateTotal = (items) => { - return items.reduce((total, item) => total + (item.price * item.quantity), 0); -}; -``` - -### Example 2: Adding Error Handling - -**Before:** -```javascript -async function fetchUserData(userId) { - const response = await fetch(`/api/users/${userId}`); - const data = await response.json(); - return data; -} -``` - -**Prompt:** "Add comprehensive error handling with custom error types" - -**After:** -```javascript -async function fetchUserData(userId) { - if (!userId) { - throw new Error('User ID is required'); - } - - try { - const response = await fetch(`/api/users/${userId}`); - - if (!response.ok) { - if (response.status === 404) { - throw new UserNotFoundError(`User with ID ${userId} not found`); - } else if (response.status >= 500) { - throw new ServerError('Internal server error occurred'); - } else { - throw new APIError(`Request failed with status ${response.status}`); - } - } - - const data = await response.json(); - return data; - } catch (error) { - if (error instanceof TypeError) { - throw new NetworkError('Network connection failed'); - } - throw error; - } -} - -class UserNotFoundError extends Error { - constructor(message) { - super(message); - this.name = 'UserNotFoundError'; - } -} - -class ServerError extends Error { - constructor(message) { - super(message); - this.name = 'ServerError'; - } -} - -class APIError extends Error { - constructor(message) { - super(message); - this.name = 'APIError'; - } -} - -class NetworkError extends Error { - constructor(message) { - super(message); - this.name = 'NetworkError'; - } -} -``` - -### Example 3: Algorithm Implementation - -**Before:** -```javascript -// TODO: Implement binary search -function findItem(arr, target) { - // Implementation needed -} -``` - -**Prompt:** "Implement efficient binary search with detailed comments" - -**After:** -```javascript -/** - * Performs binary search on a sorted array to find the target value - * @param {number[]} arr - Sorted array to search in - * @param {number} target - Value to find - * @returns {number} Index of target if found, -1 if not found - * @throws {Error} If array is not sorted - */ -function findItem(arr, target) { - if (!Array.isArray(arr)) { - throw new Error('First argument must be an array'); - } - - if (arr.length === 0) { - return -1; - } - - let left = 0; - let right = arr.length - 1; - - // Continue searching while search space exists - while (left <= right) { - // Calculate middle index, avoiding integer overflow - const mid = Math.floor(left + (right - left) / 2); - - if (arr[mid] === target) { - // Target found at middle index - return mid; - } else if (arr[mid] < target) { - // Target is in right half, narrow search space - left = mid + 1; - } else { - // Target is in left half, narrow search space - right = mid - 1; - } - } - - // Target not found in array - return -1; -} -``` - -### Example 4: Framework Conversion - -**Before (React Class Component):** -```javascript -class UserProfile extends React.Component { - constructor(props) { - super(props); - this.state = { - user: null, - loading: true, - error: null - }; - } - - componentDidMount() { - this.fetchUser(); - } - - fetchUser = async () => { - try { - const response = await fetch(`/api/users/${this.props.userId}`); - const user = await response.json(); - this.setState({ user, loading: false }); - } catch (error) { - this.setState({ error, loading: false }); - } - } - - render() { - const { user, loading, error } = this.state; - - if (loading) return
Loading...
; - if (error) return
Error: {error.message}
; - - return ( -
-

{user.name}

-

{user.email}

-
- ); - } -} -``` - -**Prompt:** "Convert to React hooks with TypeScript" - -**After:** -```typescript -import React, { useState, useEffect } from 'react'; - -interface User { - id: string; - name: string; - email: string; -} - -interface UserProfileProps { - userId: string; -} - -const UserProfile: React.FC = ({ userId }) => { - const [user, setUser] = useState(null); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - - useEffect(() => { - const fetchUser = async (): Promise => { - try { - setLoading(true); - setError(null); - - const response = await fetch(`/api/users/${userId}`); - if (!response.ok) { - throw new Error(`Failed to fetch user: ${response.statusText}`); - } - - const userData: User = await response.json(); - setUser(userData); - } catch (err) { - setError(err instanceof Error ? err : new Error('Unknown error occurred')); - } finally { - setLoading(false); - } - }; - - if (userId) { - fetchUser(); - } - }, [userId]); - - if (loading) { - return
Loading...
; - } - - if (error) { - return
Error: {error.message}
; - } - - if (!user) { - return
No user found
; - } - - return ( -
-

{user.name}

-

{user.email}

-
- ); -}; - -export default UserProfile; -``` - -## Advanced Usage - -### Context-Aware Transformations - -Inline Edit understands your project context and applies transformations accordingly: - -```typescript -// In a React project -const handleClick = () => { - // Prompt: "Add loading state and error handling" - // Result: React-specific state management with hooks -} - -// In a Node.js project -const handleRequest = () => { - // Same prompt: "Add loading state and error handling" - // Result: Express middleware patterns with try-catch -} - -// In a Python project -def handle_request(): - # Same prompt: "Add loading state and error handling" - # Result: Python exception handling with logging -``` - -### Multi-Language Support - -Inline Edit works across programming languages: - -```python -# Python example -def calculate_fibonacci(n): - # Prompt: "Optimize with memoization" - # Result: Efficient memoized implementation -``` - -```java -// Java example -public class DataProcessor { - // Prompt: "Add builder pattern" - // Result: Complete builder pattern implementation -} -``` - -```go -// Go example -func processData(data []string) { - // Prompt: "Add concurrent processing" - // Result: Goroutines with proper synchronization -} -``` - -### Custom Prompts and Templates - -#### Effective Prompt Patterns - -**Transformation Prompts:** -- "Convert to [pattern/style]" -- "Refactor using [technique]" -- "Optimize for [performance/readability/memory]" - -**Addition Prompts:** -- "Add [feature] with [constraints]" -- "Include [error handling/validation/logging]" -- "Implement [design pattern]" - -**Conversion Prompts:** -- "Convert from [old] to [new]" -- "Migrate to [framework/version]" -- "Translate to [language]" - -#### Advanced Prompt Examples - -```javascript -// Complex refactoring -const apiService = { - // Prompt: "Convert to class-based service with dependency injection, - // caching, retry logic, and comprehensive error handling" -}; - -// Performance optimization -function processLargeDataset(data) { - // Prompt: "Optimize for large datasets using streaming, - // worker threads, and memory-efficient algorithms" -} - -// Security enhancement -function handleUserInput(input) { - // Prompt: "Add input sanitization, XSS prevention, - // SQL injection protection, and rate limiting" -} -``` - -### Integration with Development Workflow - -#### Pre-commit Hooks -```bash -# Use Inline Edit in git hooks -git add . -codebolt inline-edit --auto-format --auto-optimize -git commit -m "Automated code improvements" -``` - -#### Code Review Integration -```javascript -// During code review, use Inline Edit to address feedback -function complexFunction() { - // Reviewer comment: "This function is too complex" - // Prompt: "Break down into smaller, single-responsibility functions - // with clear naming and documentation" -} -``` - -#### Pair Programming -```typescript -// Real-time collaboration with Inline Edit -interface UserService { - // Partner suggests: "Add caching layer" - // Prompt: "Add Redis caching with TTL and cache invalidation strategies" -} -``` - -## Tips and Limitations - -### Best Practices - -#### 1. Be Specific in Your Prompts -```javascript -// Good: "Convert to async/await with proper error handling and loading states" -// Bad: "Make this better" -``` - -#### 2. Provide Context When Needed -```javascript -// Good: "Refactor for React 18 with concurrent features and Suspense" -// Bad: "Update for latest React" -``` - -#### 3. Consider Edge Cases -```javascript -// Good: "Add validation for null, undefined, empty arrays, and invalid types" -// Bad: "Add validation" -``` - -#### 4. Specify Constraints -```javascript -// Good: "Optimize for mobile devices with limited memory and slow networks" -// Bad: "Optimize this" -``` - -### Common Use Cases - -#### Code Quality Improvements -- Converting legacy code to modern patterns -- Adding comprehensive error handling -- Implementing proper validation -- Adding documentation and comments - -#### Performance Optimizations -- Converting synchronous to asynchronous code -- Implementing caching strategies -- Optimizing database queries -- Adding lazy loading - -#### Security Enhancements -- Adding input sanitization -- Implementing authentication -- Adding rate limiting -- Securing API endpoints - -#### Framework Migrations -- Converting between React patterns -- Updating to new language versions -- Migrating between frameworks -- Modernizing legacy code - -### Limitations and Considerations - -#### When Inline Edit Works Best -- βœ… Well-defined transformations -- βœ… Standard programming patterns -- βœ… Code with clear context -- βœ… Incremental improvements - -#### When to Use Alternative Approaches -- ❌ Massive architectural changes -- ❌ Highly domain-specific logic -- ❌ Code requiring external system knowledge -- ❌ Complex business rule implementations - -#### Performance Considerations -- Inline Edit processes selections up to ~10,000 characters effectively -- Larger selections may need to be broken down -- Complex transformations may take 5-15 seconds -- Network connectivity affects response time - -## Troubleshooting - -### Common Issues and Solutions - -#### Issue: Inline Edit Not Activating -**Solutions:** -- Ensure text is selected before pressing Ctrl+K -- Check that Codebolt is properly initialized -- Verify keyboard shortcuts aren't conflicting -- Restart the editor if needed - -#### Issue: Unexpected Results -**Solutions:** -- Provide more specific prompts -- Include more context in your selection -- Break down complex requests into smaller parts -- Use examples in your prompts - -#### Issue: Performance Problems -**Solutions:** -- Reduce selection size for complex transformations -- Check network connectivity -- Clear Codebolt cache if needed -- Update to the latest version - -### Debug Mode - -```bash -# Enable debug mode for Inline Edit -codebolt config set inline-edit.debug true - -# View transformation logs -codebolt logs inline-edit --tail - -# Test prompts without applying changes -codebolt inline-edit test --prompt "your prompt here" --file example.js -``` - -## Advanced Configuration - -### Customizing Inline Edit Behavior - -```json -{ - "inline-edit": { - "model": "gpt-4", - "temperature": 0.1, - "max_tokens": 2000, - "timeout": 30000, - "auto_format": true, - "preserve_comments": true, - "context_lines": 10, - "custom_prompts": { - "optimize": "Optimize this code for performance and readability", - "secure": "Add comprehensive security measures and input validation", - "test": "Add unit tests with edge cases and error scenarios" - } - } -} -``` - -### Team Settings - -```json -{ - "team": { - "coding_standards": { - "style": "prettier", - "linting": "eslint", - "naming_convention": "camelCase", - "documentation": "jsdoc" - }, - "frameworks": { - "frontend": "react", - "backend": "node", - "database": "postgresql" - } - } -} -``` - -## Integration with Other Features - -### With Agents -```javascript -// Agents can use Inline Edit for code modifications -class RefactoringAgent extends CodeboltAgent { - async refactorCode(code, requirements) { - return await this.inlineEdit(code, `Refactor according to: ${requirements}`); - } -} -``` - -### With Task Flow -```yaml -workflow: - - name: "code_review" - action: "inline_edit" - prompt: "Address code review comments" - - name: "add_tests" - action: "inline_edit" - prompt: "Add comprehensive unit tests" -``` - -### With CLI -```bash -# Batch processing with Inline Edit -codebolt inline-edit batch \ - --pattern "src/**/*.js" \ - --prompt "Add JSDoc comments and error handling" \ - --output-dir refactored/ -``` - -## Next Steps - -Ready to master Inline Edit? Here's your learning path: - -1. **Start Simple**: Practice with basic transformations -2. **Learn Prompt Engineering**: Develop effective prompting skills -3. **Explore Advanced Features**: Use custom prompts and templates -4. **Integrate with Workflow**: Combine with agents and task flows -5. **Share Knowledge**: Document effective prompts for your team - -## Related Features - -- [Agents](../agents/overview.md) - Automate Inline Edit with intelligent agents -- [Task Flow](../task-flow/overview.md) - Include Inline Edit in automated workflows -- [Chats](../chats/overview.md) - Get help crafting effective prompts -- [CLI](../cli/overview.md) - Use Inline Edit programmatically - -Inline Edit transforms how you think about code modification. Instead of manually implementing every change, focus on describing your intent and let AI handle the implementation details. Start with simple transformations and gradually tackle more complex refactoring as you become comfortable with the feature. diff --git a/docs/developer/core/inlineedit.md b/docs/developer/core/inlineedit.md new file mode 100644 index 00000000..281d6461 --- /dev/null +++ b/docs/developer/core/inlineedit.md @@ -0,0 +1,8 @@ +# Inline Edit (Cntrl + K) +Use Inline Edit (Cmd/Ctrl+K) to quickly edit code or ask questions right in your editor. + +Just select some code, press Ctrl+K, and type your instructions or questions. + +![Ctrl+K](/img/ctrlK.png) + +- you have the option to accept or reject the suggested code changes. \ No newline at end of file diff --git a/docs/developer/core/mcp-tools/overview.md b/docs/developer/core/mcp-tools/overview.md deleted file mode 100644 index 167fd766..00000000 --- a/docs/developer/core/mcp-tools/overview.md +++ /dev/null @@ -1,1017 +0,0 @@ -# MCP Tools Overview - -MCP (Modular Component Plugin) Tools are the extension system that makes Codebolt AI Editor infinitely customizable and powerful. These tools integrate seamlessly with agents, workflows, and the core editor to provide specialized functionality, connect with external services, and extend Codebolt's capabilities far beyond its built-in features. - -## Introduction - -While Codebolt provides powerful built-in capabilities, every development team has unique needs, tools, and workflows. MCP Tools bridge this gap by providing a standardized way to: - -- **Integrate with external services** (databases, APIs, cloud platforms) -- **Add custom AI models** and specialized processing capabilities -- **Create domain-specific functionality** for your industry or use case -- **Connect with existing tools** in your development ecosystem -- **Extend agent capabilities** with new actions and data sources - -Think of MCP Tools as plugins that speak the same language as Codebolt's AI agents, allowing for seamless integration and intelligent automation. - -## How MCP Tools Work - -### Architecture Overview - -``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Codebolt β”‚ β”‚ MCP Runtime β”‚ β”‚ External β”‚ -β”‚ Agent/Editor │◄──►│ Environment │◄──►│ Service/Tool β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -### Core Components - -#### MCP Runtime -The runtime environment that manages tool lifecycle: -- Tool discovery and registration -- Capability negotiation -- Message routing and protocol handling -- Security and sandboxing -- Resource management - -#### Tool Interface -Standardized interface that all MCP Tools implement: -```typescript -interface MCPTool { - name: string; - version: string; - capabilities: ToolCapabilities; - - initialize(config: ToolConfig): Promise; - execute(request: ToolRequest): Promise; - cleanup(): Promise; -} -``` - -#### Communication Protocol -JSON-based protocol for tool communication: -```json -{ - "jsonrpc": "2.0", - "method": "tools/call", - "params": { - "name": "database_query", - "arguments": { - "query": "SELECT * FROM users WHERE active = true", - "database": "production" - } - }, - "id": 1 -} -``` - -## Developing MCP Tools - -### Basic Tool Structure - -```typescript -import { MCPTool, ToolCapabilities, ToolConfig, ToolRequest, ToolResponse } from '@codebolt/mcp-sdk'; - -export class DatabaseQueryTool implements MCPTool { - name = 'database_query'; - version = '1.0.0'; - capabilities: ToolCapabilities = { - actions: ['query', 'schema', 'migrate'], - inputs: ['sql', 'database_name'], - outputs: ['query_result', 'schema_info'], - requirements: ['database_connection'] - }; - - private connection: DatabaseConnection | null = null; - - async initialize(config: ToolConfig): Promise { - this.connection = await createDatabaseConnection({ - host: config.database.host, - port: config.database.port, - username: config.database.username, - password: config.database.password, - database: config.database.name - }); - - // Test connection - await this.connection.ping(); - } - - async execute(request: ToolRequest): Promise { - if (!this.connection) { - throw new Error('Database connection not initialized'); - } - - switch (request.action) { - case 'query': - return await this.executeQuery(request.arguments); - case 'schema': - return await this.getSchema(request.arguments); - case 'migrate': - return await this.runMigration(request.arguments); - default: - throw new Error(`Unknown action: ${request.action}`); - } - } - - private async executeQuery(args: any): Promise { - try { - const result = await this.connection!.query(args.query); - - return { - success: true, - data: { - rows: result.rows, - rowCount: result.rowCount, - fields: result.fields.map(f => ({ name: f.name, type: f.dataTypeID })) - }, - metadata: { - executionTime: result.executionTime, - query: args.query - } - }; - } catch (error) { - return { - success: false, - error: { - message: error.message, - code: error.code, - severity: 'error' - } - }; - } - } - - private async getSchema(args: any): Promise { - const tables = await this.connection!.query(` - SELECT table_name, column_name, data_type, is_nullable - FROM information_schema.columns - WHERE table_schema = $1 - ORDER BY table_name, ordinal_position - `, [args.schema || 'public']); - - return { - success: true, - data: { - schema: this.formatSchemaInfo(tables.rows) - } - }; - } - - async cleanup(): Promise { - if (this.connection) { - await this.connection.close(); - this.connection = null; - } - } -} -``` - -### Tool Configuration - -```json -{ - "name": "database_query", - "version": "1.0.0", - "description": "Execute database queries and schema operations", - "author": "Your Team", - "license": "MIT", - - "capabilities": { - "actions": ["query", "schema", "migrate"], - "inputs": ["sql", "database_name", "migration_file"], - "outputs": ["query_result", "schema_info", "migration_result"], - "requirements": ["database_connection"] - }, - - "configuration": { - "database": { - "type": "object", - "properties": { - "host": { "type": "string", "required": true }, - "port": { "type": "number", "default": 5432 }, - "username": { "type": "string", "required": true }, - "password": { "type": "string", "required": true, "sensitive": true }, - "name": { "type": "string", "required": true }, - "ssl": { "type": "boolean", "default": true } - } - }, - "query_timeout": { "type": "number", "default": 30000 }, - "max_rows": { "type": "number", "default": 1000 } - }, - - "permissions": { - "network": ["database.company.com:5432"], - "files": ["read:migrations/*.sql"], - "environment": ["DATABASE_*"] - } -} -``` - -## Examples of MCP Tools - -### Example 1: API Integration Tool - -```typescript -export class RestAPITool implements MCPTool { - name = 'rest_api'; - version = '1.0.0'; - capabilities = { - actions: ['get', 'post', 'put', 'delete', 'patch'], - inputs: ['url', 'headers', 'body', 'auth'], - outputs: ['response_data', 'status_code', 'headers'] - }; - - async execute(request: ToolRequest): Promise { - const { url, method, headers, body, auth } = request.arguments; - - const requestConfig: RequestConfig = { - url, - method: method.toUpperCase(), - headers: { - 'Content-Type': 'application/json', - ...headers - } - }; - - // Add authentication - if (auth) { - if (auth.type === 'bearer') { - requestConfig.headers['Authorization'] = `Bearer ${auth.token}`; - } else if (auth.type === 'basic') { - const encoded = btoa(`${auth.username}:${auth.password}`); - requestConfig.headers['Authorization'] = `Basic ${encoded}`; - } - } - - // Add body for POST/PUT/PATCH requests - if (['POST', 'PUT', 'PATCH'].includes(requestConfig.method) && body) { - requestConfig.body = JSON.stringify(body); - } - - try { - const response = await fetch(url, requestConfig); - const responseData = await response.json(); - - return { - success: true, - data: { - status: response.status, - statusText: response.statusText, - headers: Object.fromEntries(response.headers.entries()), - data: responseData - } - }; - } catch (error) { - return { - success: false, - error: { - message: error.message, - type: 'network_error' - } - }; - } - } -} -``` - -### Example 2: Cloud Storage Tool - -```typescript -export class CloudStorageTool implements MCPTool { - name = 'cloud_storage'; - version = '1.0.0'; - capabilities = { - actions: ['upload', 'download', 'list', 'delete', 'get_url'], - inputs: ['file_path', 'bucket', 'key', 'content'], - outputs: ['file_url', 'file_list', 'upload_result'] - }; - - private s3Client: S3Client | null = null; - - async initialize(config: ToolConfig): Promise { - this.s3Client = new S3Client({ - region: config.aws.region, - credentials: { - accessKeyId: config.aws.accessKeyId, - secretAccessKey: config.aws.secretAccessKey - } - }); - } - - async execute(request: ToolRequest): Promise { - switch (request.action) { - case 'upload': - return await this.uploadFile(request.arguments); - case 'download': - return await this.downloadFile(request.arguments); - case 'list': - return await this.listFiles(request.arguments); - case 'delete': - return await this.deleteFile(request.arguments); - case 'get_url': - return await this.getSignedUrl(request.arguments); - default: - throw new Error(`Unknown action: ${request.action}`); - } - } - - private async uploadFile(args: any): Promise { - try { - const command = new PutObjectCommand({ - Bucket: args.bucket, - Key: args.key, - Body: args.content, - ContentType: args.contentType || 'application/octet-stream' - }); - - const result = await this.s3Client!.send(command); - - return { - success: true, - data: { - etag: result.ETag, - location: `s3://${args.bucket}/${args.key}`, - url: `https://${args.bucket}.s3.amazonaws.com/${args.key}` - } - }; - } catch (error) { - return { - success: false, - error: { message: error.message, code: error.code } - }; - } - } -} -``` - -### Example 3: Code Analysis Tool - -```typescript -export class CodeAnalysisTool implements MCPTool { - name = 'code_analysis'; - version = '1.0.0'; - capabilities = { - actions: ['analyze_complexity', 'find_issues', 'generate_metrics', 'suggest_improvements'], - inputs: ['source_code', 'language', 'rules'], - outputs: ['analysis_result', 'metrics', 'suggestions'] - }; - - async execute(request: ToolRequest): Promise { - const { source_code, language, rules } = request.arguments; - - switch (request.action) { - case 'analyze_complexity': - return await this.analyzeComplexity(source_code, language); - case 'find_issues': - return await this.findIssues(source_code, language, rules); - case 'generate_metrics': - return await this.generateMetrics(source_code, language); - case 'suggest_improvements': - return await this.suggestImprovements(source_code, language); - default: - throw new Error(`Unknown action: ${request.action}`); - } - } - - private async analyzeComplexity(code: string, language: string): Promise { - const parser = this.getParser(language); - const ast = parser.parse(code); - - const complexity = this.calculateCyclomaticComplexity(ast); - const maintainabilityIndex = this.calculateMaintainabilityIndex(ast); - - return { - success: true, - data: { - cyclomaticComplexity: complexity, - maintainabilityIndex, - recommendation: complexity > 10 ? 'Consider refactoring' : 'Acceptable complexity', - details: { - functions: this.getFunctionComplexities(ast), - classes: this.getClassComplexities(ast) - } - } - }; - } - - private async findIssues(code: string, language: string, rules: any[]): Promise { - const issues: CodeIssue[] = []; - - // Run various analysis rules - for (const rule of rules) { - const ruleIssues = await this.runRule(code, language, rule); - issues.push(...ruleIssues); - } - - return { - success: true, - data: { - issues: issues.map(issue => ({ - type: issue.type, - severity: issue.severity, - message: issue.message, - line: issue.line, - column: issue.column, - rule: issue.rule, - suggestion: issue.suggestion - })), - summary: { - total: issues.length, - critical: issues.filter(i => i.severity === 'critical').length, - warning: issues.filter(i => i.severity === 'warning').length, - info: issues.filter(i => i.severity === 'info').length - } - } - }; - } -} -``` - -### Example 4: Visualization Tool - -```typescript -export class VisualizationTool implements MCPTool { - name = 'visualization'; - version = '1.0.0'; - capabilities = { - actions: ['create_chart', 'generate_diagram', 'create_dashboard'], - inputs: ['data', 'chart_type', 'options'], - outputs: ['chart_url', 'diagram_svg', 'dashboard_html'] - }; - - async execute(request: ToolRequest): Promise { - switch (request.action) { - case 'create_chart': - return await this.createChart(request.arguments); - case 'generate_diagram': - return await this.generateDiagram(request.arguments); - case 'create_dashboard': - return await this.createDashboard(request.arguments); - default: - throw new Error(`Unknown action: ${request.action}`); - } - } - - private async createChart(args: any): Promise { - const { data, chart_type, options } = args; - - // Create chart using a charting library (e.g., Chart.js, D3.js) - const chartConfig = { - type: chart_type, - data: { - labels: data.labels, - datasets: data.datasets - }, - options: { - responsive: true, - plugins: { - title: { - display: true, - text: options.title || 'Chart' - } - }, - ...options - } - }; - - // Generate chart image or return configuration - const chartUrl = await this.generateChartImage(chartConfig); - - return { - success: true, - data: { - chart_url: chartUrl, - config: chartConfig, - type: chart_type - } - }; - } - - private async generateDiagram(args: any): Promise { - const { diagram_type, nodes, edges, options } = args; - - let svg: string; - - switch (diagram_type) { - case 'flowchart': - svg = await this.createFlowchart(nodes, edges, options); - break; - case 'sequence': - svg = await this.createSequenceDiagram(nodes, edges, options); - break; - case 'class': - svg = await this.createClassDiagram(nodes, edges, options); - break; - default: - throw new Error(`Unsupported diagram type: ${diagram_type}`); - } - - return { - success: true, - data: { - svg, - diagram_type, - nodes: nodes.length, - edges: edges.length - } - }; - } -} -``` - -## Integrating MCP Tools with Agents - -### Agent Tool Usage - -```typescript -class DataAnalysisAgent extends CodeboltAgent { - private dbTool: MCPTool; - private chartTool: MCPTool; - - async initialize(): Promise { - this.dbTool = await this.loadTool('database_query'); - this.chartTool = await this.loadTool('visualization'); - } - - async analyzeUserMetrics(request: AnalysisRequest): Promise { - // Query database for user metrics - const queryResult = await this.dbTool.execute({ - action: 'query', - arguments: { - query: 'SELECT date, active_users, new_signups FROM user_metrics WHERE date >= $1', - params: [request.startDate] - } - }); - - if (!queryResult.success) { - throw new Error(`Database query failed: ${queryResult.error.message}`); - } - - // Create visualization - const chartResult = await this.chartTool.execute({ - action: 'create_chart', - arguments: { - chart_type: 'line', - data: { - labels: queryResult.data.rows.map(row => row.date), - datasets: [ - { - label: 'Active Users', - data: queryResult.data.rows.map(row => row.active_users), - borderColor: 'blue' - }, - { - label: 'New Signups', - data: queryResult.data.rows.map(row => row.new_signups), - borderColor: 'green' - } - ] - }, - options: { - title: 'User Metrics Over Time' - } - } - }); - - return { - metrics: queryResult.data.rows, - chart_url: chartResult.data.chart_url, - insights: await this.generateInsights(queryResult.data.rows) - }; - } -} -``` - -### Multi-Tool Workflows - -```typescript -class DeploymentAgent extends CodeboltAgent { - async deployApplication(config: DeploymentConfig): Promise { - const results: any[] = []; - - // 1. Run tests using test runner tool - const testResult = await this.useTool('test_runner', { - action: 'run_tests', - arguments: { test_suite: 'full', coverage: true } - }); - - if (!testResult.success || testResult.data.coverage < config.minCoverage) { - throw new Error('Tests failed or insufficient coverage'); - } - - // 2. Build application using build tool - const buildResult = await this.useTool('build_system', { - action: 'build', - arguments: { environment: config.environment, optimize: true } - }); - - if (!buildResult.success) { - throw new Error(`Build failed: ${buildResult.error.message}`); - } - - // 3. Upload to cloud storage - const uploadResult = await this.useTool('cloud_storage', { - action: 'upload', - arguments: { - bucket: config.deploymentBucket, - key: `releases/${config.version}/app.tar.gz`, - content: buildResult.data.artifact - } - }); - - // 4. Deploy to infrastructure - const deployResult = await this.useTool('infrastructure', { - action: 'deploy', - arguments: { - artifact_url: uploadResult.data.url, - environment: config.environment, - replicas: config.replicas - } - }); - - // 5. Notify team via communication tool - await this.useTool('notifications', { - action: 'send_message', - arguments: { - channel: '#deployments', - message: `Successfully deployed ${config.version} to ${config.environment}` - } - }); - - return { - success: true, - version: config.version, - environment: config.environment, - deployment_url: deployResult.data.url - }; - } -} -``` - -## Tool Discovery and Management - -### Tool Registry - -```typescript -class MCPToolRegistry { - private tools: Map = new Map(); - private toolConfigs: Map = new Map(); - - async registerTool(toolPath: string, config: ToolConfig): Promise { - const tool = await this.loadTool(toolPath); - - // Validate tool interface - this.validateTool(tool); - - // Initialize tool - await tool.initialize(config); - - this.tools.set(tool.name, tool); - this.toolConfigs.set(tool.name, config); - } - - async discoverTools(directory: string): Promise { - const toolFiles = await this.findToolFiles(directory); - const tools: ToolInfo[] = []; - - for (const file of toolFiles) { - try { - const manifest = await this.loadToolManifest(file); - tools.push({ - name: manifest.name, - version: manifest.version, - description: manifest.description, - capabilities: manifest.capabilities, - path: file - }); - } catch (error) { - console.warn(`Failed to load tool from ${file}:`, error.message); - } - } - - return tools; - } - - getTool(name: string): MCPTool | undefined { - return this.tools.get(name); - } - - listTools(): ToolInfo[] { - return Array.from(this.tools.values()).map(tool => ({ - name: tool.name, - version: tool.version, - capabilities: tool.capabilities - })); - } -} -``` - -### CLI Tool Management - -```bash -# List available tools -codebolt mcp list - -# Install a tool -codebolt mcp install database-query-tool - -# Configure a tool -codebolt mcp configure database-query-tool --config config.json - -# Test a tool -codebolt mcp test database-query-tool --action query --args '{"query": "SELECT 1"}' - -# Remove a tool -codebolt mcp remove database-query-tool - -# Update all tools -codebolt mcp update -``` - -## Best Practices - -### Security Considerations - -```typescript -// Implement proper input validation -export class SecureAPITool implements MCPTool { - async execute(request: ToolRequest): Promise { - // Validate input - const validation = this.validateInput(request.arguments); - if (!validation.valid) { - return { - success: false, - error: { - message: 'Invalid input', - details: validation.errors - } - }; - } - - // Sanitize inputs - const sanitizedArgs = this.sanitizeInputs(request.arguments); - - // Execute with rate limiting - await this.checkRateLimit(request.source); - - // Perform the operation - return await this.performOperation(sanitizedArgs); - } - - private validateInput(args: any): ValidationResult { - // Implement comprehensive input validation - } - - private sanitizeInputs(args: any): any { - // Sanitize all inputs to prevent injection attacks - } -} -``` - -### Error Handling - -```typescript -export class RobustTool implements MCPTool { - async execute(request: ToolRequest): Promise { - try { - return await this.performOperation(request); - } catch (error) { - if (error instanceof ValidationError) { - return this.handleValidationError(error); - } else if (error instanceof NetworkError) { - return this.handleNetworkError(error); - } else if (error instanceof TimeoutError) { - return this.handleTimeoutError(error); - } else { - return this.handleUnknownError(error); - } - } - } - - private handleValidationError(error: ValidationError): ToolResponse { - return { - success: false, - error: { - type: 'validation_error', - message: error.message, - details: error.validationErrors - } - }; - } -} -``` - -### Performance Optimization - -```typescript -export class OptimizedTool implements MCPTool { - private cache = new LRUCache({ max: 1000, ttl: 300000 }); // 5 min TTL - private rateLimiter = new RateLimiter({ requests: 100, per: 60000 }); // 100 req/min - - async execute(request: ToolRequest): Promise { - // Check rate limiting - if (!await this.rateLimiter.tryConsume()) { - return { - success: false, - error: { - type: 'rate_limit_exceeded', - message: 'Too many requests' - } - }; - } - - // Check cache - const cacheKey = this.generateCacheKey(request); - const cached = this.cache.get(cacheKey); - if (cached) { - return cached; - } - - // Execute operation - const result = await this.performOperation(request); - - // Cache successful results - if (result.success) { - this.cache.set(cacheKey, result); - } - - return result; - } -} -``` - -## Testing MCP Tools - -### Unit Testing - -```typescript -describe('DatabaseQueryTool', () => { - let tool: DatabaseQueryTool; - let mockConnection: jest.Mocked; - - beforeEach(() => { - tool = new DatabaseQueryTool(); - mockConnection = createMockDatabaseConnection(); - }); - - test('should execute simple query', async () => { - mockConnection.query.mockResolvedValue({ - rows: [{ id: 1, name: 'Test' }], - rowCount: 1 - }); - - const result = await tool.execute({ - action: 'query', - arguments: { - query: 'SELECT * FROM users LIMIT 1' - } - }); - - expect(result.success).toBe(true); - expect(result.data.rows).toHaveLength(1); - expect(result.data.rows[0]).toEqual({ id: 1, name: 'Test' }); - }); - - test('should handle query errors', async () => { - mockConnection.query.mockRejectedValue(new Error('Connection failed')); - - const result = await tool.execute({ - action: 'query', - arguments: { - query: 'SELECT * FROM invalid_table' - } - }); - - expect(result.success).toBe(false); - expect(result.error.message).toBe('Connection failed'); - }); -}); -``` - -### Integration Testing - -```typescript -describe('DatabaseQueryTool Integration', () => { - let tool: DatabaseQueryTool; - let testDb: TestDatabase; - - beforeAll(async () => { - testDb = await createTestDatabase(); - tool = new DatabaseQueryTool(); - await tool.initialize({ - database: testDb.getConnectionConfig() - }); - }); - - afterAll(async () => { - await tool.cleanup(); - await testDb.cleanup(); - }); - - test('should work with real database', async () => { - // Insert test data - await testDb.insert('users', { name: 'John Doe', email: 'john@example.com' }); - - // Query using tool - const result = await tool.execute({ - action: 'query', - arguments: { - query: 'SELECT * FROM users WHERE name = $1', - params: ['John Doe'] - } - }); - - expect(result.success).toBe(true); - expect(result.data.rows).toHaveLength(1); - expect(result.data.rows[0].email).toBe('john@example.com'); - }); -}); -``` - -## Publishing and Distribution - -### Tool Packaging - -```json -{ - "name": "database-query-tool", - "version": "1.0.0", - "description": "Execute database queries and schema operations", - "main": "dist/index.js", - "types": "dist/index.d.ts", - - "codebolt": { - "tool": true, - "capabilities": ["query", "schema", "migrate"], - "requirements": ["database_connection"] - }, - - "files": [ - "dist/", - "README.md", - "LICENSE", - "tool-manifest.json" - ], - - "scripts": { - "build": "tsc", - "test": "jest", - "package": "codebolt mcp package" - }, - - "dependencies": { - "@codebolt/mcp-sdk": "^1.0.0", - "pg": "^8.8.0" - }, - - "peerDependencies": { - "@codebolt/core": "^1.0.0" - } -} -``` - -### Publishing to Registry - -```bash -# Build and test the tool -npm run build -npm test - -# Package the tool -codebolt mcp package - -# Publish to Codebolt registry -codebolt mcp publish --registry https://registry.codebolt.ai - -# Or publish to npm for community distribution -npm publish -``` - -## Next Steps - -Ready to create your own MCP Tools? Here's your development path: - -1. **Start with Simple Tools**: Create basic tools for common tasks -2. **Learn the SDK**: Master the MCP Tool SDK and interfaces -3. **Integrate with Agents**: Use your tools in agent workflows -4. **Add Error Handling**: Implement robust error handling and validation -5. **Optimize Performance**: Add caching, rate limiting, and monitoring -6. **Share with Community**: Publish useful tools for others to use - -## Related Documentation - -- [TypeScript SDK](../typescript-sdk/overview.md) - Build tools with full TypeScript support -- [Agents](../agents/overview.md) - Use MCP Tools in intelligent agents -- [Task Flow](../task-flow/overview.md) - Integrate tools into automated workflows -- [API Reference](../../api-reference.md) - Complete MCP Tool API documentation - -## Community Resources - -- **Tool Registry**: Browse and install community tools -- **Templates**: Start with pre-built tool templates -- **Examples**: Learn from real-world tool implementations -- **Support Forum**: Get help with tool development - -MCP Tools are the key to making Codebolt truly your own. Start with simple integrations and gradually build more sophisticated tools as you become comfortable with the development patterns and best practices. diff --git a/docs/developer/core/mcptools.md b/docs/developer/core/mcptools.md new file mode 100644 index 00000000..c39cab22 --- /dev/null +++ b/docs/developer/core/mcptools.md @@ -0,0 +1,12 @@ +# MCP Tools + +Connect external tools and data sources to Codebolt using MCP. + + +## What is MCP? +Model Context Protocol (MCP) enables Codebolt to connect to external tools and data sources. + + +## Why use MCP? + +## How it works diff --git a/docs/developer/core/multi-agents/overview.md b/docs/developer/core/multi-agents/overview.md deleted file mode 100644 index 1b5a01c7..00000000 --- a/docs/developer/core/multi-agents/overview.md +++ /dev/null @@ -1,935 +0,0 @@ -# Multi-Agents Overview - -Multi-agent systems in Codebolt AI Editor represent the next evolution of development automation - coordinated teams of AI agents working together to tackle complex tasks that require different specializations and perspectives. - -## Introduction - -While individual agents excel at specific tasks, real-world development challenges often require multiple types of expertise working in harmony. Multi-agent systems orchestrate specialized agents to collaborate, share information, and coordinate their actions to achieve complex goals that would be difficult or impossible for a single agent to handle effectively. - -Think of multi-agent systems as your AI development team - with specialists for frontend, backend, testing, security, documentation, and deployment all working together under intelligent coordination. - -## Basic Concepts - -### Agent Coordination -Multi-agent systems manage how agents communicate, share data, and coordinate their actions: - -``` -Frontend Agent ←→ Coordinator ←→ Backend Agent - ↓ ↓ -Test Agent ←→ Coordinator ←→ Security Agent - ↓ ↓ -Documentation Agent ←→ Deployment Agent -``` - -### Shared Context -All agents in a multi-agent system share contextual information: -- Project structure and dependencies -- Code changes and their impact -- Previous analysis results -- User preferences and team conventions -- Real-time collaboration state - -### Workflow Orchestration -The system manages complex workflows with dependencies: -- Sequential execution (Agent B waits for Agent A) -- Parallel execution (Agents run simultaneously) -- Conditional branching (Agent C runs only if Agent A finds issues) -- Loop-back mechanisms (Iterate until criteria are met) - -## Architecture - -### Core Components - -#### Multi-Agent Coordinator -The central intelligence that manages agent interactions: - -```typescript -class MultiAgentCoordinator { - private agents: Map = new Map(); - private workflows: WorkflowDefinition[] = []; - private sharedContext: SharedContext = new SharedContext(); - - async executeWorkflow(workflowId: string, context: ExecutionContext): Promise { - const workflow = this.workflows.find(w => w.id === workflowId); - const executionPlan = await this.createExecutionPlan(workflow, context); - - return await this.executeSteps(executionPlan); - } - - private async executeSteps(plan: ExecutionPlan): Promise { - const results: StepResult[] = []; - - for (const step of plan.steps) { - if (step.type === 'parallel') { - const parallelResults = await Promise.all( - step.agents.map(agent => this.executeAgent(agent, step.context)) - ); - results.push(...parallelResults); - } else { - const result = await this.executeAgent(step.agent, step.context); - results.push(result); - - // Update shared context for next steps - this.sharedContext.update(result); - } - } - - return this.aggregateResults(results); - } -} -``` - -#### Communication Layer -Enables agents to share information and coordinate actions: - -```typescript -interface AgentCommunication { - sendMessage(fromAgent: string, toAgent: string, message: AgentMessage): Promise; - broadcastMessage(fromAgent: string, message: AgentMessage): Promise; - subscribeToMessages(agentId: string, handler: MessageHandler): void; - shareData(agentId: string, data: SharedData): Promise; - requestData(agentId: string, dataType: string): Promise; -} - -class AgentMessage { - type: 'request' | 'response' | 'notification' | 'data_share'; - payload: any; - metadata: { - timestamp: Date; - priority: 'low' | 'medium' | 'high' | 'critical'; - requires_response: boolean; - }; -} -``` - -#### Shared Context Manager -Maintains state and data across all agents: - -```typescript -class SharedContext { - private data: Map = new Map(); - private subscribers: Map = new Map(); - - update(key: string, value: any, source: string): void { - this.data.set(key, { - value, - source, - timestamp: new Date(), - version: this.getNextVersion(key) - }); - - this.notifySubscribers(key, value, source); - } - - subscribe(key: string, subscriber: ContextSubscriber): void { - if (!this.subscribers.has(key)) { - this.subscribers.set(key, []); - } - this.subscribers.get(key)!.push(subscriber); - } - - get(key: string): ContextData | undefined { - return this.data.get(key); - } -} -``` - -## Advanced Concepts - -### Agent Specialization Patterns - -#### Hierarchical Coordination -``` -Project Manager Agent (Coordinator) -β”œβ”€β”€ Frontend Team Lead Agent -β”‚ β”œβ”€β”€ React Component Agent -β”‚ β”œβ”€β”€ CSS/Style Agent -β”‚ └── Frontend Testing Agent -β”œβ”€β”€ Backend Team Lead Agent -β”‚ β”œβ”€β”€ API Development Agent -β”‚ β”œβ”€β”€ Database Agent -β”‚ └── Backend Testing Agent -└── DevOps Lead Agent - β”œβ”€β”€ CI/CD Agent - β”œβ”€β”€ Security Agent - └── Monitoring Agent -``` - -#### Peer-to-Peer Collaboration -``` -Code Review Agent ←→ Test Generation Agent - ↕ ↕ -Documentation Agent ←→ Security Agent -``` - -#### Pipeline Pattern -``` -Code Analysis β†’ Quality Check β†’ Test Generation β†’ Documentation β†’ Deployment -``` - -### Coordination Mechanisms - -#### Event-Driven Coordination -```typescript -class EventDrivenCoordinator { - private eventBus: EventBus = new EventBus(); - - setupEventHandlers(): void { - this.eventBus.on('code_changed', async (event) => { - // Trigger relevant agents based on the change - const affectedAgents = this.determineAffectedAgents(event.changes); - await this.executeAgents(affectedAgents, event.context); - }); - - this.eventBus.on('agent_completed', async (event) => { - // Check if other agents should be triggered - const nextAgents = this.determineNextAgents(event.result); - if (nextAgents.length > 0) { - await this.executeAgents(nextAgents, event.context); - } - }); - } -} -``` - -#### State-Based Coordination -```typescript -class StateMachine { - private state: WorkflowState = 'idle'; - private transitions: StateTransition[] = []; - - async transition(trigger: string, context: any): Promise { - const validTransitions = this.transitions.filter(t => - t.from === this.state && t.trigger === trigger - ); - - if (validTransitions.length === 0) { - throw new Error(`Invalid transition: ${this.state} -> ${trigger}`); - } - - const transition = validTransitions[0]; - - // Execute transition actions - await this.executeActions(transition.actions, context); - - // Update state - this.state = transition.to; - - // Trigger any automatic transitions - await this.checkAutoTransitions(); - } -} -``` - -#### Contract-Based Coordination -```typescript -interface AgentContract { - inputs: DataSchema[]; - outputs: DataSchema[]; - dependencies: string[]; - guarantees: ServiceLevelAgreement[]; - - canProcess(input: any): boolean; - estimateProcessingTime(input: any): number; - getQualityMetrics(): QualityMetrics; -} - -class ContractManager { - async findCompatibleAgents(requirement: AgentRequirement): Promise { - return this.agents.filter(agent => - agent.contract.canProcess(requirement.input) && - this.meetsQualityRequirements(agent, requirement) - ); - } -} -``` - -## Practical Examples - -### Example 1: Full-Stack Feature Development - -```typescript -class FeatureDevelopmentWorkflow { - async developFeature(featureSpec: FeatureSpecification): Promise { - const coordinator = new MultiAgentCoordinator(); - - // Define the workflow - const workflow = { - name: 'Feature Development', - steps: [ - { - name: 'analyze_requirements', - agent: 'Business Analyst Agent', - input: featureSpec, - outputs: ['technical_requirements', 'acceptance_criteria'] - }, - { - name: 'design_architecture', - agent: 'Architecture Agent', - depends_on: ['analyze_requirements'], - outputs: ['system_design', 'api_contracts'] - }, - { - name: 'parallel_development', - type: 'parallel', - steps: [ - { - name: 'frontend_development', - agent: 'Frontend Agent', - depends_on: ['design_architecture'], - outputs: ['ui_components', 'frontend_tests'] - }, - { - name: 'backend_development', - agent: 'Backend Agent', - depends_on: ['design_architecture'], - outputs: ['api_implementation', 'backend_tests'] - }, - { - name: 'database_schema', - agent: 'Database Agent', - depends_on: ['design_architecture'], - outputs: ['schema_migration', 'database_tests'] - } - ] - }, - { - name: 'integration_testing', - agent: 'Integration Test Agent', - depends_on: ['parallel_development'], - outputs: ['integration_tests', 'test_results'] - }, - { - name: 'documentation', - agent: 'Documentation Agent', - depends_on: ['integration_testing'], - outputs: ['api_docs', 'user_guide'] - }, - { - name: 'deployment', - agent: 'Deployment Agent', - depends_on: ['documentation'], - condition: 'all_tests_pass', - outputs: ['deployment_result'] - } - ] - }; - - return await coordinator.executeWorkflow(workflow); - } -} -``` - -### Example 2: Code Review and Quality Assurance - -```typescript -class CodeQualityWorkflow { - async reviewCodeChanges(changes: CodeChanges): Promise { - const workflow = { - name: 'Comprehensive Code Review', - steps: [ - { - name: 'initial_analysis', - type: 'parallel', - steps: [ - { - name: 'static_analysis', - agent: 'Static Analysis Agent', - outputs: ['syntax_issues', 'complexity_metrics'] - }, - { - name: 'security_scan', - agent: 'Security Agent', - outputs: ['security_vulnerabilities', 'security_score'] - }, - { - name: 'performance_analysis', - agent: 'Performance Agent', - outputs: ['performance_issues', 'optimization_suggestions'] - } - ] - }, - { - name: 'ai_review', - agent: 'AI Code Reviewer', - depends_on: ['initial_analysis'], - context: 'include_static_analysis_results', - outputs: ['code_suggestions', 'best_practice_violations'] - }, - { - name: 'test_analysis', - agent: 'Test Coverage Agent', - depends_on: ['ai_review'], - outputs: ['coverage_report', 'missing_tests'] - }, - { - name: 'generate_missing_tests', - agent: 'Test Generation Agent', - depends_on: ['test_analysis'], - condition: 'coverage_below_threshold', - outputs: ['generated_tests'] - }, - { - name: 'documentation_check', - agent: 'Documentation Agent', - depends_on: ['ai_review'], - outputs: ['documentation_gaps', 'generated_docs'] - }, - { - name: 'final_report', - agent: 'Report Generator Agent', - depends_on: ['generate_missing_tests', 'documentation_check'], - outputs: ['comprehensive_report'] - } - ] - }; - - return await this.coordinator.executeWorkflow(workflow, { changes }); - } -} -``` - -### Example 3: Continuous Integration Pipeline - -```typescript -class CIMultiAgentPipeline { - async processPullRequest(pr: PullRequest): Promise { - const workflow = { - name: 'CI Pipeline', - trigger: 'pull_request_opened', - steps: [ - { - name: 'pre_checks', - type: 'parallel', - steps: [ - { - name: 'branch_policy_check', - agent: 'Branch Policy Agent' - }, - { - name: 'commit_message_check', - agent: 'Commit Message Agent' - }, - { - name: 'file_size_check', - agent: 'File Size Agent' - } - ] - }, - { - name: 'code_quality_gate', - depends_on: ['pre_checks'], - condition: 'pre_checks_pass', - type: 'parallel', - steps: [ - { - name: 'lint_check', - agent: 'Linting Agent' - }, - { - name: 'format_check', - agent: 'Formatting Agent' - }, - { - name: 'type_check', - agent: 'Type Checking Agent' - } - ] - }, - { - name: 'testing_phase', - depends_on: ['code_quality_gate'], - condition: 'quality_gate_pass', - type: 'sequential', - steps: [ - { - name: 'unit_tests', - agent: 'Unit Test Agent' - }, - { - name: 'integration_tests', - agent: 'Integration Test Agent', - condition: 'unit_tests_pass' - }, - { - name: 'e2e_tests', - agent: 'E2E Test Agent', - condition: 'integration_tests_pass' - } - ] - }, - { - name: 'security_and_performance', - depends_on: ['testing_phase'], - condition: 'tests_pass', - type: 'parallel', - steps: [ - { - name: 'security_scan', - agent: 'Security Scanning Agent' - }, - { - name: 'performance_test', - agent: 'Performance Testing Agent' - }, - { - name: 'dependency_audit', - agent: 'Dependency Audit Agent' - } - ] - }, - { - name: 'approval_workflow', - depends_on: ['security_and_performance'], - condition: 'all_checks_pass', - agent: 'Approval Agent', - config: { - require_human_review: true, - auto_merge_conditions: ['minor_changes', 'all_tests_green'] - } - } - ] - }; - - return await this.coordinator.executeWorkflow(workflow, { pr }); - } -} -``` - -## Configuration and Setup - -### Defining Multi-Agent Workflows - -```json -{ - "name": "Full Stack Development Workflow", - "version": "1.0.0", - "description": "Coordinates frontend, backend, and testing agents", - - "agents": [ - { - "id": "frontend_agent", - "name": "React Frontend Agent", - "specialization": "frontend_react" - }, - { - "id": "backend_agent", - "name": "Node.js Backend Agent", - "specialization": "backend_nodejs" - }, - { - "id": "test_agent", - "name": "Jest Testing Agent", - "specialization": "testing_jest" - }, - { - "id": "security_agent", - "name": "Security Scanner Agent", - "specialization": "security_scanning" - } - ], - - "workflows": [ - { - "name": "feature_development", - "trigger": { - "type": "manual", - "command": "develop_feature" - }, - "steps": [ - { - "id": "analyze_requirements", - "agent": "frontend_agent", - "action": "analyze_feature_requirements", - "outputs": ["component_specs", "api_requirements"] - }, - { - "id": "develop_components", - "agent": "frontend_agent", - "depends_on": ["analyze_requirements"], - "action": "develop_react_components", - "inputs": ["component_specs"], - "outputs": ["components", "component_tests"] - }, - { - "id": "develop_api", - "agent": "backend_agent", - "depends_on": ["analyze_requirements"], - "action": "develop_api_endpoints", - "inputs": ["api_requirements"], - "outputs": ["api_code", "api_tests"] - }, - { - "id": "integration_tests", - "agent": "test_agent", - "depends_on": ["develop_components", "develop_api"], - "action": "create_integration_tests", - "inputs": ["components", "api_code"], - "outputs": ["integration_tests"] - }, - { - "id": "security_review", - "agent": "security_agent", - "depends_on": ["integration_tests"], - "action": "security_scan", - "inputs": ["components", "api_code"], - "outputs": ["security_report"] - } - ], - - "coordination": { - "type": "orchestrated", - "failure_handling": "rollback", - "timeout": "30m", - "retry_policy": { - "max_retries": 3, - "backoff_strategy": "exponential" - } - } - } - ], - - "communication": { - "protocol": "event_driven", - "message_format": "json", - "encryption": true, - "compression": true - }, - - "monitoring": { - "metrics_collection": true, - "performance_tracking": true, - "error_reporting": true, - "dashboard_url": "http://localhost:3000/multi-agent-dashboard" - } -} -``` - -### Agent Communication Protocols - -```typescript -// Message passing between agents -class AgentMessaging { - async sendRequest(fromAgent: string, toAgent: string, request: AgentRequest): Promise { - const message: AgentMessage = { - id: generateId(), - type: 'request', - from: fromAgent, - to: toAgent, - payload: request, - timestamp: new Date(), - requires_response: true - }; - - return await this.communicationLayer.send(message); - } - - async broadcastNotification(fromAgent: string, notification: AgentNotification): Promise { - const message: AgentMessage = { - id: generateId(), - type: 'notification', - from: fromAgent, - to: '*', - payload: notification, - timestamp: new Date(), - requires_response: false - }; - - await this.communicationLayer.broadcast(message); - } -} - -// Shared data management -class SharedDataManager { - private data: Map = new Map(); - private locks: Map = new Map(); - - async writeData(agentId: string, key: string, data: any): Promise { - const lock = await this.acquireLock(key, agentId); - - try { - this.data.set(key, { - value: data, - owner: agentId, - timestamp: new Date(), - version: this.getNextVersion(key) - }); - - await this.notifySubscribers(key, data, agentId); - } finally { - await this.releaseLock(lock); - } - } - - async readData(key: string): Promise { - const item = this.data.get(key); - return item ? item.value : undefined; - } -} -``` - -## Best Practices - -### 1. Agent Design for Collaboration - -```typescript -class CollaborativeAgent extends CodeboltAgent { - constructor(config: AgentConfig) { - super(config); - - // Enable collaboration features - this.enableCommunication(); - this.enableDataSharing(); - this.enableCoordination(); - } - - // Implement collaboration interfaces - async handleMessage(message: AgentMessage): Promise { - switch (message.type) { - case 'request': - return await this.processRequest(message.payload); - case 'notification': - await this.processNotification(message.payload); - break; - case 'data_share': - await this.processSharedData(message.payload); - break; - } - } - - // Provide clear interfaces for other agents - async getCapabilities(): Promise { - return { - actions: this.getSupportedActions(), - inputs: this.getInputSchema(), - outputs: this.getOutputSchema(), - dependencies: this.getDependencies(), - performance_metrics: this.getPerformanceMetrics() - }; - } -} -``` - -### 2. Workflow Design Patterns - -```typescript -// Pipeline Pattern -class PipelineWorkflow { - steps: WorkflowStep[] = [ - { agent: 'analyzer', action: 'analyze_code' }, - { agent: 'reviewer', action: 'review_analysis' }, - { agent: 'tester', action: 'generate_tests' }, - { agent: 'documenter', action: 'create_docs' } - ]; -} - -// Fan-out/Fan-in Pattern -class FanOutFanInWorkflow { - async execute(input: any): Promise { - // Fan-out: distribute work to multiple agents - const parallelTasks = [ - this.agents.frontend.analyze(input), - this.agents.backend.analyze(input), - this.agents.database.analyze(input) - ]; - - const results = await Promise.all(parallelTasks); - - // Fan-in: aggregate results - return this.agents.aggregator.combine(results); - } -} - -// Hierarchical Pattern -class HierarchicalWorkflow { - coordinator: CoordinatorAgent; - teamLeads: TeamLeadAgent[]; - specialists: SpecialistAgent[]; - - async execute(task: ComplexTask): Promise { - const plan = await this.coordinator.createExecutionPlan(task); - - const teamResults = await Promise.all( - this.teamLeads.map(lead => lead.executeTeamTasks(plan.getTasksForTeam(lead.team))) - ); - - return await this.coordinator.aggregateTeamResults(teamResults); - } -} -``` - -### 3. Error Handling and Resilience - -```typescript -class ResilientMultiAgentSystem { - async executeWithResilience(workflow: Workflow): Promise { - const circuit = new CircuitBreaker({ - timeout: 30000, - errorThresholdPercentage: 50, - resetTimeout: 60000 - }); - - return await circuit.fire(async () => { - try { - return await this.executeWorkflow(workflow); - } catch (error) { - if (error instanceof AgentTimeoutError) { - return await this.handleTimeoutRecovery(workflow, error); - } else if (error instanceof AgentFailureError) { - return await this.handleAgentFailure(workflow, error); - } else { - throw error; - } - } - }); - } - - private async handleAgentFailure(workflow: Workflow, error: AgentFailureError): Promise { - // Try to find a backup agent - const backupAgent = await this.findBackupAgent(error.failedAgent); - - if (backupAgent) { - return await this.retryWithBackupAgent(workflow, error.failedAgent, backupAgent); - } else { - // Graceful degradation - return await this.executePartialWorkflow(workflow, error.failedAgent); - } - } -} -``` - -## Monitoring and Debugging - -### Performance Monitoring - -```typescript -class MultiAgentMonitor { - private metrics: Map = new Map(); - - async collectMetrics(): Promise { - const agentMetrics = await Promise.all( - this.agents.map(agent => agent.getMetrics()) - ); - - return { - system_performance: this.calculateSystemPerformance(agentMetrics), - communication_stats: this.getCommunicationStats(), - workflow_completion_rates: this.getWorkflowStats(), - resource_utilization: this.getResourceStats(), - error_rates: this.getErrorStats() - }; - } - - async generateHealthReport(): Promise { - const metrics = await this.collectMetrics(); - - return { - overall_health: this.calculateOverallHealth(metrics), - agent_health: this.calculateAgentHealth(), - bottlenecks: this.identifyBottlenecks(metrics), - recommendations: this.generateRecommendations(metrics) - }; - } -} -``` - -### Debugging Tools - -```bash -# Monitor multi-agent workflow execution -codebolt multi-agent monitor --workflow "feature_development" --real-time - -# Debug agent communication -codebolt multi-agent debug-communication --agents "frontend,backend" --trace - -# Analyze workflow performance -codebolt multi-agent analyze-performance --workflow "ci_pipeline" --duration 24h - -# Visualize agent dependencies -codebolt multi-agent visualize --workflow "code_review" --output graph.png -``` - -## Integration with Development Tools - -### IDE Integration - -```typescript -class IDEMultiAgentIntegration { - async integrateWithVSCode(): Promise { - // Register multi-agent commands - vscode.commands.registerCommand('codebolt.runMultiAgentWorkflow', async () => { - const workflow = await this.selectWorkflow(); - const result = await this.executeWorkflow(workflow); - this.displayResults(result); - }); - - // Add status bar integration - this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right); - this.statusBar.text = "$(sync~spin) Multi-Agent: Ready"; - this.statusBar.show(); - } - - async displayWorkflowProgress(workflow: Workflow): Promise { - const progress = vscode.window.withProgress({ - location: vscode.ProgressLocation.Notification, - title: `Multi-Agent Workflow: ${workflow.name}`, - cancellable: true - }, async (progress, token) => { - return await this.executeWorkflowWithProgress(workflow, progress, token); - }); - } -} -``` - -### CI/CD Integration - -```yaml -# .github/workflows/multi-agent-ci.yml -name: Multi-Agent CI Pipeline -on: [push, pull_request] - -jobs: - multi-agent-analysis: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Setup Codebolt - uses: codebolt/setup-action@v1 - - name: Run Multi-Agent Workflow - run: | - codebolt multi-agent run ci_pipeline \ - --context github_action \ - --output-format json \ - --save-results ci-results.json - - name: Upload Results - uses: actions/upload-artifact@v3 - with: - name: multi-agent-results - path: ci-results.json -``` - -## Next Steps - -Ready to implement multi-agent systems? Here's your learning path: - -1. **Start Simple**: Begin with 2-3 agents in a basic workflow -2. **Learn Coordination Patterns**: Master sequential, parallel, and conditional workflows -3. **Implement Communication**: Set up agent-to-agent messaging and data sharing -4. **Add Monitoring**: Implement performance tracking and debugging tools -5. **Scale Up**: Gradually add more agents and complex coordination logic - -## Advanced Topics - -- [Agent Orchestration Patterns](orchestration-patterns.md) -- [Communication Protocols](communication-protocols.md) -- [Performance Optimization](performance-optimization.md) -- [Fault Tolerance Strategies](fault-tolerance.md) - -## Community Resources - -- **Multi-Agent Templates**: Pre-built workflow templates -- **Case Studies**: Real-world multi-agent implementations -- **Best Practices Guide**: Lessons learned from the community -- **Performance Benchmarks**: Compare your system's performance - -Multi-agent systems represent the future of intelligent development automation. Start with simple coordination patterns and gradually build more sophisticated systems as you gain experience with agent collaboration. diff --git a/docs/developer/core/task-flow/overview.md b/docs/developer/core/task-flow/overview.md deleted file mode 100644 index 8ccd6457..00000000 --- a/docs/developer/core/task-flow/overview.md +++ /dev/null @@ -1,936 +0,0 @@ -# Task Flow Overview - -Task Flow is Codebolt AI Editor's powerful workflow automation system that orchestrates complex development processes by combining agents, tools, and human interactions into seamless, intelligent workflows. Think of it as your personal DevOps pipeline that can be customized for any development workflow, from simple code transformations to complete CI/CD processes. - -## Introduction - -Modern software development involves numerous repetitive tasks: code reviews, testing, documentation generation, deployment, and more. Task Flow automates these processes while maintaining intelligent decision-making and human oversight where needed. - -Unlike simple scripts or static pipelines, Task Flow workflows are intelligent and adaptive. They can make decisions based on code analysis, respond to changing conditions, integrate with external services, and learn from outcomes to improve future executions. - -## Core Concepts - -### Workflows -A workflow is a defined sequence of tasks that accomplish a specific goal: - -```yaml -name: "Code Review and Deploy" -description: "Comprehensive code review followed by automated deployment" -trigger: "pull_request_merged" -steps: - - code_analysis - - security_scan - - test_execution - - documentation_update - - deployment -``` - -### Tasks and Steps -Individual units of work within a workflow: -- **Agent Tasks**: Execute specific agents with defined inputs -- **Tool Tasks**: Use MCP tools for external integrations -- **Human Tasks**: Require human input or approval -- **Conditional Tasks**: Execute based on previous results -- **Parallel Tasks**: Run multiple tasks simultaneously - -### Triggers -Events that initiate workflow execution: -- **File Events**: Save, create, delete, modify -- **Git Events**: Commit, push, merge, tag -- **Time-based**: Scheduled execution -- **Manual**: User-initiated -- **External**: Webhooks, API calls - -### Context and Data Flow -Information passed between workflow steps: -- **Input Context**: Initial data and parameters -- **Step Outputs**: Results from each task -- **Shared Variables**: Data accessible across steps -- **External Data**: Information from APIs or databases - -## Building Workflows - -### Visual Workflow Builder - -Codebolt provides an intuitive visual interface for creating workflows: - -``` -β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” -β”‚ Trigger │───▢│ Analysis │───▢│ Review β”‚ -β”‚ File Save β”‚ β”‚ Agent β”‚ β”‚ Agent β”‚ -β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ β”‚ - β–Ό β–Ό - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ Security β”‚ β”‚ Generate β”‚ - β”‚ Scan β”‚ β”‚ Tests β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β”‚ β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ - β–Ό - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” - β”‚ Deploy β”‚ - β”‚ (if tests β”‚ - β”‚ pass) β”‚ - β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -``` - -### Workflow Configuration - -#### Basic Workflow Structure -```yaml -name: "Feature Development Workflow" -version: "1.0.0" -description: "End-to-end feature development automation" - -# When this workflow should run -triggers: - - type: "manual" - command: "develop_feature" - - type: "file_save" - patterns: ["src/**/*.{js,ts,jsx,tsx}"] - debounce: 2000 - -# Input parameters -inputs: - - name: "feature_description" - type: "string" - required: true - description: "Description of the feature to develop" - - name: "target_branch" - type: "string" - default: "main" - description: "Target branch for the feature" - -# Workflow steps -steps: - - name: "analyze_requirements" - type: "agent" - agent: "requirements_analyzer" - inputs: - description: "${inputs.feature_description}" - outputs: - - "technical_requirements" - - "acceptance_criteria" - - - name: "create_implementation_plan" - type: "agent" - agent: "architect" - depends_on: ["analyze_requirements"] - inputs: - requirements: "${steps.analyze_requirements.outputs.technical_requirements}" - outputs: - - "implementation_plan" - - "file_structure" - - - name: "parallel_development" - type: "parallel" - depends_on: ["create_implementation_plan"] - steps: - - name: "generate_frontend_code" - type: "agent" - agent: "frontend_developer" - inputs: - plan: "${steps.create_implementation_plan.outputs.implementation_plan}" - - - name: "generate_backend_code" - type: "agent" - agent: "backend_developer" - inputs: - plan: "${steps.create_implementation_plan.outputs.implementation_plan}" - - - name: "generate_tests" - type: "agent" - agent: "test_generator" - inputs: - plan: "${steps.create_implementation_plan.outputs.implementation_plan}" - - - name: "integration_review" - type: "agent" - agent: "integration_reviewer" - depends_on: ["parallel_development"] - inputs: - frontend_code: "${steps.generate_frontend_code.outputs}" - backend_code: "${steps.generate_backend_code.outputs}" - tests: "${steps.generate_tests.outputs}" - - - name: "human_approval" - type: "human" - depends_on: ["integration_review"] - prompt: "Review the generated code and approve for deployment" - timeout: "24h" - - - name: "deploy_feature" - type: "agent" - agent: "deployment_manager" - depends_on: ["human_approval"] - condition: "${steps.human_approval.approved}" - inputs: - code: "${steps.integration_review.outputs.integrated_code}" - target_branch: "${inputs.target_branch}" - -# Error handling -error_handling: - strategy: "rollback" - max_retries: 3 - notification: - channels: ["#dev-team"] - -# Success actions -on_success: - - type: "notification" - message: "Feature '${inputs.feature_description}' successfully deployed" - - type: "create_documentation" - agent: "documentation_generator" -``` - -### Advanced Workflow Patterns - -#### Conditional Execution -```yaml -steps: - - name: "code_analysis" - type: "agent" - agent: "code_analyzer" - - - name: "security_scan" - type: "tool" - tool: "security_scanner" - condition: "${steps.code_analysis.outputs.complexity_score} > 5" - - - name: "performance_test" - type: "tool" - tool: "performance_tester" - condition: "${steps.code_analysis.outputs.has_performance_critical_code}" -``` - -#### Loop and Iteration -```yaml -steps: - - name: "code_review_loop" - type: "loop" - max_iterations: 5 - condition: "${outputs.issues_found} > 0" - steps: - - name: "review_code" - type: "agent" - agent: "code_reviewer" - - - name: "fix_issues" - type: "agent" - agent: "code_fixer" - condition: "${steps.review_code.outputs.issues_found} > 0" - - - name: "human_review" - type: "human" - condition: "${steps.review_code.outputs.critical_issues} > 0" - prompt: "Critical issues found. Please review manually." -``` - -#### Error Recovery -```yaml -steps: - - name: "deploy_to_staging" - type: "agent" - agent: "deployment_agent" - retry: - max_attempts: 3 - backoff_strategy: "exponential" - - - name: "run_smoke_tests" - type: "tool" - tool: "test_runner" - on_failure: - - name: "rollback_deployment" - type: "agent" - agent: "deployment_agent" - action: "rollback" - - name: "notify_team" - type: "notification" - message: "Deployment failed, rolled back automatically" -``` - -## Managing Workflows - -### Workflow Lifecycle - -#### Development Phase -```bash -# Create new workflow -codebolt workflow create feature-development - -# Edit workflow in visual builder -codebolt workflow edit feature-development --visual - -# Validate workflow configuration -codebolt workflow validate feature-development - -# Test workflow with sample data -codebolt workflow test feature-development --dry-run --input sample-input.json -``` - -#### Deployment Phase -```bash -# Deploy workflow to environment -codebolt workflow deploy feature-development --environment staging - -# Enable workflow triggers -codebolt workflow enable feature-development - -# Monitor workflow execution -codebolt workflow monitor feature-development --real-time -``` - -#### Maintenance Phase -```bash -# View workflow execution history -codebolt workflow history feature-development --last 30d - -# Analyze workflow performance -codebolt workflow analyze feature-development --metrics - -# Update workflow version -codebolt workflow update feature-development --version 1.1.0 -``` - -### Workflow Templates - -#### CI/CD Pipeline Template -```yaml -name: "CI/CD Pipeline" -template: true -parameters: - - name: "test_framework" - type: "select" - options: ["jest", "mocha", "pytest", "junit"] - - name: "deployment_target" - type: "select" - options: ["staging", "production", "preview"] - -steps: - - name: "checkout_code" - type: "tool" - tool: "git" - action: "checkout" - - - name: "install_dependencies" - type: "tool" - tool: "package_manager" - action: "install" - - - name: "run_linting" - type: "agent" - agent: "linter" - - - name: "run_tests" - type: "tool" - tool: "test_runner" - framework: "${parameters.test_framework}" - - - name: "build_application" - type: "tool" - tool: "build_system" - condition: "${steps.run_tests.outputs.success}" - - - name: "deploy" - type: "agent" - agent: "deployment_agent" - target: "${parameters.deployment_target}" - condition: "${steps.build_application.outputs.success}" -``` - -#### Code Quality Gate Template -```yaml -name: "Code Quality Gate" -template: true - -steps: - - name: "static_analysis" - type: "parallel" - steps: - - name: "lint_check" - type: "agent" - agent: "linter" - - name: "type_check" - type: "agent" - agent: "type_checker" - - name: "security_scan" - type: "tool" - tool: "security_scanner" - - - name: "quality_gate_decision" - type: "decision" - depends_on: ["static_analysis"] - rules: - - condition: "${steps.lint_check.outputs.error_count} > 0" - action: "fail" - message: "Linting errors must be fixed" - - condition: "${steps.type_check.outputs.error_count} > 0" - action: "fail" - message: "Type errors must be resolved" - - condition: "${steps.security_scan.outputs.high_severity_issues} > 0" - action: "fail" - message: "High severity security issues found" - - condition: "default" - action: "pass" -``` - -## Integration with Agents - -### Agent Orchestration - -```typescript -class WorkflowOrchestrator { - async executeAgentWorkflow(workflowId: string, context: WorkflowContext): Promise { - const workflow = await this.loadWorkflow(workflowId); - const executionPlan = await this.createExecutionPlan(workflow, context); - - const results: StepResult[] = []; - - for (const step of executionPlan.steps) { - if (step.type === 'agent') { - const agent = await this.getAgent(step.agentId); - const result = await this.executeAgentStep(agent, step, context); - results.push(result); - - // Update context with step results - context.updateFromStepResult(result); - } else if (step.type === 'parallel') { - const parallelResults = await Promise.all( - step.steps.map(parallelStep => this.executeStep(parallelStep, context)) - ); - results.push(...parallelResults); - } - } - - return this.aggregateResults(results); - } - - private async executeAgentStep(agent: CodeboltAgent, step: WorkflowStep, context: WorkflowContext): Promise { - try { - // Prepare agent input from workflow context - const agentInput = this.prepareAgentInput(step.inputs, context); - - // Execute agent with timeout and monitoring - const result = await this.executeWithTimeout( - () => agent.execute(agentInput), - step.timeout || 300000 // 5 minute default - ); - - return { - stepId: step.id, - success: true, - outputs: result, - executionTime: Date.now() - step.startTime, - agentId: agent.name - }; - } catch (error) { - return { - stepId: step.id, - success: false, - error: error.message, - executionTime: Date.now() - step.startTime, - agentId: agent.name - }; - } - } -} -``` - -### Multi-Agent Coordination - -```yaml -name: "Full Stack Code Review" -description: "Coordinate multiple specialized agents for comprehensive code review" - -steps: - - name: "initial_analysis" - type: "parallel" - steps: - - name: "frontend_analysis" - type: "agent" - agent: "react_specialist" - condition: "${context.has_frontend_changes}" - - - name: "backend_analysis" - type: "agent" - agent: "node_specialist" - condition: "${context.has_backend_changes}" - - - name: "database_analysis" - type: "agent" - agent: "database_specialist" - condition: "${context.has_database_changes}" - - - name: "cross_cutting_analysis" - type: "agent" - agent: "architecture_reviewer" - depends_on: ["initial_analysis"] - inputs: - frontend_analysis: "${steps.frontend_analysis.outputs}" - backend_analysis: "${steps.backend_analysis.outputs}" - database_analysis: "${steps.database_analysis.outputs}" - - - name: "security_review" - type: "agent" - agent: "security_specialist" - depends_on: ["cross_cutting_analysis"] - - - name: "performance_review" - type: "agent" - agent: "performance_specialist" - depends_on: ["cross_cutting_analysis"] - - - name: "consolidate_feedback" - type: "agent" - agent: "review_consolidator" - depends_on: ["security_review", "performance_review"] - inputs: - all_reviews: [ - "${steps.initial_analysis.outputs}", - "${steps.cross_cutting_analysis.outputs}", - "${steps.security_review.outputs}", - "${steps.performance_review.outputs}" - ] -``` - -## Integration with External Systems - -### API Integrations - -```yaml -steps: - - name: "notify_jira" - type: "tool" - tool: "rest_api" - config: - url: "https://company.atlassian.net/rest/api/3/issue" - method: "POST" - headers: - Authorization: "Bearer ${secrets.JIRA_TOKEN}" - Content-Type: "application/json" - body: - fields: - project: - key: "DEV" - summary: "Code review completed for ${context.pull_request.title}" - description: "${steps.consolidate_feedback.outputs.summary}" - issuetype: - name: "Task" - - - name: "update_slack" - type: "tool" - tool: "slack_webhook" - config: - webhook_url: "${secrets.SLACK_WEBHOOK}" - message: - text: "Code review completed" - attachments: - - color: "${steps.consolidate_feedback.outputs.overall_status === 'approved' ? 'good' : 'warning'}" - fields: - - title: "Pull Request" - value: "${context.pull_request.url}" - short: true - - title: "Status" - value: "${steps.consolidate_feedback.outputs.overall_status}" - short: true -``` - -### Database Operations - -```yaml -steps: - - name: "backup_database" - type: "tool" - tool: "database_query" - config: - action: "backup" - database: "production" - backup_name: "pre_migration_${workflow.execution_id}" - - - name: "run_migrations" - type: "tool" - tool: "database_query" - depends_on: ["backup_database"] - condition: "${steps.backup_database.outputs.success}" - config: - action: "migrate" - migration_files: "${context.changed_files.filter(f => f.path.includes('migrations/'))}" - - - name: "verify_migration" - type: "tool" - tool: "database_query" - depends_on: ["run_migrations"] - config: - action: "query" - query: "SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1" - expected_result: "${steps.run_migrations.outputs.target_version}" -``` - -### Cloud Services Integration - -```yaml -steps: - - name: "build_docker_image" - type: "tool" - tool: "docker" - config: - action: "build" - dockerfile: "Dockerfile" - tag: "${context.git.commit_sha}" - - - name: "push_to_registry" - type: "tool" - tool: "docker" - depends_on: ["build_docker_image"] - config: - action: "push" - registry: "gcr.io/company-project" - tag: "${steps.build_docker_image.outputs.tag}" - - - name: "deploy_to_kubernetes" - type: "tool" - tool: "kubectl" - depends_on: ["push_to_registry"] - config: - action: "apply" - manifest_template: "k8s/deployment.yaml" - variables: - image_tag: "${steps.push_to_registry.outputs.full_tag}" - environment: "${inputs.target_environment}" -``` - -## Monitoring and Debugging - -### Workflow Execution Monitoring - -```typescript -class WorkflowMonitor { - async monitorExecution(executionId: string): Promise { - const execution = await this.getExecution(executionId); - - // Real-time step monitoring - execution.on('step_started', (step) => { - console.log(`Step ${step.name} started at ${new Date()}`); - this.updateDashboard(executionId, step); - }); - - execution.on('step_completed', (step, result) => { - console.log(`Step ${step.name} completed: ${result.success ? 'SUCCESS' : 'FAILED'}`); - this.logMetrics(step, result); - }); - - execution.on('workflow_completed', (result) => { - this.generateExecutionReport(executionId, result); - }); - } - - private async logMetrics(step: WorkflowStep, result: StepResult): Promise { - await this.metricsCollector.record({ - workflow_id: step.workflowId, - step_name: step.name, - execution_time: result.executionTime, - success: result.success, - timestamp: new Date() - }); - } -} -``` - -### Performance Analytics - -```bash -# Analyze workflow performance -codebolt workflow analyze feature-development --metrics execution_time,success_rate,resource_usage - -# View bottlenecks -codebolt workflow bottlenecks feature-development --last 7d - -# Generate performance report -codebolt workflow report feature-development --format pdf --include metrics,trends,recommendations -``` - -### Debugging Failed Workflows - -```typescript -class WorkflowDebugger { - async debugFailedExecution(executionId: string): Promise { - const execution = await this.getExecutionDetails(executionId); - const failedSteps = execution.steps.filter(step => !step.success); - - const debugInfo: DebugInfo[] = []; - - for (const step of failedSteps) { - const stepDebugInfo = await this.analyzeFailedStep(step); - debugInfo.push({ - stepName: step.name, - error: step.error, - context: step.context, - logs: await this.getStepLogs(step.id), - suggestions: await this.generateFixSuggestions(step), - relatedIssues: await this.findRelatedIssues(step.error) - }); - } - - return { - executionId, - failureCount: failedSteps.length, - debugInfo, - overallSuggestions: await this.generateOverallSuggestions(debugInfo) - }; - } -} -``` - -## Best Practices - -### Workflow Design Principles - -#### 1. Single Responsibility -```yaml -# Good: Focused workflow -name: "Code Quality Check" -steps: - - lint_check - - type_check - - test_execution - -# Bad: Too many responsibilities -name: "Everything Workflow" -steps: - - code_review - - deployment - - documentation - - user_notification - - database_migration -``` - -#### 2. Fail Fast -```yaml -steps: - - name: "quick_validation" - type: "agent" - agent: "syntax_validator" - - - name: "expensive_analysis" - type: "agent" - agent: "deep_analyzer" - depends_on: ["quick_validation"] - condition: "${steps.quick_validation.outputs.valid}" -``` - -#### 3. Idempotent Operations -```yaml -steps: - - name: "create_branch" - type: "tool" - tool: "git" - config: - action: "create_branch" - branch_name: "feature/${inputs.feature_name}" - ignore_if_exists: true # Idempotent operation -``` - -#### 4. Proper Error Handling -```yaml -steps: - - name: "risky_operation" - type: "agent" - agent: "external_api_agent" - retry: - max_attempts: 3 - backoff_strategy: "exponential" - on_failure: - - name: "fallback_operation" - type: "agent" - agent: "local_backup_agent" - - name: "notify_admin" - type: "notification" - message: "External API failed, using fallback" -``` - -### Performance Optimization - -#### Parallel Execution -```yaml -# Execute independent steps in parallel -steps: - - name: "parallel_analysis" - type: "parallel" - steps: - - name: "frontend_lint" - type: "agent" - agent: "frontend_linter" - - name: "backend_lint" - type: "agent" - agent: "backend_linter" - - name: "security_scan" - type: "tool" - tool: "security_scanner" -``` - -#### Conditional Execution -```yaml -# Skip expensive operations when not needed -steps: - - name: "change_detection" - type: "tool" - tool: "git_diff_analyzer" - - - name: "frontend_tests" - type: "agent" - agent: "frontend_tester" - condition: "${steps.change_detection.outputs.has_frontend_changes}" - - - name: "backend_tests" - type: "agent" - agent: "backend_tester" - condition: "${steps.change_detection.outputs.has_backend_changes}" -``` - -#### Caching and Optimization -```yaml -steps: - - name: "dependency_install" - type: "tool" - tool: "package_manager" - config: - action: "install" - cache_key: "${context.package_lock_hash}" - cache_ttl: "24h" -``` - -## Advanced Features - -### Dynamic Workflow Generation - -```typescript -class DynamicWorkflowGenerator { - async generateWorkflow(context: ProjectContext): Promise { - const workflow: WorkflowDefinition = { - name: `Dynamic workflow for ${context.projectName}`, - steps: [] - }; - - // Add steps based on project characteristics - if (context.hasTypeScript) { - workflow.steps.push({ - name: "typescript_check", - type: "agent", - agent: "typescript_checker" - }); - } - - if (context.hasTests) { - workflow.steps.push({ - name: "run_tests", - type: "tool", - tool: "test_runner", - framework: context.testFramework - }); - } - - if (context.hasDocker) { - workflow.steps.push({ - name: "docker_build", - type: "tool", - tool: "docker", - action: "build" - }); - } - - return workflow; - } -} -``` - -### Workflow Composition - -```yaml -# Compose workflows from reusable components -name: "Full CI/CD Pipeline" -includes: - - workflow: "code_quality_check" - version: "1.2.0" - - workflow: "security_scan" - version: "2.0.0" - - workflow: "deployment" - version: "1.5.0" - -steps: - - name: "quality_gate" - type: "workflow" - workflow: "code_quality_check" - - - name: "security_gate" - type: "workflow" - workflow: "security_scan" - depends_on: ["quality_gate"] - - - name: "deploy_to_staging" - type: "workflow" - workflow: "deployment" - depends_on: ["security_gate"] - inputs: - environment: "staging" -``` - -### Human-in-the-Loop Workflows - -```yaml -steps: - - name: "automated_review" - type: "agent" - agent: "code_reviewer" - - - name: "human_review_decision" - type: "decision" - depends_on: ["automated_review"] - rules: - - condition: "${steps.automated_review.outputs.confidence} < 0.8" - action: "require_human_review" - - condition: "${steps.automated_review.outputs.critical_issues} > 0" - action: "require_human_review" - - condition: "default" - action: "auto_approve" - - - name: "human_review" - type: "human" - condition: "${steps.human_review_decision.action} === 'require_human_review'" - prompt: "Automated review found issues requiring human attention" - form: - - name: "approved" - type: "boolean" - label: "Approve this code?" - - name: "comments" - type: "text" - label: "Additional comments" - timeout: "48h" -``` - -## Next Steps - -Ready to build powerful workflows? Here's your learning path: - -1. **Start Simple**: Create basic workflows with 2-3 steps -2. **Learn Patterns**: Master sequential, parallel, and conditional execution -3. **Integrate Tools**: Connect workflows with external systems -4. **Add Monitoring**: Implement proper logging and error handling -5. **Scale Up**: Build complex multi-agent workflows -6. **Optimize Performance**: Implement caching and parallel execution - -## Related Features - -- [Agents](../agents/overview.md) - Use agents as workflow steps -- [Multi-Agents](../multi-agents/overview.md) - Coordinate multiple agents in workflows -- [MCP Tools](../mcp-tools/overview.md) - Extend workflows with external integrations -- [CLI](../cli/overview.md) - Manage workflows programmatically - -## Community Resources - -- **Workflow Templates**: Pre-built templates for common use cases -- **Best Practices Guide**: Learn from experienced workflow designers -- **Integration Examples**: See how to connect with popular tools -- **Performance Optimization**: Tips for building efficient workflows - -Task Flow transforms how you approach development automation. Instead of writing custom scripts for every process, you can build intelligent, reusable workflows that adapt to changing conditions and integrate seamlessly with your existing tools and processes. diff --git a/docs/developer/core/typescript-sdk/overview.md b/docs/developer/core/typescript-sdk/overview.md deleted file mode 100644 index a483c3be..00000000 --- a/docs/developer/core/typescript-sdk/overview.md +++ /dev/null @@ -1,1435 +0,0 @@ -# TypeScript SDK Overview - -The Codebolt TypeScript SDK empowers developers to build powerful extensions, custom integrations, and sophisticated tools that extend Codebolt AI Editor's capabilities. With full TypeScript support, comprehensive APIs, and rich development tools, you can create everything from simple agents to complex multi-agent systems with excellent developer experience and type safety. - -## Introduction - -While Codebolt provides extensive built-in functionality, every development team has unique needs and workflows. The TypeScript SDK bridges this gap by providing: - -- **Full TypeScript Support** - Complete type definitions and IntelliSense support -- **Comprehensive APIs** - Access to all Codebolt features and capabilities -- **Rich Development Tools** - Debugging, testing, and deployment utilities -- **Extensible Architecture** - Build agents, tools, workflows, and integrations -- **Hot Reloading** - Fast development cycle with instant feedback -- **Production Ready** - Robust error handling and performance optimization - -## Getting Started - -### Installation - -```bash -# Create a new Codebolt extension project -npx create-codebolt-extension my-extension --template typescript - -# Or add to existing project -npm install @codebolt/sdk @codebolt/types -npm install -D @codebolt/dev-tools typescript @types/node -``` - -### Project Structure - -``` -my-extension/ -β”œβ”€β”€ src/ -β”‚ β”œβ”€β”€ agents/ # Custom agents -β”‚ β”œβ”€β”€ tools/ # MCP tools -β”‚ β”œβ”€β”€ workflows/ # Task flows -β”‚ β”œβ”€β”€ integrations/ # External integrations -β”‚ └── index.ts # Main entry point -β”œβ”€β”€ tests/ -β”‚ β”œβ”€β”€ agents.test.ts -β”‚ └── tools.test.ts -β”œβ”€β”€ package.json -β”œβ”€β”€ tsconfig.json -β”œβ”€β”€ codebolt.config.ts # Extension configuration -└── README.md -``` - -### Basic Setup - -```typescript -// src/index.ts -import { CodeboltSDK, ExtensionManifest } from '@codebolt/sdk'; - -const manifest: ExtensionManifest = { - name: 'my-extension', - version: '1.0.0', - description: 'My custom Codebolt extension', - author: 'Your Name', - - agents: ['./agents/code-reviewer'], - tools: ['./tools/api-client'], - workflows: ['./workflows/ci-pipeline'], - - permissions: { - fileSystem: ['read', 'write'], - network: ['https://api.company.com'], - environment: ['NODE_ENV', 'API_KEY'] - } -}; - -export default class MyExtension { - constructor(private sdk: CodeboltSDK) {} - - async initialize(): Promise { - console.log('My extension initialized'); - - // Register event handlers - this.sdk.events.on('project:opened', this.onProjectOpened.bind(this)); - this.sdk.events.on('file:saved', this.onFileSaved.bind(this)); - } - - private async onProjectOpened(project: Project): Promise { - console.log(`Project opened: ${project.name}`); - } - - private async onFileSaved(file: SourceFile): Promise { - console.log(`File saved: ${file.path}`); - } -} -``` - -## Core SDK APIs - -### Project and File Management - -```typescript -import { ProjectManager, FileManager, SourceFile } from '@codebolt/sdk'; - -class ProjectOperations { - constructor( - private projectManager: ProjectManager, - private fileManager: FileManager - ) {} - - async analyzeProject(): Promise { - const project = await this.projectManager.getCurrentProject(); - - // Get project structure - const structure = await project.getStructure(); - - // Analyze dependencies - const dependencies = await project.getDependencies(); - - // Get configuration files - const configs = await project.getConfigFiles(); - - return { - name: project.name, - type: project.type, - structure, - dependencies, - configs, - metrics: await this.calculateMetrics(project) - }; - } - - async processFiles(pattern: string): Promise { - const files = await this.fileManager.glob(pattern); - const results: ProcessingResult[] = []; - - for (const file of files) { - try { - const content = await file.read(); - const ast = await file.parse(); - - const result = await this.processFile(file, content, ast); - results.push(result); - } catch (error) { - results.push({ - file: file.path, - success: false, - error: error.message - }); - } - } - - return results; - } - - private async processFile( - file: SourceFile, - content: string, - ast: AST - ): Promise { - // Custom file processing logic - const issues = await this.analyzeAST(ast); - const suggestions = await this.generateSuggestions(content, ast); - - return { - file: file.path, - success: true, - issues, - suggestions - }; - } -} -``` - -### AI and Language Models - -```typescript -import { AIService, LanguageModel, ChatCompletion } from '@codebolt/sdk'; - -class AIOperations { - constructor(private ai: AIService) {} - - async analyzeCode(code: string, language: string): Promise { - const model = await this.ai.getModel('gpt-4'); - - const prompt = ` - Analyze this ${language} code for: - 1. Code quality issues - 2. Performance problems - 3. Security vulnerabilities - 4. Best practice violations - - Code: - ${code} - - Provide specific, actionable feedback with examples. - `; - - const response = await model.complete({ - messages: [{ role: 'user', content: prompt }], - temperature: 0.1, - max_tokens: 2000 - }); - - return this.parseAnalysisResponse(response.content); - } - - async generateCode(specification: CodeSpecification): Promise { - const model = await this.ai.getModel('gpt-4'); - - const prompt = this.buildGenerationPrompt(specification); - - const response = await model.complete({ - messages: [{ role: 'user', content: prompt }], - temperature: 0.2, - max_tokens: 3000 - }); - - return { - code: this.extractCode(response.content), - explanation: this.extractExplanation(response.content), - tests: await this.generateTests(specification) - }; - } - - async streamCompletion(prompt: string): Promise> { - const model = await this.ai.getModel('gpt-4'); - - return model.stream({ - messages: [{ role: 'user', content: prompt }], - temperature: 0.3 - }); - } -} -``` - -### Context and State Management - -```typescript -import { ContextManager, StateManager, SharedContext } from '@codebolt/sdk'; - -class ContextOperations { - constructor( - private contextManager: ContextManager, - private stateManager: StateManager - ) {} - - async getProjectContext(): Promise { - const context = await this.contextManager.getProjectContext(); - - return { - structure: context.structure, - dependencies: context.dependencies, - conventions: context.conventions, - patterns: context.patterns, - preferences: context.preferences - }; - } - - async updateContext(updates: ContextUpdate[]): Promise { - for (const update of updates) { - await this.contextManager.updateContext(update.key, update.value, { - source: 'my-extension', - timestamp: new Date(), - version: update.version - }); - } - - // Notify other extensions of context changes - await this.contextManager.notifyContextChange(updates); - } - - async manageState(key: string, initialValue: T): Promise> { - return this.stateManager.create(key, initialValue, { - persistent: true, - shared: false, - ttl: 3600000 // 1 hour - }); - } - - async shareDataWithAgents(data: SharedData): Promise { - const sharedContext = await this.contextManager.getSharedContext(); - - await sharedContext.set('extension-data', data, { - ttl: 1800000, // 30 minutes - permissions: ['read', 'write'], - subscribers: ['all-agents'] - }); - } -} -``` - -## Building Custom Agents - -### Agent Base Class - -```typescript -import { CodeboltAgent, AgentConfig, AgentResult } from '@codebolt/sdk'; - -export class CustomCodeReviewer extends CodeboltAgent { - constructor(config: AgentConfig) { - super({ - name: 'Custom Code Reviewer', - version: '1.0.0', - description: 'Advanced code review with team-specific rules', - capabilities: ['analyze', 'suggest', 'fix'], - ...config - }); - } - - async initialize(): Promise { - await super.initialize(); - - // Load team-specific rules - this.rules = await this.loadTeamRules(); - - // Initialize AI models - this.codeModel = await this.ai.getModel('gpt-4'); - this.securityModel = await this.ai.getModel('security-specialist'); - } - - async execute(input: AgentInput): Promise { - try { - const { code, filePath, context } = input; - - // Multi-stage analysis - const results = await Promise.all([ - this.analyzeCodeQuality(code, filePath), - this.analyzeSecurity(code, filePath), - this.analyzePerformance(code, filePath), - this.analyzeTeamConventions(code, context) - ]); - - // Consolidate results - const consolidated = await this.consolidateResults(results); - - // Generate fixes if requested - if (input.generateFixes) { - consolidated.fixes = await this.generateFixes(code, consolidated.issues); - } - - return { - success: true, - results: consolidated, - metadata: { - executionTime: Date.now() - input.startTime, - rulesApplied: this.rules.length, - confidence: this.calculateConfidence(consolidated) - } - }; - } catch (error) { - return { - success: false, - error: { - message: error.message, - stack: error.stack, - code: 'ANALYSIS_FAILED' - } - }; - } - } - - private async analyzeCodeQuality(code: string, filePath: string): Promise { - const prompt = ` - Analyze this code for quality issues: - - File: ${filePath} - Code: - ${code} - - Focus on: - - Code complexity and readability - - Naming conventions - - Function/class design - - Error handling - - Documentation - - Team rules: - ${this.rules.map(rule => `- ${rule.description}`).join('\n')} - `; - - const response = await this.codeModel.complete({ - messages: [{ role: 'user', content: prompt }], - temperature: 0.1 - }); - - return this.parseQualityAnalysis(response.content); - } - - private async analyzeSecurity(code: string, filePath: string): Promise { - // Security-specific analysis using specialized model - const vulnerabilities = await this.securityModel.analyze(code, { - language: this.detectLanguage(filePath), - context: 'web_application', - severity_threshold: 'medium' - }); - - return { - vulnerabilities, - recommendations: await this.generateSecurityRecommendations(vulnerabilities) - }; - } - - private async generateFixes(code: string, issues: Issue[]): Promise { - const fixes: Fix[] = []; - - for (const issue of issues) { - if (issue.fixable) { - const fix = await this.generateFix(code, issue); - if (fix) { - fixes.push(fix); - } - } - } - - return fixes; - } -} -``` - -### Agent Registration and Lifecycle - -```typescript -// src/agents/index.ts -import { AgentRegistry } from '@codebolt/sdk'; -import { CustomCodeReviewer } from './code-reviewer'; -import { SecurityAnalyzer } from './security-analyzer'; -import { PerformanceOptimizer } from './performance-optimizer'; - -export class AgentManager { - constructor(private registry: AgentRegistry) {} - - async registerAgents(): Promise { - // Register custom agents - await this.registry.register('custom-code-reviewer', CustomCodeReviewer, { - autoStart: true, - triggers: ['file_save', 'git_commit'], - priority: 'high' - }); - - await this.registry.register('security-analyzer', SecurityAnalyzer, { - autoStart: false, - triggers: ['manual', 'pre_commit'], - priority: 'critical' - }); - - await this.registry.register('performance-optimizer', PerformanceOptimizer, { - autoStart: true, - triggers: ['file_save'], - conditions: ['file_size > 1000', 'complexity > 5'] - }); - } - - async configureAgents(): Promise { - // Configure agents with team-specific settings - await this.registry.configure('custom-code-reviewer', { - rules: await this.loadTeamRules(), - confidence_threshold: 0.8, - auto_fix: false, - notification_channels: ['slack', 'email'] - }); - } -} -``` - -## Building MCP Tools - -### Tool Implementation - -```typescript -import { MCPTool, ToolConfig, ToolRequest, ToolResponse } from '@codebolt/sdk'; - -export class DatabaseTool implements MCPTool { - name = 'database-operations'; - version = '1.0.0'; - capabilities = { - actions: ['query', 'migrate', 'backup', 'analyze'], - inputs: ['sql', 'migration_file', 'connection_string'], - outputs: ['query_result', 'migration_result', 'backup_info'] - }; - - private connection: DatabaseConnection | null = null; - - async initialize(config: ToolConfig): Promise { - this.connection = await this.createConnection(config.database); - - // Test connection - await this.connection.ping(); - - // Setup connection pool - await this.connection.setupPool({ - min: 2, - max: 10, - acquireTimeoutMillis: 30000, - idleTimeoutMillis: 600000 - }); - } - - async execute(request: ToolRequest): Promise { - if (!this.connection) { - throw new Error('Database connection not initialized'); - } - - switch (request.action) { - case 'query': - return await this.executeQuery(request.arguments); - case 'migrate': - return await this.runMigration(request.arguments); - case 'backup': - return await this.createBackup(request.arguments); - case 'analyze': - return await this.analyzeSchema(request.arguments); - default: - throw new Error(`Unknown action: ${request.action}`); - } - } - - private async executeQuery(args: QueryArgs): Promise { - const startTime = Date.now(); - - try { - // Validate query - await this.validateQuery(args.query); - - // Execute with timeout - const result = await this.connection!.query(args.query, args.params, { - timeout: args.timeout || 30000 - }); - - return { - success: true, - data: { - rows: result.rows, - rowCount: result.rowCount, - fields: result.fields?.map(f => ({ - name: f.name, - type: f.dataTypeID, - nullable: f.nullable - })) - }, - metadata: { - executionTime: Date.now() - startTime, - query: args.query, - cached: result.cached - } - }; - } catch (error) { - return { - success: false, - error: { - message: error.message, - code: error.code, - severity: this.mapErrorSeverity(error), - query: args.query - } - }; - } - } - - private async runMigration(args: MigrationArgs): Promise { - const transaction = await this.connection!.beginTransaction(); - - try { - // Create backup before migration - const backup = await this.createBackup({ - name: `pre_migration_${Date.now()}` - }); - - // Run migration - const migrationResult = await this.executeMigrationFile( - args.migrationFile, - transaction - ); - - // Verify migration - const verification = await this.verifyMigration( - migrationResult, - transaction - ); - - if (verification.success) { - await transaction.commit(); - return { - success: true, - data: { - migration: migrationResult, - verification, - backup: backup.data - } - }; - } else { - await transaction.rollback(); - return { - success: false, - error: { - message: 'Migration verification failed', - details: verification.errors - } - }; - } - } catch (error) { - await transaction.rollback(); - throw error; - } - } - - async cleanup(): Promise { - if (this.connection) { - await this.connection.close(); - this.connection = null; - } - } -} -``` - -### Tool Testing - -```typescript -// tests/tools/database-tool.test.ts -import { DatabaseTool } from '../../src/tools/database-tool'; -import { createMockDatabase } from '@codebolt/test-utils'; - -describe('DatabaseTool', () => { - let tool: DatabaseTool; - let mockDb: MockDatabase; - - beforeEach(async () => { - mockDb = await createMockDatabase(); - tool = new DatabaseTool(); - - await tool.initialize({ - database: mockDb.getConnectionConfig() - }); - }); - - afterEach(async () => { - await tool.cleanup(); - await mockDb.cleanup(); - }); - - describe('query execution', () => { - it('should execute simple queries', async () => { - // Setup test data - await mockDb.seed('users', [ - { id: 1, name: 'John Doe', email: 'john@example.com' }, - { id: 2, name: 'Jane Smith', email: 'jane@example.com' } - ]); - - const result = await tool.execute({ - action: 'query', - arguments: { - query: 'SELECT * FROM users WHERE id = $1', - params: [1] - } - }); - - expect(result.success).toBe(true); - expect(result.data.rows).toHaveLength(1); - expect(result.data.rows[0].name).toBe('John Doe'); - }); - - it('should handle query errors gracefully', async () => { - const result = await tool.execute({ - action: 'query', - arguments: { - query: 'SELECT * FROM non_existent_table' - } - }); - - expect(result.success).toBe(false); - expect(result.error.message).toContain('does not exist'); - }); - - it('should validate dangerous queries', async () => { - const result = await tool.execute({ - action: 'query', - arguments: { - query: 'DROP TABLE users' - } - }); - - expect(result.success).toBe(false); - expect(result.error.message).toContain('Dangerous query detected'); - }); - }); - - describe('migrations', () => { - it('should run migrations successfully', async () => { - const migrationSql = ` - CREATE TABLE test_table ( - id SERIAL PRIMARY KEY, - name VARCHAR(255) NOT NULL - ); - `; - - const result = await tool.execute({ - action: 'migrate', - arguments: { - migrationFile: 'create_test_table.sql', - sql: migrationSql - } - }); - - expect(result.success).toBe(true); - expect(result.data.migration.tables_created).toContain('test_table'); - }); - - it('should rollback failed migrations', async () => { - const invalidMigrationSql = ` - CREATE TABLE test_table ( - id INVALID_TYPE PRIMARY KEY - ); - `; - - const result = await tool.execute({ - action: 'migrate', - arguments: { - migrationFile: 'invalid_migration.sql', - sql: invalidMigrationSql - } - }); - - expect(result.success).toBe(false); - - // Verify rollback - table should not exist - const checkResult = await tool.execute({ - action: 'query', - arguments: { - query: "SELECT table_name FROM information_schema.tables WHERE table_name = 'test_table'" - } - }); - - expect(checkResult.data.rows).toHaveLength(0); - }); - }); -}); -``` - -## Building Workflows - -### Workflow Definition - -```typescript -import { Workflow, WorkflowStep, WorkflowContext } from '@codebolt/sdk'; - -export class CIWorkflow extends Workflow { - constructor() { - super({ - name: 'Continuous Integration', - version: '1.0.0', - description: 'Complete CI pipeline with quality gates' - }); - } - - async defineSteps(): Promise { - return [ - { - id: 'setup', - name: 'Environment Setup', - type: 'parallel', - steps: [ - { - id: 'install_deps', - name: 'Install Dependencies', - executor: this.installDependencies.bind(this) - }, - { - id: 'setup_env', - name: 'Setup Environment', - executor: this.setupEnvironment.bind(this) - } - ] - }, - - { - id: 'quality_checks', - name: 'Quality Checks', - dependsOn: ['setup'], - type: 'parallel', - steps: [ - { - id: 'lint', - name: 'Linting', - agent: 'linter', - continueOnError: false - }, - { - id: 'type_check', - name: 'Type Checking', - agent: 'type-checker', - continueOnError: false - }, - { - id: 'security_scan', - name: 'Security Scan', - agent: 'security-scanner', - continueOnError: true - } - ] - }, - - { - id: 'testing', - name: 'Testing', - dependsOn: ['quality_checks'], - condition: this.qualityChecksPassedCondition.bind(this), - type: 'sequential', - steps: [ - { - id: 'unit_tests', - name: 'Unit Tests', - executor: this.runUnitTests.bind(this) - }, - { - id: 'integration_tests', - name: 'Integration Tests', - executor: this.runIntegrationTests.bind(this), - condition: this.unitTestsPassedCondition.bind(this) - }, - { - id: 'e2e_tests', - name: 'E2E Tests', - executor: this.runE2ETests.bind(this), - condition: this.integrationTestsPassedCondition.bind(this) - } - ] - }, - - { - id: 'build', - name: 'Build Application', - dependsOn: ['testing'], - condition: this.allTestsPassedCondition.bind(this), - executor: this.buildApplication.bind(this) - }, - - { - id: 'deploy', - name: 'Deploy to Staging', - dependsOn: ['build'], - condition: this.buildSuccessCondition.bind(this), - executor: this.deployToStaging.bind(this) - } - ]; - } - - private async installDependencies(context: WorkflowContext): Promise { - const packageManager = this.detectPackageManager(context.projectPath); - - try { - await this.exec(`${packageManager} install`, { - cwd: context.projectPath, - timeout: 300000 // 5 minutes - }); - - return { - success: true, - outputs: { packageManager, installed: true } - }; - } catch (error) { - return { - success: false, - error: error.message - }; - } - } - - private async runUnitTests(context: WorkflowContext): Promise { - const testCommand = this.getTestCommand(context.projectPath); - - try { - const result = await this.exec(testCommand, { - cwd: context.projectPath, - timeout: 600000 // 10 minutes - }); - - const coverage = await this.parseCoverageReport(result.stdout); - - return { - success: result.exitCode === 0, - outputs: { - coverage, - testResults: this.parseTestResults(result.stdout) - } - }; - } catch (error) { - return { - success: false, - error: error.message - }; - } - } - - private async buildApplication(context: WorkflowContext): Promise { - const buildCommand = this.getBuildCommand(context.projectPath); - - try { - const result = await this.exec(buildCommand, { - cwd: context.projectPath, - timeout: 900000 // 15 minutes - }); - - const buildStats = await this.analyzeBuildOutput(result.stdout); - - return { - success: result.exitCode === 0, - outputs: { - buildStats, - artifacts: await this.collectBuildArtifacts(context.projectPath) - } - }; - } catch (error) { - return { - success: false, - error: error.message - }; - } - } - - // Condition functions - private async qualityChecksPassedCondition(context: WorkflowContext): Promise { - const qualityResults = context.getStepResults('quality_checks'); - return qualityResults.every(result => result.success); - } - - private async allTestsPassedCondition(context: WorkflowContext): Promise { - const testResults = context.getStepResults('testing'); - return testResults.every(result => result.success); - } -} -``` - -### Workflow Registration - -```typescript -// src/workflows/index.ts -import { WorkflowRegistry } from '@codebolt/sdk'; -import { CIWorkflow } from './ci-workflow'; -import { DeploymentWorkflow } from './deployment-workflow'; -import { CodeQualityWorkflow } from './code-quality-workflow'; - -export class WorkflowManager { - constructor(private registry: WorkflowRegistry) {} - - async registerWorkflows(): Promise { - await this.registry.register('ci-pipeline', CIWorkflow, { - triggers: [ - { type: 'git_push', branches: ['main', 'develop'] }, - { type: 'pull_request', target_branches: ['main'] } - ], - timeout: '30m', - retryPolicy: { - maxRetries: 2, - backoffStrategy: 'exponential' - } - }); - - await this.registry.register('deployment', DeploymentWorkflow, { - triggers: [ - { type: 'manual' }, - { type: 'workflow_completed', workflow: 'ci-pipeline' } - ], - requiredApproval: true, - environments: ['staging', 'production'] - }); - - await this.registry.register('code-quality', CodeQualityWorkflow, { - triggers: [ - { type: 'file_save', patterns: ['src/**/*.{ts,tsx,js,jsx}'] } - ], - debounce: 2000, - parallel: true - }); - } -} -``` - -## Development Tools and Testing - -### Development Environment - -```typescript -// codebolt.config.ts -import { defineConfig } from '@codebolt/sdk'; - -export default defineConfig({ - development: { - hotReload: true, - debugMode: true, - logLevel: 'debug', - mockServices: { - ai: true, - database: true, - external_apis: true - } - }, - - testing: { - testEnvironment: 'node', - setupFilesAfterEnv: ['/tests/setup.ts'], - testMatch: ['**/*.test.ts'], - collectCoverageFrom: [ - 'src/**/*.ts', - '!src/**/*.d.ts', - '!src/tests/**' - ] - }, - - build: { - target: 'node16', - format: 'esm', - minify: true, - sourcemap: true, - external: ['@codebolt/sdk'] - } -}); -``` - -### Testing Utilities - -```typescript -// tests/utils/test-helpers.ts -import { - createMockSDK, - createMockProject, - createMockAgent, - TestEnvironment -} from '@codebolt/test-utils'; - -export class ExtensionTestSuite { - private testEnv: TestEnvironment; - - async setup(): Promise { - this.testEnv = await TestEnvironment.create({ - extensions: ['./src/index.ts'], - mockServices: ['ai', 'database', 'git'], - projectFixtures: './tests/fixtures/projects' - }); - - await this.testEnv.initialize(); - } - - async teardown(): Promise { - await this.testEnv.cleanup(); - } - - createMockContext(overrides: Partial = {}): ProjectContext { - return { - name: 'test-project', - type: 'web', - languages: ['typescript'], - frameworks: ['react'], - structure: this.createMockStructure(), - dependencies: this.createMockDependencies(), - ...overrides - }; - } - - async runAgentTest( - agentClass: typeof CodeboltAgent, - input: AgentInput, - expectedOutput?: Partial - ): Promise { - const agent = new agentClass({ - sdk: this.testEnv.getMockSDK(), - config: this.getDefaultAgentConfig() - }); - - await agent.initialize(); - - const result = await agent.execute(input); - - if (expectedOutput) { - expect(result).toMatchObject(expectedOutput); - } - - return result; - } - - async runWorkflowTest( - workflowClass: typeof Workflow, - context: WorkflowContext, - expectedSteps?: string[] - ): Promise { - const workflow = new workflowClass(); - - const result = await this.testEnv.executeWorkflow(workflow, context); - - if (expectedSteps) { - expect(result.executedSteps.map(s => s.id)).toEqual(expectedSteps); - } - - return result; - } -} -``` - -### Integration Testing - -```typescript -// tests/integration/extension.test.ts -import { ExtensionTestSuite } from '../utils/test-helpers'; -import MyExtension from '../../src/index'; - -describe('MyExtension Integration Tests', () => { - let testSuite: ExtensionTestSuite; - let extension: MyExtension; - - beforeAll(async () => { - testSuite = new ExtensionTestSuite(); - await testSuite.setup(); - - extension = new MyExtension(testSuite.getMockSDK()); - await extension.initialize(); - }); - - afterAll(async () => { - await testSuite.teardown(); - }); - - describe('Project Analysis', () => { - it('should analyze TypeScript React projects correctly', async () => { - const mockProject = testSuite.createMockProject({ - type: 'react-typescript', - files: [ - 'src/App.tsx', - 'src/components/Button.tsx', - 'package.json', - 'tsconfig.json' - ] - }); - - testSuite.setCurrentProject(mockProject); - - const analysis = await extension.analyzeProject(); - - expect(analysis.type).toBe('web'); - expect(analysis.languages).toContain('typescript'); - expect(analysis.frameworks).toContain('react'); - expect(analysis.structure.components).toHaveLength(1); - }); - }); - - describe('Agent Integration', () => { - it('should integrate custom agents with workflows', async () => { - const workflowResult = await testSuite.runWorkflow('ci-pipeline', { - projectPath: '/test/project', - branch: 'main', - commitSha: 'abc123' - }); - - expect(workflowResult.success).toBe(true); - expect(workflowResult.executedSteps).toContain('custom-code-review'); - - const agentResults = workflowResult.stepResults.find( - r => r.stepId === 'custom-code-review' - ); - - expect(agentResults.outputs.issues).toBeDefined(); - expect(agentResults.outputs.suggestions).toBeDefined(); - }); - }); -}); -``` - -## Deployment and Distribution - -### Extension Packaging - -```typescript -// scripts/build.ts -import { ExtensionBuilder } from '@codebolt/sdk/build'; - -const builder = new ExtensionBuilder({ - entry: './src/index.ts', - outDir: './dist', - target: 'node16', - format: 'esm', - minify: true, - - assets: [ - './README.md', - './LICENSE', - './package.json' - ], - - externals: [ - '@codebolt/sdk', - '@codebolt/types' - ] -}); - -async function build() { - console.log('Building extension...'); - - await builder.build(); - - console.log('Creating package...'); - - await builder.package({ - format: 'cbx', // Codebolt Extension format - output: './dist/my-extension.cbx', - sign: true, - keyFile: process.env.SIGNING_KEY - }); - - console.log('Extension built successfully!'); -} - -build().catch(console.error); -``` - -### Publishing - -```json -{ - "name": "my-extension", - "version": "1.0.0", - "description": "My custom Codebolt extension", - "main": "dist/index.js", - "types": "dist/index.d.ts", - - "codebolt": { - "extension": true, - "minVersion": "1.0.0", - "maxVersion": "2.0.0", - "categories": ["code-quality", "automation"], - "permissions": { - "fileSystem": ["read", "write"], - "network": ["https://api.company.com"], - "ai": ["gpt-4", "claude-3"] - } - }, - - "scripts": { - "build": "tsx scripts/build.ts", - "test": "jest", - "publish": "codebolt extension publish", - "dev": "codebolt extension dev --watch" - }, - - "dependencies": { - "@codebolt/sdk": "^1.0.0" - }, - - "devDependencies": { - "@codebolt/dev-tools": "^1.0.0", - "@codebolt/test-utils": "^1.0.0", - "typescript": "^5.0.0", - "jest": "^29.0.0", - "tsx": "^4.0.0" - } -} -``` - -### CLI Publishing - -```bash -# Build the extension -npm run build - -# Test the extension locally -codebolt extension test ./dist/my-extension.cbx - -# Publish to Codebolt registry -codebolt extension publish ./dist/my-extension.cbx \ - --category "code-quality" \ - --tags "typescript,react,automation" \ - --visibility public - -# Publish to npm for community distribution -npm publish -``` - -## Best Practices - -### Error Handling - -```typescript -import { CodeboltError, ErrorCode } from '@codebolt/sdk'; - -class RobustAgent extends CodeboltAgent { - async execute(input: AgentInput): Promise { - try { - return await this.performAnalysis(input); - } catch (error) { - return this.handleError(error, input); - } - } - - private handleError(error: Error, input: AgentInput): AgentResult { - if (error instanceof CodeboltError) { - return { - success: false, - error: { - code: error.code, - message: error.message, - recoverable: error.recoverable, - suggestions: error.suggestions - } - }; - } - - // Handle specific error types - if (error.name === 'TimeoutError') { - return { - success: false, - error: { - code: ErrorCode.TIMEOUT, - message: 'Operation timed out', - recoverable: true, - suggestions: ['Try with a smaller input', 'Increase timeout limit'] - } - }; - } - - // Generic error handling - return { - success: false, - error: { - code: ErrorCode.UNKNOWN, - message: error.message, - recoverable: false - } - }; - } -} -``` - -### Performance Optimization - -```typescript -import { PerformanceMonitor, Cache } from '@codebolt/sdk'; - -class OptimizedAgent extends CodeboltAgent { - private cache = new Cache({ - maxSize: 1000, - ttl: 3600000 // 1 hour - }); - - private monitor = new PerformanceMonitor(); - - async execute(input: AgentInput): Promise { - const timer = this.monitor.startTimer('agent_execution'); - - try { - // Check cache first - const cacheKey = this.generateCacheKey(input); - const cached = await this.cache.get(cacheKey); - - if (cached) { - timer.end({ cache_hit: true }); - return { success: true, results: cached }; - } - - // Perform analysis - const result = await this.performAnalysis(input); - - // Cache successful results - if (result.success) { - await this.cache.set(cacheKey, result.results); - } - - timer.end({ cache_hit: false }); - return result; - } catch (error) { - timer.end({ error: true }); - throw error; - } - } - - private generateCacheKey(input: AgentInput): string { - return `${input.filePath}:${input.contentHash}:${this.version}`; - } -} -``` - -### Memory Management - -```typescript -class MemoryEfficientAgent extends CodeboltAgent { - private processLargeFile = async (file: SourceFile): Promise => { - // Process file in chunks to avoid memory issues - const chunkSize = 10000; // 10KB chunks - const results: AnalysisResult[] = []; - - const stream = file.createReadStream(); - let buffer = ''; - - for await (const chunk of stream) { - buffer += chunk; - - while (buffer.length >= chunkSize) { - const chunkToProcess = buffer.slice(0, chunkSize); - buffer = buffer.slice(chunkSize); - - const chunkResult = await this.processChunk(chunkToProcess); - results.push(chunkResult); - - // Explicit garbage collection hint - if (global.gc) global.gc(); - } - } - - // Process remaining buffer - if (buffer.length > 0) { - const chunkResult = await this.processChunk(buffer); - results.push(chunkResult); - } - - return this.mergeResults(results); - }; -} -``` - -## Next Steps - -Ready to build powerful Codebolt extensions? Here's your development path: - -1. **Start with Simple Extensions**: Create basic agents and tools -2. **Learn the SDK APIs**: Master the core SDK functionality -3. **Build Complex Workflows**: Create sophisticated automation -4. **Add Testing**: Implement comprehensive test suites -5. **Optimize Performance**: Use caching, monitoring, and optimization techniques -6. **Publish and Share**: Distribute your extensions to the community - -## Related Documentation - -- [Agents](../agents/overview.md) - Learn about the agent system you'll be extending -- [MCP Tools](../mcp-tools/overview.md) - Understand the tool architecture -- [Task Flow](../task-flow/overview.md) - Build custom workflow components -- [API Reference](../../api-reference.md) - Complete SDK API documentation - -## Community Resources - -- **SDK Examples**: Real-world extension examples -- **Template Library**: Starter templates for common use cases -- **Developer Forum**: Get help with SDK development -- **Best Practices Guide**: Learn from experienced extension developers - -The TypeScript SDK opens up unlimited possibilities for extending Codebolt. From simple automation scripts to sophisticated AI-powered development tools, you have the power to create exactly what your team needs with excellent developer experience and type safety. diff --git a/docs/developer/structure.md b/docs/developer/structure.md new file mode 100644 index 00000000..fdf834d3 --- /dev/null +++ b/docs/developer/structure.md @@ -0,0 +1,36 @@ +# Structure + +``` + +Get Started +β”œβ”€β”€ introduction.md # Welcome page +β”œβ”€β”€ installation.md +β”œβ”€β”€ quickstart.md +└── concepts.md # Single file with concise introductions (1-2 paragraphs each) to core concepts: Agents, Multi-Agents, MCP Tools, Inline Edit, Chats, Task Flow, Context, CLI, and TypeScript SDK. Each section includes a link to the corresponding detailed page in the Core section for deeper exploration. + +Core Concepts: +β”‚ β”œβ”€β”€ agents/ # Directory for Agents +β”‚ β”‚ β”œβ”€β”€ overview.md # Detailed overview of Agents: +β”‚ β”‚ β”œβ”€β”€ custom-agent.md # Guide to creating custom agents: +β”‚ β”‚ └── remix-agent.md # Guide to remixing agents: + │── multi-agents/ # Directory for Multi-Agents +β”‚ β”‚ └── overview.md # Comprehensive guide: +β”‚ β”œβ”€β”€ inline-edit/ # Directory for Inline Edit: +β”‚ β”‚ └── overview.md # In-depth guide: +β”‚ β”œβ”€β”€ mcp-tools/ # Directory for MCP Tools: +β”‚ β”‚ └── overview.md # Detailed guide: +β”‚ β”œβ”€β”€ chats/ # Directory for Chats +β”‚ β”‚ └── overview.md # In-depth guide: +β”‚ β”œβ”€β”€ task-flow/ # Directory for Task Flow +β”‚ β”‚ └── overview.md # Detailed guide: +β”‚ β”œβ”€β”€ context/ # Directory for Context +β”‚ β”‚ └── overview.md # In-depth guide: +β”‚ β”œβ”€β”€ cli/ # Directory for CLI +β”‚ β”‚ └── overview.md # Detailed guide +│── typescript-sdk.md +β”œβ”€β”€ tutorials.md # End-to-end tutorials +β”œβ”€β”€ api-reference.md # API documentation: +β”œβ”€β”€ troubleshooting.md # Support section +β”œβ”€β”€ contributing.md # Contribution guidelines + +``` \ No newline at end of file diff --git a/docs/developer/typescript-sdk/overview.md b/docs/developer/typescript-sdk/overview.md new file mode 100644 index 00000000..c3bebe7c --- /dev/null +++ b/docs/developer/typescript-sdk/overview.md @@ -0,0 +1,3 @@ +## typescipt sdk + +comming soon... \ No newline at end of file diff --git a/docs/developer21/structure.md b/docs/developer21/structure.md deleted file mode 100644 index a3a203a5..00000000 --- a/docs/developer21/structure.md +++ /dev/null @@ -1,75 +0,0 @@ -# Developer Documentation Structure - -``` -developer/ - -Get Started - β”œβ”€β”€ welcom.md # Main landing page with component overview - β”œβ”€β”€ installation.md # AI Agent development - β”œβ”€β”€ quickStart.md/ # MCP Tool development - β”œβ”€β”€ concept/ - |── Agents # Small Introduction - |── Multi-Agents # Small Introduction - |── MCP Tools # Small Introduction - |── Inline Edit (Control+K) # Small Introduction - |── Chats # Small Introduction - |── Task Flow # Small Introduction - |── Context # Small Introduction - |── CLI # Small Introduction - |── typeScriptSdk # Small Introduction -Core - |── Agents/ - |── Overview.md - |── introdcution - |── How Agents Works - |── Agent Architecture - |── Agent Flow - |── Its Type - |── CustomAgent.md - |── Introduction - |── how to create (Explain All Code) - |── Way of creation - |── RemixAgent.md - |──Introduction - |──how to make it Remix Agent - - |── Multi-Agents - |── Introcution basic - |── Inline Edit - Introduction - Example - -``` - -developer/ -β”œβ”€β”€ index.md # Welcome page -β”œβ”€β”€ getting-started/ # Onboarding section: -β”‚ β”œβ”€β”€ installation.md -β”‚ β”œβ”€β”€ quickstart.md -β”‚ └── concepts.md # Single file with concise introductions (1-2 paragraphs each) to core concepts: Agents, Multi-Agents, MCP Tools, Inline Edit, Chats, Task Flow, Context, CLI, and TypeScript SDK. Each section includes a link to the corresponding detailed page in the Core section for deeper exploration. - -β”œβ”€β”€ core/ # In-depth guides: -β”‚ β”œβ”€β”€ agents/ # Directory for Agents -β”‚ β”‚ β”œβ”€β”€ overview.md # Detailed overview of Agents: -β”‚ β”‚ β”œβ”€β”€ custom-agent.md # Guide to creating custom agents: -β”‚ β”‚ └── remix-agent.md # Guide to remixing agents: -β”‚ β”œβ”€β”€ multi-agents/ # Directory for Multi-Agents -β”‚ β”‚ └── overview.md # Comprehensive guide: -β”‚ β”œβ”€β”€ inline-edit/ # Directory for Inline Edit: -β”‚ β”‚ └── overview.md # In-depth guide: -β”‚ β”œβ”€β”€ mcp-tools/ # Directory for MCP Tools: -β”‚ β”‚ └── overview.md # Detailed guide: -β”‚ β”œβ”€β”€ chats/ # Directory for Chats -β”‚ β”‚ └── overview.md # In-depth guide: -β”‚ β”œβ”€β”€ task-flow/ # Directory for Task Flow -β”‚ β”‚ └── overview.md # Detailed guide: -β”‚ β”œβ”€β”€ context/ # Directory for Context -β”‚ β”‚ └── overview.md # In-depth guide: -β”‚ β”œβ”€β”€ cli/ # Directory for CLI -β”‚ β”‚ └── overview.md # Detailed guide -β”‚ └── typescript-sdk/ # Directory for TypeScript SDK -β”‚ └── overview.md # In-depth guide: -β”œβ”€β”€ tutorials.md # End-to-end tutorials -β”œβ”€β”€ api-reference.md # API documentation: -β”œβ”€β”€ troubleshooting.md # Support section -β”œβ”€β”€ contributing.md # Contribution guidelines \ No newline at end of file diff --git a/docs/developer21/agents/1_agentarchitecture/1_architecture.md b/docs/developer_old/agents/1_agentarchitecture/1_architecture.md similarity index 100% rename from docs/developer21/agents/1_agentarchitecture/1_architecture.md rename to docs/developer_old/agents/1_agentarchitecture/1_architecture.md diff --git a/docs/developer21/agents/1_agentarchitecture/_category_.json b/docs/developer_old/agents/1_agentarchitecture/_category_.json similarity index 100% rename from docs/developer21/agents/1_agentarchitecture/_category_.json rename to docs/developer_old/agents/1_agentarchitecture/_category_.json diff --git a/docs/developer21/agents/1_agentarchitecture/createagent.md b/docs/developer_old/agents/1_agentarchitecture/createagent.md similarity index 100% rename from docs/developer21/agents/1_agentarchitecture/createagent.md rename to docs/developer_old/agents/1_agentarchitecture/createagent.md diff --git a/docs/developer21/agents/1_agentarchitecture/index.md b/docs/developer_old/agents/1_agentarchitecture/index.md similarity index 100% rename from docs/developer21/agents/1_agentarchitecture/index.md rename to docs/developer_old/agents/1_agentarchitecture/index.md diff --git a/docs/developer21/agents/2_usingagents/5_runAgent.md b/docs/developer_old/agents/2_usingagents/5_runAgent.md similarity index 100% rename from docs/developer21/agents/2_usingagents/5_runAgent.md rename to docs/developer_old/agents/2_usingagents/5_runAgent.md diff --git a/docs/developer21/agents/2_usingagents/_category_.json b/docs/developer_old/agents/2_usingagents/_category_.json similarity index 100% rename from docs/developer21/agents/2_usingagents/_category_.json rename to docs/developer_old/agents/2_usingagents/_category_.json diff --git a/docs/developer21/agents/2_usingagents/index.md b/docs/developer_old/agents/2_usingagents/index.md similarity index 100% rename from docs/developer21/agents/2_usingagents/index.md rename to docs/developer_old/agents/2_usingagents/index.md diff --git a/docs/developer21/agents/3_advancagent.md b/docs/developer_old/agents/3_advancagent.md similarity index 100% rename from docs/developer21/agents/3_advancagent.md rename to docs/developer_old/agents/3_advancagent.md diff --git a/docs/developer21/agents/3_customagents/3_firstExtension.md b/docs/developer_old/agents/3_customagents/3_firstExtension.md similarity index 100% rename from docs/developer21/agents/3_customagents/3_firstExtension.md rename to docs/developer_old/agents/3_customagents/3_firstExtension.md diff --git a/docs/developer21/agents/3_customagents/4_runExtension.md b/docs/developer_old/agents/3_customagents/4_runExtension.md similarity index 100% rename from docs/developer21/agents/3_customagents/4_runExtension.md rename to docs/developer_old/agents/3_customagents/4_runExtension.md diff --git a/docs/developer21/agents/3_customagents/6_publishExtension.md b/docs/developer_old/agents/3_customagents/6_publishExtension.md similarity index 100% rename from docs/developer21/agents/3_customagents/6_publishExtension.md rename to docs/developer_old/agents/3_customagents/6_publishExtension.md diff --git a/docs/developer21/agents/3_customagents/_category_.json b/docs/developer_old/agents/3_customagents/_category_.json similarity index 100% rename from docs/developer21/agents/3_customagents/_category_.json rename to docs/developer_old/agents/3_customagents/_category_.json diff --git a/docs/developer21/agents/3_customagents/index.md b/docs/developer_old/agents/3_customagents/index.md similarity index 100% rename from docs/developer21/agents/3_customagents/index.md rename to docs/developer_old/agents/3_customagents/index.md diff --git a/docs/developer21/agents/4_remixagents/_category_.json b/docs/developer_old/agents/4_remixagents/_category_.json similarity index 100% rename from docs/developer21/agents/4_remixagents/_category_.json rename to docs/developer_old/agents/4_remixagents/_category_.json diff --git a/docs/developer21/agents/4_remixagents/aboutremixagents.md b/docs/developer_old/agents/4_remixagents/aboutremixagents.md similarity index 100% rename from docs/developer21/agents/4_remixagents/aboutremixagents.md rename to docs/developer_old/agents/4_remixagents/aboutremixagents.md diff --git a/docs/developer21/agents/agentIntroduction.md b/docs/developer_old/agents/agentIntroduction.md similarity index 100% rename from docs/developer21/agents/agentIntroduction.md rename to docs/developer_old/agents/agentIntroduction.md diff --git a/docs/developer21/agents/multi-agent.md b/docs/developer_old/agents/multi-agent.md similarity index 100% rename from docs/developer21/agents/multi-agent.md rename to docs/developer_old/agents/multi-agent.md diff --git a/docs/developer21/agents/quickstart.md b/docs/developer_old/agents/quickstart.md similarity index 100% rename from docs/developer21/agents/quickstart.md rename to docs/developer_old/agents/quickstart.md diff --git a/docs/developer21/cli/agents.md b/docs/developer_old/cli/agents.md similarity index 100% rename from docs/developer21/cli/agents.md rename to docs/developer_old/cli/agents.md diff --git a/docs/developer21/cli/authentication.md b/docs/developer_old/cli/authentication.md similarity index 100% rename from docs/developer21/cli/authentication.md rename to docs/developer_old/cli/authentication.md diff --git a/docs/developer21/cli/commands.md b/docs/developer_old/cli/commands.md similarity index 100% rename from docs/developer21/cli/commands.md rename to docs/developer_old/cli/commands.md diff --git a/docs/developer21/cli/examples.md b/docs/developer_old/cli/examples.md similarity index 100% rename from docs/developer21/cli/examples.md rename to docs/developer_old/cli/examples.md diff --git a/docs/developer21/cli/installation.md b/docs/developer_old/cli/installation.md similarity index 100% rename from docs/developer21/cli/installation.md rename to docs/developer_old/cli/installation.md diff --git a/docs/developer21/cli/overview.md b/docs/developer_old/cli/overview.md similarity index 100% rename from docs/developer21/cli/overview.md rename to docs/developer_old/cli/overview.md diff --git a/docs/developer21/cli/tools.md b/docs/developer_old/cli/tools.md similarity index 100% rename from docs/developer21/cli/tools.md rename to docs/developer_old/cli/tools.md diff --git a/docs/developer21/overview.md b/docs/developer_old/overview.md similarity index 100% rename from docs/developer21/overview.md rename to docs/developer_old/overview.md diff --git a/docs/developer21/templates/best-practices.md b/docs/developer_old/templates/best-practices.md similarity index 100% rename from docs/developer21/templates/best-practices.md rename to docs/developer_old/templates/best-practices.md diff --git a/docs/developer21/templates/configuration.md b/docs/developer_old/templates/configuration.md similarity index 100% rename from docs/developer21/templates/configuration.md rename to docs/developer_old/templates/configuration.md diff --git a/docs/developer21/templates/creating-templates.md b/docs/developer_old/templates/creating-templates.md similarity index 100% rename from docs/developer21/templates/creating-templates.md rename to docs/developer_old/templates/creating-templates.md diff --git a/docs/developer21/templates/examples.md b/docs/developer_old/templates/examples.md similarity index 100% rename from docs/developer21/templates/examples.md rename to docs/developer_old/templates/examples.md diff --git a/docs/developer21/templates/overview.md b/docs/developer_old/templates/overview.md similarity index 100% rename from docs/developer21/templates/overview.md rename to docs/developer_old/templates/overview.md diff --git a/docs/developer21/templates/publishing.md b/docs/developer_old/templates/publishing.md similarity index 100% rename from docs/developer21/templates/publishing.md rename to docs/developer_old/templates/publishing.md diff --git a/docs/developer21/tools/create_tool.md b/docs/developer_old/tools/create_tool.md similarity index 100% rename from docs/developer21/tools/create_tool.md rename to docs/developer_old/tools/create_tool.md diff --git a/docs/developer21/tools/examples.md b/docs/developer_old/tools/examples.md similarity index 100% rename from docs/developer21/tools/examples.md rename to docs/developer_old/tools/examples.md diff --git a/docs/developer21/tools/overview.md b/docs/developer_old/tools/overview.md similarity index 100% rename from docs/developer21/tools/overview.md rename to docs/developer_old/tools/overview.md diff --git a/docs/developer21/tools/publish_tool.md b/docs/developer_old/tools/publish_tool.md similarity index 100% rename from docs/developer21/tools/publish_tool.md rename to docs/developer_old/tools/publish_tool.md diff --git a/docs/developer21/tools/quickstart.md b/docs/developer_old/tools/quickstart.md similarity index 100% rename from docs/developer21/tools/quickstart.md rename to docs/developer_old/tools/quickstart.md diff --git a/docs/developer21/tools/testlocalmcp.md b/docs/developer_old/tools/testlocalmcp.md similarity index 100% rename from docs/developer21/tools/testlocalmcp.md rename to docs/developer_old/tools/testlocalmcp.md diff --git a/docs/developer21/tools/tool_registry.md b/docs/developer_old/tools/tool_registry.md similarity index 100% rename from docs/developer21/tools/tool_registry.md rename to docs/developer_old/tools/tool_registry.md diff --git a/docs/developer21/tools/troubleshoot.md b/docs/developer_old/tools/troubleshoot.md similarity index 100% rename from docs/developer21/tools/troubleshoot.md rename to docs/developer_old/tools/troubleshoot.md diff --git a/docs/developer21/typescriptSdk/agent-framework.md b/docs/developer_old/typescriptSdk/agent-framework.md similarity index 100% rename from docs/developer21/typescriptSdk/agent-framework.md rename to docs/developer_old/typescriptSdk/agent-framework.md diff --git a/docs/developer21/typescriptSdk/api-reference.md b/docs/developer_old/typescriptSdk/api-reference.md similarity index 100% rename from docs/developer21/typescriptSdk/api-reference.md rename to docs/developer_old/typescriptSdk/api-reference.md diff --git a/docs/developer21/typescriptSdk/core-modules.md b/docs/developer_old/typescriptSdk/core-modules.md similarity index 100% rename from docs/developer21/typescriptSdk/core-modules.md rename to docs/developer_old/typescriptSdk/core-modules.md diff --git a/docs/developer21/typescriptSdk/examples.md b/docs/developer_old/typescriptSdk/examples.md similarity index 100% rename from docs/developer21/typescriptSdk/examples.md rename to docs/developer_old/typescriptSdk/examples.md diff --git a/docs/developer21/typescriptSdk/installation.md b/docs/developer_old/typescriptSdk/installation.md similarity index 100% rename from docs/developer21/typescriptSdk/installation.md rename to docs/developer_old/typescriptSdk/installation.md diff --git a/docs/developer21/typescriptSdk/overview.md b/docs/developer_old/typescriptSdk/overview.md similarity index 100% rename from docs/developer21/typescriptSdk/overview.md rename to docs/developer_old/typescriptSdk/overview.md