matrix-plugin/plugins/matrix-plugin
Бородин Роман 7db5bc6989 refactor: remove session expiry, add syncWithOpenCode
- Remove expireInactive and startExpiryLoop
- Add syncWithOpenCode() to prune orphaned sessions
- Add logging for session map file path and load count
2026-09-25 15:44:33 +03:00
..
.gitignore feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
PLUGIN-DOCS-v2.md feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
README.md feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
bun.lock feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
config-loader.ts feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
index.ts refactor: remove session expiry, add syncWithOpenCode 2026-09-25 15:44:33 +03:00
logger.ts feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
matrix-client.ts feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
package-lock.json feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
package.json feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
session-manager.ts refactor: remove session expiry, add syncWithOpenCode 2026-09-25 15:44:33 +03:00
tsconfig.json feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00
types.ts feat: add matrix plugin with V1/V2 SDK support 2026-09-25 15:22:20 +03:00

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, /help for 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

  1. Copy this plugin directory into your OpenCode config:
mkdir -p ~/.config/opencode/plugins
cp -r ./opencode-matrix-plugin ~/.config/opencode/plugins/
  1. 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

Конфигурация загружается в следующем порядке приоритетов:

  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):

{
  "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

  1. Prefix trigger: Send !oc What is TypeScript?
  2. @Mention: Send @opencode What is TypeScript?
  3. DM: Send any message in a direct message with the bot
  4. 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

  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 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 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

cd plugins/opencode-matrix-plugin
npm install
npm run typecheck
npm run build

License

MIT