- Dual V1/V2 plugin export pattern - Session persistence via ~/.opencode-matrix-sessions.json - Thread-to-session mapping with deterministic IDs - Matrix bot integration with E2EE support - Config from matrix.json or environment variables |
||
|---|---|---|
| .. | ||
| .gitignore | ||
| PLUGIN-DOCS-v2.md | ||
| README.md | ||
| bun.lock | ||
| config-loader.ts | ||
| index.ts | ||
| logger.ts | ||
| matrix-client.ts | ||
| package-lock.json | ||
| package.json | ||
| session-manager.ts | ||
| tsconfig.json | ||
| types.ts | ||
README.md
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
- Multiple Trigger Modes: Prefix trigger (
!oc), @mention, or DM - Thread Replies: Respond to plain replies within active threads
- Bridge Commands:
/status,/clear,/helpfor session management - Rate Limiting: Configurable per-user rate limiting
- User Allowlisting: Restrict who can interact with the bot
- Image Support: Upload and display images in Matrix
- HTML Formatting: Optional HTML-formatted responses
- Session Persistence: Sessions survive plugin reloads
Installation
Option 1: Local Plugin (Recommended)
- Copy this plugin directory into your OpenCode config:
mkdir -p ~/.config/opencode/plugins
cp -r ./opencode-matrix-plugin ~/.config/opencode/plugins/
- Add the plugin to your
opencode.jsonc:
{
"plugins": [
"./plugins/opencode-matrix-plugin"
]
}
Option 2: npm Package
cd ~/.config/opencode
npm init -y
npm install ./path/to/opencode-matrix-plugin
Then in opencode.jsonc:
{
"plugins": [
{
"package": "opencode-matrix-plugin",
"options": {
"homeserver": "https://matrix.org",
"userId": "@opencode:matrix.org",
"password": "your-bot-password"
}
}
]
}
Configuration
Конфигурация загружается в следующем порядке приоритетов:
- Plugin options из
opencode.jsonc(plugins[].options) — высший приоритет - Config file —
.opencode/matrix.json(проект) или~/.config/opencode/matrix.json(глобальный) - Environment variables —
MATRIX_*— базовый уровень
Auto-create: Если конфиг не найден ни в одной директории, плагин автоматически создаст
~/.config/opencode/matrix.jsonс дефолтными значениями (права0o600).
Config File
Создайте matrix.json в одной из директорий:
Проектный уровень — .opencode/matrix.json (рядом с opencode.jsonc):
{
"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:
{
"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[] | ["!oc "] |
Message prefixes to trigger the bot |
ignoreRooms |
string[] | [] |
Room IDs to ignore |
ignoreUsers |
string[] | [] |
User IDs to 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 |
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 |
Usage
Triggering the Bot
- Prefix trigger: Send
!oc What is TypeScript? - @Mention: Send
@opencode What is TypeScript? - DM: Send any message in a direct message with the bot
- Thread reply: Reply to any message in an active thread
Bridge Commands
| Command | Description |
|---|---|
/help or /h |
Show help message |
/status |
Show current session info |
/clear or /reset |
Clear current session |
Room Setup
- Invite
@opencode:matrix.orgto your room - The bot auto-joins (if
autoJoin: true) - Start messaging with the trigger prefix or @mention
Bot Setup (First Time)
- Create a Matrix account for your bot (or use existing)
- Set
MATRIX_PASSWORDorMATRIX_ACCESS_TOKEN - The bot will auto-login and save the access token
- 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 lifecycle
│
▼
OpenCode V2 Plugin API
│
├── ctx.session.prompt() - send queries
├── ctx.session.hook("prompt") - intercept
├── ctx.command.transform() - bridge commands
├── ctx.event.subscribe() - event stream
└── ctx.storage - persistence
│
▼
Response → MatrixBotClient → Matrix Room
Security
- E2EE: Full end-to-end encryption support via
@matrix-org/matrix-sdk-crypto-nodejs - Token Storage: Access tokens saved with
0o600permissions - User Allowlisting: Restrict bot access to specific users
- Rate Limiting: Prevent message spam
- Event Deduplication: Prevent processing duplicate events
Troubleshooting
Bot doesn't respond
- Check that the bot is in the room
- Verify the trigger pattern matches your message
- Check if the user is in the allowed list (if configured)
- Check
~/.local/share/opencode-matrix-bot/for state files - Enable debug logging:
BRIDGE_DEBUG=1 opencode
Authentication fails
- Verify
MATRIX_USER_IDandMATRIX_PASSWORDare correct - Check that the bot account exists on the homeserver
- Try setting
MATRIX_ACCESS_TOKENdirectly - Check homeserver logs for authentication errors
E2EE issues
- Ensure
@matrix-org/matrix-sdk-crypto-nodejsis installed - Check crypto storage directory has write permissions
- Verify the bot has access to the encrypted room
Development
cd plugins/opencode-matrix-plugin
npm install
npm run typecheck
npm run build
License
MIT