zyrouter 0.1.0 → 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 +3 -2
- package/lib/configs.mjs +33 -0
- package/lib/main.mjs +208 -117
- package/lib/ui.mjs +173 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -15,8 +15,9 @@ to `~/.zyrouter/backups/`, writes the ZyRouter settings, and sends one small tes
|
|
|
15
15
|
| Claude Code | `~/.claude/settings.json` |
|
|
16
16
|
| OpenCode | `~/.config/opencode/opencode.json` and `ZYROUTER_API_KEY` |
|
|
17
17
|
| OpenClaw | `~/.openclaw/openclaw.json` |
|
|
18
|
+
| Hermes Agent | `~/.hermes/config.yaml` (the `model:` block) and `OPENAI_API_KEY` in `~/.hermes/.env` |
|
|
18
19
|
|
|
19
|
-
Cline
|
|
20
|
+
Cline and Continue are detected but stay manual; the installer prints the values to use.
|
|
20
21
|
|
|
21
22
|
Undo everything:
|
|
22
23
|
|
|
@@ -24,5 +25,5 @@ Undo everything:
|
|
|
24
25
|
npx -y zyrouter@latest uninstall
|
|
25
26
|
```
|
|
26
27
|
|
|
27
|
-
Options: `--model <id>`, `--tools codex,claude-code,opencode,openclaw`, `--yes`, `--no-test`, `--dry-run`.
|
|
28
|
+
Options: `--model <id>`, `--tools codex,claude-code,opencode,openclaw,hermes`, `--yes`, `--no-test`, `--dry-run`.
|
|
28
29
|
No dependencies; needs Node.js 18.17 or newer.
|
package/lib/configs.mjs
CHANGED
|
@@ -112,3 +112,36 @@ export function maskKey(key) {
|
|
|
112
112
|
const value = String(key || "");
|
|
113
113
|
return value.length > 12 ? `${value.slice(0, 10)}…${value.slice(-4)}` : "sk-zyr-…";
|
|
114
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
CHANGED
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
import os from "node:os";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import fs from "node:fs";
|
|
3
4
|
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
4
6
|
import { parseArgs } from "node:util";
|
|
5
|
-
import { ENV_KEY, maskKey, mergeClaudeSettings, mergeCodexToml, mergeOpenClaw, mergeOpenCode } from "./configs.mjs";
|
|
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";
|
|
6
9
|
import { createBackup, defaultRun, exists, hasEditorExtension, onPath, persistApiKey, readJson, readText, removePersistedApiKey, restoreBackups, restoreWindowsUserEnv, writeText } from "./system.mjs";
|
|
7
10
|
|
|
8
11
|
export const DEFAULT_BASE_URL = "https://zyrouter.com/v1";
|
|
9
12
|
const FALLBACK_MODELS = ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna"];
|
|
10
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
|
+
})();
|
|
11
21
|
|
|
12
|
-
const HELP = `ZyRouter installer — hubungkan Codex, Claude Code, OpenCode, dan
|
|
22
|
+
const HELP = `ZyRouter installer — hubungkan Codex, Claude Code, OpenCode, OpenClaw, dan Hermes Agent ke ZyRouter.
|
|
13
23
|
|
|
14
24
|
Pakai:
|
|
15
25
|
npx -y zyrouter@latest --key sk-zyr-... pasang (deteksi aplikasi otomatis)
|
|
@@ -18,7 +28,7 @@ Pakai:
|
|
|
18
28
|
Opsi:
|
|
19
29
|
--key <key> API key ZyRouter (atau env ZYROUTER_API_KEY, atau ditanya)
|
|
20
30
|
--model <id> model default, mis. gpt-6.1-terra
|
|
21
|
-
--tools <list> codex,claude-code,opencode,openclaw (default: yang terdeteksi)
|
|
31
|
+
--tools <list> codex,claude-code,opencode,openclaw,hermes (default: yang terdeteksi)
|
|
22
32
|
--yes tanpa pertanyaan: pakai aplikasi yang terdeteksi dan model pertama
|
|
23
33
|
--no-test lewati request tes di akhir
|
|
24
34
|
--no-env jangan simpan ZYROUTER_API_KEY ke environment (untuk tes)
|
|
@@ -77,13 +87,27 @@ function toolCatalog(ctx) {
|
|
|
77
87
|
return writeJsonConfig(this.file, (data) => mergeOpenClaw(data, opts), backup);
|
|
78
88
|
},
|
|
79
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
|
+
},
|
|
80
105
|
];
|
|
81
106
|
}
|
|
82
107
|
|
|
83
108
|
const MANUAL_TOOLS = [
|
|
84
109
|
{ id: "cline", name: "Cline", detected: (ctx) => hasEditorExtension("saoudrizwan.claude-dev", ctx), hint: "Settings Cline > API Provider: OpenAI Compatible" },
|
|
85
110
|
{ id: "continue", name: "Continue", detected: (ctx) => hasEditorExtension("continue.continue", ctx) || exists(path.join(ctx.home, ".continue")), hint: "~/.continue/config.yaml, provider openai" },
|
|
86
|
-
{ id: "hermes", name: "Hermes Agent", detected: (ctx) => onPath("hermes", ctx) || exists(path.join(ctx.home, ".hermes")), hint: "~/.hermes/config.yaml + OPENAI_API_KEY di ~/.hermes/.env" },
|
|
87
111
|
];
|
|
88
112
|
|
|
89
113
|
function writeJsonConfig(file, merge, backup) {
|
|
@@ -151,6 +175,7 @@ function parseList(value) {
|
|
|
151
175
|
}
|
|
152
176
|
|
|
153
177
|
export async function run(argv, overrides = {}) {
|
|
178
|
+
const stdinTty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
154
179
|
const ctx = {
|
|
155
180
|
env: process.env,
|
|
156
181
|
platform: process.platform,
|
|
@@ -159,9 +184,12 @@ export async function run(argv, overrides = {}) {
|
|
|
159
184
|
run: defaultRun,
|
|
160
185
|
out: (line = "") => process.stdout.write(`${line}\n`),
|
|
161
186
|
ask: null,
|
|
162
|
-
interactive:
|
|
187
|
+
interactive: stdinTty,
|
|
163
188
|
...overrides,
|
|
164
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));
|
|
165
193
|
const { values, positionals } = parseArgs({
|
|
166
194
|
args: argv,
|
|
167
195
|
allowPositionals: true,
|
|
@@ -178,146 +206,209 @@ export async function run(argv, overrides = {}) {
|
|
|
178
206
|
},
|
|
179
207
|
});
|
|
180
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)}`);
|
|
181
214
|
if (values.help) {
|
|
182
215
|
out(HELP);
|
|
183
216
|
return 0;
|
|
184
217
|
}
|
|
185
218
|
ctx.dryRun = values["dry-run"] === true;
|
|
186
219
|
|
|
187
|
-
|
|
220
|
+
// One readline interface per question, closed right away, so raw-mode menus own stdin afterwards.
|
|
188
221
|
const ask = ctx.ask || (async (question) => {
|
|
189
|
-
rl
|
|
190
|
-
|
|
222
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
223
|
+
try {
|
|
224
|
+
return await rl.question(question);
|
|
225
|
+
} finally {
|
|
226
|
+
rl.close();
|
|
227
|
+
}
|
|
191
228
|
});
|
|
192
|
-
const canAsk = !values.yes && (ctx.ask || ctx.interactive);
|
|
229
|
+
const canAsk = !values.yes && Boolean(ctx.ask || ctx.interactive);
|
|
193
230
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
if (
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
removePersistedApiKey(ctx);
|
|
202
|
-
}
|
|
203
|
-
out(result.sessions ? `✔ ${result.files} file dikembalikan dari ${result.sessions} backup.` : "Tidak ada backup ZyRouter untuk dikembalikan.");
|
|
204
|
-
out("Tutup lalu buka lagi terminal dan editor supaya perubahan terbaca.");
|
|
205
|
-
return 0;
|
|
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);
|
|
206
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
|
+
}
|
|
207
244
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
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
|
+
}
|
|
211
249
|
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
// Ask for a missing key even when stdin is not reported as a TTY (editor and app terminals often are not);
|
|
217
|
-
// only --yes means "never prompt".
|
|
218
|
-
if (!key && !values.yes) key = (await ask("Tempel API key ZyRouter (sk-zyr-...): ")).trim();
|
|
219
|
-
if (!key) throw new Error("API key belum diisi. Salin perintah lengkap dari dashboard ZyRouter, atau pakai --key sk-zyr-...");
|
|
220
|
-
if (!KEY_PATTERN.test(key)) throw new Error("API key tidak valid. Salin perintah lengkap dari dashboard ZyRouter, atau pakai --key sk-zyr-...");
|
|
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;
|
|
221
254
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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-...");
|
|
227
265
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
selected = tools.filter((tool) => wanted.includes(tool.id));
|
|
235
|
-
const unknown = wanted.filter((id) => !tools.some((tool) => tool.id === id));
|
|
236
|
-
if (unknown.length) throw new Error(`Aplikasi tidak dikenal: ${unknown.join(", ")}. Pilihan: ${tools.map((tool) => tool.id).join(", ")}`);
|
|
237
|
-
} else if (canAsk) {
|
|
238
|
-
out("\nAplikasi yang bisa diatur otomatis:");
|
|
239
|
-
tools.forEach((tool, index) => {
|
|
240
|
-
const note = !detected.includes(tool) ? " (tidak terdeteksi)" : tool.optIn ? " (terdeteksi; pilih nomornya kalau mau dialihkan ke ZyRouter)" : "";
|
|
241
|
-
out(` ${index + 1}. [${preselected.includes(tool) ? "x" : " "}] ${tool.name}${note}`);
|
|
242
|
-
});
|
|
243
|
-
const answer = (await ask(`Pilih nomor, pisahkan koma (Enter = ${preselected.length ? "yang dicentang" : "lewati"}): `)).trim();
|
|
244
|
-
selected = answer ? answer.split(",").map((n) => tools[Number(n.trim()) - 1]).filter(Boolean) : preselected;
|
|
245
|
-
} else {
|
|
246
|
-
selected = preselected;
|
|
247
|
-
}
|
|
248
|
-
if (!selected.length) {
|
|
249
|
-
out("Tidak ada aplikasi yang dipilih. Pasang dulu Codex/OpenCode/OpenClaw, atau pilih langsung dengan --tools codex,claude-code.");
|
|
250
|
-
return 1;
|
|
251
|
-
}
|
|
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.");
|
|
252
272
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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(", ")}`);
|
|
262
309
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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}`));
|
|
268
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)}`);
|
|
269
336
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
out(
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
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}`);
|
|
281
356
|
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
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;
|
|
288
366
|
}
|
|
367
|
+
}
|
|
289
368
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
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
|
+
}
|
|
295
374
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
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
|
+
}
|
|
301
380
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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;
|
|
313
395
|
}
|
|
314
396
|
}
|
|
397
|
+
}
|
|
315
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 {
|
|
316
409
|
out(`\nBackup konfigurasi lama: ${backup.dir}`);
|
|
317
410
|
out("Selesai. Tutup lalu buka lagi terminal, VS Code, dan aplikasinya supaya konfigurasi baru terbaca.");
|
|
318
411
|
out("Batalkan kapan saja: npx -y zyrouter@latest uninstall");
|
|
319
|
-
return failures ? 2 : 0;
|
|
320
|
-
} finally {
|
|
321
|
-
rl?.close();
|
|
322
412
|
}
|
|
413
|
+
return failures ? 2 : 0;
|
|
323
414
|
}
|
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,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zyrouter",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Connect Codex, Claude Code, OpenCode and
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Connect Codex, Claude Code, OpenCode, OpenClaw and Hermes Agent to ZyRouter with one command.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"zyrouter": "bin/cli.mjs"
|