> ## Documentation Index
> Fetch the complete documentation index at: https://nikcli.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Universal Agent

> Master the versatile Universal Agent with 64+ capabilities for all development tasks

## Introduction

The **Universal Agent** is NikCLI's most versatile and powerful agent. With 64+ distinct capabilities spanning code generation, analysis, testing, documentation, and more, it's your go-to agent for any development task.

Unlike specialized agents that focus on specific domains, the Universal Agent understands the full spectrum of software development and can seamlessly switch between tasks.

## Why Universal Agent?

<CardGroup cols={2}>
  <Card title="One Agent, All Tasks" icon="swiss-army-knife">
    No need to switch between agents - handles frontend, backend, DevOps, and more
  </Card>

  <Card title="Context-Aware" icon="brain">
    Understands your entire project and makes decisions based on codebase patterns
  </Card>

  <Card title="Adaptive Learning" icon="graduation-cap">
    Learns from your project structure and coding conventions
  </Card>

  <Card title="Production-Ready" icon="shield-check">
    Built-in approval system ensures safe, controlled execution
  </Card>
</CardGroup>

## Core Capabilities

### 1. Code Generation (12 Capabilities)

<AccordionGroup>
  <Accordion title="Component Creation" icon="cube">
    Generate complete, production-ready components:

    ```bash theme={null}
    /agent universal-agent "create a DataTable component with sorting, filtering, and pagination"
    ```

    **Generates:**

    * Component file with TypeScript
    * Props interface
    * State management
    * Event handlers
    * Styling (matches your approach)
    * Export statements

    **Example Output:**

    ```typescript DataTable.tsx theme={null}
    import React, { useState, useMemo } from 'react';

    interface Column<T> {
      key: keyof T;
      label: string;
      sortable?: boolean;
      render?: (value: T[keyof T], row: T) => React.ReactNode;
    }

    interface DataTableProps<T> {
      data: T[];
      columns: Column<T>[];
      pageSize?: number;
    }

    export function DataTable<T extends Record<string, any>>({
      data,
      columns,
      pageSize = 10,
    }: DataTableProps<T>) {
      const [sortKey, setSortKey] = useState<keyof T | null>(null);
      const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
      const [currentPage, setCurrentPage] = useState(1);
      const [filter, setFilter] = useState('');

      const filteredData = useMemo(() => {
        return data.filter((row) =>
          Object.values(row).some((value) =>
            String(value).toLowerCase().includes(filter.toLowerCase())
          )
        );
      }, [data, filter]);

      const sortedData = useMemo(() => {
        if (!sortKey) return filteredData;

        return [...filteredData].sort((a, b) => {
          const aVal = a[sortKey];
          const bVal = b[sortKey];

          if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;
          if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;
          return 0;
        });
      }, [filteredData, sortKey, sortOrder]);

      const paginatedData = useMemo(() => {
        const startIdx = (currentPage - 1) * pageSize;
        return sortedData.slice(startIdx, startIdx + pageSize);
      }, [sortedData, currentPage, pageSize]);

      const totalPages = Math.ceil(sortedData.length / pageSize);

      const handleSort = (key: keyof T) => {
        if (sortKey === key) {
          setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
          setSortKey(key);
          setSortOrder('asc');
        }
      };

      return (
        <div className="data-table">
          <input
            type="text"
            placeholder="Filter..."
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            className="filter-input"
          />

          <table>
            <thead>
              <tr>
                {columns.map((col) => (
                  <th
                    key={String(col.key)}
                    onClick={() => col.sortable && handleSort(col.key)}
                    className={col.sortable ? 'sortable' : ''}
                  >
                    {col.label}
                    {sortKey === col.key && (sortOrder === 'asc' ? ' ↑' : ' ↓')}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {paginatedData.map((row, idx) => (
                <tr key={idx}>
                  {columns.map((col) => (
                    <td key={String(col.key)}>
                      {col.render
                        ? col.render(row[col.key], row)
                        : String(row[col.key])}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>

          <div className="pagination">
            <button
              disabled={currentPage === 1}
              onClick={() => setCurrentPage((p) => p - 1)}
            >
              Previous
            </button>
            <span>
              Page {currentPage} of {totalPages}
            </span>
            <button
              disabled={currentPage === totalPages}
              onClick={() => setCurrentPage((p) => p + 1)}
            >
              Next
            </button>
          </div>
        </div>
      );
    }
    ```
  </Accordion>

  <Accordion title="API Endpoint Creation" icon="server">
    Generate complete REST APIs:

    ```bash theme={null}
    /agent universal-agent "create CRUD API for products with validation and error handling"
    ```

    **Generates:**

    * Route handlers
    * Validation middleware
    * Error handling
    * Database queries
    * TypeScript types
    * Response formatting

    **Example Output:**

    ```typescript products.routes.ts theme={null}
    import express from 'express';
    import { z } from 'zod';
    import { prisma } from '../lib/prisma';
    import { asyncHandler } from '../middleware/asyncHandler';
    import { validate } from '../middleware/validate';

    const router = express.Router();

    // Validation schemas
    const createProductSchema = z.object({
      name: z.string().min(1).max(255),
      description: z.string().optional(),
      price: z.number().positive(),
      stock: z.number().int().nonnegative(),
      categoryId: z.string().uuid(),
    });

    const updateProductSchema = createProductSchema.partial();

    // GET /products - List all products
    router.get(
      '/',
      asyncHandler(async (req, res) => {
        const { page = 1, limit = 10, category } = req.query;

        const where = category ? { categoryId: String(category) } : {};

        const [products, total] = await Promise.all([
          prisma.product.findMany({
            where,
            skip: (Number(page) - 1) * Number(limit),
            take: Number(limit),
            include: { category: true },
          }),
          prisma.product.count({ where }),
        ]);

        res.json({
          data: products,
          pagination: {
            page: Number(page),
            limit: Number(limit),
            total,
            pages: Math.ceil(total / Number(limit)),
          },
        });
      })
    );

    // GET /products/:id - Get single product
    router.get(
      '/:id',
      asyncHandler(async (req, res) => {
        const product = await prisma.product.findUnique({
          where: { id: req.params.id },
          include: { category: true },
        });

        if (!product) {
          return res.status(404).json({ error: 'Product not found' });
        }

        res.json({ data: product });
      })
    );

    // POST /products - Create product
    router.post(
      '/',
      validate(createProductSchema),
      asyncHandler(async (req, res) => {
        const product = await prisma.product.create({
          data: req.body,
          include: { category: true },
        });

        res.status(201).json({ data: product });
      })
    );

    // PATCH /products/:id - Update product
    router.patch(
      '/:id',
      validate(updateProductSchema),
      asyncHandler(async (req, res) => {
        const product = await prisma.product.update({
          where: { id: req.params.id },
          data: req.body,
          include: { category: true },
        });

        res.json({ data: product });
      })
    );

    // DELETE /products/:id - Delete product
    router.delete(
      '/:id',
      asyncHandler(async (req, res) => {
        await prisma.product.delete({
          where: { id: req.params.id },
        });

        res.status(204).send();
      })
    );

    export default router;
    ```
  </Accordion>

  <Accordion title="Database Schema Design" icon="database">
    Design normalized database schemas:

    ```bash theme={null}
    /agent universal-agent "create database schema for e-commerce with users, products, orders, and reviews"
    ```

    Generates schemas for Prisma, Drizzle, TypeORM, or SQL based on your project.
  </Accordion>
