|
| 1 | +import { define } from "@opencode-ai/plugin/effect/plugin" |
| 2 | +import { Document, type Entry } from "@opencode-ai/schema/config" |
| 3 | +import { Duration, Effect, Schedule, Schema, Semaphore, Stream } from "effect" |
| 4 | +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" |
| 5 | +import { Config } from "../../config.js" |
| 6 | +import { Model } from "../../model.js" |
| 7 | +import { Provider } from "../../provider.js" |
| 8 | +import type { PluginInternal } from "../internal.js" |
| 9 | + |
| 10 | +const providerID = "vllm" |
| 11 | + |
| 12 | +const RemoteModel = Schema.Struct({ |
| 13 | + id: Schema.String, |
| 14 | + owned_by: Schema.String, |
| 15 | + max_model_len: Schema.NullOr(Schema.Int), |
| 16 | +}) |
| 17 | + |
| 18 | +const Response = Schema.Struct({ data: Schema.Array(RemoteModel) }) |
| 19 | +const discovery = new Map<string, { checked: number; apiKey?: string; models?: (typeof RemoteModel.Type)[] }>() |
| 20 | +const discoveryLock = Semaphore.makeUnsafe(1) |
| 21 | + |
| 22 | +export function make(origin = "http://127.0.0.1:8000", interval: Duration.Input = "30 seconds") { |
| 23 | + return define({ |
| 24 | + id: "opencode.provider.vllm", |
| 25 | + effect: Effect.fn(function* (ctx) { |
| 26 | + const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient) |
| 27 | + const config = yield* Config.Service |
| 28 | + const source = { current: configured(yield* config.entries(), origin) } |
| 29 | + const loaded = { models: [] as (typeof RemoteModel.Type)[], hash: "[]" } |
| 30 | + |
| 31 | + yield* ctx.integration.transform((integrations) => { |
| 32 | + if (loaded.models.length === 0) return |
| 33 | + integrations.remove(providerID) |
| 34 | + }) |
| 35 | + |
| 36 | + yield* ctx.catalog.transform((catalog) => { |
| 37 | + if (loaded.models.length === 0) return |
| 38 | + for (const model of catalog.provider.get(providerID)?.models.values() ?? []) { |
| 39 | + catalog.model.remove(providerID, model.id) |
| 40 | + } |
| 41 | + catalog.provider.update(providerID, (provider) => { |
| 42 | + provider.name = "vLLM" |
| 43 | + provider.package = "@opencode-ai/ai/providers/openai-compatible" |
| 44 | + provider.settings = { |
| 45 | + baseURL: source.current.baseURL, |
| 46 | + provider: providerID, |
| 47 | + apiKey: source.current.apiKey ?? "", |
| 48 | + } |
| 49 | + provider.integrationID = undefined |
| 50 | + provider.activation = "enabled" |
| 51 | + }) |
| 52 | + for (const item of loaded.models) { |
| 53 | + catalog.model.update(providerID, item.id, (model) => { |
| 54 | + model.modelID = Model.ID.make(item.id) |
| 55 | + model.name = item.id |
| 56 | + // Tool calling depends on vLLM server flags and parsers that model discovery does not report. |
| 57 | + model.capabilities = { tools: false, input: ["text"], output: ["text"] } |
| 58 | + model.limit = { context: item.max_model_len ?? 0, output: 0 } |
| 59 | + }) |
| 60 | + } |
| 61 | + }) |
| 62 | + |
| 63 | + const discover = Effect.fn("VLLMPlugin.discover")(function* () { |
| 64 | + const current = source.current |
| 65 | + if (!current.healthEndpoint || !current.modelsEndpoint) return undefined |
| 66 | + return yield* discoveryLock.withPermit( |
| 67 | + Effect.gen(function* () { |
| 68 | + const endpoint = `${current.healthEndpoint}\n${current.modelsEndpoint}` |
| 69 | + const cached = discovery.get(endpoint) |
| 70 | + if (cached && cached.apiKey === current.apiKey && Date.now() - cached.checked < Duration.toMillis(interval)) |
| 71 | + return { source: current, models: cached.models } |
| 72 | + discovery.set(endpoint, { |
| 73 | + checked: Date.now(), |
| 74 | + apiKey: current.apiKey, |
| 75 | + models: cached && cached.apiKey === current.apiKey ? cached.models : undefined, |
| 76 | + }) |
| 77 | + const request = (endpoint: string) => |
| 78 | + current.apiKey |
| 79 | + ? HttpClientRequest.get(endpoint).pipe( |
| 80 | + HttpClientRequest.acceptJson, |
| 81 | + HttpClientRequest.bearerToken(current.apiKey), |
| 82 | + ) |
| 83 | + : HttpClientRequest.get(endpoint).pipe(HttpClientRequest.acceptJson) |
| 84 | + yield* http.execute(request(current.healthEndpoint)).pipe(Effect.timeout("1 second")) |
| 85 | + const response = yield* http |
| 86 | + .execute(request(current.modelsEndpoint)) |
| 87 | + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(Response)), Effect.timeout("1 second")) |
| 88 | + const models = response.data |
| 89 | + .filter((model) => model.owned_by === providerID && model.id.length > 0) |
| 90 | + .toSorted((a, b) => a.id.localeCompare(b.id)) |
| 91 | + discovery.set(endpoint, { checked: Date.now(), apiKey: current.apiKey, models }) |
| 92 | + return { source: current, models } |
| 93 | + }), |
| 94 | + ) |
| 95 | + }) |
| 96 | + |
| 97 | + const refresh = Effect.fn("VLLMPlugin.refresh")(function* () { |
| 98 | + const result = yield* discover() |
| 99 | + if (!result?.models || result.source !== source.current) return |
| 100 | + const hash = JSON.stringify(result.models) |
| 101 | + if (hash === loaded.hash) return |
| 102 | + loaded.models = result.models |
| 103 | + loaded.hash = hash |
| 104 | + yield* ctx.integration.reload() |
| 105 | + yield* ctx.catalog.reload() |
| 106 | + }) |
| 107 | + |
| 108 | + // Keep the last successful inventory through transient outages instead of flickering model availability. |
| 109 | + yield* refresh().pipe(Effect.ignore, Effect.repeat(Schedule.spaced(interval)), Effect.forkScoped) |
| 110 | + const reload = Effect.fn("VLLMPlugin.reload")(function* () { |
| 111 | + const next = configured(yield* config.entries(), origin) |
| 112 | + if ( |
| 113 | + next.baseURL === source.current.baseURL && |
| 114 | + next.apiKey === source.current.apiKey && |
| 115 | + next.healthEndpoint === source.current.healthEndpoint && |
| 116 | + next.modelsEndpoint === source.current.modelsEndpoint |
| 117 | + ) |
| 118 | + return |
| 119 | + source.current = next |
| 120 | + loaded.models = [] |
| 121 | + loaded.hash = "[]" |
| 122 | + yield* ctx.integration.reload() |
| 123 | + yield* ctx.catalog.reload() |
| 124 | + yield* refresh().pipe(Effect.ignore) |
| 125 | + }) |
| 126 | + yield* ctx.event.subscribe().pipe( |
| 127 | + Stream.filter((event) => event.type === "config.updated"), |
| 128 | + Stream.runForEach(reload), |
| 129 | + Effect.forkScoped({ startImmediately: true }), |
| 130 | + ) |
| 131 | + }), |
| 132 | + } satisfies PluginInternal.InternalPlugin) |
| 133 | +} |
| 134 | + |
| 135 | +export const VLLMPlugin = make() |
| 136 | + |
| 137 | +function configured(entries: readonly Entry[], origin: string) { |
| 138 | + const settings = entries |
| 139 | + .filter((entry): entry is Document => entry.type === "document") |
| 140 | + .flatMap((entry) => { |
| 141 | + const settings = entry.info.providers?.[providerID]?.settings |
| 142 | + return settings ? [settings] : [] |
| 143 | + }) |
| 144 | + .reduce<Provider.Settings | undefined>((result, item) => Provider.mergeOverlay(result, item), undefined) |
| 145 | + const baseURL = ( |
| 146 | + typeof settings?.baseURL === "string" ? settings.baseURL : `${origin.replace(/\/+$/, "")}/v1` |
| 147 | + ).replace(/\/+$/, "") |
| 148 | + const apiKey = typeof settings?.apiKey === "string" ? settings.apiKey : undefined |
| 149 | + if (!URL.canParse(baseURL)) return { baseURL, apiKey } |
| 150 | + const models = new URL(baseURL) |
| 151 | + if (models.protocol !== "http:" && models.protocol !== "https:") return { baseURL, apiKey } |
| 152 | + models.pathname = `${models.pathname.replace(/\/+$/, "")}/models` |
| 153 | + models.search = "" |
| 154 | + models.hash = "" |
| 155 | + const health = new URL(baseURL) |
| 156 | + const path = health.pathname.replace(/\/+$/, "") |
| 157 | + const prefix = path.endsWith("/v1") ? path.slice(0, -3) : path |
| 158 | + health.pathname = `${prefix}/health` |
| 159 | + health.search = "" |
| 160 | + health.hash = "" |
| 161 | + return { baseURL, apiKey, healthEndpoint: health.toString(), modelsEndpoint: models.toString() } |
| 162 | +} |