# Autopilot

[![Commercial](https://img.shields.io/badge/License-Commercial-red.svg)](LICENSE.md)
[![Cockpit CMS](https://img.shields.io/badge/Cockpit%20CMS-Addon-blue.svg)](https://getcockpit.com)
[![AI](https://img.shields.io/badge/Feature-AI%20Assistant-green.svg)](#features)

> **AI-powered assistant for enhanced productivity in Cockpit CMS**

Autopilot brings OpenAI's advanced AI capabilities directly into your Cockpit CMS admin interface. Get instant help, generate content, create images, and boost your productivity with an intelligent AI workmate that's always available.

## ✨ AI Features

### 🤖 **Chat Assistant**
- **GPT Models**: Support for GPT-4o, GPT-4o-mini, and other OpenAI chat models
- **Streaming Responses**: Real-time conversation with progressive text display
- **Context Awareness**: Maintains conversation history for contextual responses
- **Markdown Support**: Rich text formatting with syntax highlighting for code blocks
- **Copy to Clipboard**: Easy copying of AI responses for reuse

### 🎨 **Image Generation**
- **DALL-E Integration**: AI-powered image creation using DALL-E 3
- **Multiple Sizes**: Support for 1024x1024, 1792x1024, and 1024x1792 image dimensions
- **Style Options**: Natural and vivid image styles
- **Asset Integration**: Automatically save generated images to Cockpit's asset library
- **Direct Download**: Generated images can be imported directly into your media library

### 🚀 **Productivity Features**
- **Admin Integration**: Accessible via header button in admin interface
- **Modal Interface**: Non-intrusive chat overlay that doesn't disrupt workflow
- **Progress Tracking**: Real-time progress updates for long-running operations
- **Error Handling**: Graceful error handling with user-friendly messages

## 🔧 Configuration

### Basic Setup

Configure Autopilot in your `config/config.php`:

```php
<?php
return [
    // ... other config options

    'autopilot' => [
        'openAI' => [
            'apiKey' => 'your-openai-api-key',
            'chatModel' => 'gpt-4o-mini',                    // Default chat model
            'imageModel' => 'dall-e-3',                // Default image model
            'baseUri' => 'api.openai.com/v1'            // Optional: Custom API endpoint
        ],
        'useTools' => true
    ]
];
```

### Required Configuration

**API Key** (Required):
```php
'autopilot' => [
    'openAI' => [
        'apiKey' => 'sk-proj-your-openai-api-key'
    ]
]
```

Get your API key from [OpenAI Platform](https://platform.openai.com/api-keys).

### Optional Configuration

**Chat Model Selection**:
```php
'autopilot' => [
    'openAI' => [
        'apiKey' => 'your-api-key',
        'chatModel' => 'gpt-4o'                 // Options: gpt-4o, gpt-4o-mini, gpt-4-turbo
    ]
]
```

**Image Model Selection**:
```php
'autopilot' => [
    'openAI' => [
        'apiKey' => 'your-api-key',
        'imageModel' => 'dall-e-3'         // Options: dall-e-3, dall-e-2
    ]
]
```

**Custom API Endpoint**:
```php
'autopilot' => [
    'openAI' => [
        'apiKey' => 'your-api-key',
        'baseUri' => 'your-custom-endpoint.com/v1'    // For Azure OpenAI or other providers
    ]
]
```

## 🎯 Supported AI Models

### Chat Models

| Model | Description | Use Case |
|-------|-------------|----------|
| **gpt-4o** | Most capable model with enhanced reasoning | Complex tasks, analysis, creative writing |
| **gpt-4o-mini** | Fast and efficient model (default) | General assistance, quick responses |
| **gpt-4-turbo** | High-performance model with large context | Long conversations, detailed analysis |

### Image Generation Models

| Model | Description | Features |
|-------|-------------|----------|
| **dall-e-3** | Latest image generation model (default) | High quality, better prompt adherence |
| **dall-e-2** | Previous generation model | Faster generation, lower cost |

### Image Generation Options

**Supported Sizes**:
- `1024x1024` - Square format (default)
- `1792x1024` - Landscape format
- `1024x1792` - Portrait format

**Style Options**:
- `natural` - Natural, realistic style (default)
- `vivid` - Enhanced colors and contrast

## 🧩 Agent Tools & CMS Integration

### Adding Custom Tools

You can extend Autopilot with custom tools for your specific needs. Tools are automatically loaded from the `config/agent-tools` directory.

#### Creating a Custom Tool

Create a new PHP file in `/config/agent-tools/`:

```php
<?php
// File: /config/agent-tools/myCustomTool.php

return [
    'name' => 'myCustomTool',
    'description' => 'Description that helps the AI understand when to use this tool',
    'parameters' => [
        'type' => 'object',
        'properties' => [
            'param1' => [
                'type' => 'string',
                'description' => 'Description of parameter 1'
            ],
            'param2' => [
                'type' => 'integer',
                'description' => 'Description of parameter 2',
                'default' => 10
            ]
        ],
        'required' => ['param1']  // List required parameters
    ],
    'handler' => function($args, $app) {
        // Your tool logic here
        $param1 = $args['param1'];
        $param2 = $args['param2'] ?? 10;

        // Interact with Cockpit
        $result = $app->module('content')->items('collection_name', [
            'filter' => ['field' => $param1],
            'limit' => $param2
        ]);

        return $result;
    },
    'options' => [
        'permission' => 'autopilot/tools/read'  // Required permission
    ]
];
```

#### Tool Structure

Each tool file must return an array with:

| Key | Type | Description |
|-----|------|-------------|
| `name` | string | Unique identifier for the tool |
| `description` | string | Clear description for AI to understand tool purpose |
| `parameters` | array | JSON Schema defining input parameters |
| `handler` | callable | Function that executes the tool logic |
| `options` | array | Optional settings like permissions |

#### Parameter Schema

Parameters follow JSON Schema format:

```php
'parameters' => [
    'type' => 'object',
    'properties' => [
        // Define each parameter
        'fieldName' => [
            'type' => 'string',     // string, integer, boolean, array, object
            'description' => '...',  // Help text for the AI
            'default' => '...',      // Optional default value
            'enum' => ['opt1', 'opt2'] // Optional: restrict to specific values
        ]
    ],
    'required' => ['fieldName']     // List of required parameters
]
```

#### Accessing Cockpit Services

The handler function receives two arguments:
- `$args`: Parameters passed by the AI
- `$app`: Cockpit application instance

Common Cockpit services:

```php
// Content management
$app->module('content')->models()           // Get all models
$app->module('content')->items($model)      // Get collection items
$app->module('content')->item($model, $id)  // Get single item

// Data storage
$app->datastore->find($collection)          // Query data
$app->datastore->count($collection)         // Count records

// File storage
$app->fileStorage->read($path)              // Read file
$app->fileStorage->write($path, $content)   // Write file

// Authentication
$app->helper('auth')->getUser()             // Current user
$app->helper('acl')->isAllowed($resource)   // Check permissions
```

#### Example: Asset Search Tool

```php
<?php
// File: /config/agent-tools/searchAssets.php

return [
    'name' => 'searchAssets',
    'description' => 'Search for assets/media files in Cockpit',
    'parameters' => [
        'type' => 'object',
        'properties' => [
            'mime' => [
                'type' => 'string',
                'description' => 'MIME type to filter (e.g., image/jpeg)'
            ],
            'folder' => [
                'type' => 'string',
                'description' => 'Folder path to search in'
            ],
            'limit' => [
                'type' => 'integer',
                'description' => 'Maximum results to return',
                'default' => 10
            ]
        ],
        'required' => []
    ],
    'handler' => function($args, $app) {
        $filter = [];

        if (isset($args['mime'])) {
            $filter['mime'] = ['$regex' => $args['mime']];
        }

        if (isset($args['folder'])) {
            $filter['folder'] = $args['folder'];
        }

        $assets = $app->datastore->find('assets', [
            'filter' => $filter,
            'limit' => $args['limit'] ?? 10,
            'sort' => ['_created' => -1]
        ])->toArray();

        return array_map(function($asset) {
            return [
                'id' => $asset['_id'],
                'title' => $asset['title'] ?? $asset['name'],
                'mime' => $asset['mime'],
                'size' => $asset['size'],
                'path' => $asset['path']
            ];
        }, $assets);
    },
    'options' => [
        'permission' => 'autopilot/tools/read'
    ]
];
```

#### Registering Tools Programmatically

You can also register tools via code:

```php
// In bootstrap.php or custom module
$this->on('autopilot:agent:register', function($agent) {
    $agent->registerTool(
        'myTool',
        'Tool description',
        ['type' => 'object', 'properties' => new \stdClass()],
        function($args, $app) {
            return ['result' => 'success'];
        },
        ['permission' => 'autopilot/tools/custom']
    );
});
```

## 🛡️ Security & Permissions

### Access Control

Autopilot respects Cockpit's permission system:

```php
// Core permissions
'autopilot/available' => 'Autopilot availability'

// Tool permissions
'autopilot/tools/read' => 'Use read-only agent tools'
'autopilot/tools/write' => 'Use write agent tools'
'autopilot/tools/custom' => 'Use custom tools'
```

### Security Features

- **CSRF Protection**: All API requests include CSRF token validation
- **Session Management**: Secure session handling for chat conversations
- **File Validation**: Generated images are validated before asset creation
- **Timeout Protection**: Configurable execution timeouts for long operations
- **Tool Permissions**: Granular permissions for agent tool access

## 📋 Usage Requirements

### Dependencies

Autopilot requires the OpenAI PHP client library:

```bash
# Automatically installed via composer.json
composer require openai-php/client
```

### System Requirements

- **PHP**: 8.1 or higher
- **Memory**: Adequate memory for image processing and streaming responses
- **Network**: Outbound HTTPS access to OpenAI API endpoints
- **Cockpit CMS**: Pro license required (commercial addon)

### API Limits

Consider OpenAI API usage limits:

- **Rate Limits**: Varies by model and tier
- **Token Limits**: Context window limits per model
- **Image Limits**: Generation limits based on your OpenAI plan
- **Cost**: Usage-based pricing from OpenAI

## 🔍 Troubleshooting

### Common Issues

**❌ "API key not configured"**
- Ensure `autopilot/openAI/apiKey` is set in config
- Verify API key is valid and has sufficient credits
- Check API key permissions in OpenAI dashboard

**❌ "Model not available"**
- Verify model name is spelled correctly
- Check your OpenAI account has access to the specified model
- Some models require higher tier access

**❌ "Image generation failed"**
- Check OpenAI account has DALL-E access
- Verify image size and style parameters are valid
- Ensure sufficient API credits for image generation

**❌ "Connection timeout"**
- Increase PHP execution time limits
- Check network connectivity to OpenAI servers
- Verify firewall allows outbound HTTPS connections

### Debug Mode

Enable debug logging in `config/config.php`:

```php
'debug' => true
```

Check logs for detailed error information and API response details.

## 📄 License

This is a commercial addon for Cockpit CMS. See [LICENSE.md](LICENSE.md) for full terms.

## 🙏 Credits

Autopilot is developed by [Agentejo](https://agentejo.com) as part of the Cockpit CMS Pro ecosystem, powered by [OpenAI](https://openai.com).

---

**Ready to supercharge your workflow?** Configure your OpenAI API key and start collaborating with your AI workmate today!