@joaogsbarbosa/opencode-9router-installer 0.0.0-stage → 1.0.0

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 (3) hide show
  1. package/README.md +14 -2
  2. package/install.mjs +451 -0
  3. package/package.json +28 -3
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @joaogsbarbosa/opencode-9router-installer
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
+ Interactive installer for the [opencode-9router](https://www.npmjs.com/package/@joaogsbarbosa/opencode-9router) plugin.
4
+
5
+ ```bash
6
+ npx @joaogsbarbosa/opencode-9router-installer
7
+ ```
8
+
9
+ Use `--project` to edit the project config instead of the global config:
10
+
11
+ ```bash
12
+ npx @joaogsbarbosa/opencode-9router-installer --project
13
+ ```
14
+
15
+ Requires Node 18+.
package/install.mjs ADDED
@@ -0,0 +1,451 @@
1
+ #!/usr/bin/env node
2
+ // opencode-9router installer.
3
+ //
4
+ // npx @joaogsbarbosa/opencode-9router-installer # interactive menu
5
+ // npx @joaogsbarbosa/opencode-9router-installer --project # edit ./opencode.jsonc
6
+
7
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync } from "node:fs";
8
+ import { createInterface } from "node:readline/promises";
9
+ import { homedir } from "node:os";
10
+ import path from "node:path";
11
+ import { parse, modify, applyEdits, printParseErrorCode } from "jsonc-parser";
12
+
13
+ const PACKAGE = "@joaogsbarbosa/opencode-9router@latest";
14
+ const DEFAULT_BASE_URL = "http://localhost:20128";
15
+ const DEFAULT_CACHE_TTL = 3 * 60 * 60 * 1000; // 3 h (default do plugin)
16
+ const DEFAULT_DISCOVERY_TIMEOUT = 30000;
17
+ const SCHEMA = "https://opencode.ai/config.json";
18
+
19
+ const project = process.argv.includes("--project");
20
+
21
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
22
+
23
+ async function ask(text, initial = "") {
24
+ const canPrefill = rl.terminal && process.stdin.isTTY;
25
+ const label = initial && !canPrefill ? `${text.replace(/:\s*$/, "")} [${initial}]: ` : text;
26
+ const answer = await new Promise((resolve) => {
27
+ let settled = false;
28
+ let onClose;
29
+ const finish = (value) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ if (onClose) rl.removeListener("close", onClose);
33
+ resolve(value);
34
+ };
35
+ onClose = () => finish(null);
36
+ rl.once("close", onClose);
37
+ rl.question(label).then(finish, () => finish(null));
38
+ if (initial && canPrefill) {
39
+ try { rl.write(String(initial)); } catch { /* ignore write errors */ }
40
+ }
41
+ });
42
+ if (answer === "" && initial && !canPrefill) return initial;
43
+ return answer;
44
+ }
45
+
46
+ async function askYesNo(label, defaultYes = true) {
47
+ const hint = defaultYes ? "Y/n" : "y/N";
48
+ const raw = await ask(`${label} [${hint}]: `);
49
+ if (raw === null) return defaultYes;
50
+ const answer = raw.trim().toLowerCase();
51
+ if (!answer) return defaultYes;
52
+ return !answer.startsWith("n");
53
+ }
54
+
55
+ async function askNumber(label, defaultValue) {
56
+ const raw = await ask(`${label}: `, String(defaultValue));
57
+ const n = Number(raw);
58
+ return Number.isFinite(n) && n > 0 ? n : defaultValue;
59
+ }
60
+
61
+ function resolveConfigPath() {
62
+ if (project) {
63
+ const candidates = [
64
+ path.join(process.cwd(), "opencode.jsonc"),
65
+ path.join(process.cwd(), "opencode.json"),
66
+ path.join(process.cwd(), ".opencode", "opencode.jsonc"),
67
+ path.join(process.cwd(), ".opencode", "opencode.json"),
68
+ ];
69
+ for (const candidate of candidates) if (existsSync(candidate)) return candidate;
70
+ return path.join(process.cwd(), "opencode.jsonc");
71
+ }
72
+ const dir = process.env.XDG_CONFIG_HOME
73
+ ? path.join(process.env.XDG_CONFIG_HOME, "opencode")
74
+ : path.join(homedir(), ".config", "opencode");
75
+ const jsonc = path.join(dir, "opencode.jsonc");
76
+ const json = path.join(dir, "opencode.json");
77
+ if (existsSync(jsonc)) return jsonc;
78
+ if (existsSync(json)) return json;
79
+ return jsonc;
80
+ }
81
+
82
+ function cacheDir() {
83
+ const home = process.env.XDG_CACHE_HOME || path.join(homedir(), ".cache");
84
+ return path.join(home, "opencode-9router");
85
+ }
86
+
87
+ function readConfig(cfgPath) {
88
+ let text;
89
+ try {
90
+ text = readFileSync(cfgPath, "utf8");
91
+ } catch (error) {
92
+ if (error && error.code === "ENOENT") {
93
+ return { text: "", config: { $schema: SCHEMA, plugins: [] }, exists: false };
94
+ }
95
+ throw error;
96
+ }
97
+ if (!text.trim()) {
98
+ return { text: "", config: { $schema: SCHEMA, plugins: [] }, exists: true };
99
+ }
100
+ const errors = [];
101
+ const config = parse(text, errors, { allowTrailingComma: true, disallowComments: false });
102
+ if (errors.length > 0) {
103
+ throw new Error(`invalid JSONC in ${cfgPath}: ${printParseErrorCode(errors[0].error)} at offset ${errors[0].offset}`);
104
+ }
105
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
106
+ throw new Error("config root is not an object");
107
+ }
108
+ return { text, config, exists: true };
109
+ }
110
+
111
+ function writeConfig(cfgPath, text) {
112
+ mkdirSync(path.dirname(cfgPath), { recursive: true });
113
+ writeFileSync(cfgPath, text.endsWith("\n") ? text : text + "\n");
114
+ }
115
+
116
+ function editConfig(text, keyPath, value) {
117
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
118
+ const edits = modify(text, keyPath, value, {
119
+ formattingOptions: { insertSpaces: true, tabSize: 2, eol },
120
+ });
121
+ return applyEdits(text, edits);
122
+ }
123
+
124
+ function buildConfigText(text, plugins) {
125
+ if (!text.trim()) {
126
+ return JSON.stringify({ $schema: SCHEMA, plugins }, null, 2) + "\n";
127
+ }
128
+ return editConfig(text, ["plugins"], plugins);
129
+ }
130
+
131
+ function syncProviderSettings(cfgPath, providerKey, url, key) {
132
+ const { text, config } = readConfig(cfgPath);
133
+ const providers = config.providers;
134
+ if (!providers || typeof providers !== "object" || Array.isArray(providers)) return false;
135
+ const provider = providers[providerKey];
136
+ if (!provider || typeof provider !== "object") return false;
137
+
138
+ let updated = editConfig(text, ["providers", providerKey, "settings", "baseURL"], url);
139
+ const settings = provider.settings;
140
+ if (key) {
141
+ updated = editConfig(updated, ["providers", providerKey, "settings", "apiKey"], key);
142
+ } else if (settings && typeof settings === "object" && "apiKey" in settings) {
143
+ updated = editConfig(updated, ["providers", providerKey, "settings", "apiKey"], undefined);
144
+ }
145
+ writeConfig(cfgPath, updated);
146
+ return true;
147
+ }
148
+
149
+ function entryPackage(entry) {
150
+ if (typeof entry === "string") return entry;
151
+ if (entry && typeof entry.package === "string") return entry.package;
152
+ return "";
153
+ }
154
+
155
+ function pkgName(spec) {
156
+ if (typeof spec !== "string") return "";
157
+ const at = spec.lastIndexOf("@");
158
+ return at > 0 ? spec.slice(0, at) : spec;
159
+ }
160
+
161
+ function matches(spec, pkg = PACKAGE) {
162
+ if (!spec) return false;
163
+ const name = pkgName(spec);
164
+ const target = pkgName(pkg);
165
+ if (name === target) return true;
166
+ const short = target.split("/").pop();
167
+ return name === short || name.endsWith(`/${short}`);
168
+ }
169
+
170
+ function buildOptions(url, apikey, cache, cacheTTL, discoveryTimeout, providers) {
171
+ const options = {};
172
+ if (url) options.baseURL = url;
173
+ if (apikey) options.apiKey = apikey;
174
+ if (cache) options.cache = cache === "true";
175
+ const ttl = Number(cacheTTL);
176
+ if (Number.isFinite(ttl) && ttl > 0) options.cacheTTL = ttl;
177
+ const timeout = Number(discoveryTimeout);
178
+ if (Number.isFinite(timeout) && timeout > 0) options.discoveryTimeout = timeout;
179
+ if (Array.isArray(providers) && providers.length > 0) options.providers = providers;
180
+ return options;
181
+ }
182
+
183
+ function computePlugins(config, action, pkg, url, apikey, cache, cacheTTL, discoveryTimeout, providers) {
184
+ const plugins = Array.isArray(config.plugins) ? config.plugins.slice() : [];
185
+ if (action === "set") {
186
+ const kept = plugins.filter((entry) => !matches(entryPackage(entry), pkg));
187
+ kept.push({ package: pkg, options: buildOptions(url, apikey, cache, cacheTTL, discoveryTimeout, providers) });
188
+ return kept;
189
+ }
190
+ if (action === "remove") {
191
+ return plugins.filter((entry) => !matches(entryPackage(entry), pkg));
192
+ }
193
+ throw new Error(`unknown action: ${action}`);
194
+ }
195
+
196
+ function applyAction(cfgPath, action, pkg, url, apikey, cache, cacheTTL, discoveryTimeout, providers) {
197
+ const { text, config, exists } = readConfig(cfgPath);
198
+ const before = Array.isArray(config.plugins) ? config.plugins.length : 0;
199
+ const plugins = computePlugins(config, action, pkg, url, apikey, cache, cacheTTL, discoveryTimeout, providers);
200
+ if (action === "remove" && (!exists || plugins.length === before)) return 0;
201
+ writeConfig(cfgPath, buildConfigText(text, plugins));
202
+ return action === "remove" ? before - plugins.length : 0;
203
+ }
204
+
205
+ function findEntry(config) {
206
+ return (Array.isArray(config.plugins) ? config.plugins : []).find((item) => matches(entryPackage(item)));
207
+ }
208
+
209
+ function resolveCurrent(cfgPath) {
210
+ const defaults = {
211
+ url: DEFAULT_BASE_URL,
212
+ key: "",
213
+ cache: true,
214
+ cacheTTL: DEFAULT_CACHE_TTL,
215
+ discoveryTimeout: DEFAULT_DISCOVERY_TIMEOUT,
216
+ source: "options",
217
+ providerKey: "",
218
+ providers: [],
219
+ installed: false,
220
+ package: PACKAGE,
221
+ };
222
+
223
+ const { config } = readConfig(cfgPath);
224
+ const entry = findEntry(config);
225
+ const installed = !!entry;
226
+ const pkg = entryPackage(entry) || PACKAGE;
227
+ const options = entry && typeof entry === "object" ? entry.options || {} : {};
228
+ const optProviders = Array.isArray(options.providers)
229
+ ? options.providers.filter((item) => item && typeof item === "object")
230
+ : [];
231
+
232
+ if (optProviders.length > 0) {
233
+ const provider = optProviders.find((item) => item.key === "9router" || item.id === "9router") || optProviders[0];
234
+ const providerKey = String(provider.key || provider.id || "9router");
235
+ return {
236
+ url: provider.baseURL || defaults.url,
237
+ key: provider.apiKey || "",
238
+ cache: options.cache !== false,
239
+ cacheTTL: Number(options.cacheTTL) || defaults.cacheTTL,
240
+ discoveryTimeout: Number(options.discoveryTimeout) || defaults.discoveryTimeout,
241
+ source: "options.providers",
242
+ providerKey,
243
+ providers: optProviders,
244
+ installed,
245
+ package: pkg,
246
+ };
247
+ }
248
+
249
+ const providers = config.providers && typeof config.providers === "object" && !Array.isArray(config.providers)
250
+ ? config.providers
251
+ : {};
252
+ const providerKey = Object.keys(providers).find((key) => key === "9router" || key.startsWith("9router"));
253
+ if (providerKey) {
254
+ const settings = providers[providerKey]?.settings;
255
+ const resolved = settings && typeof settings === "object" ? settings : {};
256
+ return {
257
+ url: resolved.baseURL || defaults.url,
258
+ key: resolved.apiKey || "",
259
+ cache: options.cache !== false,
260
+ cacheTTL: Number(options.cacheTTL) || defaults.cacheTTL,
261
+ discoveryTimeout: Number(options.discoveryTimeout) || defaults.discoveryTimeout,
262
+ source: "providers",
263
+ providerKey,
264
+ providers: [],
265
+ installed,
266
+ package: pkg,
267
+ };
268
+ }
269
+
270
+ return {
271
+ url: options.baseURL || defaults.url,
272
+ key: options.apiKey || "",
273
+ cache: options.cache !== false,
274
+ cacheTTL: Number(options.cacheTTL) || defaults.cacheTTL,
275
+ discoveryTimeout: Number(options.discoveryTimeout) || defaults.discoveryTimeout,
276
+ source: "options",
277
+ providerKey: "",
278
+ providers: [],
279
+ installed,
280
+ package: pkg,
281
+ };
282
+ }
283
+
284
+ function maskSecret(value) {
285
+ if (!value) return "(not set)";
286
+ const text = String(value);
287
+ if (text.length <= 8) return "****";
288
+ return `${text.slice(0, 4)}...${text.slice(-4)}`;
289
+ }
290
+
291
+ function formatMs(value) {
292
+ const n = Number(value);
293
+ if (!Number.isFinite(n) || n <= 0) return "?";
294
+ if (n >= 3600000 && n % 3600000 === 0) return `${n / 3600000} h`;
295
+ if (n >= 60000 && n % 60000 === 0) return `${n / 60000} min`;
296
+ if (n >= 1000 && n % 1000 === 0) return `${n / 1000} s`;
297
+ return `${n} ms`;
298
+ }
299
+
300
+ function showStatus(cfgPath) {
301
+ console.log("\nopencode-9router");
302
+ try {
303
+ const current = resolveCurrent(cfgPath);
304
+ console.log(` status: ${current.installed ? "installed" : "not installed"}`);
305
+ console.log(` config: ${cfgPath}`);
306
+ if (!current.installed) return false;
307
+ console.log(` package: ${current.package}`);
308
+ console.log(` baseURL: ${current.url}`);
309
+ console.log(` apiKey: ${maskSecret(current.key)}`);
310
+ console.log(` cache: ${current.cache ? `enabled (TTL ${formatMs(current.cacheTTL)})` : "disabled"}`);
311
+ console.log(` discovery: ${formatMs(current.discoveryTimeout)}`);
312
+ return true;
313
+ } catch (error) {
314
+ console.log(` status: config error (${error.message})`);
315
+ return false;
316
+ }
317
+ }
318
+
319
+ async function checkConnection(baseUrl, apiKey) {
320
+ let url = baseUrl.replace(/\/+$/, "");
321
+ if (!url.endsWith("/v1")) url += "/v1";
322
+ url += "/models";
323
+ try {
324
+ const headers = {};
325
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
326
+ const response = await fetch(url, { headers, signal: AbortSignal.timeout(10000) });
327
+ return response.ok;
328
+ } catch {
329
+ return false;
330
+ }
331
+ }
332
+
333
+ async function promptOptions(current) {
334
+ const urlAnswer = await ask("Base URL: ", current.url);
335
+ const url = (urlAnswer === null ? "" : urlAnswer.trim()) || current.url;
336
+ const keyAnswer = await ask("API key (optional): ", current.key);
337
+ const key = keyAnswer === null ? current.key : keyAnswer.trim();
338
+ const cache = await askYesNo("Enable cache?", current.cache);
339
+ const cacheTTL = await askNumber("Cache TTL (ms)", current.cacheTTL);
340
+ const discoveryTimeout = await askNumber("Discovery timeout (ms)", current.discoveryTimeout);
341
+ return { url, key, cache: cache ? "true" : "false", cacheTTL, discoveryTimeout };
342
+ }
343
+
344
+ async function requireConnection(options) {
345
+ if (!(await checkConnection(options.url, options.key))) {
346
+ throw new Error(`could not connect to ${options.url}. Check the URL and API key.`);
347
+ }
348
+ }
349
+
350
+ async function doSetup(cfgPath) {
351
+ const current = resolveCurrent(cfgPath);
352
+ const options = await promptOptions(current);
353
+ await requireConnection(options);
354
+
355
+ let providers;
356
+ if (current.source === "options.providers") {
357
+ const key = current.providerKey;
358
+ const list = Array.isArray(current.providers) ? current.providers : [];
359
+ const withUrl = (item) => {
360
+ const { apiKey: _ignored, ...rest } = item;
361
+ return { ...rest, baseURL: options.url, ...(options.key ? { apiKey: options.key } : {}) };
362
+ };
363
+ const updated = list.map((item) => {
364
+ if (item && (item.key === key || item.id === key)) {
365
+ return withUrl(item);
366
+ }
367
+ return item;
368
+ });
369
+ if (!updated.some((item) => item && (item.key === key || item.id === key))) {
370
+ updated.push({ key, baseURL: options.url, ...(options.key ? { apiKey: options.key } : {}) });
371
+ }
372
+ providers = updated;
373
+ }
374
+
375
+ applyAction(cfgPath, "set", PACKAGE, options.url, options.key, options.cache, options.cacheTTL, options.discoveryTimeout, providers);
376
+
377
+ if (current.source === "providers") {
378
+ syncProviderSettings(cfgPath, current.providerKey, options.url, options.key);
379
+ }
380
+
381
+ console.log(`\nPlugin configured: ${PACKAGE}`);
382
+ console.log(`Config: ${cfgPath}`);
383
+ console.log("OpenCode installs the package automatically. Restart (or /reload).");
384
+ }
385
+
386
+ function doUninstall(cfgPath) {
387
+ const { config } = readConfig(cfgPath);
388
+ const installed = !!findEntry(config);
389
+ const removed = applyAction(cfgPath, "remove", PACKAGE);
390
+ if (!installed) {
391
+ console.log("Plugin is not installed.");
392
+ } else {
393
+ console.log(`Entries removed from config: ${removed}`);
394
+ }
395
+ if (existsSync(cacheDir())) {
396
+ rmSync(cacheDir(), { recursive: true, force: true });
397
+ console.log(`Removed ${cacheDir()}`);
398
+ }
399
+ console.log("\nUninstalled. The package in ~/.config/opencode/node_modules is managed by OpenCode.");
400
+ }
401
+
402
+ async function chooseAction(installed) {
403
+ while (true) {
404
+ console.log("\nChoose an option:");
405
+ console.log(installed
406
+ ? " 1) configure - change the current configuration"
407
+ : " 1) install - install the plugin");
408
+ console.log(" 2) uninstall - remove entry and cache");
409
+ console.log(" 0) quit");
410
+ const choice = await ask("> ");
411
+ if (choice === null) return "";
412
+ switch (choice.trim()) {
413
+ case "1": return "setup";
414
+ case "2": return "uninstall";
415
+ case "0": case "q": case "Q": return "";
416
+ default: console.log("invalid option");
417
+ }
418
+ }
419
+ }
420
+
421
+ async function main() {
422
+ if (!process.stdin.isTTY) {
423
+ console.error("interactive terminal required. Run `npx @joaogsbarbosa/opencode-9router-installer` in a terminal.");
424
+ process.exitCode = 1;
425
+ return;
426
+ }
427
+
428
+ const cfgPath = resolveConfigPath();
429
+
430
+ while (true) {
431
+ const installed = showStatus(cfgPath);
432
+ const action = await chooseAction(installed);
433
+ if (!action) return;
434
+
435
+ try {
436
+ if (action === "setup") await doSetup(cfgPath);
437
+ else doUninstall(cfgPath);
438
+ } catch (error) {
439
+ console.error(`error: ${error.message}`);
440
+ }
441
+ }
442
+ }
443
+
444
+ try {
445
+ await main();
446
+ } catch (error) {
447
+ console.error(`error: ${error.message}`);
448
+ process.exitCode = 1;
449
+ } finally {
450
+ rl.close();
451
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@joaogsbarbosa/opencode-9router-installer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Interactive installer for the OpenCode 9Router plugin.",
5
+ "type": "module",
6
+ "bin": {
7
+ "opencode-9router": "./install.mjs"
8
+ },
9
+ "files": [
10
+ "install.mjs",
11
+ "README.md"
12
+ ],
13
+ "dependencies": {
14
+ "jsonc-parser": "^3.3.1"
15
+ },
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/joaogsbarbosa/opencode-9router.git",
23
+ "directory": "installer"
24
+ },
25
+ "keywords": [
26
+ "opencode",
27
+ "9router",
28
+ "installer",
29
+ "cli"
30
+ ]
6
31
  }