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@aa71865

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • client/src/promise/generated
      • types.ts
    • core
      • src/plugin
        • internal.ts
        • provider
          • openai-compatible.ts
      • test/plugin
        • provider-openai-compatible.test.ts
    • protocol
      • openapi.json
    • schema/src/config
      • flag.ts
  • services/site/src/docs/content
    • config.mdx
    • providers.mdx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/client/src/promise/generated/types.ts‎

Copy file name to clipboardExpand all lines: packages/client/src/promise/generated/types.ts
+1Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
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
@@ -110,6 +110,7 @@ import { McpCodeModeDefaultsPlugin } from "./mcp-codemode-defaults.js"
110110
import { ProviderPlugins } from "./provider.js"
111111
import { DynamicProviderPlugin } from "./provider/dynamic.js"
112112
import { OpencodePlugin } from "./provider/opencode.js"
113+
import { OpenAICompatiblePlugin } from "./provider/openai-compatible.js"
113114
import { WebSearchPlugins } from "./websearch/index.js"
114115
import { SkillPlugin } from "./skill.js"
115116
import { VcsHgPlugin } from "./vcs/hg.js"
@@ -305,6 +306,8 @@ const post = [
305306
ConfigProviderPlugin.Plugin,
306307
// Run the dynamic npm SDK loader after SDK, instance, and external plugins register their `sdk` hooks.
307308
DynamicProviderPlugin,
309+
// Fills configured providers with discovered models, so it must see their config applied first.
310+
OpenAICompatiblePlugin,
308311
ConfigWebSearchPlugin.Plugin,
309312
ConfigPolicyPlugin.Plugin,
310313
] as const satisfies readonly InternalPlugin[]
Collapse file

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

Copy file name to clipboard
+178Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
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.Service
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.resolve(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+
}

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.