opencode-openai-compatible-discovery 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -23
- package/adapters.ts +8 -20
- package/configuration.ts +61 -0
- package/discovery.ts +51 -9
- package/index.ts +5 -104
- package/package.json +3 -3
- package/publication.ts +81 -0
- package/registry.ts +16 -33
- package/inventory.ts +0 -54
- package/lifecycle.ts +0 -41
package/README.md
CHANGED
|
@@ -33,26 +33,31 @@ Then configure the endpoint in `~/.config/opencode/opencode.jsonc`:
|
|
|
33
33
|
}
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
| Option
|
|
37
|
-
|
|
|
38
|
-
| `baseURL`
|
|
39
|
-
| `apiKey`
|
|
40
|
-
| `providerID`
|
|
41
|
-
| `providerName`
|
|
42
|
-
| `
|
|
43
|
-
| `
|
|
44
|
-
| `
|
|
36
|
+
| Option | Default | Description |
|
|
37
|
+
| --------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
38
|
+
| `baseURL` | None (required per provider) | Base URL of the OpenAI-compatible API, including `/v1` if required by the endpoint. |
|
|
39
|
+
| `apiKey` | None | Optional bearer token for inventory requests. |
|
|
40
|
+
| `providerID` | `local` | Unique provider ID and model prefix (`<providerID>/<model-id>`). |
|
|
41
|
+
| `providerName` | `Local` for `local`; otherwise the `providerID` | Display name for a new provider. An existing name is preserved unless explicitly overridden. |
|
|
42
|
+
| `includeModels` | All discoverable chat models | Optional list of exact model IDs to discover for this provider. |
|
|
43
|
+
| `refreshMs` | `60000` (60 seconds) | Wait after a discovery pass finishes before starting the next one. |
|
|
44
|
+
| `timeoutMs` | `3000` (3 seconds) | Timeout per discovery HTTP request, including requests to enrich metadata. |
|
|
45
|
+
| `providers` | None | Optional array of provider configurations; available only at the top level of `options`. |
|
|
45
46
|
|
|
46
47
|
The endpoint should return OpenAI-compatible model records from `GET <baseURL>/models`. Temporary discovery failures
|
|
47
48
|
keep the last successfully published inventory. Tool calling defaults to enabled when the inventory does not specify
|
|
48
49
|
support; an endpoint can set `capabilities.tools: false` on a model to disable it.
|
|
49
50
|
|
|
51
|
+
Use `includeModels` to limit which models from a shared endpoint appear in OpenCode. IDs are case-sensitive and
|
|
52
|
+
match the `id` returned by `/models`, without an added provider prefix. An empty list discovers no models and leaves
|
|
53
|
+
manually configured models alone. The filter applies on startup and on every refresh.
|
|
54
|
+
|
|
50
55
|
Both `refreshMs` and `timeoutMs` must be integers in milliseconds from `1` to `2147483647`. The first discovery pass
|
|
51
56
|
runs immediately.
|
|
52
57
|
|
|
53
58
|
For multiple endpoints, configure one plugin entry with a `providers` array. Use a unique `providerID` for each
|
|
54
|
-
endpoint. If you also keep the top-level `baseURL`, it configures one additional provider. The top-level
|
|
55
|
-
options apply only to that provider; entries in `providers` use their own values or the defaults.
|
|
59
|
+
endpoint. If you also keep the top-level `baseURL`, it configures one additional provider. The top-level filter and
|
|
60
|
+
timing options apply only to that provider; entries in `providers` use their own values or the defaults.
|
|
56
61
|
|
|
57
62
|
```jsonc
|
|
58
63
|
{
|
|
@@ -71,6 +76,7 @@ options apply only to that provider; entries in `providers` use their own values
|
|
|
71
76
|
"providerName": "Team models",
|
|
72
77
|
"baseURL": "https://llm.example.com/v1",
|
|
73
78
|
"apiKey": "{env:TEAM_LLM_API_KEY}",
|
|
79
|
+
"includeModels": ["team/general-chat", "team/coding"],
|
|
74
80
|
"refreshMs": 120000,
|
|
75
81
|
"timeoutMs": 10000
|
|
76
82
|
}
|
|
@@ -90,7 +96,7 @@ use `opencode-openai-compatible-discovery@0.1.0` to pin the first release once p
|
|
|
90
96
|
bun install --frozen-lockfile
|
|
91
97
|
pre-commit run --all-files
|
|
92
98
|
bun test
|
|
93
|
-
|
|
99
|
+
npm pack
|
|
94
100
|
bun run test:package ./opencode-openai-compatible-discovery-0.1.0.tgz
|
|
95
101
|
```
|
|
96
102
|
|
|
@@ -106,21 +112,18 @@ Commits](https://www.conventionalcommits.org/) for commit messages and PR titles
|
|
|
106
112
|
Use `feat`, `fix`, `perf`, or `revert` for changes to the published plugin; these trigger a patch release. CI-only
|
|
107
113
|
(`ci`), documentation (`docs`), test-only (`test`), and maintenance (`chore`) changes do not bump the version.
|
|
108
114
|
If several merges land before a release runs, semantic-release can publish them together from the latest `main` commit.
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
115
|
+
Semantic-release creates the version tag, publishes via npm Trusted Publishing, and creates the GitHub release.
|
|
116
|
+
Tests and the smoke check run on the PR. Semantic-release updates the package version for publishing without committing
|
|
117
|
+
a version bump. Update dependencies manually when needed; `bun audit` checks the Bun lockfile, including transitive
|
|
118
|
+
dependencies.
|
|
119
|
+
|
|
120
|
+
The original `v0.1.0` GitHub release already records the first npm publication and is the versioning baseline.
|
|
113
121
|
|
|
114
122
|
### One-time setup
|
|
115
123
|
|
|
116
124
|
1. Protect `main` with a required PR and the `Validate package` status check from GitHub Actions. Require branches to be
|
|
117
|
-
up to date before merging and disallow bypasses.
|
|
118
|
-
|
|
119
|
-
2. With the variable still unset, run **Actions → Release → Run workflow** on `main`. This only
|
|
120
|
-
builds the `npm-package` artifact. Download and unpack it, then publish the tarball once with an authenticated npm
|
|
121
|
-
account and 2FA: `npm publish ./opencode-openai-compatible-discovery-0.1.0.tgz --access public`. Create the GitHub
|
|
122
|
-
release `v0.1.0` on the exact commit used by that workflow run to establish the starting version.
|
|
123
|
-
3. Use the GitHub environment `npm`, restricted to `main` and without required reviewers. In the npm package's
|
|
125
|
+
up to date before merging and disallow bypasses.
|
|
126
|
+
2. Use the GitHub environment `npm`, restricted to `main` and without required reviewers. In the npm package's
|
|
124
127
|
[Trusted Publishing settings](https://docs.npmjs.com/trusted-publishers/), authorize this repository's `release.yml`
|
|
125
128
|
workflow and the `npm` environment, with permission for `npm publish`. Set `NPM_RELEASES_ENABLED=true` once ready,
|
|
126
129
|
and publish the next version within two days to validate the trusted publisher configuration.
|
package/adapters.ts
CHANGED
|
@@ -35,17 +35,14 @@ export interface NormalizedModelMetadata {
|
|
|
35
35
|
|
|
36
36
|
export type JSONResult = { available: true; data: unknown; headers: Headers } | { available: false; reason: string }
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
interface AdapterFetchContext {
|
|
39
39
|
baseURL: string
|
|
40
|
-
headers: Headers
|
|
41
40
|
loadJSON: (url: string) => Promise<JSONResult>
|
|
42
41
|
}
|
|
43
42
|
|
|
44
|
-
|
|
45
|
-
readonly name: string
|
|
43
|
+
interface ModelMetadataAdapter {
|
|
46
44
|
matches(entries: readonly RawModelEntry[], headers: Headers): boolean
|
|
47
|
-
|
|
48
|
-
enrich?(
|
|
45
|
+
enrich(
|
|
49
46
|
entries: readonly RawModelEntry[],
|
|
50
47
|
ctx: AdapterFetchContext,
|
|
51
48
|
): Promise<ReadonlyMap<string, NormalizedModelMetadata>>
|
|
@@ -59,7 +56,7 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
59
56
|
return typeof value === "object" && value !== null
|
|
60
57
|
}
|
|
61
58
|
|
|
62
|
-
|
|
59
|
+
function positiveInteger(...values: unknown[]): number | undefined {
|
|
63
60
|
for (const value of values) {
|
|
64
61
|
if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return value
|
|
65
62
|
}
|
|
@@ -83,7 +80,7 @@ function readInputModalities(entry: RawModelEntry): string[] | undefined {
|
|
|
83
80
|
return stringArray(entry.input_modalities) ?? stringArray(entry.architecture?.input_modalities)
|
|
84
81
|
}
|
|
85
82
|
|
|
86
|
-
function extractInlineMetadata(entry: RawModelEntry): NormalizedModelMetadata {
|
|
83
|
+
export function extractInlineMetadata(entry: RawModelEntry): NormalizedModelMetadata {
|
|
87
84
|
const metadata: NormalizedModelMetadata = {}
|
|
88
85
|
|
|
89
86
|
const modalities = readInputModalities(entry)
|
|
@@ -145,12 +142,6 @@ function extractInlineMetadata(entry: RawModelEntry): NormalizedModelMetadata {
|
|
|
145
142
|
return metadata
|
|
146
143
|
}
|
|
147
144
|
|
|
148
|
-
export const genericAdapter: ModelMetadataAdapter = {
|
|
149
|
-
name: "generic",
|
|
150
|
-
matches: () => true,
|
|
151
|
-
extract: extractInlineMetadata,
|
|
152
|
-
}
|
|
153
|
-
|
|
154
145
|
interface RawOmlxStatusModel {
|
|
155
146
|
id?: unknown
|
|
156
147
|
model_alias?: unknown
|
|
@@ -198,8 +189,7 @@ function omlxStatusReasoning(status: RawOmlxStatusModel | undefined): string[] {
|
|
|
198
189
|
return [...DEFAULT_EFFORTS]
|
|
199
190
|
}
|
|
200
191
|
|
|
201
|
-
|
|
202
|
-
name: "omlx",
|
|
192
|
+
const omlxAdapter: ModelMetadataAdapter = {
|
|
203
193
|
matches(entries, headers) {
|
|
204
194
|
const server = `${headers.get("server") ?? ""} ${headers.get("x-powered-by") ?? ""}`.toLowerCase()
|
|
205
195
|
return server.includes("omlx") || entries.some((entry) => entry?.owned_by === "omlx")
|
|
@@ -301,8 +291,7 @@ function parseLmStudioModels(data: unknown): Map<string, NormalizedModelMetadata
|
|
|
301
291
|
return enriched
|
|
302
292
|
}
|
|
303
293
|
|
|
304
|
-
|
|
305
|
-
name: "lm-studio",
|
|
294
|
+
const lmStudioAdapter: ModelMetadataAdapter = {
|
|
306
295
|
matches(entries, headers) {
|
|
307
296
|
const server = `${headers.get("server") ?? ""} ${headers.get("x-powered-by") ?? ""}`.toLowerCase()
|
|
308
297
|
if (server.includes("lm-studio") || server.includes("lm studio") || server.includes("lmstudio")) return true
|
|
@@ -328,8 +317,7 @@ export const lmStudioAdapter: ModelMetadataAdapter = {
|
|
|
328
317
|
},
|
|
329
318
|
}
|
|
330
319
|
|
|
331
|
-
|
|
332
|
-
name: "llama.cpp",
|
|
320
|
+
const llamaCppAdapter: ModelMetadataAdapter = {
|
|
333
321
|
matches(entries, headers) {
|
|
334
322
|
const server = (headers.get("server") ?? "").toLowerCase()
|
|
335
323
|
if (server.includes("llama-cpp") || server.includes("llama.cpp") || server.includes("llama-server")) return true
|
package/configuration.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { Provider } from "@opencode/plugin"
|
|
2
|
+
import { isRecord } from "./adapters.ts"
|
|
3
|
+
|
|
4
|
+
const DEFAULT_PROVIDER_ID = "local"
|
|
5
|
+
const DEFAULT_REFRESH_MS = 60_000
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 3_000
|
|
7
|
+
const MAX_TIMER_MS = 2_147_483_647
|
|
8
|
+
|
|
9
|
+
function readDuration(value: unknown, fallback: number, option: string, providerID: string): number {
|
|
10
|
+
if (value === undefined) return fallback
|
|
11
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_TIMER_MS) {
|
|
12
|
+
throw new Error(`${option} for provider ${providerID} must be an integer from 1 to ${MAX_TIMER_MS} milliseconds`)
|
|
13
|
+
}
|
|
14
|
+
return value
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function readProvider(options: Record<string, unknown>, baseURL: string) {
|
|
18
|
+
const { providerID = DEFAULT_PROVIDER_ID, providerName, apiKey, includeModels } = options
|
|
19
|
+
if (typeof providerID !== "string" || !/^[\w.-]+$/.test(providerID.trim())) {
|
|
20
|
+
throw new Error("providerID must contain only letters, digits, underscores, hyphens, or dots")
|
|
21
|
+
}
|
|
22
|
+
if (providerName !== undefined && (typeof providerName !== "string" || !providerName.trim())) {
|
|
23
|
+
throw new Error("providerName must be a non-empty string")
|
|
24
|
+
}
|
|
25
|
+
const id = Provider.ID.make(providerID.trim())
|
|
26
|
+
if (
|
|
27
|
+
includeModels !== undefined &&
|
|
28
|
+
(!Array.isArray(includeModels) || includeModels.some((modelID) => typeof modelID !== "string" || !modelID.trim()))
|
|
29
|
+
) {
|
|
30
|
+
throw new Error(`includeModels for provider ${id} must be an array of non-empty model IDs`)
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
providerID: id,
|
|
34
|
+
providerName: providerName?.trim(),
|
|
35
|
+
baseURL: baseURL.trim().replace(/\/+$/, ""),
|
|
36
|
+
apiKey: typeof apiKey === "string" ? apiKey.trim() : "",
|
|
37
|
+
refreshMs: readDuration(options.refreshMs, DEFAULT_REFRESH_MS, "refreshMs", id),
|
|
38
|
+
timeoutMs: readDuration(options.timeoutMs, DEFAULT_TIMEOUT_MS, "timeoutMs", id),
|
|
39
|
+
includeModels: includeModels === undefined ? undefined : new Set<string>(includeModels),
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type ProviderConfig = ReturnType<typeof readProvider>
|
|
44
|
+
|
|
45
|
+
export function readProviders(options: Readonly<Record<string, unknown>> = {}): ProviderConfig[] {
|
|
46
|
+
const providers =
|
|
47
|
+
typeof options.baseURL === "string" && options.baseURL.trim() ? [readProvider(options, options.baseURL)] : []
|
|
48
|
+
if (options.providers !== undefined) {
|
|
49
|
+
if (!Array.isArray(options.providers)) throw new Error("providers must be an array")
|
|
50
|
+
for (const [index, provider] of options.providers.entries()) {
|
|
51
|
+
if (!isRecord(provider) || typeof provider.baseURL !== "string" || !provider.baseURL.trim()) {
|
|
52
|
+
throw new Error(`providers[${index}].baseURL must be a non-empty string`)
|
|
53
|
+
}
|
|
54
|
+
providers.push(readProvider(provider, provider.baseURL))
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (new Set(providers.map(({ providerID }) => providerID)).size !== providers.length) {
|
|
58
|
+
throw new Error("Each configured provider must have a unique providerID")
|
|
59
|
+
}
|
|
60
|
+
return providers
|
|
61
|
+
}
|
package/discovery.ts
CHANGED
|
@@ -1,21 +1,65 @@
|
|
|
1
1
|
import type { Model, Provider } from "@opencode/plugin"
|
|
2
2
|
import {
|
|
3
|
+
extractInlineMetadata,
|
|
3
4
|
isRecord,
|
|
4
5
|
type JSONResult,
|
|
6
|
+
mergeMetadata,
|
|
5
7
|
type NormalizedModelMetadata,
|
|
6
8
|
type RawModelEntry,
|
|
7
9
|
SPECIALIZED_ADAPTERS,
|
|
8
10
|
} from "./adapters.ts"
|
|
9
|
-
import { normalizeInventory } from "./inventory.ts"
|
|
10
11
|
|
|
11
12
|
export type DiscoverySnapshot = { available: true; models: Model.Info[] } | { available: false; reason: string }
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
interface DiscoverModelsOptions {
|
|
14
15
|
baseURL: string
|
|
15
16
|
apiKey: string
|
|
16
17
|
signal: AbortSignal
|
|
17
18
|
timeoutMs: number
|
|
18
19
|
providerID: Provider.ID
|
|
20
|
+
includeModels?: ReadonlySet<string>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const ZERO_COST = 0 as Model.Info["cost"][number]["input"]
|
|
24
|
+
|
|
25
|
+
function projectModel(id: string, metadata: NormalizedModelMetadata, providerID: Provider.ID): Model.Info {
|
|
26
|
+
const modelID = id as Model.ID
|
|
27
|
+
const supportsImages = metadata.supportsImages === true
|
|
28
|
+
const supportsTools = metadata.supportsTools ?? true
|
|
29
|
+
const efforts = metadata.reasoningEfforts ?? []
|
|
30
|
+
return {
|
|
31
|
+
id: modelID,
|
|
32
|
+
modelID,
|
|
33
|
+
providerID,
|
|
34
|
+
name: id,
|
|
35
|
+
type: "chat",
|
|
36
|
+
status: "active",
|
|
37
|
+
enabled: true,
|
|
38
|
+
headers: {},
|
|
39
|
+
settings: {},
|
|
40
|
+
cost: [{ input: ZERO_COST, output: ZERO_COST, cache: { read: ZERO_COST, write: ZERO_COST } }],
|
|
41
|
+
limit: { context: metadata.contextLimit ?? 0, output: metadata.outputLimit ?? 0 },
|
|
42
|
+
capabilities: { tools: supportsTools, input: supportsImages ? ["text", "image"] : ["text"], output: ["text"] },
|
|
43
|
+
time: { released: 0 },
|
|
44
|
+
variants: [...new Set(efforts)]
|
|
45
|
+
.filter((effort) => effort.trim().length > 0)
|
|
46
|
+
.map((effort) => ({ id: effort as Model.VariantID, settings: { reasoningEffort: effort } })),
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normalizeInventory(
|
|
51
|
+
entries: readonly RawModelEntry[],
|
|
52
|
+
enrichment: ReadonlyMap<string, NormalizedModelMetadata> | undefined,
|
|
53
|
+
providerID: Provider.ID,
|
|
54
|
+
): Model.Info[] {
|
|
55
|
+
const models = new Map<string, Model.Info>()
|
|
56
|
+
for (const entry of entries) {
|
|
57
|
+
if (typeof entry?.id !== "string" || !entry.id.trim()) continue
|
|
58
|
+
const metadata = mergeMetadata(extractInlineMetadata(entry), enrichment?.get(entry.id))
|
|
59
|
+
if (metadata.isChat === false) continue
|
|
60
|
+
models.set(entry.id, projectModel(entry.id, metadata, providerID))
|
|
61
|
+
}
|
|
62
|
+
return [...models.values()].sort((a, b) => a.id.localeCompare(b.id))
|
|
19
63
|
}
|
|
20
64
|
|
|
21
65
|
async function loadJSON(url: string, apiKey: string, signal: AbortSignal, timeoutMs: number): Promise<JSONResult> {
|
|
@@ -47,6 +91,7 @@ export async function discoverModels({
|
|
|
47
91
|
signal,
|
|
48
92
|
timeoutMs,
|
|
49
93
|
providerID,
|
|
94
|
+
includeModels,
|
|
50
95
|
}: DiscoverModelsOptions): Promise<DiscoverySnapshot> {
|
|
51
96
|
const fetchJSON = (url: string) => loadJSON(url, apiKey, signal, timeoutMs)
|
|
52
97
|
const inventory = await fetchJSON(`${baseURL}/models`)
|
|
@@ -59,16 +104,13 @@ export async function discoverModels({
|
|
|
59
104
|
}
|
|
60
105
|
|
|
61
106
|
const entries = rawEntries as RawModelEntry[]
|
|
107
|
+
// Detection and enrichment depend on the complete catalogue, before any model selection.
|
|
62
108
|
const adapter = SPECIALIZED_ADAPTERS.find((candidate) => candidate.matches(entries, inventory.headers))
|
|
63
|
-
const enrichment
|
|
64
|
-
? await adapter.enrich(entries, { baseURL, headers: inventory.headers, loadJSON: fetchJSON })
|
|
65
|
-
: new Map()
|
|
109
|
+
const enrichment = await adapter?.enrich(entries, { baseURL, loadJSON: fetchJSON })
|
|
66
110
|
if (signal.aborted) {
|
|
67
111
|
return { available: false, reason: "aborted" }
|
|
68
112
|
}
|
|
69
113
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
models: normalizeInventory(entries, enrichment, providerID, adapter),
|
|
73
|
-
}
|
|
114
|
+
const models = normalizeInventory(entries, enrichment, providerID)
|
|
115
|
+
return { available: true, models: includeModels ? models.filter(({ id }) => includeModels.has(id)) : models }
|
|
74
116
|
}
|
package/index.ts
CHANGED
|
@@ -1,111 +1,12 @@
|
|
|
1
1
|
/** OpenCode V2 discovery for a local OpenAI-compatible model inventory. */
|
|
2
|
-
import { Plugin
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { snapshotsDiffer, startRefreshLifecycle } from "./lifecycle.ts"
|
|
6
|
-
import { publishSnapshot } from "./registry.ts"
|
|
7
|
-
|
|
8
|
-
const DEFAULT_PROVIDER_ID = "local"
|
|
9
|
-
const RUNTIME = "@opencode/ai/providers/openai-compatible"
|
|
10
|
-
const DEFAULT_REFRESH_MS = 60_000
|
|
11
|
-
const DEFAULT_TIMEOUT_MS = 3_000
|
|
12
|
-
const MAX_TIMER_MS = 2_147_483_647
|
|
13
|
-
|
|
14
|
-
function readDuration(value: unknown, fallback: number, option: string, providerID: string): number {
|
|
15
|
-
if (value === undefined) return fallback
|
|
16
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_TIMER_MS) {
|
|
17
|
-
throw new Error(`${option} for provider ${providerID} must be an integer from 1 to ${MAX_TIMER_MS} milliseconds`)
|
|
18
|
-
}
|
|
19
|
-
return value
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function readProvider(options: Record<string, unknown>, baseURL: string) {
|
|
23
|
-
const { providerID = DEFAULT_PROVIDER_ID, providerName, apiKey } = options
|
|
24
|
-
if (typeof providerID !== "string" || !/^[\w.-]+$/.test(providerID.trim())) {
|
|
25
|
-
throw new Error("providerID must contain only letters, digits, underscores, hyphens, or dots")
|
|
26
|
-
}
|
|
27
|
-
if (providerName !== undefined && (typeof providerName !== "string" || !providerName.trim())) {
|
|
28
|
-
throw new Error("providerName must be a non-empty string")
|
|
29
|
-
}
|
|
30
|
-
const id = Provider.ID.make(providerID.trim())
|
|
31
|
-
return {
|
|
32
|
-
providerID: id,
|
|
33
|
-
providerName: providerName?.trim(),
|
|
34
|
-
baseURL: baseURL.trim().replace(/\/+$/, ""),
|
|
35
|
-
apiKey: typeof apiKey === "string" ? apiKey.trim() : "",
|
|
36
|
-
refreshMs: readDuration(options.refreshMs, DEFAULT_REFRESH_MS, "refreshMs", id),
|
|
37
|
-
timeoutMs: readDuration(options.timeoutMs, DEFAULT_TIMEOUT_MS, "timeoutMs", id),
|
|
38
|
-
}
|
|
39
|
-
}
|
|
2
|
+
import { Plugin } from "@opencode/plugin"
|
|
3
|
+
import { readProviders } from "./configuration.ts"
|
|
4
|
+
import { startPublication } from "./publication.ts"
|
|
40
5
|
|
|
41
6
|
export default Plugin.define({
|
|
42
7
|
id: "openai-compat-provider",
|
|
43
8
|
async setup(ctx) {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
typeof options.baseURL === "string" && options.baseURL.trim() ? [readProvider(options, options.baseURL)] : []
|
|
47
|
-
if (options.providers !== undefined) {
|
|
48
|
-
if (!Array.isArray(options.providers)) throw new Error("providers must be an array")
|
|
49
|
-
for (const [index, provider] of options.providers.entries()) {
|
|
50
|
-
if (!isRecord(provider) || typeof provider.baseURL !== "string" || !provider.baseURL.trim()) {
|
|
51
|
-
throw new Error(`providers[${index}].baseURL must be a non-empty string`)
|
|
52
|
-
}
|
|
53
|
-
providers.push(readProvider(provider, provider.baseURL))
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
if (!providers.length) return
|
|
57
|
-
if (new Set(providers.map(({ providerID }) => providerID)).size !== providers.length) {
|
|
58
|
-
throw new Error("Each configured provider must have a unique providerID")
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const controller = new AbortController()
|
|
62
|
-
const { signal } = controller
|
|
63
|
-
const sources = await Promise.all(
|
|
64
|
-
providers.map(async ({ providerID, providerName, baseURL, apiKey, refreshMs, timeoutMs }) => {
|
|
65
|
-
const load = () => discoverModels({ baseURL, apiKey, signal, timeoutMs, providerID })
|
|
66
|
-
return {
|
|
67
|
-
providerID,
|
|
68
|
-
providerName,
|
|
69
|
-
refreshMs,
|
|
70
|
-
settings: { baseURL, ...(apiKey ? { apiKey } : {}) },
|
|
71
|
-
load,
|
|
72
|
-
snapshot: await load(),
|
|
73
|
-
managedIDs: new Set<string>(),
|
|
74
|
-
}
|
|
75
|
-
}),
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
await ctx.provider.transform((editor) => {
|
|
79
|
-
for (const source of sources) {
|
|
80
|
-
const { snapshot, managedIDs, providerID, providerName, settings } = source
|
|
81
|
-
source.managedIDs = publishSnapshot(editor, snapshot, managedIDs, providerID, RUNTIME, settings, providerName)
|
|
82
|
-
}
|
|
83
|
-
})
|
|
84
|
-
|
|
85
|
-
const stopRefreshing = sources.map((source) =>
|
|
86
|
-
startRefreshLifecycle({
|
|
87
|
-
signal,
|
|
88
|
-
intervalMs: source.refreshMs,
|
|
89
|
-
load: source.load,
|
|
90
|
-
shouldPublish: (next) => snapshotsDiffer(source.snapshot, next),
|
|
91
|
-
async publish(next: DiscoverySnapshot) {
|
|
92
|
-
const { snapshot, managedIDs } = source
|
|
93
|
-
source.snapshot = next
|
|
94
|
-
try {
|
|
95
|
-
await ctx.provider.reload()
|
|
96
|
-
} catch (error) {
|
|
97
|
-
source.snapshot = snapshot
|
|
98
|
-
source.managedIDs = managedIDs
|
|
99
|
-
throw error
|
|
100
|
-
}
|
|
101
|
-
},
|
|
102
|
-
onError: (error) => console.warn(`[openai-compat-provider] Failed to refresh ${source.providerID}`, error),
|
|
103
|
-
}),
|
|
104
|
-
)
|
|
105
|
-
|
|
106
|
-
return () => {
|
|
107
|
-
controller.abort()
|
|
108
|
-
for (const stop of stopRefreshing) stop()
|
|
109
|
-
}
|
|
9
|
+
const providers = readProviders(ctx.options ?? {})
|
|
10
|
+
if (providers.length > 0) return startPublication(providers, ctx.provider)
|
|
110
11
|
},
|
|
111
12
|
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-openai-compatible-discovery",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"packageManager": "bun@1.4.5",
|
|
5
5
|
"description": "Discover models from OpenAI-compatible local and self-hosted endpoints in OpenCode V2.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
"index.js",
|
|
21
21
|
"index.ts",
|
|
22
22
|
"adapters.ts",
|
|
23
|
+
"configuration.ts",
|
|
23
24
|
"discovery.ts",
|
|
24
|
-
"
|
|
25
|
-
"lifecycle.ts",
|
|
25
|
+
"publication.ts",
|
|
26
26
|
"registry.ts",
|
|
27
27
|
"README.md"
|
|
28
28
|
],
|
package/publication.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import type { ProviderConfig } from "./configuration.ts"
|
|
3
|
+
import { type DiscoverySnapshot, discoverModels } from "./discovery.ts"
|
|
4
|
+
import { publishSnapshot } from "./registry.ts"
|
|
5
|
+
|
|
6
|
+
interface ProviderSource {
|
|
7
|
+
config: ProviderConfig
|
|
8
|
+
snapshot: DiscoverySnapshot
|
|
9
|
+
timer?: ReturnType<typeof setTimeout>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function startPublication(
|
|
13
|
+
providers: readonly ProviderConfig[],
|
|
14
|
+
registry: Pick<Plugin.Context["provider"], "transform" | "reload">,
|
|
15
|
+
): Promise<() => void> {
|
|
16
|
+
const controller = new AbortController()
|
|
17
|
+
const { signal } = controller
|
|
18
|
+
const sources: ProviderSource[] = await Promise.all(
|
|
19
|
+
providers.map(async (config) => ({ config, snapshot: await discoverModels({ ...config, signal }) })),
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
let replayed = false
|
|
23
|
+
let restorationPending = false
|
|
24
|
+
await registry.transform((editor) => {
|
|
25
|
+
replayed = true
|
|
26
|
+
for (const { config, snapshot } of sources) publishSnapshot(editor, config, snapshot)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
async function publish(source: ProviderSource, next: DiscoverySnapshot) {
|
|
30
|
+
if (signal.aborted) return
|
|
31
|
+
const previous = source.snapshot
|
|
32
|
+
const changed =
|
|
33
|
+
next.available && (!previous.available || JSON.stringify(previous.models) !== JSON.stringify(next.models))
|
|
34
|
+
if (!changed && !restorationPending) return
|
|
35
|
+
|
|
36
|
+
if (changed) source.snapshot = next
|
|
37
|
+
replayed = false
|
|
38
|
+
try {
|
|
39
|
+
await registry.reload()
|
|
40
|
+
restorationPending = false
|
|
41
|
+
} catch (error) {
|
|
42
|
+
source.snapshot = previous
|
|
43
|
+
// Rebuild if a host read observed the staged snapshot before reload failed.
|
|
44
|
+
if (replayed && !signal.aborted) {
|
|
45
|
+
restorationPending = true
|
|
46
|
+
try {
|
|
47
|
+
await registry.reload()
|
|
48
|
+
restorationPending = false
|
|
49
|
+
} catch (restoreError) {
|
|
50
|
+
throw new AggregateError([error, restoreError], "Failed to publish and restore the model registry")
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
throw error
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Requests run independently; only changes to the shared registry are serialized.
|
|
58
|
+
let publication = Promise.resolve()
|
|
59
|
+
async function refresh(source: ProviderSource) {
|
|
60
|
+
const next = await discoverModels({ ...source.config, signal })
|
|
61
|
+
const update = publication.then(() => publish(source, next))
|
|
62
|
+
publication = update.catch(() => {})
|
|
63
|
+
await update
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function schedule(source: ProviderSource) {
|
|
67
|
+
if (signal.aborted) return
|
|
68
|
+
source.timer = setTimeout(() => {
|
|
69
|
+
void refresh(source)
|
|
70
|
+
.catch((error) => console.warn(`[openai-compat-provider] Failed to refresh ${source.config.providerID}`, error))
|
|
71
|
+
.finally(() => schedule(source))
|
|
72
|
+
}, source.config.refreshMs)
|
|
73
|
+
source.timer.unref?.()
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
for (const source of sources) schedule(source)
|
|
77
|
+
return () => {
|
|
78
|
+
controller.abort()
|
|
79
|
+
for (const source of sources) clearTimeout(source.timer)
|
|
80
|
+
}
|
|
81
|
+
}
|
package/registry.ts
CHANGED
|
@@ -1,59 +1,42 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import type { ProviderConfig } from "./configuration.ts"
|
|
2
3
|
import type { DiscoverySnapshot } from "./discovery.ts"
|
|
3
4
|
|
|
4
5
|
export type ProviderEditor = Parameters<Parameters<Plugin.Context["provider"]["transform"]>[0]>[0]
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
existingModels: ReadonlyMap<string, Model.Info>,
|
|
8
|
-
discoveredModels: readonly Model.Info[],
|
|
9
|
-
managedIDs: ReadonlySet<string>,
|
|
10
|
-
): { models: Model.Info[]; managedIDs: Set<string> } {
|
|
11
|
-
const reconciled = new Map<string, Model.Info>(existingModels)
|
|
12
|
-
for (const id of managedIDs) reconciled.delete(id)
|
|
13
|
-
|
|
14
|
-
const nextManaged = new Set<string>()
|
|
15
|
-
for (const model of discoveredModels) {
|
|
16
|
-
const wasManaged = managedIDs.has(model.id)
|
|
17
|
-
if (!reconciled.has(model.id) || wasManaged) {
|
|
18
|
-
reconciled.set(model.id, model)
|
|
19
|
-
nextManaged.add(model.id)
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
return { models: [...reconciled.values()], managedIDs: nextManaged }
|
|
23
|
-
}
|
|
7
|
+
const RUNTIME = "@opencode/ai/providers/openai-compatible"
|
|
24
8
|
|
|
25
9
|
export function publishSnapshot(
|
|
26
10
|
editor: ProviderEditor,
|
|
11
|
+
{ providerID, providerName, baseURL, apiKey }: ProviderConfig,
|
|
27
12
|
snapshot: DiscoverySnapshot,
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
settings: Record<string, unknown>,
|
|
32
|
-
providerName?: string,
|
|
33
|
-
): Set<string> {
|
|
34
|
-
if (!snapshot.available) return new Set(managedIDs)
|
|
13
|
+
): void {
|
|
14
|
+
if (!snapshot.available) return
|
|
15
|
+
const settings = { baseURL, ...(apiKey ? { apiKey } : {}) }
|
|
35
16
|
const existing = editor.get(providerID)
|
|
36
17
|
if (existing) {
|
|
37
|
-
const reconciled = reconcileModels(existing.models, snapshot.models, managedIDs)
|
|
38
18
|
editor.update(providerID, (provider) => {
|
|
39
19
|
if (providerName !== undefined) provider.name = providerName
|
|
40
|
-
provider.package =
|
|
20
|
+
provider.package = RUNTIME
|
|
41
21
|
provider.activation = "enabled"
|
|
42
22
|
provider.settings = { ...provider.settings, ...settings }
|
|
43
23
|
})
|
|
44
|
-
|
|
45
|
-
|
|
24
|
+
// OpenCode replays transforms on a fresh registry. Entries already present belong to other sources.
|
|
25
|
+
editor.models.set(providerID, [
|
|
26
|
+
...existing.models.values(),
|
|
27
|
+
...snapshot.models.filter(({ id }) => !existing.models.has(id)),
|
|
28
|
+
])
|
|
29
|
+
return
|
|
46
30
|
}
|
|
47
|
-
if (snapshot.models.length === 0) return
|
|
31
|
+
if (snapshot.models.length === 0) return
|
|
48
32
|
editor.add({
|
|
49
33
|
info: {
|
|
50
34
|
id: providerID,
|
|
51
35
|
name: providerName ?? (providerID === "local" ? "Local" : providerID),
|
|
52
36
|
activation: "enabled",
|
|
53
|
-
package:
|
|
37
|
+
package: RUNTIME,
|
|
54
38
|
settings,
|
|
55
39
|
},
|
|
56
40
|
models: snapshot.models,
|
|
57
41
|
})
|
|
58
|
-
return new Set(snapshot.models.map((model) => model.id))
|
|
59
42
|
}
|
package/inventory.ts
DELETED
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import type { Model, Provider } from "@opencode/plugin"
|
|
2
|
-
import {
|
|
3
|
-
genericAdapter,
|
|
4
|
-
type ModelMetadataAdapter,
|
|
5
|
-
mergeMetadata,
|
|
6
|
-
type NormalizedModelMetadata,
|
|
7
|
-
type RawModelEntry,
|
|
8
|
-
} from "./adapters.ts"
|
|
9
|
-
|
|
10
|
-
const ZERO_COST = 0 as Model.Info["cost"][number]["input"]
|
|
11
|
-
|
|
12
|
-
function projectModel(id: string, metadata: NormalizedModelMetadata, providerID: Provider.ID): Model.Info {
|
|
13
|
-
const modelID = id as Model.ID
|
|
14
|
-
const supportsImages = metadata.supportsImages === true
|
|
15
|
-
const supportsTools = metadata.supportsTools ?? true
|
|
16
|
-
const efforts = metadata.reasoningEfforts ?? []
|
|
17
|
-
return {
|
|
18
|
-
id: modelID,
|
|
19
|
-
modelID,
|
|
20
|
-
providerID,
|
|
21
|
-
name: id,
|
|
22
|
-
type: "chat",
|
|
23
|
-
status: "active",
|
|
24
|
-
enabled: true,
|
|
25
|
-
headers: {},
|
|
26
|
-
settings: {},
|
|
27
|
-
cost: [{ input: ZERO_COST, output: ZERO_COST, cache: { read: ZERO_COST, write: ZERO_COST } }],
|
|
28
|
-
limit: { context: metadata.contextLimit ?? 0, output: metadata.outputLimit ?? 0 },
|
|
29
|
-
capabilities: { tools: supportsTools, input: supportsImages ? ["text", "image"] : ["text"], output: ["text"] },
|
|
30
|
-
time: { released: 0 },
|
|
31
|
-
variants: [...new Set(efforts)]
|
|
32
|
-
.filter((effort) => effort.trim().length > 0)
|
|
33
|
-
.map((effort) => ({ id: effort as Model.VariantID, settings: { reasoningEffort: effort } })),
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function normalizeInventory(
|
|
38
|
-
entries: readonly RawModelEntry[],
|
|
39
|
-
enrichment: ReadonlyMap<string, NormalizedModelMetadata>,
|
|
40
|
-
providerID: Provider.ID,
|
|
41
|
-
adapter?: ModelMetadataAdapter,
|
|
42
|
-
): Model.Info[] {
|
|
43
|
-
const models = new Map<string, Model.Info>()
|
|
44
|
-
for (const entry of entries) {
|
|
45
|
-
if (typeof entry?.id !== "string" || !entry.id.trim()) continue
|
|
46
|
-
const base = genericAdapter.extract ? genericAdapter.extract(entry) : {}
|
|
47
|
-
const specialized = adapter?.extract ? adapter.extract(entry) : undefined
|
|
48
|
-
const inline = specialized ? mergeMetadata(specialized, base) : base
|
|
49
|
-
const metadata = mergeMetadata(inline, enrichment.get(entry.id))
|
|
50
|
-
if (metadata.isChat === false) continue
|
|
51
|
-
models.set(entry.id, projectModel(entry.id, metadata, providerID))
|
|
52
|
-
}
|
|
53
|
-
return [...models.values()].sort((a, b) => a.id.localeCompare(b.id))
|
|
54
|
-
}
|
package/lifecycle.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import type { DiscoverySnapshot } from "./discovery.ts"
|
|
2
|
-
|
|
3
|
-
export interface RefreshLifecycleOptions {
|
|
4
|
-
signal: AbortSignal
|
|
5
|
-
intervalMs: number
|
|
6
|
-
load: () => Promise<DiscoverySnapshot>
|
|
7
|
-
shouldPublish: (next: DiscoverySnapshot) => boolean
|
|
8
|
-
publish: (next: DiscoverySnapshot) => Promise<void>
|
|
9
|
-
onError: (error: unknown) => void
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export function snapshotsDiffer(current: DiscoverySnapshot, next: DiscoverySnapshot): boolean {
|
|
13
|
-
return next.available && (!current.available || JSON.stringify(next.models) !== JSON.stringify(current.models))
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function startRefreshLifecycle({
|
|
17
|
-
signal,
|
|
18
|
-
intervalMs,
|
|
19
|
-
load,
|
|
20
|
-
shouldPublish,
|
|
21
|
-
publish,
|
|
22
|
-
onError,
|
|
23
|
-
}: RefreshLifecycleOptions): () => void {
|
|
24
|
-
let timer: ReturnType<typeof setTimeout> | undefined
|
|
25
|
-
const schedule = () => {
|
|
26
|
-
if (signal.aborted) return
|
|
27
|
-
timer = setTimeout(() => {
|
|
28
|
-
void refresh().catch(onError).finally(schedule)
|
|
29
|
-
}, intervalMs)
|
|
30
|
-
timer.unref?.()
|
|
31
|
-
}
|
|
32
|
-
const refresh = async () => {
|
|
33
|
-
const next = await load()
|
|
34
|
-
if (signal.aborted || !next.available || !shouldPublish(next)) return
|
|
35
|
-
await publish(next)
|
|
36
|
-
}
|
|
37
|
-
schedule()
|
|
38
|
-
return () => {
|
|
39
|
-
clearTimeout(timer)
|
|
40
|
-
}
|
|
41
|
-
}
|