</AccordionGroup>

### 2. Code Analysis (10 Capabilities)

<Tabs>
  <Tab title="Quality Assessment">
    ```bash theme={null}
    /agent universal-agent "analyze code quality in src/components/"
    ```

    **Analyzes:**

    * Code complexity
    * Code smells
    * Duplication
    * Naming conventions
    * File structure
    * Dependencies

    **Reports:**

    ```
    📊 Code Quality Report

    Overall Score: 78/100

    Issues Found:
    • High Complexity (3 files)
      - UserDashboard.tsx: Cyclomatic complexity 15
      - OrderProcessor.ts: Cyclomatic complexity 18
      - DataTransformer.ts: Cyclomatic complexity 12

    • Code Duplication (2 instances)
      - validateEmail() in utils/validation.ts and helpers/user.ts
      - formatCurrency() in components/Price.tsx and utils/format.ts

    • Long Functions (4 files)
      - processCheckout(): 120 lines
      - renderDashboard(): 95 lines

    Recommendations:
    ✓ Extract validateEmail() to shared utility
    ✓ Split processCheckout() into smaller functions
    ✓ Reduce UserDashboard component complexity
    ```
  </Tab>

  <Tab title="Security Audit">
    ```bash theme={null}
    /agent universal-agent "scan for security vulnerabilities"
    ```

    **Detects:**

    * SQL injection risks
    * XSS vulnerabilities
    * Insecure dependencies
    * Hardcoded secrets
    * Weak cryptography
    * CSRF vulnerabilities

    **Reports:**

    ```
    🔒 Security Audit Results

    Critical Issues: 2
    High: 5
    Medium: 8
    Low: 12

    🚨 Critical:
    1. Hardcoded API key in config.ts:15
       → Move to environment variables

    2. SQL injection risk in database/query.ts:42
       → Use parameterized queries

    ⚠️ High:
    1. Weak password hashing (MD5) in auth/password.ts
       → Use bcrypt or argon2

    2. Missing rate limiting on /api/login
       → Add express-rate-limit

    3. Unvalidated user input in search.ts:28
       → Add input validation with Zod
    ```
  </Tab>

  <Tab title="Performance Analysis">
    ```bash theme={null}
    /agent universal-agent "analyze performance bottlenecks"
    ```

    **Identifies:**

    * Slow algorithms
    * Memory leaks
    * Inefficient queries
    * Large bundle sizes
    * Render performance

    **Suggests optimizations**
  </Tab>
