|
| 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 = "ollama" |
| 11 | + |
| 12 | +const Details = Schema.Struct({ |
| 13 | + parent_model: Schema.String.pipe(Schema.optional), |
| 14 | + format: Schema.String, |
| 15 | + family: Schema.String, |
| 16 | + families: Schema.Array(Schema.String).pipe(Schema.optional), |
| 17 | + parameter_size: Schema.String, |
| 18 | + quantization_level: Schema.String, |
| 19 | +}) |
| 20 | + |
| 21 | +const RemoteModel = Schema.Struct({ |
| 22 | + name: Schema.String, |
| 23 | + model: Schema.String, |
| 24 | + remote_model: Schema.String.pipe(Schema.optional), |
| 25 | + remote_host: Schema.String.pipe(Schema.optional), |
| 26 | + modified_at: Schema.String, |
| 27 | + size: Schema.Int, |
| 28 | + digest: Schema.String, |
| 29 | + details: Details, |
| 30 | +}) |
| 31 | + |
| 32 | +const TagsResponse = Schema.Struct({ models: Schema.Array(RemoteModel) }) |
| 33 | +const ShowRequest = Schema.Struct({ model: Schema.String }) |
| 34 | +const ShowResponse = Schema.Struct({ |
| 35 | + parameters: Schema.String.pipe(Schema.optional), |
| 36 | + license: Schema.String.pipe(Schema.optional), |
| 37 | + modified_at: Schema.String.pipe(Schema.optional), |
| 38 | + details: Details.pipe(Schema.optional), |
| 39 | + template: Schema.String.pipe(Schema.optional), |
| 40 | + capabilities: Schema.Array(Schema.String).pipe(Schema.optional), |
| 41 | + model_info: Schema.Record(Schema.String, Schema.Unknown).pipe(Schema.optional), |
| 42 | +}) |
| 43 | + |
| 44 | +type DiscoveredModel = typeof RemoteModel.Type & { show: typeof ShowResponse.Type } |
| 45 | +type Discovery = { |
| 46 | + checked: number |
| 47 | + apiKey?: string |
| 48 | + models?: DiscoveredModel[] |
| 49 | + shows: Map<string, { digest: string; info: typeof ShowResponse.Type }> |
| 50 | +} |
| 51 | + |
| 52 | +const discovery = new Map<string, Discovery>() |
| 53 | +const discoveryLock = Semaphore.makeUnsafe(1) |
| 54 | + |
| 55 | +export function make(origin = "http://127.0.0.1:11434", interval: Duration.Input = "30 seconds") { |
| 56 | + return define({ |
| 57 | + id: "opencode.provider.ollama", |
| 58 | + effect: Effect.fn(function* (ctx) { |
| 59 | + const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient) |
| 60 | + const config = yield* Config.Service |
| 61 | + const source = { current: configured(yield* config.entries(), origin) } |
| 62 | + const loaded = { models: [] as DiscoveredModel[], hash: "[]" } |
| 63 | + |
| 64 | + yield* ctx.integration.transform((integrations) => { |
| 65 | + if (loaded.models.length === 0) return |
| 66 | + integrations.remove(providerID) |
| 67 | + }) |
| 68 | + |
| 69 | + yield* ctx.catalog.transform((catalog) => { |
| 70 | + if (loaded.models.length === 0) return |
| 71 | + for (const model of catalog.provider.get(providerID)?.models.values() ?? []) { |
| 72 | + catalog.model.remove(providerID, model.id) |
| 73 | + } |
| 74 | + catalog.provider.update(providerID, (provider) => { |
| 75 | + provider.name = "Ollama" |
| 76 | + provider.activation = "enabled" |
| 77 | + provider.package = "@opencode-ai/ai/providers/openai-compatible" |
| 78 | + provider.settings = { |
| 79 | + baseURL: source.current.baseURL, |
| 80 | + provider: providerID, |
| 81 | + apiKey: source.current.apiKey ?? "", |
| 82 | + } |
| 83 | + provider.integrationID = undefined |
| 84 | + }) |
| 85 | + for (const item of loaded.models) { |
| 86 | + catalog.model.update(providerID, item.model, (model) => { |
| 87 | + model.modelID = Model.ID.make(item.model) |
| 88 | + model.name = item.name || item.model |
| 89 | + model.family = item.show.details?.family |
| 90 | + ? Model.Family.make(item.show.details.family) |
| 91 | + : item.details.family |
| 92 | + ? Model.Family.make(item.details.family) |
| 93 | + : undefined |
| 94 | + model.capabilities = { |
| 95 | + tools: item.show.capabilities?.includes("tools") ?? false, |
| 96 | + input: ["text", ...(item.show.capabilities?.includes("vision") ? ["image"] : [])], |
| 97 | + output: ["text"], |
| 98 | + } |
| 99 | + model.limit = { |
| 100 | + context: |
| 101 | + Object.entries(item.show.model_info ?? {}).flatMap(([key, value]) => |
| 102 | + key.endsWith(".context_length") && typeof value === "number" && value > 0 ? [value] : [], |
| 103 | + )[0] ?? 0, |
| 104 | + output: 0, |
| 105 | + } |
| 106 | + }) |
| 107 | + } |
| 108 | + }) |
| 109 | + |
| 110 | + const discover = Effect.fn("OllamaPlugin.discover")(function* () { |
| 111 | + const current = source.current |
| 112 | + if (!current.tagsEndpoint || !current.showEndpoint) return undefined |
| 113 | + return yield* discoveryLock.withPermit( |
| 114 | + Effect.gen(function* () { |
| 115 | + const cached = discovery.get(current.tagsEndpoint) |
| 116 | + if (cached && cached.apiKey === current.apiKey && Date.now() - cached.checked < Duration.toMillis(interval)) |
| 117 | + return { source: current, models: cached.models } |
| 118 | + const previous: Discovery = |
| 119 | + cached && cached.apiKey === current.apiKey |
| 120 | + ? cached |
| 121 | + : { checked: 0, apiKey: current.apiKey, shows: new Map() } |
| 122 | + discovery.set(current.tagsEndpoint, { ...previous, checked: Date.now(), apiKey: current.apiKey }) |
| 123 | + const tagsRequest = current.apiKey |
| 124 | + ? HttpClientRequest.get(current.tagsEndpoint).pipe( |
| 125 | + HttpClientRequest.acceptJson, |
| 126 | + HttpClientRequest.bearerToken(current.apiKey), |
| 127 | + ) |
| 128 | + : HttpClientRequest.get(current.tagsEndpoint).pipe(HttpClientRequest.acceptJson) |
| 129 | + const response = yield* http |
| 130 | + .execute(tagsRequest) |
| 131 | + .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(TagsResponse)), Effect.timeout("1 second")) |
| 132 | + const summaries = response.models |
| 133 | + .filter((model) => model.model.length > 0) |
| 134 | + .toSorted((a, b) => a.model.localeCompare(b.model)) |
| 135 | + const shows = new Map<string, { digest: string; info: typeof ShowResponse.Type }>() |
| 136 | + const models = yield* Effect.forEach( |
| 137 | + summaries, |
| 138 | + (model) => |
| 139 | + Effect.gen(function* () { |
| 140 | + const saved = previous.shows.get(model.model) |
| 141 | + const info = |
| 142 | + saved?.digest === model.digest |
| 143 | + ? saved.info |
| 144 | + : yield* HttpClientRequest.post(current.showEndpoint).pipe( |
| 145 | + HttpClientRequest.acceptJson, |
| 146 | + current.apiKey ? HttpClientRequest.bearerToken(current.apiKey) : (request) => request, |
| 147 | + HttpClientRequest.schemaBodyJson(ShowRequest)({ model: model.model }), |
| 148 | + Effect.flatMap(http.execute), |
| 149 | + Effect.flatMap(HttpClientResponse.schemaBodyJson(ShowResponse)), |
| 150 | + Effect.timeout("1 second"), |
| 151 | + ) |
| 152 | + shows.set(model.model, { digest: model.digest, info }) |
| 153 | + return { ...model, show: info } |
| 154 | + }).pipe(Effect.catch(() => Effect.succeed(undefined))), |
| 155 | + { concurrency: 4 }, |
| 156 | + ) |
| 157 | + const filtered = models.filter( |
| 158 | + (model): model is DiscoveredModel => |
| 159 | + model !== undefined && (model.show.capabilities?.includes("completion") ?? false), |
| 160 | + ) |
| 161 | + discovery.set(current.tagsEndpoint, { |
| 162 | + checked: Date.now(), |
| 163 | + apiKey: current.apiKey, |
| 164 | + models: filtered, |
| 165 | + shows, |
| 166 | + }) |
| 167 | + return { source: current, models: filtered } |
| 168 | + }), |
| 169 | + ) |
| 170 | + }) |
| 171 | + |
| 172 | + const refresh = Effect.fn("OllamaPlugin.refresh")(function* () { |
| 173 | + const result = yield* discover() |
| 174 | + if (!result?.models || result.source !== source.current) return |
| 175 | + const hash = JSON.stringify(result.models) |
| 176 | + if (hash === loaded.hash) return |
| 177 | + loaded.models = result.models |
| 178 | + loaded.hash = hash |
| 179 | + yield* ctx.integration.reload() |
| 180 | + yield* ctx.catalog.reload() |
| 181 | + }) |
| 182 | + |
| 183 | + // Keep the last successful inventory through transient outages instead of flickering model availability. |
| 184 | + yield* refresh().pipe(Effect.ignore, Effect.repeat(Schedule.spaced(interval)), Effect.forkScoped) |
| 185 | + const reload = Effect.fn("OllamaPlugin.reload")(function* () { |
| 186 | + const next = configured(yield* config.entries(), origin) |
| 187 | + if ( |
| 188 | + next.baseURL === source.current.baseURL && |
| 189 | + next.apiKey === source.current.apiKey && |
| 190 | + next.tagsEndpoint === source.current.tagsEndpoint |
| 191 | + ) |
| 192 | + return |
| 193 | + source.current = next |
| 194 | + loaded.models = [] |
| 195 | + loaded.hash = "[]" |
| 196 | + yield* ctx.integration.reload() |
| 197 | + yield* ctx.catalog.reload() |
| 198 | + yield* refresh().pipe(Effect.ignore) |
| 199 | + }) |
| 200 | + yield* ctx.event.subscribe().pipe( |
| 201 | + Stream.filter((event) => event.type === "config.updated"), |
| 202 | + Stream.runForEach(reload), |
| 203 | + Effect.forkScoped({ startImmediately: true }), |
| 204 | + ) |
| 205 | + }), |
| 206 | + } satisfies PluginInternal.InternalPlugin) |
| 207 | +} |
| 208 | + |
| 209 | +export const OllamaPlugin = make() |
| 210 | + |
| 211 | +function configured(entries: readonly Entry[], origin: string) { |
| 212 | + const settings = entries |
| 213 | + .filter((entry): entry is Document => entry.type === "document") |
| 214 | + .flatMap((entry) => { |
| 215 | + const settings = entry.info.providers?.[providerID]?.settings |
| 216 | + return settings ? [settings] : [] |
| 217 | + }) |
| 218 | + .reduce<Provider.Settings | undefined>((result, item) => Provider.mergeOverlay(result, item), undefined) |
| 219 | + const baseURL = ( |
| 220 | + typeof settings?.baseURL === "string" ? settings.baseURL : `${origin.replace(/\/+$/, "")}/v1` |
| 221 | + ).replace(/\/+$/, "") |
| 222 | + const apiKey = typeof settings?.apiKey === "string" ? settings.apiKey : undefined |
| 223 | + if (!URL.canParse(baseURL)) return { baseURL, apiKey } |
| 224 | + const url = new URL(baseURL) |
| 225 | + if (url.protocol !== "http:" && url.protocol !== "https:") return { baseURL, apiKey } |
| 226 | + const prefix = url.pathname.endsWith("/v1") ? url.pathname.slice(0, -3) : url.pathname.replace(/\/+$/, "") |
| 227 | + url.pathname = `${prefix}/api/tags` |
| 228 | + url.search = "" |
| 229 | + url.hash = "" |
| 230 | + const tagsEndpoint = url.toString() |
| 231 | + url.pathname = `${prefix}/api/show` |
| 232 | + return { baseURL, apiKey, tagsEndpoint, showEndpoint: url.toString() } |
| 233 | +} |