matrix-plugin/README.md

272 lines
8.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# opencode-matrix-plugin
OpenCode V2 plugin that connects your OpenCode agent to Matrix messaging servers.
## Features
- **Matrix Bot Integration**: Connect OpenCode to any Matrix homeserver
- **Thread Isolation**: Each Matrix thread gets its own isolated session
- **E2EE Support**: End-to-end encryption via Rust crypto SDK
- **Auto-join**: Bot auto-joins rooms it's invited to
- **Configurable Triggers**: `triggerPatterns` array — empty = all messages, configured = only trigger/mention/thread-reply
- **Thread Replies**: Respond to plain replies within active threads (follow-up mode)
- **Bridge Commands**: `/status`, `/clear`, `/help` for session management
- **Rate Limiting**: Configurable per-user rate limiting
- **User Allowlisting**: Restrict who can interact with the bot
- **Session Persistence**: Sessions survive plugin reloads via `~/.opencode-matrix-sessions.json`
## Installation
### Option 1: Local Plugin (Recommended)
1. Create a symlink from your OpenCode config to this plugin:
```bash
mkdir -p ~/.config/opencode/plugins
ln -s /path/to/your/opencode_matrix ~/.config/opencode/plugins/matrix-plugin
```
2. Add the plugin to your `opencode.jsonc`:
```jsonc
{
"plugins": [
"./plugins/matrix-plugin"
]
}
```
### Option 2: Published Package
```jsonc
{
"plugins": [
"opencode-matrix-plugin"
]
}
```
## Configuration
Конфигурация загружается в следующем порядке приоритетов:
1. **Plugin options** из `opencode.jsonc` (`plugins[].options`) — высший приоритет
2. **Config file** — `.opencode/matrix.json` (проект) или `~/.config/opencode/matrix.json` (глобальный)
3. **Environment variables** — `MATRIX_*` — базовый уровень
> **Auto-create**: Если конфиг не найден ни в одной директории, плагин автоматически создаст
> `~/.config/opencode/matrix.json` с дефолтными значениями (права `0o600`).
### Config File
Создайте `matrix.json` в одной из директорий:
**Проектный уровень** — `.opencode/matrix.json` (рядом с `opencode.jsonc`):
```json
{
"homeserver": "https://matrix.org",
"userId": "@opencode-bot:matrix.org",
"password": "your-bot-password",
"autoJoin": true,
"triggerPatterns": ["!oc ", "!ai "],
"allowedUsers": ["@alice:matrix.org"],
"threadIsolation": true,
"respondToThreadReplies": true,
"rateLimitSeconds": 5,
"botName": "opencode",
"enabled": true
}
```
**Глобальный уровень** — `~/.config/opencode/matrix.json`:
```json
{
"homeserver": "https://matrix.org",
"userId": "@opencode-bot:matrix.org",
"password": "your-bot-password",
"triggerPatterns": ["!oc "],
"threadIsolation": true,
"enabled": true
}
```
Файлы поддерживают JSONC (комментарии `//`).
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `MATRIX_HOMESERVER` | Matrix server URL | `https://matrix.org` |
| `MATRIX_USER_ID` | Bot user ID | (required) |
| `MATRIX_ACCESS_TOKEN` | Static access token | (optional) |
| `MATRIX_PASSWORD` | Bot password for login | (optional, preferred) |
| `MATRIX_STORAGE_PATH` | Override storage directory | `~/.local/share/opencode-matrix-bot` |
| `MATRIX_TRIGGER` | Override trigger pattern | — |
| `MATRIX_ALLOWED_USERS` | Comma-separated user IDs | — |
### All Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `homeserver` | string | `https://matrix.org` | Matrix homeserver URL |
| `userId` | string | - | Bot user ID (e.g., `@bot:server.org`) |
| `accessToken` | string | - | Static access token (or use `password`) |
| `password` | string | - | Bot password (preferred, auto-refreshes token) |
| `deviceId` | string | `opencode-matrix-plugin` | Device ID for login |
| `autoJoin` | boolean | `true` | Auto-join rooms the bot is invited to |
| `triggerPatterns` | string[] | `[]` | Message prefixes to trigger the bot. Empty = all messages. |
| `ignoreRooms` | string[] | `[]` | Room IDs to completely ignore |
| `ignoreUsers` | string[] | `[]` | User IDs to completely ignore |
| `allowedUsers` | string[] | `[]` | Allowlist (empty = everyone) |
| `formatHtml` | boolean | `false` | Send HTML-formatted responses |
| `threadIsolation` | boolean | `true` | Per-thread sessions |
| `respondToThreadReplies` | boolean | `true` | Reply to plain thread messages (follow-up) |
| `rateLimitSeconds` | number | `5` | Per-user cooldown between messages |
| `botName` | string | `opencode` | Bot display name for @mentions |
| `storagePath` | string | auto | Directory for bot state and crypto keys |
| `enabled` | boolean | `true` | Enable/disable the plugin |
### Config Priority
Configuration is loaded in this order (highest priority first):
1. **Plugin options** from `opencode.jsonc` (`plugins[].options`)
2. **Config file** — `matrix.json` or `matrix.jsonc` in:
- Project level: `.opencode/matrix.json` (next to `opencode.jsonc`)
- Global level: `~/.config/opencode/matrix.json`
3. **Environment variables** — `MATRIX_*`
> **Auto-create**: If no config is found, the plugin auto-creates `~/.config/opencode/matrix.json` with defaults (permissions `0o600`).
### Example Config
Copy `matrix.json.example` from the project root and customize:
```bash
cp matrix.json.example ~/.config/opencode/matrix.json
```
See the example file for fully commented configuration with all options.
## Usage
### Triggering the Bot
Behavior depends on `triggerPatterns` config:
**With triggers configured** (e.g., `["!oc "]`):
1. **Prefix trigger**: Send `!oc What is TypeScript?`
2. **@Mention**: Send `@opencode What is TypeScript?`
3. **Thread reply**: Reply to any message in an active thread (follow-up mode)
**With empty triggers** (`triggerPatterns: []`):
- All messages are processed
### Bridge Commands
| Command | Description |
|---------|-------------|
| `/help` or `/h` | Show help message |
| `/status` | Show current session info |
| `/clear` or `/reset` | Clear current session |
### Room Setup
1. Invite `@opencode:matrix.org` to your room
2. The bot auto-joins (if `autoJoin: true`)
3. Start messaging with the trigger prefix or @mention
### Bot Setup (First Time)
1. Create a Matrix account for your bot (or use existing)
2. Set `MATRIX_PASSWORD` or `MATRIX_ACCESS_TOKEN`
3. The bot will auto-login and save the access token
4. Invite the bot to your rooms
## Architecture
```
Matrix Room
│
▼
MatrixBotClient (matrix-bot-sdk + Rust crypto)
│
├── Event: room.message
├── Authentication: password / token
├── E2EE: automatic
└── Thread handling: m.relates_to
│
▼
SessionManager
│
├── Rate limiting
├── Thread isolation (room:threadId)
└── Session persistence (~/.opencode-matrix-sessions.json)
│
▼
OpenCode V2 API
│
├── ctx.session.prompt() / ctx.session.create()
└── Session mapping: Matrix thread → OpenCode session
│
▼
Response → MatrixBotClient → Matrix Room
```
## Session Management
Sessions are persisted across plugin restarts in `~/.opencode-matrix-sessions.json`.
- **V2 API**: Sessions are created with deterministic IDs (`roomId:threadRootId`)
- **Sync**: Use `sessionManager.syncWithOpenCode(sessionIds)` to prune orphaned sessions
## Security
- **E2EE**: Full end-to-end encryption support via `@matrix-org/matrix-sdk-crypto-nodejs`
- **Token Storage**: Access tokens saved with `0o600` permissions
- **User Allowlisting**: Restrict bot access to specific users
- **Rate Limiting**: Prevent message spam
- **Mutex Lock**: Prevents duplicate bot startup (server + client both load plugins)
## Troubleshooting
### Bot doesn't respond
1. Check that the bot is in the room
2. Verify the trigger pattern matches your message
3. Check if the user is in the allowed list (if configured)
4. Check `~/.local/share/opencode-matrix-bot/` for state files
5. Check logs: `~/.opencode-matrix-plugin/plugin.log`
### Authentication fails
1. Verify `MATRIX_USER_ID` and `MATRIX_PASSWORD` are correct
2. Check that the bot account exists on the homeserver
3. Try setting `MATRIX_ACCESS_TOKEN` directly
4. Check homeserver logs for authentication errors
### E2EE issues
1. Ensure `@matrix-org/matrix-sdk-crypto-nodejs` is installed
2. Check crypto storage directory has write permissions
3. Verify the bot has access to the encrypted room
### Double bot startup
OpenCode V2 loads plugins in both the background server and the client. The plugin uses a file-based mutex (`~/.local/share/opencode-matrix-bot/plugin-data/lock`) to prevent duplicate bot instances. If you see two bots, check that the lock file is being created.
## Development
```bash
cd /path/to/opencode_matrix
bun install
bun run typecheck
bun run build
```
## License
MIT