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

269 lines
8.9 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")
}
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "0.0.0.0"])
function firstString(...values) {
for (const value of values) {
if (typeof value === "string" && value.trim()) return value.trim()
}
return null
}
// OpenCode 2.x keeps provider endpoints in `providers.<id>.settings.baseURL`.
// The deprecated 1.x shape used `provider.<id>.options.baseURL`; read both so a
// config migration cannot silently disable inference.
function providerBaseURL(provider) {
return firstString(provider?.settings?.baseURL, provider?.options?.baseURL, provider?.baseURL)
}
// Explicit opt-in: `settings.agentURL` (or the legacy `options.agentURL`) points
// straight at the swap agent, so such providers bypass the heuristics below.
function providerAgentURL(provider) {
return firstString(
provider?.settings?.agentURL,
provider?.settings?.swap_agent_url,
provider?.options?.agentURL,
provider?.options?.swap_agent_url,
)
}
function hostOf(url) {
const match = String(url || "").match(/^https?:\/\/([^:/]+)(?::\d+)?/)
return match ? match[1] : null
}
function isLoopbackHost(host) {
return LOOPBACK_HOSTS.has(host) || host.endsWith(".localhost")
}
// A swap agent listens on plain HTTP on a LAN address. Public HTTPS gateways and
// loopback providers (a local Ollama with no agent) would only log a connection
// error on every poll, so they are skipped unless inference was opted in.
function looksLikeSwapHost(baseURL, options) {
let url
try {
url = new URL(baseURL)
} catch {
return false
}
if (url.protocol !== "http:") return false
if (isLoopbackHost(url.hostname)) return options.infer_loopback
return true
}
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)
const options = {
infer_providers: configured.infer_providers !== false,
infer_loopback: configured.infer_loopback === true,
}
// Infer agent endpoints from OpenCode providers that point at an Ollama server.
const inferred = []
if (options.infer_providers) {
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))
// V2 `providers` wins over the deprecated `provider` block; both may exist.
const providers = Object.entries({ ...(config?.provider || {}), ...(config?.providers || {}) })
for (const [id, provider] of providers) {
const baseURL = providerBaseURL(provider)
const explicitAgent = providerAgentURL(provider)
if (!baseURL && !explicitAgent) continue
const host = hostOf(explicitAgent) || hostOf(baseURL)
if (!host) continue
if (!explicitAgent && !looksLikeSwapHost(baseURL, options)) continue
if (controls.some((item) => hostOf(item.agent_url) === host || item.host === host)) continue
if (inferred.some((item) => item.host === host)) continue
inferred.push({
name: provider?.name || id || host,
host,
agent_url: explicitAgent || "http://" + host + ":8731",
token,
ollama_base_url: baseURL ? baseURL.replace(/\/v1\/?$/, "") : null,
inferred: true,
})
}
} catch {
// OpenCode config is optional; explicit clients.json is enough.
}
}
return { controls: [...controls, ...inferred], 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) {
const hint = control.inferred ? " — inferred from opencode config; set infer_providers: false in clients.json to silence" : ""
logLine("warn", "agent unreachable: " + control.name + " (" + String(error) + ")" + hint, {
control: control.name,
inferred: Boolean(control.inferred),
})
}
}
}
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