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.
204 lines
6.4 KiB
JavaScript
204 lines
6.4 KiB
JavaScript
// ollama-plagin-swap: low-overhead remote Ollama swap monitor for OpenCode.
|
|
// 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() {
|
|
try {
|
|
const raw = fs.readFileSync(CLIENT_CONFIG, "utf8")
|
|
const parsed = JSON.parse(raw)
|
|
if (Array.isArray(parsed?.controls)) return parsed
|
|
if (Array.isArray(parsed)) return { controls: parsed, interval_seconds: 60 }
|
|
return { controls: [], interval_seconds: 60 }
|
|
} catch {
|
|
return { controls: [], interval_seconds: 60 }
|
|
}
|
|
}
|
|
|
|
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
|
|
const interval = Number(configured.interval_seconds || process.env.OLLAMA_SWAP_INTERVAL || 60)
|
|
|
|
// Infer agent endpoints from OpenCode providers that point at an Ollama server.
|
|
try {
|
|
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(stripJsonComments(raw))
|
|
for (const provider of Object.values(config?.provider || {})) {
|
|
const baseURL = provider?.options?.baseURL
|
|
if (typeof baseURL !== "string") continue
|
|
const match = baseURL.match(/^https?:\/\/([^:/]+)(?::\d+)?/)
|
|
if (!match) continue
|
|
const host = match[1]
|
|
if (controls.some((item) => item.agent_url?.includes(host))) continue
|
|
controls.push({
|
|
name: provider?.name || host,
|
|
host,
|
|
agent_url: "http://" + host + ":8731",
|
|
token,
|
|
ollama_base_url: baseURL.replace(/\/v1\/?$/, ""),
|
|
})
|
|
}
|
|
} catch {
|
|
// OpenCode config is optional; explicit clients.json is enough.
|
|
}
|
|
|
|
return { controls, interval_seconds: interval > 0 ? interval : 60 }
|
|
}
|
|
|
|
async function fetchStatus(control) {
|
|
const controller = new AbortController()
|
|
const timer = setTimeout(() => controller.abort(), 5000)
|
|
try {
|
|
const response = await fetch(control.agent_url.replace(/\/$/, "") + "/status", {
|
|
headers: control.token ? { Authorization: "Bearer " + control.token } : {},
|
|
signal: controller.signal,
|
|
})
|
|
if (!response.ok) throw new Error("HTTP " + response.status)
|
|
return await response.json()
|
|
} finally {
|
|
clearTimeout(timer)
|
|
}
|
|
}
|
|
|
|
// 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.
|
|
}
|
|
if (level === "warn") console.warn(SERVICE + " " + line)
|
|
else console.log(SERVICE + " " + line)
|
|
}
|
|
|
|
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 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
|