opencode-openai-compatible-discovery 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +131 -2
- package/adapters.ts +376 -0
- package/discovery.ts +74 -0
- package/index.js +2 -0
- package/index.ts +118 -0
- package/inventory.ts +54 -0
- package/lifecycle.ts +41 -0
- package/package.json +42 -4
- package/registry.ts +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Iñigo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,132 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OpenCode OpenAI-Compatible Model Discovery
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Discover chat models from an OpenAI-compatible `/v1/models` endpoint and add them to OpenCode V2. Built-in metadata
|
|
4
|
+
adapters read inline extended fields from `/v1/models` (vLLM, SGLang, MTPLX, OpenRouter, llama.cpp `meta`, etc.) and
|
|
5
|
+
optionally enrich models from native server endpoints when detected (oMLX `/v1/models/status`, LM Studio
|
|
6
|
+
`/api/v1/models` & `/api/v0/models`, and single-model llama.cpp `/props`).
|
|
7
|
+
|
|
8
|
+
OpenCode includes native discovery for LM Studio and Ollama. Use this plugin for other compatible endpoints or when
|
|
9
|
+
you need the extra oMLX reasoning metadata.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
opencode plugin add opencode-openai-compatible-discovery@latest
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Then configure the endpoint in `~/.config/opencode/opencode.jsonc`:
|
|
18
|
+
|
|
19
|
+
```jsonc
|
|
20
|
+
{
|
|
21
|
+
"$schema": "https://opencode.ai/config.json",
|
|
22
|
+
"plugins": [
|
|
23
|
+
{
|
|
24
|
+
"package": "opencode-openai-compatible-discovery@latest",
|
|
25
|
+
"options": {
|
|
26
|
+
"baseURL": "http://127.0.0.1:8001/v1",
|
|
27
|
+
"apiKey": "{env:LOCAL_LLM_API_KEY}",
|
|
28
|
+
"refreshMs": 30000,
|
|
29
|
+
"timeoutMs": 5000
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
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`. |
|
|
46
|
+
|
|
47
|
+
The endpoint should return OpenAI-compatible model records from `GET <baseURL>/models`. Temporary discovery failures
|
|
48
|
+
keep the last successfully published inventory. Tool calling defaults to enabled when the inventory does not specify
|
|
49
|
+
support; an endpoint can set `capabilities.tools: false` on a model to disable it.
|
|
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
|
+
|
|
55
|
+
Both `refreshMs` and `timeoutMs` must be integers in milliseconds from `1` to `2147483647`. The first discovery pass
|
|
56
|
+
runs immediately.
|
|
57
|
+
|
|
58
|
+
For multiple endpoints, configure one plugin entry with a `providers` array. Use a unique `providerID` for each
|
|
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.
|
|
61
|
+
|
|
62
|
+
```jsonc
|
|
63
|
+
{
|
|
64
|
+
"plugins": [
|
|
65
|
+
{
|
|
66
|
+
"package": "opencode-openai-compatible-discovery@latest",
|
|
67
|
+
"options": {
|
|
68
|
+
"providers": [
|
|
69
|
+
{
|
|
70
|
+
"providerID": "workstation",
|
|
71
|
+
"providerName": "Workstation",
|
|
72
|
+
"baseURL": "http://127.0.0.1:8001/v1"
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
"providerID": "team-llm",
|
|
76
|
+
"providerName": "Team models",
|
|
77
|
+
"baseURL": "https://llm.example.com/v1",
|
|
78
|
+
"apiKey": "{env:TEAM_LLM_API_KEY}",
|
|
79
|
+
"includeModels": ["team/general-chat", "team/coding"],
|
|
80
|
+
"refreshMs": 120000,
|
|
81
|
+
"timeoutMs": 10000
|
|
82
|
+
}
|
|
83
|
+
]
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
]
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
CI tests the installed package with OpenCode **2.4.3**. The `@latest` entry follows new versions automatically;
|
|
91
|
+
use `opencode-openai-compatible-discovery@0.1.0` to pin the first release once published.
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
bun install --frozen-lockfile
|
|
97
|
+
pre-commit run --all-files
|
|
98
|
+
bun test
|
|
99
|
+
bun pm pack
|
|
100
|
+
bun run test:package ./opencode-openai-compatible-discovery-0.1.0.tgz
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The smoke test requires OpenCode 2.4.3 on `PATH`. Start each change on a new branch from up-to-date `main` and submit
|
|
104
|
+
it through a PR. On the PR, pre-commit runs first with Biome. Unit tests and the installed-package smoke test run in
|
|
105
|
+
parallel after it passes. See the [OpenCode plugin guide](https://opencode.ai/docs/build/plugins)
|
|
106
|
+
for the V2 plugin contract and [plugin management](https://opencode.ai/docs/plugins) for install, update, and removal commands.
|
|
107
|
+
|
|
108
|
+
## Releasing
|
|
109
|
+
|
|
110
|
+
Once enabled, each update to `main` triggers [semantic-release](https://semantic-release.org/). Use [Conventional
|
|
111
|
+
Commits](https://www.conventionalcommits.org/) for commit messages and PR titles so squash merges preserve the type.
|
|
112
|
+
Use `feat`, `fix`, `perf`, or `revert` for changes to the published plugin; these trigger a patch release. CI-only
|
|
113
|
+
(`ci`), documentation (`docs`), test-only (`test`), and maintenance (`chore`) changes do not bump the version.
|
|
114
|
+
If several merges land before a release runs, semantic-release can publish them together from the latest `main` commit.
|
|
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
|
+
### One-time setup
|
|
121
|
+
|
|
122
|
+
1. Protect `main` with a required PR and the `Validate package` status check from GitHub Actions. Require branches to be
|
|
123
|
+
up to date before merging and disallow bypasses.
|
|
124
|
+
2. The Release workflow records the already-published npm version `0.1.0` in GitHub. It verifies the tarball's integrity
|
|
125
|
+
and creates the `v0.1.0` tag and GitHub release on the original commit. It does not publish that version again.
|
|
126
|
+
3. Use the GitHub environment `npm`, restricted to `main` and without required reviewers. In the npm package's
|
|
127
|
+
[Trusted Publishing settings](https://docs.npmjs.com/trusted-publishers/), authorize this repository's `release.yml`
|
|
128
|
+
workflow and the `npm` environment, with permission for `npm publish`. Set `NPM_RELEASES_ENABLED=true` once ready,
|
|
129
|
+
and publish the next version within two days to validate the trusted publisher configuration.
|
|
130
|
+
|
|
131
|
+
If the run fails before creating a tag, rerun **Release** on `main`. If a tag was created, check npm and GitHub Releases
|
|
132
|
+
before retrying: semantic-release uses existing tags to decide which changes have already been released.
|
package/adapters.ts
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
export interface RawModelEntry {
|
|
2
|
+
id?: unknown
|
|
3
|
+
owned_by?: unknown
|
|
4
|
+
model_type?: unknown
|
|
5
|
+
type?: unknown
|
|
6
|
+
capability?: unknown
|
|
7
|
+
input_modalities?: unknown
|
|
8
|
+
architecture?: {
|
|
9
|
+
input_modalities?: unknown
|
|
10
|
+
} | null
|
|
11
|
+
max_model_len?: unknown
|
|
12
|
+
context_length?: unknown
|
|
13
|
+
max_context_length?: unknown
|
|
14
|
+
context_window?: unknown
|
|
15
|
+
max_context_len?: unknown
|
|
16
|
+
max_tokens?: unknown
|
|
17
|
+
max_output_tokens?: unknown
|
|
18
|
+
max_completion_tokens?: unknown
|
|
19
|
+
meta?: {
|
|
20
|
+
n_ctx?: unknown
|
|
21
|
+
n_ctx_train?: unknown
|
|
22
|
+
} | null
|
|
23
|
+
capabilities?: unknown
|
|
24
|
+
reasoning?: unknown
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface NormalizedModelMetadata {
|
|
28
|
+
isChat?: boolean
|
|
29
|
+
supportsImages?: boolean
|
|
30
|
+
supportsTools?: boolean
|
|
31
|
+
contextLimit?: number
|
|
32
|
+
outputLimit?: number
|
|
33
|
+
reasoningEfforts?: readonly string[]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type JSONResult = { available: true; data: unknown; headers: Headers } | { available: false; reason: string }
|
|
37
|
+
|
|
38
|
+
export interface AdapterFetchContext {
|
|
39
|
+
baseURL: string
|
|
40
|
+
headers: Headers
|
|
41
|
+
loadJSON: (url: string) => Promise<JSONResult>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ModelMetadataAdapter {
|
|
45
|
+
readonly name: string
|
|
46
|
+
matches(entries: readonly RawModelEntry[], headers: Headers): boolean
|
|
47
|
+
extract?(entry: RawModelEntry): NormalizedModelMetadata
|
|
48
|
+
enrich?(
|
|
49
|
+
entries: readonly RawModelEntry[],
|
|
50
|
+
ctx: AdapterFetchContext,
|
|
51
|
+
): Promise<ReadonlyMap<string, NormalizedModelMetadata>>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const DEFAULT_EFFORTS = ["low", "medium", "high"] as const
|
|
55
|
+
const REASONING_EFFORTS = new Set<string>(["none", "minimal", ...DEFAULT_EFFORTS, "xhigh", "max"])
|
|
56
|
+
const CHAT_MODEL_TYPES = new Set(["llm", "vlm", "chat"])
|
|
57
|
+
|
|
58
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
59
|
+
return typeof value === "object" && value !== null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function positiveInteger(...values: unknown[]): number | undefined {
|
|
63
|
+
for (const value of values) {
|
|
64
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return value
|
|
65
|
+
}
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function serverOriginBase(baseURL: string): string {
|
|
70
|
+
return baseURL.replace(/\/v1$/i, "")
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function filterNamedEfforts(values: readonly unknown[]): string[] {
|
|
74
|
+
return values.filter((effort): effort is string => typeof effort === "string" && REASONING_EFFORTS.has(effort))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function stringArray(value: unknown): string[] | undefined {
|
|
78
|
+
if (!Array.isArray(value)) return undefined
|
|
79
|
+
return value.filter((item): item is string => typeof item === "string")
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function readInputModalities(entry: RawModelEntry): string[] | undefined {
|
|
83
|
+
return stringArray(entry.input_modalities) ?? stringArray(entry.architecture?.input_modalities)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function extractInlineMetadata(entry: RawModelEntry): NormalizedModelMetadata {
|
|
87
|
+
const metadata: NormalizedModelMetadata = {}
|
|
88
|
+
|
|
89
|
+
const modalities = readInputModalities(entry)
|
|
90
|
+
if (modalities && !modalities.includes("text")) {
|
|
91
|
+
metadata.isChat = false
|
|
92
|
+
} else if (typeof entry.capability === "string") {
|
|
93
|
+
metadata.isChat = entry.capability === "chat"
|
|
94
|
+
} else {
|
|
95
|
+
const modelType =
|
|
96
|
+
typeof entry.model_type === "string" ? entry.model_type : typeof entry.type === "string" ? entry.type : undefined
|
|
97
|
+
if (modelType !== undefined) {
|
|
98
|
+
metadata.isChat = CHAT_MODEL_TYPES.has(modelType)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const rawModelType =
|
|
103
|
+
typeof entry.model_type === "string" ? entry.model_type : typeof entry.type === "string" ? entry.type : undefined
|
|
104
|
+
const capArray = stringArray(entry.capabilities)
|
|
105
|
+
const capObject = !Array.isArray(entry.capabilities) && isRecord(entry.capabilities) ? entry.capabilities : undefined
|
|
106
|
+
|
|
107
|
+
if (
|
|
108
|
+
rawModelType === "vlm" ||
|
|
109
|
+
modalities?.includes("image") === true ||
|
|
110
|
+
capObject?.vision === true ||
|
|
111
|
+
capArray?.some((cap) => cap === "vision" || cap === "image" || cap === "multimodal") === true
|
|
112
|
+
) {
|
|
113
|
+
metadata.supportsImages = true
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (typeof capObject?.tools === "boolean") {
|
|
117
|
+
metadata.supportsTools = capObject.tools
|
|
118
|
+
} else if (typeof capObject?.trained_for_tool_use === "boolean") {
|
|
119
|
+
metadata.supportsTools = capObject.trained_for_tool_use
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const meta = isRecord(entry.meta) ? entry.meta : undefined
|
|
123
|
+
const contextLimit = positiveInteger(
|
|
124
|
+
entry.max_model_len,
|
|
125
|
+
entry.context_length,
|
|
126
|
+
entry.max_context_length,
|
|
127
|
+
entry.context_window,
|
|
128
|
+
entry.max_context_len,
|
|
129
|
+
meta?.n_ctx,
|
|
130
|
+
meta?.n_ctx_train,
|
|
131
|
+
)
|
|
132
|
+
if (contextLimit !== undefined) metadata.contextLimit = contextLimit
|
|
133
|
+
|
|
134
|
+
const outputLimit = positiveInteger(entry.max_tokens, entry.max_output_tokens, entry.max_completion_tokens)
|
|
135
|
+
if (outputLimit !== undefined) metadata.outputLimit = outputLimit
|
|
136
|
+
|
|
137
|
+
if (isRecord(entry.reasoning) && Array.isArray(entry.reasoning.efforts)) {
|
|
138
|
+
metadata.reasoningEfforts = entry.reasoning.efforts.filter(
|
|
139
|
+
(effort): effort is string => typeof effort === "string" && effort.trim().length > 0,
|
|
140
|
+
)
|
|
141
|
+
} else if (isRecord(capObject?.reasoning) && Array.isArray(capObject.reasoning.allowed_options)) {
|
|
142
|
+
metadata.reasoningEfforts = filterNamedEfforts(capObject.reasoning.allowed_options)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return metadata
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export const genericAdapter: ModelMetadataAdapter = {
|
|
149
|
+
name: "generic",
|
|
150
|
+
matches: () => true,
|
|
151
|
+
extract: extractInlineMetadata,
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
interface RawOmlxStatusModel {
|
|
155
|
+
id?: unknown
|
|
156
|
+
model_alias?: unknown
|
|
157
|
+
profile_api_name?: unknown
|
|
158
|
+
model_type?: unknown
|
|
159
|
+
engine_type?: unknown
|
|
160
|
+
is_helper?: unknown
|
|
161
|
+
max_context_window?: unknown
|
|
162
|
+
max_tokens?: unknown
|
|
163
|
+
reasoning_levels?: unknown
|
|
164
|
+
reasoning_effort_options?: unknown
|
|
165
|
+
reasoning_efforts?: unknown
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function indexOmlxStatus(statusModels: readonly RawOmlxStatusModel[]): Map<string, RawOmlxStatusModel> {
|
|
169
|
+
const indexed = new Map<string, RawOmlxStatusModel>()
|
|
170
|
+
for (const model of statusModels) {
|
|
171
|
+
if (typeof model?.id !== "string") continue
|
|
172
|
+
indexed.set(model.id, model)
|
|
173
|
+
if (typeof model.model_alias !== "string" || !model.model_alias) continue
|
|
174
|
+
const alias =
|
|
175
|
+
typeof model.profile_api_name === "string" && model.profile_api_name
|
|
176
|
+
? `${model.model_alias}:${model.profile_api_name}`
|
|
177
|
+
: model.model_alias
|
|
178
|
+
indexed.set(alias, model)
|
|
179
|
+
}
|
|
180
|
+
return indexed
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function omlxStatusReasoning(status: RawOmlxStatusModel | undefined): string[] {
|
|
184
|
+
// oMLX exposes chat UI stops separately from its OpenAI-compatible inventory.
|
|
185
|
+
// Ignore UI on/off switches: they are not named effort levels.
|
|
186
|
+
if (Array.isArray(status?.reasoning_levels)) {
|
|
187
|
+
return filterNamedEfforts(status.reasoning_levels)
|
|
188
|
+
}
|
|
189
|
+
if (Array.isArray(status?.reasoning_effort_options)) {
|
|
190
|
+
return filterNamedEfforts(status.reasoning_effort_options)
|
|
191
|
+
}
|
|
192
|
+
if (status?.reasoning_efforts === null) return []
|
|
193
|
+
if (Array.isArray(status?.reasoning_efforts) && status.reasoning_efforts.length > 0) {
|
|
194
|
+
return status.reasoning_efforts.filter(
|
|
195
|
+
(effort): effort is string => typeof effort === "string" && effort.trim().length > 0,
|
|
196
|
+
)
|
|
197
|
+
}
|
|
198
|
+
return [...DEFAULT_EFFORTS]
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export const omlxAdapter: ModelMetadataAdapter = {
|
|
202
|
+
name: "omlx",
|
|
203
|
+
matches(entries, headers) {
|
|
204
|
+
const server = `${headers.get("server") ?? ""} ${headers.get("x-powered-by") ?? ""}`.toLowerCase()
|
|
205
|
+
return server.includes("omlx") || entries.some((entry) => entry?.owned_by === "omlx")
|
|
206
|
+
},
|
|
207
|
+
async enrich(entries, ctx) {
|
|
208
|
+
const result = await ctx.loadJSON(`${ctx.baseURL}/models/status`)
|
|
209
|
+
if (!result.available || !isRecord(result.data)) return new Map()
|
|
210
|
+
const rawList = Array.isArray(result.data.models)
|
|
211
|
+
? result.data.models
|
|
212
|
+
: Array.isArray(result.data.data)
|
|
213
|
+
? result.data.data
|
|
214
|
+
: undefined
|
|
215
|
+
if (!rawList) return new Map()
|
|
216
|
+
|
|
217
|
+
const indexed = indexOmlxStatus(rawList as RawOmlxStatusModel[])
|
|
218
|
+
const enriched = new Map<string, NormalizedModelMetadata>()
|
|
219
|
+
|
|
220
|
+
for (const entry of entries) {
|
|
221
|
+
if (typeof entry?.id !== "string") continue
|
|
222
|
+
const status = indexed.get(entry.id)
|
|
223
|
+
const metadata: NormalizedModelMetadata = {}
|
|
224
|
+
|
|
225
|
+
if (status?.is_helper === true) {
|
|
226
|
+
metadata.isChat = false
|
|
227
|
+
} else {
|
|
228
|
+
const modelType =
|
|
229
|
+
typeof status?.model_type === "string"
|
|
230
|
+
? status.model_type
|
|
231
|
+
: typeof status?.engine_type === "string"
|
|
232
|
+
? status.engine_type
|
|
233
|
+
: undefined
|
|
234
|
+
if (modelType !== undefined) {
|
|
235
|
+
metadata.isChat = CHAT_MODEL_TYPES.has(modelType)
|
|
236
|
+
if (modelType === "vlm") metadata.supportsImages = true
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const contextLimit = positiveInteger(status?.max_context_window)
|
|
241
|
+
if (contextLimit !== undefined) metadata.contextLimit = contextLimit
|
|
242
|
+
|
|
243
|
+
const outputLimit = positiveInteger(status?.max_tokens)
|
|
244
|
+
if (outputLimit !== undefined) metadata.outputLimit = outputLimit
|
|
245
|
+
|
|
246
|
+
if (entry.owned_by === "omlx") {
|
|
247
|
+
metadata.reasoningEfforts = omlxStatusReasoning(status)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
enriched.set(entry.id, metadata)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return enriched
|
|
254
|
+
},
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function parseLmStudioModels(data: unknown): Map<string, NormalizedModelMetadata> | undefined {
|
|
258
|
+
if (!isRecord(data)) return undefined
|
|
259
|
+
const rawModels = Array.isArray(data.models) ? data.models : Array.isArray(data.data) ? data.data : undefined
|
|
260
|
+
if (!rawModels) return undefined
|
|
261
|
+
|
|
262
|
+
const enriched = new Map<string, NormalizedModelMetadata>()
|
|
263
|
+
for (const item of rawModels) {
|
|
264
|
+
if (!isRecord(item)) continue
|
|
265
|
+
const id = typeof item.key === "string" ? item.key : typeof item.id === "string" ? item.id : undefined
|
|
266
|
+
if (!id) continue
|
|
267
|
+
|
|
268
|
+
const metadata: NormalizedModelMetadata = {}
|
|
269
|
+
if (typeof item.type === "string") {
|
|
270
|
+
metadata.isChat = CHAT_MODEL_TYPES.has(item.type)
|
|
271
|
+
if (item.type === "vlm") metadata.supportsImages = true
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
let loadedContext: number | undefined
|
|
275
|
+
if (Array.isArray(item.loaded_instances)) {
|
|
276
|
+
for (const instance of item.loaded_instances) {
|
|
277
|
+
if (!isRecord(instance) || !isRecord(instance.config)) continue
|
|
278
|
+
const ctxLen = positiveInteger(instance.config.context_length)
|
|
279
|
+
if (ctxLen !== undefined) {
|
|
280
|
+
loadedContext = loadedContext === undefined ? ctxLen : Math.max(loadedContext, ctxLen)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
const contextLimit = positiveInteger(loadedContext, item.loaded_context_length, item.max_context_length)
|
|
285
|
+
if (contextLimit !== undefined) metadata.contextLimit = contextLimit
|
|
286
|
+
|
|
287
|
+
const capArray = stringArray(item.capabilities)
|
|
288
|
+
const capObject = !Array.isArray(item.capabilities) && isRecord(item.capabilities) ? item.capabilities : undefined
|
|
289
|
+
if (capObject?.vision === true || capArray?.some((cap) => cap === "vision" || cap === "image") === true) {
|
|
290
|
+
metadata.supportsImages = true
|
|
291
|
+
}
|
|
292
|
+
if (typeof capObject?.trained_for_tool_use === "boolean") {
|
|
293
|
+
metadata.supportsTools = capObject.trained_for_tool_use
|
|
294
|
+
}
|
|
295
|
+
if (isRecord(capObject?.reasoning) && Array.isArray(capObject.reasoning.allowed_options)) {
|
|
296
|
+
metadata.reasoningEfforts = filterNamedEfforts(capObject.reasoning.allowed_options)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
enriched.set(id, metadata)
|
|
300
|
+
}
|
|
301
|
+
return enriched
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export const lmStudioAdapter: ModelMetadataAdapter = {
|
|
305
|
+
name: "lm-studio",
|
|
306
|
+
matches(entries, headers) {
|
|
307
|
+
const server = `${headers.get("server") ?? ""} ${headers.get("x-powered-by") ?? ""}`.toLowerCase()
|
|
308
|
+
if (server.includes("lm-studio") || server.includes("lm studio") || server.includes("lmstudio")) return true
|
|
309
|
+
return entries.some(
|
|
310
|
+
(entry) =>
|
|
311
|
+
typeof entry?.owned_by === "string" &&
|
|
312
|
+
(entry.owned_by.toLowerCase().includes("lmstudio") || entry.owned_by.toLowerCase().includes("lm-studio")),
|
|
313
|
+
)
|
|
314
|
+
},
|
|
315
|
+
async enrich(_entries, ctx) {
|
|
316
|
+
const origin = serverOriginBase(ctx.baseURL)
|
|
317
|
+
const v1 = await ctx.loadJSON(`${origin}/api/v1/models`)
|
|
318
|
+
if (v1.available) {
|
|
319
|
+
const parsed = parseLmStudioModels(v1.data)
|
|
320
|
+
if (parsed && parsed.size > 0) return parsed
|
|
321
|
+
}
|
|
322
|
+
const v0 = await ctx.loadJSON(`${origin}/api/v0/models`)
|
|
323
|
+
if (v0.available) {
|
|
324
|
+
const parsed = parseLmStudioModels(v0.data)
|
|
325
|
+
if (parsed && parsed.size > 0) return parsed
|
|
326
|
+
}
|
|
327
|
+
return new Map()
|
|
328
|
+
},
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export const llamaCppAdapter: ModelMetadataAdapter = {
|
|
332
|
+
name: "llama.cpp",
|
|
333
|
+
matches(entries, headers) {
|
|
334
|
+
const server = (headers.get("server") ?? "").toLowerCase()
|
|
335
|
+
if (server.includes("llama-cpp") || server.includes("llama.cpp") || server.includes("llama-server")) return true
|
|
336
|
+
return entries.some((entry) => entry?.owned_by === "llamacpp" || isRecord(entry?.meta))
|
|
337
|
+
},
|
|
338
|
+
async enrich(entries, ctx) {
|
|
339
|
+
// /props describes a single loaded model; only apply it when there is one model in the catalogue.
|
|
340
|
+
if (entries.length !== 1 || typeof entries[0]?.id !== "string") return new Map()
|
|
341
|
+
const origin = serverOriginBase(ctx.baseURL)
|
|
342
|
+
const result = await ctx.loadJSON(`${origin}/props`)
|
|
343
|
+
if (!result.available || !isRecord(result.data)) return new Map()
|
|
344
|
+
|
|
345
|
+
const metadata: NormalizedModelMetadata = {}
|
|
346
|
+
const defaults = isRecord(result.data.default_generation_settings)
|
|
347
|
+
? result.data.default_generation_settings
|
|
348
|
+
: undefined
|
|
349
|
+
const params = isRecord(defaults?.params) ? defaults.params : undefined
|
|
350
|
+
const contextLimit = positiveInteger(defaults?.n_ctx, params?.n_ctx)
|
|
351
|
+
if (contextLimit !== undefined) metadata.contextLimit = contextLimit
|
|
352
|
+
|
|
353
|
+
const modalities = isRecord(result.data.modalities) ? result.data.modalities : undefined
|
|
354
|
+
if (modalities?.vision === true) metadata.supportsImages = true
|
|
355
|
+
|
|
356
|
+
return new Map([[entries[0].id, metadata]])
|
|
357
|
+
},
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export const SPECIALIZED_ADAPTERS: readonly ModelMetadataAdapter[] = [omlxAdapter, lmStudioAdapter, llamaCppAdapter]
|
|
361
|
+
|
|
362
|
+
export function mergeMetadata(
|
|
363
|
+
inline: NormalizedModelMetadata,
|
|
364
|
+
enrichment: NormalizedModelMetadata | undefined,
|
|
365
|
+
): NormalizedModelMetadata {
|
|
366
|
+
if (!enrichment) return inline
|
|
367
|
+
return {
|
|
368
|
+
// Explicit non-chat classification from enrichment (e.g. oMLX is_helper or embedding status) excludes the model.
|
|
369
|
+
isChat: inline.isChat === false || enrichment.isChat === false ? false : (inline.isChat ?? enrichment.isChat),
|
|
370
|
+
supportsImages: inline.supportsImages ?? enrichment.supportsImages,
|
|
371
|
+
supportsTools: inline.supportsTools ?? enrichment.supportsTools,
|
|
372
|
+
contextLimit: inline.contextLimit ?? enrichment.contextLimit,
|
|
373
|
+
outputLimit: inline.outputLimit ?? enrichment.outputLimit,
|
|
374
|
+
reasoningEfforts: inline.reasoningEfforts ?? enrichment.reasoningEfforts,
|
|
375
|
+
}
|
|
376
|
+
}
|
package/discovery.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Model, Provider } from "@opencode/plugin"
|
|
2
|
+
import {
|
|
3
|
+
isRecord,
|
|
4
|
+
type JSONResult,
|
|
5
|
+
type NormalizedModelMetadata,
|
|
6
|
+
type RawModelEntry,
|
|
7
|
+
SPECIALIZED_ADAPTERS,
|
|
8
|
+
} from "./adapters.ts"
|
|
9
|
+
import { normalizeInventory } from "./inventory.ts"
|
|
10
|
+
|
|
11
|
+
export type DiscoverySnapshot = { available: true; models: Model.Info[] } | { available: false; reason: string }
|
|
12
|
+
|
|
13
|
+
export interface DiscoverModelsOptions {
|
|
14
|
+
baseURL: string
|
|
15
|
+
apiKey: string
|
|
16
|
+
signal: AbortSignal
|
|
17
|
+
timeoutMs: number
|
|
18
|
+
providerID: Provider.ID
|
|
19
|
+
includeModels?: ReadonlySet<string>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function loadJSON(url: string, apiKey: string, signal: AbortSignal, timeoutMs: number): Promise<JSONResult> {
|
|
23
|
+
try {
|
|
24
|
+
const response = await fetch(url, {
|
|
25
|
+
headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : undefined,
|
|
26
|
+
redirect: "error",
|
|
27
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
28
|
+
})
|
|
29
|
+
if (!response.ok) return { available: false, reason: `http-${response.status}` }
|
|
30
|
+
return { available: true, data: await response.json(), headers: response.headers ?? new Headers() }
|
|
31
|
+
} catch (error) {
|
|
32
|
+
const name = isRecord(error) ? error.name : undefined
|
|
33
|
+
return {
|
|
34
|
+
available: false,
|
|
35
|
+
reason:
|
|
36
|
+
error instanceof SyntaxError
|
|
37
|
+
? "invalid-json"
|
|
38
|
+
: name === "AbortError" || name === "TimeoutError"
|
|
39
|
+
? "aborted"
|
|
40
|
+
: "transport",
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function discoverModels({
|
|
46
|
+
baseURL,
|
|
47
|
+
apiKey,
|
|
48
|
+
signal,
|
|
49
|
+
timeoutMs,
|
|
50
|
+
providerID,
|
|
51
|
+
includeModels,
|
|
52
|
+
}: DiscoverModelsOptions): Promise<DiscoverySnapshot> {
|
|
53
|
+
const fetchJSON = (url: string) => loadJSON(url, apiKey, signal, timeoutMs)
|
|
54
|
+
const inventory = await fetchJSON(`${baseURL}/models`)
|
|
55
|
+
if (!inventory.available) {
|
|
56
|
+
return { available: false, reason: inventory.reason }
|
|
57
|
+
}
|
|
58
|
+
const rawEntries = isRecord(inventory.data) ? inventory.data.data : undefined
|
|
59
|
+
if (!Array.isArray(rawEntries) || signal.aborted) {
|
|
60
|
+
return { available: false, reason: "invalid-inventory" }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const entries = rawEntries as RawModelEntry[]
|
|
64
|
+
const adapter = SPECIALIZED_ADAPTERS.find((candidate) => candidate.matches(entries, inventory.headers))
|
|
65
|
+
const enrichment: ReadonlyMap<string, NormalizedModelMetadata> = adapter?.enrich
|
|
66
|
+
? await adapter.enrich(entries, { baseURL, headers: inventory.headers, loadJSON: fetchJSON })
|
|
67
|
+
: new Map()
|
|
68
|
+
if (signal.aborted) {
|
|
69
|
+
return { available: false, reason: "aborted" }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const models = normalizeInventory(entries, enrichment, providerID, adapter)
|
|
73
|
+
return { available: true, models: includeModels ? models.filter(({ id }) => includeModels.has(id)) : models }
|
|
74
|
+
}
|
package/index.js
ADDED
package/index.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** OpenCode V2 discovery for a local OpenAI-compatible model inventory. */
|
|
2
|
+
import { Plugin, Provider } from "@opencode/plugin"
|
|
3
|
+
import { isRecord } from "./adapters.ts"
|
|
4
|
+
import { type DiscoverySnapshot, discoverModels } from "./discovery.ts"
|
|
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, includeModels } = 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
|
+
if (
|
|
32
|
+
includeModels !== undefined &&
|
|
33
|
+
(!Array.isArray(includeModels) || includeModels.some((modelID) => typeof modelID !== "string" || !modelID.trim()))
|
|
34
|
+
) {
|
|
35
|
+
throw new Error(`includeModels for provider ${id} must be an array of non-empty model IDs`)
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
providerID: id,
|
|
39
|
+
providerName: providerName?.trim(),
|
|
40
|
+
baseURL: baseURL.trim().replace(/\/+$/, ""),
|
|
41
|
+
apiKey: typeof apiKey === "string" ? apiKey.trim() : "",
|
|
42
|
+
refreshMs: readDuration(options.refreshMs, DEFAULT_REFRESH_MS, "refreshMs", id),
|
|
43
|
+
timeoutMs: readDuration(options.timeoutMs, DEFAULT_TIMEOUT_MS, "timeoutMs", id),
|
|
44
|
+
includeModels: includeModels === undefined ? undefined : new Set<string>(includeModels),
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export default Plugin.define({
|
|
49
|
+
id: "openai-compat-provider",
|
|
50
|
+
async setup(ctx) {
|
|
51
|
+
const options = ctx.options ?? {}
|
|
52
|
+
const providers =
|
|
53
|
+
typeof options.baseURL === "string" && options.baseURL.trim() ? [readProvider(options, options.baseURL)] : []
|
|
54
|
+
if (options.providers !== undefined) {
|
|
55
|
+
if (!Array.isArray(options.providers)) throw new Error("providers must be an array")
|
|
56
|
+
for (const [index, provider] of options.providers.entries()) {
|
|
57
|
+
if (!isRecord(provider) || typeof provider.baseURL !== "string" || !provider.baseURL.trim()) {
|
|
58
|
+
throw new Error(`providers[${index}].baseURL must be a non-empty string`)
|
|
59
|
+
}
|
|
60
|
+
providers.push(readProvider(provider, provider.baseURL))
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!providers.length) return
|
|
64
|
+
if (new Set(providers.map(({ providerID }) => providerID)).size !== providers.length) {
|
|
65
|
+
throw new Error("Each configured provider must have a unique providerID")
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const controller = new AbortController()
|
|
69
|
+
const { signal } = controller
|
|
70
|
+
const sources = await Promise.all(
|
|
71
|
+
providers.map(async ({ providerID, providerName, baseURL, apiKey, refreshMs, timeoutMs, includeModels }) => {
|
|
72
|
+
const load = () => discoverModels({ baseURL, apiKey, signal, timeoutMs, providerID, includeModels })
|
|
73
|
+
return {
|
|
74
|
+
providerID,
|
|
75
|
+
providerName,
|
|
76
|
+
refreshMs,
|
|
77
|
+
settings: { baseURL, ...(apiKey ? { apiKey } : {}) },
|
|
78
|
+
load,
|
|
79
|
+
snapshot: await load(),
|
|
80
|
+
managedIDs: new Set<string>(),
|
|
81
|
+
}
|
|
82
|
+
}),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
await ctx.provider.transform((editor) => {
|
|
86
|
+
for (const source of sources) {
|
|
87
|
+
const { snapshot, managedIDs, providerID, providerName, settings } = source
|
|
88
|
+
source.managedIDs = publishSnapshot(editor, snapshot, managedIDs, providerID, RUNTIME, settings, providerName)
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
const stopRefreshing = sources.map((source) =>
|
|
93
|
+
startRefreshLifecycle({
|
|
94
|
+
signal,
|
|
95
|
+
intervalMs: source.refreshMs,
|
|
96
|
+
load: source.load,
|
|
97
|
+
shouldPublish: (next) => snapshotsDiffer(source.snapshot, next),
|
|
98
|
+
async publish(next: DiscoverySnapshot) {
|
|
99
|
+
const { snapshot, managedIDs } = source
|
|
100
|
+
source.snapshot = next
|
|
101
|
+
try {
|
|
102
|
+
await ctx.provider.reload()
|
|
103
|
+
} catch (error) {
|
|
104
|
+
source.snapshot = snapshot
|
|
105
|
+
source.managedIDs = managedIDs
|
|
106
|
+
throw error
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
onError: (error) => console.warn(`[openai-compat-provider] Failed to refresh ${source.providerID}`, error),
|
|
110
|
+
}),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return () => {
|
|
114
|
+
controller.abort()
|
|
115
|
+
for (const stop of stopRefreshing) stop()
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
})
|
package/inventory.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-openai-compatible-discovery",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"packageManager": "bun@1.4.5",
|
|
5
|
+
"description": "Discover models from OpenAI-compatible local and self-hosted endpoints in OpenCode V2.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/dinigo/opencode-openai-compatible-discovery.git"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"registry": "https://registry.npmjs.org/"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./index.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"index.js",
|
|
21
|
+
"index.ts",
|
|
22
|
+
"adapters.ts",
|
|
23
|
+
"discovery.ts",
|
|
24
|
+
"inventory.ts",
|
|
25
|
+
"lifecycle.ts",
|
|
26
|
+
"registry.ts",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "bun test",
|
|
31
|
+
"test:package": "bun scripts/smoke.mjs",
|
|
32
|
+
"lint": "biome check .",
|
|
33
|
+
"format": "biome check --write .",
|
|
34
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@opencode/plugin": "^2.4.3"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@biomejs/biome": "^2.6.9",
|
|
41
|
+
"@types/node": "^26.6.11",
|
|
42
|
+
"typescript": "^7.0.2"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/registry.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { Model, Plugin, Provider } from "@opencode/plugin"
|
|
2
|
+
import type { DiscoverySnapshot } from "./discovery.ts"
|
|
3
|
+
|
|
4
|
+
export type ProviderEditor = Parameters<Parameters<Plugin.Context["provider"]["transform"]>[0]>[0]
|
|
5
|
+
|
|
6
|
+
export function reconcileModels(
|
|
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
|
+
}
|
|
24
|
+
|
|
25
|
+
export function publishSnapshot(
|
|
26
|
+
editor: ProviderEditor,
|
|
27
|
+
snapshot: DiscoverySnapshot,
|
|
28
|
+
managedIDs: ReadonlySet<string>,
|
|
29
|
+
providerID: Provider.ID,
|
|
30
|
+
runtime: string,
|
|
31
|
+
settings: Record<string, unknown>,
|
|
32
|
+
providerName?: string,
|
|
33
|
+
): Set<string> {
|
|
34
|
+
if (!snapshot.available) return new Set(managedIDs)
|
|
35
|
+
const existing = editor.get(providerID)
|
|
36
|
+
if (existing) {
|
|
37
|
+
const reconciled = reconcileModels(existing.models, snapshot.models, managedIDs)
|
|
38
|
+
editor.update(providerID, (provider) => {
|
|
39
|
+
if (providerName !== undefined) provider.name = providerName
|
|
40
|
+
provider.package = runtime
|
|
41
|
+
provider.activation = "enabled"
|
|
42
|
+
provider.settings = { ...provider.settings, ...settings }
|
|
43
|
+
})
|
|
44
|
+
editor.models.set(providerID, reconciled.models)
|
|
45
|
+
return reconciled.managedIDs
|
|
46
|
+
}
|
|
47
|
+
if (snapshot.models.length === 0) return new Set(managedIDs)
|
|
48
|
+
editor.add({
|
|
49
|
+
info: {
|
|
50
|
+
id: providerID,
|
|
51
|
+
name: providerName ?? (providerID === "local" ? "Local" : providerID),
|
|
52
|
+
activation: "enabled",
|
|
53
|
+
package: runtime,
|
|
54
|
+
settings,
|
|
55
|
+
},
|
|
56
|
+
models: snapshot.models,
|
|
57
|
+
})
|
|
58
|
+
return new Set(snapshot.models.map((model) => model.id))
|
|
59
|
+
}
|