@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 +21 -0
- package/README.md +490 -3
- package/dist/cache.d.ts +28 -0
- package/dist/cache.js +168 -0
- package/dist/capabilities.d.ts +50 -0
- package/dist/capabilities.js +300 -0
- package/dist/constants.d.ts +43 -0
- package/dist/constants.js +106 -0
- package/dist/discovery.d.ts +9 -0
- package/dist/discovery.js +145 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +21 -0
- package/dist/plugin.d.ts +7 -0
- package/dist/plugin.js +85 -0
- package/dist/reasoning.d.ts +15 -0
- package/dist/reasoning.js +58 -0
- package/dist/types.d.ts +98 -0
- package/dist/types.js +2 -0
- package/dist/utils.d.ts +21 -0
- package/dist/utils.js +38 -0
- package/dist/v2-map.d.ts +19 -0
- package/dist/v2-map.js +104 -0
- package/dist/v2.d.ts +17 -0
- package/dist/v2.js +316 -0
- package/package.json +58 -6
- package/server.js +9 -0
package/dist/v2.js
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { Plugin, Provider } from "@opencode/plugin";
|
|
2
|
+
import { DEFAULT_BASE_URL, DISCOVERY_CACHE_TTL, DISCOVERY_TIMEOUT, PLUGIN_NAME, PROVIDER_DISPLAY_NAME, } from "./constants.js";
|
|
3
|
+
import { discoverModels } from "./discovery.js";
|
|
4
|
+
import { ensureAPIPath, normalizeBaseURL } from "./utils.js";
|
|
5
|
+
import { toModelInfos } from "./v2-map.js";
|
|
6
|
+
// ── OpenCode V2 Plugin ──────────────────────────────────────
|
|
7
|
+
/** Runtime package used for OpenAI-compatible providers in OpenCode V2. */
|
|
8
|
+
export const OPENAI_COMPATIBLE_PACKAGE = "@opencode/ai/providers/openai-compatible";
|
|
9
|
+
/** How often captured discovery data is refreshed and replayed. */
|
|
10
|
+
export const REFRESH_INTERVAL = 5 * 60 * 1000;
|
|
11
|
+
/** Bounded retries for config providers registered after external plugin setup. */
|
|
12
|
+
export const CONFIG_PROVIDER_RETRY_DELAYS = [0, 100, 500, 1500, 5000];
|
|
13
|
+
/** Delay before retrying a refresh whose provider publication failed. */
|
|
14
|
+
export const REFRESH_RETRY_DELAY = 1000;
|
|
15
|
+
/** Consecutive publication retries allowed before waiting for an external trigger. */
|
|
16
|
+
export const MAX_REFRESH_RETRIES = 1;
|
|
17
|
+
// ── Coercion helpers ────────────────────────────────────────
|
|
18
|
+
/** Coerce an unknown value to a non-empty string when possible. */
|
|
19
|
+
function asString(value) {
|
|
20
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
21
|
+
}
|
|
22
|
+
/** Coerce an unknown value to a finite number when possible. */
|
|
23
|
+
function asNumber(value) {
|
|
24
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
25
|
+
}
|
|
26
|
+
/** Coerce an unknown value to a boolean when possible. */
|
|
27
|
+
function asBoolean(value) {
|
|
28
|
+
return typeof value === "boolean" ? value : undefined;
|
|
29
|
+
}
|
|
30
|
+
/** Check whether a value is a non-null object with string keys. */
|
|
31
|
+
function isRecord(value) {
|
|
32
|
+
return typeof value === "object" && value !== null;
|
|
33
|
+
}
|
|
34
|
+
/** Extract a provider target from a V2 ProviderRecord or a legacy record. */
|
|
35
|
+
function toExistingProvider(value) {
|
|
36
|
+
if (!isRecord(value)) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const provider = isRecord(value.provider) ? value.provider : value;
|
|
40
|
+
const id = asString(provider.id);
|
|
41
|
+
if (!id) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
id,
|
|
46
|
+
name: asString(provider.name) ?? id,
|
|
47
|
+
settings: isRecord(provider.settings) ? provider.settings : undefined,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** Normalize provider list results across supported OpenCode API shapes. */
|
|
51
|
+
function normalizeProviderList(value) {
|
|
52
|
+
const entries = Array.isArray(value)
|
|
53
|
+
? value
|
|
54
|
+
: isRecord(value) && Array.isArray(value.data)
|
|
55
|
+
? value.data
|
|
56
|
+
: [];
|
|
57
|
+
return entries
|
|
58
|
+
.map(toExistingProvider)
|
|
59
|
+
.filter((provider) => provider !== undefined);
|
|
60
|
+
}
|
|
61
|
+
// ── Target resolution ───────────────────────────────────────
|
|
62
|
+
/**
|
|
63
|
+
* Resolve the set of 9router-family providers to manage. Explicit plugin
|
|
64
|
+
* options win, existing provider records (whose id starts with `9router`) are
|
|
65
|
+
* merged in, and a default `9router` provider is registered when nothing else
|
|
66
|
+
* is configured — mirroring the V1 config-hook fallback.
|
|
67
|
+
*/
|
|
68
|
+
function resolveTargets(existing, options) {
|
|
69
|
+
const targets = new Map();
|
|
70
|
+
const optCache = asBoolean(options.cache) ?? true;
|
|
71
|
+
const optCacheTTL = asNumber(options.cacheTTL) ?? DISCOVERY_CACHE_TTL;
|
|
72
|
+
const optTimeout = asNumber(options.discoveryTimeout) ?? DISCOVERY_TIMEOUT;
|
|
73
|
+
// 1. Explicit `providers` array from plugin options.
|
|
74
|
+
const optProviders = Array.isArray(options.providers) ? options.providers : [];
|
|
75
|
+
for (const raw of optProviders) {
|
|
76
|
+
if (!raw || typeof raw !== "object")
|
|
77
|
+
continue;
|
|
78
|
+
const entry = raw;
|
|
79
|
+
const key = asString(entry.key) ?? asString(entry.id) ?? PLUGIN_NAME;
|
|
80
|
+
targets.set(key, {
|
|
81
|
+
key,
|
|
82
|
+
name: asString(entry.name) ??
|
|
83
|
+
(key === PLUGIN_NAME ? PROVIDER_DISPLAY_NAME : key),
|
|
84
|
+
baseURL: asString(entry.baseURL) ?? DEFAULT_BASE_URL,
|
|
85
|
+
apiKey: asString(entry.apiKey),
|
|
86
|
+
cacheEnabled: asBoolean(entry.cache) ?? optCache,
|
|
87
|
+
cacheTTL: asNumber(entry.cacheTTL) ?? optCacheTTL,
|
|
88
|
+
discoveryTimeout: asNumber(entry.discoveryTimeout) ?? optTimeout,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
// 2. Existing provider records for 9router-family providers.
|
|
92
|
+
for (const info of existing) {
|
|
93
|
+
const id = info?.id;
|
|
94
|
+
if (typeof id !== "string" || !id.startsWith(PLUGIN_NAME))
|
|
95
|
+
continue;
|
|
96
|
+
if (targets.has(id))
|
|
97
|
+
continue;
|
|
98
|
+
const settings = (info.settings ?? {});
|
|
99
|
+
targets.set(id, {
|
|
100
|
+
key: id,
|
|
101
|
+
name: asString(info.name) ?? (id === PLUGIN_NAME ? PROVIDER_DISPLAY_NAME : id),
|
|
102
|
+
baseURL: asString(settings.baseURL) ?? DEFAULT_BASE_URL,
|
|
103
|
+
apiKey: asString(settings.apiKey),
|
|
104
|
+
cacheEnabled: optCache,
|
|
105
|
+
cacheTTL: optCacheTTL,
|
|
106
|
+
discoveryTimeout: optTimeout,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
// 3. Fallback: register the default provider from plugin options.
|
|
110
|
+
if (targets.size === 0) {
|
|
111
|
+
targets.set(PLUGIN_NAME, {
|
|
112
|
+
key: PLUGIN_NAME,
|
|
113
|
+
name: PROVIDER_DISPLAY_NAME,
|
|
114
|
+
baseURL: asString(options.baseURL) ?? DEFAULT_BASE_URL,
|
|
115
|
+
apiKey: asString(options.apiKey),
|
|
116
|
+
cacheEnabled: optCache,
|
|
117
|
+
cacheTTL: optCacheTTL,
|
|
118
|
+
discoveryTimeout: optTimeout,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
return Array.from(targets.values());
|
|
122
|
+
}
|
|
123
|
+
/** Build the V2 provider info record for a target. */
|
|
124
|
+
function buildProviderInfo(key, name, apiURL, apiKey) {
|
|
125
|
+
return {
|
|
126
|
+
...Provider.Info.empty(Provider.ID.make(key)),
|
|
127
|
+
name,
|
|
128
|
+
activation: "enabled",
|
|
129
|
+
package: OPENAI_COMPATIBLE_PACKAGE,
|
|
130
|
+
settings: {
|
|
131
|
+
baseURL: apiURL,
|
|
132
|
+
...(apiKey ? { apiKey } : {}),
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* OpenCode V2 plugin for 9Router. Discovers models for every 9router-family
|
|
138
|
+
* provider, injects them through provider and model transforms, and refreshes
|
|
139
|
+
* captured inventories as config providers and model lists change.
|
|
140
|
+
*/
|
|
141
|
+
export const nineRouterV2 = Plugin.define({
|
|
142
|
+
id: PLUGIN_NAME,
|
|
143
|
+
async setup(ctx) {
|
|
144
|
+
const log = async (level, message) => {
|
|
145
|
+
const line = `[9router-provider] ${message}`;
|
|
146
|
+
if (level === "error") {
|
|
147
|
+
console.error(line);
|
|
148
|
+
}
|
|
149
|
+
else if (level === "warn") {
|
|
150
|
+
console.warn(line);
|
|
151
|
+
}
|
|
152
|
+
else if (level === "info") {
|
|
153
|
+
console.log(line);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const source = { providers: [] };
|
|
157
|
+
let disposed = false;
|
|
158
|
+
let refreshRunning = false;
|
|
159
|
+
let refreshPending = false;
|
|
160
|
+
let refreshTask;
|
|
161
|
+
let refreshRetryTimer;
|
|
162
|
+
let refreshRetriesLeft = MAX_REFRESH_RETRIES;
|
|
163
|
+
/** Discover and map models for the given resolved targets. */
|
|
164
|
+
const discoverTargets = async (resolvedTargets) => {
|
|
165
|
+
const results = await Promise.all(resolvedTargets.map(async (target) => {
|
|
166
|
+
const normalizedURL = normalizeBaseURL(target.baseURL);
|
|
167
|
+
const apiURL = ensureAPIPath(normalizedURL);
|
|
168
|
+
const models = await discoverModels(normalizedURL, target.apiKey, target.cacheEnabled, target.cacheTTL, target.discoveryTimeout, target.key, log);
|
|
169
|
+
if (models) {
|
|
170
|
+
log("info", `[${target.key}] Discovered ${Object.keys(models).length} models from ${apiURL}`);
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
log("warn", `[${target.key}] Failed to discover models from ${apiURL}. Check if the service is running and accessible.`);
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
key: target.key,
|
|
177
|
+
info: buildProviderInfo(target.key, target.name, apiURL, target.apiKey),
|
|
178
|
+
models: toModelInfos(target.key, models ?? {}),
|
|
179
|
+
};
|
|
180
|
+
}));
|
|
181
|
+
return results;
|
|
182
|
+
};
|
|
183
|
+
/** Re-list providers, rediscover models, and replay the transforms. */
|
|
184
|
+
const refresh = async () => {
|
|
185
|
+
let existing = [];
|
|
186
|
+
try {
|
|
187
|
+
const listed = await ctx.provider.list();
|
|
188
|
+
existing = normalizeProviderList(listed);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
log("warn", "[9router-provider] Unable to list existing providers; using options/defaults");
|
|
192
|
+
}
|
|
193
|
+
const resolvedTargets = resolveTargets(existing, ctx.options);
|
|
194
|
+
const nextProviders = await discoverTargets(resolvedTargets);
|
|
195
|
+
if (disposed) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
// Source variants must refresh too. Never reapply discovery over configured
|
|
199
|
+
// model overrides; OpenCode merges those after provider source definitions.
|
|
200
|
+
const previous = source.providers;
|
|
201
|
+
const changed = JSON.stringify(previous) !== JSON.stringify(nextProviders);
|
|
202
|
+
source.providers = nextProviders;
|
|
203
|
+
if (changed) {
|
|
204
|
+
try {
|
|
205
|
+
await ctx.provider.reload();
|
|
206
|
+
}
|
|
207
|
+
catch (error) {
|
|
208
|
+
// Retry unchanged discovery after a failed publication.
|
|
209
|
+
source.providers = previous;
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
/** Coalesce refresh requests so only one discovery runs at a time. */
|
|
215
|
+
const scheduleRefresh = () => {
|
|
216
|
+
if (disposed) {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
refreshPending = true;
|
|
220
|
+
if (refreshRunning) {
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
refreshRunning = true;
|
|
224
|
+
refreshTask = (async () => {
|
|
225
|
+
try {
|
|
226
|
+
while (refreshPending && !disposed) {
|
|
227
|
+
refreshPending = false;
|
|
228
|
+
await refresh();
|
|
229
|
+
refreshRetriesLeft = MAX_REFRESH_RETRIES;
|
|
230
|
+
if (refreshRetryTimer) {
|
|
231
|
+
clearTimeout(refreshRetryTimer);
|
|
232
|
+
refreshRetryTimer = undefined;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
238
|
+
await log("error", `[9router-provider] Refresh failed: ${message}`);
|
|
239
|
+
// A failed publication leaves the previous inventory live. Retry once
|
|
240
|
+
// after a short delay instead of waiting for the 5 minute interval.
|
|
241
|
+
if (!disposed && refreshRetriesLeft > 0 && !refreshRetryTimer) {
|
|
242
|
+
refreshRetriesLeft--;
|
|
243
|
+
refreshRetryTimer = setTimeout(() => {
|
|
244
|
+
refreshRetryTimer = undefined;
|
|
245
|
+
scheduleRefresh();
|
|
246
|
+
}, REFRESH_RETRY_DELAY);
|
|
247
|
+
if (typeof refreshRetryTimer === "object")
|
|
248
|
+
refreshRetryTimer.unref();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
})().finally(() => {
|
|
252
|
+
refreshRunning = false;
|
|
253
|
+
refreshTask = undefined;
|
|
254
|
+
if (refreshPending && !disposed) {
|
|
255
|
+
scheduleRefresh();
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
await ctx.provider.transform((editor) => {
|
|
260
|
+
for (const provider of source.providers) {
|
|
261
|
+
if (editor.get(provider.key)) {
|
|
262
|
+
// Existing provider (e.g. user-defined `providers.9router`): update
|
|
263
|
+
// its info so it gains the required OpenAI-compatible package and
|
|
264
|
+
// baseURL, then replace its discovered model inventory.
|
|
265
|
+
editor.update(provider.key, (info) => {
|
|
266
|
+
info.package = OPENAI_COMPATIBLE_PACKAGE;
|
|
267
|
+
info.activation = "enabled";
|
|
268
|
+
info.settings = {
|
|
269
|
+
...(info.settings ?? {}),
|
|
270
|
+
...provider.info.settings,
|
|
271
|
+
};
|
|
272
|
+
});
|
|
273
|
+
editor.models.set(provider.key, provider.models);
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
editor.add({ info: provider.info, models: provider.models });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
// Model transform removed: OpenCode 2.1.4 merges configured variants by ID
|
|
281
|
+
// after provider source definitions are published. Discovery provides the
|
|
282
|
+
// base variants; user config overlays them natively.
|
|
283
|
+
const eventAbort = new AbortController();
|
|
284
|
+
const eventTask = (async () => {
|
|
285
|
+
try {
|
|
286
|
+
for await (const event of ctx.event.subscribe({ signal: eventAbort.signal })) {
|
|
287
|
+
if (event.type === "provider.updated") {
|
|
288
|
+
scheduleRefresh();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
if (!disposed) {
|
|
294
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
295
|
+
await log("warn", `[9router-provider] Event subscription failed: ${message}`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
})();
|
|
299
|
+
const retryTimers = CONFIG_PROVIDER_RETRY_DELAYS.map((delay) => setTimeout(scheduleRefresh, delay));
|
|
300
|
+
const timer = setInterval(scheduleRefresh, REFRESH_INTERVAL);
|
|
301
|
+
return async () => {
|
|
302
|
+
disposed = true;
|
|
303
|
+
for (const retryTimer of retryTimers) {
|
|
304
|
+
clearTimeout(retryTimer);
|
|
305
|
+
}
|
|
306
|
+
if (refreshRetryTimer) {
|
|
307
|
+
clearTimeout(refreshRetryTimer);
|
|
308
|
+
refreshRetryTimer = undefined;
|
|
309
|
+
}
|
|
310
|
+
clearInterval(timer);
|
|
311
|
+
eventAbort.abort();
|
|
312
|
+
await eventTask;
|
|
313
|
+
await refreshTask;
|
|
314
|
+
};
|
|
315
|
+
},
|
|
316
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@joaogsbarbosa/opencode-9router",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@joaogsbarbosa/opencode-9router",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "OpenCode plugin provider for 9Router — FREE AI Router & Token Saver. 40+ providers, 100+ models.",
|
|
5
|
+
"author": "joaogsbarbosa",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"opencode",
|
|
8
|
+
"9router",
|
|
9
|
+
"ai-router",
|
|
10
|
+
"llm",
|
|
11
|
+
"provider",
|
|
12
|
+
"openai-compatible",
|
|
13
|
+
"token-saver",
|
|
14
|
+
"plugin"
|
|
15
|
+
],
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/joaogsbarbosa/opencode-9router.git"
|
|
19
|
+
},
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./server": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"main": "dist/index.js",
|
|
33
|
+
"types": "dist/index.d.ts",
|
|
34
|
+
"files": [
|
|
35
|
+
"dist",
|
|
36
|
+
"server.js",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsc",
|
|
42
|
+
"pretest": "npm run build",
|
|
43
|
+
"test": "node test-minimal.mjs && node test-limit.mjs && node test-combo.mjs && node test-v2.mjs && node test-reasoning.mjs",
|
|
44
|
+
"prepublishOnly": "npm run build"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@opencode/plugin": "^2.0.12"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@opencode-ai/plugin": "^1.0.182",
|
|
51
|
+
"@opencode-ai/sdk": "^1.0.182",
|
|
52
|
+
"@types/node": "^22.0.0",
|
|
53
|
+
"typescript": "^5.9.3"
|
|
54
|
+
},
|
|
55
|
+
"overrides": {
|
|
56
|
+
"toml": "^4.2.0"
|
|
57
|
+
}
|
|
58
|
+
}
|
package/server.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Load the built 9Router plugin for OpenCode's local-directory resolver.
|
|
3
|
+
*
|
|
4
|
+
* OpenCode V2 resolves an absolute plugin directory through its `server`
|
|
5
|
+
* entrypoint. Published packages use the equivalent `./server` export from
|
|
6
|
+
* package.json; this bridge keeps local development and V1-style paths aligned.
|
|
7
|
+
*/
|
|
8
|
+
export { default } from "./dist/index.js";
|
|
9
|
+
export * from "./dist/index.js";
|