</Tabs>

### 3. Code Refactoring (8 Capabilities)

<Steps>
  <Step title="Identify Refactoring Opportunities">
    ```bash theme={null}
    /agent universal-agent "suggest refactoring improvements for UserProfile.tsx"
    ```

    Agent analyzes code and suggests:

    * Extract complex logic to hooks
    * Split large components
    * Reduce prop drilling
    * Simplify conditional logic
  </Step>

  <Step title="Execute Refactoring">
    ```bash theme={null}
    /agent universal-agent "refactor UserProfile.tsx following clean code principles"
    ```

    Agent performs refactoring while:

    * Preserving functionality
    * Maintaining tests
    * Improving readability
    * Following best practices
  </Step>

  <Step title="Verify Changes">
    ```bash theme={null}
    /exec npm test
    ```

    Runs tests to ensure refactoring didn't break functionality
  </Step>
</Steps>

### 4. Testing (8 Capabilities)

<Tabs>
  <Tab title="Unit Tests">
    ```bash theme={null}
    /agent universal-agent "create comprehensive unit tests for utils/validation.ts"
    ```

    **Generates:**

    * Test suite setup
    * Test cases for all functions
    * Edge cases
    * Error scenarios
    * Mocks and stubs
    * 100% coverage

    ```typescript validation.test.ts theme={null}
    import { describe, it, expect } from 'vitest';
    import {
      validateEmail,
      validatePassword,
      validatePhone,
    } from './validation';

    describe('validateEmail', () => {
      it('should accept valid emails', () => {
        expect(validateEmail('user@example.com')).toBe(true);
        expect(validateEmail('test+tag@domain.co.uk')).toBe(true);
      });

      it('should reject invalid emails', () => {
        expect(validateEmail('invalid')).toBe(false);
        expect(validateEmail('@example.com')).toBe(false);
        expect(validateEmail('user@')).toBe(false);
      });

      it('should handle edge cases', () => {
        expect(validateEmail('')).toBe(false);
        expect(validateEmail(null as any)).toBe(false);
        expect(validateEmail(undefined as any)).toBe(false);
      });
    });

    describe('validatePassword', () => {
      it('should require minimum length', () => {
        expect(validatePassword('short')).toBe(false);
        expect(validatePassword('longenough123')).toBe(true);
      });

      it('should require complexity', () => {
        expect(validatePassword('alllowercase')).toBe(false);
        expect(validatePassword('WithUpperCase123')).toBe(true);
      });
    });
    ```
  </Tab>

  <Tab title="Integration Tests">
    ```bash theme={null}
    /agent universal-agent "create integration tests for authentication flow"
    ```

    Tests complete user flows including:

    * API endpoints
    * Database operations
    * External services
    * Error handling
  </Tab>

  <Tab title="E2E Tests">
    ```bash theme={null}
    /agent universal-agent "create Playwright tests for checkout process"
    ```

    Generates full end-to-end browser tests
  </Tab>
</Tabs>

### 5. Documentation (6 Capabilities)

Generate comprehensive documentation:

```bash theme={null}
/agent universal-agent "create complete documentation for this API"
```

**Generates:**

* README.md with setup instructions
* API documentation
* JSDoc/TSDoc comments
* Usage examples
* Architecture diagrams
* Contributing guidelines

### 6. Debugging (6 Capabilities)

<CodeGroup>
  ```bash Diagnose Error theme={null}
  /agent universal-agent "debug this TypeError: Cannot read property 'map' of undefined"
  ```

  ```bash Fix Bug theme={null}
  /agent universal-agent "fix the memory leak in useEffect"
  ```

  ```bash Explain Error theme={null}
  /agent universal-agent "explain this error and suggest fixes"
  ```
</CodeGroup>

## Advanced Usage

### Multi-Step Workflows

Handle complex tasks spanning multiple files:

```bash theme={null}
/agent universal-agent "implement user authentication system with:
- JWT tokens with refresh
- Email verification
- Password reset
- Rate limiting
- Session management
- Comprehensive tests
- Full documentation"
```

**Agent workflow:**

1. Analyzes project structure
2. Creates detailed 12-step plan
3. Requests approval
4. Implements each component
5. Creates tests
6. Generates documentation
7. Provides usage examples

### Context-Aware Development

Agent understands your project:

```bash theme={null}
/agent universal-agent "add dark mode support"
```

**Agent automatically:**

* Detects your UI framework (React, Vue, etc.)
* Finds your theming approach
* Identifies components to update
* Matches your code style
* Updates all relevant files

