matrix-plugin/README.md

269 lines
8.9 KiB
Markdown
Raw 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 plugin that connects your OpenCode agent to Matrix messaging servers. Supports both V1 (SDK) and V2 (full context) APIs.
## 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`
- **V1/V2 Dual Support**: Works with OpenCode 1.18.x (V1 SDK) and V2 (full context)
## Installation
### Option 1: Local Plugin (Recommended)
1. Copy this plugin directory into your OpenCode config:
```bash
mkdir -p ~/.config/opencode/plugins
cp -r ./plugins/matrix-plugin ~/.config/opencode/plugins/
```
2. Add the plugin to your `opencode.jsonc`:
```jsonc
{
"plugins": [
"./plugins/matrix-plugin"
]
}
```
### Option 2: Symlink
```bash
mkdir -p ~/.config/opencode/plugins
ln -s /path/to/your/project/plugins/matrix-plugin ~/.config/opencode/plugins/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
├── Event deduplication
├── Thread isolation (room:threadId)
└── Session persistence (~/.opencode-matrix-sessions.json)
│
▼
OpenCode API
│
├── V2: ctx.session.prompt() / ctx.session.create()
├── V1: sdkClient.session.prompt() / sdkClient.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`.
- **V1 API**: Sessions are created with auto-generated IDs, mapped via JSON file
- **V2 API**: Sessions can be created with custom deterministic IDs (no map needed)
- **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
- **Event Deduplication**: Prevent processing duplicate events
## 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. Enable debug logging: `BRIDGE_DEBUG=1 opencode`
### 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
## Development
```bash
cd plugins/matrix-plugin
bun install
bun run typecheck
bun run build
```
## License
MIT