@samaluk/opencode-cliproxyapi 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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -2
  3. package/dist/index.js +417 -0
  4. package/package.json +46 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sebastián Maluk
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,84 @@
1
- # Temporary Holding Version
1
+ # CLIProxyAPI model discovery for OpenCode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Discover the CLIProxyAPI models available to your API key in OpenCode 2.3.2 or later in the 2.x series. The plugin keeps OpenCode's model registry in sync and sends generation requests through OpenCode's AI SDK integration using Chat Completions.
4
+
5
+ ## Requirements
6
+
7
+ Use a CLIProxyAPI gateway that supports Chat Completions. For full model metadata, stock CLIProxyAPI serves `GET /v1/models?client_version=cpa` with a `models` array. The gateway API key must have access to the models you want to use.
8
+
9
+ ## Install
10
+
11
+ Install the pinned package globally with the [OpenCode plugin command](https://opencode.ai/docs/plugins/#manage).
12
+
13
+ ```sh
14
+ opencode plugin add @samaluk/opencode-cliproxyapi@0.1.0
15
+ ```
16
+
17
+ To configure options or install for a project, add the package to the [`plugins` array](https://opencode.ai/docs/plugins/#configure) in the corresponding `opencode.json` or `opencode.jsonc`. If you ran the command above, edit its existing entry.
18
+
19
+ ```json
20
+ {
21
+ "$schema": "https://opencode.ai/config.json",
22
+ "plugins": [
23
+ {
24
+ "package": "@samaluk/opencode-cliproxyapi@0.1.0",
25
+ "options": {
26
+ "providerId": "cliproxyapi",
27
+ "refreshIntervalSeconds": 300
28
+ }
29
+ }
30
+ ]
31
+ }
32
+ ```
33
+
34
+ Set `CLIPROXYAPI_BASE_URL` to your gateway URL, for example `https://gateway.example`, and supply its bearer token through `CLIPROXYAPI_API_KEY`. Set both in the environment of the OpenCode process that loads the plugin. For a background OpenCode server, set them in the server's environment.
35
+
36
+ OpenCode installs the plugin and its dependencies. Run `opencode models` to see the discovered models, then select one as `cliproxyapi/<gateway-model-id>`.
37
+
38
+ ## Options
39
+
40
+ Explicit plugin options take precedence over environment defaults.
41
+
42
+ | Option | Default and behavior |
43
+ | --- | --- |
44
+ | `baseUrl` | `CLIPROXYAPI_BASE_URL`. Accepts an HTTP(S) origin or gateway path prefix, with or without a trailing `/v1`. |
45
+ | `apiKey` | `CLIPROXYAPI_API_KEY`. Use the environment to keep the key out of `opencode.json`. |
46
+ | `providerId` | `cliproxyapi`. Give each gateway configuration a dedicated provider ID. |
47
+ | `name` | `CLIProxyAPI`. Display name for the provider. |
48
+ | `refreshIntervalSeconds` | 300 seconds. Positive values below 60 are raised to 60. |
49
+ | `cacheDir` | `$XDG_CACHE_HOME/opencode-cliproxyapi` or `~/.cache/opencode-cliproxyapi`. |
50
+
51
+ ## Refresh and cache
52
+
53
+ Discovery runs at startup and on the configured interval. A changed catalog replaces the provider's models, including removing routes that disappeared, and triggers a registry reload. On authentication failure, invalid responses, or outages, the plugin uses the last valid catalog in memory or on disk. Cached catalogs have no expiration, so model availability can be stale until the gateway returns.
54
+
55
+ The cache contains selected model metadata. It uses atomic writes and owner-only file permissions (`0600` on POSIX systems), with separate files per normalized gateway URL and key. The bearer stays out of the cache, provider registry, and plugin diagnostics. Requests attach the bearer only at the configured origin and reject redirects. Use HTTPS for remote gateways.
56
+
57
+ ## Catalog support
58
+
59
+ Full discovery hides routes marked `visibility: hide`, preserves reported limits and recognized modalities, and maps advertised reasoning efforts to OpenCode variants. The advertised default applies when you select no variant. Pricing is reported as zero because the catalog supplies no pricing. Missing limits default to 8,192 context tokens and up to 4,096 output tokens.
60
+
61
+ If the rich endpoint is unsupported or returns a plain model list, the plugin requests `/v1/models` and appends `(ID only)` to the display names. This fallback has no visibility, reasoning, or capability metadata, so it can include routes that rich discovery would hide.
62
+
63
+ ## Releasing
64
+
65
+ For the first release, create a short-lived [granular access token](https://docs.npmjs.com/creating-and-viewing-access-tokens) on npmjs.com with **Read and write (publish and stage)** access to the `@samaluk` scope. Leave **Bypass 2FA** off. Run these commands from the repository root with Bun 1.4.5. Paste the token when prompted. Bun opens a browser for two-factor authentication if npm requests it. For a one-time code, append `--otp <code>` to the publish command.
66
+
67
+ ```sh
68
+ (
69
+ bun install --frozen-lockfile &&
70
+ bun run check &&
71
+ bun test &&
72
+ bun run build &&
73
+ bun pm pack --dry-run &&
74
+ printf 'npm publish token: ' &&
75
+ IFS= read -rs npm_publish_token &&
76
+ printf '\n' &&
77
+ NPM_CONFIG_USERCONFIG=/dev/null NPM_CONFIG_TOKEN="${npm_publish_token:?Token required}" \
78
+ bun publish --no-env-file --registry https://registry.npmjs.org --access public
79
+ )
80
+ ```
81
+
82
+ For automated releases, add a trusted publisher once the package exists: on npmjs.com open the package's **Settings → Trusted publishing**, choose **GitHub Actions**, and enter owner `samaluk`, repository `opencode-cliproxyapi` and workflow `release.yml`, leaving the environment blank. Then bump the version in `package.json`, push the commit, and push a matching tag such as `v0.1.1`.
83
+
84
+ The release workflow builds and tests with Bun and uploads with `pnpm publish`, which uses npm trusted publishing (GitHub Actions OIDC) and attaches provenance. No npm token or repository secret is needed. Bun 1.4.5 cannot use trusted publishing, and npm [retires direct publishing with granular tokens in January 2027](https://docs.npmjs.com/about-access-tokens#direct-publishing-is-being-deprecated).
package/dist/index.js ADDED
@@ -0,0 +1,417 @@
1
+ // src/index.ts
2
+ import { randomUUID as randomUUID2 } from "node:crypto";
3
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
4
+ import { Plugin } from "@opencode/plugin";
5
+
6
+ // src/catalog.ts
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import { constants } from "node:fs";
9
+ import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
10
+ import { homedir } from "node:os";
11
+ import { join } from "node:path";
12
+ var efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"];
13
+ var modalities = ["text", "image", "audio", "video", "pdf"];
14
+ var fallbackContext = 8192;
15
+ var fallbackOutput = 4096;
16
+ var unsupportedStatuses = [400, 404, 406, 422, 501];
17
+ function record(value, message = "Invalid CLIProxyAPI catalog") {
18
+ if (typeof value !== "object" || value === null || Array.isArray(value))
19
+ throw new Error(message);
20
+ return value;
21
+ }
22
+ function stringOption(value, name) {
23
+ if (value === undefined)
24
+ return;
25
+ if (typeof value !== "string" || value.trim() === "")
26
+ throw new Error(`Invalid ${name} option`);
27
+ return value;
28
+ }
29
+ function providerID(value) {
30
+ const id = stringOption(value, "providerId") ?? "cliproxyapi";
31
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(id))
32
+ throw new Error("Invalid providerId option");
33
+ return id;
34
+ }
35
+ function normalizeBaseUrl(value) {
36
+ let url;
37
+ try {
38
+ url = new URL(value);
39
+ } catch {
40
+ throw new Error("Invalid CLIProxyAPI base URL");
41
+ }
42
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || /[?#]/.test(value)) {
43
+ throw new Error("CLIProxyAPI requires an HTTP(S) base URL without credentials, query, or fragment");
44
+ }
45
+ const prefix = url.pathname.replace(/\/+$/, "").replace(/(?:\/v1)+$/, "").replace(/\/+$/, "");
46
+ return url.origin + prefix + "/v1";
47
+ }
48
+ function resolveConnection(options, env = process.env) {
49
+ const baseUrl = stringOption(options.baseUrl, "baseUrl") ?? env.CLIPROXYAPI_BASE_URL;
50
+ const apiKey = stringOption(options.apiKey, "apiKey") ?? env.CLIPROXYAPI_API_KEY;
51
+ if (!baseUrl || !apiKey)
52
+ throw new Error("Set CLIPROXYAPI_BASE_URL and CLIPROXYAPI_API_KEY or pass options");
53
+ if (!/^[A-Za-z0-9._~+/-]+=*$/.test(apiKey))
54
+ throw new Error("Invalid CLIProxyAPI bearer token");
55
+ return { baseUrl: normalizeBaseUrl(baseUrl), apiKey };
56
+ }
57
+ function defaultCacheDir(packageName) {
58
+ const root = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
59
+ return join(root, packageName);
60
+ }
61
+ function gatewayFetch({ baseUrl, apiKey }, fetcher = fetch) {
62
+ const origin = new URL(baseUrl).origin;
63
+ return (input, init) => {
64
+ const url = new URL(input instanceof Request ? input.url : input);
65
+ if (url.origin !== origin || url.username || url.password)
66
+ throw new Error("CLIProxyAPI request changed origin");
67
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
68
+ headers.set("authorization", `Bearer ${apiKey}`);
69
+ return fetcher(input, { ...init, headers, redirect: "error" });
70
+ };
71
+ }
72
+ function getID(value, seen) {
73
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:+@-]*(?:\/[A-Za-z0-9][A-Za-z0-9._:+@-]*)*$/.test(value)) {
74
+ throw new Error("Invalid CLIProxyAPI model ID");
75
+ }
76
+ if (seen.has(value))
77
+ throw new Error("Duplicate CLIProxyAPI model ID");
78
+ seen.add(value);
79
+ return value;
80
+ }
81
+ function nameOf(value, id) {
82
+ if (value == null)
83
+ return id;
84
+ if (typeof value !== "string" || !value.trim() || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value)) {
85
+ throw new Error("Invalid CLIProxyAPI display name");
86
+ }
87
+ return value.trim();
88
+ }
89
+ function tokenLimit(value, fallback) {
90
+ if (value == null)
91
+ return fallback;
92
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
93
+ throw new Error("Invalid CLIProxyAPI token limit");
94
+ }
95
+ return value;
96
+ }
97
+ function selectModalities(value) {
98
+ if (value == null)
99
+ return ["text"];
100
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
101
+ throw new Error("Invalid CLIProxyAPI modality list");
102
+ }
103
+ return modalities.filter((modality) => value.includes(modality));
104
+ }
105
+ function selectEfforts(value) {
106
+ if (value == null)
107
+ return [];
108
+ if (!Array.isArray(value))
109
+ throw new Error("Invalid CLIProxyAPI reasoning list");
110
+ const advertised = value.map((item) => record(item).effort);
111
+ if (!advertised.every((effort) => typeof effort === "string")) {
112
+ throw new Error("Invalid CLIProxyAPI reasoning effort");
113
+ }
114
+ return efforts.filter((effort) => advertised.includes(effort));
115
+ }
116
+ function sortModels(models) {
117
+ return models.sort((left, right) => left.id < right.id ? -1 : Number(left.id > right.id));
118
+ }
119
+ function richCatalog(rows) {
120
+ if (!Array.isArray(rows))
121
+ throw new Error("Invalid CLIProxyAPI rich catalog");
122
+ const seen = new Set;
123
+ const models = [];
124
+ for (const entry of rows) {
125
+ const row = record(entry);
126
+ const id = getID(row.slug, seen);
127
+ if (row.visibility === "hide")
128
+ continue;
129
+ if (row.visibility != null && row.visibility !== "list")
130
+ throw new Error("Invalid CLIProxyAPI model visibility");
131
+ const contextWindow = tokenLimit(row.context_window, fallbackContext);
132
+ const supported = selectEfforts(row.supported_reasoning_levels);
133
+ const defaultEffort = supported.find((effort) => effort === row.default_reasoning_level);
134
+ if (row.default_reasoning_level != null && typeof row.default_reasoning_level !== "string") {
135
+ throw new Error("Invalid CLIProxyAPI reasoning default");
136
+ }
137
+ if (row.supports_tool_use != null && typeof row.supports_tool_use !== "boolean") {
138
+ throw new Error("Invalid CLIProxyAPI tool capability");
139
+ }
140
+ models.push({
141
+ id,
142
+ name: nameOf(row.display_name, id),
143
+ contextWindow,
144
+ maxTokens: tokenLimit(row.max_tokens, Math.min(fallbackOutput, contextWindow)),
145
+ input: selectModalities(row.input_modalities),
146
+ output: selectModalities(row.output_modalities),
147
+ efforts: supported,
148
+ defaultEffort,
149
+ tools: row.supports_tool_use ?? undefined
150
+ });
151
+ }
152
+ return { mode: "rich", models: sortModels(models) };
153
+ }
154
+ function degradedCatalog(rows) {
155
+ if (!Array.isArray(rows))
156
+ throw new Error("Invalid CLIProxyAPI ID-only catalog");
157
+ const seen = new Set;
158
+ const models = rows.map((entry) => {
159
+ const id = getID(record(entry).id, seen);
160
+ return {
161
+ id,
162
+ name: `${id} (ID only)`,
163
+ contextWindow: fallbackContext,
164
+ maxTokens: fallbackOutput,
165
+ input: ["text"],
166
+ output: ["text"],
167
+ efforts: []
168
+ };
169
+ });
170
+ return { mode: "degraded", models: sortModels(models) };
171
+ }
172
+ async function fetchCatalog(connection, signal, fetcher) {
173
+ const send = gatewayFetch(connection, fetcher);
174
+ const timeout = AbortSignal.timeout(1e4);
175
+ const init = { signal: signal ? AbortSignal.any([timeout, signal]) : timeout, headers: { accept: "application/json" } };
176
+ const endpoint = `${connection.baseUrl}/models`;
177
+ const rich = await send(`${endpoint}?client_version=cpa`, init);
178
+ if (rich.ok) {
179
+ const document = record(await rich.json());
180
+ if (Object.hasOwn(document, "models"))
181
+ return checkedCatalog(richCatalog(document.models), connection.apiKey);
182
+ if (!Array.isArray(document.data))
183
+ throw new Error("Unrecognized CLIProxyAPI catalog");
184
+ } else {
185
+ await rich.body?.cancel();
186
+ if (!unsupportedStatuses.includes(rich.status))
187
+ throw new Error("CLIProxyAPI rich catalog request failed");
188
+ }
189
+ const plain = await send(endpoint, init);
190
+ if (!plain.ok) {
191
+ await plain.body?.cancel();
192
+ throw new Error("CLIProxyAPI ID-only catalog request failed");
193
+ }
194
+ return checkedCatalog(degradedCatalog(record(await plain.json()).data), connection.apiKey);
195
+ }
196
+ function checkedCatalog(catalog, key) {
197
+ if (catalog.models.some(({ id, name }) => id === key || name === key || name.includes(`Bearer ${key}`) || key.length >= 16 && (id.includes(key) || name.includes(key)))) {
198
+ throw new Error("CLIProxyAPI catalog echoed its credential");
199
+ }
200
+ return catalog;
201
+ }
202
+ function encodeCache(catalog) {
203
+ const rows = catalog.mode === "degraded" ? catalog.models.map(({ id }) => ({ id })) : catalog.models.map((model) => ({
204
+ slug: model.id,
205
+ display_name: model.name,
206
+ context_window: model.contextWindow,
207
+ max_tokens: model.maxTokens,
208
+ input_modalities: model.input,
209
+ output_modalities: model.output,
210
+ supported_reasoning_levels: model.efforts.map((effort) => ({ effort })),
211
+ default_reasoning_level: model.defaultEffort,
212
+ supports_tool_use: model.tools
213
+ }));
214
+ return JSON.stringify({ version: 1, mode: catalog.mode, rows }) + `
215
+ `;
216
+ }
217
+ async function readCache(path, key) {
218
+ try {
219
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
220
+ try {
221
+ const stat = await file.stat();
222
+ if (!stat.isFile() || (stat.mode & 511) !== 384 || stat.uid !== process.getuid?.())
223
+ return;
224
+ const { version, mode, rows } = record(JSON.parse(await file.readFile("utf8")));
225
+ if (version !== 1)
226
+ return;
227
+ if (mode === "rich")
228
+ return checkedCatalog(richCatalog(rows), key);
229
+ if (mode === "degraded")
230
+ return checkedCatalog(degradedCatalog(rows), key);
231
+ } finally {
232
+ await file.close();
233
+ }
234
+ } catch {
235
+ return;
236
+ }
237
+ }
238
+ async function writeCache(directory, path, contents) {
239
+ await mkdir(directory, { recursive: true, mode: 448 });
240
+ const tempPath = join(directory, `.${randomUUID()}.tmp`);
241
+ try {
242
+ await writeFile(tempPath, contents, { flag: "wx", mode: 384 });
243
+ await rename(tempPath, path);
244
+ } finally {
245
+ await rm(tempPath, { force: true });
246
+ }
247
+ }
248
+ function createDiscovery(connection, cacheDir, fetcher) {
249
+ const identity = createHash("sha256").update(connection.baseUrl).update("\x00").update(connection.apiKey).digest("hex");
250
+ const path = join(cacheDir, `catalog-v1-${identity}.json`);
251
+ let lastGood;
252
+ let lastWritten;
253
+ return async (signal) => {
254
+ let catalog;
255
+ try {
256
+ catalog = await fetchCatalog(connection, signal, fetcher);
257
+ } catch {
258
+ signal?.throwIfAborted();
259
+ const cached = lastGood ?? await readCache(path, connection.apiKey);
260
+ signal?.throwIfAborted();
261
+ if (!cached)
262
+ throw new Error("CLIProxyAPI catalog unavailable and no private cache is readable");
263
+ lastGood = cached;
264
+ return { catalog: cached, source: "cache" };
265
+ }
266
+ signal?.throwIfAborted();
267
+ lastGood = catalog;
268
+ const contents = encodeCache(catalog);
269
+ try {
270
+ if (contents !== lastWritten) {
271
+ await writeCache(cacheDir, path, contents);
272
+ lastWritten = contents;
273
+ }
274
+ return { catalog, source: "live" };
275
+ } catch {
276
+ return { catalog, source: "live", cacheWriteFailed: true };
277
+ }
278
+ };
279
+ }
280
+ function warnOnDiscoveryStatus(label) {
281
+ let previous;
282
+ return (status) => {
283
+ const notes = [];
284
+ if (!status)
285
+ notes.push("catalog unavailable and no private cache is readable");
286
+ if (status?.source === "cache")
287
+ notes.push("using the cached catalog");
288
+ if (status?.catalog.mode === "degraded")
289
+ notes.push("degraded catalog (IDs only)");
290
+ if (status?.cacheWriteFailed)
291
+ notes.push("could not update the private catalog cache");
292
+ const message = notes.join(". ");
293
+ if (message && message !== previous)
294
+ console.warn(`[${label}] ${message}.`);
295
+ previous = message;
296
+ };
297
+ }
298
+
299
+ // src/index.ts
300
+ var packageName = "opencode-cliproxyapi";
301
+ var sdkPackage = `aisdk:${packageName}`;
302
+ var zero = 0;
303
+ function toModel(providerId, row, mode) {
304
+ const id = row.id;
305
+ return {
306
+ id,
307
+ modelID: id,
308
+ providerID: providerId,
309
+ name: row.name,
310
+ capabilities: { tools: row.tools ?? mode === "rich", input: row.input, output: row.output },
311
+ limit: { context: row.contextWindow, output: row.maxTokens },
312
+ cost: [{ input: zero, output: zero, cache: { read: zero, write: zero } }],
313
+ time: { released: 0 },
314
+ status: "active",
315
+ enabled: true,
316
+ body: row.defaultEffort === undefined ? undefined : { reasoning_effort: row.defaultEffort },
317
+ variants: row.efforts.map((effort) => ({
318
+ id: effort,
319
+ body: { reasoning_effort: effort }
320
+ }))
321
+ };
322
+ }
323
+ function intervalMs(option) {
324
+ if (option === undefined)
325
+ return 300000;
326
+ if (typeof option !== "number" || !Number.isFinite(option) || option <= 0 || option > 2147483) {
327
+ throw new Error("Invalid refreshIntervalSeconds option");
328
+ }
329
+ return Math.max(60000, Math.round(option * 1000));
330
+ }
331
+ var src_default = Plugin.define({
332
+ id: packageName,
333
+ async setup(ctx) {
334
+ const options = ctx.options;
335
+ const connection = resolveConnection(options);
336
+ const id = providerID(options.providerId);
337
+ const name = stringOption(options.name, "name") ?? "CLIProxyAPI";
338
+ const interval = intervalMs(options.refreshIntervalSeconds);
339
+ const cacheDir = stringOption(options.cacheDir, "cacheDir") ?? defaultCacheDir(packageName);
340
+ const discover = createDiscovery(connection, cacheDir);
341
+ const report = warnOnDiscoveryStatus(packageName);
342
+ const lifetime = new AbortController;
343
+ const instance = randomUUID2();
344
+ await ctx.aisdk.hook("sdk", (event) => {
345
+ if (event.package !== packageName)
346
+ return;
347
+ const sdk = createOpenAICompatible({
348
+ name: id,
349
+ baseURL: connection.baseUrl,
350
+ fetch: gatewayFetch(connection, event.options.fetch)
351
+ });
352
+ event.sdk = { languageModel: sdk.chatModel };
353
+ }, { providerID: id });
354
+ let catalog;
355
+ try {
356
+ const initial = await discover(lifetime.signal);
357
+ report(initial);
358
+ catalog = initial.catalog;
359
+ } catch {
360
+ report();
361
+ }
362
+ await ctx.provider.transform((editor) => {
363
+ const snapshot = catalog;
364
+ if (!snapshot)
365
+ return;
366
+ editor.update(id, (provider) => {
367
+ provider.name = name;
368
+ provider.activation = "enabled";
369
+ provider.package = sdkPackage;
370
+ provider.canonical = undefined;
371
+ provider.integrationID = undefined;
372
+ provider.headers = undefined;
373
+ provider.body = undefined;
374
+ provider.settings = { baseURL: connection.baseUrl, cpaDiscoveryInstance: instance };
375
+ });
376
+ editor.models.set(id, snapshot.models.map((model) => toModel(id, model, snapshot.mode)));
377
+ });
378
+ let published = JSON.stringify(catalog);
379
+ let pending;
380
+ const refresh = () => {
381
+ pending ??= (async () => {
382
+ try {
383
+ const result = await discover(lifetime.signal);
384
+ if (lifetime.signal.aborted)
385
+ return;
386
+ report(result);
387
+ const signature = JSON.stringify(result.catalog);
388
+ if (signature === published)
389
+ return;
390
+ catalog = result.catalog;
391
+ try {
392
+ await ctx.provider.reload();
393
+ published = signature;
394
+ } catch {
395
+ console.warn(`[${packageName}] could not reload the model registry. Retrying on the next refresh.`);
396
+ }
397
+ } catch {
398
+ if (!lifetime.signal.aborted)
399
+ report();
400
+ }
401
+ })().finally(() => {
402
+ pending = undefined;
403
+ });
404
+ return pending;
405
+ };
406
+ const timer = setInterval(refresh, interval);
407
+ timer.unref();
408
+ return async () => {
409
+ clearInterval(timer);
410
+ lifetime.abort();
411
+ await pending;
412
+ };
413
+ }
414
+ });
415
+ export {
416
+ src_default as default
417
+ };
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@samaluk/opencode-cliproxyapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Live CLIProxyAPI model discovery for OpenCode 2",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "exports": {
9
+ ".": "./dist/index.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "keywords": [
17
+ "opencode",
18
+ "opencode-plugin",
19
+ "cliproxyapi",
20
+ "model discovery"
21
+ ],
22
+ "dependencies": {
23
+ "@ai-sdk/openai-compatible": "^2.0.94",
24
+ "@opencode/plugin": "^2.3.2"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/samaluk/opencode-cliproxyapi.git"
29
+ },
30
+ "homepage": "https://github.com/samaluk/opencode-cliproxyapi#readme",
31
+ "bugs": {
32
+ "url": "https://github.com/samaluk/opencode-cliproxyapi/issues"
33
+ },
34
+ "engines": {
35
+ "node": ">=22"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "devDependencies": {
41
+ "@types/bun": "1.4.5",
42
+ "typescript": "5.9.3"
43
+ },
44
+ "scripts": {
45
+ "build": "bun build src/index.ts --outdir dist --target node --packages external",
46
+ "check": "tsc --noEmit",
47
+ "test": "bun test"
48
+ }
6
49
  }