### Iterative Refinement

Refine results through conversation:

```
> /agent universal-agent "create a login form"

[Agent creates form]

> Add validation and show errors inline

[Agent adds validation]

> Use Zod for schema validation instead

[Agent refactors to use Zod]

> Make it look better with Tailwind

[Agent adds Tailwind styling]
```

## Best Practices

<AccordionGroup>
  <Accordion title="Be Specific" icon="crosshairs">
    ✅ **Good**: "create a Button component with primary/secondary/danger variants, loading state, disabled state, and size options (sm/md/lg) using Tailwind CSS"

    ❌ **Bad**: "make a button"

    **Why**: Specific instructions produce better, more complete results
  </Accordion>

  <Accordion title="Provide Context" icon="context">
    Mention technologies and patterns:

    ```bash theme={null}
    /agent universal-agent "create authentication API using Express, Prisma, JWT, bcrypt, and Zod for validation"
    ```

    **Benefits:**

    * Agent uses correct libraries
    * Matches your stack
    * Follows framework conventions
  </Accordion>

  <Accordion title="Review Plans" icon="eye">
    Always review execution plans:

    Press `v` to view detailed changes before approving:

    ```
    📋 Execution Plan Details:

    Step 1: Create src/components/Button.tsx
    + 45 lines added
    + TypeScript interfaces
    + Three variants implementation
    + Event handlers

    Step 2: Create tests
    + Button.test.tsx with 12 test cases
    + 100% coverage

    Step 3: Update exports
    + Add to src/components/index.ts
    ```
  </Accordion>

  <Accordion title="Iterate as Needed" icon="rotate">
    Don't expect perfection on first try:

    ```bash theme={null}
    # First attempt
    /agent universal-agent "create a navbar"

    # Refine
    /agent universal-agent "make the navbar sticky and add mobile menu"

    # Polish
    /agent universal-agent "add smooth scroll animations to navbar"
    ```
  </Accordion>

  <Accordion title="Use Autonomous Mode Wisely" icon="bolt">
    Use `/auto` for:

    * Routine, well-defined tasks
    * Tasks you've done before
    * Non-critical changes

    Avoid `/auto` for:

    * Critical system changes
    * Security-sensitive operations
    * Complex refactoring
    * First-time tasks
  </Accordion>
</AccordionGroup>

## Performance Tips

<CardGroup cols={2}>
  <Card title="Provide File Paths" icon="file">
    ```bash theme={null}
    /agent universal-agent "refactor src/components/Dashboard.tsx"
    ```

    Faster than letting agent search
  </Card>

  <Card title="Break Down Large Tasks" icon="list">
    Split into smaller, focused tasks:

    * ✅ "Create user model"
    * ✅ "Create auth endpoints"
    * ❌ "Build entire auth system"
  </Card>

  <Card title="Use Project Context" icon="folder-tree">
    ```bash theme={null}
    /analyze-project
    ```

    Run once to build context cache
  </Card>

  <Card title="Reuse Sessions" icon="save">
    ```bash theme={null}
    /save my-session
    ```

    Preserve context for future work
  </Card>
</CardGroup>

## Common Patterns

### Feature Development

```bash theme={null}
/agent universal-agent "implement [feature] with:
- Frontend components
- Backend API
- Database schema
- Tests
- Documentation"
```

### Bug Fixing

```bash theme={null}
/agent universal-agent "fix [issue] in [file]:
- Identify root cause
- Fix the bug
- Add tests to prevent regression
- Update documentation if needed"
```

### Code Quality

```bash theme={null}
/agent universal-agent "improve [file/directory]:
- Refactor for readability
- Add type safety
- Optimize performance
- Add missing tests"
```

### Documentation

```bash theme={null}
/agent universal-agent "document [feature/module]:
- Add inline comments
- Create README
- Add usage examples
- Include API reference"
```

## Limitations

<Warning>
  **Current Limitations:**

  * Cannot execute system commands (use `/exec` separately)
  * Cannot access external APIs without configuration
  * File size limit: 100KB per file
  * Cannot modify binary files
  * Internet access limited to configured integrations
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Specialized Agents" icon="toolbox" href="/agent-system/specialized-agents">
    Learn about domain-specific agents
  </Card>

  <Card title="Autonomous Mode" icon="bolt" href="/agent-system/autonomous-execution">
    Master fully autonomous execution
  </Card>

  <Card title="Custom Agents" icon="wrench" href="/agent-system/custom-agents">
    Create your own specialized agents
  </Card>

  <Card title="Agent Examples" icon="lightbulb" href="/examples/agent-examples">
    See real-world usage examples
  </Card>
</CardGroup>

<Tip>
  **Pro Tip**: The Universal Agent learns from your feedback. If results aren't perfect, provide specific feedback and iterate until satisfied.
</Tip>
