Files
ollama-plagin-swap/examples/opencode/ollama-swap.ts
T

262 lines
8.9 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 { existsSync } from "node:fs"
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
host?: string
agent_url: string
token?: string | null
ollama_base_url?: string | null
inferred?: boolean
}
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}`)
}
// Minimal JSONC support: strip // and /* */ comments outside strings, and
// trailing commas, so opencode.jsonc can be parsed with JSON.parse.
function stripJsonComments(raw: string): string {
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")
}
// Directory OpenCode passes to setup(); used to locate opencode.json(c) for
// provider inference. Falls back to the server's working directory.
let locationDirectory: string | undefined
async function controls(baseDirectory?: string): Promise<Control[]> {
const file = path.join(homedir(), ".config", "ollama-plagin-swap", "clients.json")
let configured: any = {}
try {
configured = JSON.parse(await readFile(file, "utf8"))
} catch {
configured = {}
}
const explicit: Control[] = Array.isArray(configured?.controls) ? configured.controls : []
const inferred = configured?.infer_providers === false ? [] : await inferFromProviders(baseDirectory || locationDirectory, configured)
const seen = new Set(explicit.map((item) => item.host || item.agent_url))
return [...explicit, ...inferred.filter((item) => !seen.has(item.host || item.agent_url))]
}
// Mirror of the JS plugin's inference: V2 `providers.<id>.settings.baseURL` first,
// then the deprecated `provider.<id>.options.baseURL`.
async function inferFromProviders(baseDirectory?: string, configured: any = {}): Promise<Control[]> {
const directory = baseDirectory || process.cwd()
const configPath = ["opencode.json", "opencode.jsonc", path.join(".opencode", "opencode.json"), path.join(".opencode", "opencode.jsonc")]
.map((name) => path.resolve(directory, name))
.find((candidate) => existsSync(candidate))
if (!configPath) return []
let config: any
try {
config = JSON.parse(stripJsonComments(await readFile(configPath, "utf8")))
} catch {
return []
}
const token = process.env.OLLAMA_SWAP_TOKEN || null
const result: Control[] = []
for (const [id, provider] of Object.entries<any>({ ...(config?.provider || {}), ...(config?.providers || {}) })) {
const settings = provider?.settings || provider?.options || {}
const baseURL: string | undefined = settings.baseURL || provider?.baseURL
const explicitAgent: string | undefined = settings.agentURL || settings.swap_agent_url
const source = explicitAgent || baseURL
if (!source) continue
const match = source.match(/^https?:\/\/([^:/]+)(?::\d+)?/)
if (!match) continue
const host = match[1]
if (!explicitAgent) {
if (!/^http:/.test(baseURL || "")) continue
const loopback = ["localhost", "127.0.0.1", "::1", "0.0.0.0"].includes(host)
if (loopback && configured?.infer_loopback !== true) continue
}
if (result.some((item) => item.host === host)) continue
result.push({ name: provider?.name || id || host, host, agent_url: explicitAgent || "http://" + host + ":8731", token })
}
return result
}
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) {
const hint = control.inferred
? " — inferred from opencode config; set infer_providers: false in clients.json to silence"
: ""
await logLine("warn", `agent unreachable: ${control.name} (${String(error)})${hint}`)
}
}
}
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
locationDirectory = ctx?.location?.directory
// 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