# AI Assistant Pro

> Advanced AI-powered assistant for Jodit Pro Editor

Transform your Jodit editor into an intelligent writing companion with AI Assistant Pro. An interactive chat interface where AI can read, analyze, and modify your content using built-in tools - similar to Cursor or Claude Code.

## Features

- 🤖 **Intelligent AI Agent** - Multi-turn conversations with full context awareness
- 🛠️ **Built-in Tools** - Read, insert, and replace content programmatically
- 🔒 **Permission System** - User confirmation for sensitive operations
- 💾 **Flexible Storage** - localStorage, IndexedDB, or custom backend
- 🎨 **Multiple Display Modes** - Dialog, left panel, or right panel
- 🌐 **i18n Support** - Multiple languages out of the box
- ⚡ **Performance Optimized** - Reconciliation pattern for smooth UI
- 🔄 **Two API Modes** - Full conversation or incremental (OpenAI-style)

## Quick Start

```javascript
import Jodit from 'jodit-pro';

Jodit.make('#editor', {
    aiAssistantPro: {
        // Required: AI API request handler
        apiRequest: async (context, signal) => {
            const response = await fetch('https://api.openai.com/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${YOUR_API_KEY}`
                },
                body: JSON.stringify({
                    model: 'gpt-4',
                    messages: [{ role: 'user', content: context.newMessage.content }]
                }),
                signal
            });

            const data = await response.json();

            return {
                mode: 'final',
                response: {
                    responseId: data.id,
                    content: data.choices[0].message.content,
                    finished: true
                }
            };
        },

        // Optional: Display configuration
        displayMode: 'right',
        panelWidth: 400
    }
});
```

## Installation

AI Assistant Pro is included with Jodit Pro. Simply import and configure:

```javascript
import 'jodit-pro';
import 'jodit-pro/build/plugins/ai-assistant-pro';
```

Or via CDN:

```html
<script src="https://xdsoft.net/jodit/pro/build/jodit.min.js"></script>
<script src="https://xdsoft.net/jodit/pro/build/plugins/ai-assistant-pro.min.js"></script>
```

## Documentation

Complete documentation is available in the [docs](./docs/) folder:

- **[Getting Started](./docs/getting-started.md)** - Installation, basic setup, and first steps
- **[Configuration](./docs/configuration.md)** - Complete reference for all 50+ options
- **[Examples](./docs/examples.md)** - Practical usage examples and patterns
- **[Tools System](./docs/tools.md)** - Built-in and custom tools documentation
- **[Advanced Features](./docs/advanced.md)** - Custom storage, events, state management
- **[API Reference](./docs/api-reference.md)** - TypeScript interfaces and API documentation

### Integration Guides

- **[OpenAI / ChatGPT](./docs/integrations/openai.md)** - GPT-5, function calling
- **[Jodit AI Adapter](./docs/integrations/jodit-ai-adapter.md)** - OpenAI models, DeepSeek etc. 
- **[DeepSeek](./docs/integrations/deepseek.md)** - DeepSeek Chat and Coder models

## Built-in Tools

The AI has access to 9 built-in tools for interacting with the editor:

**Read operations:**
- **readDocument** - Read entire document content
- **readBlocks** - Read specific blocks by index or selector
- **readSelection** - Get currently selected text

**Write operations:**
- **writeDocument** - Replace entire document content
- **replaceSelection** - Replace current selection
- **replaceBlock** - Replace specific block by index or selector
- **replaceInDocument** - Find and replace throughout document
- **insertHTML** - Insert HTML at cursor position

**Formatting:**
- **applyFormat** - Apply formatting to selection

[Learn more about tools →](./docs/tools.md)

## Display Modes

Choose how the AI assistant appears in your editor:

```javascript
// Right panel (default)
displayMode: 'right'

// Left panel
displayMode: 'left'

// Top panel
displayMode: 'top'

// Bottom panel
displayMode: 'bottom'

// Modal dialog
displayMode: 'dialog'
```

## API Modes

Support two different API communication patterns:

```javascript
// Incremental (OpenAI-style) - sends only new messages
apiMode: 'incremental'

// Full - sends entire conversation history
apiMode: 'full'
```

## Storage Options

Choose where conversations are stored:

```javascript
// IndexedDB (default)
storage: 'indexedDB'

