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:
Andrew Emelyaneko
2026-11-02 14:27:37 +03:00
parent cad35c8bd3
commit d25aa7a686
3 changed files with 281 additions and 111 deletions
+45 -4
View File
@@ -6,9 +6,15 @@
- `src/ollama_swap_agent.py` и `src/ollama_swap_common.py`: Python-агент для macOS и Ubuntu. - `src/ollama_swap_agent.py` и `src/ollama_swap_common.py`: Python-агент для macOS и Ubuntu.
- `examples/opencode/ollama-swap.js`: канонический клиентский плагин OpenCode без зависимостей. - `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`. - Агент предоставляет `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/` проекта и из OpenCode автоматически загружает все файлы плагинов из `.opencode/plugins/` проекта и из
@@ -171,9 +177,42 @@ curl -sS -H "Authorization: Bearer <token>" http://127.0.0.1:8731/health
## Проверка клиентского плагина OpenCode ## Проверка клиентского плагина OpenCode
OpenCode автоматически подключает глобальный plugin из OpenCode 2.x автоматически подключает глобальный плагин из
`~/.config/opencode/plugins/ollama-swap.js`. После запуска OpenCode проверьте логи/уведомления: `~/.config/opencode/plugins/ollama-swap.js` и вызывает `setup(ctx)` сразу при загрузке —
при `server.connected` клиент получит статус с удалённого агента и запустит периодический опрос. именно на этом шаге выполняется первый опрос агента. `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 ## Неполадки LaunchAgent
@@ -195,3 +234,5 @@ OpenCode автоматически подключает глобальный pl
/opt/homebrew/bin/pytest -q /opt/homebrew/bin/pytest -q
node --check examples/opencode/ollama-swap.js node --check examples/opencode/ollama-swap.js
``` ```
Для `.ts`-варианта нужен `@opencode/plugin` версии 2.x в `devDependencies` и проверка через `tsc`.
+114 -37
View File
@@ -1,9 +1,16 @@
// ollama-plagin-swap: low-overhead remote Ollama swap monitor for OpenCode. // ollama-plagin-swap: low-overhead remote Ollama swap monitor for OpenCode.
const fs = require("node:fs") // Targets the OpenCode 2.x plugin API (V2): a default export with `id` and `setup`.
const os = require("node:os") import fs from "node:fs"
const path = require("node:path") import os from "node:os"
import path from "node:path"
const SERVICE = "ollama-plagin-swap"
const CLIENT_CONFIG = path.join(os.homedir(), ".config", "ollama-plagin-swap", "clients.json") const CLIENT_CONFIG = path.join(os.homedir(), ".config", "ollama-plagin-swap", "clients.json")
const LOG_FILE = path.join(
process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"),
"ollama-plagin-swap",
"client.log",
)
const STARTED_KEY = Symbol.for("ollamaPlaginSwapStarted") const STARTED_KEY = Symbol.for("ollamaPlaginSwapStarted")
function readClientConfig() { function readClientConfig() {
@@ -18,7 +25,59 @@ function readClientConfig() {
} }
} }
function inferControls(ctx) { function stripJsonComments(raw) {
// Minimal JSONC support: drop // line comments and /* block */ comments
// outside of strings, plus trailing commas.
let out = ""
let inString = false
let inLine = false
let inBlock = false
let escaped = false
for (let i = 0; i < raw.length; i++) {
const char = raw[i]
const next = raw[i + 1]
if (inLine) {
if (char === "\n") {
inLine = false
out += char
}
continue
}
if (inBlock) {
if (char === "*" && next === "/") {
inBlock = false
i++
}
continue
}
if (inString) {
out += char
if (escaped) escaped = false
else if (char === "\\") escaped = true
else if (char === '"') inString = false
continue
}
if (char === '"') {
inString = true
out += char
continue
}
if (char === "/" && next === "/") {
inLine = true
i++
continue
}
if (char === "/" && next === "*") {
inBlock = true
i++
continue
}
out += char
}
return out.replace(/,(\s*[}\]])/g, "$1")
}
function inferControls(baseDirectory) {
const configured = readClientConfig() const configured = readClientConfig()
const controls = [...(configured.controls || [])] const controls = [...(configured.controls || [])]
const token = process.env.OLLAMA_SWAP_TOKEN || null const token = process.env.OLLAMA_SWAP_TOKEN || null
@@ -26,9 +85,13 @@ function inferControls(ctx) {
// Infer agent endpoints from OpenCode providers that point at an Ollama server. // Infer agent endpoints from OpenCode providers that point at an Ollama server.
try { try {
const configPath = path.join(ctx.directory || process.cwd(), "opencode.json") const directory = baseDirectory
const configPath = ["opencode.json", "opencode.jsonc", path.join(".opencode", "opencode.json"), path.join(".opencode", "opencode.jsonc")]
.map((name) => path.resolve(directory || process.cwd(), name))
.find((candidate) => fs.existsSync(candidate))
if (!configPath) throw new Error("no opencode config")
const raw = fs.readFileSync(configPath, "utf8") const raw = fs.readFileSync(configPath, "utf8")
const config = JSON.parse(raw) const config = JSON.parse(stripJsonComments(raw))
for (const provider of Object.values(config?.provider || {})) { for (const provider of Object.values(config?.provider || {})) {
const baseURL = provider?.options?.baseURL const baseURL = provider?.options?.baseURL
if (typeof baseURL !== "string") continue if (typeof baseURL !== "string") continue
@@ -66,15 +129,25 @@ async function fetchStatus(control) {
} }
} }
export const OllamaSwapPlugin = async (ctx) => { // OpenCode 2.x plugins run inside the server process and have no client logging
if (globalThis[STARTED_KEY]) { // API. The managed background service writes its stdout to /dev/null, so record
return {} // poll results in our own log file (and mirror them to the console).
function logLine(level, message, detail) {
const line = new Date().toISOString() + " [" + level + "] " + message
try {
fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true })
fs.appendFileSync(
LOG_FILE,
detail ? line + " " + JSON.stringify(detail) + "\n" : line + "\n",
)
} catch {
// Logging must never break polling; fall back to the console only.
}
if (level === "warn") console.warn(SERVICE + " " + line)
else console.log(SERVICE + " " + line)
} }
globalThis[STARTED_KEY] = true
const { controls, interval_seconds } = inferControls(ctx) async function pollOnce(controls) {
async function pollOnce(client) {
for (const control of controls) { for (const control of controls) {
try { try {
const status = await fetchStatus(control) const status = await fetchStatus(control)
@@ -88,39 +161,43 @@ export const OllamaSwapPlugin = async (ctx) => {
(status?.swap?.swap_percent ?? "?") + (status?.swap?.swap_percent ?? "?") +
"%), recommendation=" + "%), recommendation=" +
(status?.recommendation ?? "unknown") (status?.recommendation ?? "unknown")
await client.app.log({ logLine(status?.threshold_exceeded ? "warn" : "info", summary, {
body: { control: control.name,
service: "ollama-plagin-swap", threshold_exceeded: status?.threshold_exceeded ?? null,
level: status?.threshold_exceeded ? "warn" : "info", ollama_busy: status?.ollama_busy ?? null,
message: summary,
extra: { control: control.name, status },
},
}) })
} catch (error) { } catch (error) {
await client.app.log({ logLine("warn", "agent unreachable: " + control.name + " (" + String(error) + ")", {
body: { control: control.name,
service: "ollama-plagin-swap",
level: "warn",
message: "agent unreachable: " + control.name + " (" + String(error) + ")",
extra: { control: control.name },
},
}) })
} }
} }
} }
const timer = setInterval(() => { const OllamaSwapPlugin = {
pollOnce(ctx.client).catch(() => {}) id: "ollama-plagin-swap",
}, interval_seconds * 1000) async setup(ctx) {
if (globalThis[STARTED_KEY]) return
globalThis[STARTED_KEY] = true
return { const { controls, interval_seconds } = inferControls(ctx?.location?.directory)
event: async ({ event }) => {
if (event.type === "server.connected") { // V2 never delivers `server.connected` to plugins, so start polling here.
await pollOnce(ctx.client) // Do not block plugin setup on network I/O.
} void pollOnce(controls).catch(() => {})
if (event.type === "session.deleted") {
const timer = setInterval(() => {
pollOnce(controls).catch(() => {})
}, interval_seconds * 1000)
// Do not keep the server alive just for monitoring.
timer.unref?.()
// Returned cleanup runs when the plugin is unloaded or reloaded.
return () => {
clearInterval(timer) clearInterval(timer)
globalThis[STARTED_KEY] = false
} }
}, },
} }
}
export default OllamaSwapPlugin
+92 -40
View File
@@ -1,4 +1,7 @@
import { type Plugin, tool } from "@opencode-ai/plugin" // ollama-plagin-swap (tool variant) for OpenCode 2.x.
// Register as a directory plugin: package.json with `"exports": { ".": "./index.ts" }`.
import type { Plugin } from "@opencode/plugin"
import { appendFile, mkdir } from "node:fs/promises"
import { readFile } from "node:fs/promises" import { readFile } from "node:fs/promises"
import { homedir } from "node:os" import { homedir } from "node:os"
import path from "node:path" import path from "node:path"
@@ -9,7 +12,28 @@ interface Control {
token?: string | null token?: string | null
} }
async function controls() { const SERVICE = "ollama-plagin-swap"
const LOG_FILE = path.join(
process.env.XDG_STATE_HOME || path.join(homedir(), ".local", "state"),
"ollama-plagin-swap",
"client.log",
)
// The managed OpenCode service writes stdout to /dev/null, so persist poll
// results to our own log file and mirror them to the console.
async function logLine(level: "info" | "warn", message: string) {
const line = `${new Date().toISOString()} [${level}] ${message}`
try {
await mkdir(path.dirname(LOG_FILE), { recursive: true })
await appendFile(LOG_FILE, line + "\n")
} catch {
// Logging must never break polling.
}
if (level === "warn") console.warn(`${SERVICE} ${line}`)
else console.log(`${SERVICE} ${line}`)
}
async function controls(): Promise<Control[]> {
const file = path.join(homedir(), ".config", "ollama-plagin-swap", "clients.json") const file = path.join(homedir(), ".config", "ollama-plagin-swap", "clients.json")
try { try {
const parsed = JSON.parse(await readFile(file, "utf8")) const parsed = JSON.parse(await readFile(file, "utf8"))
@@ -19,7 +43,7 @@ async function controls() {
} }
} }
async function request(control: Control, method: string, pathname: string, body?: unknown) { async function request(control: Control, method: string, pathname: string, body?: unknown): Promise<any> {
const response = await fetch(control.agent_url.replace(/\/$/, "") + pathname, { const response = await fetch(control.agent_url.replace(/\/$/, "") + pathname, {
method, method,
headers: { headers: {
@@ -40,42 +64,46 @@ async function request(control: Control, method: string, pathname: string, body?
return parsed return parsed
} }
export const OllamaSwapPlugin: Plugin = async (ctx) => { function summary(control: Control, status: any) {
const startedKey = Symbol.for("ollamaPlaginSwapStarted") return (
if ((globalThis as any)[startedKey]) { `${control.name}: swap ${status?.swap?.swap_used_mb ?? "?"}/${status?.swap?.swap_total_mb ?? "?"}` +
return {} ` MB (${status?.swap?.swap_percent ?? "?"}%), recommendation=${status?.recommendation ?? "unknown"}`
)
} }
(globalThis as any)[startedKey] = true
return { async function pollOnce() {
event: async ({ event }) => {
if (event.type !== "server.connected") return
for (const control of await controls()) { for (const control of await controls()) {
try { try {
const status = await request(control, "GET", "/status") const status = await request(control, "GET", "/status")
await ctx.client.app.log({ await logLine(
body: { status?.threshold_exceeded ? "warn" : "info",
service: "ollama-plagin-swap", summary(control, status),
level: status?.threshold_exceeded ? "warn" : "info", )
message: `${control.name}: swap ${status?.swap?.swap_used_mb}/${status?.swap?.swap_total_mb} MB (${status?.swap?.swap_percent}%), recommendation=${status?.recommendation}`,
extra: { control: control.name, status },
},
})
} catch (error) { } catch (error) {
await ctx.client.app.log({ await logLine("warn", `agent unreachable: ${control.name} (${String(error)})`)
body: {
service: "ollama-plagin-swap",
level: "warn",
message: `${control.name}: agent unreachable (${String(error)})`,
},
})
} }
} }
}, }
tool: {
ollama_swap_status: tool({ const STARTED_KEY = Symbol.for("ollamaPlaginSwapToolsStarted")
const plugin: Plugin.Plugin = {
// Must differ from the plain-file variant, otherwise OpenCode reports
// "Duplicate plugin ID" and refuses to load the second copy.
id: "ollama-plagin-swap.tools",
async setup(ctx): Promise<Plugin.Cleanup | void> {
if ((globalThis as any)[STARTED_KEY]) return
;(globalThis as any)[STARTED_KEY] = true
// V2 plugins never receive `server.connected`, so start polling here.
// Do not block plugin setup on network I/O.
void pollOnce().catch(() => {})
await ctx.tool.transform((editor) => {
editor.add({
name: "ollama_swap_status",
description: "Read Ollama swap status from configured remote agents", description: "Read Ollama swap status from configured remote agents",
args: {}, input: { type: "object", properties: {}, additionalProperties: false },
async execute() { async execute() {
const result = [] const result = []
for (const control of await controls()) { for (const control of await controls()) {
@@ -85,21 +113,45 @@ export const OllamaSwapPlugin: Plugin = async (ctx) => {
result.push({ name: control.name, error: String(error) }) result.push({ name: control.name, error: String(error) })
} }
} }
return JSON.stringify(result, null, 2) const text = JSON.stringify(result, null, 2)
return { content: text }
}, },
}), })
ollama_swap_restart: tool({
editor.add({
name: "ollama_swap_restart",
description: "Restart a remote Ollama service after its swap threshold is exceeded", description: "Restart a remote Ollama service after its swap threshold is exceeded",
args: { input: {
name: tool.schema.string().describe("Agent name from clients.json"), type: "object",
force: tool.schema.boolean().optional().describe("Force restart even if models are active"), properties: {
name: { type: "string", description: "Agent name from clients.json" },
force: {
type: "boolean",
description: "Force restart even if models are active",
}, },
async execute(args) { },
required: ["name"],
additionalProperties: false,
},
async execute(input) {
const args = input as { name: string; force?: boolean }
const control = (await controls()).find((item) => item.name === args.name) const control = (await controls()).find((item) => item.name === args.name)
if (!control) throw new Error("unknown agent: " + args.name) if (!control) throw new Error("unknown agent: " + args.name)
return JSON.stringify(await request(control, "POST", "/restart", { force: Boolean(args.force), reason: "opencode" }), null, 2) const result = await request(control, "POST", "/restart", {
force: Boolean(args.force),
reason: "opencode",
})
const text = JSON.stringify(result, null, 2)
return { content: text }
}, },
}), })
})
// OpenCode 2.x has no dispose hook; return a cleanup closure instead.
return () => {
;(globalThis as any)[STARTED_KEY] = false
}
}, },
} }
}
export default plugin