zyrouter 0.0.0-stage → 0.1.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.
- package/README.md +27 -2
- package/bin/cli.mjs +20 -0
- package/lib/configs.mjs +114 -0
- package/lib/main.mjs +323 -0
- package/lib/system.mjs +184 -0
- package/package.json +27 -4
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# zyrouter
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
|
|
19
|
+
Cline, Continue and Hermes Agent are detected but stay manual; the installer prints the values to use.
|
|
20
|
+
|
|
21
|
+
Undo everything:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npx -y zyrouter@latest uninstall
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Options: `--model <id>`, `--tools codex,claude-code,opencode,openclaw`, `--yes`, `--no-test`, `--dry-run`.
|
|
28
|
+
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
|
+
);
|
package/lib/configs.mjs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
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
|
+
}
|
package/lib/main.mjs
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { createInterface } from "node:readline/promises";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { ENV_KEY, maskKey, mergeClaudeSettings, mergeCodexToml, mergeOpenClaw, mergeOpenCode } from "./configs.mjs";
|
|
6
|
+
import { createBackup, defaultRun, exists, hasEditorExtension, onPath, persistApiKey, readJson, readText, removePersistedApiKey, restoreBackups, restoreWindowsUserEnv, writeText } from "./system.mjs";
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_BASE_URL = "https://zyrouter.com/v1";
|
|
9
|
+
const FALLBACK_MODELS = ["gpt-6-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna"];
|
|
10
|
+
const KEY_PATTERN = /^sk-zyr-[A-Za-z0-9_-]{20,}$/;
|
|
11
|
+
|
|
12
|
+
const HELP = `ZyRouter installer — hubungkan Codex, Claude Code, OpenCode, dan OpenClaw ke ZyRouter.
|
|
13
|
+
|
|
14
|
+
Pakai:
|
|
15
|
+
npx -y zyrouter@latest --key sk-zyr-... pasang (deteksi aplikasi otomatis)
|
|
16
|
+
npx -y zyrouter@latest uninstall kembalikan semua konfigurasi seperti semula
|
|
17
|
+
|
|
18
|
+
Opsi:
|
|
19
|
+
--key <key> API key ZyRouter (atau env ZYROUTER_API_KEY, atau ditanya)
|
|
20
|
+
--model <id> model default, mis. gpt-6.1-terra
|
|
21
|
+
--tools <list> codex,claude-code,opencode,openclaw (default: yang terdeteksi)
|
|
22
|
+
--yes tanpa pertanyaan: pakai aplikasi yang terdeteksi dan model pertama
|
|
23
|
+
--no-test lewati request tes di akhir
|
|
24
|
+
--no-env jangan simpan ZYROUTER_API_KEY ke environment (untuk tes)
|
|
25
|
+
--dry-run tampilkan rencana tanpa mengubah file
|
|
26
|
+
--base-url <url> endpoint lain (default ${DEFAULT_BASE_URL})
|
|
27
|
+
`;
|
|
28
|
+
|
|
29
|
+
/** Tools whose config files the installer writes; manual ones only get printed instructions. */
|
|
30
|
+
function toolCatalog(ctx) {
|
|
31
|
+
const home = ctx.home;
|
|
32
|
+
return [
|
|
33
|
+
{
|
|
34
|
+
id: "codex",
|
|
35
|
+
name: "Codex (CLI & VS Code)",
|
|
36
|
+
protocol: "responses",
|
|
37
|
+
file: path.join(home, ".codex", "config.toml"),
|
|
38
|
+
detected: () => onPath("codex", ctx) || exists(path.join(home, ".codex")) || hasEditorExtension("openai.chatgpt", ctx),
|
|
39
|
+
apply(opts, backup) {
|
|
40
|
+
backup.record(this.file);
|
|
41
|
+
writeText(this.file, mergeCodexToml(readText(this.file), opts));
|
|
42
|
+
return { ok: true };
|
|
43
|
+
},
|
|
44
|
+
needsEnv: true,
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
id: "claude-code",
|
|
48
|
+
name: "Claude Code",
|
|
49
|
+
protocol: "messages",
|
|
50
|
+
// ~/.claude exists for every Claude Code user; redirecting it must be a deliberate choice, never a default.
|
|
51
|
+
optIn: true,
|
|
52
|
+
file: path.join(home, ".claude", "settings.json"),
|
|
53
|
+
detected: () => onPath("claude", ctx) || exists(path.join(home, ".claude")),
|
|
54
|
+
apply(opts, backup) {
|
|
55
|
+
return writeJsonConfig(this.file, (data) => mergeClaudeSettings(data, opts), backup);
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
id: "opencode",
|
|
60
|
+
name: "OpenCode",
|
|
61
|
+
protocol: "chat",
|
|
62
|
+
file: path.join(home, ".config", "opencode", "opencode.json"),
|
|
63
|
+
detected: () => onPath("opencode", ctx) || exists(path.join(home, ".config", "opencode")),
|
|
64
|
+
apply(opts, backup) {
|
|
65
|
+
if (exists(path.join(path.dirname(this.file), "opencode.jsonc"))) return { ok: false, reason: "opencode.jsonc dipakai; tambahkan provider secara manual" };
|
|
66
|
+
return writeJsonConfig(this.file, (data) => mergeOpenCode(data, opts), backup);
|
|
67
|
+
},
|
|
68
|
+
needsEnv: true,
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
id: "openclaw",
|
|
72
|
+
name: "OpenClaw",
|
|
73
|
+
protocol: "chat",
|
|
74
|
+
file: path.join(home, ".openclaw", "openclaw.json"),
|
|
75
|
+
detected: () => onPath("openclaw", ctx) || exists(path.join(home, ".openclaw")),
|
|
76
|
+
apply(opts, backup) {
|
|
77
|
+
return writeJsonConfig(this.file, (data) => mergeOpenClaw(data, opts), backup);
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const MANUAL_TOOLS = [
|
|
84
|
+
{ id: "cline", name: "Cline", detected: (ctx) => hasEditorExtension("saoudrizwan.claude-dev", ctx), hint: "Settings Cline > API Provider: OpenAI Compatible" },
|
|
85
|
+
{ 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
|
+
];
|
|
88
|
+
|
|
89
|
+
function writeJsonConfig(file, merge, backup) {
|
|
90
|
+
const current = readJson(file);
|
|
91
|
+
if (!current.ok) return { ok: false, reason: `${path.basename(file)} tidak bisa dibaca sebagai JSON (mungkin ada komentar); ubah manual` };
|
|
92
|
+
backup.record(file);
|
|
93
|
+
writeText(file, `${JSON.stringify(merge(current.data), null, 2)}\n`);
|
|
94
|
+
return { ok: true };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function fetchModels(ctx, baseUrl, key) {
|
|
98
|
+
try {
|
|
99
|
+
const response = await ctx.fetch(`${baseUrl}/models`, { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(15_000) });
|
|
100
|
+
if (response.status === 401 || response.status === 403) return { ok: false, invalidKey: true };
|
|
101
|
+
if (!response.ok) return { ok: false, status: response.status };
|
|
102
|
+
const body = await response.json();
|
|
103
|
+
const models = (Array.isArray(body?.data) ? body.data : []).map((item) => item?.id).filter((id) => typeof id === "string" && id);
|
|
104
|
+
return models.length ? { ok: true, models } : { ok: false, status: response.status };
|
|
105
|
+
} catch (error) {
|
|
106
|
+
return { ok: false, error: error?.name || "Error" };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const PROTOCOL_TESTS = {
|
|
111
|
+
chat: {
|
|
112
|
+
label: "OpenAI Chat Completions",
|
|
113
|
+
url: (o) => `${o.baseUrl}/chat/completions`,
|
|
114
|
+
body: (model) => ({ model, messages: [{ role: "user", content: "Reply with exactly: ZyRouter OK" }], max_tokens: 16, stream: false }),
|
|
115
|
+
text: (b) => b?.choices?.[0]?.message?.content,
|
|
116
|
+
},
|
|
117
|
+
responses: {
|
|
118
|
+
label: "OpenAI Responses (Codex)",
|
|
119
|
+
url: (o) => `${o.baseUrl}/responses`,
|
|
120
|
+
body: (model) => ({ model, input: "Reply with exactly: ZyRouter OK", max_output_tokens: 16, stream: false }),
|
|
121
|
+
text: (b) => b?.output_text || (b?.output || []).flatMap((item) => item?.content || []).map((part) => part?.text).filter(Boolean).join(""),
|
|
122
|
+
},
|
|
123
|
+
messages: {
|
|
124
|
+
label: "Anthropic Messages (Claude Code)",
|
|
125
|
+
url: (o) => `${o.anthropicBaseUrl}/v1/messages`,
|
|
126
|
+
headers: { "anthropic-version": "2023-06-01" },
|
|
127
|
+
body: (model) => ({ model, max_tokens: 16, messages: [{ role: "user", content: "Reply with exactly: ZyRouter OK" }] }),
|
|
128
|
+
text: (b) => (b?.content || []).map((part) => part?.text).filter(Boolean).join(""),
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
async function testProtocol(ctx, protocol, opts) {
|
|
133
|
+
const spec = PROTOCOL_TESTS[protocol];
|
|
134
|
+
try {
|
|
135
|
+
const response = await ctx.fetch(spec.url(opts), {
|
|
136
|
+
method: "POST",
|
|
137
|
+
headers: { Authorization: `Bearer ${opts.key}`, "Content-Type": "application/json", ...(spec.headers || {}) },
|
|
138
|
+
body: JSON.stringify(spec.body(opts.model)),
|
|
139
|
+
signal: AbortSignal.timeout(90_000),
|
|
140
|
+
});
|
|
141
|
+
const body = await response.json().catch(() => ({}));
|
|
142
|
+
if (!response.ok) return { ok: false, label: spec.label, status: response.status, message: body?.error?.message || body?.message };
|
|
143
|
+
return { ok: true, label: spec.label, text: String(spec.text(body) || "").trim() };
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return { ok: false, label: spec.label, error: error?.name || "Error" };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function parseList(value) {
|
|
150
|
+
return String(value || "").split(",").map((item) => item.trim().toLowerCase()).filter(Boolean);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function run(argv, overrides = {}) {
|
|
154
|
+
const ctx = {
|
|
155
|
+
env: process.env,
|
|
156
|
+
platform: process.platform,
|
|
157
|
+
home: process.env.ZYROUTER_INSTALLER_HOME || os.homedir(),
|
|
158
|
+
fetch: globalThis.fetch,
|
|
159
|
+
run: defaultRun,
|
|
160
|
+
out: (line = "") => process.stdout.write(`${line}\n`),
|
|
161
|
+
ask: null,
|
|
162
|
+
interactive: Boolean(process.stdin.isTTY),
|
|
163
|
+
...overrides,
|
|
164
|
+
};
|
|
165
|
+
const { values, positionals } = parseArgs({
|
|
166
|
+
args: argv,
|
|
167
|
+
allowPositionals: true,
|
|
168
|
+
options: {
|
|
169
|
+
key: { type: "string" },
|
|
170
|
+
model: { type: "string" },
|
|
171
|
+
tools: { type: "string" },
|
|
172
|
+
"base-url": { type: "string" },
|
|
173
|
+
yes: { type: "boolean", short: "y" },
|
|
174
|
+
"no-test": { type: "boolean" },
|
|
175
|
+
"no-env": { type: "boolean" },
|
|
176
|
+
"dry-run": { type: "boolean" },
|
|
177
|
+
help: { type: "boolean", short: "h" },
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
const out = ctx.out;
|
|
181
|
+
if (values.help) {
|
|
182
|
+
out(HELP);
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
185
|
+
ctx.dryRun = values["dry-run"] === true;
|
|
186
|
+
|
|
187
|
+
let rl = null;
|
|
188
|
+
const ask = ctx.ask || (async (question) => {
|
|
189
|
+
rl ||= createInterface({ input: process.stdin, output: process.stdout });
|
|
190
|
+
return rl.question(question);
|
|
191
|
+
});
|
|
192
|
+
const canAsk = !values.yes && (ctx.ask || ctx.interactive);
|
|
193
|
+
|
|
194
|
+
try {
|
|
195
|
+
if (positionals[0] === "uninstall") {
|
|
196
|
+
const result = restoreBackups(ctx);
|
|
197
|
+
// Windows: put back the value from before the first install. Elsewhere the rc files were restored already.
|
|
198
|
+
if (ctx.platform === "win32") {
|
|
199
|
+
if (result.windowsEnv) restoreWindowsUserEnv(ctx, result.windowsEnvPrevious);
|
|
200
|
+
} else {
|
|
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;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const baseUrl = String(values["base-url"] || ctx.env.ZYROUTER_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
209
|
+
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).");
|
|
210
|
+
const anthropicBaseUrl = baseUrl.replace(/\/v1$/i, "");
|
|
211
|
+
|
|
212
|
+
// An existing ZYROUTER_API_KEY is only reused when it is a ZyRouter key; other tools use the name too.
|
|
213
|
+
const envKey = ctx.env[ENV_KEY] || "";
|
|
214
|
+
let key = values.key || (KEY_PATTERN.test(envKey) ? envKey : "");
|
|
215
|
+
if (!values.key && envKey && !key) out(`! ${ENV_KEY} di environment bukan key ZyRouter; diabaikan.`);
|
|
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-...");
|
|
221
|
+
|
|
222
|
+
out(`ZyRouter installer · key ${maskKey(key)}`);
|
|
223
|
+
const listed = await fetchModels(ctx, baseUrl, key);
|
|
224
|
+
if (listed.invalidKey) throw new Error("API key ditolak (401). Cek key di dashboard ZyRouter tab API.");
|
|
225
|
+
const models = listed.ok ? listed.models : FALLBACK_MODELS;
|
|
226
|
+
out(listed.ok ? `✔ API key valid · ${models.length} model tersedia` : "! Daftar model belum bisa diambil; memakai daftar bawaan.");
|
|
227
|
+
|
|
228
|
+
const tools = toolCatalog(ctx);
|
|
229
|
+
const detected = tools.filter((tool) => tool.detected());
|
|
230
|
+
const preselected = detected.filter((tool) => !tool.optIn);
|
|
231
|
+
let selected;
|
|
232
|
+
if (values.tools) {
|
|
233
|
+
const wanted = parseList(values.tools);
|
|
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
|
+
}
|
|
252
|
+
|
|
253
|
+
let model = values.model || "";
|
|
254
|
+
if (!model && canAsk) {
|
|
255
|
+
out("\nModel default:");
|
|
256
|
+
models.forEach((id, index) => out(` ${index + 1}. ${id}`));
|
|
257
|
+
const answer = (await ask(`Pilih nomor (Enter = ${models[0]}): `)).trim();
|
|
258
|
+
model = (answer && models[Number(answer) - 1]) || models[0];
|
|
259
|
+
}
|
|
260
|
+
model ||= models[0];
|
|
261
|
+
if (listed.ok && !models.includes(model)) throw new Error(`Model ${model} tidak tersedia untuk key ini.`);
|
|
262
|
+
|
|
263
|
+
if (ctx.dryRun) {
|
|
264
|
+
out("\nRencana (dry run, tidak ada file yang diubah):");
|
|
265
|
+
selected.forEach((tool) => out(` • ${tool.name} → ${tool.file}`));
|
|
266
|
+
if (selected.some((tool) => tool.needsEnv)) out(` • ${ENV_KEY} disimpan untuk terminal baru`);
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const backup = createBackup(ctx);
|
|
271
|
+
const opts = { baseUrl, anthropicBaseUrl, key, model, models };
|
|
272
|
+
out("");
|
|
273
|
+
let failures = 0;
|
|
274
|
+
for (const tool of selected) {
|
|
275
|
+
const result = tool.apply(opts, backup);
|
|
276
|
+
if (result.ok) out(`✔ ${tool.name} → ${tool.file}`);
|
|
277
|
+
else {
|
|
278
|
+
failures += 1;
|
|
279
|
+
out(`✖ ${tool.name}: ${result.reason}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (selected.some((tool) => tool.needsEnv) && values["no-env"]) {
|
|
283
|
+
out(`! ${ENV_KEY} tidak disimpan (--no-env). Set sendiri sebelum menjalankan Codex/OpenCode.`);
|
|
284
|
+
} else if (selected.some((tool) => tool.needsEnv)) {
|
|
285
|
+
const env = persistApiKey(key, ctx, backup);
|
|
286
|
+
out(env.ok ? `✔ ${ENV_KEY} disimpan (${env.where})${env.replaced ? "; nilai lamanya disimpan di backup dan dikembalikan saat uninstall" : ""}` : `✖ Gagal menyimpan ${ENV_KEY}; set manual lalu buka terminal baru.`);
|
|
287
|
+
if (!env.ok) failures += 1;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ZyRouter rejects a request whose x-api-key and Bearer token differ, which happens when Claude Code
|
|
291
|
+
// also picks up an Anthropic key from the environment.
|
|
292
|
+
if (selected.some((tool) => tool.id === "claude-code") && ctx.env.ANTHROPIC_API_KEY) {
|
|
293
|
+
out("! ANTHROPIC_API_KEY masih ada di environment. Hapus dulu supaya Claude Code tidak mengirim dua key berbeda.");
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const manual = MANUAL_TOOLS.filter((tool) => tool.detected(ctx));
|
|
297
|
+
if (manual.length) {
|
|
298
|
+
out("\nAtur manual (nilai di bawah, key ada di dashboard):");
|
|
299
|
+
manual.forEach((tool) => out(` • ${tool.name}: ${tool.hint} · Base URL ${baseUrl} · model ${model}`));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (!values["no-test"]) {
|
|
303
|
+
// One tiny request per protocol the chosen tools actually use.
|
|
304
|
+
const protocols = [...new Set(selected.map((tool) => tool.protocol))];
|
|
305
|
+
out(`\nTes koneksi (${protocols.length} request kecil ke ${model})...`);
|
|
306
|
+
for (const protocol of protocols) {
|
|
307
|
+
const test = await testProtocol(ctx, protocol, opts);
|
|
308
|
+
const hint = protocol === "messages" && test.status === 400 && /anthropic-compatible/i.test(test.message || "")
|
|
309
|
+
? `Model ${model} belum dibuka untuk Claude Code; jalankan lagi dengan --model lain.`
|
|
310
|
+
: "Cek saldo dan model.";
|
|
311
|
+
out(test.ok ? `✔ ${test.label}: ${test.text || "OK"}` : `✖ ${test.label} gagal (${test.status || test.error}${test.message ? `: ${test.message}` : ""}). ${hint}`);
|
|
312
|
+
if (!test.ok) failures += 1;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
out(`\nBackup konfigurasi lama: ${backup.dir}`);
|
|
317
|
+
out("Selesai. Tutup lalu buka lagi terminal, VS Code, dan aplikasinya supaya konfigurasi baru terbaca.");
|
|
318
|
+
out("Batalkan kapan saja: npx -y zyrouter@latest uninstall");
|
|
319
|
+
return failures ? 2 : 0;
|
|
320
|
+
} finally {
|
|
321
|
+
rl?.close();
|
|
322
|
+
}
|
|
323
|
+
}
|
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/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zyrouter",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Connect Codex, Claude Code, OpenCode and OpenClaw 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
|
+
}
|