GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(core): discover models for configured OpenAI-compatible providers · anomalyco/opencode@727c389

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/core
    • src/plugin
      • internal.ts
      • provider
        • openai-compatible.ts
    • test/plugin
      • provider-openai-compatible.test.ts
  • services/site/src/docs/content
    • providers.mdx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/plugin/internal.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/plugin/internal.ts
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ import { McpCodeModeDefaultsPlugin } from "./mcp-codemode-defaults.js"
108108
import { ProviderPlugins } from "./provider.js"
109109
import { DynamicProviderPlugin } from "./provider/dynamic.js"
110110
import { OpencodePlugin } from "./provider/opencode.js"
111+
import { OpenAICompatiblePlugin } from "./provider/openai-compatible.js"
111112
import { WebSearchPlugins } from "./websearch/index.js"
112113
import { SkillPlugin } from "./skill.js"
113114
import { VcsHgPlugin } from "./vcs/hg.js"
@@ -300,6 +301,8 @@ const post = [
300301
ConfigProviderPlugin.Plugin,
301302
// Run the dynamic npm SDK loader after SDK, instance, and external plugins register their `sdk` hooks.
302303
DynamicProviderPlugin,
304+
// Fills configured providers with discovered models, so it must see their config applied first.
305+
OpenAICompatiblePlugin,
303306
ConfigWebSearchPlugin.Plugin,
304307
ConfigPolicyPlugin.Plugin,
305308
] as const satisfies readonly InternalPlugin[]
Collapse file

‎packages/core/src/plugin/provider/openai-compatible.ts‎

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

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.