// Custom storage backend
storage: customStorageImplementation
```

[See storage examples →](./docs/examples.md#storage-examples)

## UI Workflow

1. **Welcome Screen** - Shown for first-time users
2. **Conversation List** - Browse and manage conversations
3. **Active Chat** - Interactive conversation with AI
4. **Permission Dialogs** - Inline approval for tool execution

## Configuration Example

```javascript
Jodit.make('#editor', {
    aiAssistantPro: {
        // Required
        apiRequest: async (context, signal) => { /* ... */ },

        // Display
        displayMode: 'right',
        panelWidth: 450,
        panelHeight: 500,

        // API
        apiMode: 'incremental',
        requestTimeout: 300000,

        // Tools
        enabledTools: ['insertHTML', 'readDocument', 'readBlocks', 'readSelection', 'replaceInDocument'],
        autoApproveTools: ['readDocument', 'readBlocks', 'readSelection', 'insertHTML'],

        // UI
        placeholderText: 'Ask AI assistant...',
        sendOnEnter: true,
        showTimestamps: true,

        // System instructions
        instructions: 'You are a helpful writing assistant.',

        // Context
        includeSelectionByDefault: true,
        maxContextRanges: 5
    }
});
```

[View all configuration options →](./docs/configuration.md)

## Events

Listen to plugin events for custom behavior:

```javascript
editor.e.on('messageSent.ai-assistant-pro', (message) => {
    console.log('User sent:', message.content);
});

editor.e.on('messageReceived.ai-assistant-pro', (message) => {
    console.log('AI replied:', message.content);
});

editor.e.on('toolCallExecuted.ai-assistant-pro', (toolCallId, result) => {
    console.log('Tool executed:', result);
});
```

[See all events →](./docs/api-reference.md#events)

## Browser Support

- Chrome/Edge 90+
- Firefox 88+
- Safari 14+

## Requirements

- Jodit Pro license
- Modern browser with ES6+ support
- AI API access (OpenAI, Anthropic, etc.)

## License

This plugin requires a valid Jodit Pro license.

## Text Autocomplete

The AI Assistant Pro can provide AI-powered text autocomplete suggestions as the user types. When enabled, it registers an autocomplete source via the `autocomplete` plugin and automatically sets the display mode to `inline` for a clean, text-completion-style popup.

### Configuration

```js
Jodit.make('#editor', {
	aiAssistantPro: {
		textAutocompleteEnabled: true,             // Enable AI text autocomplete
		textAutocompleteApiRequest: async (query, maxSuggestions, signal) => {
			const resp = await fetch(`/api/autocomplete?q=${query}&max=${maxSuggestions}`, { signal });
			return resp.json(); // should return string[]
		},
		textAutocompleteMinQueryLength: 3,          // Min chars before triggering (default: 3)
		textAutocompleteMaxSuggestions: 3,           // Max suggestions (default: 3)
		textAutocompleteDebounceMs: 500,             // Debounce delay in ms (default: 500)
		textAutocompleteCacheTTL: 30000,             // Cache TTL in ms, 0 to disable (default: 30000)
		textAutocompleteCacheMaxSize: 50             // Max cache entries (default: 50)
	}
});
```

When using the `jodit-ai-adapter` provider, `textAutocompleteEnabled` and `textAutocompleteApiRequest` are provided automatically:

```js
const providerOptions = Jodit.defaultOptions.aiAssistantPro
	.getAIProviderOptions('jodit-ai-adapter', {
		url: 'https://cloud.xdsoft.net',
		apiKey: 'your-api-key'
	});

Jodit.make('#editor', {
	aiAssistantPro: {
		...providerOptions // includes textAutocompleteEnabled and textAutocompleteApiRequest
	}
});
```

### How it works

1. As the user types, the autocomplete plugin extracts the current word/query
2. If the query meets `textAutocompleteMinQueryLength`, it calls `textAutocompleteApiRequest`
3. The API returns an array of suggestion strings
4. Suggestions appear in an inline popup near the cursor with the first item bold and a "tab" shortcut hint
5. The user can select a suggestion with Tab, Enter, arrow keys, or mouse click

## Support

- **Documentation**: [./docs/](./docs/)
- **Website**: https://xdsoft.net/jodit/pro/
- **GitHub Issues**: https://github.com/jodit/jodit-pro/issues

## Related

- [Jodit Pro](https://xdsoft.net/jodit/pro/) - Professional WYSIWYG editor
- [Jodit](https://xdsoft.net/jodit/) - Open source editor

---

Made with ❤️ for Jodit Pro
