@joaogsbarbosa/opencode-9router 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vheins
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,490 @@
1
- # Temporary Holding Version
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.
1
+ # @joaogsbarbosa/opencode-9router
2
+
3
+ OpenCode plugin provider for [9Router](https://github.com/decolua/9router) — FREE AI Router & Token Saver. 40+ providers, 100+ models.
4
+
5
+ Registers 9Router as a custom provider in OpenCode with auto-discovery of models.
6
+
7
+ > **Dual V1 + V2 support.** This package ships a single entrypoint that works on both **OpenCode V1** (via the V1 `server` hook, OpenCode `1.18.29`+) and **OpenCode V2** (via the V2 `Plugin.define({ id, setup })` API). The discovery core is shared; only the plugin entrypoint differs. No separate package is needed.
8
+
9
+ ## Quick Start
10
+
11
+ > **Automated:** run `npx @joaogsbarbosa/opencode-9router-installer` for the
12
+ > interactive installer, or add the plugin manually below.
13
+
14
+ ### OpenCode V1
15
+
16
+ ```json
17
+ {
18
+ "$schema": "https://opencode.ai/config.json",
19
+ "plugin": ["@joaogsbarbosa/opencode-9router@latest"]
20
+ }
21
+ ```
22
+
23
+ 1. Add the plugin to `opencode.json`
24
+ 2. Restart OpenCode
25
+ 3. `/models` → select a 9Router model
26
+
27
+ ### OpenCode V2
28
+
29
+ ```json
30
+ {
31
+ "$schema": "https://opencode.ai/config.json",
32
+ "plugins": ["@joaogsbarbosa/opencode-9router@latest"]
33
+ }
34
+ ```
35
+
36
+ Or with plugin options (object form):
37
+
38
+ ```json
39
+ {
40
+ "$schema": "https://opencode.ai/config.json",
41
+ "plugins": [
42
+ {
43
+ "package": "@joaogsbarbosa/opencode-9router@latest",
44
+ "options": {
45
+ "baseURL": "http://localhost:20128",
46
+ "apiKey": "{env:ROUTER_API_KEY}",
47
+ "cache": true,
48
+ "cacheTTL": 10800000,
49
+ "discoveryTimeout": 30000
50
+ }
51
+ }
52
+ ]
53
+ }
54
+ ```
55
+
56
+ The plugin will auto-discover models from `http://localhost:20128` (default).
57
+
58
+ ## Features
59
+
60
+ - **Auto-discover models** — Models from 9Router are automatically detected on startup
61
+ - **Smart caching** — Discovery results cached for 3 hours (configurable) for instant subsequent loads
62
+ - **Stale fallback** — If the backend is unreachable, returns cached models instead of failing
63
+ - **Configurable timeout** — Adjustable discovery timeout (default 30s) for slow backends
64
+ - **Dynamic model list** — All models from 9Router are available, including custom combos
65
+ - **Combo multimodal defaults** — Combo models (`owned_by: "combo"`) that expose no capability info are forced to accept text/image/audio input with tool calling, reasoning, 256K context, 128K output, and `low`/`medium`/`high`/`xhigh`/`max`/`minimal`/`thinking` variants
66
+ - **Catalog thinking modes (V2)** — Reasoning variants from exact provider/model matches in models.dev, preserving configured overrides and combo variants
67
+ - **OpenAI-compatible** — Uses `@ai-sdk/openai-compatible` (V1) / `@opencode/ai/providers/openai-compatible` (V2)
68
+ - **Type-safe** — Uses the `config` hook (V1) / provider transforms (V2) for provider registration that conforms to the OpenCode config schema
69
+
70
+ ### Catalog thinking modes (V2)
71
+
72
+ Raw models expose effort and toggle variants from models.dev `reasoning_options`. Efforts use `reasoningEffort`; toggles use 9Router's `enable_thinking` body field and clear inherited effort with `reasoningEffort: null` in variant settings so it cannot override the toggle. The adapter omits the cleared effort from the request. Native OpenCode configuration merges variants by ID: settings/body fields you supply win, while unspecified catalog fields remain; an empty configured variants array does not remove catalog variants. Unknown controls and numeric budgets are omitted. Leaving the variant unselected preserves upstream defaults. These controls remain subject to 9Router's downstream effort rewriting and toggle handling.
73
+
74
+ `src/reasoning.ts` translates provider IDs using a subset of 9Router's [`PROVIDER_ALIASES`](https://github.com/decolua/9router/blob/89ffac5a2c8108449c432afd1ad6531578fa81cd/src/lib/modelCatalog/sync.js#L22-L40) at commit `89ffac5a2c8108449c432afd1ad6531578fa81cd` (`hunyuan` is omitted). The additional `gh` prefix comes from that revision's [GitHub provider registry](https://github.com/decolua/9router/blob/89ffac5a2c8108449c432afd1ad6531578fa81cd/open-sse/providers/registry/github.js#L1-L5). These aliases translate identities, not reasoning levels; controls still require an exact full model ID within the matched provider. Alias identity does not guarantee capability parity across authentication modes, notably Kimi's OAuth and API-key routes.
75
+
76
+ ## OpenCode V2
77
+
78
+ OpenCode V2 replaces the V1 `plugin` config key with `plugins` and the single-function plugin shape with `Plugin.define({ id, setup })`. This package handles both — the same published entrypoint is loaded by V1 and V2.
79
+
80
+ ### Configure (V2)
81
+
82
+ ```jsonc
83
+ {
84
+ "$schema": "https://opencode.ai/config.json",
85
+ "plugins": ["@joaogsbarbosa/opencode-9router@latest"]
86
+ }
87
+ ```
88
+
89
+ For a local checkout, keep the directory path in the V2 `plugins` list:
90
+
91
+ ```jsonc
92
+ {
93
+ "plugins": ["/absolute/path/to/opencode-9router"]
94
+ }
95
+ ```
96
+
97
+ The local directory must expose a root `server` entrypoint; this repository provides `server.js` for that purpose. The V1 configuration key remains `plugin` and can continue to use the published package name as shown above.
98
+
99
+ Plugin options use the object form (`{ "package": ..., "options": { ... } }`) and are read from `ctx.options`:
100
+
101
+ ```jsonc
102
+ {
103
+ "$schema": "https://opencode.ai/config.json",
104
+ "plugins": [
105
+ {
106
+ "package": "@joaogsbarbosa/opencode-9router@latest",
107
+ "options": {
108
+ "baseURL": "http://localhost:20128",
109
+ "apiKey": "{env:ROUTER_API_KEY}",
110
+ "cache": true,
111
+ "cacheTTL": 10800000,
112
+ "discoveryTimeout": 30000
113
+ }
114
+ }
115
+ ]
116
+ }
117
+ ```
118
+
119
+ ### Providers (V2)
120
+
121
+ In V2, providers are declared under the `providers` key. Each 9router-family provider uses the OpenAI-compatible runtime package and carries the endpoint in `settings.baseURL`. The plugin discovers models for every provider whose ID starts with `9router` and fills in the model list.
122
+
123
+ ```jsonc
124
+ {
125
+ "$schema": "https://opencode.ai/config.json",
126
+ "plugins": ["@joaogsbarbosa/opencode-9router@latest"],
127
+ "providers": {
128
+ "9router": {
129
+ "name": "9Router",
130
+ "package": "@opencode/ai/providers/openai-compatible",
131
+ "settings": {
132
+ "baseURL": "http://localhost:20128/v1",
133
+ "apiKey": "{env:ROUTER_API_KEY}"
134
+ }
135
+ },
136
+ "9router-remote": {
137
+ "name": "Remote 9Router",
138
+ "package": "@opencode/ai/providers/openai-compatible",
139
+ "settings": {
140
+ "baseURL": "https://your-9router-endpoint.example.com/v1"
141
+ }
142
+ }
143
+ }
144
+ }
145
+ ```
146
+
147
+ If no 9router-family provider exists, the plugin registers a default `9router` provider pointing at `http://localhost:20128`. A background refresh re-discovers models and calls `ctx.provider.reload()` every 5 minutes; the discovery interval is cleaned up when the plugin unloads.
148
+
149
+ ### Dual V1 + V2 entrypoint
150
+
151
+ The default export exposes both implementations:
152
+
153
+ ```ts
154
+ import { Plugin } from "@opencode/plugin"
155
+ import { NineRouterPlugin } from "./plugin.js" // V1
156
+ import { nineRouterV2 } from "./v2.js" // V2
157
+
158
+ const v2 = Plugin.define(nineRouterV2)
159
+ export default { id: v2.id, setup: v2.setup, server: NineRouterPlugin }
160
+ export { NineRouterPlugin }
161
+ ```
162
+
163
+ V2 reads `id`/`setup`; V1 (1.18.29+) reads `server`. The named `NineRouterPlugin` export is kept for older V1 consumers. For local development, the repository also includes a root `server.js` bridge because OpenCode resolves an absolute plugin directory through its `server` entrypoint. The published package exposes the same entry through the `./server` export.
164
+
165
+ ## Installation
166
+
167
+ ### From npm (recommended)
168
+
169
+ ```json
170
+ {
171
+ "$schema": "https://opencode.ai/config.json",
172
+ "plugins": ["@joaogsbarbosa/opencode-9router@latest"]
173
+ }
174
+ ```
175
+
176
+ No need to define a provider manually — the plugin registers it automatically. On
177
+ OpenCode V1, use the legacy `plugin` key as shown in the Quick Start above.
178
+
179
+ ### Automated install (npx)
180
+
181
+ A separate installer package ships the interactive setup. It uses
182
+ `jsonc-parser` to edit the `plugins` array and the matching `providers` entry,
183
+ preserving comments and formatting elsewhere in the file. It targets the V2
184
+ `plugins` key; on OpenCode V1, add the package to the legacy `plugin` key
185
+ manually (see Quick Start).
186
+
187
+ **Run with npx:**
188
+
189
+ ```bash
190
+ npx @joaogsbarbosa/opencode-9router-installer
191
+ ```
192
+
193
+ The interactive menu shows the current installation status (including the
194
+ effective base URL, API key, cache and timeouts) before asking what to do.
195
+
196
+ **Flags:** `--project` edits the project config instead of the global config. It
197
+ uses `./opencode.jsonc` by default, or an existing `./opencode.json` or
198
+ `.opencode/opencode.json(c)`.
199
+
200
+ **Prompts:** base URL (default `http://localhost:20128`), API key (optional),
201
+ cache (default `Y`), cache TTL in ms (default `10800000`, 3 h), discovery
202
+ timeout in ms (default `30000`). The install/configure option reads the current
203
+ values from the plugin options, or from a `providers` entry whose ID starts with
204
+ `9router` (its `settings.baseURL`/`settings.apiKey`) when one exists. The values
205
+ are pre-filled at the cursor, so pressing Enter keeps them. The connection
206
+ (`{baseURL}/v1/models`) is verified before saving.
207
+
208
+ **Menu:**
209
+
210
+ - Option 1 — `install` when not installed, `configure` when already installed.
211
+ Installs the plugin or changes the current configuration.
212
+ - Option 2 — `uninstall` removes the plugin entry and cache.
213
+ - Option 0 — `quit` exits.
214
+
215
+ **What it writes:**
216
+
217
+ ```json
218
+ {
219
+ "package": "@joaogsbarbosa/opencode-9router@latest",
220
+ "options": {
221
+ "baseURL": "...",
222
+ "apiKey": "...",
223
+ "cache": true,
224
+ "cacheTTL": 10800000,
225
+ "discoveryTimeout": 30000
226
+ }
227
+ }
228
+ ```
229
+
230
+ `apiKey` is omitted when left empty. If the plugin options contain a
231
+ `providers` array, the matching entry is updated in place. If the config already
232
+ has a `providers` entry for `9router` (or another ID starting with `9router`), the
233
+ installer also updates that entry's `settings.baseURL` and `settings.apiKey`,
234
+ since V2 prefers the provider settings over the plugin options. OpenCode installs
235
+ the package and its dependencies automatically. The uninstall option removes the
236
+ config entry and the plugin cache (`~/.cache/opencode-9router`, or
237
+ `$XDG_CACHE_HOME/opencode-9router`); a `providers` entry for `9router` is left
238
+ untouched. Requires Node 18+.
239
+
240
+ ### Multiple Providers
241
+
242
+ Add one or more 9Router-family providers with custom options:
243
+
244
+ ```json
245
+ {
246
+ "$schema": "https://opencode.ai/config.json",
247
+ "plugin": ["@joaogsbarbosa/opencode-9router@latest"],
248
+ "provider": {
249
+ "9router": {
250
+ "npm": "@ai-sdk/openai-compatible",
251
+ "name": "Your Provider",
252
+ "options": {
253
+ "baseURL": "https://your-9router-endpoint.example.com/v1",
254
+ "apiKey": "{env:ROUTER_API_KEY}",
255
+ "cache": true,
256
+ "cacheTTL": 10800000,
257
+ "discoveryTimeout": 60000
258
+ }
259
+ },
260
+ "9router-local": {
261
+ "npm": "@ai-sdk/openai-compatible",
262
+ "name": "Local Router",
263
+ "options": {
264
+ "baseURL": "http://127.0.0.1:20128/v1",
265
+ "apiKey": "sk-...",
266
+ "cache": true,
267
+ "discoveryTimeout": 60000
268
+ }
269
+ }
270
+ }
271
+ }
272
+ ```
273
+
274
+ Each provider key must start with `9router`. The `npm` must be `@ai-sdk/openai-compatible`. The `name` is a display label shown in OpenCode.
275
+
276
+ > **Never commit real API keys.** Replace the `baseURL`/`apiKey` above with your own endpoint and a placeholder such as `{env:ROUTER_API_KEY}` (or a dummy value like `sk-...`). Real keys belong in environment variables, not in `opencode.json` or this README.
277
+
278
+ ### With Environment Variable
279
+
280
+ ```json
281
+ {
282
+ "provider": {
283
+ "9router": {
284
+ "npm": "@ai-sdk/openai-compatible",
285
+ "name": "Remote 9Router",
286
+ "options": {
287
+ "baseURL": "https://example.com/v1",
288
+ "apiKey": "{env:ROUTER_API_KEY}",
289
+ "cache": true,
290
+ "discoveryTimeout": 30000
291
+ }
292
+ }
293
+ }
294
+ }
295
+ ```
296
+
297
+ ```bash
298
+ export ROUTER_API_KEY=your-api-key-here
299
+ opencode
300
+ ```
301
+
302
+ ## Provider Options
303
+
304
+ | Option | Type | Default | Description |
305
+ | --------------------- | --------- | ----------- | ------------------------------------------------------ |
306
+ | `baseURL` | `string` | `http://localhost:20128` | 9Router API endpoint |
307
+ | `apiKey` | `string` | — | API key (if required by backend) |
308
+ | `cache` | `boolean` | `true` | Cache discovery results to `~/.cache/opencode-9router/` |
309
+ | `cacheTTL` | `number` | `10800000` (3h) | Cache TTL in milliseconds |
310
+ | `discoveryTimeout` | `number` | `30000` (30s) | Timeout for `/v1/models` request in milliseconds |
311
+
312
+ ### Example with cache and timeout tuning
313
+
314
+ ```json
315
+ {
316
+ "provider": {
317
+ "9router": {
318
+ "npm": "@ai-sdk/openai-compatible",
319
+ "name": "Local Router",
320
+ "options": {
321
+ "baseURL": "http://localhost:20128",
322
+ "cache": true,
323
+ "discoveryTimeout": 60000
324
+ }
325
+ },
326
+ "9router-remote": {
327
+ "npm": "@ai-sdk/openai-compatible",
328
+ "name": "Remote API",
329
+ "options": {
330
+ "baseURL": "https://your-9router-endpoint.example.com/v1",
331
+ "apiKey": "{env:ROUTER_API_KEY}",
332
+ "cacheTTL": 3600000
333
+ }
334
+ }
335
+ }
336
+ }
337
+ ```
338
+
339
+ ### Disable cache
340
+
341
+ ```json
342
+ {
343
+ "provider": {
344
+ "9router": {
345
+ "npm": "@ai-sdk/openai-compatible",
346
+ "name": "Local Router",
347
+ "options": {
348
+ "baseURL": "http://localhost:20128",
349
+ "apiKey": "sk-...",
350
+ "cache": false,
351
+ "discoveryTimeout": 30000
352
+ }
353
+ }
354
+ }
355
+ }
356
+ ```
357
+
358
+ ## Usage
359
+
360
+ ### Select a model
361
+
362
+ ```
363
+ /models
364
+ → Find the 9Router provider
365
+ → Pick any model (e.g., kr/claude-sonnet-4.5, cc/claude-opus-4-7)
366
+ ```
367
+
368
+ ## Model Prefixes
369
+
370
+ | Prefix | Provider | Tier |
371
+ |--------|----------|------|
372
+ | `cc/` | Claude Code | Subscription |
373
+ | `cx/` | Codex | Subscription |
374
+ | `gh/` | GitHub Copilot | Subscription |
375
+ | `cu/` | Cursor IDE | Subscription |
376
+ | `kr/` | Kiro AI | **FREE** |
377
+ | `oc/` | OpenCode Free | **FREE** |
378
+ | `vertex/` | Vertex AI | $300 credits |
379
+ | `glm/` | GLM | $0.6/1M |
380
+ | `minimax/` | MiniMax | $0.2/1M |
381
+ | `kimi/` | Kimi | $9/mo flat |
382
+ | `openrouter/` | OpenRouter | API key |
383
+ | `deepseek/` | DeepSeek | API key |
384
+ | `groq/` | Groq | API key |
385
+
386
+ ## How It Works
387
+
388
+ ```
389
+ opencode.json "plugin": ["@joaogsbarbosa/opencode-9router@latest"]
390
+ ↓
391
+ Plugin loads at startup detects 9Router-family providers in config
392
+ ↓
393
+ For each provider:
394
+ 1. Check local cache (~/.cache/opencode-9router/discovery-*.json)
395
+ └─ Fresh cache (≤3h) → return cached models instantly
396
+ 2. If cache miss/stale:
397
+ └─ GET {baseURL}/v1/models with 30s timeout (configurable)
398
+ └─ If OK → register live models + save to cache
399
+ └─ If fail → fallback to stale cache (if exists), else skip
400
+ ↓
401
+ config hook creates/updates provider with discovered models
402
+ ↓
403
+ Provider appears in /models
404
+ ```
405
+
406
+ ### Cache storage
407
+
408
+ Cache files are stored at `~/.cache/opencode-9router/discovery-{base64url}.json`, one per unique `baseURL`. The cache directory also stores the models.dev capability catalog (`models-dev.json`).
409
+
410
+ ## Development
411
+
412
+ ```bash
413
+ git clone https://github.com/joaogsbarbosa/opencode-9router
414
+ cd opencode-9router
415
+ npm install
416
+ npm install --prefix installer
417
+ npm run build
418
+ node installer/install.mjs # run the installer locally
419
+ ```
420
+
421
+ ### Test
422
+
423
+ ```bash
424
+ node test-minimal.mjs
425
+ opencode models 9router --print-logs
426
+ ```
427
+
428
+ ### Validate after publish
429
+
430
+ After publishing to npm, verify the plugin works end-to-end:
431
+
432
+ ```bash
433
+ opencode models 9router-local --print-logs --log-level DEBUG
434
+ ```
435
+
436
+ This runs model discovery against the published package with full debug logging to confirm caching, timeout, and capability resolution are working correctly.
437
+
438
+ ### Publish
439
+
440
+ Plugin:
441
+
442
+ ```bash
443
+ npm login
444
+ npm version patch # or minor, major
445
+ npm publish --access public
446
+ git push --follow-tags
447
+ ```
448
+
449
+ Installer (separate package):
450
+
451
+ ```bash
452
+ cd installer
453
+ npm version patch # or minor, major
454
+ npm publish --access public
455
+ ```
456
+
457
+ ## Files
458
+
459
+ ```
460
+ opencode-9router/
461
+ src/
462
+ index.ts # Dual V1 + V2 package entry
463
+ plugin.ts # V1 plugin entry (provider registration + config hook)
464
+ v2.ts # V2 plugin entry (Plugin.define + provider transform)
465
+ v2-map.ts # V1 ModelConfig → V2 Model.Info mapping
466
+ discovery.ts # Model discovery pipeline
467
+ capabilities.ts # Capability resolution (catalog + per-model API)
468
+ cache.ts # Discovery + models.dev cache
469
+ reasoning.ts # Catalog reasoning options (effort + toggle) from models.dev
470
+ types.ts # Shared types
471
+ utils.ts # Shared helpers
472
+ constants.ts # Models, defaults, prefixes
473
+ dist/ # Compiled output (generated)
474
+ installer/
475
+ install.mjs # Interactive installer (separate npx package)
476
+ package.json # Installer package config
477
+ README.md # Installer usage
478
+ package.json # npm package config
479
+ tsconfig.json # TypeScript config
480
+ README.md # This file
481
+ LICENSE # MIT
482
+ ```
483
+
484
+ ## Links
485
+
486
+ - [npm package](https://www.npmjs.com/package/@joaogsbarbosa/opencode-9router)
487
+ - [OpenCode Plugin Docs](https://opencode.ai/docs/plugins/)
488
+ - [OpenCode Custom Provider](https://opencode.ai/docs/providers/#custom-provider)
489
+ - [9Router GitHub](https://github.com/decolua/9router)
490
+ - [9Router Website](https://9router.com)
@@ -0,0 +1,28 @@
1
+ import type { ModelConfig, ModelsDevEntry } from "./types.js";
2
+ /**
3
+ * Read a valid (fresh) discovery cache entry.
4
+ * Returns `null` if missing, stale, or corrupted.
5
+ */
6
+ export declare function readDiscoveryCache(baseURL: string, ttl: number, providerKey: string): Record<string, ModelConfig> | null;
7
+ /**
8
+ * Read a stale (expired) discovery cache entry as fallback.
9
+ */
10
+ export declare function readStaleDiscoveryCache(baseURL: string, providerKey: string): Record<string, ModelConfig> | null;
11
+ /**
12
+ * Persist discovery results to cache (best-effort).
13
+ */
14
+ export declare function writeDiscoveryCache(baseURL: string, models: Record<string, ModelConfig>, providerKey: string): void;
15
+ /**
16
+ * Fetch the models.dev capability catalog, cached for MODELS_DEV_CACHE_TTL.
17
+ * Returns the flattened entry list, or `null` when the catalog is unreachable
18
+ * and no fresh cache exists.
19
+ */
20
+ export declare function fetchModelsDevCatalog(): Promise<ModelsDevEntry[] | null>;
21
+ /**
22
+ * models.dev/api.json returns a dict of providers, each with a nested
23
+ * models dict. Flatten into a list of entries preserving catalogProvider
24
+ * for exact matching in reasoning control lookup.
25
+ */
26
+ export declare function flattenModelsDevCatalog(raw: Record<string, {
27
+ models?: Record<string, ModelsDevEntry>;
28
+ }>): ModelsDevEntry[];