zyrouter 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.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # zyrouter
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
+ Connect your coding tools to [ZyRouter](https://zyrouter.com) with one command:
4
+
5
+ ```bash
6
+ npx -y zyrouter@latest --key sk-zyr-YOUR_KEY
7
+ ```
8
+
9
+ The installer checks the key, detects which tools are installed, backs up their current config
10
+ to `~/.zyrouter/backups/`, writes the ZyRouter settings, and sends one small test request.
11
+
12
+ | Tool | File it writes |
13
+ | --- | --- |
14
+ | Codex (CLI & VS Code) | `~/.codex/config.toml` and the `ZYROUTER_API_KEY` user environment variable |
15
+ | Claude Code | `~/.claude/settings.json` |
16
+ | OpenCode | `~/.config/opencode/opencode.json` and `ZYROUTER_API_KEY` |
17
+ | OpenClaw | `~/.openclaw/openclaw.json` |
18
+ | Hermes Agent | `~/.hermes/config.yaml` (the `model:` block) and `OPENAI_API_KEY` in `~/.hermes/.env` |
19
+
20
+ Cline and Continue are detected but stay manual; the installer prints the values to use.
21
+
22
+ Undo everything:
23
+
24
+ ```bash
25
+ npx -y zyrouter@latest uninstall
26
+ ```
27
+
28
+ Options: `--model <id>`, `--tools codex,claude-code,opencode,openclaw,hermes`, `--yes`, `--no-test`, `--dry-run`.
29
+ No dependencies; needs Node.js 18.17 or newer.
package/bin/cli.mjs ADDED
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../lib/main.mjs";
3
+
4
+ const major = Number(process.versions.node.split(".")[0]);
5
+ if (major < 18) {
6
+ console.error(`ZyRouter installer butuh Node.js 18 atau lebih baru (sekarang ${process.versions.node}).`);
7
+ process.exit(1);
8
+ }
9
+
10
+ // Set exitCode instead of calling process.exit(): on Windows an exit while fetch sockets are still
11
+ // closing can abort Node with a libuv assertion.
12
+ run(process.argv.slice(2)).then(
13
+ (code) => {
14
+ process.exitCode = code;
15
+ },
16
+ (error) => {
17
+ console.error(`✖ ${error?.message || error}`);
18
+ process.exitCode = 1;
19
+ },
20
+ );
@@ -0,0 +1,147 @@
1
+ // Pure config mergers: each takes the current file content (or parsed JSON) and returns the new one.
2
+ // They only touch ZyRouter's own entries, so the customer's other providers and settings survive.
3
+
4
+ export const PROVIDER_ID = "zyrouter";
5
+ export const ENV_KEY = "ZYROUTER_API_KEY";
6
+
7
+ const SAFE_VALUE = /^[A-Za-z0-9._:/\-[\]]+$/;
8
+
9
+ export function assertSafeValue(label, value) {
10
+ if (typeof value !== "string" || !SAFE_VALUE.test(value)) throw new Error(`Invalid ${label}: ${value}`);
11
+ return value;
12
+ }
13
+
14
+ /**
15
+ * Codex ~/.codex/config.toml: sets the top-level model/model_provider, keeps an existing
16
+ * model_reasoning_effort, and replaces any previous [model_providers.zyrouter] table.
17
+ */
18
+ export function mergeCodexToml(existing, { baseUrl, model }) {
19
+ assertSafeValue("base URL", baseUrl);
20
+ assertSafeValue("model", model);
21
+ const lines = String(existing || "").replace(/\r\n/g, "\n").split("\n");
22
+ const kept = [];
23
+ let section = null;
24
+ let skipping = false;
25
+ let hasEffort = false;
26
+ for (const line of lines) {
27
+ const header = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/.exec(line);
28
+ if (header) {
29
+ section = header[1].replace(/"/g, "").trim();
30
+ skipping = section === `model_providers.${PROVIDER_ID}`;
31
+ if (!skipping) kept.push(line);
32
+ continue;
33
+ }
34
+ if (skipping) continue;
35
+ if (section === null) {
36
+ if (/^\s*(model|model_provider)\s*=/.test(line)) continue;
37
+ if (/^\s*model_reasoning_effort\s*=/.test(line)) hasEffort = true;
38
+ }
39
+ kept.push(line);
40
+ }
41
+ while (kept.length && kept[0].trim() === "") kept.shift();
42
+ while (kept.length && kept[kept.length - 1].trim() === "") kept.pop();
43
+ const head = [`model = "${model}"`, `model_provider = "${PROVIDER_ID}"`];
44
+ if (!hasEffort) head.push('model_reasoning_effort = "high"');
45
+ const provider = [
46
+ `[model_providers.${PROVIDER_ID}]`,
47
+ 'name = "ZyRouter"',
48
+ `base_url = "${baseUrl}"`,
49
+ `env_key = "${ENV_KEY}"`,
50
+ 'wire_api = "responses"',
51
+ ];
52
+ // Top-level keys must come before the first table, so ours go first and the provider table last.
53
+ return [...head, ...(kept.length ? ["", ...kept] : []), "", ...provider, ""].join("\n");
54
+ }
55
+
56
+ /** Claude Code ~/.claude/settings.json: points the Anthropic client at ZyRouter. */
57
+ export function mergeClaudeSettings(data, { anthropicBaseUrl, key, model }) {
58
+ const next = { ...(data || {}) };
59
+ next.env = { ...(next.env || {}), ANTHROPIC_BASE_URL: anthropicBaseUrl, ANTHROPIC_AUTH_TOKEN: key, ANTHROPIC_MODEL: model };
60
+ return next;
61
+ }
62
+
63
+ /** OpenCode ~/.config/opencode/opencode.json: an OpenAI-compatible provider reading the key from the environment. */
64
+ export function mergeOpenCode(data, { baseUrl, models, model }) {
65
+ const next = { ...(data || {}) };
66
+ next.$schema ||= "https://opencode.ai/config.json";
67
+ next.provider = {
68
+ ...(next.provider || {}),
69
+ [PROVIDER_ID]: {
70
+ npm: "@ai-sdk/openai-compatible",
71
+ name: "ZyRouter",
72
+ options: { baseURL: baseUrl, apiKey: `{env:${ENV_KEY}}` },
73
+ models: Object.fromEntries(models.map((id) => [id, { name: id }])),
74
+ },
75
+ };
76
+ next.model = `${PROVIDER_ID}/${model}`;
77
+ return next;
78
+ }
79
+
80
+ /** OpenClaw ~/.openclaw/openclaw.json: same shape as the dashboard guide. */
81
+ export function mergeOpenClaw(data, { baseUrl, key, models, model }) {
82
+ const next = { ...(data || {}) };
83
+ next.models = { ...(next.models || {}) };
84
+ next.models.providers = {
85
+ ...(next.models.providers || {}),
86
+ [PROVIDER_ID]: { baseUrl, apiKey: key, api: "openai-completions", models: models.map((id) => ({ id, name: id })) },
87
+ };
88
+ next.agents = { ...(next.agents || {}) };
89
+ next.agents.defaults = { ...(next.agents.defaults || {}) };
90
+ next.agents.defaults.model = { ...(next.agents.defaults.model || {}), primary: `${PROVIDER_ID}/${model}` };
91
+ return next;
92
+ }
93
+
94
+ const RC_START = "# >>> zyrouter >>>";
95
+ const RC_END = "# <<< zyrouter <<<";
96
+
97
+ /** Shell rc file: one marked block exporting the key, replaced on every run. */
98
+ export function setRcBlock(existing, key) {
99
+ assertSafeValue("API key", key);
100
+ const without = removeRcBlock(existing);
101
+ const block = `${RC_START}\nexport ${ENV_KEY}="${key}"\n${RC_END}\n`;
102
+ return `${without ? `${without.replace(/\n*$/, "\n")}\n` : ""}${block}`;
103
+ }
104
+
105
+ export function removeRcBlock(existing) {
106
+ const text = String(existing || "");
107
+ const pattern = new RegExp(`\\n?${RC_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${RC_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n?`, "g");
108
+ return text.replace(pattern, "\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "");
109
+ }
110
+
111
+ export function maskKey(key) {
112
+ const value = String(key || "");
113
+ return value.length > 12 ? `${value.slice(0, 10)}…${value.slice(-4)}` : "sk-zyr-…";
114
+ }
115
+
116
+ /**
117
+ * Hermes Agent ~/.hermes/config.yaml: replaces only the top-level `model:` block (the shape the dashboard
118
+ * guide uses) and leaves every other key untouched.
119
+ */
120
+ export function mergeHermesConfig(existing, { baseUrl, model }) {
121
+ assertSafeValue("base URL", baseUrl);
122
+ assertSafeValue("model", model);
123
+ const block = ["model:", ` default: "${model}"`, ' provider: "custom"', ` base_url: "${baseUrl}"`];
124
+ const lines = String(existing || "").replace(/\r\n/g, "\n").split("\n");
125
+ const start = lines.findIndex((line) => /^model\s*:/.test(line));
126
+ if (start === -1) {
127
+ const rest = lines.join("\n").replace(/^\n+/, "").replace(/\n*$/, "");
128
+ return `${block.join("\n")}\n${rest ? `\n${rest}\n` : ""}`;
129
+ }
130
+ let end = start + 1;
131
+ // The block runs while lines are indented, blank, or comments that belong to it.
132
+ while (end < lines.length && (lines[end].trim() === "" || /^[ \t]/.test(lines[end]))) end += 1;
133
+ while (end > start + 1 && lines[end - 1].trim() === "") end -= 1;
134
+ const merged = [...lines.slice(0, start), ...block, ...lines.slice(end)].join("\n").replace(/\n*$/, "\n");
135
+ return merged;
136
+ }
137
+
138
+ /** Hermes Agent ~/.hermes/.env: sets OPENAI_API_KEY, keeping the other variables. */
139
+ export function setDotenvValue(existing, name, value) {
140
+ assertSafeValue(name, value);
141
+ const lines = String(existing || "").replace(/\r\n/g, "\n").split("\n").filter((line, index, all) => !(index === all.length - 1 && line === ""));
142
+ const pattern = new RegExp(`^\s*(export\s+)?${name}\s*=`);
143
+ const index = lines.findIndex((line) => pattern.test(line));
144
+ if (index === -1) lines.push(`${name}=${value}`);
145
+ else lines[index] = `${name}=${value}`;
146
+ return `${lines.join("\n")}\n`;
147
+ }
package/lib/main.mjs ADDED
@@ -0,0 +1,414 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ import { createInterface } from "node:readline/promises";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
+ import { ENV_KEY, maskKey, mergeClaudeSettings, mergeCodexToml, mergeHermesConfig, mergeOpenClaw, mergeOpenCode, setDotenvValue } from "./configs.mjs";
8
+ import { box, createStyle, groupModels, pickFromMenu, readSecret, withSpinner } from "./ui.mjs";
9
+ import { createBackup, defaultRun, exists, hasEditorExtension, onPath, persistApiKey, readJson, readText, removePersistedApiKey, restoreBackups, restoreWindowsUserEnv, writeText } from "./system.mjs";
10
+
11
+ export const DEFAULT_BASE_URL = "https://zyrouter.com/v1";
12
+ const FALLBACK_MODELS = ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna"];
13
+ const KEY_PATTERN = /^sk-zyr-[A-Za-z0-9_-]{20,}$/;
14
+ const VERSION = (() => {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
17
+ } catch {
18
+ return "";
19
+ }
20
+ })();
21
+
22
+ const HELP = `ZyRouter installer — hubungkan Codex, Claude Code, OpenCode, OpenClaw, dan Hermes Agent ke ZyRouter.
23
+
24
+ Pakai:
25
+ npx -y zyrouter@latest --key sk-zyr-... pasang (deteksi aplikasi otomatis)
26
+ npx -y zyrouter@latest uninstall kembalikan semua konfigurasi seperti semula
27
+
28
+ Opsi:
29
+ --key <key> API key ZyRouter (atau env ZYROUTER_API_KEY, atau ditanya)
30
+ --model <id> model default, mis. gpt-6.1-terra
31
+ --tools <list> codex,claude-code,opencode,openclaw,hermes (default: yang terdeteksi)
32
+ --yes tanpa pertanyaan: pakai aplikasi yang terdeteksi dan model pertama
33
+ --no-test lewati request tes di akhir
34
+ --no-env jangan simpan ZYROUTER_API_KEY ke environment (untuk tes)
35
+ --dry-run tampilkan rencana tanpa mengubah file
36
+ --base-url <url> endpoint lain (default ${DEFAULT_BASE_URL})
37
+ `;
38
+
39
+ /** Tools whose config files the installer writes; manual ones only get printed instructions. */
40
+ function toolCatalog(ctx) {
41
+ const home = ctx.home;
42
+ return [
43
+ {
44
+ id: "codex",
45
+ name: "Codex (CLI & VS Code)",
46
+ protocol: "responses",
47
+ file: path.join(home, ".codex", "config.toml"),
48
+ detected: () => onPath("codex", ctx) || exists(path.join(home, ".codex")) || hasEditorExtension("openai.chatgpt", ctx),
49
+ apply(opts, backup) {
50
+ backup.record(this.file);
51
+ writeText(this.file, mergeCodexToml(readText(this.file), opts));
52
+ return { ok: true };
53
+ },
54
+ needsEnv: true,
55
+ },
56
+ {
57
+ id: "claude-code",
58
+ name: "Claude Code",
59
+ protocol: "messages",
60
+ // ~/.claude exists for every Claude Code user; redirecting it must be a deliberate choice, never a default.
61
+ optIn: true,
62
+ file: path.join(home, ".claude", "settings.json"),
63
+ detected: () => onPath("claude", ctx) || exists(path.join(home, ".claude")),
64
+ apply(opts, backup) {
65
+ return writeJsonConfig(this.file, (data) => mergeClaudeSettings(data, opts), backup);
66
+ },
67
+ },
68
+ {
69
+ id: "opencode",
70
+ name: "OpenCode",
71
+ protocol: "chat",
72
+ file: path.join(home, ".config", "opencode", "opencode.json"),
73
+ detected: () => onPath("opencode", ctx) || exists(path.join(home, ".config", "opencode")),
74
+ apply(opts, backup) {
75
+ if (exists(path.join(path.dirname(this.file), "opencode.jsonc"))) return { ok: false, reason: "opencode.jsonc dipakai; tambahkan provider secara manual" };
76
+ return writeJsonConfig(this.file, (data) => mergeOpenCode(data, opts), backup);
77
+ },
78
+ needsEnv: true,
79
+ },
80
+ {
81
+ id: "openclaw",
82
+ name: "OpenClaw",
83
+ protocol: "chat",
84
+ file: path.join(home, ".openclaw", "openclaw.json"),
85
+ detected: () => onPath("openclaw", ctx) || exists(path.join(home, ".openclaw")),
86
+ apply(opts, backup) {
87
+ return writeJsonConfig(this.file, (data) => mergeOpenClaw(data, opts), backup);
88
+ },
89
+ },
90
+ {
91
+ id: "hermes",
92
+ name: "Hermes Agent",
93
+ protocol: "chat",
94
+ file: path.join(home, ".hermes", "config.yaml"),
95
+ envFile: path.join(home, ".hermes", ".env"),
96
+ detected: () => onPath("hermes", ctx) || exists(path.join(home, ".hermes")),
97
+ apply(opts, backup) {
98
+ backup.record(this.file);
99
+ backup.record(this.envFile);
100
+ writeText(this.file, mergeHermesConfig(readText(this.file), opts));
101
+ writeText(this.envFile, setDotenvValue(readText(this.envFile), "OPENAI_API_KEY", opts.key));
102
+ return { ok: true };
103
+ },
104
+ },
105
+ ];
106
+ }
107
+
108
+ const MANUAL_TOOLS = [
109
+ { id: "cline", name: "Cline", detected: (ctx) => hasEditorExtension("saoudrizwan.claude-dev", ctx), hint: "Settings Cline > API Provider: OpenAI Compatible" },
110
+ { id: "continue", name: "Continue", detected: (ctx) => hasEditorExtension("continue.continue", ctx) || exists(path.join(ctx.home, ".continue")), hint: "~/.continue/config.yaml, provider openai" },
111
+ ];
112
+
113
+ function writeJsonConfig(file, merge, backup) {
114
+ const current = readJson(file);
115
+ if (!current.ok) return { ok: false, reason: `${path.basename(file)} tidak bisa dibaca sebagai JSON (mungkin ada komentar); ubah manual` };
116
+ backup.record(file);
117
+ writeText(file, `${JSON.stringify(merge(current.data), null, 2)}\n`);
118
+ return { ok: true };
119
+ }
120
+
121
+ async function fetchModels(ctx, baseUrl, key) {
122
+ try {
123
+ const response = await ctx.fetch(`${baseUrl}/models`, { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(15_000) });
124
+ if (response.status === 401 || response.status === 403) return { ok: false, invalidKey: true };
125
+ if (!response.ok) return { ok: false, status: response.status };
126
+ const body = await response.json();
127
+ const models = (Array.isArray(body?.data) ? body.data : []).map((item) => item?.id).filter((id) => typeof id === "string" && id);
128
+ return models.length ? { ok: true, models } : { ok: false, status: response.status };
129
+ } catch (error) {
130
+ return { ok: false, error: error?.name || "Error" };
131
+ }
132
+ }
133
+
134
+ const PROTOCOL_TESTS = {
135
+ chat: {
136
+ label: "OpenAI Chat Completions",
137
+ url: (o) => `${o.baseUrl}/chat/completions`,
138
+ body: (model) => ({ model, messages: [{ role: "user", content: "Reply with exactly: ZyRouter OK" }], max_tokens: 16, stream: false }),
139
+ text: (b) => b?.choices?.[0]?.message?.content,
140
+ },
141
+ responses: {
142
+ label: "OpenAI Responses (Codex)",
143
+ url: (o) => `${o.baseUrl}/responses`,
144
+ body: (model) => ({ model, input: "Reply with exactly: ZyRouter OK", max_output_tokens: 16, stream: false }),
145
+ text: (b) => b?.output_text || (b?.output || []).flatMap((item) => item?.content || []).map((part) => part?.text).filter(Boolean).join(""),
146
+ },
147
+ messages: {
148
+ label: "Anthropic Messages (Claude Code)",
149
+ url: (o) => `${o.anthropicBaseUrl}/v1/messages`,
150
+ headers: { "anthropic-version": "2023-06-01" },
151
+ body: (model) => ({ model, max_tokens: 16, messages: [{ role: "user", content: "Reply with exactly: ZyRouter OK" }] }),
152
+ text: (b) => (b?.content || []).map((part) => part?.text).filter(Boolean).join(""),
153
+ },
154
+ };
155
+
156
+ async function testProtocol(ctx, protocol, opts) {
157
+ const spec = PROTOCOL_TESTS[protocol];
158
+ try {
159
+ const response = await ctx.fetch(spec.url(opts), {
160
+ method: "POST",
161
+ headers: { Authorization: `Bearer ${opts.key}`, "Content-Type": "application/json", ...(spec.headers || {}) },
162
+ body: JSON.stringify(spec.body(opts.model)),
163
+ signal: AbortSignal.timeout(90_000),
164
+ });
165
+ const body = await response.json().catch(() => ({}));
166
+ if (!response.ok) return { ok: false, label: spec.label, status: response.status, message: body?.error?.message || body?.message };
167
+ return { ok: true, label: spec.label, text: String(spec.text(body) || "").trim() };
168
+ } catch (error) {
169
+ return { ok: false, label: spec.label, error: error?.name || "Error" };
170
+ }
171
+ }
172
+
173
+ function parseList(value) {
174
+ return String(value || "").split(",").map((item) => item.trim().toLowerCase()).filter(Boolean);
175
+ }
176
+
177
+ export async function run(argv, overrides = {}) {
178
+ const stdinTty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
179
+ const ctx = {
180
+ env: process.env,
181
+ platform: process.platform,
182
+ home: process.env.ZYROUTER_INSTALLER_HOME || os.homedir(),
183
+ fetch: globalThis.fetch,
184
+ run: defaultRun,
185
+ out: (line = "") => process.stdout.write(`${line}\n`),
186
+ ask: null,
187
+ interactive: stdinTty,
188
+ ...overrides,
189
+ };
190
+ // Arrow-key menus, spinner and colors only on a real terminal; tests and pipes get plain text.
191
+ ctx.tty = overrides.tty ?? (!overrides.out && !ctx.ask && ctx.interactive && stdinTty);
192
+ ctx.style = createStyle(overrides.color ?? (ctx.tty && !ctx.env.NO_COLOR));
193
+ const { values, positionals } = parseArgs({
194
+ args: argv,
195
+ allowPositionals: true,
196
+ options: {
197
+ key: { type: "string" },
198
+ model: { type: "string" },
199
+ tools: { type: "string" },
200
+ "base-url": { type: "string" },
201
+ yes: { type: "boolean", short: "y" },
202
+ "no-test": { type: "boolean" },
203
+ "no-env": { type: "boolean" },
204
+ "dry-run": { type: "boolean" },
205
+ help: { type: "boolean", short: "h" },
206
+ },
207
+ });
208
+ const out = ctx.out;
209
+ const s = ctx.style;
210
+ const ok = (text) => out(`${s.green("✔")} ${text}`);
211
+ const warn = (text) => out(`${s.yellow("!")} ${text}`);
212
+ const fail = (text) => out(`${s.red("✖")} ${text}`);
213
+ const step = (index, total, text) => out(`\n${s.orange(s.bold(`${index}/${total}`))} ${s.bold(text)}`);
214
+ if (values.help) {
215
+ out(HELP);
216
+ return 0;
217
+ }
218
+ ctx.dryRun = values["dry-run"] === true;
219
+
220
+ // One readline interface per question, closed right away, so raw-mode menus own stdin afterwards.
221
+ const ask = ctx.ask || (async (question) => {
222
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
223
+ try {
224
+ return await rl.question(question);
225
+ } finally {
226
+ rl.close();
227
+ }
228
+ });
229
+ const canAsk = !values.yes && Boolean(ctx.ask || ctx.interactive);
230
+
231
+ if (positionals[0] === "uninstall") {
232
+ const result = restoreBackups(ctx);
233
+ // Windows: put back the value from before the first install. Elsewhere the rc files were restored already.
234
+ if (ctx.platform === "win32") {
235
+ if (result.windowsEnv) restoreWindowsUserEnv(ctx, result.windowsEnvPrevious);
236
+ } else {
237
+ removePersistedApiKey(ctx);
238
+ }
239
+ if (result.sessions) ok(`${result.files} file dikembalikan dari ${result.sessions} backup.`);
240
+ else out("Tidak ada backup ZyRouter untuk dikembalikan.");
241
+ out("Tutup lalu buka lagi terminal dan editor supaya perubahan terbaca.");
242
+ return 0;
243
+ }
244
+
245
+ if (ctx.tty) {
246
+ out("");
247
+ box(s, [`${s.orange(s.bold("ZyRouter"))} ${s.bold("installer")} ${s.gray(VERSION ? `v${VERSION}` : "")}`, s.gray("Hubungkan coding agent kamu ke ZyRouter")]).forEach((line) => out(line));
248
+ }
249
+
250
+ const baseUrl = String(values["base-url"] || ctx.env.ZYROUTER_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
251
+ if (!/^https:\/\//.test(baseUrl) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?\//.test(`${baseUrl}/`)) throw new Error("Base URL harus https:// (atau http://localhost untuk tes).");
252
+ const anthropicBaseUrl = baseUrl.replace(/\/v1$/i, "");
253
+ const totalSteps = values["no-test"] ? 4 : 5;
254
+
255
+ // 1. API key. An existing ZYROUTER_API_KEY is only reused when it is a ZyRouter key; other tools use the name too.
256
+ if (ctx.tty) step(1, totalSteps, "API key");
257
+ const envKey = ctx.env[ENV_KEY] || "";
258
+ let key = values.key || (KEY_PATTERN.test(envKey) ? envKey : "");
259
+ if (!values.key && envKey && !key) warn(`${ENV_KEY} di environment bukan key ZyRouter; diabaikan.`);
260
+ // Ask for a missing key even when stdin is not reported as a TTY (editor and app terminals often are not);
261
+ // only --yes means "never prompt".
262
+ if (!key && !values.yes) key = ctx.tty ? await readSecret(ctx, "Tempel API key ZyRouter (sk-zyr-...)") : (await ask("Tempel API key ZyRouter (sk-zyr-...): ")).trim();
263
+ if (!key) throw new Error("API key belum diisi. Salin perintah lengkap dari dashboard ZyRouter, atau pakai --key sk-zyr-...");
264
+ if (!KEY_PATTERN.test(key)) throw new Error("API key tidak valid. Salin perintah lengkap dari dashboard ZyRouter, atau pakai --key sk-zyr-...");
265
+
266
+ if (!ctx.tty) out(`ZyRouter installer · key ${maskKey(key)}`);
267
+ const listed = await withSpinner(ctx, "Memeriksa API key...", () => fetchModels(ctx, baseUrl, key));
268
+ if (listed.invalidKey) throw new Error("API key ditolak (401). Cek key di dashboard ZyRouter tab API.");
269
+ const models = listed.ok ? listed.models : FALLBACK_MODELS;
270
+ if (listed.ok) ok(`API key valid · ${models.length} model tersedia${ctx.tty ? ` ${s.gray(maskKey(key))}` : ""}`);
271
+ else warn("Daftar model belum bisa diambil; memakai daftar bawaan.");
272
+
273
+ // 2. Tools.
274
+ if (ctx.tty) step(2, totalSteps, "Aplikasi");
275
+ const tools = toolCatalog(ctx);
276
+ const detected = tools.filter((tool) => tool.detected());
277
+ const preselected = detected.filter((tool) => !tool.optIn);
278
+ const toolNote = (tool) => (!detected.includes(tool) ? "tidak terdeteksi" : tool.optIn ? "terdeteksi · pilih kalau mau dialihkan ke ZyRouter" : "terdeteksi");
279
+ let selected;
280
+ if (values.tools) {
281
+ const wanted = parseList(values.tools);
282
+ selected = tools.filter((tool) => wanted.includes(tool.id));
283
+ const unknown = wanted.filter((id) => !tools.some((tool) => tool.id === id));
284
+ if (unknown.length) throw new Error(`Aplikasi tidak dikenal: ${unknown.join(", ")}. Pilihan: ${tools.map((tool) => tool.id).join(", ")}`);
285
+ } else if (canAsk && ctx.tty) {
286
+ const ids = await pickFromMenu(ctx, {
287
+ title: "Pilih aplikasi yang mau diatur",
288
+ hint: "↑↓ pindah · spasi centang · a semua · enter lanjut",
289
+ multi: true,
290
+ rows: tools.map((tool) => ({ label: tool.name, value: tool.id, note: toolNote(tool), checked: preselected.includes(tool) })),
291
+ });
292
+ selected = tools.filter((tool) => ids.includes(tool.id));
293
+ } else if (canAsk) {
294
+ out("\nAplikasi yang bisa diatur otomatis:");
295
+ tools.forEach((tool, index) => {
296
+ const note = !detected.includes(tool) ? " (tidak terdeteksi)" : tool.optIn ? " (terdeteksi; pilih nomornya kalau mau dialihkan ke ZyRouter)" : "";
297
+ out(` ${index + 1}. [${preselected.includes(tool) ? "x" : " "}] ${tool.name}${note}`);
298
+ });
299
+ const answer = (await ask(`Pilih nomor, pisahkan koma (Enter = ${preselected.length ? "yang dicentang" : "lewati"}): `)).trim();
300
+ selected = answer ? answer.split(",").map((n) => tools[Number(n.trim()) - 1]).filter(Boolean) : preselected;
301
+ } else {
302
+ selected = preselected;
303
+ }
304
+ if (!selected.length) {
305
+ out("Tidak ada aplikasi yang dipilih. Pasang dulu Codex/OpenCode/OpenClaw/Hermes, atau pilih langsung dengan --tools codex,claude-code.");
306
+ return 1;
307
+ }
308
+ if (ctx.tty) ok(`Aplikasi: ${selected.map((tool) => s.bold(tool.name)).join(", ")}`);
309
+
310
+ // 3. Default model, grouped by family.
311
+ if (ctx.tty) step(3, totalSteps, "Model default");
312
+ const families = groupModels(models);
313
+ const ordered = families.flatMap((group) => group.models);
314
+ let model = values.model || "";
315
+ if (!model && canAsk && ctx.tty) {
316
+ const numbered = new Map(ordered.map((id, index) => [id, index + 1]));
317
+ model = await pickFromMenu(ctx, {
318
+ title: "Pilih model default",
319
+ hint: "↑↓ pindah · enter pilih",
320
+ initialValue: models[0],
321
+ rows: families.flatMap((group) => [{ header: `${group.family} Family` }, ...group.models.map((id) => ({ label: `[${numbered.get(id)}] ${id}`, value: id }))]),
322
+ });
323
+ } else if (!model && canAsk) {
324
+ out("\nModel default:");
325
+ let index = 0;
326
+ for (const group of families) {
327
+ out(`${group.family} Family`);
328
+ group.models.forEach((id) => out(` [${++index}] ${id}`));
329
+ }
330
+ const answer = (await ask(`Pilih nomor (Enter = ${models[0]}): `)).trim();
331
+ model = (answer && ordered[Number(answer) - 1]) || models[0];
332
+ }
333
+ model ||= models[0];
334
+ if (listed.ok && !models.includes(model)) throw new Error(`Model ${model} tidak tersedia untuk key ini.`);
335
+ if (ctx.tty) ok(`Model: ${s.bold(model)}`);
336
+
337
+ if (ctx.dryRun) {
338
+ out("\nRencana (dry run, tidak ada file yang diubah):");
339
+ selected.forEach((tool) => out(` • ${tool.name} → ${tool.file}`));
340
+ if (selected.some((tool) => tool.needsEnv)) out(` • ${ENV_KEY} disimpan untuk terminal baru`);
341
+ return 0;
342
+ }
343
+
344
+ // 4. Write configs.
345
+ if (ctx.tty) step(4, totalSteps, "Menulis konfigurasi");
346
+ const backup = createBackup(ctx);
347
+ const opts = { baseUrl, anthropicBaseUrl, key, model, models };
348
+ if (!ctx.tty) out("");
349
+ let failures = 0;
350
+ for (const tool of selected) {
351
+ const result = tool.apply(opts, backup);
352
+ if (result.ok) ok(`${tool.name} → ${s.gray(tool.file)}`);
353
+ else {
354
+ failures += 1;
355
+ fail(`${tool.name}: ${result.reason}`);
356
+ }
357
+ }
358
+ if (selected.some((tool) => tool.needsEnv) && values["no-env"]) {
359
+ warn(`${ENV_KEY} tidak disimpan (--no-env). Set sendiri sebelum menjalankan Codex/OpenCode.`);
360
+ } else if (selected.some((tool) => tool.needsEnv)) {
361
+ const env = persistApiKey(key, ctx, backup);
362
+ if (env.ok) ok(`${ENV_KEY} disimpan (${env.where})${env.replaced ? "; nilai lamanya disimpan di backup dan dikembalikan saat uninstall" : ""}`);
363
+ else {
364
+ fail(`Gagal menyimpan ${ENV_KEY}; set manual lalu buka terminal baru.`);
365
+ failures += 1;
366
+ }
367
+ }
368
+
369
+ // ZyRouter rejects a request whose x-api-key and Bearer token differ, which happens when Claude Code
370
+ // also picks up an Anthropic key from the environment.
371
+ if (selected.some((tool) => tool.id === "claude-code") && ctx.env.ANTHROPIC_API_KEY) {
372
+ warn("ANTHROPIC_API_KEY masih ada di environment. Hapus dulu supaya Claude Code tidak mengirim dua key berbeda.");
373
+ }
374
+
375
+ const manual = MANUAL_TOOLS.filter((tool) => tool.detected(ctx));
376
+ if (manual.length) {
377
+ out(`\n${s.bold("Atur manual")} ${s.gray("(nilai di bawah, key ada di dashboard):")}`);
378
+ manual.forEach((tool) => out(` ${s.cyan("•")} ${s.bold(tool.name)}: ${tool.hint} · Base URL ${baseUrl} · model ${model}`));
379
+ }
380
+
381
+ // 5. One tiny request per protocol the chosen tools actually use.
382
+ if (!values["no-test"]) {
383
+ const protocols = [...new Set(selected.map((tool) => tool.protocol))];
384
+ if (ctx.tty) step(5, totalSteps, `Tes koneksi ${s.gray(`(${protocols.length} request kecil ke ${model})`)}`);
385
+ else out(`\nTes koneksi (${protocols.length} request kecil ke ${model})...`);
386
+ for (const protocol of protocols) {
387
+ const test = await withSpinner(ctx, `Menguji ${PROTOCOL_TESTS[protocol].label}...`, () => testProtocol(ctx, protocol, opts));
388
+ const hint = protocol === "messages" && test.status === 400 && /anthropic-compatible/i.test(test.message || "")
389
+ ? `Model ${model} belum dibuka untuk Claude Code; jalankan lagi dengan --model lain.`
390
+ : "Cek saldo dan model.";
391
+ if (test.ok) ok(`${test.label}: ${test.text || "OK"}`);
392
+ else {
393
+ fail(`${test.label} gagal (${test.status || test.error}${test.message ? `: ${test.message}` : ""}). ${hint}`);
394
+ failures += 1;
395
+ }
396
+ }
397
+ }
398
+
399
+ const closing = [
400
+ failures ? s.yellow(s.bold(`Selesai dengan ${failures} catatan di atas`)) : s.green(s.bold("Selesai! ZyRouter siap dipakai")),
401
+ `Backup konfigurasi lama: ${backup.dir}`,
402
+ "Tutup lalu buka lagi terminal, VS Code, dan aplikasinya supaya konfigurasi baru terbaca.",
403
+ "Batalkan kapan saja: npx -y zyrouter@latest uninstall",
404
+ ];
405
+ if (ctx.tty) {
406
+ out("");
407
+ box(s, closing, failures ? s.yellow : s.green).forEach((line) => out(line));
408
+ } else {
409
+ out(`\nBackup konfigurasi lama: ${backup.dir}`);
410
+ out("Selesai. Tutup lalu buka lagi terminal, VS Code, dan aplikasinya supaya konfigurasi baru terbaca.");
411
+ out("Batalkan kapan saja: npx -y zyrouter@latest uninstall");
412
+ }
413
+ return failures ? 2 : 0;
414
+ }
package/lib/system.mjs ADDED
@@ -0,0 +1,184 @@
1
+ // Filesystem, detection, environment variables and backups. Everything takes a context so tests can
2
+ // point it at a temporary home directory and a fake platform.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { ENV_KEY, removeRcBlock, setRcBlock } from "./configs.mjs";
8
+
9
+ export function exists(file) {
10
+ try {
11
+ fs.accessSync(file);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ export function readText(file) {
19
+ return exists(file) ? fs.readFileSync(file, "utf8") : null;
20
+ }
21
+
22
+ export function writeText(file, text) {
23
+ fs.mkdirSync(path.dirname(file), { recursive: true });
24
+ fs.writeFileSync(file, text, "utf8");
25
+ }
26
+
27
+ /** Parses a JSON config. Returns { ok: false } for files with comments (JSONC/JSON5) so they are left alone. */
28
+ export function readJson(file) {
29
+ const text = readText(file);
30
+ if (text === null) return { ok: true, data: {}, existed: false };
31
+ if (!text.trim()) return { ok: true, data: {}, existed: true };
32
+ try {
33
+ const data = JSON.parse(text.replace(/^/, ""));
34
+ return data && typeof data === "object" && !Array.isArray(data) ? { ok: true, data, existed: true } : { ok: false };
35
+ } catch {
36
+ return { ok: false };
37
+ }
38
+ }
39
+
40
+ export function onPath(name, ctx) {
41
+ const dirs = String(ctx.env.PATH || ctx.env.Path || "").split(ctx.platform === "win32" ? ";" : ":").filter(Boolean);
42
+ const exts = ctx.platform === "win32" ? ["", ...String(ctx.env.PATHEXT || ".EXE;.CMD;.BAT;.PS1").split(";").map((e) => e.toLowerCase())] : [""];
43
+ return dirs.some((dir) => exts.some((ext) => exists(path.join(dir, name + ext))));
44
+ }
45
+
46
+ const EDITOR_DIRS = [".vscode", ".vscode-insiders", ".cursor", ".windsurf", ".vscode-oss"];
47
+
48
+ export function hasEditorExtension(prefix, ctx) {
49
+ const wanted = `${prefix.toLowerCase()}-`;
50
+ return EDITOR_DIRS.some((dir) => {
51
+ try {
52
+ return fs.readdirSync(path.join(ctx.home, dir, "extensions")).some((name) => name.toLowerCase().startsWith(wanted));
53
+ } catch {
54
+ return false;
55
+ }
56
+ });
57
+ }
58
+
59
+ function rcFiles(ctx) {
60
+ const candidates = ctx.platform === "darwin" ? [".zshrc", ".bash_profile", ".bashrc"] : [".bashrc", ".zshrc"];
61
+ const present = candidates.map((name) => path.join(ctx.home, name)).filter(exists);
62
+ return present.length ? present : [path.join(ctx.home, candidates[0])];
63
+ }
64
+
65
+ /** Persists the key for new terminals and GUI apps. Windows: user environment (setx). Others: shell rc block. */
66
+ export function persistApiKey(key, ctx, backup) {
67
+ if (ctx.platform === "win32") {
68
+ // Keep the value it replaces (e.g. from the manual guide or another tool) so uninstall can put it back.
69
+ const previous = readWindowsUserEnv(ctx);
70
+ const result = ctx.run("setx", [ENV_KEY, key]);
71
+ backup.note({ windowsEnv: true, windowsEnvPrevious: previous });
72
+ return { ok: result.status === 0, where: "Windows user environment", replaced: previous !== null && previous !== key };
73
+ }
74
+ const files = rcFiles(ctx);
75
+ for (const file of files) {
76
+ backup.record(file);
77
+ writeText(file, setRcBlock(readText(file), key));
78
+ }
79
+ return { ok: true, where: files.map((file) => path.basename(file)).join(", ") };
80
+ }
81
+
82
+ /** The user-level (HKCU) value, or null when it is not set. */
83
+ export function readWindowsUserEnv(ctx) {
84
+ const result = ctx.run("reg", ["query", "HKCU\\Environment", "/v", ENV_KEY], { capture: true });
85
+ if (result.status !== 0) return null;
86
+ const line = String(result.stdout || "").split(/\r?\n/).find((row) => row.trim().startsWith(ENV_KEY));
87
+ const match = line && /REG_(?:EXPAND_)?SZ\s+(.*)$/.exec(line.trim());
88
+ return match ? match[1].trim() : null;
89
+ }
90
+
91
+ /** Windows: `previous` is the value from before the first install (null = it was not set). */
92
+ export function restoreWindowsUserEnv(ctx, previous) {
93
+ if (previous) return ctx.run("setx", [ENV_KEY, previous]).status === 0;
94
+ return ctx.run("reg", ["delete", "HKCU\\Environment", "/v", ENV_KEY, "/f"]).status === 0;
95
+ }
96
+
97
+ /** Non-Windows: drops the marked block from the rc files. */
98
+ export function removePersistedApiKey(ctx) {
99
+ for (const file of rcFiles(ctx)) {
100
+ const text = readText(file);
101
+ if (text !== null && text.includes("# >>> zyrouter >>>")) writeText(file, removeRcBlock(text));
102
+ }
103
+ return true;
104
+ }
105
+
106
+ export function defaultRun(command, args, { capture = false } = {}) {
107
+ // No shell: arguments (the API key included) are passed verbatim and never interpreted.
108
+ return spawnSync(command, args, { stdio: capture ? ["ignore", "pipe", "ignore"] : "ignore", encoding: "utf8", windowsHide: true });
109
+ }
110
+
111
+ /** One backup session per run under ~/.zyrouter/backups/<timestamp>, restorable by `uninstall`. */
112
+ export function createBackup(ctx) {
113
+ const dir = path.join(ctx.home, ".zyrouter", "backups", new Date().toISOString().replace(/[:.]/g, "-"));
114
+ const manifest = { createdAt: new Date().toISOString(), files: [], restored: false };
115
+ const seen = new Set();
116
+ return {
117
+ dir,
118
+ record(file) {
119
+ if (seen.has(file) || ctx.dryRun) return;
120
+ seen.add(file);
121
+ fs.mkdirSync(dir, { recursive: true });
122
+ if (exists(file)) {
123
+ const copy = path.join(dir, `${manifest.files.length}-${path.basename(file)}`);
124
+ fs.copyFileSync(file, copy);
125
+ manifest.files.push({ path: file, backup: copy, existed: true });
126
+ } else {
127
+ manifest.files.push({ path: file, existed: false });
128
+ }
129
+ this.save();
130
+ },
131
+ note(extra) {
132
+ if (ctx.dryRun) return;
133
+ Object.assign(manifest, extra);
134
+ fs.mkdirSync(dir, { recursive: true });
135
+ this.save();
136
+ },
137
+ save() {
138
+ fs.writeFileSync(path.join(dir, "manifest.json"), JSON.stringify(manifest, null, 2));
139
+ },
140
+ };
141
+ }
142
+
143
+ /** Restores every unrestored session, newest first, so the files end up as they were before the first run. */
144
+ export function restoreBackups(ctx) {
145
+ const root = path.join(ctx.home, ".zyrouter", "backups");
146
+ let sessions = [];
147
+ try {
148
+ sessions = fs.readdirSync(root).sort().reverse();
149
+ } catch {
150
+ return { sessions: 0, files: 0, windowsEnv: false, windowsEnvPrevious: null };
151
+ }
152
+ let restoredSessions = 0;
153
+ let restoredFiles = 0;
154
+ let windowsEnv = false;
155
+ let windowsEnvPrevious = null;
156
+ for (const name of sessions) {
157
+ const manifestPath = path.join(root, name, "manifest.json");
158
+ let manifest;
159
+ try {
160
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
161
+ } catch {
162
+ continue;
163
+ }
164
+ if (manifest.restored) continue;
165
+ for (const entry of manifest.files || []) {
166
+ if (entry.existed && exists(entry.backup)) {
167
+ fs.mkdirSync(path.dirname(entry.path), { recursive: true });
168
+ fs.copyFileSync(entry.backup, entry.path);
169
+ } else if (!entry.existed && exists(entry.path)) {
170
+ fs.rmSync(entry.path, { force: true });
171
+ }
172
+ restoredFiles += 1;
173
+ }
174
+ if (manifest.windowsEnv === true) {
175
+ windowsEnv = true;
176
+ // Sessions run newest first, so the last one seen holds the value from before the first install.
177
+ windowsEnvPrevious = manifest.windowsEnvPrevious ?? null;
178
+ }
179
+ manifest.restored = true;
180
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
181
+ restoredSessions += 1;
182
+ }
183
+ return { sessions: restoredSessions, files: restoredFiles, windowsEnv, windowsEnvPrevious };
184
+ }
package/lib/ui.mjs ADDED
@@ -0,0 +1,173 @@
1
+ // Terminal UI without dependencies: colors, a spinner, arrow-key menus and masked input.
2
+ // Interactive pieces need a real TTY; callers fall back to numbered prompts everywhere else.
3
+
4
+ import readline from "node:readline";
5
+
6
+ export function createStyle(enabled) {
7
+ const wrap = (open, close) => (text) => (enabled ? `\x1b[${open}m${text}\x1b[${close}m` : String(text));
8
+ return {
9
+ bold: wrap(1, 22),
10
+ dim: wrap(2, 22),
11
+ red: wrap(31, 39),
12
+ green: wrap(32, 39),
13
+ yellow: wrap(33, 39),
14
+ cyan: wrap(36, 39),
15
+ magenta: wrap(35, 39),
16
+ gray: wrap(90, 39),
17
+ orange: wrap("38;5;208", 39),
18
+ inverse: wrap(7, 27),
19
+ };
20
+ }
21
+
22
+ const FAMILIES = [
23
+ { name: "OpenAI", match: /^(gpt|o\d|chatgpt|codex)/i },
24
+ { name: "Anthropic", match: /^claude/i },
25
+ { name: "Google", match: /gemini/i },
26
+ { name: "DeepSeek", match: /deepseek/i },
27
+ { name: "Moonshot", match: /kimi/i },
28
+ { name: "Zhipu", match: /glm/i },
29
+ { name: "Alibaba", match: /qwen/i },
30
+ { name: "MiniMax", match: /minimax/i },
31
+ { name: "Xiaomi", match: /mimo/i },
32
+ ];
33
+
34
+ export function modelFamily(id) {
35
+ return FAMILIES.find((family) => family.match.test(id))?.name ?? "Other";
36
+ }
37
+
38
+ /** Models grouped by family, keeping the catalog order inside each group and of the groups themselves. */
39
+ export function groupModels(models) {
40
+ const groups = new Map();
41
+ for (const id of models) {
42
+ const family = modelFamily(id);
43
+ if (!groups.has(family)) groups.set(family, []);
44
+ groups.get(family).push(id);
45
+ }
46
+ const other = groups.get("Other");
47
+ groups.delete("Other");
48
+ if (other) groups.set("Other", other);
49
+ return [...groups].map(([family, ids]) => ({ family, models: ids }));
50
+ }
51
+
52
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
53
+
54
+ /** Spinner on one line while `task` runs; without a TTY it just runs the task. */
55
+ export async function withSpinner(ctx, text, task) {
56
+ if (!ctx.tty) return task();
57
+ const { style } = ctx;
58
+ let frame = 0;
59
+ const draw = () => process.stdout.write(`\r\x1b[2K${style.cyan(SPINNER_FRAMES[frame++ % SPINNER_FRAMES.length])} ${text}`);
60
+ draw();
61
+ const timer = setInterval(draw, 80);
62
+ try {
63
+ return await task();
64
+ } finally {
65
+ clearInterval(timer);
66
+ process.stdout.write("\r\x1b[2K");
67
+ }
68
+ }
69
+
70
+ function withRawInput(handler) {
71
+ return new Promise((resolve, reject) => {
72
+ const input = process.stdin;
73
+ readline.emitKeypressEvents(input);
74
+ const wasRaw = input.isRaw;
75
+ input.setRawMode(true);
76
+ input.resume();
77
+ const finish = (error, value) => {
78
+ input.off("keypress", onKey);
79
+ input.setRawMode(wasRaw);
80
+ input.pause();
81
+ if (error) reject(error);
82
+ else resolve(value);
83
+ };
84
+ const onKey = (text, key = {}) => {
85
+ if ((key.ctrl && key.name === "c") || key.name === "escape") return finish(new Error("Dibatalkan."));
86
+ handler(text, key, (value) => finish(null, value));
87
+ };
88
+ input.on("keypress", onKey);
89
+ });
90
+ }
91
+
92
+ /** Masked input: shows • per character, supports paste and backspace. */
93
+ export async function readSecret(ctx, label) {
94
+ const { style } = ctx;
95
+ let value = "";
96
+ const draw = () => process.stdout.write(`\r\x1b[2K${style.cyan("?")} ${style.bold(label)} ${style.gray("•".repeat(Math.min(value.length, 48)))}`);
97
+ draw();
98
+ const result = await withRawInput((text, key, done) => {
99
+ if (key.name === "return" || key.name === "enter") return done(value);
100
+ if (key.name === "backspace") value = value.slice(0, -1);
101
+ else if (text && !key.ctrl && !key.meta) value += text.replace(/[\r\n]/g, "");
102
+ draw();
103
+ });
104
+ process.stdout.write("\n");
105
+ return result.trim();
106
+ }
107
+
108
+ /**
109
+ * Arrow-key menu. `rows` mixes { header } lines with { label, value, note, checked } items.
110
+ * Single choice returns a value; multi choice returns the checked values.
111
+ */
112
+ export async function pickFromMenu(ctx, { title, hint, rows, multi = false, initialValue }) {
113
+ const { style } = ctx;
114
+ const items = rows.filter((row) => !row.header);
115
+ let cursor = Math.max(0, items.findIndex((item) => item.value === initialValue));
116
+ const checked = new Set(items.filter((item) => item.checked).map((item) => item.value));
117
+ let drawn = 0;
118
+ process.stdout.write("\x1b[?25l");
119
+
120
+ const render = () => {
121
+ const height = Math.max(8, (process.stdout.rows || 24) - 5);
122
+ const current = items[cursor];
123
+ const currentRow = rows.indexOf(current);
124
+ const start = Math.max(0, Math.min(currentRow - Math.floor(height / 2), rows.length - height));
125
+ const visible = rows.slice(start, start + height);
126
+ const lines = [`${style.cyan("?")} ${style.bold(title)} ${style.gray(hint)}`];
127
+ if (start > 0) lines.push(style.gray(" ↑ lainnya"));
128
+ for (const row of visible) {
129
+ if (row.header) {
130
+ lines.push(` ${style.orange(style.bold(row.header))}`);
131
+ continue;
132
+ }
133
+ const active = row === current;
134
+ const pointer = active ? style.cyan("❯") : " ";
135
+ const box = multi ? (checked.has(row.value) ? style.green("◉") : style.gray("◯")) + " " : "";
136
+ const label = active ? style.cyan(style.bold(row.label)) : row.label;
137
+ lines.push(` ${pointer} ${box}${label}${row.note ? ` ${style.gray(row.note)}` : ""}`);
138
+ }
139
+ if (start + height < rows.length) lines.push(style.gray(" ↓ lainnya"));
140
+ if (drawn) process.stdout.write(`\x1b[${drawn}A\x1b[0J`);
141
+ process.stdout.write(`${lines.join("\n")}\n`);
142
+ drawn = lines.length;
143
+ };
144
+
145
+ render();
146
+ try {
147
+ return await withRawInput((text, key, done) => {
148
+ if (key.name === "up" || key.name === "k") cursor = (cursor - 1 + items.length) % items.length;
149
+ else if (key.name === "down" || key.name === "j") cursor = (cursor + 1) % items.length;
150
+ else if (multi && key.name === "space") {
151
+ const value = items[cursor].value;
152
+ if (checked.has(value)) checked.delete(value);
153
+ else checked.add(value);
154
+ } else if (multi && key.name === "a") {
155
+ if (checked.size === items.length) checked.clear();
156
+ else items.forEach((item) => checked.add(item.value));
157
+ } else if (key.name === "return" || key.name === "enter") {
158
+ return done(multi ? items.filter((item) => checked.has(item.value)).map((item) => item.value) : items[cursor].value);
159
+ }
160
+ render();
161
+ });
162
+ } finally {
163
+ if (drawn) process.stdout.write(`\x1b[${drawn}A\x1b[0J`);
164
+ process.stdout.write("\x1b[?25h");
165
+ }
166
+ }
167
+
168
+ /** A rounded box around a few lines, sized to the longest one (ANSI codes excluded). */
169
+ export function box(style, lines, color = style.gray) {
170
+ const width = Math.max(...lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").length));
171
+ const pad = (line) => line + " ".repeat(width - line.replace(/\x1b\[[0-9;]*m/g, "").length);
172
+ return [color(`╭${"─".repeat(width + 2)}╮`), ...lines.map((line) => `${color("│")} ${pad(line)} ${color("│")}`), color(`╰${"─".repeat(width + 2)}╯`)];
173
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "zyrouter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Connect Codex, Claude Code, OpenCode, OpenClaw and Hermes Agent to ZyRouter with one command.",
5
+ "type": "module",
6
+ "bin": {
7
+ "zyrouter": "bin/cli.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "lib",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18.17"
16
+ },
17
+ "scripts": {
18
+ "test": "node --test test/*.test.mjs"
19
+ },
20
+ "keywords": [
21
+ "zyrouter",
22
+ "codex",
23
+ "claude-code",
24
+ "opencode",
25
+ "installer"
26
+ ],
27
+ "homepage": "https://zyrouter.com",
28
+ "license": "UNLICENSED"
29
+ }