opencode-openai-compatible-discovery 0.1.1 → 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 CHANGED
@@ -96,7 +96,7 @@ use `opencode-openai-compatible-discovery@0.1.0` to pin the first release once p
96
96
  bun install --frozen-lockfile
97
97
  pre-commit run --all-files
98
98
  bun test
99
- bun pm pack
99
+ npm pack
100
100
  bun run test:package ./opencode-openai-compatible-discovery-0.1.0.tgz
101
101
  ```
102
102
 
@@ -117,13 +117,13 @@ Tests and the smoke check run on the PR. Semantic-release updates the package ve
117
117
  a version bump. Update dependencies manually when needed; `bun audit` checks the Bun lockfile, including transitive
118
118
  dependencies.
119
119
 
120
+ The original `v0.1.0` GitHub release already records the first npm publication and is the versioning baseline.
121
+
120
122
  ### One-time setup
121
123
 
122
124
  1. Protect `main` with a required PR and the `Validate package` status check from GitHub Actions. Require branches to be
123
125
  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
126
+ 2. Use the GitHub environment `npm`, restricted to `main` and without required reviewers. In the npm package's
127
127
  [Trusted Publishing settings](https://docs.npmjs.com/trusted-publishers/), authorize this repository's `release.yml`
128
128
  workflow and the `npm` environment, with permission for `npm publish`. Set `NPM_RELEASES_ENABLED=true` once ready,
129
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
- export interface AdapterFetchContext {
38
+ interface AdapterFetchContext {
39
39
  baseURL: string
40
- headers: Headers
41
40
  loadJSON: (url: string) => Promise<JSONResult>
42
41
  }
43
42
 
44
- export interface ModelMetadataAdapter {
45
- readonly name: string
43
+ interface ModelMetadataAdapter {
46
44
  matches(entries: readonly RawModelEntry[], headers: Headers): boolean
47
- extract?(entry: RawModelEntry): NormalizedModelMetadata
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
- export function positiveInteger(...values: unknown[]): number | undefined {
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
- export const omlxAdapter: ModelMetadataAdapter = {
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
- export const lmStudioAdapter: ModelMetadataAdapter = {
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
- export const llamaCppAdapter: ModelMetadataAdapter = {
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
@@ -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,16 +1,17 @@
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
- export interface DiscoverModelsOptions {
14
+ interface DiscoverModelsOptions {
14
15
  baseURL: string
15
16
  apiKey: string
16
17
  signal: AbortSignal
@@ -19,6 +20,48 @@ export interface DiscoverModelsOptions {
19
20
  includeModels?: ReadonlySet<string>
20
21
  }
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))
63
+ }
64
+
22
65
  async function loadJSON(url: string, apiKey: string, signal: AbortSignal, timeoutMs: number): Promise<JSONResult> {
23
66
  try {
24
67
  const response = await fetch(url, {
@@ -61,14 +104,13 @@ export async function discoverModels({
61
104
  }
62
105
 
63
106
  const entries = rawEntries as RawModelEntry[]
107
+ // Detection and enrichment depend on the complete catalogue, before any model selection.
64
108
  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()
109
+ const enrichment = await adapter?.enrich(entries, { baseURL, loadJSON: fetchJSON })
68
110
  if (signal.aborted) {
69
111
  return { available: false, reason: "aborted" }
70
112
  }
71
113
 
72
- const models = normalizeInventory(entries, enrichment, providerID, adapter)
114
+ const models = normalizeInventory(entries, enrichment, providerID)
73
115
  return { available: true, models: includeModels ? models.filter(({ id }) => includeModels.has(id)) : models }
74
116
  }
package/index.ts CHANGED
@@ -1,118 +1,12 @@
1
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
- }
2
+ import { Plugin } from "@opencode/plugin"
3
+ import { readProviders } from "./configuration.ts"
4
+ import { startPublication } from "./publication.ts"
47
5
 
48
6
  export default Plugin.define({
49
7
  id: "openai-compat-provider",
50
8
  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
- }
9
+ const providers = readProviders(ctx.options ?? {})
10
+ if (providers.length > 0) return startPublication(providers, ctx.provider)
117
11
  },
118
12
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-openai-compatible-discovery",
3
- "version": "0.1.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
- "inventory.ts",
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 { Model, Plugin, Provider } from "@opencode/plugin"
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
- 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
- }
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
- 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)
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 = runtime
20
+ provider.package = RUNTIME
41
21
  provider.activation = "enabled"
42
22
  provider.settings = { ...provider.settings, ...settings }
43
23
  })
44
- editor.models.set(providerID, reconciled.models)
45
- return reconciled.managedIDs
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 new Set(managedIDs)
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: runtime,
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
- }