Port OpenCode plugins to the V2 plugin API (2.2.5)
OpenCode 2.x uses a new plugin API; V1 plugins do not load at all. Both
example plugins are rewritten as `export default { id, setup }`.
Fixes, in order of severity:
- Default export with id/setup instead of a named `export const XPlugin`,
which the V2 loader rejects with "Plugin must export a default definition
with an id and an effect or setup function".
- Drop `client.app.log`: the V2 context has no client and no logging API.
Poll results go to ~/.local/state/ollama-plagin-swap/client.log and to the
console. A file log is required because the managed background service
sends stdout to /dev/null.
- Replace the `server.connected` trigger with an immediate poll in `setup`;
V2 never delivers that event to in-process plugins.
- Replace the `session.deleted` interval teardown with a cleanup function
returned from `setup`, and unref the timer so monitoring never keeps the
server alive.
- Use `ctx.location.directory` instead of `ctx.directory`.
- Read opencode.jsonc as well as opencode.json when inferring controls from
providers, stripping comments and trailing commas; provider inference
previously failed silently on JSONC configs.
- Switch from require() to ESM imports.
- TypeScript variant: import types from `@opencode/plugin`, not
`@opencode-ai/plugin`; register tools via `ctx.tool.transform` with JSON
Schema and return `{ content }` from executors.
- Give the tool variant the id `ollama-plagin-swap.tools`, since reusing
`ollama-plagin-swap` makes OpenCode fail it with "Duplicate plugin ID".
Verified on a live OpenCode 2.2.5 server: both variants report `active` via
/api/plugin and the poller writes swap status every interval.
This commit is contained in:
@@ -6,9 +6,15 @@
|
||||
|
||||
- `src/ollama_swap_agent.py` и `src/ollama_swap_common.py`: Python-агент для macOS и Ubuntu.
|
||||
- `examples/opencode/ollama-swap.js`: канонический клиентский плагин OpenCode без зависимостей.
|
||||
- `examples/opencode/ollama-swap.ts`: необязательный TypeScript-плагин с пользовательскими инструментами и runtime-guard.
|
||||
- `examples/opencode/ollama-swap.ts`: необязательный TypeScript-плагин с пользовательскими инструментами
|
||||
(`ollama_swap_status`, `ollama_swap_restart`) и runtime-guard. Требует установки как каталог-плагин
|
||||
с `package.json` (см. ниже).
|
||||
- Агент предоставляет `GET /health`, `GET /status` и `POST /restart`.
|
||||
|
||||
Оба плагина написаны под **API плагинов OpenCode 2.x** (проверено на 2.2.5): экспортируют
|
||||
`export default { id, setup }` и возвращают cleanup-функцию. Плагины V1 API
|
||||
(`export const XPlugin = async (ctx) => ({...})`) в OpenCode 2.x не загружаются.
|
||||
|
||||
## Почему раньше дублировались плагины
|
||||
|
||||
OpenCode автоматически загружает все файлы плагинов из `.opencode/plugins/` проекта и из
|
||||
@@ -171,9 +177,42 @@ curl -sS -H "Authorization: Bearer <token>" http://127.0.0.1:8731/health
|
||||
|
||||
## Проверка клиентского плагина OpenCode
|
||||
|
||||
OpenCode автоматически подключает глобальный plugin из
|
||||
`~/.config/opencode/plugins/ollama-swap.js`. После запуска OpenCode проверьте логи/уведомления:
|
||||
при `server.connected` клиент получит статус с удалённого агента и запустит периодический опрос.
|
||||
OpenCode 2.x автоматически подключает глобальный плагин из
|
||||
`~/.config/opencode/plugins/ollama-swap.js` и вызывает `setup(ctx)` сразу при загрузке —
|
||||
именно на этом шаге выполняется первый опрос агента. `server.connected` плагинам в OpenCode 2.x
|
||||
не доставляется, поэтому старый триггер больше не используется.
|
||||
|
||||
Проверить загрузку:
|
||||
|
||||
```sh
|
||||
opencode plugin list
|
||||
```
|
||||
|
||||
Результат опроса пишется в файл `~/.local/state/ollama-plagin-swap/client.log` (фоновый сервис
|
||||
OpenCode направляет stdout в `/dev/null`, поэтому собственный лог надёжнее) и дублируется в
|
||||
консоль сервера. Строка вида:
|
||||
|
||||
```text
|
||||
2026-11-02T11:21:09.728Z [info] ollama-remote: swap 663.19/2048 MB (32.38%), recommendation=none
|
||||
```
|
||||
|
||||
При превышении порога уровень меняется на `[warn]`, при недоступном агенте пишется
|
||||
`agent unreachable: <name> (<error>)`.
|
||||
|
||||
### Установка TS-варианта с инструментами
|
||||
|
||||
`ollama-swap.ts` регистрирует инструменты, поэтому его нужно ставить как каталог-плагин:
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.config/opencode/plugins/ollama-tools
|
||||
cp examples/opencode/ollama-swap.ts ~/.config/opencode/plugins/ollama-tools/index.ts
|
||||
printf '{ "name": "ollama-swap-tools", "type": "module", "exports": { ".": "./index.ts" } }\n' \
|
||||
> ~/.config/opencode/plugins/ollama-tools/package.json
|
||||
```
|
||||
|
||||
Его id — `ollama-plagin-swap.tools`, поэтому он не конфликтует с обычным файловым плагином: OpenCode
|
||||
отклоняет второй плагин с тем же `id` с ошибкой `Duplicate plugin ID`. Держать оба одновременно
|
||||
обычно не нужно — инструменты лишь дублируют фоновый опрос.
|
||||
|
||||
## Неполадки LaunchAgent
|
||||
|
||||
@@ -195,3 +234,5 @@ OpenCode автоматически подключает глобальный pl
|
||||
/opt/homebrew/bin/pytest -q
|
||||
node --check examples/opencode/ollama-swap.js
|
||||
```
|
||||
|
||||
Для `.ts`-варианта нужен `@opencode/plugin` версии 2.x в `devDependencies` и проверка через `tsc`.
|
||||
|
||||
Reference in New Issue
Block a user