From 87be6660fbbe0c81a904d37157c0ab9735d28bc5 Mon Sep 17 00:00:00 2001 From: Andrew Emelyaneko Date: Mon, 23 Nov 2026 21:04:21 +0300 Subject: [PATCH] Support OpenCode 2.x providers block and quiet provider inference --- README.md | 46 +++++++++++- clients.example.json | 2 + examples/opencode/ollama-swap.js | 123 +++++++++++++++++++++++-------- examples/opencode/ollama-swap.ts | 112 +++++++++++++++++++++++++++- scripts/install-client.sh | 2 + 5 files changed, 248 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 2dc2b73..1e7365b 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ с `package.json` (см. ниже). - Агент предоставляет `GET /health`, `GET /status` и `POST /restart`. -Оба плагина написаны под **API плагинов OpenCode 2.x** (проверено на 2.2.5): экспортируют +Оба плагина написаны под **API плагинов OpenCode 2.x** (проверено на 2.4.1): экспортируют `export default { id, setup }` и возвращают cleanup-функцию. Плагины V1 API (`export const XPlugin = async (ctx) => ({...})`) в OpenCode 2.x не загружаются. @@ -37,6 +37,36 @@ OpenCode автоматически загружает все файлы пла Отредактируйте `clients.json` и укажите URL и токен удалённого агента Ollama. +### Автоопределение агентов из конфигурации OpenCode + +Если `controls` пуст или его нужно дополнить, плагин читает `opencode.json(c)` из каталога +проекта (`ctx.location.directory`) и создаёт контрол `http://:8731` для каждого провайдера +с `baseURL`. Поддерживаются обе формы конфигурации: + +- V2: `providers..settings.baseURL` +- устаревшая (deprecated в V2): `provider..options.baseURL` + +Правила, чтобы не засорять лог заведомо недоступными адресами: + +- берутся только провайдеры с `http://` адресом; публичные `https://`‑шлюзы пропускаются; +- loopback (`localhost`, `127.0.0.1`, `::1`) по умолчанию пропускается; +- явный адрес агента задаётся через `settings.agentURL` — тогда провайдер попадает в контролы + независимо от схемы и адреса `baseURL`. + +Всё это управляется двумя ключами в `clients.json`: + +```json +{ + "infer_providers": true, + "infer_loopback": false +} +``` + +`"infer_providers": false` полностью отключает автоопределение — остаются только записи из +`controls`. Явно прописанные контролы всегда имеют приоритет: если хост уже есть в `controls`, +он не дублируется. Строка `agent unreachable: … — inferred from opencode config` в логе означает, +что контрол создан автоматически. + ## Установка агента на сервере Ollama Подключитесь по SSH к серверу `10.8.0.62` под пользователем с правами администратора/root. Пример: @@ -182,10 +212,11 @@ OpenCode 2.x автоматически подключает глобальны именно на этом шаге выполняется первый опрос агента. `server.connected` плагинам в OpenCode 2.x не доставляется, поэтому старый триггер больше не используется. -Проверить загрузку: +Проверить загрузку (список `plugin list` показывает только package-плагины из конфигурации, поэтому +дополнительно смотрите API, которое видит все загруженные плагины и их состояние): ```sh -opencode plugin list +opencode api get /api/plugin | grep ollama-plagin-swap ``` Результат опроса пишется в файл `~/.local/state/ollama-plagin-swap/client.log` (фоновый сервис @@ -197,7 +228,14 @@ OpenCode направляет stdout в `/dev/null`, поэтому собств ``` При превышении порога уровень меняется на `[warn]`, при недоступном агенте пишется -`agent unreachable: ()`. +`agent unreachable: ()`. Если контрол был создан автоопределением, в строку +добавляется подсказка `— inferred from opencode config`. + +Плагин ставит интервал на процесс сервера, поэтому если запущено несколько серверов OpenCode +(например, `opencode serve --service` и отдельный `opencode serve`), каждый из них опрашивает +агентов независимо и в лог попадают две серии записей. Runtime-guard через +`Symbol.for("ollamaPlaginSwapStarted")` защищает только от повторной загрузки внутри одного +процесса. ### Установка TS-варианта с инструментами diff --git a/clients.example.json b/clients.example.json index cbe29ba..3fea434 100644 --- a/clients.example.json +++ b/clients.example.json @@ -1,5 +1,7 @@ { "interval_seconds": 60, + "infer_providers": true, + "infer_loopback": false, "controls": [ { "name": "ollama-mac-62", diff --git a/examples/opencode/ollama-swap.js b/examples/opencode/ollama-swap.js index 2280ab5..25e9b3e 100644 --- a/examples/opencode/ollama-swap.js +++ b/examples/opencode/ollama-swap.js @@ -77,41 +77,104 @@ function stripJsonComments(raw) { 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..settings.baseURL`. +// The deprecated 1.x shape used `provider..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) - - // 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. + const options = { + infer_providers: configured.infer_providers !== false, + infer_loopback: configured.infer_loopback === true, } - return { controls, interval_seconds: interval > 0 ? interval : 60 } + // 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) { @@ -167,8 +230,10 @@ async function pollOnce(controls) { ollama_busy: status?.ollama_busy ?? null, }) } catch (error) { - logLine("warn", "agent unreachable: " + control.name + " (" + String(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), }) } } diff --git a/examples/opencode/ollama-swap.ts b/examples/opencode/ollama-swap.ts index eeb8f1e..f7f4f3b 100644 --- a/examples/opencode/ollama-swap.ts +++ b/examples/opencode/ollama-swap.ts @@ -1,6 +1,7 @@ // 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" @@ -8,8 +9,11 @@ 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" @@ -33,14 +37,110 @@ async function logLine(level: "info" | "warn", message: string) { else console.log(`${SERVICE} ${line}`) } -async function controls(): Promise { +// 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 { const file = path.join(homedir(), ".config", "ollama-plagin-swap", "clients.json") + let configured: any = {} try { - const parsed = JSON.parse(await readFile(file, "utf8")) - return Array.isArray(parsed?.controls) ? parsed.controls : [] + 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..settings.baseURL` first, +// then the deprecated `provider..options.baseURL`. +async function inferFromProviders(baseDirectory?: string, configured: any = {}): Promise { + 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({ ...(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 { @@ -80,7 +180,10 @@ async function pollOnce() { summary(control, status), ) } catch (error) { - await logLine("warn", `agent unreachable: ${control.name} (${String(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}`) } } } @@ -94,6 +197,7 @@ const plugin: Plugin.Plugin = { async setup(ctx): Promise { 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. diff --git a/scripts/install-client.sh b/scripts/install-client.sh index 45f65dd..0660e3c 100755 --- a/scripts/install-client.sh +++ b/scripts/install-client.sh @@ -13,6 +13,8 @@ if [ ! -f "${CLIENT_CONFIG}" ]; then cat > "${CLIENT_CONFIG}" <<'JSON' { "interval_seconds": 60, + "infer_providers": true, + "infer_loopback": false, "controls": [ { "name": "ollama-remote",