Порядок когда execute имеет детей: 1. Thinking spoiler 2. Каждый дочерний инструмент с args 3. Execute result spoiler 4. --- separator + step.text |
||
|---|---|---|
| .env.example | ||
| .gitignore | ||
| PLUGIN-DOCS-v2.md | ||
| README.md | ||
| bun.lock | ||
| config-loader.ts | ||
| index.ts | ||
| logger.ts | ||
| matrix-client.ts | ||
| matrix.json.example | ||
| opencode.example.jsonc | ||
| 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
- Configurable Triggers:
triggerPatternsarray — 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,/helpfor 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)
- Create a symlink from your OpenCode config to this plugin:
mkdir -p ~/.config/opencode/plugins
ln -s /path/to/your/opencode_matrix ~/.config/opencode/plugins/matrix-plugin
- Add the plugin to your
opencode.jsonc:
{
"plugins": [
"./plugins/matrix-plugin"
]
}
Option 2: Published Package
{
"plugins": [
"opencode-matrix-plugin"
]
}
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[] | [] |
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):
- Plugin options from
opencode.jsonc(plugins[].options) - Config file —
matrix.jsonormatrix.jsoncin:- Project level:
.opencode/matrix.json(next toopencode.jsonc) - Global level:
~/.config/opencode/matrix.json
- Project level:
- Environment variables —
MATRIX_*
Auto-create: If no config is found, the plugin auto-creates
~/.config/opencode/matrix.jsonwith defaults (permissions0o600).
Example Config
Copy matrix.json.example from the project root and customize:
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 "]):
- Prefix trigger: Send
!oc What is TypeScript? - @Mention: Send
@opencode What is TypeScript? - 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
- 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
├── 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
0o600permissions - 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
- 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 - Check logs:
~/.opencode-matrix-plugin/plugin.log
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
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
cd /path/to/opencode_matrix
bun install
bun run typecheck
bun run build
License
MIT