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.
158 lines
5.2 KiB
TypeScript
158 lines
5.2 KiB
TypeScript
// 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 { homedir } from "node:os"
|
|
import path from "node:path"
|
|
|
|
interface Control {
|
|
name: string
|
|
agent_url: string
|
|
token?: string | null
|
|
}
|
|
|
|
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")
|
|
try {
|
|
const parsed = JSON.parse(await readFile(file, "utf8"))
|
|
return Array.isArray(parsed?.controls) ? parsed.controls : []
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
async function request(control: Control, method: string, pathname: string, body?: unknown): Promise<any> {
|
|
const response = await fetch(control.agent_url.replace(/\/$/, "") + pathname, {
|
|
method,
|
|
headers: {
|
|
...(control.token ? { Authorization: "Bearer " + control.token } : {}),
|
|
...(body ? { "Content-Type": "application/json" } : {}),
|
|
},
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
signal: AbortSignal.timeout(8000),
|
|
})
|
|
const text = await response.text()
|
|
let parsed: unknown
|
|
try {
|
|
parsed = JSON.parse(text)
|
|
} catch {
|
|
parsed = text
|
|
}
|
|
if (!response.ok) throw new Error(control.name + ": HTTP " + response.status + " " + text)
|
|
return parsed
|
|
}
|
|
|
|
function summary(control: Control, status: any) {
|
|
return (
|
|
`${control.name}: swap ${status?.swap?.swap_used_mb ?? "?"}/${status?.swap?.swap_total_mb ?? "?"}` +
|
|
` MB (${status?.swap?.swap_percent ?? "?"}%), recommendation=${status?.recommendation ?? "unknown"}`
|
|
)
|
|
}
|
|
|
|
async function pollOnce() {
|
|
for (const control of await controls()) {
|
|
try {
|
|
const status = await request(control, "GET", "/status")
|
|
await logLine(
|
|
status?.threshold_exceeded ? "warn" : "info",
|
|
summary(control, status),
|
|
)
|
|
} catch (error) {
|
|
await logLine("warn", `agent unreachable: ${control.name} (${String(error)})`)
|
|
}
|
|
}
|
|
}
|
|
|
|
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",
|
|
input: { type: "object", properties: {}, additionalProperties: false },
|
|
async execute() {
|
|
const result = []
|
|
for (const control of await controls()) {
|
|
try {
|
|
result.push({ name: control.name, status: await request(control, "GET", "/status") })
|
|
} catch (error) {
|
|
result.push({ name: control.name, error: String(error) })
|
|
}
|
|
}
|
|
const text = JSON.stringify(result, null, 2)
|
|
return { content: text }
|
|
},
|
|
})
|
|
|
|
editor.add({
|
|
name: "ollama_swap_restart",
|
|
description: "Restart a remote Ollama service after its swap threshold is exceeded",
|
|
input: {
|
|
type: "object",
|
|
properties: {
|
|
name: { type: "string", description: "Agent name from clients.json" },
|
|
force: {
|
|
type: "boolean",
|
|
description: "Force restart even if models are active",
|
|
},
|
|
},
|
|
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)
|
|
if (!control) throw new Error("unknown agent: " + args.name)
|
|
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
|