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:
@@ -1,9 +1,16 @@
|
||||
// ollama-plagin-swap: low-overhead remote Ollama swap monitor for OpenCode.
|
||||
const fs = require("node:fs")
|
||||
const os = require("node:os")
|
||||
const path = require("node:path")
|
||||
// Targets the OpenCode 2.x plugin API (V2): a default export with `id` and `setup`.
|
||||
import fs from "node:fs"
|
||||
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 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")
|
||||
|
||||
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 controls = [...(configured.controls || [])]
|
||||
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.
|
||||
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 config = JSON.parse(raw)
|
||||
const config = JSON.parse(stripJsonComments(raw))
|
||||
for (const provider of Object.values(config?.provider || {})) {
|
||||
const baseURL = provider?.options?.baseURL
|
||||
if (typeof baseURL !== "string") continue
|
||||
@@ -66,61 +129,75 @@ async function fetchStatus(control) {
|
||||
}
|
||||
}
|
||||
|
||||
export const OllamaSwapPlugin = async (ctx) => {
|
||||
if (globalThis[STARTED_KEY]) {
|
||||
return {}
|
||||
// OpenCode 2.x plugins run inside the server process and have no client logging
|
||||
// API. The managed background service writes its stdout to /dev/null, so record
|
||||
// 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.
|
||||
}
|
||||
globalThis[STARTED_KEY] = true
|
||||
if (level === "warn") console.warn(SERVICE + " " + line)
|
||||
else console.log(SERVICE + " " + line)
|
||||
}
|
||||
|
||||
const { controls, interval_seconds } = inferControls(ctx)
|
||||
|
||||
async function pollOnce(client) {
|
||||
for (const control of controls) {
|
||||
try {
|
||||
const status = await fetchStatus(control)
|
||||
const summary =
|
||||
control.name +
|
||||
": swap " +
|
||||
(status?.swap?.swap_used_mb ?? "?") +
|
||||
"/" +
|
||||
(status?.swap?.swap_total_mb ?? "?") +
|
||||
" MB (" +
|
||||
(status?.swap?.swap_percent ?? "?") +
|
||||
"%), recommendation=" +
|
||||
(status?.recommendation ?? "unknown")
|
||||
await client.app.log({
|
||||
body: {
|
||||
service: "ollama-plagin-swap",
|
||||
level: status?.threshold_exceeded ? "warn" : "info",
|
||||
message: summary,
|
||||
extra: { control: control.name, status },
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
await client.app.log({
|
||||
body: {
|
||||
service: "ollama-plagin-swap",
|
||||
level: "warn",
|
||||
message: "agent unreachable: " + control.name + " (" + String(error) + ")",
|
||||
extra: { control: control.name },
|
||||
},
|
||||
})
|
||||
}
|
||||
async function pollOnce(controls) {
|
||||
for (const control of controls) {
|
||||
try {
|
||||
const status = await fetchStatus(control)
|
||||
const summary =
|
||||
control.name +
|
||||
": swap " +
|
||||
(status?.swap?.swap_used_mb ?? "?") +
|
||||
"/" +
|
||||
(status?.swap?.swap_total_mb ?? "?") +
|
||||
" MB (" +
|
||||
(status?.swap?.swap_percent ?? "?") +
|
||||
"%), recommendation=" +
|
||||
(status?.recommendation ?? "unknown")
|
||||
logLine(status?.threshold_exceeded ? "warn" : "info", summary, {
|
||||
control: control.name,
|
||||
threshold_exceeded: status?.threshold_exceeded ?? null,
|
||||
ollama_busy: status?.ollama_busy ?? null,
|
||||
})
|
||||
} catch (error) {
|
||||
logLine("warn", "agent unreachable: " + control.name + " (" + String(error) + ")", {
|
||||
control: control.name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const timer = setInterval(() => {
|
||||
pollOnce(ctx.client).catch(() => {})
|
||||
}, interval_seconds * 1000)
|
||||
|
||||
return {
|
||||
event: async ({ event }) => {
|
||||
if (event.type === "server.connected") {
|
||||
await pollOnce(ctx.client)
|
||||
}
|
||||
if (event.type === "session.deleted") {
|
||||
clearInterval(timer)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const OllamaSwapPlugin = {
|
||||
id: "ollama-plagin-swap",
|
||||
async setup(ctx) {
|
||||
if (globalThis[STARTED_KEY]) return
|
||||
globalThis[STARTED_KEY] = true
|
||||
|
||||
const { controls, interval_seconds } = inferControls(ctx?.location?.directory)
|
||||
|
||||
// V2 never delivers `server.connected` to plugins, so start polling here.
|
||||
// Do not block plugin setup on network I/O.
|
||||
void pollOnce(controls).catch(() => {})
|
||||
|
||||
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)
|
||||
globalThis[STARTED_KEY] = false
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export default OllamaSwapPlugin
|
||||
|
||||
Reference in New Issue
Block a user