|
| 1 | +import { define } from "@opencode/plugin/effect/plugin" |
| 2 | +import type { Document, Entry } from "@opencode/schema/config" |
| 3 | +import { type Duration, Effect, Schedule, Schema, Semaphore, Stream } from "effect" |
| 4 | +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http" |
| 5 | +import { Bus } from "../../bus.js" |
| 6 | +import { Config } from "../../config.js" |
| 7 | +import { Credential } from "../../credential.js" |
| 8 | +import { Flag } from "../../flag.js" |
| 9 | +import { Model } from "../../model.js" |
| 10 | +import { Provider } from "../../provider.js" |
| 11 | +import type { PluginInternal } from "../internal.js" |
| 12 | +import { foldSettings } from "./configured.js" |
| 13 | + |
| 14 | +const Strings = Schema.NullOr(Schema.Array(Schema.String)).pipe(Schema.optional) |
| 15 | + |
| 16 | +const RemoteModel = Schema.Struct({ |
| 17 | + id: Schema.String, |
| 18 | + mode: Schema.NullOr(Schema.String).pipe(Schema.optional), |
| 19 | + // Gateways report modalities at the top level or under `architecture`, as OpenRouter does. |
| 20 | + input_modalities: Strings, |
| 21 | + output_modalities: Strings, |
| 22 | + architecture: Schema.NullOr(Schema.Struct({ input_modalities: Strings, output_modalities: Strings })).pipe( |
| 23 | + Schema.optional, |
| 24 | + ), |
| 25 | + supported_parameters: Strings, |
| 26 | +}) |
| 27 | + |
| 28 | +const Models = Schema.Struct({ data: Schema.Array(RemoteModel) }) |
| 29 | + |
| 30 | +// Gateways such as LiteLLM also list embedding, image, and audio models. |
| 31 | +const chat = new Set(["chat", "responses"]) |
| 32 | + |
| 33 | +const packages = new Set(["@ai-sdk/openai-compatible", "@opencode/ai/providers/openai-compatible"]) |
| 34 | + |
| 35 | +// These providers have dedicated discovery plugins that own their whole model list. |
| 36 | +const dedicated = new Set(["ollama", "lmstudio", "vllm"]) |
| 37 | + |
| 38 | +type Target = ReturnType<typeof targets>[number] |
| 39 | + |
| 40 | +export function make(interval: Duration.Input = "5 minutes") { |
| 41 | + return define({ |
| 42 | + id: "opencode.provider.openai-compatible", |
| 43 | + effect: Effect.fn(function* (ctx) { |
| 44 | + const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient) |
| 45 | + const bus = yield* Bus.Service |
| 46 | + const config = yield* Config.Service |
| 47 | + const flags = yield* Flag.resolver |
| 48 | + const loading = Semaphore.makeUnsafe(1) |
| 49 | + const loaded = { |
| 50 | + inventory: new Map< |
| 51 | + Provider.ID, |
| 52 | + { source: string; models: readonly { id: string; capabilities: Model.Capabilities }[] } |
| 53 | + >(), |
| 54 | + hash: "[]", |
| 55 | + } |
| 56 | + |
| 57 | + yield* ctx.provider.transform((providers) => { |
| 58 | + for (const [providerID, item] of loaded.inventory) { |
| 59 | + const provider = providers.get(providerID) |
| 60 | + if (!provider) continue |
| 61 | + for (const model of item.models) { |
| 62 | + // Configured models keep their own capabilities. |
| 63 | + if (provider.models.has(Model.ID.make(model.id))) continue |
| 64 | + providers.models.update(providerID, model.id, (draft) => { |
| 65 | + draft.capabilities = { |
| 66 | + tools: model.capabilities.tools, |
| 67 | + input: [...model.capabilities.input], |
| 68 | + output: [...model.capabilities.output], |
| 69 | + } |
| 70 | + }) |
| 71 | + } |
| 72 | + } |
| 73 | + }) |
| 74 | + |
| 75 | + const inventory = Effect.fnUntraced(function* (target: Target) { |
| 76 | + const connection = yield* ctx.integration.connection.active(target.providerID) |
| 77 | + const credential = connection |
| 78 | + ? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined)) |
| 79 | + : undefined |
| 80 | + // Same precedence as requests: a stored key replaces the configured one. |
| 81 | + const apiKey = credential?.type === "key" ? credential.key : target.apiKey |
| 82 | + const source = JSON.stringify([target.baseURL, apiKey, target.headers]) |
| 83 | + const previous = loaded.inventory.get(target.providerID) |
| 84 | + const request = HttpClientRequest.get(`${target.baseURL}/models`).pipe( |
| 85 | + HttpClientRequest.acceptJson, |
| 86 | + HttpClientRequest.setHeaders(target.headers ?? {}), |
| 87 | + ) |
| 88 | + const models = yield* http.execute(apiKey ? request.pipe(HttpClientRequest.bearerToken(apiKey)) : request).pipe( |
| 89 | + Effect.flatMap(HttpClientResponse.schemaBodyJson(Models)), |
| 90 | + Effect.timeout("5 seconds"), |
| 91 | + Effect.map((response) => |
| 92 | + response.data |
| 93 | + .filter((model) => model.id.length > 0 && (!model.mode || chat.has(model.mode))) |
| 94 | + .map((model) => ({ id: model.id, capabilities: capabilities(model) })) |
| 95 | + .toSorted((a, b) => a.id.localeCompare(b.id)), |
| 96 | + ), |
| 97 | + // Log the message only: the request in the cause carries configured headers, which may hold secrets. |
| 98 | + Effect.tapError((error) => |
| 99 | + Effect.logDebug("openai-compatible model discovery failed", { |
| 100 | + providerID: target.providerID, |
| 101 | + message: error.message, |
| 102 | + }), |
| 103 | + ), |
| 104 | + // Keep the last successful inventory through transient outages while the endpoint and key are unchanged. |
| 105 | + Effect.orElseSucceed(() => (previous?.source === source ? previous.models : undefined)), |
| 106 | + ) |
| 107 | + return models === undefined ? [] : [[target.providerID, { source, models }] as const] |
| 108 | + }) |
| 109 | + |
| 110 | + const load = Effect.fn("OpenAICompatiblePlugin.load")(function* () { |
| 111 | + const entries = yield* config.entries() |
| 112 | + // Internal plugins are not re-run on config changes, so read the flag on every refresh; turning it off drops |
| 113 | + // the discovered models. |
| 114 | + const results = flags(entries).openai_compatible_discovery.enabled |
| 115 | + ? yield* Effect.forEach(targets(entries), inventory, { concurrency: 4 }) |
| 116 | + : [] |
| 117 | + const next = new Map(results.flat()) |
| 118 | + const hash = JSON.stringify([...next]) |
| 119 | + if (hash === loaded.hash) return |
| 120 | + loaded.inventory = next |
| 121 | + loaded.hash = hash |
| 122 | + yield* ctx.provider.reload() |
| 123 | + }) |
| 124 | + const refresh = () => loading.withPermit(load()) |
| 125 | + |
| 126 | + yield* ctx.event.subscribe().pipe( |
| 127 | + Stream.filter((event) => event.type === "config.updated"), |
| 128 | + Stream.runForEach(refresh), |
| 129 | + Effect.forkScoped({ startImmediately: true }), |
| 130 | + ) |
| 131 | + yield* bus.subscribe(Credential.Event.Switched).pipe( |
| 132 | + Stream.runForEach(refresh), |
| 133 | + Effect.forkScoped({ startImmediately: true }), |
| 134 | + ) |
| 135 | + yield* refresh().pipe(Effect.ignore, Effect.repeat(Schedule.spaced(interval)), Effect.forkScoped) |
| 136 | + }), |
| 137 | + } satisfies PluginInternal.InternalPlugin) |
| 138 | +} |
| 139 | + |
| 140 | +export const OpenAICompatiblePlugin = make() |
| 141 | + |
| 142 | +function targets(entries: readonly Entry[]) { |
| 143 | + const documents = entries.filter((entry): entry is Document => entry.type === "document") |
| 144 | + const ids = new Set(documents.flatMap((file) => Object.keys(file.info.providers ?? {}))) |
| 145 | + return [...ids].flatMap((id) => { |
| 146 | + if (dedicated.has(id)) return [] |
| 147 | + const configured = documents.flatMap((file) => file.info.providers?.[id] ?? []) |
| 148 | + const pkg = configured.findLast((item) => item.package !== undefined)?.package |
| 149 | + // Migrated V1 configs store the package as `aisdk:@ai-sdk/openai-compatible`. |
| 150 | + if (pkg === undefined || !packages.has(Provider.packageName(pkg))) return [] |
| 151 | + const settings = foldSettings(entries, id, undefined) |
| 152 | + const baseURL = typeof settings?.baseURL === "string" ? settings.baseURL.replace(/\/+$/, "") : "" |
| 153 | + if (!URL.canParse(baseURL) || !["http:", "https:"].includes(new URL(baseURL).protocol)) return [] |
| 154 | + return [ |
| 155 | + { |
| 156 | + providerID: Provider.ID.make(id), |
| 157 | + baseURL, |
| 158 | + apiKey: typeof settings?.apiKey === "string" && settings.apiKey !== "" ? settings.apiKey : undefined, |
| 159 | + headers: configured.reduce( |
| 160 | + (headers: Record<string, string> | undefined, item) => Provider.mergeHeaders(headers, item.headers), |
| 161 | + undefined, |
| 162 | + ), |
| 163 | + }, |
| 164 | + ] |
| 165 | + }) |
| 166 | +} |
| 167 | + |
| 168 | +// Without metadata, assume text-only input: an image sent to a text-only model fails every later request in the |
| 169 | +// session, while a missing image capability only blocks attachments. |
| 170 | +function capabilities(model: typeof RemoteModel.Type): Model.Capabilities { |
| 171 | + const input = model.input_modalities ?? model.architecture?.input_modalities ?? ["text"] |
| 172 | + return { |
| 173 | + tools: model.supported_parameters?.includes("tools") ?? true, |
| 174 | + // OpenRouter calls PDF input `file`. |
| 175 | + input: input.map((modality) => (modality === "file" ? "pdf" : modality)), |
| 176 | + output: model.output_modalities ?? model.architecture?.output_modalities ?? ["text"], |
| 177 | + } |
| 178 | +} |